-
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
91 lines (71 loc) · 2.25 KB
/
index.ts
File metadata and controls
91 lines (71 loc) · 2.25 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
import path from 'path';
import { connectDatabase } from '@admin/db/connect';
import { createDatabaseModels } from '@admin/db/models';
import { parseEnvironment } from '@admin/env';
import { routeApiRequest } from '@admin/http/router';
import { type ServiceContext } from '@admin/services/context';
import { createS3StorageClient } from '@admin/storage/s3-client';
const env = parseEnvironment(process.env);
await connectDatabase(env.MONGO_URL);
const models = createDatabaseModels();
const storage = createS3StorageClient(env);
await storage.verifyBuckets();
const context: ServiceContext = {
env,
models,
storage,
startedAt: Date.now(),
};
async function resolvePublicRoot() {
const candidates = [
path.resolve(import.meta.dir, '../public'),
path.resolve(import.meta.dir, '../dist/public'),
];
for (const candidate of candidates) {
if (await Bun.file(path.join(candidate, 'index.html')).exists()) {
return candidate;
}
}
return candidates[0];
}
const publicRoot = await resolvePublicRoot();
function safeResolvePublicPath(urlPath: string) {
const normalized = path.normalize(urlPath).replace(/^(\.\.(\/|\\|$))+/, '');
const fullPath = path.resolve(publicRoot, `.${normalized}`);
if (!fullPath.startsWith(publicRoot)) {
return null;
}
return fullPath;
}
async function serveStatic(request: Request) {
const url = new URL(request.url);
const pathname = url.pathname === '/' ? '/index.html' : url.pathname;
const filePath = safeResolvePublicPath(pathname);
if (filePath) {
const file = Bun.file(filePath);
if (await file.exists()) {
return new Response(file);
}
}
const spaFallback = Bun.file(path.join(publicRoot, 'index.html'));
if (await spaFallback.exists()) {
return new Response(spaFallback);
}
return new Response('index.html was not found. Run `bun run build` first.', {
status: 500,
});
}
Bun.serve({
hostname: env.ADMIN_APP_HOST,
port: env.ADMIN_APP_PORT,
async fetch(request) {
const url = new URL(request.url);
if (url.pathname.startsWith('/api/')) {
return routeApiRequest(request, context);
}
return serveStatic(request);
},
});
process.stdout.write(
`@nbw/admin listening on http://${env.ADMIN_APP_HOST}:${env.ADMIN_APP_PORT}\n`,
);