-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
61 lines (53 loc) · 1.65 KB
/
index.js
File metadata and controls
61 lines (53 loc) · 1.65 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
/**
* @typedef {Object} WebConfig
* @property {number} port The port to listen on.
*/
import path from 'path'
import { promisify } from 'util'
import fs from 'fs'
import { execSync } from 'child_process'
import polka from 'polka'
import sirv from 'sirv'
import cors from 'cors'
export async function startServer(log, port = 3000) {
const app = polka()
// Enable CORS for map origins
app.use(cors())
// Serve static files from the specified directory
const staticLocalDir = path.join(process.cwd(), 'node_modules/@aiswarm/ui-web/dist')
if (fs.existsSync(staticLocalDir)) {
app.use(sirv(staticLocalDir))
} else {
log.trace('Could not find local UI files, looking in global node_modules directory.')
const staticGlobalDir = path.join(getGlobalNodeModulesPath(log), '@aiswarm/ui-web/dist')
if (fs.existsSync(staticGlobalDir)) {
app.use(sirv(staticGlobalDir))
} else {
throw new Error(
"Could not find UI files, please run 'npm run build' in the ui-web directory first."
)
}
}
// Start the server
const listen = promisify(app.listen).bind(app)
await listen(port)
log.info(`Web UI is available at http://localhost:${port}`)
}
function getGlobalNodeModulesPath(log) {
try {
return execSync('npm root -g').toString().trim()
} catch (error) {
log.debug('Error getting global node_modules directory:', error)
}
}
/**
* @param {API} api
* @param {WebConfig} api.config.web The configuration object for the web server.
*/
export function initialize(api) {
const config = api.config.web ?? {}
startServer(api.log, config.port).catch(err => {
api.log.error(err)
throw new Error(err)
})
}