@moostjs/vite 0.7.6 → 0.7.8
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/index.cjs +123 -47
- package/dist/index.d.ts +21 -0
- package/dist/index.mjs +361 -285
- package/dist/prod-server.cjs +168 -62
- package/dist/prod-server.d.ts +34 -4
- package/dist/prod-server.mjs +169 -63
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -8,6 +8,7 @@ import { readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
|
8
8
|
import { availableParallelism } from "node:os";
|
|
9
9
|
import { promisify } from "node:util";
|
|
10
10
|
import { brotliCompress, constants, gzip } from "node:zlib";
|
|
11
|
+
import { validateHeaderName, validateHeaderValue } from "node:http";
|
|
11
12
|
|
|
12
13
|
//#region packages/vite/src/utils.ts
|
|
13
14
|
const PLUGIN_NAME = "moost-vite";
|
|
@@ -40,12 +41,13 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
|
|
|
40
41
|
}
|
|
41
42
|
return render(url, ctx);
|
|
42
43
|
}
|
|
44
|
+
/** A CSP nonce: base64 / base64url characters, optional `=` padding. */ const NONCE_RE = /^[\w+/-]+={0,2}$/;
|
|
43
45
|
/**
|
|
44
46
|
* Applies an SSR render result to the HTTP response: sets the status code and
|
|
45
|
-
* headers, then
|
|
46
|
-
* template. Shared by all three render call sites (the dev middleware,
|
|
47
|
-
* `createSSRServer` branch and the prod `createSSRServer` branch) so the
|
|
48
|
-
* contract stays identical across them.
|
|
47
|
+
* headers, then fills the outlet, state and head markers and the CSP nonce
|
|
48
|
+
* into the template. Shared by all three render call sites (the dev middleware,
|
|
49
|
+
* the dev `createSSRServer` branch and the prod `createSSRServer` branch) so the
|
|
50
|
+
* render contract stays identical across them.
|
|
49
51
|
*
|
|
50
52
|
* Fully backwards compatible: every field beyond `html` is optional, a missing
|
|
51
53
|
* marker in the template is a no-op `String.replace`, and headers from the render
|
|
@@ -54,11 +56,15 @@ const DEFAULT_SSR_HEAD = "<!--ssr-head-->";
|
|
|
54
56
|
* rendered payloads (JSON state, JSON-LD `<head>` tags) are inserted literally
|
|
55
57
|
* rather than interpreted as `String.replace` special patterns.
|
|
56
58
|
*/ function sendSSRResponse(res, template, markers, result) {
|
|
59
|
+
const { nonce } = result;
|
|
60
|
+
if (nonce !== void 0 && (typeof nonce !== "string" || !NONCE_RE.test(nonce))) throw new TypeError("SSR render returned an invalid `nonce`: use base64 or base64url characters only (A-Z, a-z, 0-9, +, /, -, _, with optional trailing =)");
|
|
57
61
|
res.statusCode = result.status ?? 200;
|
|
58
62
|
res.setHeader("Content-Type", "text/html");
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
63
|
+
for (const [key, value] of Object.entries(result.headers ?? {})) res.setHeader(key, value);
|
|
64
|
+
const nonceAttr = nonce ? ` nonce="${nonce}"` : "";
|
|
65
|
+
const stateScript = result.state ? `<script${nonceAttr}>window.__SSR_STATE__=${result.state}<\/script>` : "";
|
|
66
|
+
const page = nonce && markers.cspNonce ? template.split(`nonce="${markers.cspNonce}"`).join(`nonce="${nonce}"`) : template;
|
|
67
|
+
res.end(page.replace(markers.ssrOutlet, () => result.html).replace(markers.ssrState, () => stateScript).replace(markers.ssrHead, () => result.head ?? ""));
|
|
62
68
|
}
|
|
63
69
|
function entryBasename(entry) {
|
|
64
70
|
return entry.split("/").pop().replace(/\.ts$/, ".js");
|
|
@@ -827,6 +833,59 @@ const DEFAULT_PRECOMPRESS_INCLUDE = /\.(?:m?js|cjs|css|html?|svg|json|webmanifes
|
|
|
827
833
|
}
|
|
828
834
|
}
|
|
829
835
|
|
|
836
|
+
//#endregion
|
|
837
|
+
//#region packages/vite/src/dev-ssr.ts
|
|
838
|
+
/**
|
|
839
|
+
* The dev server's SSR page fallback (registered after Vite's own middlewares): renders GET
|
|
840
|
+
* requests nobody answered with the SSR entry, through Vite's `transformIndexHtml`.
|
|
841
|
+
*/ function devSSRFallback(server, options) {
|
|
842
|
+
return async (req, res, next) => {
|
|
843
|
+
if (req.method !== "GET") {
|
|
844
|
+
next();
|
|
845
|
+
return;
|
|
846
|
+
}
|
|
847
|
+
const url = req.originalUrl || req.url || "/";
|
|
848
|
+
try {
|
|
849
|
+
if (await options.gate?.(res)) return;
|
|
850
|
+
const source = await readFile(resolve(server.config.root, "index.html"), "utf8");
|
|
851
|
+
const template = await server.transformIndexHtml(url, source);
|
|
852
|
+
const { render } = await server.ssrLoadModule(options.ssrEntry);
|
|
853
|
+
const result = await renderSSRPage({
|
|
854
|
+
render,
|
|
855
|
+
url,
|
|
856
|
+
req,
|
|
857
|
+
res,
|
|
858
|
+
http: options.http()
|
|
859
|
+
});
|
|
860
|
+
const cspNonce = server.config.html?.cspNonce;
|
|
861
|
+
sendSSRResponse(res, template, {
|
|
862
|
+
...options.markers,
|
|
863
|
+
cspNonce
|
|
864
|
+
}, result);
|
|
865
|
+
} catch (error) {
|
|
866
|
+
if (error instanceof Error) server.ssrFixStacktrace(error);
|
|
867
|
+
console.error(error);
|
|
868
|
+
res.statusCode = 500;
|
|
869
|
+
res.end(error?.message);
|
|
870
|
+
}
|
|
871
|
+
};
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
//#endregion
|
|
875
|
+
//#region packages/vite/src/server-middleware.ts
|
|
876
|
+
/** Name of the dev-server plugin `createSSRServer()` adds for its headers, middlewares and SSR. */ const SERVER_PLUGIN_NAME = `${PLUGIN_NAME}:server`;
|
|
877
|
+
/** Throws, naming the header, when a name or value could not be sent. */ function validateHeaders(headers, from) {
|
|
878
|
+
for (const [name, value] of Object.entries(headers ?? {})) try {
|
|
879
|
+
validateHeaderName(name);
|
|
880
|
+
validateHeaderValue(name, value);
|
|
881
|
+
} catch (error) {
|
|
882
|
+
throw new TypeError(`[${PLUGIN_NAME}] ${from}: invalid header ${JSON.stringify(name)} — ${error.message}`, { cause: error });
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
/** Sets each of `headers` on the response (later `setHeader` calls still replace them). */ function setResponseHeaders(res, headers) {
|
|
886
|
+
for (const [name, value] of Object.entries(headers ?? {})) res.setHeader(name, value);
|
|
887
|
+
}
|
|
888
|
+
|
|
830
889
|
//#endregion
|
|
831
890
|
//#region packages/vite/src/moost-vite.ts
|
|
832
891
|
/**
|
|
@@ -881,6 +940,8 @@ function generatedServerEntry(root) {
|
|
|
881
940
|
}
|
|
882
941
|
function moostVite(options) {
|
|
883
942
|
const externals = options.externals ?? true;
|
|
943
|
+
validateHeaders(options.headers, "moostVite({ headers })");
|
|
944
|
+
/** The `headers` option: middleware mode only (backend mode: see the warning in configResolved). */ const headers = options.middleware ? options.headers : void 0;
|
|
884
945
|
const prefixes = normalizePrefixes(options.prefix);
|
|
885
946
|
let moostMiddleware = null;
|
|
886
947
|
let localFetchTeardown = null;
|
|
@@ -1041,310 +1102,325 @@ function moostVite(options) {
|
|
|
1041
1102
|
res.setHeader("Content-Type", "text/plain");
|
|
1042
1103
|
res.end(`Moost app failed to load: ${bootError.message}`);
|
|
1043
1104
|
};
|
|
1105
|
+
/**
|
|
1106
|
+
* Runs before each dev SSR render (whichever fallback renders: this plugin's or the
|
|
1107
|
+
* `createSSRServer()` one): the reload lock — an HMR mid-render would otherwise race
|
|
1108
|
+
* ssrLoadModule against a half-ejected app — and the boot-error gate, since the local-fetch
|
|
1109
|
+
* hook listen() installed would dispatch SSR self-fetches into a half-bound app.
|
|
1110
|
+
*/ const ssrGate = async (res) => {
|
|
1111
|
+
await drainReload();
|
|
1112
|
+
if (bootError) {
|
|
1113
|
+
answerBootError(res);
|
|
1114
|
+
return true;
|
|
1115
|
+
}
|
|
1116
|
+
return false;
|
|
1117
|
+
};
|
|
1044
1118
|
/** Set by the middleware-mode `config` hook: the consumer externalized the runtime themselves. */ let runtimeExternalized = false;
|
|
1045
1119
|
let resolvedConfig;
|
|
1046
|
-
return [
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1120
|
+
return [
|
|
1121
|
+
{
|
|
1122
|
+
name: PLUGIN_NAME,
|
|
1123
|
+
enforce: "pre",
|
|
1124
|
+
config(cfg, env) {
|
|
1125
|
+
if (options.middleware) {
|
|
1126
|
+
const entryKeyBase = entryBasename(options.entry).replace(/\.js$/, "");
|
|
1127
|
+
const entryKey = entryKeyBase === "server" ? "moost-entry" : entryKeyBase;
|
|
1128
|
+
const serverDefines = {
|
|
1129
|
+
"process.env.MOOST_DEFERRED_ENV": "\"production\"",
|
|
1130
|
+
__MOOST_ENTRY__: JSON.stringify(`./${entryKey}.js`),
|
|
1131
|
+
__MOOST_PREFIX__: JSON.stringify(prefixes ?? null),
|
|
1132
|
+
__MOOST_PREFIX_FALLTHROUGH__: JSON.stringify(options.prefixFallthrough === true),
|
|
1133
|
+
__MOOST_SSR_FORWARDING__: JSON.stringify(ssrForwarding),
|
|
1134
|
+
__MOOST_SSR_ENTRY__: "undefined",
|
|
1135
|
+
__MOOST_SSR_OUTLET__: JSON.stringify(ssrOutlet),
|
|
1136
|
+
__MOOST_SSR_STATE__: JSON.stringify(ssrState),
|
|
1137
|
+
__MOOST_SSR_HEAD__: JSON.stringify(ssrHead),
|
|
1138
|
+
__MOOST_PRECOMPRESS__: JSON.stringify(precompressedVariants),
|
|
1139
|
+
__MOOST_CACHE_CONTROL__: JSON.stringify(bakedCacheControl(cfg)),
|
|
1140
|
+
__MOOST_HEADERS__: JSON.stringify(options.headers ?? null),
|
|
1141
|
+
__MOOST_CSP_NONCE__: JSON.stringify(cfg.html?.cspNonce ?? null)
|
|
1142
|
+
};
|
|
1143
|
+
const ssrInput = {
|
|
1144
|
+
server: options.serverEntry || generatedServerEntry(cfg.root),
|
|
1145
|
+
[entryKey]: options.entry
|
|
1146
|
+
};
|
|
1147
|
+
if (options.ssrEntry) {
|
|
1148
|
+
const ssrBasename = entryBasename(options.ssrEntry);
|
|
1149
|
+
ssrInput[`ssr/${ssrBasename.replace(/\.js$/, "")}`] = options.ssrEntry;
|
|
1150
|
+
serverDefines.__MOOST_SSR_ENTRY__ = JSON.stringify(`./ssr/${ssrBasename}`);
|
|
1151
|
+
}
|
|
1152
|
+
const outDir = cfg.build?.outDir || "dist";
|
|
1153
|
+
const isBuild = env.command === "build";
|
|
1154
|
+
const userNoExternal = cfg.ssr?.noExternal;
|
|
1155
|
+
let ssrNoExternal = userNoExternal === true ? true : userNoExternal !== void 0 ? [...Array.isArray(userNoExternal) ? userNoExternal : [userNoExternal], PLUGIN_NO_EXTERNAL] : isBuild ? true : [PLUGIN_NO_EXTERNAL];
|
|
1156
|
+
const userExternal = cfg.ssr?.external;
|
|
1157
|
+
const ssrExternal = isBuild ? [...Array.isArray(userExternal) ? userExternal : [], ...options.ssrExternal ?? []] : void 0;
|
|
1158
|
+
runtimeExternalized = (ssrExternal ?? []).some((e) => typeof e === "string" && RUNTIME_PACKAGE_PATTERNS.some((re) => re.test(e)));
|
|
1159
|
+
if (isBuild && Array.isArray(ssrNoExternal) && !runtimeExternalized) ssrNoExternal = [...ssrNoExternal, ...RUNTIME_PACKAGE_PATTERNS];
|
|
1160
|
+
return {
|
|
1161
|
+
...options.ssrEntry && { appType: "custom" },
|
|
1162
|
+
ssr: {
|
|
1163
|
+
noExternal: ssrNoExternal,
|
|
1164
|
+
...ssrExternal && ssrExternal.length > 0 ? { external: ssrExternal } : {}
|
|
1165
|
+
},
|
|
1166
|
+
builder: { async buildApp(builder) {
|
|
1167
|
+
rmSync(resolve(cfg.root || process.cwd(), outDir), {
|
|
1168
|
+
recursive: true,
|
|
1169
|
+
force: true
|
|
1170
|
+
});
|
|
1171
|
+
for (const env of Object.values(builder.environments)) await builder.build(env);
|
|
1172
|
+
} },
|
|
1173
|
+
environments: {
|
|
1174
|
+
client: { build: {
|
|
1175
|
+
outDir: `${outDir}/client`,
|
|
1176
|
+
emptyOutDir: false,
|
|
1177
|
+
...options.ssrEntry && { ssrManifest: true }
|
|
1178
|
+
} },
|
|
1179
|
+
ssr: {
|
|
1180
|
+
build: {
|
|
1181
|
+
outDir: `${outDir}/server`,
|
|
1182
|
+
emptyOutDir: false,
|
|
1183
|
+
minify: false,
|
|
1184
|
+
sourcemap: !!(options.sourcemap ?? true),
|
|
1185
|
+
rollupOptions: {
|
|
1186
|
+
input: ssrInput,
|
|
1187
|
+
output: { format: "esm" }
|
|
1188
|
+
}
|
|
1189
|
+
},
|
|
1190
|
+
define: serverDefines
|
|
1191
|
+
}
|
|
1192
|
+
}
|
|
1193
|
+
};
|
|
1074
1194
|
}
|
|
1075
|
-
const
|
|
1076
|
-
const
|
|
1077
|
-
const userNoExternal = cfg.ssr?.noExternal;
|
|
1078
|
-
let ssrNoExternal = userNoExternal === true ? true : userNoExternal !== void 0 ? [...Array.isArray(userNoExternal) ? userNoExternal : [userNoExternal], PLUGIN_NO_EXTERNAL] : isBuild ? true : [PLUGIN_NO_EXTERNAL];
|
|
1079
|
-
const userExternal = cfg.ssr?.external;
|
|
1080
|
-
const ssrExternal = isBuild ? [...Array.isArray(userExternal) ? userExternal : [], ...options.ssrExternal ?? []] : void 0;
|
|
1081
|
-
runtimeExternalized = (ssrExternal ?? []).some((e) => typeof e === "string" && RUNTIME_PACKAGE_PATTERNS.some((re) => re.test(e)));
|
|
1082
|
-
if (isBuild && Array.isArray(ssrNoExternal) && !runtimeExternalized) ssrNoExternal = [...ssrNoExternal, ...RUNTIME_PACKAGE_PATTERNS];
|
|
1195
|
+
const entry = cfg.build?.rollupOptions?.input || options.entry;
|
|
1196
|
+
const outfile = typeof entry === "string" ? entryBasename(entry) : void 0;
|
|
1083
1197
|
return {
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
...ssrExternal && ssrExternal.length > 0 ? { external: ssrExternal } : {}
|
|
1198
|
+
server: {
|
|
1199
|
+
port: cfg.server?.port || options.port || 3e3,
|
|
1200
|
+
host: cfg.server?.host || options.host
|
|
1088
1201
|
},
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
sourcemap: !!(options.sourcemap ?? true),
|
|
1108
|
-
rollupOptions: {
|
|
1109
|
-
input: ssrInput,
|
|
1110
|
-
output: { format: "esm" }
|
|
1111
|
-
}
|
|
1112
|
-
},
|
|
1113
|
-
define: serverDefines
|
|
1202
|
+
optimizeDeps: { noDiscovery: cfg.optimizeDeps?.noDiscovery === void 0 ? true : cfg.optimizeDeps.noDiscovery },
|
|
1203
|
+
build: {
|
|
1204
|
+
target: cfg.build?.target || "node",
|
|
1205
|
+
outDir: cfg.build?.outDir || options.outDir || "dist",
|
|
1206
|
+
ssr: cfg.build?.ssr ?? true,
|
|
1207
|
+
minify: cfg.build?.minify || false,
|
|
1208
|
+
sourcemap: !!(options.sourcemap ?? true),
|
|
1209
|
+
rollupOptions: {
|
|
1210
|
+
external: cfg.build?.rollupOptions?.external || (externals === false ? [] : getExternals({
|
|
1211
|
+
node: Boolean(externals === true || externals?.node),
|
|
1212
|
+
workspace: Boolean(externals === true || externals?.workspace)
|
|
1213
|
+
})),
|
|
1214
|
+
input: entry,
|
|
1215
|
+
output: {
|
|
1216
|
+
format: options.format,
|
|
1217
|
+
entryFileNames: outfile,
|
|
1218
|
+
...cfg.build?.rollupOptions?.output
|
|
1219
|
+
}
|
|
1114
1220
|
}
|
|
1115
1221
|
}
|
|
1116
1222
|
};
|
|
1117
|
-
}
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
minify: cfg.build?.minify || false,
|
|
1131
|
-
sourcemap: !!(options.sourcemap ?? true),
|
|
1132
|
-
rollupOptions: {
|
|
1133
|
-
external: cfg.build?.rollupOptions?.external || (externals === false ? [] : getExternals({
|
|
1134
|
-
node: Boolean(externals === true || externals?.node),
|
|
1135
|
-
workspace: Boolean(externals === true || externals?.workspace)
|
|
1136
|
-
})),
|
|
1137
|
-
input: entry,
|
|
1138
|
-
output: {
|
|
1139
|
-
format: options.format,
|
|
1140
|
-
entryFileNames: outfile,
|
|
1141
|
-
...cfg.build?.rollupOptions?.output
|
|
1142
|
-
}
|
|
1143
|
-
}
|
|
1223
|
+
},
|
|
1224
|
+
buildApp: {
|
|
1225
|
+
order: "post",
|
|
1226
|
+
async handler(builder) {
|
|
1227
|
+
const client = builder.environments.client;
|
|
1228
|
+
if (!options.middleware || precompress === false || !client?.isBuilt) return;
|
|
1229
|
+
const { root, build } = client.config;
|
|
1230
|
+
if (build.write === false) return;
|
|
1231
|
+
const result = await precompressDir(resolve(root, build.outDir), {
|
|
1232
|
+
...precompress === true ? {} : precompress,
|
|
1233
|
+
exclude: options.ssrEntry ? (rel) => rel === "index.html" : void 0
|
|
1234
|
+
});
|
|
1235
|
+
if (result.files > 0) client.logger.info(`[${PLUGIN_NAME}] precompressed ${result.files} client files (${result.brotli} .br, ${result.gzip} .gz)`);
|
|
1144
1236
|
}
|
|
1145
|
-
}
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1237
|
+
},
|
|
1238
|
+
configResolved(config) {
|
|
1239
|
+
config.__moostViteOptions = {
|
|
1240
|
+
entry: options.entry,
|
|
1241
|
+
ssrEntry: options.ssrEntry,
|
|
1242
|
+
serverEntry: options.serverEntry,
|
|
1243
|
+
prefix: prefixes,
|
|
1244
|
+
prefixFallthrough: options.prefixFallthrough,
|
|
1245
|
+
ssrOutlet: options.ssrOutlet,
|
|
1246
|
+
ssrState: options.ssrState,
|
|
1247
|
+
ssrHead: options.ssrHead,
|
|
1248
|
+
ssrFetchForwarding: options.ssrFetchForwarding,
|
|
1249
|
+
headers
|
|
1250
|
+
};
|
|
1251
|
+
config.__moostViteHttpRef = moostHttpRef;
|
|
1252
|
+
config.__moostViteSsrGate = ssrGate;
|
|
1253
|
+
resolvedConfig = config;
|
|
1254
|
+
if (options.headers && !options.middleware) config.logger.warn(`[${PLUGIN_NAME}] The \`headers\` option applies in middleware mode only and is ignored: in backend mode Moost answers every request itself, in dev and in production — set the headers with \`new MoostHttp({ defaultHeaders })\` instead.`);
|
|
1255
|
+
},
|
|
1256
|
+
generateBundle(_outputOptions, bundle) {
|
|
1257
|
+
const cfg = resolvedConfig;
|
|
1258
|
+
if (!cfg || cfg.command !== "build" || !options.middleware || options.ssrExternalCheck === false || this.environment?.name !== "ssr") return;
|
|
1259
|
+
const { externalIds, bundledPackages } = scanSsrBundle(bundle);
|
|
1260
|
+
const splits = findSplitPackages({
|
|
1261
|
+
root: cfg.root,
|
|
1262
|
+
externalIds,
|
|
1263
|
+
bundledPackages,
|
|
1264
|
+
patterns: splitCheckPatterns
|
|
1157
1265
|
});
|
|
1158
|
-
if (
|
|
1159
|
-
}
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
externalIds,
|
|
1183
|
-
bundledPackages,
|
|
1184
|
-
patterns: splitCheckPatterns
|
|
1185
|
-
});
|
|
1186
|
-
if (splits.length > 0) cfg.logger.warn(`\n[${PLUGIN_NAME}] ${formatSplitPackagesWarning(splits)}\n`);
|
|
1187
|
-
},
|
|
1188
|
-
async transform(code, id) {
|
|
1189
|
-
if (!id.endsWith(".ts")) return null;
|
|
1190
|
-
for (const adapter of adapters) if (!adapter.detected && adapter.regex.test(code)) await adapter.init();
|
|
1191
|
-
if (code.search(REG_DI_CLASS) !== -1) {
|
|
1192
|
-
const s = new MagicString(code);
|
|
1193
|
-
s.replace(REG_DI_CLASS, "\n@__VITE_ID(import.meta.filename)\n$1");
|
|
1194
|
-
s.prepend(`import { __VITE_ID } from 'virtual:vite-id'\n\n`);
|
|
1195
|
-
return {
|
|
1196
|
-
code: s.toString(),
|
|
1197
|
-
map: s.generateMap({ hires: true })
|
|
1266
|
+
if (splits.length > 0) cfg.logger.warn(`\n[${PLUGIN_NAME}] ${formatSplitPackagesWarning(splits)}\n`);
|
|
1267
|
+
},
|
|
1268
|
+
async transform(code, id) {
|
|
1269
|
+
if (!id.endsWith(".ts")) return null;
|
|
1270
|
+
for (const adapter of adapters) if (!adapter.detected && adapter.regex.test(code)) await adapter.init();
|
|
1271
|
+
if (code.search(REG_DI_CLASS) !== -1) {
|
|
1272
|
+
const s = new MagicString(code);
|
|
1273
|
+
s.replace(REG_DI_CLASS, "\n@__VITE_ID(import.meta.filename)\n$1");
|
|
1274
|
+
s.prepend(`import { __VITE_ID } from 'virtual:vite-id'\n\n`);
|
|
1275
|
+
return {
|
|
1276
|
+
code: s.toString(),
|
|
1277
|
+
map: s.generateMap({ hires: true })
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
return null;
|
|
1281
|
+
},
|
|
1282
|
+
resolveId(id) {
|
|
1283
|
+
if (id === "virtual:vite-id" || id.startsWith(ADAPTER_VIRTUAL_PREFIX)) return `\0${id}`;
|
|
1284
|
+
},
|
|
1285
|
+
load(id) {
|
|
1286
|
+
const adapterModule = loadAdapterVirtualModule(id);
|
|
1287
|
+
if (adapterModule !== void 0) return {
|
|
1288
|
+
code: adapterModule,
|
|
1289
|
+
map: null
|
|
1198
1290
|
};
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
},
|
|
1202
|
-
resolveId(id) {
|
|
1203
|
-
if (id === "virtual:vite-id" || id.startsWith(ADAPTER_VIRTUAL_PREFIX)) return `\0${id}`;
|
|
1204
|
-
},
|
|
1205
|
-
load(id) {
|
|
1206
|
-
const adapterModule = loadAdapterVirtualModule(id);
|
|
1207
|
-
if (adapterModule !== void 0) return {
|
|
1208
|
-
code: adapterModule,
|
|
1209
|
-
map: null
|
|
1210
|
-
};
|
|
1211
|
-
if (id === "\0virtual:vite-id") return {
|
|
1212
|
-
code: `
|
|
1291
|
+
if (id === "\0virtual:vite-id") return {
|
|
1292
|
+
code: `
|
|
1213
1293
|
import { getMoostMate } from "moost";
|
|
1214
1294
|
const mate = getMoostMate();
|
|
1215
1295
|
export function __VITE_ID(id) {
|
|
1216
1296
|
return mate.decorate(${JSON.stringify(VITE_ID_KEY)}, id)
|
|
1217
1297
|
}
|
|
1218
1298
|
`,
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
reloadRequired = false;
|
|
1227
|
-
reloadPromise = null;
|
|
1228
|
-
pendingCleanup = null;
|
|
1229
|
-
beginBoot();
|
|
1230
|
-
const runReload = () => {
|
|
1299
|
+
map: null
|
|
1300
|
+
};
|
|
1301
|
+
},
|
|
1302
|
+
async configureServer(server) {
|
|
1303
|
+
const runner = createServerModuleRunner(server.environments.ssr, { hmr: false });
|
|
1304
|
+
const ssrImport = (id) => runner.import(id);
|
|
1305
|
+
bootError = null;
|
|
1231
1306
|
reloadRequired = false;
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1307
|
+
reloadPromise = null;
|
|
1308
|
+
pendingCleanup = null;
|
|
1309
|
+
beginBoot();
|
|
1310
|
+
const runReload = () => {
|
|
1311
|
+
reloadRequired = false;
|
|
1312
|
+
console.log();
|
|
1313
|
+
logger.debug("🚀 Reloading Moost App...");
|
|
1314
|
+
console.log();
|
|
1315
|
+
return (async () => {
|
|
1316
|
+
try {
|
|
1317
|
+
beginBoot();
|
|
1318
|
+
const cleanup = pendingCleanup ?? EJECT_ALL;
|
|
1319
|
+
pendingCleanup = null;
|
|
1320
|
+
await prepareBoot(cleanup);
|
|
1321
|
+
const entryModule = await getEntryModule(server.environments.ssr.moduleGraph);
|
|
1322
|
+
if (entryModule?.transformResult) server.environments.ssr.moduleGraph.invalidateModule(entryModule);
|
|
1323
|
+
await ssrImport(options.entry);
|
|
1324
|
+
if (await settleBootInit() && httpCaptured && !moostMiddleware) logger.error(`⚠️ Moost app reloaded but no HTTP middleware was captured — the entry did not re-run listen().`);
|
|
1325
|
+
} catch (error) {
|
|
1326
|
+
bootError = error;
|
|
1327
|
+
logger.error(`✖️ Failed to reload Moost App: ${error.message}`);
|
|
1328
|
+
}
|
|
1329
|
+
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
1330
|
+
})().finally(() => {
|
|
1331
|
+
reloadPromise = null;
|
|
1332
|
+
});
|
|
1333
|
+
};
|
|
1334
|
+
drainReload = async () => {
|
|
1335
|
+
while (reloadRequired || reloadPromise) {
|
|
1336
|
+
if (!reloadPromise) reloadPromise = runReload();
|
|
1337
|
+
await reloadPromise;
|
|
1248
1338
|
}
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
if (
|
|
1257
|
-
await reloadPromise;
|
|
1258
|
-
}
|
|
1259
|
-
};
|
|
1260
|
-
if (options.ssrExternalCheck !== false) {
|
|
1261
|
-
const splits = findDevSplitPackages({
|
|
1262
|
-
root: server.config.root,
|
|
1263
|
-
config: server.environments.ssr.config.resolve,
|
|
1264
|
-
patterns: splitCheckPatterns
|
|
1265
|
-
});
|
|
1266
|
-
if (splits.length > 0) server.config.logger.warn(`\n[${PLUGIN_NAME}] ${formatDevSplitPackagesWarning(splits)}\n`);
|
|
1267
|
-
}
|
|
1268
|
-
for (const adapter of adapters) adapter.ssrLoadModule = ssrImport;
|
|
1269
|
-
await prepareBoot(EJECT_ALL);
|
|
1270
|
-
await ssrImport(options.entry);
|
|
1271
|
-
await settleBootInit();
|
|
1272
|
-
server.middlewares.use(async (req, res, next) => {
|
|
1273
|
-
await drainReload();
|
|
1274
|
-
if (options.middleware && prefixes && !matchesPrefix(req.url || "", prefixes)) return next();
|
|
1275
|
-
if (bootError) {
|
|
1276
|
-
answerBootError(res);
|
|
1277
|
-
return;
|
|
1339
|
+
};
|
|
1340
|
+
if (options.ssrExternalCheck !== false) {
|
|
1341
|
+
const splits = findDevSplitPackages({
|
|
1342
|
+
root: server.config.root,
|
|
1343
|
+
config: server.environments.ssr.config.resolve,
|
|
1344
|
+
patterns: splitCheckPatterns
|
|
1345
|
+
});
|
|
1346
|
+
if (splits.length > 0) server.config.logger.warn(`\n[${PLUGIN_NAME}] ${formatDevSplitPackagesWarning(splits)}\n`);
|
|
1278
1347
|
}
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1348
|
+
for (const adapter of adapters) adapter.ssrLoadModule = ssrImport;
|
|
1349
|
+
await prepareBoot(EJECT_ALL);
|
|
1350
|
+
await ssrImport(options.entry);
|
|
1351
|
+
await settleBootInit();
|
|
1352
|
+
server.middlewares.use(async (req, res, next) => {
|
|
1353
|
+
await drainReload();
|
|
1354
|
+
if (options.middleware && prefixes && !matchesPrefix(req.url || "", prefixes)) return next();
|
|
1355
|
+
if (bootError) {
|
|
1356
|
+
answerBootError(res);
|
|
1283
1357
|
return;
|
|
1284
1358
|
}
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
},
|
|
1290
|
-
async hotUpdate({ file, modules }) {
|
|
1291
|
-
if (this.environment.name !== "ssr" || modules.length === 0) return;
|
|
1292
|
-
const { moduleGraph } = this.environment;
|
|
1293
|
-
const entryModule = await getEntryModule(moduleGraph);
|
|
1294
|
-
const importerSets = modules.map((mod) => gatherAllImporters(mod));
|
|
1295
|
-
if (entryModule && !importerSets.some((importers) => importers.has(entryModule))) return;
|
|
1296
|
-
logger.debug(`🔃 Hot update: ${file}`);
|
|
1297
|
-
const cleanupInstances = /* @__PURE__ */ new Set();
|
|
1298
|
-
for (const importers of importerSets) for (const impModule of importers) if (impModule.id) cleanupInstances.add(impModule.id);
|
|
1299
|
-
for (const mod of modules) moduleGraph.invalidateModule(mod);
|
|
1300
|
-
if (entryModule) {
|
|
1301
|
-
moduleGraph.invalidateModule(entryModule);
|
|
1302
|
-
ejectApp(cleanupInstances);
|
|
1303
|
-
} else {
|
|
1304
|
-
moduleGraph.invalidateAll();
|
|
1305
|
-
ejectApp(EJECT_ALL);
|
|
1306
|
-
}
|
|
1307
|
-
return [];
|
|
1308
|
-
}
|
|
1309
|
-
}, options.middleware && options.ssrEntry ? {
|
|
1310
|
-
name: `${PLUGIN_NAME}:ssr-fallback`,
|
|
1311
|
-
async configureServer(server) {
|
|
1312
|
-
const fs = await import("node:fs/promises");
|
|
1313
|
-
return () => {
|
|
1314
|
-
server.middlewares.use(async (req, res, next) => {
|
|
1315
|
-
if (req.method !== "GET") return next();
|
|
1316
|
-
const url = req.originalUrl || req.url || "/";
|
|
1317
|
-
try {
|
|
1318
|
-
await drainReload();
|
|
1319
|
-
if (bootError) {
|
|
1320
|
-
answerBootError(res);
|
|
1359
|
+
if (moostMiddleware) {
|
|
1360
|
+
if (options.middleware) {
|
|
1361
|
+
pendingNextMap.set(req, next);
|
|
1362
|
+
moostMiddleware(req, res);
|
|
1321
1363
|
return;
|
|
1322
1364
|
}
|
|
1323
|
-
|
|
1324
|
-
template = await server.transformIndexHtml(url, template);
|
|
1325
|
-
const { render } = await server.ssrLoadModule(options.ssrEntry);
|
|
1326
|
-
const result = await renderSSRPage({
|
|
1327
|
-
render,
|
|
1328
|
-
url,
|
|
1329
|
-
req,
|
|
1330
|
-
res,
|
|
1331
|
-
http: ssrForwarding ? moostHttpRef.current : null
|
|
1332
|
-
});
|
|
1333
|
-
sendSSRResponse(res, template, {
|
|
1334
|
-
ssrOutlet,
|
|
1335
|
-
ssrState,
|
|
1336
|
-
ssrHead
|
|
1337
|
-
}, result);
|
|
1338
|
-
} catch (error) {
|
|
1339
|
-
server.ssrFixStacktrace(error);
|
|
1340
|
-
console.error(error);
|
|
1341
|
-
res.statusCode = 500;
|
|
1342
|
-
res.end(error.message);
|
|
1365
|
+
return moostMiddleware(req, res);
|
|
1343
1366
|
}
|
|
1367
|
+
next();
|
|
1344
1368
|
});
|
|
1345
|
-
}
|
|
1346
|
-
|
|
1347
|
-
|
|
1369
|
+
},
|
|
1370
|
+
async hotUpdate({ file, modules }) {
|
|
1371
|
+
if (this.environment.name !== "ssr" || modules.length === 0) return;
|
|
1372
|
+
const { moduleGraph } = this.environment;
|
|
1373
|
+
const entryModule = await getEntryModule(moduleGraph);
|
|
1374
|
+
const importerSets = modules.map((mod) => gatherAllImporters(mod));
|
|
1375
|
+
if (entryModule && !importerSets.some((importers) => importers.has(entryModule))) return;
|
|
1376
|
+
logger.debug(`🔃 Hot update: ${file}`);
|
|
1377
|
+
const cleanupInstances = /* @__PURE__ */ new Set();
|
|
1378
|
+
for (const importers of importerSets) for (const impModule of importers) if (impModule.id) cleanupInstances.add(impModule.id);
|
|
1379
|
+
for (const mod of modules) moduleGraph.invalidateModule(mod);
|
|
1380
|
+
if (entryModule) {
|
|
1381
|
+
moduleGraph.invalidateModule(entryModule);
|
|
1382
|
+
ejectApp(cleanupInstances);
|
|
1383
|
+
} else {
|
|
1384
|
+
moduleGraph.invalidateAll();
|
|
1385
|
+
ejectApp(EJECT_ALL);
|
|
1386
|
+
}
|
|
1387
|
+
return [];
|
|
1388
|
+
}
|
|
1389
|
+
},
|
|
1390
|
+
options.middleware && options.ssrEntry ? {
|
|
1391
|
+
name: `${PLUGIN_NAME}:ssr-fallback`,
|
|
1392
|
+
configureServer(server) {
|
|
1393
|
+
if (server.config.plugins.some((p) => p.name === SERVER_PLUGIN_NAME)) return;
|
|
1394
|
+
const fallback = devSSRFallback(server, {
|
|
1395
|
+
ssrEntry: options.ssrEntry,
|
|
1396
|
+
markers: {
|
|
1397
|
+
ssrOutlet,
|
|
1398
|
+
ssrState,
|
|
1399
|
+
ssrHead
|
|
1400
|
+
},
|
|
1401
|
+
http: () => ssrForwarding ? moostHttpRef.current : null,
|
|
1402
|
+
gate: ssrGate
|
|
1403
|
+
});
|
|
1404
|
+
return () => {
|
|
1405
|
+
server.middlewares.use(fallback);
|
|
1406
|
+
};
|
|
1407
|
+
}
|
|
1408
|
+
} : null,
|
|
1409
|
+
headers ? {
|
|
1410
|
+
name: `${PLUGIN_NAME}:headers`,
|
|
1411
|
+
enforce: "pre",
|
|
1412
|
+
configureServer: {
|
|
1413
|
+
order: "pre",
|
|
1414
|
+
handler(server) {
|
|
1415
|
+
if (server.config.plugins.some((p) => p.name === SERVER_PLUGIN_NAME)) return;
|
|
1416
|
+
server.middlewares.use((_req, res, next) => {
|
|
1417
|
+
setResponseHeaders(res, headers);
|
|
1418
|
+
next();
|
|
1419
|
+
});
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
} : null
|
|
1423
|
+
];
|
|
1348
1424
|
}
|
|
1349
1425
|
|
|
1350
1426
|
//#endregion
|