@web-ts-toolkit/express-runtime 0.7.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 +201 -0
- package/README.md +337 -0
- package/cli.js +636 -0
- package/index.d.mts +189 -0
- package/index.d.ts +189 -0
- package/index.js +259 -0
- package/index.mjs +220 -0
- package/package.json +52 -0
package/cli.js
ADDED
|
@@ -0,0 +1,636 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __copyProps = (to, from, except, desc) => {
|
|
10
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
11
|
+
for (let key of __getOwnPropNames(from))
|
|
12
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
13
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
14
|
+
}
|
|
15
|
+
return to;
|
|
16
|
+
};
|
|
17
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
18
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
19
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
20
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
21
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
22
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
23
|
+
mod
|
|
24
|
+
));
|
|
25
|
+
|
|
26
|
+
// src/cli-utils.ts
|
|
27
|
+
var import_node_url = require("url");
|
|
28
|
+
var import_node_path = require("path");
|
|
29
|
+
var import_node_fs = require("fs");
|
|
30
|
+
|
|
31
|
+
// src/index.ts
|
|
32
|
+
var import_node_http = __toESM(require("http"));
|
|
33
|
+
var import_express = __toESM(require("express"));
|
|
34
|
+
var import_serverless_http = __toESM(require("serverless-http"));
|
|
35
|
+
var defaultLogger = {
|
|
36
|
+
log: (...args) => console.log(...args),
|
|
37
|
+
error: (...args) => console.error(...args),
|
|
38
|
+
debug: (...args) => console.debug(...args)
|
|
39
|
+
};
|
|
40
|
+
function applySettings(app, options) {
|
|
41
|
+
if (options.disablePoweredBy !== false) {
|
|
42
|
+
app.disable("x-powered-by");
|
|
43
|
+
}
|
|
44
|
+
app.set("etag", options.etag ?? false);
|
|
45
|
+
app.set("trust proxy", options.trustProxy ?? false);
|
|
46
|
+
}
|
|
47
|
+
function applyMiddlewareList(app, list) {
|
|
48
|
+
if (list) {
|
|
49
|
+
for (const mw of list) {
|
|
50
|
+
app.use(mw);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
function applyRouters(app, options) {
|
|
55
|
+
const mounts = [];
|
|
56
|
+
if (options.router) mounts.push(options.router);
|
|
57
|
+
if (options.routers) mounts.push(...options.routers);
|
|
58
|
+
for (const mount of mounts) {
|
|
59
|
+
const path = typeof mount.path === "function" ? mount.path() : mount.path;
|
|
60
|
+
app.use(path, mount.handler);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
function createExpressApp(options = {}) {
|
|
64
|
+
const app = (0, import_express.default)();
|
|
65
|
+
applySettings(app, options);
|
|
66
|
+
applyMiddlewareList(app, options.preMiddleware);
|
|
67
|
+
if (options.json !== false) {
|
|
68
|
+
app.use(import_express.default.json(options.json ?? { limit: "1mb" }));
|
|
69
|
+
}
|
|
70
|
+
if (options.urlencoded !== false) {
|
|
71
|
+
app.use(import_express.default.urlencoded(options.urlencoded ?? { extended: false, limit: "1mb" }));
|
|
72
|
+
}
|
|
73
|
+
applyMiddlewareList(app, options.middleware);
|
|
74
|
+
applyRouters(app, options);
|
|
75
|
+
applyMiddlewareList(app, options.postMiddleware);
|
|
76
|
+
if (options.finalize) {
|
|
77
|
+
options.finalize(app);
|
|
78
|
+
}
|
|
79
|
+
if (options.errorHandler) {
|
|
80
|
+
app.use(options.errorHandler);
|
|
81
|
+
}
|
|
82
|
+
return app;
|
|
83
|
+
}
|
|
84
|
+
var DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
|
|
85
|
+
var DEFAULT_SHUTDOWN_TIMEOUT = 5e3;
|
|
86
|
+
function normalizePort(val) {
|
|
87
|
+
if (val === void 0 || val === "") {
|
|
88
|
+
const envPort = process.env.PORT;
|
|
89
|
+
if (envPort === void 0 || envPort === "") {
|
|
90
|
+
return 8080;
|
|
91
|
+
}
|
|
92
|
+
val = envPort;
|
|
93
|
+
}
|
|
94
|
+
if (typeof val === "string") {
|
|
95
|
+
const parsed = Number(val);
|
|
96
|
+
if (Number.isNaN(parsed)) {
|
|
97
|
+
return val;
|
|
98
|
+
}
|
|
99
|
+
val = parsed;
|
|
100
|
+
}
|
|
101
|
+
if (!Number.isFinite(val) || val < 0 || val > 65535) {
|
|
102
|
+
throw new Error(`Invalid port: ${String(val)}`);
|
|
103
|
+
}
|
|
104
|
+
return val;
|
|
105
|
+
}
|
|
106
|
+
function defaultOnError(error, port, logger) {
|
|
107
|
+
if (error.syscall !== "listen") {
|
|
108
|
+
throw error;
|
|
109
|
+
}
|
|
110
|
+
const bind = typeof port === "string" ? `Pipe ${port}` : `Port ${port}`;
|
|
111
|
+
if (error.code === "EACCES") {
|
|
112
|
+
logger.error(`${bind} requires elevated privileges`);
|
|
113
|
+
process.exit(1);
|
|
114
|
+
} else if (error.code === "EADDRINUSE") {
|
|
115
|
+
logger.error(`${bind} is already in use`);
|
|
116
|
+
process.exit(1);
|
|
117
|
+
} else {
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
function startLocalServer(app, options = {}) {
|
|
122
|
+
const logger = options.logger ?? defaultLogger;
|
|
123
|
+
const port = normalizePort(options.port);
|
|
124
|
+
const host = options.host ?? process.env.HOST ?? "0.0.0.0";
|
|
125
|
+
const shutdownTimeout = options.shutdownTimeout ?? DEFAULT_SHUTDOWN_TIMEOUT;
|
|
126
|
+
const server = import_node_http.default.createServer(app);
|
|
127
|
+
app.set("port", port);
|
|
128
|
+
const onError = (error) => {
|
|
129
|
+
if (options.onError) {
|
|
130
|
+
options.onError(error);
|
|
131
|
+
} else {
|
|
132
|
+
defaultOnError(error, port, logger);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const onListening = () => {
|
|
136
|
+
const addr = server.address();
|
|
137
|
+
const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr?.port}`;
|
|
138
|
+
logger.log(`Server running at http://${host}:${port}/ (${bind})`);
|
|
139
|
+
options.onListening?.();
|
|
140
|
+
};
|
|
141
|
+
server.on("error", onError);
|
|
142
|
+
server.on("listening", onListening);
|
|
143
|
+
const shutdown = async () => {
|
|
144
|
+
logger.log("Shutting down...");
|
|
145
|
+
try {
|
|
146
|
+
if (options.onShutdown) {
|
|
147
|
+
await options.onShutdown();
|
|
148
|
+
}
|
|
149
|
+
} catch (err) {
|
|
150
|
+
logger.error("onShutdown hook failed:", err);
|
|
151
|
+
}
|
|
152
|
+
await new Promise((resolve) => {
|
|
153
|
+
const timer = setTimeout(() => {
|
|
154
|
+
server.closeAllConnections?.();
|
|
155
|
+
resolve();
|
|
156
|
+
}, shutdownTimeout);
|
|
157
|
+
server.close((err) => {
|
|
158
|
+
clearTimeout(timer);
|
|
159
|
+
if (err) {
|
|
160
|
+
logger.error("Server close error:", err);
|
|
161
|
+
}
|
|
162
|
+
resolve();
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
if (options.exitAfterShutdown) {
|
|
166
|
+
process.exit(0);
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
if (options.signals !== false) {
|
|
170
|
+
const list = options.signals === void 0 || options.signals === true ? DEFAULT_SIGNALS : options.signals;
|
|
171
|
+
for (const sig of list) {
|
|
172
|
+
process.once(sig, () => void shutdown());
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
const start = async () => {
|
|
176
|
+
try {
|
|
177
|
+
if (options.init) {
|
|
178
|
+
await options.init();
|
|
179
|
+
}
|
|
180
|
+
if (typeof port === "number") {
|
|
181
|
+
server.listen(port, host);
|
|
182
|
+
} else {
|
|
183
|
+
server.listen(port);
|
|
184
|
+
}
|
|
185
|
+
} catch (err) {
|
|
186
|
+
server.emit("error", err);
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
void start();
|
|
190
|
+
return {
|
|
191
|
+
server,
|
|
192
|
+
shutdown
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/cli-utils.ts
|
|
197
|
+
var CLI_VERSION = "0.0.0-PLACEHOLDER";
|
|
198
|
+
function readValue(argv, index, name) {
|
|
199
|
+
const value = argv[index + 1];
|
|
200
|
+
if (value === void 0 || value.startsWith("--")) {
|
|
201
|
+
throw new Error(`Missing value for argument: ${name}`);
|
|
202
|
+
}
|
|
203
|
+
return value;
|
|
204
|
+
}
|
|
205
|
+
function printHelp() {
|
|
206
|
+
console.log(`web-ts-toolkit-express-runtime
|
|
207
|
+
|
|
208
|
+
Run an Express app locally, bundle it as a serverless handler, or run the bundle.
|
|
209
|
+
|
|
210
|
+
Usage:
|
|
211
|
+
web-ts-toolkit-express-runtime <command> <app-module> [options]
|
|
212
|
+
web-ts-toolkit-express-runtime <app-module> [options] (alias for dev)
|
|
213
|
+
|
|
214
|
+
Commands:
|
|
215
|
+
dev Run the Express app as a local dev server
|
|
216
|
+
build Bundle the Express app as a serverless handler
|
|
217
|
+
start Run a bundled serverless handler locally
|
|
218
|
+
|
|
219
|
+
Dev options:
|
|
220
|
+
--port <number> Port or named pipe (default: process.env.PORT or 8080)
|
|
221
|
+
--host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
|
|
222
|
+
--no-signals Disable SIGINT/SIGTERM handler registration
|
|
223
|
+
--shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
|
|
224
|
+
|
|
225
|
+
Build options:
|
|
226
|
+
--init <path> Init hook module (default export, async function)
|
|
227
|
+
--out-dir <path> Output directory (default: dist)
|
|
228
|
+
--out-name <name> Output filename without extension (default: handler)
|
|
229
|
+
--format <cjs|esm> Output format (default: cjs)
|
|
230
|
+
--target <target> Compilation target (default: node20)
|
|
231
|
+
--external <pkg> Mark package as external (repeatable; express always external)
|
|
232
|
+
--no-clean Don't clean the output directory before building
|
|
233
|
+
|
|
234
|
+
Start options:
|
|
235
|
+
--port <number> Port or named pipe (default: process.env.PORT or 8080)
|
|
236
|
+
--host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
|
|
237
|
+
--no-signals Disable SIGINT/SIGTERM handler registration
|
|
238
|
+
--shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
|
|
239
|
+
|
|
240
|
+
Global options:
|
|
241
|
+
-V, --version Show version
|
|
242
|
+
-h, --help Show this help message
|
|
243
|
+
|
|
244
|
+
Examples:
|
|
245
|
+
web-ts-toolkit-express-runtime dev ./dist/app.js
|
|
246
|
+
web-ts-toolkit-express-runtime dev ./dist/app.js --port 3000 --host localhost
|
|
247
|
+
web-ts-toolkit-express-runtime build ./src/app.ts --out-dir netlify/functions
|
|
248
|
+
web-ts-toolkit-express-runtime build ./src/app.ts --init ./src/init.ts --format esm
|
|
249
|
+
web-ts-toolkit-express-runtime start ./netlify/functions/handler.js --port 9000
|
|
250
|
+
web-ts-toolkit-express-runtime build ./src/app.ts && web-ts-toolkit-express-runtime start ./dist/handler.js
|
|
251
|
+
|
|
252
|
+
Notes:
|
|
253
|
+
- In dev mode, the CLI evaluates arbitrary code from <app-module> in the current process.
|
|
254
|
+
- TypeScript app modules in dev mode require a TS loader. Run via tsx:
|
|
255
|
+
npx tsx ./node_modules/@web-ts-toolkit/express-runtime/dist/cli.js dev ./src/app.ts
|
|
256
|
+
- In build mode, tsup is required: pnpm add -D tsup
|
|
257
|
+
- In start mode, the bundled handler file must be a JS/CJS module whose "handler"
|
|
258
|
+
export (or default export) is a function: (event, context) => Promise<result>.
|
|
259
|
+
- Init logic for dev mode (DB connections, etc.): add at the top level of your app module.
|
|
260
|
+
`);
|
|
261
|
+
}
|
|
262
|
+
function isVersion(arg) {
|
|
263
|
+
return arg === "-V" || arg === "--version";
|
|
264
|
+
}
|
|
265
|
+
function isHelp(arg) {
|
|
266
|
+
return arg === "-h" || arg === "--help";
|
|
267
|
+
}
|
|
268
|
+
function isSubcommand(arg) {
|
|
269
|
+
return arg === "dev" || arg === "build" || arg === "start";
|
|
270
|
+
}
|
|
271
|
+
function parseDevArgs(argv) {
|
|
272
|
+
const options = {};
|
|
273
|
+
let appPath;
|
|
274
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
275
|
+
const arg = argv[index];
|
|
276
|
+
if (arg === "--") {
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
if (isHelp(arg) || isVersion(arg)) {
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (arg === "--port") {
|
|
283
|
+
const port = readValue(argv, index, arg);
|
|
284
|
+
const portNum = Number(port);
|
|
285
|
+
options.port = Number.isNaN(portNum) ? port : portNum;
|
|
286
|
+
index += 1;
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
if (arg.startsWith("--port=")) {
|
|
290
|
+
const port = arg.slice("--port=".length);
|
|
291
|
+
const portNum = Number(port);
|
|
292
|
+
options.port = Number.isNaN(portNum) ? port : portNum;
|
|
293
|
+
continue;
|
|
294
|
+
}
|
|
295
|
+
if (arg === "--host") {
|
|
296
|
+
options.host = readValue(argv, index, arg);
|
|
297
|
+
index += 1;
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
if (arg.startsWith("--host=")) {
|
|
301
|
+
options.host = arg.slice("--host=".length);
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
if (arg === "--no-signals") {
|
|
305
|
+
options.signals = false;
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
if (arg === "--shutdown-timeout") {
|
|
309
|
+
options.shutdownTimeout = Number(readValue(argv, index, arg));
|
|
310
|
+
index += 1;
|
|
311
|
+
continue;
|
|
312
|
+
}
|
|
313
|
+
if (arg.startsWith("--shutdown-timeout=")) {
|
|
314
|
+
options.shutdownTimeout = Number(arg.slice("--shutdown-timeout=".length));
|
|
315
|
+
continue;
|
|
316
|
+
}
|
|
317
|
+
if (!arg.startsWith("--")) {
|
|
318
|
+
if (appPath) {
|
|
319
|
+
throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
|
|
320
|
+
}
|
|
321
|
+
appPath = arg;
|
|
322
|
+
continue;
|
|
323
|
+
}
|
|
324
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
325
|
+
}
|
|
326
|
+
if (!appPath) {
|
|
327
|
+
printHelp();
|
|
328
|
+
throw new Error("Missing required argument: <app-module>");
|
|
329
|
+
}
|
|
330
|
+
return { appPath, options };
|
|
331
|
+
}
|
|
332
|
+
function parseStartArgs(argv) {
|
|
333
|
+
const result = parseDevArgs(argv);
|
|
334
|
+
return { handlerPath: result.appPath, options: result.options };
|
|
335
|
+
}
|
|
336
|
+
function parseBuildArgs(argv) {
|
|
337
|
+
let appPath;
|
|
338
|
+
const external = [];
|
|
339
|
+
const result = {
|
|
340
|
+
initPath: void 0,
|
|
341
|
+
outDir: "dist",
|
|
342
|
+
outName: "handler",
|
|
343
|
+
format: "cjs",
|
|
344
|
+
target: "node20",
|
|
345
|
+
external,
|
|
346
|
+
clean: true
|
|
347
|
+
};
|
|
348
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
349
|
+
const arg = argv[index];
|
|
350
|
+
if (arg === "--") {
|
|
351
|
+
continue;
|
|
352
|
+
}
|
|
353
|
+
if (isHelp(arg) || isVersion(arg)) {
|
|
354
|
+
continue;
|
|
355
|
+
}
|
|
356
|
+
if (arg === "--init") {
|
|
357
|
+
result.initPath = readValue(argv, index, arg);
|
|
358
|
+
index += 1;
|
|
359
|
+
continue;
|
|
360
|
+
}
|
|
361
|
+
if (arg.startsWith("--init=")) {
|
|
362
|
+
result.initPath = arg.slice("--init=".length);
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
if (arg === "--out-dir") {
|
|
366
|
+
result.outDir = readValue(argv, index, arg);
|
|
367
|
+
index += 1;
|
|
368
|
+
continue;
|
|
369
|
+
}
|
|
370
|
+
if (arg.startsWith("--out-dir=")) {
|
|
371
|
+
result.outDir = arg.slice("--out-dir=".length);
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (arg === "--out-name") {
|
|
375
|
+
result.outName = readValue(argv, index, arg);
|
|
376
|
+
index += 1;
|
|
377
|
+
continue;
|
|
378
|
+
}
|
|
379
|
+
if (arg.startsWith("--out-name=")) {
|
|
380
|
+
result.outName = arg.slice("--out-name=".length);
|
|
381
|
+
continue;
|
|
382
|
+
}
|
|
383
|
+
if (arg === "--format") {
|
|
384
|
+
const fmt = readValue(argv, index, arg);
|
|
385
|
+
if (fmt !== "cjs" && fmt !== "esm") {
|
|
386
|
+
throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
|
|
387
|
+
}
|
|
388
|
+
result.format = fmt;
|
|
389
|
+
index += 1;
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (arg.startsWith("--format=")) {
|
|
393
|
+
const fmt = arg.slice("--format=".length);
|
|
394
|
+
if (fmt !== "cjs" && fmt !== "esm") {
|
|
395
|
+
throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
|
|
396
|
+
}
|
|
397
|
+
result.format = fmt;
|
|
398
|
+
continue;
|
|
399
|
+
}
|
|
400
|
+
if (arg === "--target") {
|
|
401
|
+
result.target = readValue(argv, index, arg);
|
|
402
|
+
index += 1;
|
|
403
|
+
continue;
|
|
404
|
+
}
|
|
405
|
+
if (arg.startsWith("--target=")) {
|
|
406
|
+
result.target = arg.slice("--target=".length);
|
|
407
|
+
continue;
|
|
408
|
+
}
|
|
409
|
+
if (arg === "--external") {
|
|
410
|
+
external.push(readValue(argv, index, arg));
|
|
411
|
+
index += 1;
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (arg.startsWith("--external=")) {
|
|
415
|
+
external.push(arg.slice("--external=".length));
|
|
416
|
+
continue;
|
|
417
|
+
}
|
|
418
|
+
if (arg === "--no-clean") {
|
|
419
|
+
result.clean = false;
|
|
420
|
+
continue;
|
|
421
|
+
}
|
|
422
|
+
if (!arg.startsWith("--")) {
|
|
423
|
+
if (appPath) {
|
|
424
|
+
throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
|
|
425
|
+
}
|
|
426
|
+
appPath = arg;
|
|
427
|
+
continue;
|
|
428
|
+
}
|
|
429
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
430
|
+
}
|
|
431
|
+
if (!appPath) {
|
|
432
|
+
printHelp();
|
|
433
|
+
throw new Error("Missing required argument: <app-module>");
|
|
434
|
+
}
|
|
435
|
+
return { appPath, ...result };
|
|
436
|
+
}
|
|
437
|
+
function parseArgs(argv) {
|
|
438
|
+
if (argv.length === 0) {
|
|
439
|
+
printHelp();
|
|
440
|
+
return null;
|
|
441
|
+
}
|
|
442
|
+
if (argv.some((a) => isHelp(a))) {
|
|
443
|
+
printHelp();
|
|
444
|
+
return null;
|
|
445
|
+
}
|
|
446
|
+
if (argv.some((a) => isVersion(a))) {
|
|
447
|
+
console.log(CLI_VERSION);
|
|
448
|
+
return null;
|
|
449
|
+
}
|
|
450
|
+
const first = argv[0];
|
|
451
|
+
if (isSubcommand(first)) {
|
|
452
|
+
const rest = argv.slice(1);
|
|
453
|
+
if (first === "dev") {
|
|
454
|
+
return { subcommand: "dev", dev: parseDevArgs(rest) };
|
|
455
|
+
}
|
|
456
|
+
if (first === "start") {
|
|
457
|
+
return { subcommand: "start", start: parseStartArgs(rest) };
|
|
458
|
+
}
|
|
459
|
+
return { subcommand: "build", build: parseBuildArgs(rest) };
|
|
460
|
+
}
|
|
461
|
+
return { subcommand: "dev", dev: parseDevArgs(argv) };
|
|
462
|
+
}
|
|
463
|
+
function isExpressApp(x) {
|
|
464
|
+
if (x === null || x === void 0) return false;
|
|
465
|
+
const t = typeof x;
|
|
466
|
+
if (t !== "object" && t !== "function") return false;
|
|
467
|
+
return typeof x.listen === "function" && typeof x.use === "function";
|
|
468
|
+
}
|
|
469
|
+
function extractExport(mod) {
|
|
470
|
+
return mod.default ?? mod.app;
|
|
471
|
+
}
|
|
472
|
+
async function resolveExport(exported, appPath) {
|
|
473
|
+
if (isExpressApp(exported)) {
|
|
474
|
+
return exported;
|
|
475
|
+
}
|
|
476
|
+
if (typeof exported === "function") {
|
|
477
|
+
const result = await exported();
|
|
478
|
+
if (!isExpressApp(result)) {
|
|
479
|
+
throw new Error(`Function in "${appPath}" did not return an Express app.`);
|
|
480
|
+
}
|
|
481
|
+
return result;
|
|
482
|
+
}
|
|
483
|
+
throw new Error(`Default export of "${appPath}" is not an Express app or an async function returning one.`);
|
|
484
|
+
}
|
|
485
|
+
async function loadApp(appPath) {
|
|
486
|
+
const fullPath = (0, import_node_path.resolve)(process.cwd(), appPath);
|
|
487
|
+
const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
|
|
488
|
+
const mod = await import(moduleUrl);
|
|
489
|
+
const exported = extractExport(mod);
|
|
490
|
+
if (!exported) {
|
|
491
|
+
throw new Error(
|
|
492
|
+
`Module "${appPath}" must default-export an Express app or an async function returning one. Exports: ${Object.keys(mod).join(", ")}`
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
return resolveExport(exported, appPath);
|
|
496
|
+
}
|
|
497
|
+
var TEMP_ENTRY_FILENAME = ".express-runtime-build-entry.ts";
|
|
498
|
+
function generateServerlessEntry(appPath, initPath) {
|
|
499
|
+
const absAppPath = (0, import_node_path.resolve)(process.cwd(), appPath);
|
|
500
|
+
const absInitPath = initPath ? (0, import_node_path.resolve)(process.cwd(), initPath) : void 0;
|
|
501
|
+
const lines = [
|
|
502
|
+
"// Auto-generated by @web-ts-toolkit/express-runtime CLI \u2014 do not edit.",
|
|
503
|
+
`import { createServerlessHandler } from '@web-ts-toolkit/express-runtime';`,
|
|
504
|
+
`import app from ${JSON.stringify(absAppPath)};`
|
|
505
|
+
];
|
|
506
|
+
if (absInitPath) {
|
|
507
|
+
lines.push(`import init from ${JSON.stringify(absInitPath)};`);
|
|
508
|
+
lines.push(`const handler = createServerlessHandler(app, { init });`);
|
|
509
|
+
} else {
|
|
510
|
+
lines.push(`const handler = createServerlessHandler(app);`);
|
|
511
|
+
}
|
|
512
|
+
lines.push(`export { handler };`);
|
|
513
|
+
return lines.join("\n") + "\n";
|
|
514
|
+
}
|
|
515
|
+
async function buildServerless(args) {
|
|
516
|
+
let tsupModule;
|
|
517
|
+
try {
|
|
518
|
+
tsupModule = await import("tsup");
|
|
519
|
+
} catch {
|
|
520
|
+
throw new Error("`tsup` is required for the `build` command. Install it as a dev dependency:\n pnpm add -D tsup");
|
|
521
|
+
}
|
|
522
|
+
const { build } = tsupModule;
|
|
523
|
+
const entryContent = generateServerlessEntry(args.appPath, args.initPath);
|
|
524
|
+
const tempEntryPath = (0, import_node_path.resolve)(process.cwd(), TEMP_ENTRY_FILENAME);
|
|
525
|
+
(0, import_node_fs.writeFileSync)(tempEntryPath, entryContent, "utf8");
|
|
526
|
+
try {
|
|
527
|
+
await build({
|
|
528
|
+
config: false,
|
|
529
|
+
// Don't auto-load tsup.config.ts from cwd
|
|
530
|
+
entry: { [args.outName]: tempEntryPath },
|
|
531
|
+
format: [args.format],
|
|
532
|
+
target: args.target,
|
|
533
|
+
outDir: args.outDir,
|
|
534
|
+
clean: args.clean,
|
|
535
|
+
external: ["express", ...args.external],
|
|
536
|
+
sourcemap: false,
|
|
537
|
+
dts: false,
|
|
538
|
+
splitting: false
|
|
539
|
+
});
|
|
540
|
+
} finally {
|
|
541
|
+
(0, import_node_fs.rmSync)(tempEntryPath, { force: true });
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
function collectBody(req) {
|
|
545
|
+
return new Promise((resolve, reject) => {
|
|
546
|
+
const chunks = [];
|
|
547
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
548
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
549
|
+
req.on("error", reject);
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
function toServerlessEvent(method, url, headers, body) {
|
|
553
|
+
return {
|
|
554
|
+
httpMethod: method,
|
|
555
|
+
path: url,
|
|
556
|
+
headers,
|
|
557
|
+
body: body.length > 0 ? body : void 0
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
function applyServerlessResult(result, res) {
|
|
561
|
+
if (result === null || result === void 0) {
|
|
562
|
+
res.status(200).end();
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const r = result;
|
|
566
|
+
if (typeof r.statusCode === "number") {
|
|
567
|
+
res.status(r.statusCode);
|
|
568
|
+
}
|
|
569
|
+
if (r.headers && typeof r.headers === "object") {
|
|
570
|
+
for (const [key, value] of Object.entries(r.headers)) {
|
|
571
|
+
if (value !== void 0) {
|
|
572
|
+
res.setHeader(key, Array.isArray(value) ? value.join(",") : value);
|
|
573
|
+
}
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
if (r.isBase64Encoded && typeof r.body === "string") {
|
|
577
|
+
res.end(Buffer.from(r.body, "base64"));
|
|
578
|
+
} else if (typeof r.body === "string") {
|
|
579
|
+
res.end(r.body);
|
|
580
|
+
} else {
|
|
581
|
+
res.end();
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
function createServerlessAdapterApp(handler) {
|
|
585
|
+
return createExpressApp({
|
|
586
|
+
json: false,
|
|
587
|
+
urlencoded: false,
|
|
588
|
+
finalize: (app) => {
|
|
589
|
+
app.use(async (req, res) => {
|
|
590
|
+
const body = await collectBody(req);
|
|
591
|
+
const event = toServerlessEvent(req.method, req.url, req.headers, body);
|
|
592
|
+
const result = await handler(event, {});
|
|
593
|
+
applyServerlessResult(result, res);
|
|
594
|
+
});
|
|
595
|
+
},
|
|
596
|
+
errorHandler: (error, _req, res, _next) => {
|
|
597
|
+
console.error("Serverless adapter error:", error);
|
|
598
|
+
res.status(500).end("Internal server error");
|
|
599
|
+
}
|
|
600
|
+
});
|
|
601
|
+
}
|
|
602
|
+
async function loadHandler(handlerPath) {
|
|
603
|
+
const fullPath = (0, import_node_path.resolve)(process.cwd(), handlerPath);
|
|
604
|
+
const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
|
|
605
|
+
const mod = await import(moduleUrl);
|
|
606
|
+
const exported = mod.handler ?? mod.default;
|
|
607
|
+
if (typeof exported !== "function") {
|
|
608
|
+
throw new Error(
|
|
609
|
+
`Module "${handlerPath}" must export a "handler" function. Exports: ${Object.keys(mod).join(", ")}`
|
|
610
|
+
);
|
|
611
|
+
}
|
|
612
|
+
return exported;
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// src/cli.ts
|
|
616
|
+
async function main() {
|
|
617
|
+
const parsedArgs = parseArgs(process.argv.slice(2));
|
|
618
|
+
if (!parsedArgs) {
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
if (parsedArgs.subcommand === "dev") {
|
|
622
|
+
const app = await loadApp(parsedArgs.dev.appPath);
|
|
623
|
+
startLocalServer(app, { ...parsedArgs.dev.options, exitAfterShutdown: true });
|
|
624
|
+
} else if (parsedArgs.subcommand === "start") {
|
|
625
|
+
const handler = await loadHandler(parsedArgs.start.handlerPath);
|
|
626
|
+
const app = createServerlessAdapterApp(handler);
|
|
627
|
+
startLocalServer(app, { ...parsedArgs.start.options, exitAfterShutdown: true });
|
|
628
|
+
} else {
|
|
629
|
+
await buildServerless(parsedArgs.build);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
main().catch((error) => {
|
|
633
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
634
|
+
console.error(message);
|
|
635
|
+
process.exitCode = 1;
|
|
636
|
+
});
|