dev-web.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /**
  2. * Watch-build for client-plugin HMR: runs every `dsh.client` plugin package
  3. * through the tsdown JS API in watch mode. Reload signaling is not this
  4. * script's business — the host webserver stat-polls the bundles it serves and
  5. * broadcasts `rebuilt` frames itself (`dsh web`), so any process that
  6. * rewrites `lib/client.js` files triggers reloads; this script is merely the
  7. * convenient way to keep them all rebuilt on source change.
  8. *
  9. * Usage: `pnpm exec tsx scripts/dev-web.ts [--poll[=ms]]`. Requires the
  10. * packages' node halves built once (`tsc -b tsconfig.build.json`): the lib
  11. * config's entries are tsc output. `--poll` switches the source-file watcher
  12. * to polling (default 500ms): network mounts (weka) deliver no inotify
  13. * events, so native watching sees the initial build only and never a source
  14. * change.
  15. *
  16. * Each package keeps its own tsdown.config.ts untouched: this script layers
  17. * `watch` through API-level inline config (tsdown workspace mode fills inline
  18. * keys under each package's file config, and no package config defines it).
  19. */
  20. import { globSync, readFileSync } from 'node:fs'
  21. import { dirname, join, resolve, sep } from 'node:path'
  22. import { fileURLToPath, pathToFileURL } from 'node:url'
  23. import { build } from 'tsdown'
  24. import type { TsdownBundle } from 'tsdown'
  25. const repoRoot = fileURLToPath(new URL('..', import.meta.url))
  26. /**
  27. * Discover the watch workspace by declaration: every packages/<group>/<name>
  28. * whose package.json carries `dsh.client` with platform "web" is a client
  29. * plugin bundle emitter. Scanned once at startup — a package added while
  30. * watching means restarting this script.
  31. * @param root - repository root containing the grouped package directories.
  32. * @returns workspace-relative plugin package directories.
  33. */
  34. export function discoverPluginDirs(root = repoRoot): string[] {
  35. const dirs: string[] = []
  36. for (const manifestPath of globSync('packages/*/*/package.json', { cwd: root }).sort()) {
  37. const manifest = JSON.parse(readFileSync(join(root, manifestPath), 'utf8')) as {
  38. dsh?: { client?: { platform?: unknown } }
  39. }
  40. if (manifest.dsh?.client?.platform === 'web') dirs.push(dirname(manifestPath).split(sep).join('/'))
  41. }
  42. return dirs
  43. }
  44. /**
  45. * Start the tsdown watch build used by `pnpm run dev:web`.
  46. * @param root - repository or fixture root passed to tsdown.
  47. * @param pluginDirs - workspace-relative package directories to watch.
  48. * @param pollInterval - optional source-watcher polling interval in milliseconds.
  49. * @returns live bundles after every watcher has completed its initial build.
  50. */
  51. export async function watchClientPlugins(
  52. root: string,
  53. pluginDirs: readonly string[],
  54. pollInterval?: number,
  55. ): Promise<TsdownBundle[]> {
  56. let resolveInitialBuilds: (() => void) | undefined
  57. const initialBuilds = new Promise<void>((resolve) => { resolveInitialBuilds = resolve })
  58. const initialized = new WeakSet<object>()
  59. const readiness: { expectedBuilds?: number; initializedBuilds: number } = { initializedBuilds: 0 }
  60. const bundles = await build({
  61. cwd: root,
  62. workspace: [...pluginDirs],
  63. watch: true,
  64. hooks: {
  65. 'build:done': ({ options }) => {
  66. if (initialized.has(options)) return
  67. initialized.add(options)
  68. readiness.initializedBuilds += 1
  69. if (
  70. readiness.expectedBuilds !== undefined
  71. && readiness.initializedBuilds >= readiness.expectedBuilds
  72. ) resolveInitialBuilds?.()
  73. },
  74. },
  75. ...pollInterval !== undefined
  76. ? { inputOptions: { watch: { watcher: { usePolling: true, pollInterval } } } }
  77. : {},
  78. })
  79. readiness.expectedBuilds = bundles.length
  80. if (readiness.initializedBuilds >= readiness.expectedBuilds) resolveInitialBuilds?.()
  81. await initialBuilds
  82. return bundles
  83. }
  84. const invokedPath = process.argv[1]
  85. const isMain = invokedPath !== undefined && import.meta.url === pathToFileURL(resolve(invokedPath)).href
  86. if (isMain) {
  87. const pluginDirs = discoverPluginDirs()
  88. if (pluginDirs.length === 0) {
  89. console.error('dev-web: no dsh.client (platform "web") packages found under packages/')
  90. process.exit(1)
  91. }
  92. const args = process.argv.slice(2)
  93. const pollArg = args.find(a => a === '--poll' || a.startsWith('--poll='))
  94. if (args.some(a => a !== pollArg)) {
  95. console.error('dev-web: usage: tsx scripts/dev-web.ts [--poll[=ms]]')
  96. process.exit(1)
  97. }
  98. const pollInterval = pollArg === undefined ? undefined : Number(pollArg.split('=')[1] ?? '500')
  99. if (pollInterval !== undefined && (!Number.isInteger(pollInterval) || pollInterval <= 0)) {
  100. console.error(`dev-web: invalid --poll interval "${pollArg ?? ''}"`)
  101. process.exit(1)
  102. }
  103. await watchClientPlugins(repoRoot, pluginDirs, pollInterval)
  104. console.log(
  105. `dev-web: watching ${String(pluginDirs.length)} dsh.client plugin packages`
  106. + `${pollInterval !== undefined ? ` (polling ${String(pollInterval)}ms)` : ''}:\n ${pluginDirs.join('\n ')}`,
  107. )
  108. }