-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvite.config.js
More file actions
458 lines (418 loc) · 12.9 KB
/
Copy pathvite.config.js
File metadata and controls
458 lines (418 loc) · 12.9 KB
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
// Copyright (C) 2026 Snuffy2
// SPDX-License-Identifier: AGPL-3.0-only
import vue from "@vitejs/plugin-vue";
import { execFileSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { defineConfig } from "vite";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)));
const uiRoot = path.join(repoRoot, "ui");
const distDir = path.join(repoRoot, ".tmp", "dist");
const backendTarget = "http://127.0.0.1:8182";
const publicDir = path.join(uiRoot, "public");
const defaultSourceURL = "https://github.com/Snuffy2/shellport";
const versionFilePath = path.join(repoRoot, ".shellport-version");
/**
* Resolve and validate the source URL embedded into the frontend.
*
* @param {NodeJS.ProcessEnv} env Environment variables.
* @returns {string} HTTPS source URL to expose in the UI.
*/
export function resolveSourceURL(env = process.env) {
const sourceURL = env.SHELLPORT_SOURCE_URL ?? defaultSourceURL;
if (sourceURL.trim() !== sourceURL || sourceURL.length === 0) {
throw new Error("SHELLPORT_SOURCE_URL must be a non-empty URL");
}
let parsedURL;
try {
parsedURL = new URL(sourceURL);
} catch {
throw new Error("SHELLPORT_SOURCE_URL must be a valid URL");
}
if (parsedURL.protocol !== "https:") {
throw new Error("SHELLPORT_SOURCE_URL must use https:");
}
if (parsedURL.username !== "" || parsedURL.password !== "") {
throw new Error("SHELLPORT_SOURCE_URL must not include credentials");
}
return sourceURL;
}
const sourceURL = resolveSourceURL();
/**
* Resolve the version embedded into the frontend.
*
* @param {NodeJS.ProcessEnv} env Environment variables.
* @param {{
* execFileSync?: typeof execFileSync,
* readFileSync?: typeof fs.readFileSync,
* versionFilePath?: string,
* }} options Optional test seams for version sources.
* @returns {string} Existing environment version, Git description, or dev.
*/
export function resolveVersion(env = process.env, options = {}) {
const cleanVersion = (value) => {
const version = value.trim();
return version.length > 0 ? version : null;
};
if (env.SHELLPORT_VERSION) {
const version = cleanVersion(env.SHELLPORT_VERSION);
if (version) {
return version;
}
}
const runGit = options.execFileSync ?? execFileSync;
try {
const version = cleanVersion(
runGit(
"git",
["describe", "--always", "--dirty=*", "--tag"],
{
cwd: repoRoot,
encoding: "utf8",
stdio: ["ignore", "pipe", "ignore"],
},
),
);
if (version) {
return version;
}
} catch {
// Fall through to the source-tree version file used by archive deploys.
}
const readVersionFile = options.readFileSync ?? fs.readFileSync;
try {
const version = cleanVersion(
readVersionFile(options.versionFilePath ?? versionFilePath, "utf8"),
);
if (version) {
return version;
}
} catch {
// Fall through to the development fallback.
}
return "dev";
}
const version = resolveVersion();
const copiedRootFiles = [
"README.md",
"CONFIGURATION.md",
"DEPENDENCIES.md",
"LICENSE.md",
];
const fixedPublicAssets = new Map([
["/shellport/assets/site.webmanifest", "site.webmanifest"],
["/shellport/assets/shellport.svg", "shellport.svg"],
["/shellport/assets/robots.txt", "robots.txt"],
]);
const fixedRootAssets = new Map(
copiedRootFiles.map((fileName) => [`/shellport/assets/${fileName}`, fileName]),
);
const rootCompatibilityAssets = new Map([
["/favicon.ico", "favicon.ico"],
["/manifest.json", "site.webmanifest"],
["/browserconfig.xml", "browserconfig.xml"],
]);
const publicAssetContentTypes = new Map([
["site.webmanifest", "application/manifest+json"],
["browserconfig.xml", "application/xml; charset=utf-8"],
["shellport.svg", "image/svg+xml"],
["favicon.ico", "image/x-icon"],
]);
const rootAssetContentTypes = new Map([
[".md", "text/markdown; charset=utf-8"],
]);
const browserEncodingPackages = [
"/node_modules/buffer/",
"/node_modules/events/",
"/node_modules/iconv-lite/",
"/node_modules/process/",
"/node_modules/string_decoder/",
];
/**
* Assign selected dependencies to stable vendor chunks.
*
* @param {string} id Rollup module identifier.
* @returns {string | undefined} Manual chunk name, when applicable.
*/
function vendorChunkName(id) {
if (!id.includes("/node_modules/")) {
return undefined;
}
if (id.includes("/node_modules/@xterm/")) {
return "vendor-xterm";
}
if (id.includes("/node_modules/vue/")) {
return "vendor-vue";
}
if (browserEncodingPackages.some((packagePath) => id.includes(packagePath))) {
return "vendor-encoding";
}
return "vendor";
}
/**
* Create a Vite plugin that copies root documentation files into the bundle.
*
* @returns {import("vite").Plugin} Vite build plugin.
*/
function copyRootFilesPlugin() {
return {
name: "copy-root-files",
apply: "build",
/**
* Copy root documentation files after Vite writes the build bundle.
*/
closeBundle() {
fs.mkdirSync(distDir, { recursive: true });
for (const fileName of copiedRootFiles) {
fs.copyFileSync(
path.join(repoRoot, fileName),
path.join(distDir, fileName),
);
}
},
};
}
/**
* Resolve a development server fixed asset route to a source file.
*
* @param {string} requestPath Browser request path without query string.
* @returns {{ filePath: string, contentType: string } | null} Route target.
*/
export function resolveDevAssetRoute(requestPath) {
const rootFile = fixedRootAssets.get(requestPath);
if (rootFile) {
const filePath = path.join(repoRoot, rootFile);
const contentType =
rootAssetContentTypes.get(path.extname(rootFile)) ??
"text/plain; charset=utf-8";
return { filePath, contentType };
}
const publicFile =
fixedPublicAssets.get(requestPath) ??
rootCompatibilityAssets.get(requestPath);
if (!publicFile) {
return null;
}
const filePath = path.join(publicDir, publicFile);
const contentType =
publicAssetContentTypes.get(publicFile) ?? "text/plain; charset=utf-8";
return { filePath, contentType };
}
/**
* Rewrite shell module script paths for the development URL namespace.
*
* The source HTML keeps local script paths so Vite can resolve entrypoints
* during production builds. In development, the shell is served from
* `/shellport/assets/`, so those relative paths must point to Vite's source
* module URLs instead of resolving beside the served shell URL.
*
* @param {string} html Transformed development shell HTML.
* @returns {string} HTML with development script paths rewritten.
*/
export function rewriteDevShellScriptPaths(html) {
return html
.replaceAll('src="node-globals.js"', 'src="/node-globals.js"')
.replaceAll('src="app.js"', 'src="/app.js"');
}
/**
* Normalize development shell URLs after Vite transforms HTML placeholders.
*
* @param {string} html Transformed development shell HTML.
* @returns {string} HTML with fixed public asset URLs restored.
*/
function normalizeDevShellAssetPaths(html) {
return html.replaceAll(
"/shellport/assets/shellport/assets/",
"/shellport/assets/",
);
}
/**
* Render the development shell through Vite's HTML transform pipeline.
*
* @param {import("vite").ViteDevServer} server Vite dev server.
* @param {string} requestQuery Request query string without leading question mark.
* @param {string | undefined} sourceHtml Optional source HTML for tests.
* @returns {Promise<string>} Transformed development shell HTML.
*/
export async function renderDevShellHtml(server, requestQuery, sourceHtml) {
const html =
sourceHtml ?? fs.readFileSync(path.join(uiRoot, "index.html"), "utf8");
const transformedHtml = await server.transformIndexHtml(
"/index.html" + (requestQuery.length > 0 ? `?${requestQuery}` : ""),
rewriteDevShellScriptPaths(html),
);
return normalizeDevShellAssetPaths(transformedHtml);
}
/**
* Create a Vite plugin for ShellPort's fixed public asset routes.
*
* @returns {import("vite").Plugin} Vite plugin for build and dev asset paths.
*/
function shellportPublicAssetsPlugin() {
return {
name: "shellport-public-assets",
enforce: "pre",
/**
* Add development middleware for ShellPort shell and fixed public assets.
*
* @param {import("vite").ViteDevServer} server Vite dev server.
*/
configureServer(server) {
/**
* Rewrite shell entry requests to the Vite-served index document.
*
* @param {import("node:http").IncomingMessage} req HTTP request.
* @param {import("node:http").ServerResponse} _res HTTP response.
* @param {() => void} next Next middleware callback.
*/
const rewriteShellRequest = async (req, res, next) => {
const requestUrl = req.url ?? "";
const [requestPath, requestQuery = ""] = requestUrl.split("?", 2);
if (
requestPath === "/" ||
requestPath === "/shellport/assets" ||
requestPath === "/shellport/assets/"
) {
try {
const transformedHtml = await renderDevShellHtml(
server,
requestQuery,
);
res.setHeader("Content-Type", "text/html; charset=utf-8");
res.end(transformedHtml);
} catch (error) {
next(error);
}
return;
}
next();
};
server.middlewares.use(rewriteShellRequest);
server.middlewares.use(
/**
* Serve selected public assets from fixed compatibility routes.
*
* @param {import("node:http").IncomingMessage} req HTTP request.
* @param {import("node:http").ServerResponse} res HTTP response.
* @param {() => void} next Next middleware callback.
*/
(req, res, next) => {
const requestUrl = req.url ?? "";
const [requestPath] = requestUrl.split("?", 1);
const asset = resolveDevAssetRoute(requestPath);
if (!asset) {
next();
return;
}
res.setHeader("Content-Type", asset.contentType);
const stream = fs.createReadStream(asset.filePath);
stream.on(
"error",
/**
* Convert file stream failures into HTTP errors.
*
* @param {NodeJS.ErrnoException} error Stream error.
*/
(error) => {
console.error(
`Failed to stream dev asset ${requestPath} from ${asset.filePath}:`,
error,
);
if (!res.headersSent) {
res.statusCode = error.code === "ENOENT" ? 404 : 500;
}
res.end();
},
);
stream.pipe(res);
},
);
},
};
}
export default defineConfig(
/**
* Build the Vite configuration for the current command and mode.
*
* @param {{ command: string, mode: string }} env Vite config environment.
* @returns {import("vite").UserConfig} Vite configuration.
*/
({ command, mode }) => ({
base: "/shellport/assets/",
root: uiRoot,
plugins: [vue(), copyRootFilesPlugin(), shellportPublicAssetsPlugin()],
publicDir,
resolve: {
alias: [
{
find: /^~(.*)$/,
replacement: "$1",
},
{
find: "vue",
replacement: "vue/dist/vue.esm-bundler.js",
},
{
find: /^buffer$/,
replacement: "buffer",
},
{
find: /^events$/,
replacement: "events",
},
{
find: /^string_decoder$/,
replacement: "string_decoder",
},
{
find: /^process$/,
replacement: "process/browser",
},
],
},
define: {
__VUE_OPTIONS_API__: JSON.stringify(true),
__VUE_PROD_DEVTOOLS__: JSON.stringify(false),
__VUE_PROD_HYDRATION_MISMATCH_DETAILS__: JSON.stringify(false),
__SHELLPORT_SOURCE_URL__: JSON.stringify(sourceURL),
__SHELLPORT_VERSION__: JSON.stringify(version),
"process.env.NODE_ENV": JSON.stringify(mode),
},
build: {
target: ["es2020"],
outDir: distDir,
emptyOutDir: true,
sourcemap: command === "serve",
rollupOptions: {
input: {
index: path.join(uiRoot, "index.html"),
error: path.join(uiRoot, "error.html"),
},
output: {
manualChunks: vendorChunkName,
entryFileNames: "[name]-[hash].js",
chunkFileNames: "chunk-[hash].js",
assetFileNames: "asset-[hash][extname]",
},
},
},
server: {
host: "127.0.0.1",
port: 5173,
strictPort: true,
proxy: {
"/shellport/socket": {
target: backendTarget,
ws: true,
},
},
},
test: {
root: repoRoot,
include: ["ui/**/*_test.js"],
globals: true,
environment: "node",
},
}),
);