@web-ts-toolkit/express-runtime 0.26.0 → 0.28.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/README.md +2 -0
- package/chunk-SOW7OLVN.mjs +221 -0
- package/cli-api.d.mts +241 -0
- package/cli-api.d.ts +241 -0
- package/cli-api.js +1111 -0
- package/cli-api.mjs +866 -0
- package/cli.js +187 -54
- package/index.mjs +7 -213
- package/package.json +7 -1
package/cli-api.js
ADDED
|
@@ -0,0 +1,1111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
7
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
8
|
+
var __esm = (fn, res) => function __init() {
|
|
9
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
10
|
+
};
|
|
11
|
+
var __export = (target, all) => {
|
|
12
|
+
for (var name in all)
|
|
13
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
14
|
+
};
|
|
15
|
+
var __copyProps = (to, from, except, desc) => {
|
|
16
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
17
|
+
for (let key of __getOwnPropNames(from))
|
|
18
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
19
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
20
|
+
}
|
|
21
|
+
return to;
|
|
22
|
+
};
|
|
23
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
24
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
25
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
26
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
27
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
28
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
29
|
+
mod
|
|
30
|
+
));
|
|
31
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
32
|
+
|
|
33
|
+
// src/index.ts
|
|
34
|
+
function applySettings(app, options) {
|
|
35
|
+
if (options.disablePoweredBy !== false) {
|
|
36
|
+
app.disable("x-powered-by");
|
|
37
|
+
}
|
|
38
|
+
app.set("etag", options.etag ?? false);
|
|
39
|
+
app.set("trust proxy", options.trustProxy ?? false);
|
|
40
|
+
}
|
|
41
|
+
function applyMiddlewareList(app, list) {
|
|
42
|
+
if (list) {
|
|
43
|
+
for (const mw of list) {
|
|
44
|
+
app.use(mw);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
function applyRouters(app, options) {
|
|
49
|
+
const mounts = [];
|
|
50
|
+
if (options.router) mounts.push(options.router);
|
|
51
|
+
if (options.routers) mounts.push(...options.routers);
|
|
52
|
+
for (const mount of mounts) {
|
|
53
|
+
const path = typeof mount.path === "function" ? mount.path() : mount.path;
|
|
54
|
+
app.use(path, mount.handler);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
function createExpressApp(options = {}) {
|
|
58
|
+
const app = (0, import_express.default)();
|
|
59
|
+
applySettings(app, options);
|
|
60
|
+
applyMiddlewareList(app, options.preMiddleware);
|
|
61
|
+
if (options.json !== false) {
|
|
62
|
+
app.use(import_express.default.json(options.json ?? { limit: "1mb" }));
|
|
63
|
+
}
|
|
64
|
+
if (options.urlencoded !== false) {
|
|
65
|
+
app.use(import_express.default.urlencoded(options.urlencoded ?? { extended: false, limit: "1mb" }));
|
|
66
|
+
}
|
|
67
|
+
applyMiddlewareList(app, options.middleware);
|
|
68
|
+
applyRouters(app, options);
|
|
69
|
+
applyMiddlewareList(app, options.postMiddleware);
|
|
70
|
+
if (options.finalize) {
|
|
71
|
+
options.finalize(app);
|
|
72
|
+
}
|
|
73
|
+
if (options.errorHandler) {
|
|
74
|
+
app.use(options.errorHandler);
|
|
75
|
+
}
|
|
76
|
+
return app;
|
|
77
|
+
}
|
|
78
|
+
function normalizePort(val) {
|
|
79
|
+
if (val === void 0 || val === "") {
|
|
80
|
+
const envPort = process.env.PORT;
|
|
81
|
+
if (envPort === void 0 || envPort === "") {
|
|
82
|
+
return 8080;
|
|
83
|
+
}
|
|
84
|
+
val = envPort;
|
|
85
|
+
}
|
|
86
|
+
if (typeof val === "string") {
|
|
87
|
+
const parsed = Number(val);
|
|
88
|
+
if (Number.isNaN(parsed)) {
|
|
89
|
+
return val;
|
|
90
|
+
}
|
|
91
|
+
val = parsed;
|
|
92
|
+
}
|
|
93
|
+
if (!Number.isFinite(val) || val < 0 || val > 65535) {
|
|
94
|
+
throw new Error(`Invalid port: ${String(val)}`);
|
|
95
|
+
}
|
|
96
|
+
return val;
|
|
97
|
+
}
|
|
98
|
+
function defaultOnError(error, port, logger) {
|
|
99
|
+
if (error.syscall !== "listen") {
|
|
100
|
+
throw error;
|
|
101
|
+
}
|
|
102
|
+
const bind = typeof port === "string" ? `Pipe ${port}` : `Port ${port}`;
|
|
103
|
+
if (error.code === "EACCES") {
|
|
104
|
+
logger.error(`${bind} requires elevated privileges`);
|
|
105
|
+
process.exit(1);
|
|
106
|
+
} else if (error.code === "EADDRINUSE") {
|
|
107
|
+
logger.error(`${bind} is already in use`);
|
|
108
|
+
process.exit(1);
|
|
109
|
+
} else {
|
|
110
|
+
throw error;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
function startLocalServer(app, options = {}) {
|
|
114
|
+
const logger = options.logger ?? defaultLogger;
|
|
115
|
+
const port = normalizePort(options.port);
|
|
116
|
+
const host = options.host ?? process.env.HOST ?? "0.0.0.0";
|
|
117
|
+
const shutdownTimeout = options.shutdownTimeout ?? DEFAULT_SHUTDOWN_TIMEOUT;
|
|
118
|
+
const server = import_node_http.default.createServer(app);
|
|
119
|
+
app.set("port", port);
|
|
120
|
+
const onError = (error) => {
|
|
121
|
+
if (options.onError) {
|
|
122
|
+
options.onError(error);
|
|
123
|
+
} else {
|
|
124
|
+
defaultOnError(error, port, logger);
|
|
125
|
+
}
|
|
126
|
+
};
|
|
127
|
+
const onListening = () => {
|
|
128
|
+
const addr = server.address();
|
|
129
|
+
const bind = typeof addr === "string" ? `pipe ${addr}` : `port ${addr?.port}`;
|
|
130
|
+
logger.log(`Server running at http://${host}:${port}/ (${bind})`);
|
|
131
|
+
options.onListening?.();
|
|
132
|
+
};
|
|
133
|
+
server.on("error", onError);
|
|
134
|
+
server.on("listening", onListening);
|
|
135
|
+
const shutdown = async () => {
|
|
136
|
+
logger.log("Shutting down...");
|
|
137
|
+
try {
|
|
138
|
+
if (options.onShutdown) {
|
|
139
|
+
await options.onShutdown();
|
|
140
|
+
}
|
|
141
|
+
} catch (err) {
|
|
142
|
+
logger.error("onShutdown hook failed:", err);
|
|
143
|
+
}
|
|
144
|
+
await new Promise((resolve) => {
|
|
145
|
+
const timer = setTimeout(() => {
|
|
146
|
+
server.closeAllConnections?.();
|
|
147
|
+
resolve();
|
|
148
|
+
}, shutdownTimeout);
|
|
149
|
+
server.close((err) => {
|
|
150
|
+
clearTimeout(timer);
|
|
151
|
+
if (err) {
|
|
152
|
+
logger.error("Server close error:", err);
|
|
153
|
+
}
|
|
154
|
+
resolve();
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
if (options.exitAfterShutdown) {
|
|
158
|
+
process.exit(0);
|
|
159
|
+
}
|
|
160
|
+
};
|
|
161
|
+
if (options.signals !== false) {
|
|
162
|
+
const list = options.signals === void 0 || options.signals === true ? DEFAULT_SIGNALS : options.signals;
|
|
163
|
+
for (const sig of list) {
|
|
164
|
+
process.once(sig, () => void shutdown());
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
const start = async () => {
|
|
168
|
+
try {
|
|
169
|
+
if (options.init) {
|
|
170
|
+
await options.init();
|
|
171
|
+
}
|
|
172
|
+
if (typeof port === "number") {
|
|
173
|
+
server.listen(port, host);
|
|
174
|
+
} else {
|
|
175
|
+
server.listen(port);
|
|
176
|
+
}
|
|
177
|
+
} catch (err) {
|
|
178
|
+
server.emit("error", err);
|
|
179
|
+
}
|
|
180
|
+
};
|
|
181
|
+
void start();
|
|
182
|
+
return {
|
|
183
|
+
server,
|
|
184
|
+
shutdown
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
var import_node_http, import_express, import_serverless_http, defaultLogger, DEFAULT_SIGNALS, DEFAULT_SHUTDOWN_TIMEOUT;
|
|
188
|
+
var init_index = __esm({
|
|
189
|
+
"src/index.ts"() {
|
|
190
|
+
"use strict";
|
|
191
|
+
import_node_http = __toESM(require("http"));
|
|
192
|
+
import_express = __toESM(require("express"));
|
|
193
|
+
import_serverless_http = __toESM(require("serverless-http"));
|
|
194
|
+
defaultLogger = {
|
|
195
|
+
log: (...args) => console.log(...args),
|
|
196
|
+
error: (...args) => console.error(...args),
|
|
197
|
+
debug: (...args) => console.debug(...args)
|
|
198
|
+
};
|
|
199
|
+
DEFAULT_SIGNALS = ["SIGINT", "SIGTERM"];
|
|
200
|
+
DEFAULT_SHUTDOWN_TIMEOUT = 5e3;
|
|
201
|
+
}
|
|
202
|
+
});
|
|
203
|
+
|
|
204
|
+
// src/cli-utils.ts
|
|
205
|
+
function readValue(argv, index, name) {
|
|
206
|
+
const value = argv[index + 1];
|
|
207
|
+
if (value === void 0 || value.startsWith("--")) {
|
|
208
|
+
throw new Error(`Missing value for argument: ${name}`);
|
|
209
|
+
}
|
|
210
|
+
return value;
|
|
211
|
+
}
|
|
212
|
+
function printHelp() {
|
|
213
|
+
console.log(`wtt-express-runtime
|
|
214
|
+
|
|
215
|
+
Run an Express app locally, bundle it for local or serverless runtimes, or run the bundle.
|
|
216
|
+
|
|
217
|
+
Usage:
|
|
218
|
+
wtt-express-runtime <command> <app-module> [options]
|
|
219
|
+
wtt-express-runtime <app-module> [options] (alias for dev)
|
|
220
|
+
|
|
221
|
+
Commands:
|
|
222
|
+
dev Run the Express app as a local dev server
|
|
223
|
+
build Bundle the Express app as a local app module
|
|
224
|
+
start Run a bundled local app module
|
|
225
|
+
build-serverless Bundle the Express app as a serverless handler
|
|
226
|
+
start-serverless Run a bundled serverless handler locally
|
|
227
|
+
|
|
228
|
+
Dev options:
|
|
229
|
+
--port <number> Port or named pipe (default: process.env.PORT or 8080)
|
|
230
|
+
--host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
|
|
231
|
+
--no-signals Disable SIGINT/SIGTERM handler registration
|
|
232
|
+
--shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
|
|
233
|
+
--require <module> Module(s) to preload before app load (repeatable)
|
|
234
|
+
--env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
|
|
235
|
+
--tsconfig <path> Tsconfig used by config-aware consumers for TS path resolution
|
|
236
|
+
--watch <paths> Comma-separated paths to watch for restart (repeatable; dev only)
|
|
237
|
+
--ext <extensions> Comma-separated extensions to watch (default: ts,js,mjs,cjs,json)
|
|
238
|
+
--delay <ms> Debounce ms before restarting on change (default: 500)
|
|
239
|
+
|
|
240
|
+
Build options:
|
|
241
|
+
--init <path> Init hook module (default export, async function)
|
|
242
|
+
--tsconfig <path> Use a custom tsconfig for bundling
|
|
243
|
+
--out-dir <path> Output directory (default: dist)
|
|
244
|
+
--out-name <name> Output filename without extension (default: app)
|
|
245
|
+
--format <cjs|esm> Output format (default: cjs)
|
|
246
|
+
--target <target> Compilation target (default: node22)
|
|
247
|
+
--external <pkg> Mark package as external (repeatable; express always external)
|
|
248
|
+
--no-clean Don't clean the output directory before building
|
|
249
|
+
|
|
250
|
+
Start options:
|
|
251
|
+
--port <number> Port or named pipe (default: process.env.PORT or 8080)
|
|
252
|
+
--host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
|
|
253
|
+
--no-signals Disable SIGINT/SIGTERM handler registration
|
|
254
|
+
--shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
|
|
255
|
+
--require <module> Module(s) to preload before app load (repeatable)
|
|
256
|
+
--env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
|
|
257
|
+
|
|
258
|
+
Build-serverless options:
|
|
259
|
+
--init <path> Init hook module (default export, async function)
|
|
260
|
+
--tsconfig <path> Use a custom tsconfig for bundling
|
|
261
|
+
--out-dir <path> Output directory (default: dist)
|
|
262
|
+
--out-name <name> Output filename without extension (default: handler)
|
|
263
|
+
--format <cjs|esm> Output format (default: cjs)
|
|
264
|
+
--target <target> Compilation target (default: node22)
|
|
265
|
+
--external <pkg> Mark package as external (repeatable; express always external)
|
|
266
|
+
--no-clean Don't clean the output directory before building
|
|
267
|
+
|
|
268
|
+
Start-serverless options:
|
|
269
|
+
--port <number> Port or named pipe (default: process.env.PORT or 8080)
|
|
270
|
+
--host <hostname> Hostname to bind (default: process.env.HOST or 0.0.0.0)
|
|
271
|
+
--no-signals Disable SIGINT/SIGTERM handler registration
|
|
272
|
+
--shutdown-timeout <ms> Max ms to wait for in-flight requests (default: 5000)
|
|
273
|
+
--require <module> Module(s) to preload before handler load (repeatable)
|
|
274
|
+
--env <path> Env file(s) to load (repeatable; existing env vars are not overridden)
|
|
275
|
+
|
|
276
|
+
Global options:
|
|
277
|
+
-V, --version Show version
|
|
278
|
+
-h, --help Show this help message
|
|
279
|
+
|
|
280
|
+
Examples:
|
|
281
|
+
wtt-express-runtime dev ./dist/app.js
|
|
282
|
+
wtt-express-runtime dev ./dist/app.js --port 3000 --host localhost
|
|
283
|
+
wtt-express-runtime dev ./src/app.ts --env .env --require tsconfig-paths/register --watch ./src,./shared
|
|
284
|
+
wtt-express-runtime build ./src/app.ts --out-dir dist
|
|
285
|
+
wtt-express-runtime start ./dist/app.js --port 3000 --env .env
|
|
286
|
+
wtt-express-runtime build-serverless ./src/app.ts --out-dir netlify/functions
|
|
287
|
+
wtt-express-runtime build-serverless ./src/app.ts --init ./src/init.ts --format esm
|
|
288
|
+
wtt-express-runtime start-serverless ./netlify/functions/handler.js --port 9000 --env .env
|
|
289
|
+
wtt-express-runtime build-serverless ./src/app.ts && wtt-express-runtime start-serverless ./dist/handler.js
|
|
290
|
+
|
|
291
|
+
Notes:
|
|
292
|
+
- In dev mode, the CLI evaluates arbitrary code from <app-module> in the current process.
|
|
293
|
+
- TypeScript app modules in dev mode require a TS loader. Run via tsx:
|
|
294
|
+
npx tsx ./node_modules/@web-ts-toolkit/express-runtime/dist/cli.js dev ./src/app.ts
|
|
295
|
+
Or use --require with a TS-aware loader module.
|
|
296
|
+
- --env files are parsed as KEY=VALUE; existing process.env entries are never overridden.
|
|
297
|
+
For advanced dotenv features (multiline, expansion), --require dotenv/config instead.
|
|
298
|
+
- --watch forks a child process running the same CLI without --watch. On file change,
|
|
299
|
+
the child is killed (SIGTERM) and respawned after the debounce delay.
|
|
300
|
+
- In build/build-serverless mode, express is always external. Add more externals with --external.
|
|
301
|
+
- In start mode, the bundled app file must default-export an Express app (or export it as "app").
|
|
302
|
+
If the bundle exports "init", it runs before the server starts listening.
|
|
303
|
+
- In start-serverless mode, the bundled handler file must be a JS/CJS module whose
|
|
304
|
+
"handler" export (or default export) is a function: (event, context) => Promise<result>.
|
|
305
|
+
- Init logic for dev mode (DB connections, etc.): add at the top level of your app module.
|
|
306
|
+
`);
|
|
307
|
+
}
|
|
308
|
+
function isVersion(arg) {
|
|
309
|
+
return arg === "-V" || arg === "--version";
|
|
310
|
+
}
|
|
311
|
+
function isHelp(arg) {
|
|
312
|
+
return arg === "-h" || arg === "--help";
|
|
313
|
+
}
|
|
314
|
+
function isSubcommand(arg) {
|
|
315
|
+
return arg === "dev" || arg === "build" || arg === "start" || arg === "build-serverless" || arg === "start-serverless";
|
|
316
|
+
}
|
|
317
|
+
function parseRepeatable(argv, index, arg, list) {
|
|
318
|
+
const value = readValue(argv, index, arg);
|
|
319
|
+
for (const part of value.split(",")) {
|
|
320
|
+
const trimmed = part.trim();
|
|
321
|
+
if (trimmed) list.push(trimmed);
|
|
322
|
+
}
|
|
323
|
+
return index + 1;
|
|
324
|
+
}
|
|
325
|
+
function parseDevArgs(argv) {
|
|
326
|
+
const options = {};
|
|
327
|
+
const requireModules = [];
|
|
328
|
+
const envFiles = [];
|
|
329
|
+
const watchPaths = [];
|
|
330
|
+
let watchExt;
|
|
331
|
+
let watchDelay;
|
|
332
|
+
let tsconfigPath;
|
|
333
|
+
let appPath;
|
|
334
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
335
|
+
const arg = argv[index];
|
|
336
|
+
if (arg === "--") {
|
|
337
|
+
continue;
|
|
338
|
+
}
|
|
339
|
+
if (isHelp(arg) || isVersion(arg)) {
|
|
340
|
+
continue;
|
|
341
|
+
}
|
|
342
|
+
if (arg === "--port") {
|
|
343
|
+
const port = readValue(argv, index, arg);
|
|
344
|
+
const portNum = Number(port);
|
|
345
|
+
options.port = Number.isNaN(portNum) ? port : portNum;
|
|
346
|
+
index += 1;
|
|
347
|
+
continue;
|
|
348
|
+
}
|
|
349
|
+
if (arg.startsWith("--port=")) {
|
|
350
|
+
const port = arg.slice("--port=".length);
|
|
351
|
+
const portNum = Number(port);
|
|
352
|
+
options.port = Number.isNaN(portNum) ? port : portNum;
|
|
353
|
+
continue;
|
|
354
|
+
}
|
|
355
|
+
if (arg === "--host") {
|
|
356
|
+
options.host = readValue(argv, index, arg);
|
|
357
|
+
index += 1;
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
if (arg.startsWith("--host=")) {
|
|
361
|
+
options.host = arg.slice("--host=".length);
|
|
362
|
+
continue;
|
|
363
|
+
}
|
|
364
|
+
if (arg === "--no-signals") {
|
|
365
|
+
options.signals = false;
|
|
366
|
+
continue;
|
|
367
|
+
}
|
|
368
|
+
if (arg === "--shutdown-timeout") {
|
|
369
|
+
options.shutdownTimeout = Number(readValue(argv, index, arg));
|
|
370
|
+
index += 1;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
if (arg.startsWith("--shutdown-timeout=")) {
|
|
374
|
+
options.shutdownTimeout = Number(arg.slice("--shutdown-timeout=".length));
|
|
375
|
+
continue;
|
|
376
|
+
}
|
|
377
|
+
if (arg === "--require") {
|
|
378
|
+
index = parseRepeatable(argv, index, arg, requireModules);
|
|
379
|
+
continue;
|
|
380
|
+
}
|
|
381
|
+
if (arg.startsWith("--require=")) {
|
|
382
|
+
for (const part of arg.slice("--require=".length).split(",")) {
|
|
383
|
+
const trimmed = part.trim();
|
|
384
|
+
if (trimmed) requireModules.push(trimmed);
|
|
385
|
+
}
|
|
386
|
+
continue;
|
|
387
|
+
}
|
|
388
|
+
if (arg === "--env") {
|
|
389
|
+
index = parseRepeatable(argv, index, arg, envFiles);
|
|
390
|
+
continue;
|
|
391
|
+
}
|
|
392
|
+
if (arg.startsWith("--env=")) {
|
|
393
|
+
for (const part of arg.slice("--env=".length).split(",")) {
|
|
394
|
+
const trimmed = part.trim();
|
|
395
|
+
if (trimmed) envFiles.push(trimmed);
|
|
396
|
+
}
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
if (arg === "--tsconfig") {
|
|
400
|
+
tsconfigPath = readValue(argv, index, arg);
|
|
401
|
+
index += 1;
|
|
402
|
+
continue;
|
|
403
|
+
}
|
|
404
|
+
if (arg.startsWith("--tsconfig=")) {
|
|
405
|
+
tsconfigPath = arg.slice("--tsconfig=".length);
|
|
406
|
+
continue;
|
|
407
|
+
}
|
|
408
|
+
if (arg === "--watch") {
|
|
409
|
+
index = parseRepeatable(argv, index, arg, watchPaths);
|
|
410
|
+
continue;
|
|
411
|
+
}
|
|
412
|
+
if (arg.startsWith("--watch=")) {
|
|
413
|
+
for (const part of arg.slice("--watch=".length).split(",")) {
|
|
414
|
+
const trimmed = part.trim();
|
|
415
|
+
if (trimmed) watchPaths.push(trimmed);
|
|
416
|
+
}
|
|
417
|
+
continue;
|
|
418
|
+
}
|
|
419
|
+
if (arg === "--ext") {
|
|
420
|
+
watchExt = [];
|
|
421
|
+
index = parseRepeatable(argv, index, arg, watchExt);
|
|
422
|
+
continue;
|
|
423
|
+
}
|
|
424
|
+
if (arg.startsWith("--ext=")) {
|
|
425
|
+
watchExt = [];
|
|
426
|
+
for (const part of arg.slice("--ext=".length).split(",")) {
|
|
427
|
+
const trimmed = part.trim();
|
|
428
|
+
if (trimmed) watchExt.push(trimmed);
|
|
429
|
+
}
|
|
430
|
+
continue;
|
|
431
|
+
}
|
|
432
|
+
if (arg === "--delay") {
|
|
433
|
+
watchDelay = Number(readValue(argv, index, arg));
|
|
434
|
+
index += 1;
|
|
435
|
+
continue;
|
|
436
|
+
}
|
|
437
|
+
if (arg.startsWith("--delay=")) {
|
|
438
|
+
watchDelay = Number(arg.slice("--delay=".length));
|
|
439
|
+
continue;
|
|
440
|
+
}
|
|
441
|
+
if (!arg.startsWith("--")) {
|
|
442
|
+
if (appPath) {
|
|
443
|
+
throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
|
|
444
|
+
}
|
|
445
|
+
appPath = arg;
|
|
446
|
+
continue;
|
|
447
|
+
}
|
|
448
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
449
|
+
}
|
|
450
|
+
if (!appPath) {
|
|
451
|
+
printHelp();
|
|
452
|
+
throw new Error("Missing required argument: <app-module>");
|
|
453
|
+
}
|
|
454
|
+
return {
|
|
455
|
+
appPath,
|
|
456
|
+
options,
|
|
457
|
+
tsconfigPath,
|
|
458
|
+
require: requireModules,
|
|
459
|
+
env: envFiles,
|
|
460
|
+
watch: watchPaths,
|
|
461
|
+
watchExt: watchExt ?? DEFAULT_WATCH_EXTENSIONS,
|
|
462
|
+
watchDelay: watchDelay ?? DEFAULT_WATCH_DELAY
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
function parseStartLikeArgs(argv, subcommandName) {
|
|
466
|
+
for (const arg of argv) {
|
|
467
|
+
if (arg === "--watch" || arg.startsWith("--watch=") || arg === "--tsconfig" || arg.startsWith("--tsconfig=") || arg === "--ext" || arg.startsWith("--ext=") || arg === "--delay" || arg.startsWith("--delay=")) {
|
|
468
|
+
throw new Error(`--watch/--tsconfig/--ext/--delay are not supported with the ${subcommandName} subcommand`);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
return parseDevArgs(argv);
|
|
472
|
+
}
|
|
473
|
+
function parseStartArgs(argv) {
|
|
474
|
+
const result = parseStartLikeArgs(argv, "start");
|
|
475
|
+
return {
|
|
476
|
+
appPath: result.appPath,
|
|
477
|
+
options: result.options,
|
|
478
|
+
require: result.require,
|
|
479
|
+
env: result.env
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function parseStartServerlessArgs(argv) {
|
|
483
|
+
const result = parseStartLikeArgs(argv, "start-serverless");
|
|
484
|
+
return {
|
|
485
|
+
handlerPath: result.appPath,
|
|
486
|
+
options: result.options,
|
|
487
|
+
require: result.require,
|
|
488
|
+
env: result.env
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
function parseBuildArgs(argv, outNameDefault) {
|
|
492
|
+
let appPath;
|
|
493
|
+
const external = [];
|
|
494
|
+
const result = {
|
|
495
|
+
initPath: void 0,
|
|
496
|
+
tsconfigPath: void 0,
|
|
497
|
+
outDir: "dist",
|
|
498
|
+
outName: outNameDefault,
|
|
499
|
+
format: "cjs",
|
|
500
|
+
target: "node22",
|
|
501
|
+
external,
|
|
502
|
+
clean: true
|
|
503
|
+
};
|
|
504
|
+
for (let index = 0; index < argv.length; index += 1) {
|
|
505
|
+
const arg = argv[index];
|
|
506
|
+
if (arg === "--") {
|
|
507
|
+
continue;
|
|
508
|
+
}
|
|
509
|
+
if (isHelp(arg) || isVersion(arg)) {
|
|
510
|
+
continue;
|
|
511
|
+
}
|
|
512
|
+
if (arg === "--init") {
|
|
513
|
+
result.initPath = readValue(argv, index, arg);
|
|
514
|
+
index += 1;
|
|
515
|
+
continue;
|
|
516
|
+
}
|
|
517
|
+
if (arg.startsWith("--init=")) {
|
|
518
|
+
result.initPath = arg.slice("--init=".length);
|
|
519
|
+
continue;
|
|
520
|
+
}
|
|
521
|
+
if (arg === "--tsconfig") {
|
|
522
|
+
result.tsconfigPath = readValue(argv, index, arg);
|
|
523
|
+
index += 1;
|
|
524
|
+
continue;
|
|
525
|
+
}
|
|
526
|
+
if (arg.startsWith("--tsconfig=")) {
|
|
527
|
+
result.tsconfigPath = arg.slice("--tsconfig=".length);
|
|
528
|
+
continue;
|
|
529
|
+
}
|
|
530
|
+
if (arg === "--out-dir") {
|
|
531
|
+
result.outDir = readValue(argv, index, arg);
|
|
532
|
+
index += 1;
|
|
533
|
+
continue;
|
|
534
|
+
}
|
|
535
|
+
if (arg.startsWith("--out-dir=")) {
|
|
536
|
+
result.outDir = arg.slice("--out-dir=".length);
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
if (arg === "--out-name") {
|
|
540
|
+
result.outName = readValue(argv, index, arg);
|
|
541
|
+
index += 1;
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
if (arg.startsWith("--out-name=")) {
|
|
545
|
+
result.outName = arg.slice("--out-name=".length);
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
if (arg === "--format") {
|
|
549
|
+
const fmt = readValue(argv, index, arg);
|
|
550
|
+
if (fmt !== "cjs" && fmt !== "esm") {
|
|
551
|
+
throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
|
|
552
|
+
}
|
|
553
|
+
result.format = fmt;
|
|
554
|
+
index += 1;
|
|
555
|
+
continue;
|
|
556
|
+
}
|
|
557
|
+
if (arg.startsWith("--format=")) {
|
|
558
|
+
const fmt = arg.slice("--format=".length);
|
|
559
|
+
if (fmt !== "cjs" && fmt !== "esm") {
|
|
560
|
+
throw new Error(`Invalid --format: ${fmt}. Must be 'cjs' or 'esm'.`);
|
|
561
|
+
}
|
|
562
|
+
result.format = fmt;
|
|
563
|
+
continue;
|
|
564
|
+
}
|
|
565
|
+
if (arg === "--target") {
|
|
566
|
+
result.target = readValue(argv, index, arg);
|
|
567
|
+
index += 1;
|
|
568
|
+
continue;
|
|
569
|
+
}
|
|
570
|
+
if (arg.startsWith("--target=")) {
|
|
571
|
+
result.target = arg.slice("--target=".length);
|
|
572
|
+
continue;
|
|
573
|
+
}
|
|
574
|
+
if (arg === "--external") {
|
|
575
|
+
external.push(readValue(argv, index, arg));
|
|
576
|
+
index += 1;
|
|
577
|
+
continue;
|
|
578
|
+
}
|
|
579
|
+
if (arg.startsWith("--external=")) {
|
|
580
|
+
external.push(arg.slice("--external=".length));
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
if (arg === "--no-clean") {
|
|
584
|
+
result.clean = false;
|
|
585
|
+
continue;
|
|
586
|
+
}
|
|
587
|
+
if (!arg.startsWith("--")) {
|
|
588
|
+
if (appPath) {
|
|
589
|
+
throw new Error(`Unexpected positional argument: ${arg}. App module already set to ${appPath}`);
|
|
590
|
+
}
|
|
591
|
+
appPath = arg;
|
|
592
|
+
continue;
|
|
593
|
+
}
|
|
594
|
+
throw new Error(`Unknown argument: ${arg}`);
|
|
595
|
+
}
|
|
596
|
+
if (!appPath) {
|
|
597
|
+
printHelp();
|
|
598
|
+
throw new Error("Missing required argument: <app-module>");
|
|
599
|
+
}
|
|
600
|
+
return { appPath, ...result };
|
|
601
|
+
}
|
|
602
|
+
function parseLocalBuildArgs(argv) {
|
|
603
|
+
return parseBuildArgs(argv, "app");
|
|
604
|
+
}
|
|
605
|
+
function parseBuildServerlessArgs(argv) {
|
|
606
|
+
return parseBuildArgs(argv, "handler");
|
|
607
|
+
}
|
|
608
|
+
function parseArgs(argv) {
|
|
609
|
+
if (argv.length === 0) {
|
|
610
|
+
printHelp();
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
if (argv.some((a) => isHelp(a))) {
|
|
614
|
+
printHelp();
|
|
615
|
+
return null;
|
|
616
|
+
}
|
|
617
|
+
if (argv.some((a) => isVersion(a))) {
|
|
618
|
+
console.log(CLI_VERSION);
|
|
619
|
+
return null;
|
|
620
|
+
}
|
|
621
|
+
const first = argv[0];
|
|
622
|
+
if (isSubcommand(first)) {
|
|
623
|
+
const rest = argv.slice(1);
|
|
624
|
+
if (first === "dev") {
|
|
625
|
+
return { subcommand: "dev", dev: parseDevArgs(rest) };
|
|
626
|
+
}
|
|
627
|
+
if (first === "build") {
|
|
628
|
+
return { subcommand: "build", build: parseLocalBuildArgs(rest) };
|
|
629
|
+
}
|
|
630
|
+
if (first === "start") {
|
|
631
|
+
return { subcommand: "start", start: parseStartArgs(rest) };
|
|
632
|
+
}
|
|
633
|
+
if (first === "build-serverless") {
|
|
634
|
+
return { subcommand: "build-serverless", buildServerless: parseBuildServerlessArgs(rest) };
|
|
635
|
+
}
|
|
636
|
+
return { subcommand: "start-serverless", startServerless: parseStartServerlessArgs(rest) };
|
|
637
|
+
}
|
|
638
|
+
return { subcommand: "dev", dev: parseDevArgs(argv) };
|
|
639
|
+
}
|
|
640
|
+
function isExpressApp(x) {
|
|
641
|
+
if (x === null || x === void 0) return false;
|
|
642
|
+
const t = typeof x;
|
|
643
|
+
if (t !== "object" && t !== "function") return false;
|
|
644
|
+
return typeof x.listen === "function" && typeof x.use === "function";
|
|
645
|
+
}
|
|
646
|
+
function extractExport(mod) {
|
|
647
|
+
return mod.default ?? mod.app;
|
|
648
|
+
}
|
|
649
|
+
async function resolveExport(exported, appPath) {
|
|
650
|
+
if (isExpressApp(exported)) {
|
|
651
|
+
return exported;
|
|
652
|
+
}
|
|
653
|
+
if (typeof exported === "function") {
|
|
654
|
+
const result = await exported();
|
|
655
|
+
if (!isExpressApp(result)) {
|
|
656
|
+
throw new Error(`Function in "${appPath}" did not return an Express app.`);
|
|
657
|
+
}
|
|
658
|
+
return result;
|
|
659
|
+
}
|
|
660
|
+
throw new Error(`Default export of "${appPath}" is not an Express app or an async function returning one.`);
|
|
661
|
+
}
|
|
662
|
+
async function loadApp(appPath) {
|
|
663
|
+
const fullPath = (0, import_node_path.resolve)(process.cwd(), appPath);
|
|
664
|
+
const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
|
|
665
|
+
const mod = await import(moduleUrl);
|
|
666
|
+
const exported = extractExport(mod);
|
|
667
|
+
if (!exported) {
|
|
668
|
+
throw new Error(
|
|
669
|
+
`Module "${appPath}" must default-export an Express app or an async function returning one. Exports: ${Object.keys(mod).join(", ")}`
|
|
670
|
+
);
|
|
671
|
+
}
|
|
672
|
+
return resolveExport(exported, appPath);
|
|
673
|
+
}
|
|
674
|
+
function parseEnvFile(content) {
|
|
675
|
+
const result = {};
|
|
676
|
+
for (const line of content.split("\n")) {
|
|
677
|
+
let trimmed = line.trim();
|
|
678
|
+
if (!trimmed || trimmed.startsWith("#")) continue;
|
|
679
|
+
if (trimmed.startsWith("export ")) trimmed = trimmed.slice("export ".length).trim();
|
|
680
|
+
const eqIndex = trimmed.indexOf("=");
|
|
681
|
+
if (eqIndex === -1) continue;
|
|
682
|
+
const key = trimmed.slice(0, eqIndex).trim();
|
|
683
|
+
let value = trimmed.slice(eqIndex + 1).trim();
|
|
684
|
+
if (value.length >= 2) {
|
|
685
|
+
const first = value[0];
|
|
686
|
+
const last = value[value.length - 1];
|
|
687
|
+
if (first === '"' && last === '"' || first === "'" && last === "'") {
|
|
688
|
+
value = value.slice(1, -1);
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
result[key] = value;
|
|
692
|
+
}
|
|
693
|
+
return result;
|
|
694
|
+
}
|
|
695
|
+
function loadEnvFiles(paths) {
|
|
696
|
+
for (const p of paths) {
|
|
697
|
+
const absPath = (0, import_node_path.resolve)(process.cwd(), p);
|
|
698
|
+
if (!(0, import_node_fs.existsSync)(absPath)) {
|
|
699
|
+
throw new Error(`Env file not found: ${p}`);
|
|
700
|
+
}
|
|
701
|
+
const content = (0, import_node_fs.readFileSync)(absPath, "utf8");
|
|
702
|
+
const parsed = parseEnvFile(content);
|
|
703
|
+
for (const [key, value] of Object.entries(parsed)) {
|
|
704
|
+
if (process.env[key] === void 0) {
|
|
705
|
+
process.env[key] = value;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
async function preloadModules(modules) {
|
|
711
|
+
for (const mod of modules) {
|
|
712
|
+
moduleRequire(mod);
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
function buildChildArgs(args) {
|
|
716
|
+
const result = ["dev", args.appPath];
|
|
717
|
+
if (args.options.port !== void 0) result.push("--port", String(args.options.port));
|
|
718
|
+
if (args.options.host !== void 0) result.push("--host", args.options.host);
|
|
719
|
+
if (args.options.signals === false) result.push("--no-signals");
|
|
720
|
+
if (args.options.shutdownTimeout !== void 0)
|
|
721
|
+
result.push("--shutdown-timeout", String(args.options.shutdownTimeout));
|
|
722
|
+
if (args.tsconfigPath !== void 0) result.push("--tsconfig", args.tsconfigPath);
|
|
723
|
+
for (const r of args.require) result.push("--require", r);
|
|
724
|
+
for (const e of args.env) result.push("--env", e);
|
|
725
|
+
return result;
|
|
726
|
+
}
|
|
727
|
+
function runWithWatch(args) {
|
|
728
|
+
const cliPath = process.argv[1];
|
|
729
|
+
const childArgv = buildChildArgs(args);
|
|
730
|
+
let child = null;
|
|
731
|
+
let restartTimer = null;
|
|
732
|
+
let isShuttingDown = false;
|
|
733
|
+
const restartDelay = args.watchDelay;
|
|
734
|
+
const spawnChild = () => {
|
|
735
|
+
child = (0, import_node_child_process.fork)(cliPath, childArgv, { stdio: "inherit" });
|
|
736
|
+
child.on("exit", (code) => {
|
|
737
|
+
child = null;
|
|
738
|
+
if (!isShuttingDown && code !== null && code !== 0) {
|
|
739
|
+
}
|
|
740
|
+
});
|
|
741
|
+
};
|
|
742
|
+
const killChild = () => {
|
|
743
|
+
return new Promise((resolve) => {
|
|
744
|
+
if (!child || !child.pid) {
|
|
745
|
+
resolve();
|
|
746
|
+
return;
|
|
747
|
+
}
|
|
748
|
+
child.once("exit", () => resolve());
|
|
749
|
+
child.kill("SIGTERM");
|
|
750
|
+
});
|
|
751
|
+
};
|
|
752
|
+
const restart = async () => {
|
|
753
|
+
await killChild();
|
|
754
|
+
spawnChild();
|
|
755
|
+
};
|
|
756
|
+
const debouncedRestart = () => {
|
|
757
|
+
if (restartTimer) clearTimeout(restartTimer);
|
|
758
|
+
restartTimer = setTimeout(() => {
|
|
759
|
+
restartTimer = null;
|
|
760
|
+
void restart();
|
|
761
|
+
}, restartDelay);
|
|
762
|
+
};
|
|
763
|
+
for (const watchPath of args.watch) {
|
|
764
|
+
const absPath = (0, import_node_path.resolve)(process.cwd(), watchPath);
|
|
765
|
+
if (!(0, import_node_fs.existsSync)(absPath)) {
|
|
766
|
+
throw new Error(`Watch path not found: ${watchPath}`);
|
|
767
|
+
}
|
|
768
|
+
(0, import_node_fs.watch)(absPath, { recursive: true }, (_eventType, filename) => {
|
|
769
|
+
if (!filename) return;
|
|
770
|
+
const ext = (0, import_node_path.extname)(filename).slice(1).toLowerCase();
|
|
771
|
+
if (args.watchExt.includes(ext)) {
|
|
772
|
+
debouncedRestart();
|
|
773
|
+
}
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
const shutdown = () => {
|
|
777
|
+
isShuttingDown = true;
|
|
778
|
+
if (restartTimer) clearTimeout(restartTimer);
|
|
779
|
+
if (child && child.pid) {
|
|
780
|
+
child.once("exit", () => process.exit(0));
|
|
781
|
+
child.kill("SIGTERM");
|
|
782
|
+
} else {
|
|
783
|
+
process.exit(0);
|
|
784
|
+
}
|
|
785
|
+
};
|
|
786
|
+
process.on("SIGINT", shutdown);
|
|
787
|
+
process.on("SIGTERM", shutdown);
|
|
788
|
+
spawnChild();
|
|
789
|
+
}
|
|
790
|
+
function generateServerlessEntry(appPath, initPath) {
|
|
791
|
+
const absAppPath = (0, import_node_path.resolve)(process.cwd(), appPath);
|
|
792
|
+
const absInitPath = initPath ? (0, import_node_path.resolve)(process.cwd(), initPath) : void 0;
|
|
793
|
+
const lines = [
|
|
794
|
+
"// Auto-generated by @web-ts-toolkit/express-runtime CLI \u2014 do not edit.",
|
|
795
|
+
`import { createServerlessHandler } from '@web-ts-toolkit/express-runtime';`,
|
|
796
|
+
`import app from ${JSON.stringify(absAppPath)};`
|
|
797
|
+
];
|
|
798
|
+
if (absInitPath) {
|
|
799
|
+
lines.push(`import init from ${JSON.stringify(absInitPath)};`);
|
|
800
|
+
lines.push(`const handler = createServerlessHandler(app, { init });`);
|
|
801
|
+
} else {
|
|
802
|
+
lines.push(`const handler = createServerlessHandler(app);`);
|
|
803
|
+
}
|
|
804
|
+
lines.push(`export { handler };`);
|
|
805
|
+
return lines.join("\n") + "\n";
|
|
806
|
+
}
|
|
807
|
+
function generateRuntimeEntry(appPath, initPath) {
|
|
808
|
+
const absAppPath = (0, import_node_path.resolve)(process.cwd(), appPath);
|
|
809
|
+
const absInitPath = initPath ? (0, import_node_path.resolve)(process.cwd(), initPath) : void 0;
|
|
810
|
+
const lines = [
|
|
811
|
+
"// Auto-generated by @web-ts-toolkit/express-runtime CLI \u2014 do not edit.",
|
|
812
|
+
`import app from ${JSON.stringify(absAppPath)};`,
|
|
813
|
+
"export default app;",
|
|
814
|
+
"export { app };"
|
|
815
|
+
];
|
|
816
|
+
if (absInitPath) {
|
|
817
|
+
lines.push(`export { default as init } from ${JSON.stringify(absInitPath)};`);
|
|
818
|
+
}
|
|
819
|
+
return lines.join("\n") + "\n";
|
|
820
|
+
}
|
|
821
|
+
async function buildBundleFromEntryContent(args) {
|
|
822
|
+
const tsupModule = await import("tsup");
|
|
823
|
+
const { build } = tsupModule;
|
|
824
|
+
const tempEntryPath = (0, import_node_path.resolve)(process.cwd(), args.tempEntryFilename);
|
|
825
|
+
(0, import_node_fs.writeFileSync)(tempEntryPath, args.entryContent, "utf8");
|
|
826
|
+
try {
|
|
827
|
+
await build({
|
|
828
|
+
config: false,
|
|
829
|
+
entry: { [args.outName]: tempEntryPath },
|
|
830
|
+
tsconfig: args.tsconfigPath,
|
|
831
|
+
format: [args.format],
|
|
832
|
+
target: args.target,
|
|
833
|
+
outDir: args.outDir,
|
|
834
|
+
clean: args.clean,
|
|
835
|
+
external: ["express", ...args.external],
|
|
836
|
+
sourcemap: false,
|
|
837
|
+
dts: false,
|
|
838
|
+
splitting: false
|
|
839
|
+
});
|
|
840
|
+
} finally {
|
|
841
|
+
(0, import_node_fs.rmSync)(tempEntryPath, { force: true });
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
async function buildRuntime(args) {
|
|
845
|
+
const { runBuildEntryCommand: runBuildEntryCommand2 } = await Promise.resolve().then(() => (init_cli_api(), cli_api_exports));
|
|
846
|
+
await runBuildEntryCommand2(args, {
|
|
847
|
+
generateEntry: generateRuntimeEntry,
|
|
848
|
+
tempEntryFilename: TEMP_BUILD_ENTRY_FILENAME
|
|
849
|
+
});
|
|
850
|
+
}
|
|
851
|
+
async function buildServerless(args) {
|
|
852
|
+
const { runBuildEntryCommand: runBuildEntryCommand2 } = await Promise.resolve().then(() => (init_cli_api(), cli_api_exports));
|
|
853
|
+
await runBuildEntryCommand2(args, {
|
|
854
|
+
generateEntry: generateServerlessEntry,
|
|
855
|
+
tempEntryFilename: TEMP_SERVERLESS_ENTRY_FILENAME
|
|
856
|
+
});
|
|
857
|
+
}
|
|
858
|
+
function collectBody(req) {
|
|
859
|
+
return new Promise((resolve, reject) => {
|
|
860
|
+
const chunks = [];
|
|
861
|
+
req.on("data", (chunk) => chunks.push(chunk));
|
|
862
|
+
req.on("end", () => resolve(Buffer.concat(chunks)));
|
|
863
|
+
req.on("error", reject);
|
|
864
|
+
});
|
|
865
|
+
}
|
|
866
|
+
function toServerlessEvent(method, url, headers, body) {
|
|
867
|
+
return {
|
|
868
|
+
httpMethod: method,
|
|
869
|
+
path: url,
|
|
870
|
+
headers,
|
|
871
|
+
body: body.length > 0 ? body : void 0
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
function applyServerlessResult(result, res) {
|
|
875
|
+
if (result === null || result === void 0) {
|
|
876
|
+
res.status(200).end();
|
|
877
|
+
return;
|
|
878
|
+
}
|
|
879
|
+
const r = result;
|
|
880
|
+
if (typeof r.statusCode === "number") {
|
|
881
|
+
res.status(r.statusCode);
|
|
882
|
+
}
|
|
883
|
+
if (r.headers && typeof r.headers === "object") {
|
|
884
|
+
for (const [key, value] of Object.entries(r.headers)) {
|
|
885
|
+
if (value !== void 0) {
|
|
886
|
+
res.setHeader(key, Array.isArray(value) ? value.join(",") : value);
|
|
887
|
+
}
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
if (r.isBase64Encoded && typeof r.body === "string") {
|
|
891
|
+
res.end(Buffer.from(r.body, "base64"));
|
|
892
|
+
} else if (typeof r.body === "string") {
|
|
893
|
+
res.end(r.body);
|
|
894
|
+
} else {
|
|
895
|
+
res.end();
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
function createServerlessAdapterApp(handler) {
|
|
899
|
+
return createExpressApp({
|
|
900
|
+
json: false,
|
|
901
|
+
urlencoded: false,
|
|
902
|
+
finalize: (app) => {
|
|
903
|
+
app.use(async (req, res) => {
|
|
904
|
+
const body = await collectBody(req);
|
|
905
|
+
const event = toServerlessEvent(req.method, req.url, req.headers, body);
|
|
906
|
+
const result = await handler(event, {});
|
|
907
|
+
applyServerlessResult(result, res);
|
|
908
|
+
});
|
|
909
|
+
},
|
|
910
|
+
errorHandler: (error, _req, res, _next) => {
|
|
911
|
+
console.error("Serverless adapter error:", error);
|
|
912
|
+
res.status(500).end("Internal server error");
|
|
913
|
+
}
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
async function loadBuiltApp(appPath) {
|
|
917
|
+
const fullPath = (0, import_node_path.resolve)(process.cwd(), appPath);
|
|
918
|
+
const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
|
|
919
|
+
const mod = await import(moduleUrl);
|
|
920
|
+
const exported = extractExport(mod);
|
|
921
|
+
if (!exported) {
|
|
922
|
+
throw new Error(
|
|
923
|
+
`Module "${appPath}" must default-export an Express app or export it as "app". Exports: ${Object.keys(mod).join(", ")}`
|
|
924
|
+
);
|
|
925
|
+
}
|
|
926
|
+
const init = mod.init;
|
|
927
|
+
if (init !== void 0 && typeof init !== "function") {
|
|
928
|
+
throw new Error(`Module "${appPath}" must export "init" as a function when present.`);
|
|
929
|
+
}
|
|
930
|
+
return {
|
|
931
|
+
app: await resolveExport(exported, appPath),
|
|
932
|
+
init
|
|
933
|
+
};
|
|
934
|
+
}
|
|
935
|
+
async function loadHandler(handlerPath) {
|
|
936
|
+
const fullPath = (0, import_node_path.resolve)(process.cwd(), handlerPath);
|
|
937
|
+
const moduleUrl = (0, import_node_url.pathToFileURL)(fullPath).href;
|
|
938
|
+
const mod = await import(moduleUrl);
|
|
939
|
+
const exported = mod.handler ?? mod.default;
|
|
940
|
+
if (typeof exported !== "function") {
|
|
941
|
+
throw new Error(
|
|
942
|
+
`Module "${handlerPath}" must export a "handler" function. Exports: ${Object.keys(mod).join(", ")}`
|
|
943
|
+
);
|
|
944
|
+
}
|
|
945
|
+
return exported;
|
|
946
|
+
}
|
|
947
|
+
var import_node_url, import_node_path, import_node_fs, import_node_module, import_node_child_process, import_meta, CLI_VERSION, DEFAULT_WATCH_EXTENSIONS, DEFAULT_WATCH_DELAY, moduleRequire, TEMP_BUILD_ENTRY_FILENAME, TEMP_SERVERLESS_ENTRY_FILENAME;
|
|
948
|
+
var init_cli_utils = __esm({
|
|
949
|
+
"src/cli-utils.ts"() {
|
|
950
|
+
"use strict";
|
|
951
|
+
import_node_url = require("url");
|
|
952
|
+
import_node_path = require("path");
|
|
953
|
+
import_node_fs = require("fs");
|
|
954
|
+
import_node_module = require("module");
|
|
955
|
+
import_node_child_process = require("child_process");
|
|
956
|
+
init_index();
|
|
957
|
+
import_meta = {};
|
|
958
|
+
CLI_VERSION = "0.0.0-PLACEHOLDER";
|
|
959
|
+
DEFAULT_WATCH_EXTENSIONS = ["ts", "js", "mjs", "cjs", "json"];
|
|
960
|
+
DEFAULT_WATCH_DELAY = 500;
|
|
961
|
+
moduleRequire = (0, import_node_module.createRequire)(
|
|
962
|
+
typeof import_meta !== "undefined" && import_meta.url || (0, import_node_path.resolve)(process.cwd(), "x").replace(/x$/, "")
|
|
963
|
+
);
|
|
964
|
+
TEMP_BUILD_ENTRY_FILENAME = ".express-runtime-build-entry.ts";
|
|
965
|
+
TEMP_SERVERLESS_ENTRY_FILENAME = ".express-runtime-build-serverless-entry.ts";
|
|
966
|
+
}
|
|
967
|
+
});
|
|
968
|
+
|
|
969
|
+
// src/cli-api.ts
|
|
970
|
+
var cli_api_exports = {};
|
|
971
|
+
__export(cli_api_exports, {
|
|
972
|
+
CLI_VERSION: () => CLI_VERSION,
|
|
973
|
+
applyServerlessResult: () => applyServerlessResult,
|
|
974
|
+
buildBundleFromEntryContent: () => buildBundleFromEntryContent,
|
|
975
|
+
buildChildArgs: () => buildChildArgs,
|
|
976
|
+
buildRuntime: () => buildRuntime,
|
|
977
|
+
buildServerless: () => buildServerless,
|
|
978
|
+
createServerlessAdapterApp: () => createServerlessAdapterApp,
|
|
979
|
+
extractExport: () => extractExport,
|
|
980
|
+
generateRuntimeEntry: () => generateRuntimeEntry,
|
|
981
|
+
generateServerlessEntry: () => generateServerlessEntry,
|
|
982
|
+
isExpressApp: () => isExpressApp,
|
|
983
|
+
loadApp: () => loadApp,
|
|
984
|
+
loadBuiltApp: () => loadBuiltApp,
|
|
985
|
+
loadEnvFiles: () => loadEnvFiles,
|
|
986
|
+
loadHandler: () => loadHandler,
|
|
987
|
+
parseArgs: () => parseArgs,
|
|
988
|
+
parseEnvFile: () => parseEnvFile,
|
|
989
|
+
preloadModules: () => preloadModules,
|
|
990
|
+
printHelp: () => printHelp,
|
|
991
|
+
readValue: () => readValue,
|
|
992
|
+
resolveExport: () => resolveExport,
|
|
993
|
+
runBuildEntryCommand: () => runBuildEntryCommand,
|
|
994
|
+
runCliCommand: () => runCliCommand,
|
|
995
|
+
runDevCommand: () => runDevCommand,
|
|
996
|
+
runExpressDevCommand: () => runExpressDevCommand,
|
|
997
|
+
runWithWatch: () => runWithWatch,
|
|
998
|
+
toServerlessEvent: () => toServerlessEvent
|
|
999
|
+
});
|
|
1000
|
+
module.exports = __toCommonJS(cli_api_exports);
|
|
1001
|
+
async function runDevCommand(args, runner) {
|
|
1002
|
+
if (args.watch.length > 0) {
|
|
1003
|
+
(runner.watch ?? runWithWatch)(args);
|
|
1004
|
+
return;
|
|
1005
|
+
}
|
|
1006
|
+
if (args.env.length > 0) {
|
|
1007
|
+
loadEnvFiles(args.env);
|
|
1008
|
+
}
|
|
1009
|
+
await preloadModules(args.require);
|
|
1010
|
+
const loaded = await runner.load(args.appPath);
|
|
1011
|
+
runner.start(loaded, { ...args.options, exitAfterShutdown: true });
|
|
1012
|
+
}
|
|
1013
|
+
async function runExpressDevCommand(args) {
|
|
1014
|
+
await runDevCommand(args, {
|
|
1015
|
+
load: loadApp,
|
|
1016
|
+
start: (app, options) => {
|
|
1017
|
+
startLocalServer(app, options);
|
|
1018
|
+
}
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
async function runBuildEntryCommand(args, options) {
|
|
1022
|
+
if (options.allowInit === false && args.initPath) {
|
|
1023
|
+
throw new Error(options.initErrorMessage ?? "This build command manages init automatically. Remove --init.");
|
|
1024
|
+
}
|
|
1025
|
+
await buildBundleFromEntryContent({
|
|
1026
|
+
entryContent: options.generateEntry(args.appPath, args.initPath),
|
|
1027
|
+
tempEntryFilename: options.tempEntryFilename,
|
|
1028
|
+
tsconfigPath: args.tsconfigPath,
|
|
1029
|
+
outDir: args.outDir,
|
|
1030
|
+
outName: args.outName,
|
|
1031
|
+
format: args.format,
|
|
1032
|
+
target: args.target,
|
|
1033
|
+
external: args.external,
|
|
1034
|
+
clean: args.clean
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
async function runCliCommand(parsedArgs) {
|
|
1038
|
+
if (parsedArgs.subcommand === "dev") {
|
|
1039
|
+
await runExpressDevCommand(parsedArgs.dev);
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1042
|
+
if (parsedArgs.subcommand === "start") {
|
|
1043
|
+
const { start } = parsedArgs;
|
|
1044
|
+
if (start.env.length > 0) {
|
|
1045
|
+
loadEnvFiles(start.env);
|
|
1046
|
+
}
|
|
1047
|
+
await preloadModules(start.require);
|
|
1048
|
+
const { app, init } = await loadBuiltApp(start.appPath);
|
|
1049
|
+
startLocalServer(app, {
|
|
1050
|
+
...start.options,
|
|
1051
|
+
init: init ? async () => {
|
|
1052
|
+
await init();
|
|
1053
|
+
} : void 0,
|
|
1054
|
+
exitAfterShutdown: true
|
|
1055
|
+
});
|
|
1056
|
+
return;
|
|
1057
|
+
}
|
|
1058
|
+
if (parsedArgs.subcommand === "build") {
|
|
1059
|
+
await buildRuntime(parsedArgs.build);
|
|
1060
|
+
return;
|
|
1061
|
+
}
|
|
1062
|
+
if (parsedArgs.subcommand === "start-serverless") {
|
|
1063
|
+
const { startServerless } = parsedArgs;
|
|
1064
|
+
if (startServerless.env.length > 0) {
|
|
1065
|
+
loadEnvFiles(startServerless.env);
|
|
1066
|
+
}
|
|
1067
|
+
await preloadModules(startServerless.require);
|
|
1068
|
+
const handler = await loadHandler(startServerless.handlerPath);
|
|
1069
|
+
const app = createServerlessAdapterApp(handler);
|
|
1070
|
+
startLocalServer(app, { ...startServerless.options, exitAfterShutdown: true });
|
|
1071
|
+
return;
|
|
1072
|
+
}
|
|
1073
|
+
await buildServerless(parsedArgs.buildServerless);
|
|
1074
|
+
}
|
|
1075
|
+
var init_cli_api = __esm({
|
|
1076
|
+
"src/cli-api.ts"() {
|
|
1077
|
+
init_index();
|
|
1078
|
+
init_cli_utils();
|
|
1079
|
+
}
|
|
1080
|
+
});
|
|
1081
|
+
init_cli_api();
|
|
1082
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1083
|
+
0 && (module.exports = {
|
|
1084
|
+
CLI_VERSION,
|
|
1085
|
+
applyServerlessResult,
|
|
1086
|
+
buildBundleFromEntryContent,
|
|
1087
|
+
buildChildArgs,
|
|
1088
|
+
buildRuntime,
|
|
1089
|
+
buildServerless,
|
|
1090
|
+
createServerlessAdapterApp,
|
|
1091
|
+
extractExport,
|
|
1092
|
+
generateRuntimeEntry,
|
|
1093
|
+
generateServerlessEntry,
|
|
1094
|
+
isExpressApp,
|
|
1095
|
+
loadApp,
|
|
1096
|
+
loadBuiltApp,
|
|
1097
|
+
loadEnvFiles,
|
|
1098
|
+
loadHandler,
|
|
1099
|
+
parseArgs,
|
|
1100
|
+
parseEnvFile,
|
|
1101
|
+
preloadModules,
|
|
1102
|
+
printHelp,
|
|
1103
|
+
readValue,
|
|
1104
|
+
resolveExport,
|
|
1105
|
+
runBuildEntryCommand,
|
|
1106
|
+
runCliCommand,
|
|
1107
|
+
runDevCommand,
|
|
1108
|
+
runExpressDevCommand,
|
|
1109
|
+
runWithWatch,
|
|
1110
|
+
toServerlessEvent
|
|
1111
|
+
});
|