-
Notifications
You must be signed in to change notification settings - Fork 531
/
nitro.ts
188 lines (174 loc) · 5.37 KB
/
nitro.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
import { existsSync } from "node:fs";
import { resolve, normalize } from "pathe";
import { createHooks, createDebugger } from "hookable";
import { createUnimport } from "unimport";
import { defu } from "defu";
import { consola } from "consola";
import type { NitroConfig, NitroDynamicConfig, Nitro } from "./types";
import {
LoadConfigOptions,
loadOptions,
normalizeRouteRules,
normalizeRuntimeConfig,
} from "./options";
import { scanModules, scanPlugins, scanTasks } from "./scan";
import { createStorage } from "./storage";
import { resolveNitroModule } from "./module";
export async function createNitro(
config: NitroConfig = {},
opts: LoadConfigOptions = {}
): Promise<Nitro> {
// Resolve options
const options = await loadOptions(config, opts);
// Create context
const nitro: Nitro = {
options,
hooks: createHooks(),
vfs: {},
logger: consola.withTag("nitro"),
scannedHandlers: [],
close: () => nitro.hooks.callHook("close"),
storage: undefined,
async updateConfig(config: NitroDynamicConfig) {
nitro.options.routeRules = normalizeRouteRules(
config.routeRules ? config : nitro.options
);
nitro.options.runtimeConfig = normalizeRuntimeConfig(
config.runtimeConfig ? config : nitro.options
);
await nitro.hooks.callHook("rollup:reload");
consola.success("Nitro config hot reloaded!");
},
};
// Storage
nitro.storage = await createStorage(nitro);
nitro.hooks.hook("close", async () => {
await nitro.storage.dispose();
});
if (nitro.options.debug) {
createDebugger(nitro.hooks, { tag: "nitro" });
nitro.options.plugins.push("#internal/nitro/debug");
}
if (nitro.options.timing) {
nitro.options.plugins.push("#internal/nitro/timing");
}
// Logger config
if (nitro.options.logLevel !== undefined) {
nitro.logger.level = nitro.options.logLevel;
}
// Init hooks
nitro.hooks.addHooks(nitro.options.hooks);
// Public assets
for (const dir of options.scanDirs) {
const publicDir = resolve(dir, "public");
if (!existsSync(publicDir)) {
continue;
}
if (options.publicAssets.some((asset) => asset.dir === publicDir)) {
continue;
}
options.publicAssets.push({ dir: publicDir } as any);
}
for (const asset of options.publicAssets) {
asset.baseURL = asset.baseURL || "/";
const isTopLevel = asset.baseURL === "/";
asset.fallthrough = asset.fallthrough ?? isTopLevel;
const routeRule = options.routeRules[asset.baseURL + "/**"];
asset.maxAge =
(routeRule?.cache as { maxAge: number })?.maxAge ?? asset.maxAge ?? 0;
if (asset.maxAge && !asset.fallthrough) {
options.routeRules[asset.baseURL + "/**"] = defu(routeRule, {
headers: {
"cache-control": `public, max-age=${asset.maxAge}, immutable`,
},
});
}
}
// Server assets
nitro.options.serverAssets.push({
baseName: "server",
dir: resolve(nitro.options.srcDir, "assets"),
});
// Plugins
const scannedPlugins = await scanPlugins(nitro);
for (const plugin of scannedPlugins) {
if (!nitro.options.plugins.includes(plugin)) {
nitro.options.plugins.push(plugin);
}
}
// Tasks
const scannedTasks = await scanTasks(nitro);
for (const scannedTask of scannedTasks) {
if (scannedTask.name in nitro.options.tasks) {
if (!nitro.options.tasks[scannedTask.name].handler) {
nitro.options.tasks[scannedTask.name].handler = scannedTask.handler;
}
} else {
nitro.options.tasks[scannedTask.name] = {
handler: scannedTask.handler,
description: "",
};
}
}
const taskNames = Object.keys(nitro.options.tasks).sort();
if (taskNames.length > 0) {
consola.warn(
`Nitro tasks are experimental and API may change in the future releases!`
);
consola.log(
`Available Tasks:\n\n${taskNames
.map(
(t) =>
` - \`${t}\`${
nitro.options.tasks[t].description
? ` - ${nitro.options.tasks[t].description}`
: ""
}`
)
.join("\n")}`
);
}
nitro.options.virtual["#internal/nitro/virtual/tasks"] = () => `
export const tasks = {
${Object.entries(nitro.options.tasks)
.map(
([name, task]) =>
`"${name}": {
description: ${JSON.stringify(task.description)},
get: ${
task.handler
? `() => import("${normalize(task.handler)}")`
: "undefined"
},
}`
)
.join(",\n")}
};
`;
// Auto imports
if (nitro.options.imports) {
nitro.unimport = createUnimport(nitro.options.imports);
await nitro.unimport.init();
// Support for importing from '#imports'
nitro.options.virtual["#imports"] = () => nitro.unimport.toExports();
// Backward compatibility
nitro.options.virtual["#nitro"] = 'export * from "#imports"';
}
// Resolve and run modules after initial setup
const scannedModules = await scanModules(nitro);
const _modules = [...(nitro.options.modules || []), ...scannedModules];
const modules = await Promise.all(
_modules.map((mod) => resolveNitroModule(mod, nitro.options))
);
const _installedURLs = new Set<string>();
for (const mod of modules) {
if (mod._url) {
if (_installedURLs.has(mod._url)) {
continue;
}
_installedURLs.add(mod._url);
}
await mod.setup(nitro);
}
return nitro;
}