Skip to content

Commit f9e6adf

Browse files
committed
fix server sandbox
1 parent d268aeb commit f9e6adf

1 file changed

Lines changed: 18 additions & 10 deletions

File tree

server/src/sandbox.ts

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import cors from 'cors';
33
import express from 'express';
44
import fs from 'node:fs';
55
import path from 'node:path';
6-
import { sandboxVersion } from '../../src/livecodes/html/sandbox/index.ts';
76
import { dirname } from './utils.ts';
87

98
export const sandbox = async ({ hostname, port }: { hostname: string; port: number }) => {
@@ -13,28 +12,37 @@ export const sandbox = async ({ hostname, port }: { hostname: string; port: numb
1312
app.disable('x-powered-by');
1413

1514
const sandboxDir = path.resolve(dirname, 'sandbox');
16-
let sandboxVersionDir = path.resolve(sandboxDir, sandboxVersion);
1715
const dirs = await fs.promises.readdir(sandboxDir);
18-
for (const v of dirs) {
19-
if ((await fs.promises.stat(path.resolve(sandboxDir, v))).isDirectory()) {
20-
sandboxVersionDir = path.resolve(sandboxDir, v);
21-
}
22-
}
16+
const version =
17+
dirs
18+
.filter((v) => v.startsWith('v'))
19+
.map((v) => Number(v.slice(1)))
20+
.filter((v) => !Number.isNaN(v))
21+
.sort((a, b) => b - a)
22+
.map((v) => 'v' + v)
23+
.pop() || '';
24+
const sandboxVersionDir = path.resolve(sandboxDir, version);
2325

2426
app.use('/', (req, res) => {
2527
if (req.path === '/') {
2628
res.set('Content-Type', 'text/html');
2729
res.status(200).sendFile(path.resolve(sandboxVersionDir, 'index.html'));
2830
return;
2931
}
30-
const reqPath = req.path.endsWith('/')
32+
let reqPath = req.path.endsWith('/')
3133
? req.path + 'index.html'
3234
: !req.path.split('/').pop()?.includes('.')
3335
? req.path + '.html'
3436
: req.path;
37+
if (reqPath.startsWith('/')) {
38+
reqPath = reqPath.slice(1);
39+
}
40+
const filePath = path.resolve(sandboxDir, reqPath);
41+
const onError = (_err: unknown) => {
42+
if (res.headersSent) return;
43+
res.status(404).sendFile(path.resolve(sandboxVersionDir, 'index.html'));
44+
};
3545
res.set('Content-Type', 'text/html');
36-
const filePath = path.resolve(dirname, 'sandbox' + reqPath);
37-
const onError = () => res.status(404).sendFile(path.resolve(sandboxVersionDir, 'index.html'));
3846
res.status(200).sendFile(filePath, onError);
3947
});
4048

0 commit comments

Comments
 (0)