-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathserver.ts
More file actions
52 lines (45 loc) · 1.6 KB
/
Copy pathserver.ts
File metadata and controls
52 lines (45 loc) · 1.6 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
import type { Buffer } from 'node:buffer'
import type { CreateWsServerOptions } from './ws'
import { readFile, stat } from 'node:fs/promises'
import { createServer } from 'node:http'
import { createApp, eventHandler, serveStatic, toNodeListener } from 'h3'
import { lookup } from 'mrmime'
import { join } from 'pathe'
import { distDir } from '../dirs'
import { createWsServer } from './ws'
export async function createHostServer(options: CreateWsServerOptions) {
const app = createApp()
const { rpc, getMetadata } = await createWsServer(options)
const fileMap = new Map<string, Promise<string | Buffer<ArrayBufferLike> | undefined>>()
const readCachedFile = (id: string) => {
if (!fileMap.has(id))
fileMap.set(id, readFile(id).catch(() => undefined))
return fileMap.get(id)
}
app.use('/api/metadata.json', eventHandler(async (event) => {
event.node.res.setHeader('Content-Type', 'application/json')
return event.node.res.end(JSON.stringify(await getMetadata()))
}))
app.use('/', eventHandler(async (event) => {
const result = await serveStatic(event, {
fallthrough: true,
getContents: id => readCachedFile(join(distDir, id)),
getMeta: async (id) => {
const stats = await stat(join(distDir, id)).catch(() => {})
if (!stats || !stats.isFile())
return
return {
type: lookup(id),
size: stats.size,
mtime: stats.mtimeMs,
}
},
})
if (result === false)
return readCachedFile(join(distDir, 'index.html'))
}))
return {
server: createServer(toNodeListener(app)),
rpc,
}
}