web.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /**
  2. * `dsh web` — thin bin over the config-tree boot: run AppCLIEntry with the
  3. * already-parsed host/port/dev, print the URL line, wire signals. All
  4. * composition lives in cordis.yml; all boot glue lives in AppCLIEntry. Host and
  5. * port are unvalidated pass-through overrides — the `dsh-host-webserver` schema
  6. * gates them at boot.
  7. */
  8. import { fileURLToPath } from 'node:url'
  9. import { AppCLIEntry } from './app-cli-entry.ts'
  10. const CONFIG_PATH = fileURLToPath(new URL('../cordis.yml', import.meta.url))
  11. // Display-only mirror of the webserver schema's loopback host: the address the
  12. // local URL always prints. Not a source of truth — the schema is.
  13. const LOOPBACK_HOST = '127.0.0.1'
  14. /**
  15. * Serve the browser UI from the shipped config tree. `host`/`port` are passed
  16. * through only when the flag was given; absent, the `cordis.yml` value stands.
  17. * @param host - the bind host, or `undefined` to keep the config default.
  18. * @param port - the listen port (`0` requests an OS-assigned port), or `undefined` to keep the config default.
  19. * @param dev - mount the client HMR driver and watch plugin bundles for rebuilds.
  20. * @param workspaceRoot - parent directory for name-created workspaces, or `undefined` for the gateway's cwd fallback.
  21. * @param trustedHosts - extra authorities for the /api browser-trust fence, or `undefined` for the derived LAN literals alone.
  22. */
  23. export async function runWeb(
  24. host: string | undefined,
  25. port: number | undefined,
  26. dev: boolean,
  27. workspaceRoot: string | undefined,
  28. trustedHosts: string[] | undefined,
  29. ): Promise<void> {
  30. const entry = new AppCLIEntry({
  31. configPath: CONFIG_PATH,
  32. dev,
  33. ...host !== undefined && { host },
  34. ...port !== undefined && { port },
  35. ...workspaceRoot !== undefined && { workspaceRoot },
  36. ...trustedHosts !== undefined && { trustedHosts },
  37. })
  38. const { ctx, port: boundPort } = await entry.run()
  39. let exiting = false
  40. const shutdown = (code: number): void => {
  41. if (exiting) return
  42. exiting = true
  43. void Promise.resolve(ctx.fiber.dispose()).finally(() => { process.exit(code) })
  44. }
  45. // The entry's boot-time snapshot, not a fresh sample: the printed LAN URL
  46. // must name an address the /api trust fence was configured with.
  47. const lanCandidate = entry.lanAddresses[0]
  48. const localUrl = `http://${LOOPBACK_HOST}:${boundPort}`
  49. console.log(`dsh web: ${localUrl}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${boundPort})`}`)
  50. process.on('SIGTERM', () => { shutdown(0) })
  51. process.on('SIGINT', () => { shutdown(130) })
  52. }