-
Notifications
You must be signed in to change notification settings - Fork 168
/
Copy pathmod.ts
71 lines (61 loc) · 2.17 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { serve as stdServe, serveTls } from "./deps.ts";
import { createHandler } from "./handler.ts";
import log, { type LevelName } from "./log.ts";
import { build } from "./build.ts";
import { watch } from "./dev.ts";
import { getAppDir } from "./helpers.ts";
import type { AlephConfig, ServeInit } from "./types.ts";
export type { Context, Middleware } from "./types.ts";
/** The options for Aleph.js server. */
export type ServeOptions = AlephConfig & Omit<ServeInit, "onError">;
/** Start the Aleph.js server. */
export async function serve(options?: ServeOptions): Promise<void> {
const isDev = Deno.args.includes("--dev");
const { hostname, port, signal, onListen: _onListen, plugins, ...config } = options ?? {};
// use plugins
if (plugins) {
for (const plugin of plugins) {
try {
await plugin.setup(config, { isDev });
log.debug(`plugin ${plugin.name ?? "Unnamed"} setup`);
} catch (err) {
log.fatal(`[plugin:${plugin.name}] ${err.message}`);
}
}
}
// inject the config to global
Reflect.set(globalThis, "__ALEPH_CONFIG", config);
const handler = createHandler(config);
// build the app for production
if (Deno.args.includes("--build")) {
return build(handler);
}
// watch file changes in development mode
if (isDev) {
watch(getAppDir(), config.router?.onChange);
}
const { tls } = config;
const onListen = (arg: { port: number; hostname: string }) => {
const origin = `${tls ? "https" : "http"}://${hostname ?? "localhost"}:${arg.port}`;
Reflect.set(globalThis, "__ALEPH_SERVER_ORIGIN", origin);
log.info(`Server ready on ${origin}`);
_onListen?.(arg);
};
const serveOptions = { hostname, port, signal, onListen };
const flagPort = Number(Deno.args.join(" ").match(/--port=(\d+)/)?.[1]);
if (flagPort) {
serveOptions.port = flagPort;
}
if (tls) {
return serveTls(handler, { ...tls, ...serveOptions });
}
return stdServe(handler, serveOptions);
}
/** Set the log level. */
export function setLogLevel(level: LevelName) {
log.setLevel(level);
}
// set log level to debug when debug aleph.js itself.
if (import.meta.url.startsWith("file:")) {
log.setLevel("debug");
}