@revenexx/integrations-node-devkit 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/dist/{chunk-YXIYTBOZ.js → chunk-4QB5F7RT.js} +112 -5
- package/dist/chunk-4QB5F7RT.js.map +1 -0
- package/dist/chunk-PME34X7E.js +30 -0
- package/dist/chunk-PME34X7E.js.map +1 -0
- package/dist/cli.cjs +133 -7
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +133 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -4
- package/dist/index.d.ts +38 -4
- package/dist/index.js +2 -1
- package/dist/testing/index.cjs +133 -3
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +62 -3
- package/dist/testing/index.d.ts +62 -3
- package/dist/testing/index.js +110 -0
- package/dist/testing/index.js.map +1 -1
- package/package.json +3 -3
- package/preview-host/package.json +1 -1
- package/dist/chunk-YXIYTBOZ.js.map +0 -1
package/dist/cli.js
CHANGED
|
@@ -11,7 +11,8 @@ import {
|
|
|
11
11
|
loadSeedsFromDir,
|
|
12
12
|
loadState,
|
|
13
13
|
saveState
|
|
14
|
-
} from "./chunk-
|
|
14
|
+
} from "./chunk-4QB5F7RT.js";
|
|
15
|
+
import "./chunk-PME34X7E.js";
|
|
15
16
|
|
|
16
17
|
// src/cli.ts
|
|
17
18
|
import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync3, watch } from "fs";
|
package/dist/cli.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/cli.ts","../src/cli-args.ts","../src/ports.ts","../src/preview/child-env.ts","../src/preview/host.ts","../src/preview/pid.ts","../src/preview/registry.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `integrations-devkit` — local mock Integrations API + preview for a node package.\n *\n * integrations-devkit # start the mock API (+ static UI via --ui)\n * integrations-devkit preview # run the Nuxt host together with the mock\n * integrations-devkit init-preview --dir # take an unmanaged copy of the host to hack on\n * integrations-devkit reset # delete the persisted session overlay\n *\n * The preview host is NOT placed in your repo. It is copied into a version-keyed\n * cache directory (see src/preview/host.ts), so every repo on this machine shares\n * one dependency install and a devkit upgrade can never leave a stale host behind.\n *\n * Options:\n * --dir <path> use this host dir instead of the managed cache (unmanaged)\n * --force re-copy the host even if the target looks complete\n * --parallel allow a second preview next to one already running\n * --entry <path> package entry (default: src/index.ts, else dist/index.js)\n * --seed <dir> committed seeds dir (default: dev/seeds)\n * --state <file> session overlay file (default: .revenexx-dev/state.json)\n * --no-persist do not write the session overlay (in-memory only)\n * --port <n> listen port (default: $PORT or 3555; the default relocates\n * when taken, an explicit one is reported as a conflict)\n * --ui <dir> static UI build dir to serve (default: resolve the UI package)\n * --no-ui run API-only, do not serve a UI\n * --open open the preview in a browser\n * --env <path> env file to load *instead of* .env (default: .env when present)\n * --no-env do not load any env file\n */\n\nimport { existsSync, readdirSync, readFileSync, watch } from 'node:fs';\nimport type http from 'node:http';\nimport { createServer } from 'node:http';\nimport { createRequire } from 'node:module';\nimport { basename, extname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { type CliOptions, parseArgs } from './cli-args.js';\nimport { loadEnvFile } from './env.js';\nimport { CliError } from './errors.js';\nimport { DEVKIT_VERSION } from './index.js';\nimport { isReloadableSource, type LoadedPackage, loadPackageFromEntry } from './loader.js';\nimport { applySeeds, loadSeedsFromDir, loadState, saveState } from './persistence.js';\nimport { previewChildEnv } from './preview/child-env.js';\nimport { clearHostInstallMarker, hostBuildDir, hostDotenvName, hostNeedsInstall, hostViteCacheDir, markHostInstalled, materializeHost, resolveHostDir, withInstallLock } from './preview/host.js';\nimport { describePreview, previewConflict, readLivePreviews, registerPreview, unregisterPreview } from './preview/registry.js';\nimport { findFreePort, listenWithFallback } from './ports.js';\nimport { createRequestListener } from './server.js';\nimport { DevStore } from './store.js';\n\n/** Loads any JSON schemas bundled in the package's `assets/schemas` dir. */\nfunction loadSchemas(): Record<string, unknown> {\n const here = fileURLToPath(new URL('.', import.meta.url));\n // dist/cli.js → package root is one level up.\n const schemasDir = resolve(here, '..', 'assets', 'schemas');\n const schemas: Record<string, unknown> = {};\n if (!existsSync(schemasDir)) {\n return schemas;\n }\n for (const file of readdirSync(schemasDir)) {\n if (extname(file) !== '.json') {\n continue;\n }\n const parsed = JSON.parse(readFileSync(join(schemasDir, file), 'utf-8'));\n // File `node-v0-draft.json` → keys `node/v0-draft` and (latest) `node`.\n // Split on the first dash only: domain=`node`, version=`v0-draft`.\n const base = file.replace(/\\.json$/, '');\n const dash = base.indexOf('-');\n if (dash > 0) {\n const domain = base.slice(0, dash);\n const version = base.slice(dash + 1);\n schemas[`${domain}/${version}`] = parsed;\n schemas[domain] = parsed;\n } else {\n schemas[base] = parsed;\n }\n }\n return schemas;\n}\n\n/**\n * Resolves a *static* UI build dir to serve. Only used for a prebuilt SPA\n * passed via `--ui`. The Cockpit UI (`@revenexx/studio-integrations`) is a Nuxt\n * *module*, not a static build — it is consumed by a Nuxt host app whose\n * `runtimeConfig.public.integrationsApi` points at this mock (see README).\n * Auto-resolution only kicks in for a package that ships a `dist/` with an\n * `index.html`; otherwise the devkit stays API-only.\n */\nfunction resolveUiDir(explicit: string | null): string | null {\n if (explicit) {\n return existsSync(explicit) ? explicit : null;\n }\n const candidates = ['@revenexx/studio-integrations'];\n const req = createRequire(import.meta.url);\n for (const pkg of candidates) {\n try {\n const entry = req.resolve(`${pkg}/package.json`);\n const dist = resolve(entry, '..', 'dist');\n if (existsSync(join(dist, 'index.html'))) {\n return dist;\n }\n } catch {\n // not installed / not a static build — fall through to API-only\n }\n }\n return null;\n}\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'text/javascript',\n '.mjs': 'text/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n};\n\n/** Serves a static SPA build, falling back to index.html for client routes. */\nfunction serveStatic(uiDir: string, req: http.IncomingMessage, res: http.ServerResponse): void {\n const url = new URL(req.url ?? '/', 'http://localhost');\n const relative = url.pathname === '/' ? 'index.html' : url.pathname.replace(/^\\/+/, '');\n let filePath = resolve(uiDir, relative);\n if (!filePath.startsWith(uiDir) || !existsSync(filePath)) {\n filePath = join(uiDir, 'index.html');\n }\n if (!existsSync(filePath)) {\n res.writeHead(404).end('UI build not found');\n return;\n }\n res.writeHead(200, { 'Content-Type': MIME[extname(filePath)] ?? 'application/octet-stream' });\n res.end(readFileSync(filePath));\n}\n\ninterface MockHandle {\n uiDir: string | null;\n /** The port actually bound, which is not necessarily the one that was asked for. */\n port: number;\n dispose(): void;\n}\n\n/** Boots the mock API (store + seeds + persistence + hot-reload). No signal handlers. */\nasync function startMock(options: CliOptions): Promise<MockHandle> {\n let loaded: LoadedPackage = await loadPackageFromEntry(options.entry);\n console.log(`Loaded ${loaded.nodes.length} node(s), ${loaded.credentials.length} credential(s), ${loaded.templates.length} template(s) from ${options.entry}`);\n\n const store = new DevStore();\n applySeeds(store, await loadSeedsFromDir(options.seedDir));\n if (options.persist) {\n const state = loadState(options.stateFile);\n if (state) {\n store.mergeSnapshot(state);\n console.log(`Restored session from ${options.stateFile}`);\n }\n // Attach persistence only now, so applying seeds doesn't rewrite the overlay.\n let timer: NodeJS.Timeout | undefined;\n store.setOnMutation(() => {\n clearTimeout(timer);\n timer = setTimeout(() => saveState(options.stateFile, store.toSnapshot()), 150);\n });\n }\n\n const schemas = loadSchemas();\n const apiListener = createRequestListener({ getPackage: () => loaded, store, schemas });\n\n const uiDir = options.serveUi ? resolveUiDir(options.uiDir) : null;\n const server = createServer((req, res) => {\n const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;\n if (pathname.startsWith('/api/') || pathname === '/health') {\n apiListener(req, res);\n } else if (uiDir) {\n serveStatic(uiDir, req, res);\n } else {\n res.writeHead(404, { 'Content-Type': 'application/json' }).end(\n JSON.stringify({\n message: 'API-only. Point your Nuxt host (studio-integrations) integrationsApi at this URL, or pass --ui <static-build-dir>. CORS is open.',\n }),\n );\n }\n });\n\n const port = await listenWithFallback(server, { port: options.port, strict: options.portExplicit });\n if (port !== options.port) {\n console.log(`Port ${options.port} was taken — the mock is on ${port} instead.`);\n }\n\n const stopWatch = watchAndReload(options.entry, async () => {\n try {\n loaded = await loadPackageFromEntry(options.entry);\n console.log(`↻ Reloaded package (${loaded.nodes.length} nodes, ${loaded.credentials.length} credentials).`);\n } catch (err) {\n console.error(`Reload failed: ${(err as Error).message}`);\n }\n });\n\n return {\n uiDir,\n port,\n dispose() {\n if (options.persist) {\n saveState(options.stateFile, store.toSnapshot());\n }\n stopWatch?.();\n server.close();\n },\n };\n}\n\n/** Interactive mock server (API + optional static UI). */\nasync function run(options: CliOptions): Promise<void> {\n const mock = await startMock(options);\n const urlBase = `http://localhost:${mock.port}`;\n console.log(`\\n Mock Integrations API ${urlBase}/api/v1`);\n console.log(mock.uiDir ? ` Preview UI ${urlBase}` : ` Preview UI API-only — set your Nuxt host's integrationsApi to ${urlBase}/api/v1`);\n console.log('\\n Watching for changes. Ctrl-C to stop.\\n');\n\n if (options.open && mock.uiDir) {\n void openBrowser(urlBase);\n }\n\n const shutdown = () => {\n mock.dispose();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n}\n\n/** Watches the entry's directory tree and fires `onChange` (debounced). Returns a stop fn. */\nfunction watchAndReload(entry: string, onChange: () => void): (() => void) | undefined {\n const dir = resolve(entry, '..');\n let timer: NodeJS.Timeout | undefined;\n try {\n const watcher = watch(dir, { recursive: true }, (_event, file) => {\n if (file && isReloadableSource(file.toString())) {\n clearTimeout(timer);\n timer = setTimeout(onChange, 200);\n }\n });\n return () => watcher.close();\n } catch {\n // Recursive watch unsupported on this platform — skip hot-reload.\n console.warn('Hot-reload unavailable on this platform; restart to pick up changes.');\n return undefined;\n }\n}\n\n/** Runs `npm install` in `dir`, inheriting stdio. */\nasync function runNpmInstall(dir: string): Promise<void> {\n const { spawn } = await import('node:child_process');\n await new Promise<void>((resolvePromise, reject) => {\n const child = spawn('npm', ['install'], { cwd: dir, stdio: 'inherit' });\n child.on('exit', code => (code === 0 ? resolvePromise() : reject(new Error(`npm install exited with code ${code}`))));\n child.on('error', reject);\n });\n}\n\n/**\n * Warns about a `.revenexx-dev/preview` left over from before the host moved into\n * the shared cache. Not deleted automatically — it is the user's directory, and it\n * may hold edits they want to keep.\n */\nfunction noteLegacyPreviewDir(): void {\n const legacy = resolve(process.cwd(), '.revenexx-dev/preview');\n if (existsSync(legacy)) {\n console.log(`Note: ${legacy} is no longer used — the preview host now lives in a shared cache. You can delete it to reclaim the space.`);\n }\n}\n\n/** Default port for the Nuxt dev server, matching Nuxt's own. */\nconst UI_PORT = 3000;\n\n/** Materializes (if needed), installs, and runs the Nuxt preview host + the mock together. */\nasync function preview(options: CliOptions): Promise<void> {\n const cwd = process.cwd();\n const managed = options.previewDir === null;\n const hostDir = resolve(options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION }));\n\n // Before anything is bound or copied: a second preview is usually a forgotten\n // one from an earlier session, not a deliberate one.\n const running = readLivePreviews(hostDir);\n const conflict = previewConflict(running, { cwd, hostDir, parallel: options.parallel, force: options.force });\n if (conflict) {\n throw new CliError(conflict);\n }\n\n noteLegacyPreviewDir();\n\n // Bind the mock BEFORE copying and installing. A port clash or an entry that\n // does not load then costs seconds, instead of surfacing after a multi-minute\n // `npm install` with a Nuxt child already on the way.\n const mock = await startMock({ ...options, serveUi: false });\n const apiUrl = `http://localhost:${mock.port}/api/v1`;\n\n try {\n const { dir } = materializeHost({\n targetDir: hostDir,\n integrationsApiUrl: apiUrl,\n dotenvName: managed ? hostDotenvName(cwd) : undefined,\n force: options.force,\n managed,\n log: msg => console.log(msg),\n });\n\n if (options.force) {\n // `hostNeedsInstall` already reinstalls when the pins changed, so this is not\n // that case — it is the escape hatch --force is documented to be: an install\n // that reported success but left an unusable tree has no other way out short\n // of deleting the directory.\n clearHostInstallMarker(dir);\n }\n if (hostNeedsInstall(dir)) {\n await withInstallLock(\n dir,\n async () => {\n console.log('Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)…');\n await runNpmInstall(dir);\n markHostInstalled(dir);\n },\n { needsInstall: () => hostNeedsInstall(dir), log: msg => console.log(msg) },\n );\n }\n\n // Honour an explicit NUXT_PORT; otherwise take the first free port. Nuxt's own\n // listhen fallback still covers the gap between this check and its bind, which\n // is why the URL below is Nuxt's to print, not ours.\n const uiPort = process.env.NUXT_PORT ? Number(process.env.NUXT_PORT) : await findFreePort(UI_PORT);\n\n console.log(`\\n Previewing ${basename(cwd)} (${cwd})`);\n console.log(` Mock Integrations API ${apiUrl}`);\n if (managed) {\n console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);\n }\n console.log(` Preview UI starting on port ${uiPort} — Nuxt prints the URL it got, below.`);\n for (const entry of running) {\n console.log(` Also running ${describePreview(entry)}`);\n }\n console.log('');\n\n const { spawn } = await import('node:child_process');\n // The managed host reads a per-repo dotenv file, so it has to be named. An\n // unmanaged copy keeps plain `.env`, which Nuxt picks up on its own.\n const args = managed ? ['run', 'dev', '--', '--dotenv', hostDotenvName(cwd)] : ['run', 'dev'];\n const child = spawn('npm', args, {\n cwd: dir,\n stdio: 'inherit',\n env: previewChildEnv({\n base: process.env,\n apiUrl,\n uiPort,\n buildDir: hostBuildDir(dir, cwd),\n viteCacheDir: hostViteCacheDir(dir, cwd),\n }),\n });\n\n registerPreview(dir, { pid: process.pid, cwd, mockPort: mock.port, uiPort, startedAt: new Date().toISOString() });\n const cleanUp = () => {\n unregisterPreview(dir);\n mock.dispose();\n };\n\n const shutdown = () => {\n child.kill('SIGTERM');\n cleanUp();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n child.on('exit', code => {\n cleanUp();\n process.exit(code ?? 0);\n });\n } catch (err) {\n // The mock is already listening at this point; leaving it bound would make the\n // next attempt look like a port conflict.\n mock.dispose();\n throw err;\n }\n}\n\nasync function openBrowser(url: string): Promise<void> {\n const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';\n const { spawn } = await import('node:child_process');\n spawn(cmd, [url], { stdio: 'ignore', detached: true }).unref();\n}\n\nasync function main(): Promise<void> {\n const argv = process.argv.slice(2);\n // Before parseArgs: it reads `PORT`, and seeds interpolate `${VAR}` from the\n // environment once the mock starts.\n const envFile = loadEnvFile(argv);\n const { command, options } = parseArgs(argv);\n if (command === 'version') {\n console.log(DEVKIT_VERSION);\n return;\n }\n if (envFile) {\n console.log(`Loaded env from ${envFile}`);\n }\n if (command === 'reset') {\n const { rmSync } = await import('node:fs');\n rmSync(options.stateFile, { force: true });\n console.log(`Removed ${options.stateFile}`);\n return;\n }\n if (command === 'init-preview') {\n // The managed host is a disposable artifact `preview` handles on its own, so\n // this command only makes sense for taking a copy you intend to change.\n if (options.previewDir === null) {\n console.error('init-preview needs an explicit target: `integrations-devkit init-preview --dir ./my-preview`.');\n console.error('It exists to give you an UNMANAGED copy of the preview host to modify. For the normal preview, just run `integrations-devkit preview` —');\n console.error('that materializes the host into a shared cache and keeps it in step with the devkit version.');\n process.exit(1);\n }\n const { dir } = materializeHost({\n targetDir: options.previewDir,\n integrationsApiUrl: `http://localhost:${options.port}/api/v1`,\n force: options.force,\n log: msg => console.log(msg),\n });\n console.log('\\nThis copy is yours and will NOT be updated by devkit upgrades.');\n console.log(`Run it with: \\`cd ${dir} && npm install && npm run dev\\` (plus \\`integrations-devkit --no-ui\\` for the mock),`);\n console.log(`or \\`integrations-devkit preview --dir ${dir}\\` to have both started for you.`);\n return;\n }\n if (command === 'preview') {\n await preview(options);\n return;\n }\n await run(options);\n}\n\nmain().catch(err => {\n // A CliError is a message for the user, not a defect: print the message alone.\n // Anything else keeps its stack, which is the only useful thing about it.\n console.error(err instanceof CliError ? err.message : err);\n process.exit(1);\n});\n","import { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { CliError } from './errors.js';\nimport { parsePort } from './ports.js';\n\n/**\n * Argument parsing, kept apart from `cli.ts` so it can be tested.\n *\n * `cli.ts` runs `main()` on import, so anything reachable only from there is\n * unreachable from a test. This function is pure — it throws {@link CliError}\n * instead of calling `process.exit`, and reads the environment but never writes it.\n */\n\nexport interface CliOptions {\n entry: string;\n seedDir: string;\n stateFile: string;\n persist: boolean;\n port: number;\n /**\n * True when the port was named by the user (`--port` or `$PORT`). An explicit\n * port is honoured or reported as a conflict; only the default may relocate.\n */\n portExplicit: boolean;\n uiDir: string | null;\n serveUi: boolean;\n open: boolean;\n /** Explicit host directory from `--dir`; null means use the managed cache. */\n previewDir: string | null;\n /** Re-copy the host even when the target looks complete. */\n force: boolean;\n /** Allow a second preview alongside one that is already running. */\n parallel: boolean;\n}\n\nexport const DEFAULT_PORT = 3555;\n\nexport function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): { command: string | null; options: CliOptions } {\n const cwd = process.cwd();\n const opts: CliOptions = {\n entry: '',\n seedDir: resolve(cwd, 'dev/seeds'),\n stateFile: resolve(cwd, '.revenexx-dev/state.json'),\n persist: true,\n port: env.PORT === undefined ? DEFAULT_PORT : parsePort(env.PORT, '$PORT'),\n portExplicit: env.PORT !== undefined,\n uiDir: null,\n serveUi: true,\n open: false,\n previewDir: null,\n force: false,\n parallel: false,\n };\n let command: string | null = null;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n switch (arg) {\n case 'reset':\n command = 'reset';\n break;\n case 'init-preview':\n command = 'init-preview';\n break;\n case 'preview':\n command = 'preview';\n break;\n case '--dir':\n opts.previewDir = resolve(cwd, argv[++i] ?? '');\n break;\n case '--force':\n opts.force = true;\n break;\n case '--parallel':\n opts.parallel = true;\n break;\n case '--entry':\n opts.entry = resolve(cwd, argv[++i] ?? '');\n break;\n case '--seed':\n opts.seedDir = resolve(cwd, argv[++i] ?? '');\n break;\n case '--state':\n opts.stateFile = resolve(cwd, argv[++i] ?? '');\n break;\n case '--no-persist':\n opts.persist = false;\n break;\n case '--port':\n // A missing or non-numeric value used to fall back to the default or reach\n // `listen(NaN)`; both hid a typo the user would rather be told about.\n opts.port = parsePort(argv[++i], '--port');\n opts.portExplicit = true;\n break;\n case '--ui':\n opts.uiDir = resolve(cwd, argv[++i] ?? '');\n break;\n case '--no-ui':\n opts.serveUi = false;\n break;\n case '--open':\n opts.open = true;\n break;\n // Both are consumed by loadEnvFile() before parsing; listed here so they\n // do not fall through to the unknown-option branch. A repeated `--env`\n // resolves to the last one, so each occurrence skips its own value.\n case '--env':\n i++;\n break;\n case '--no-env':\n break;\n case '--version':\n case '-v':\n command = 'version';\n break;\n default:\n // Node acts on `--env-file[-if-exists]` itself but still forwards it\n // here, so accept and skip it rather than rejecting the user's input.\n // loadEnvFile() has already pointed them at `--env`.\n if (arg?.startsWith('--env-file')) {\n if (!arg.includes('=')) {\n i++;\n }\n break;\n }\n if (arg?.startsWith('-')) {\n throw new CliError(`Unknown option: ${arg}`);\n }\n }\n }\n if (!opts.entry) {\n const src = resolve(cwd, 'src/index.ts');\n opts.entry = existsSync(src) ? src : resolve(cwd, 'dist/index.js');\n }\n return { command, options: opts };\n}\n","import type { Server } from 'node:http';\nimport { createServer } from 'node:net';\nimport { CliError } from './errors.js';\n\n/**\n * Port allocation for the mock API and the Nuxt dev server.\n *\n * Two rules shape this module:\n *\n * - **Bind, do not probe.** Asking \"is this port free?\" and then binding it is a\n * race against every other process on the machine. The mock therefore binds for\n * real and moves on only after an actual `EADDRINUSE`. (The Nuxt port cannot\n * work that way — a child process binds it — so `findFreePort` does probe, and\n * listhen's own fallback is the backstop for the window in between.)\n * - **A named port is a promise, not a preference.** `--port 4000` or `PORT=4000`\n * means 4000; if it is taken, that is an error, not an invitation to pick 4001.\n * Only the default may wander, because nothing outside devkit depends on it.\n */\n\n/** How many consecutive ports to try before giving up. */\nconst DEFAULT_LIMIT = 20;\n\nexport interface ListenOptions {\n port: number;\n /** True when the port was named explicitly (`--port` / `$PORT`): never relocate. */\n strict: boolean;\n limit?: number;\n}\n\n/**\n * Binds `server`, walking up from `options.port` on `EADDRINUSE`. Resolves with the\n * port actually bound — callers must use that value rather than the one they asked\n * for, since every URL they print or hand to a child process depends on it.\n */\nexport async function listenWithFallback(server: Server, options: ListenOptions): Promise<number> {\n const limit = options.strict ? 1 : (options.limit ?? DEFAULT_LIMIT);\n const first = options.port;\n for (let port = first; port < first + limit; port += 1) {\n const bound = await bind(server, port);\n if (bound !== null) {\n return bound;\n }\n }\n throw options.strict\n ? new CliError(`Port ${first} is already in use. Stop whatever is holding it, or pass a different --port.`)\n : new CliError(`No free port between ${first} and ${first + limit - 1}. Pass --port <n> to choose one explicitly.`);\n}\n\n/** Resolves with the bound port, or null when the port is taken. */\nfunction bind(server: Server, port: number): Promise<number | null> {\n return new Promise((resolvePort, reject) => {\n const onError = (err: NodeJS.ErrnoException) => {\n server.removeListener('listening', onListening);\n if (err.code === 'EADDRINUSE') {\n resolvePort(null);\n return;\n }\n reject(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n const address = server.address();\n resolvePort(typeof address === 'object' && address !== null ? address.port : port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port);\n });\n}\n\n/**\n * First free port at or above `base`, found by binding a throwaway listener.\n *\n * For ports someone else will bind — the Nuxt dev server runs as a child process.\n * The gap between this check and that bind is a real (if narrow) race; Nuxt's own\n * listhen fallback covers it, which is why devkit no longer prints the UI URL\n * itself and lets Nuxt announce the port it truly got.\n */\nexport async function findFreePort(base: number, limit = DEFAULT_LIMIT): Promise<number> {\n for (let port = base; port < base + limit; port += 1) {\n if (await isFree(port)) {\n return port;\n }\n }\n throw new CliError(`No free port between ${base} and ${base + limit - 1} for the preview UI.`);\n}\n\nfunction isFree(port: number): Promise<boolean> {\n return new Promise(resolveFree => {\n const probe = createServer();\n probe.once('error', () => resolveFree(false));\n probe.once('listening', () => probe.close(() => resolveFree(true)));\n probe.listen(port);\n });\n}\n\n/** Parses a `--port` value, rejecting what would otherwise reach `listen()` as NaN. */\nexport function parsePort(value: string | undefined, flag: string): number {\n if (value === undefined || value.startsWith('-')) {\n throw new CliError(`${flag} needs a port number, e.g. \\`${flag} 4000\\`.`);\n }\n const port = Number(value);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new CliError(`${flag} expects an integer between 1 and 65535, got \\`${value}\\`.`);\n }\n return port;\n}\n","export interface PreviewChildEnvOptions {\n /** Usually `process.env`. */\n base: NodeJS.ProcessEnv;\n /** Mock API base URL, including the port actually bound. */\n apiUrl: string;\n /** Per-repo Nuxt build directory (`hostBuildDir`). */\n buildDir: string;\n /** Per-repo Vite dependency cache (`hostViteCacheDir`). */\n viteCacheDir: string;\n /** Port the Nuxt dev server should listen on. */\n uiPort: number;\n}\n\n/**\n * Environment for the `nuxt dev` child process.\n *\n * A pure function because the three things it gets right are all invisible at a\n * glance, and each of them was a bug:\n *\n * - **`PORT` is deleted.** It is the mock's variable, but Nuxt's listhen reads it\n * too, so `PORT=4000 integrations-devkit preview` used to have the mock *and*\n * the UI both claim 4000. Nuxt then relocated silently and every URL devkit\n * printed was wrong. `NUXT_PORT` outranks `PORT` anyway; deleting it as well\n * keeps the mock's port out of the child's namespace entirely.\n * - **`DEVKIT_VITE_CACHE_DIR` is set.** Without it Vite's dependency cache lands\n * in the *shared* host's `node_modules/.cache/vite`, and since Vite's config\n * hash includes the `#build` alias — i.e. the per-repo build dir — two repos\n * each consider the other's cache stale and `rm -rf` it while it is being\n * served from. Per-repo build dirs alone actively caused that.\n * - **`NUXT_PORT` is set explicitly**, so devkit knows the UI port instead of\n * guessing 3000 and hoping listhen agreed.\n */\nexport function previewChildEnv(options: PreviewChildEnvOptions): NodeJS.ProcessEnv {\n const env = { ...options.base };\n delete env.PORT;\n return {\n ...env,\n NUXT_PUBLIC_INTEGRATIONS_API: options.apiUrl,\n NUXT_PUBLIC_DEV_TOKEN: options.base.NUXT_PUBLIC_DEV_TOKEN ?? 'dev',\n NUXT_PUBLIC_DEV_TENANT: options.base.NUXT_PUBLIC_DEV_TENANT ?? 'dev-tenant',\n NUXT_PORT: String(options.uiPort),\n DEVKIT_NUXT_BUILD_DIR: options.buildDir,\n DEVKIT_VITE_CACHE_DIR: options.viteCacheDir,\n };\n}\n","import { createHash } from 'node:crypto';\nimport { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { CliError } from '../errors.js';\nimport { type IsAlive, pidIsAlive } from './pid.js';\n\n/**\n * The Nuxt preview host ships as real files in the devkit package (`preview-host/`)\n * and is copied into a version-keyed directory at run time. It is deliberately NOT\n * placed inside the consuming repo:\n *\n * - A per-repo copy is never refreshed (the old scaffold only checked whether\n * two filenames existed), so a devkit upgrade silently left a broken host\n * behind — unfixable for external node-package authors.\n * - Every repo paid for its own ~500 MB dependency tree of the same packages.\n * - Keying the directory by devkit version makes staleness structurally\n * impossible: a new devkit version means a new directory.\n *\n * The copy is therefore a disposable artifact, not something to edit. Authors who\n * want to hack on the host take an explicit unmanaged copy with\n * `integrations-devkit init-preview --dir ./my-preview`.\n */\n\n/** Marker written after a *successful* dependency install. */\nconst INSTALL_MARKER = '.devkit-install-complete';\n\n/**\n * Marker written after the file copy finished, holding a fingerprint of the source\n * it copied. Without it, \"is the host here?\" would again be \"do two filenames\n * exist\" — the same check whose weakness this module exists to fix, only for the\n * copy instead of the install: `cpSync` is not atomic, so an interrupted copy can\n * leave `package.json` and `nuxt.config.ts` behind while the rest is missing, and\n * that half-host would be treated as intact forever.\n *\n * The fingerprint covers the second half of the same problem. Keying the directory\n * by devkit version makes a stale host impossible *between releases*, but says\n * nothing while the version stands still — so anyone working on `preview-host/`\n * itself, this repo's own developers included, silently kept running the copy from\n * before their change. Comparing the source instead of trusting the version keeps\n * that honest, and costs nothing: the dependency install is keyed separately, so a\n * changed host file re-copies without reinstalling.\n */\nconst COPY_MARKER = '.devkit-copy-complete';\n\n/** Lock held while `npm install` runs, so two repos cannot install over each other. */\nconst INSTALL_LOCK = '.devkit-install.lock';\n\n/** Files generated into the target rather than shipped, since they carry runtime values. */\nconst HOST_GITIGNORE = `node_modules/\n.nuxt/\n.nuxt-*/\n.vite-*/\n.output/\n.data/\n.env*\npreviews/\n${COPY_MARKER}\n${INSTALL_MARKER}\n${INSTALL_LOCK}\n`;\n\nexport interface HostDirOptions {\n /** Devkit version; keys the cache directory. */\n version: string;\n /** Overrides the whole cache location (mainly for tests). */\n cacheRoot?: string;\n}\n\n/**\n * Cache location for the managed host: `<cache>/revenexx/devkit-preview/<version>`.\n * Honours `XDG_CACHE_HOME`, falling back to `~/.cache`.\n */\nexport function resolveHostDir(options: HostDirOptions): string {\n const root = options.cacheRoot ?? process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache');\n return join(root, 'revenexx', 'devkit-preview', options.version);\n}\n\n/**\n * Absolute path of the `preview-host/` directory shipped inside this package.\n *\n * Walks up from this module rather than assuming a fixed depth, because the\n * module sits at `dist/cli.js` in the published package but at\n * `src/preview/host.ts` when running from source (tsx, vitest).\n */\nexport function shippedHostDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let up = 0; up < 5; up += 1) {\n const candidate = join(dir, 'preview-host');\n if (existsSync(join(candidate, 'nuxt.config.ts'))) {\n return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new Error('Preview host not found: no preview-host/nuxt.config.ts above this module. Reinstall @revenexx/integrations-node-devkit.');\n}\n\nexport interface MaterializeHostOptions {\n /** Where to put the host. */\n targetDir: string;\n /** Overrides the shipped host to copy from (mainly for tests). */\n sourceDir?: string;\n /** Mock API base URL written into the generated `.env`. */\n integrationsApiUrl: string;\n /** Dev token/tenant written into the generated `.env`. */\n devToken?: string;\n devTenant?: string;\n /** Re-copy even when the target already looks complete. */\n force?: boolean;\n /**\n * Name of the generated dotenv file. Defaults to `.env`; `preview` passes a\n * per-repo name for the managed cache (see {@link hostDotenvName}).\n */\n dotenvName?: string;\n /**\n * True for the version-keyed cache directory devkit owns, false for a `--dir`\n * copy that belongs to the user. Decides two things: whether an incomplete copy\n * may be redone (safe when devkit owns the directory, destructive when the user\n * does), and whether the generated `.env` / `.gitignore` are rewritten on every\n * run or left alone once they exist.\n */\n managed?: boolean;\n log?: (msg: string) => void;\n}\n\nexport interface MaterializeHostResult {\n dir: string;\n /** True when files were (re-)copied; false when an intact copy was reused. */\n copied: boolean;\n}\n\n/**\n * Copies the shipped host into `targetDir` and writes the generated files.\n *\n * The copy is wholesale rather than per-file. For the managed cache that is free —\n * nothing in it is worth preserving — so an incomplete copy is simply redone. A\n * `--dir` copy belongs to the user, so there \"the defining files are present\" has\n * to be enough: re-copying over someone's edits to repair a hypothetical\n * interrupted copy would cost more than it saves.\n *\n * `node_modules/` and the install marker survive a re-copy so an unchanged\n * dependency set is not reinstalled for nothing — `hostNeedsInstall` compares the\n * manifest, so changed pins still reinstall.\n */\nexport function materializeHost(options: MaterializeHostOptions): MaterializeHostResult {\n const log = options.log ?? (() => {});\n const source = options.sourceDir ?? shippedHostDir();\n const dir = resolve(options.targetDir);\n const managed = options.managed ?? false;\n // A `--dir` copy belongs to the user: \"the defining files are present\" has to be\n // enough there, because a re-copy would overwrite their edits. The managed cache\n // is devkit's, so it is held to the stricter test — finished, and copied from\n // exactly this source.\n const intact = managed ? hostIsComplete(dir) && copyIsCurrent(dir, source) : hostExists(dir);\n const alreadyIntact = intact && !options.force;\n\n if (!alreadyIntact) {\n mkdirSync(dir, { recursive: true });\n // Never copy a node_modules/ that lives INSIDE the host (present when someone\n // is working on preview-host/ itself) — it is the expensive part and is\n // validated separately via the install marker.\n //\n // The filter must judge the path RELATIVE to the source. Testing the absolute\n // path breaks the moment devkit is installed as a dependency, because the\n // source is then `…/node_modules/@revenexx/integrations-node-devkit/preview-host`\n // and the filter rejects the source root itself — cpSync then copies nothing\n // at all, silently.\n rmSync(join(dir, COPY_MARKER), { force: true });\n cpSync(source, dir, { recursive: true, filter: src => !isInsideNodeModules(source, src) });\n writeFileSync(join(dir, COPY_MARKER), `${sourceFingerprint(source)}\\n${new Date().toISOString()}\\n`, 'utf-8');\n writeFileSync(join(dir, '.gitignore'), HOST_GITIGNORE, 'utf-8');\n log(`Preview host ready in ${dir}`);\n }\n\n // Managed: always refresh, because the API URL depends on --port and the\n // directory is devkit's to maintain. Unmanaged: write it only when it is\n // missing — that copy is the user's, and `preview` passes the same values to\n // the Nuxt child process anyway, so a hand-edited `.env` stays theirs.\n //\n // The managed name is per repo (`.env.<hash>`), and that is not cosmetic: Nuxt\n // watches its dotenv file and does a full respawn when it changes, so a single\n // shared `.env` rewritten on every run restarted every *other* preview running\n // out of this directory. The dedupe is mtime-based, so identical content did not\n // help. A per-repo filename ends the crossfire — instances only watch their own.\n const envPath = join(dir, options.dotenvName ?? '.env');\n if (managed || !existsSync(envPath)) {\n writeFileSync(envPath, envFile(options), 'utf-8');\n }\n\n return { dir, copied: !alreadyIntact };\n}\n\n/** True when `src` sits under a `node_modules/` *within* the copied tree. */\nfunction isInsideNodeModules(source: string, src: string): boolean {\n const rel = relative(source, src);\n return rel !== '' && rel.split(sep).includes('node_modules');\n}\n\n/**\n * Content hash of the shipped host, over paths and bytes. Deliberately not mtimes:\n * reinstalling the devkit rewrites those without changing a thing, and a 500 MB\n * cache directory should not be invalidated by a timestamp.\n */\nfunction sourceFingerprint(source: string): string {\n const hash = createHash('sha256');\n for (const file of listFiles(source, source).sort()) {\n hash.update(file);\n hash.update(readFileSync(join(source, file)));\n }\n return hash.digest('hex').slice(0, 16);\n}\n\nfunction listFiles(root: string, dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules') {\n continue;\n }\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...listFiles(root, full));\n } else if (entry.isFile()) {\n files.push(relative(root, full));\n }\n }\n return files;\n}\n\n/** True when the copy in `dir` was made from this exact source. */\nfunction copyIsCurrent(dir: string, source: string): boolean {\n try {\n const recorded = readFileSync(join(dir, COPY_MARKER), 'utf-8').split('\\n')[0]?.trim();\n return recorded === sourceFingerprint(source);\n } catch {\n return false;\n }\n}\n\nfunction envFile(options: MaterializeHostOptions): string {\n const name = options.dotenvName ?? '.env';\n const manual = name === '.env' ? 'npm run dev' : `npm run dev -- --dotenv ${name}`;\n return `# Generated by integrations-devkit — overrides the Nuxt runtimeConfig.public.* values.\n# The \\`preview\\` command also passes these to the Nuxt child process; this file is\n# what makes a manual \\`${manual}\\` in this directory work.\nNUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}\nNUXT_PUBLIC_DEV_TOKEN=${options.devToken ?? 'dev'}\nNUXT_PUBLIC_DEV_TENANT=${options.devTenant ?? 'dev-tenant'}\n`;\n}\n\n/**\n * Stable per-repo key. One host directory serves every node package on the machine,\n * so everything that must not be shared is suffixed with this.\n */\nfunction consumerKey(consumerDir: string): string {\n return createHash('sha256').update(consumerDir).digest('hex').slice(0, 12);\n}\n\n/**\n * Per-consumer Nuxt build directory inside the shared host.\n *\n * The dependency tree is worth sharing; the compiled app is not. Two repos running\n * `preview` concurrently would otherwise build into the same `.nuxt/` and serve\n * each other's app. Keyed by a hash of the consumer's directory so it is stable\n * across runs — the build cache still pays off — and distinct per repo.\n *\n * Necessary but **not sufficient** on its own, and for a while it was worse than\n * that: see {@link hostViteCacheDir}.\n */\nexport function hostBuildDir(hostDir: string, consumerDir: string): string {\n return join(hostDir, `.nuxt-${consumerKey(consumerDir)}`);\n}\n\n/**\n * Per-consumer Vite dependency cache inside the shared host.\n *\n * Vite anchors its `cacheDir` on `rootDir`, not on the build dir, so every repo\n * previewing out of this directory shared one `node_modules/.cache/vite`. That\n * would have been merely wasteful were it not for how Vite invalidates it: the\n * `configHash` covers `resolve.alias`, which contains Nuxt's `#build` alias, which\n * is the per-repo build dir. Two repos therefore each computed a different hash,\n * each judged the other's cache stale, and each ran `rm -rf` on the dependency\n * directory the other was actively serving from — every time, in both directions,\n * until one of them was killed.\n *\n * Overriding `cacheDir` per repo is what actually isolates them. It also pays off\n * sequentially: switching between repos no longer re-optimizes from scratch.\n */\nexport function hostViteCacheDir(hostDir: string, consumerDir: string): string {\n return join(hostDir, `.vite-${consumerKey(consumerDir)}`);\n}\n\n/**\n * Per-consumer dotenv filename inside the shared host.\n *\n * Nuxt watches its dotenv file and treats a change as a reason to respawn, so one\n * shared `.env` — rewritten on every run, because it carries the mock's port —\n * restarted every other preview using this directory.\n */\nexport function hostDotenvName(consumerDir: string): string {\n return `.env.${consumerKey(consumerDir)}`;\n}\n\n/** True when `dir` holds something that looks like a host (its two defining files). */\nexport function hostExists(dir: string): boolean {\n return existsSync(join(dir, 'package.json')) && existsSync(join(dir, 'nuxt.config.ts'));\n}\n\n/**\n * True when `dir` holds a host this devkit finished copying. Stricter than\n * {@link hostExists}, which cannot tell a complete host from the first two files\n * of an interrupted one.\n */\nexport function hostIsComplete(dir: string): boolean {\n return hostExists(dir) && existsSync(join(dir, COPY_MARKER));\n}\n\n/**\n * True when dependencies must be installed.\n *\n * Deliberately not just `existsSync(node_modules)`: that was the root of a real\n * bug — `--force` rewrote `package.json` with new pins, the `node_modules/` check\n * then reported \"installed\", `npm install` was skipped, and Nuxt booted against\n * the old dependency tree. The marker records the manifest the install actually\n * succeeded for, so changed pins and interrupted installs both reinstall.\n */\nexport function hostNeedsInstall(dir: string): boolean {\n const marker = join(dir, INSTALL_MARKER);\n if (!existsSync(join(dir, 'node_modules')) || !existsSync(marker)) {\n return true;\n }\n try {\n return readFileSync(marker, 'utf-8').trim() !== manifestFingerprint(dir);\n } catch {\n return true;\n }\n}\n\n/** Records a successful install for the host's current manifest. */\nexport function markHostInstalled(dir: string): void {\n writeFileSync(join(dir, INSTALL_MARKER), `${manifestFingerprint(dir)}\\n`, 'utf-8');\n}\n\n/** Clears the install marker so the next run reinstalls. */\nexport function clearHostInstallMarker(dir: string): void {\n rmSync(join(dir, INSTALL_MARKER), { force: true });\n}\n\n/**\n * Runs `install` with an exclusive lock on the host directory.\n *\n * `npm install` in a directory another npm is installing into is a good way to end\n * up with a half-written dependency tree, and the shared cache makes that a normal\n * occurrence rather than an exotic one: two repos previewing for the first time\n * after a devkit upgrade both decide they need to install.\n *\n * The lock is a file created with `wx` — the exclusivity comes from the filesystem,\n * not from a check-then-write. It records a pid so a lock left behind by a killed\n * process can be identified and taken over, which matters because the alternative\n * is a cache directory that refuses to install ever again.\n *\n * `needsInstall` is re-checked while holding the lock: after waiting behind another\n * process, the install we were queuing for has usually already done the work.\n */\nexport async function withInstallLock<T>(\n dir: string,\n install: () => Promise<T>,\n options: { needsInstall?: () => boolean; isAlive?: IsAlive; log?: (msg: string) => void; timeoutMs?: number; pollMs?: number } = {},\n): Promise<T | null> {\n const isAlive = options.isAlive ?? pidIsAlive;\n const log = options.log ?? (() => {});\n const timeoutMs = options.timeoutMs ?? 20 * 60_000;\n const pollMs = options.pollMs ?? 500;\n const lockPath = join(dir, INSTALL_LOCK);\n const deadline = Date.now() + timeoutMs;\n let waitingFor: number | null = null;\n\n while (!acquire(lockPath)) {\n const holder = lockHolder(lockPath);\n if (holder === null || !isAlive(holder)) {\n // The holder is gone; the lock can never be released by anyone else.\n rmSync(lockPath, { force: true });\n continue;\n }\n if (holder !== waitingFor) {\n waitingFor = holder;\n log(`Another devkit (PID ${holder}) is installing the preview host's dependencies — waiting for it to finish…`);\n }\n if (Date.now() > deadline) {\n throw new CliError(`Timed out after ${Math.round(timeoutMs / 60_000)} min waiting for PID ${holder} to finish installing in ${dir}. If that process is gone, delete ${lockPath}.`);\n }\n await new Promise(done => setTimeout(done, pollMs));\n }\n\n try {\n if (options.needsInstall && !options.needsInstall()) {\n return null;\n }\n return await install();\n } finally {\n rmSync(lockPath, { force: true });\n }\n}\n\n/** True when the lock was created by us. `wx` fails if the file already exists. */\nfunction acquire(lockPath: string): boolean {\n try {\n mkdirSync(dirname(lockPath), { recursive: true });\n writeFileSync(lockPath, `${process.pid}\\n${new Date().toISOString()}\\n`, { encoding: 'utf-8', flag: 'wx' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction lockHolder(lockPath: string): number | null {\n try {\n const pid = Number.parseInt(readFileSync(lockPath, 'utf-8').split('\\n')[0] ?? '', 10);\n return Number.isInteger(pid) ? pid : null;\n } catch {\n // Vanished between the failed acquire and this read — treat as unheld.\n return null;\n }\n}\n\n/**\n * The dependency sets the install must match. Only the dependency blocks matter —\n * editing a script or the description should not trigger a 500 MB reinstall.\n */\nfunction manifestFingerprint(dir: string): string {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8')) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return JSON.stringify({ dependencies: pkg.dependencies ?? {}, devDependencies: pkg.devDependencies ?? {} });\n}\n","/**\n * Whether a process is still around.\n *\n * `kill(pid, 0)` sends no signal — it only asks the kernel whether the process\n * exists and whether we may signal it. `EPERM` therefore means \"alive, but not\n * yours\", which counts as alive: a preview started under another user still holds\n * the port.\n *\n * Both the preview registry and the install lock record a pid, and both need the\n * same answer, so this lives on its own rather than in either of them.\n */\nexport function pidIsAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) {\n return false;\n }\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Injectable liveness check, so tests need no real processes. */\nexport type IsAlive = (pid: number) => boolean;\n","import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { basename, join } from 'node:path';\nimport { type IsAlive, pidIsAlive } from './pid.js';\n\n/**\n * Which previews are running out of a given host directory.\n *\n * One host directory is shared by every node package on the machine, so devkit has\n * to be able to answer \"is someone else already using it?\" — both to refuse a\n * second preview unless it was asked for, and to refuse a `--force` reinstall that\n * would swap `node_modules` out from under a running dev server.\n *\n * Stored as one file per pid rather than a single JSON document: two previews\n * starting at once would otherwise read-modify-write over each other, and the\n * failure mode of a lost registration is exactly the collision this prevents.\n */\n\nconst REGISTRY_DIR = 'previews';\n\nexport interface PreviewEntry {\n pid: number;\n /** The node package being previewed — what the user needs in order to recognise it. */\n cwd: string;\n mockPort: number;\n /**\n * The port the Nuxt child was told to use. Nuxt relocates on its own if it lost\n * the race for it, so this is the intended port, not a guaranteed one.\n */\n uiPort: number;\n startedAt: string;\n}\n\n/**\n * Live entries, with dead ones deleted as a side effect.\n *\n * Cleaning up on read is deliberate: a preview killed with SIGKILL never gets to\n * deregister, and a registry that only grows would refuse every future preview.\n */\nexport function readLivePreviews(hostDir: string, isAlive: IsAlive = pidIsAlive): PreviewEntry[] {\n const dir = join(hostDir, REGISTRY_DIR);\n if (!existsSync(dir)) {\n return [];\n }\n const live: PreviewEntry[] = [];\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.json')) {\n continue;\n }\n const path = join(dir, file);\n const entry = readEntry(path);\n if (entry && isAlive(entry.pid)) {\n live.push(entry);\n } else {\n // Unreadable or dead — either way it can never become valid again.\n rmSync(path, { force: true });\n }\n }\n return live.sort((a, b) => a.startedAt.localeCompare(b.startedAt));\n}\n\nfunction readEntry(path: string): PreviewEntry | null {\n try {\n const parsed = JSON.parse(readFileSync(path, 'utf-8')) as PreviewEntry;\n return Number.isInteger(parsed?.pid) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function registerPreview(hostDir: string, entry: PreviewEntry): void {\n const dir = join(hostDir, REGISTRY_DIR);\n mkdirSync(dir, { recursive: true });\n writeFileSync(join(dir, `${entry.pid}.json`), `${JSON.stringify(entry, null, 2)}\\n`, 'utf-8');\n}\n\nexport function unregisterPreview(hostDir: string, pid: number = process.pid): void {\n rmSync(join(hostDir, REGISTRY_DIR, `${pid}.json`), { force: true });\n}\n\n/** One line per running preview, for the refusal message and the startup banner. */\nexport function describePreview(entry: PreviewEntry): string {\n return `${basename(entry.cwd)} (PID ${entry.pid}, mock :${entry.mockPort}, UI :${entry.uiPort}) — ${entry.cwd}`;\n}\n\nexport interface ConflictOptions {\n /** The repo about to be previewed. */\n cwd: string;\n /** Whether `--parallel` was given. */\n parallel: boolean;\n /** Whether this run would reinstall the shared dependency tree. */\n force?: boolean;\n hostDir: string;\n}\n\n/**\n * Why this preview must not start, or null if it may.\n *\n * A pure function so the decision is testable — `preview` itself only turns the\n * message into a {@link CliError}. Three cases, in order of severity:\n */\nexport function previewConflict(running: PreviewEntry[], options: ConflictOptions): string | null {\n // Same repo twice: the build dir, Vite cache and dotenv file are all keyed by cwd,\n // so a second run would compile into the first one's build and serve its app. That\n // is the failure --parallel exists to make safe, so --parallel cannot license it.\n const sameRepo = running.find(entry => entry.cwd === options.cwd);\n if (sameRepo) {\n return [\n `A preview of this very package is already running: ${describePreview(sameRepo)}`,\n '',\n \"Two previews of one package share a build directory and would serve each other's\",\n 'output, so this is refused even with --parallel. Stop that one first.',\n ].join('\\n');\n }\n\n if (options.force && running.length > 0) {\n return `--force reinstalls the host's dependencies, which would pull node_modules out from under the preview still running in ${running[0]?.cwd}. Stop it first.`;\n }\n\n if (running.length > 0 && !options.parallel) {\n return [\n `A preview is already running out of ${options.hostDir}:`,\n ...running.map(entry => ` ${describePreview(entry)}`),\n '',\n 'Stop it (Ctrl-C in its terminal), or run this one alongside it with --parallel.',\n ].join('\\n');\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA8BA,SAAS,cAAAA,aAAY,eAAAC,cAAa,gBAAAC,eAAc,aAAa;AAE7D,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,YAAAC,WAAU,SAAS,QAAAC,OAAM,WAAAC,gBAAe;AACjD,SAAS,iBAAAC,sBAAqB;;;ACnC9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe;;;ACAxB,S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C,GAAG,kCAAkC;AAC3F;AAAA,EACF;AACA,MAAI,YAAY,WAAW;AACzB,UAAM,QAAQ,OAAO;AACrB;AAAA,EACF;AACA,QAAM,IAAI,OAAO;AACnB;AAEA,KAAK,EAAE,MAAM,SAAO;AAGlB,UAAQ,MAAM,eAAe,WAAW,IAAI,UAAU,GAAG;AACzD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","readdirSync","readFileSync","createServer","basename","join","resolve","fileURLToPath","existsSync","resolve","existsSync","resolve","existsSync","mkdirSync","readFileSync","readdirSync","rmSync","writeFileSync","join","join","existsSync","readdirSync","rmSync","readFileSync","mkdirSync","writeFileSync","fileURLToPath","resolve","existsSync","readdirSync","readFileSync","join","relative","createServer","basename","envFile","rmSync"]}
|
|
1
|
+
{"version":3,"sources":["../src/cli.ts","../src/cli-args.ts","../src/ports.ts","../src/preview/child-env.ts","../src/preview/host.ts","../src/preview/pid.ts","../src/preview/registry.ts"],"sourcesContent":["#!/usr/bin/env node\n/**\n * `integrations-devkit` — local mock Integrations API + preview for a node package.\n *\n * integrations-devkit # start the mock API (+ static UI via --ui)\n * integrations-devkit preview # run the Nuxt host together with the mock\n * integrations-devkit init-preview --dir # take an unmanaged copy of the host to hack on\n * integrations-devkit reset # delete the persisted session overlay\n *\n * The preview host is NOT placed in your repo. It is copied into a version-keyed\n * cache directory (see src/preview/host.ts), so every repo on this machine shares\n * one dependency install and a devkit upgrade can never leave a stale host behind.\n *\n * Options:\n * --dir <path> use this host dir instead of the managed cache (unmanaged)\n * --force re-copy the host even if the target looks complete\n * --parallel allow a second preview next to one already running\n * --entry <path> package entry (default: src/index.ts, else dist/index.js)\n * --seed <dir> committed seeds dir (default: dev/seeds)\n * --state <file> session overlay file (default: .revenexx-dev/state.json)\n * --no-persist do not write the session overlay (in-memory only)\n * --port <n> listen port (default: $PORT or 3555; the default relocates\n * when taken, an explicit one is reported as a conflict)\n * --ui <dir> static UI build dir to serve (default: resolve the UI package)\n * --no-ui run API-only, do not serve a UI\n * --open open the preview in a browser\n * --env <path> env file to load *instead of* .env (default: .env when present)\n * --no-env do not load any env file\n */\n\nimport { existsSync, readdirSync, readFileSync, watch } from 'node:fs';\nimport type http from 'node:http';\nimport { createServer } from 'node:http';\nimport { createRequire } from 'node:module';\nimport { basename, extname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { type CliOptions, parseArgs } from './cli-args.js';\nimport { loadEnvFile } from './env.js';\nimport { CliError } from './errors.js';\nimport { DEVKIT_VERSION } from './index.js';\nimport { isReloadableSource, type LoadedPackage, loadPackageFromEntry } from './loader.js';\nimport { applySeeds, loadSeedsFromDir, loadState, saveState } from './persistence.js';\nimport { previewChildEnv } from './preview/child-env.js';\nimport { clearHostInstallMarker, hostBuildDir, hostDotenvName, hostNeedsInstall, hostViteCacheDir, markHostInstalled, materializeHost, resolveHostDir, withInstallLock } from './preview/host.js';\nimport { describePreview, previewConflict, readLivePreviews, registerPreview, unregisterPreview } from './preview/registry.js';\nimport { findFreePort, listenWithFallback } from './ports.js';\nimport { createRequestListener } from './server.js';\nimport { DevStore } from './store.js';\n\n/** Loads any JSON schemas bundled in the package's `assets/schemas` dir. */\nfunction loadSchemas(): Record<string, unknown> {\n const here = fileURLToPath(new URL('.', import.meta.url));\n // dist/cli.js → package root is one level up.\n const schemasDir = resolve(here, '..', 'assets', 'schemas');\n const schemas: Record<string, unknown> = {};\n if (!existsSync(schemasDir)) {\n return schemas;\n }\n for (const file of readdirSync(schemasDir)) {\n if (extname(file) !== '.json') {\n continue;\n }\n const parsed = JSON.parse(readFileSync(join(schemasDir, file), 'utf-8'));\n // File `node-v0-draft.json` → keys `node/v0-draft` and (latest) `node`.\n // Split on the first dash only: domain=`node`, version=`v0-draft`.\n const base = file.replace(/\\.json$/, '');\n const dash = base.indexOf('-');\n if (dash > 0) {\n const domain = base.slice(0, dash);\n const version = base.slice(dash + 1);\n schemas[`${domain}/${version}`] = parsed;\n schemas[domain] = parsed;\n } else {\n schemas[base] = parsed;\n }\n }\n return schemas;\n}\n\n/**\n * Resolves a *static* UI build dir to serve. Only used for a prebuilt SPA\n * passed via `--ui`. The Cockpit UI (`@revenexx/studio-integrations`) is a Nuxt\n * *module*, not a static build — it is consumed by a Nuxt host app whose\n * `runtimeConfig.public.integrationsApi` points at this mock (see README).\n * Auto-resolution only kicks in for a package that ships a `dist/` with an\n * `index.html`; otherwise the devkit stays API-only.\n */\nfunction resolveUiDir(explicit: string | null): string | null {\n if (explicit) {\n return existsSync(explicit) ? explicit : null;\n }\n const candidates = ['@revenexx/studio-integrations'];\n const req = createRequire(import.meta.url);\n for (const pkg of candidates) {\n try {\n const entry = req.resolve(`${pkg}/package.json`);\n const dist = resolve(entry, '..', 'dist');\n if (existsSync(join(dist, 'index.html'))) {\n return dist;\n }\n } catch {\n // not installed / not a static build — fall through to API-only\n }\n }\n return null;\n}\n\nconst MIME: Record<string, string> = {\n '.html': 'text/html',\n '.js': 'text/javascript',\n '.mjs': 'text/javascript',\n '.css': 'text/css',\n '.json': 'application/json',\n '.svg': 'image/svg+xml',\n '.png': 'image/png',\n '.ico': 'image/x-icon',\n '.woff2': 'font/woff2',\n};\n\n/** Serves a static SPA build, falling back to index.html for client routes. */\nfunction serveStatic(uiDir: string, req: http.IncomingMessage, res: http.ServerResponse): void {\n const url = new URL(req.url ?? '/', 'http://localhost');\n const relative = url.pathname === '/' ? 'index.html' : url.pathname.replace(/^\\/+/, '');\n let filePath = resolve(uiDir, relative);\n if (!filePath.startsWith(uiDir) || !existsSync(filePath)) {\n filePath = join(uiDir, 'index.html');\n }\n if (!existsSync(filePath)) {\n res.writeHead(404).end('UI build not found');\n return;\n }\n res.writeHead(200, { 'Content-Type': MIME[extname(filePath)] ?? 'application/octet-stream' });\n res.end(readFileSync(filePath));\n}\n\ninterface MockHandle {\n uiDir: string | null;\n /** The port actually bound, which is not necessarily the one that was asked for. */\n port: number;\n dispose(): void;\n}\n\n/** Boots the mock API (store + seeds + persistence + hot-reload). No signal handlers. */\nasync function startMock(options: CliOptions): Promise<MockHandle> {\n let loaded: LoadedPackage = await loadPackageFromEntry(options.entry);\n console.log(`Loaded ${loaded.nodes.length} node(s), ${loaded.credentials.length} credential(s), ${loaded.templates.length} template(s) from ${options.entry}`);\n\n const store = new DevStore();\n applySeeds(store, await loadSeedsFromDir(options.seedDir));\n if (options.persist) {\n const state = loadState(options.stateFile);\n if (state) {\n store.mergeSnapshot(state);\n console.log(`Restored session from ${options.stateFile}`);\n }\n // Attach persistence only now, so applying seeds doesn't rewrite the overlay.\n let timer: NodeJS.Timeout | undefined;\n store.setOnMutation(() => {\n clearTimeout(timer);\n timer = setTimeout(() => saveState(options.stateFile, store.toSnapshot()), 150);\n });\n }\n\n const schemas = loadSchemas();\n const apiListener = createRequestListener({ getPackage: () => loaded, store, schemas });\n\n const uiDir = options.serveUi ? resolveUiDir(options.uiDir) : null;\n const server = createServer((req, res) => {\n const pathname = new URL(req.url ?? '/', 'http://localhost').pathname;\n if (pathname.startsWith('/api/') || pathname === '/health') {\n apiListener(req, res);\n } else if (uiDir) {\n serveStatic(uiDir, req, res);\n } else {\n res.writeHead(404, { 'Content-Type': 'application/json' }).end(\n JSON.stringify({\n message: 'API-only. Point your Nuxt host (studio-integrations) integrationsApi at this URL, or pass --ui <static-build-dir>. CORS is open.',\n }),\n );\n }\n });\n\n const port = await listenWithFallback(server, { port: options.port, strict: options.portExplicit });\n if (port !== options.port) {\n console.log(`Port ${options.port} was taken — the mock is on ${port} instead.`);\n }\n\n const stopWatch = watchAndReload(options.entry, async () => {\n try {\n loaded = await loadPackageFromEntry(options.entry);\n console.log(`↻ Reloaded package (${loaded.nodes.length} nodes, ${loaded.credentials.length} credentials).`);\n } catch (err) {\n console.error(`Reload failed: ${(err as Error).message}`);\n }\n });\n\n return {\n uiDir,\n port,\n dispose() {\n if (options.persist) {\n saveState(options.stateFile, store.toSnapshot());\n }\n stopWatch?.();\n server.close();\n },\n };\n}\n\n/** Interactive mock server (API + optional static UI). */\nasync function run(options: CliOptions): Promise<void> {\n const mock = await startMock(options);\n const urlBase = `http://localhost:${mock.port}`;\n console.log(`\\n Mock Integrations API ${urlBase}/api/v1`);\n console.log(mock.uiDir ? ` Preview UI ${urlBase}` : ` Preview UI API-only — set your Nuxt host's integrationsApi to ${urlBase}/api/v1`);\n console.log('\\n Watching for changes. Ctrl-C to stop.\\n');\n\n if (options.open && mock.uiDir) {\n void openBrowser(urlBase);\n }\n\n const shutdown = () => {\n mock.dispose();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n}\n\n/** Watches the entry's directory tree and fires `onChange` (debounced). Returns a stop fn. */\nfunction watchAndReload(entry: string, onChange: () => void): (() => void) | undefined {\n const dir = resolve(entry, '..');\n let timer: NodeJS.Timeout | undefined;\n try {\n const watcher = watch(dir, { recursive: true }, (_event, file) => {\n if (file && isReloadableSource(file.toString())) {\n clearTimeout(timer);\n timer = setTimeout(onChange, 200);\n }\n });\n return () => watcher.close();\n } catch {\n // Recursive watch unsupported on this platform — skip hot-reload.\n console.warn('Hot-reload unavailable on this platform; restart to pick up changes.');\n return undefined;\n }\n}\n\n/** Runs `npm install` in `dir`, inheriting stdio. */\nasync function runNpmInstall(dir: string): Promise<void> {\n const { spawn } = await import('node:child_process');\n await new Promise<void>((resolvePromise, reject) => {\n const child = spawn('npm', ['install'], { cwd: dir, stdio: 'inherit' });\n child.on('exit', code => (code === 0 ? resolvePromise() : reject(new Error(`npm install exited with code ${code}`))));\n child.on('error', reject);\n });\n}\n\n/**\n * Warns about a `.revenexx-dev/preview` left over from before the host moved into\n * the shared cache. Not deleted automatically — it is the user's directory, and it\n * may hold edits they want to keep.\n */\nfunction noteLegacyPreviewDir(): void {\n const legacy = resolve(process.cwd(), '.revenexx-dev/preview');\n if (existsSync(legacy)) {\n console.log(`Note: ${legacy} is no longer used — the preview host now lives in a shared cache. You can delete it to reclaim the space.`);\n }\n}\n\n/** Default port for the Nuxt dev server, matching Nuxt's own. */\nconst UI_PORT = 3000;\n\n/** Materializes (if needed), installs, and runs the Nuxt preview host + the mock together. */\nasync function preview(options: CliOptions): Promise<void> {\n const cwd = process.cwd();\n const managed = options.previewDir === null;\n const hostDir = resolve(options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION }));\n\n // Before anything is bound or copied: a second preview is usually a forgotten\n // one from an earlier session, not a deliberate one.\n const running = readLivePreviews(hostDir);\n const conflict = previewConflict(running, { cwd, hostDir, parallel: options.parallel, force: options.force });\n if (conflict) {\n throw new CliError(conflict);\n }\n\n noteLegacyPreviewDir();\n\n // Bind the mock BEFORE copying and installing. A port clash or an entry that\n // does not load then costs seconds, instead of surfacing after a multi-minute\n // `npm install` with a Nuxt child already on the way.\n const mock = await startMock({ ...options, serveUi: false });\n const apiUrl = `http://localhost:${mock.port}/api/v1`;\n\n try {\n const { dir } = materializeHost({\n targetDir: hostDir,\n integrationsApiUrl: apiUrl,\n dotenvName: managed ? hostDotenvName(cwd) : undefined,\n force: options.force,\n managed,\n log: msg => console.log(msg),\n });\n\n if (options.force) {\n // `hostNeedsInstall` already reinstalls when the pins changed, so this is not\n // that case — it is the escape hatch --force is documented to be: an install\n // that reported success but left an unusable tree has no other way out short\n // of deleting the directory.\n clearHostInstallMarker(dir);\n }\n if (hostNeedsInstall(dir)) {\n await withInstallLock(\n dir,\n async () => {\n console.log('Installing preview-host dependencies (this pulls Nuxt + the studio packages and may take a while)…');\n await runNpmInstall(dir);\n markHostInstalled(dir);\n },\n { needsInstall: () => hostNeedsInstall(dir), log: msg => console.log(msg) },\n );\n }\n\n // Honour an explicit NUXT_PORT; otherwise take the first free port. Nuxt's own\n // listhen fallback still covers the gap between this check and its bind, which\n // is why the URL below is Nuxt's to print, not ours.\n const uiPort = process.env.NUXT_PORT ? Number(process.env.NUXT_PORT) : await findFreePort(UI_PORT);\n\n console.log(`\\n Previewing ${basename(cwd)} (${cwd})`);\n console.log(` Mock Integrations API ${apiUrl}`);\n if (managed) {\n console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);\n }\n console.log(` Preview UI starting on port ${uiPort} — Nuxt prints the URL it got, below.`);\n for (const entry of running) {\n console.log(` Also running ${describePreview(entry)}`);\n }\n console.log('');\n\n const { spawn } = await import('node:child_process');\n // The managed host reads a per-repo dotenv file, so it has to be named. An\n // unmanaged copy keeps plain `.env`, which Nuxt picks up on its own.\n const args = managed ? ['run', 'dev', '--', '--dotenv', hostDotenvName(cwd)] : ['run', 'dev'];\n const child = spawn('npm', args, {\n cwd: dir,\n stdio: 'inherit',\n env: previewChildEnv({\n base: process.env,\n apiUrl,\n uiPort,\n buildDir: hostBuildDir(dir, cwd),\n viteCacheDir: hostViteCacheDir(dir, cwd),\n }),\n });\n\n registerPreview(dir, { pid: process.pid, cwd, mockPort: mock.port, uiPort, startedAt: new Date().toISOString() });\n const cleanUp = () => {\n unregisterPreview(dir);\n mock.dispose();\n };\n\n const shutdown = () => {\n child.kill('SIGTERM');\n cleanUp();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n child.on('exit', code => {\n cleanUp();\n process.exit(code ?? 0);\n });\n } catch (err) {\n // The mock is already listening at this point; leaving it bound would make the\n // next attempt look like a port conflict.\n mock.dispose();\n throw err;\n }\n}\n\nasync function openBrowser(url: string): Promise<void> {\n const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'start' : 'xdg-open';\n const { spawn } = await import('node:child_process');\n spawn(cmd, [url], { stdio: 'ignore', detached: true }).unref();\n}\n\nasync function main(): Promise<void> {\n const argv = process.argv.slice(2);\n // Before parseArgs: it reads `PORT`, and seeds interpolate `${VAR}` from the\n // environment once the mock starts.\n const envFile = loadEnvFile(argv);\n const { command, options } = parseArgs(argv);\n if (command === 'version') {\n console.log(DEVKIT_VERSION);\n return;\n }\n if (envFile) {\n console.log(`Loaded env from ${envFile}`);\n }\n if (command === 'reset') {\n const { rmSync } = await import('node:fs');\n rmSync(options.stateFile, { force: true });\n console.log(`Removed ${options.stateFile}`);\n return;\n }\n if (command === 'init-preview') {\n // The managed host is a disposable artifact `preview` handles on its own, so\n // this command only makes sense for taking a copy you intend to change.\n if (options.previewDir === null) {\n console.error('init-preview needs an explicit target: `integrations-devkit init-preview --dir ./my-preview`.');\n console.error('It exists to give you an UNMANAGED copy of the preview host to modify. For the normal preview, just run `integrations-devkit preview` —');\n console.error('that materializes the host into a shared cache and keeps it in step with the devkit version.');\n process.exit(1);\n }\n const { dir } = materializeHost({\n targetDir: options.previewDir,\n integrationsApiUrl: `http://localhost:${options.port}/api/v1`,\n force: options.force,\n log: msg => console.log(msg),\n });\n console.log('\\nThis copy is yours and will NOT be updated by devkit upgrades.');\n console.log(`Run it with: \\`cd ${dir} && npm install && npm run dev\\` (plus \\`integrations-devkit --no-ui\\` for the mock),`);\n console.log(`or \\`integrations-devkit preview --dir ${dir}\\` to have both started for you.`);\n return;\n }\n if (command === 'preview') {\n await preview(options);\n return;\n }\n await run(options);\n}\n\nmain().catch(err => {\n // A CliError is a message for the user, not a defect: print the message alone.\n // Anything else keeps its stack, which is the only useful thing about it.\n console.error(err instanceof CliError ? err.message : err);\n process.exit(1);\n});\n","import { existsSync } from 'node:fs';\nimport { resolve } from 'node:path';\nimport { CliError } from './errors.js';\nimport { parsePort } from './ports.js';\n\n/**\n * Argument parsing, kept apart from `cli.ts` so it can be tested.\n *\n * `cli.ts` runs `main()` on import, so anything reachable only from there is\n * unreachable from a test. This function is pure — it throws {@link CliError}\n * instead of calling `process.exit`, and reads the environment but never writes it.\n */\n\nexport interface CliOptions {\n entry: string;\n seedDir: string;\n stateFile: string;\n persist: boolean;\n port: number;\n /**\n * True when the port was named by the user (`--port` or `$PORT`). An explicit\n * port is honoured or reported as a conflict; only the default may relocate.\n */\n portExplicit: boolean;\n uiDir: string | null;\n serveUi: boolean;\n open: boolean;\n /** Explicit host directory from `--dir`; null means use the managed cache. */\n previewDir: string | null;\n /** Re-copy the host even when the target looks complete. */\n force: boolean;\n /** Allow a second preview alongside one that is already running. */\n parallel: boolean;\n}\n\nexport const DEFAULT_PORT = 3555;\n\nexport function parseArgs(argv: string[], env: NodeJS.ProcessEnv = process.env): { command: string | null; options: CliOptions } {\n const cwd = process.cwd();\n const opts: CliOptions = {\n entry: '',\n seedDir: resolve(cwd, 'dev/seeds'),\n stateFile: resolve(cwd, '.revenexx-dev/state.json'),\n persist: true,\n port: env.PORT === undefined ? DEFAULT_PORT : parsePort(env.PORT, '$PORT'),\n portExplicit: env.PORT !== undefined,\n uiDir: null,\n serveUi: true,\n open: false,\n previewDir: null,\n force: false,\n parallel: false,\n };\n let command: string | null = null;\n for (let i = 0; i < argv.length; i++) {\n const arg = argv[i];\n switch (arg) {\n case 'reset':\n command = 'reset';\n break;\n case 'init-preview':\n command = 'init-preview';\n break;\n case 'preview':\n command = 'preview';\n break;\n case '--dir':\n opts.previewDir = resolve(cwd, argv[++i] ?? '');\n break;\n case '--force':\n opts.force = true;\n break;\n case '--parallel':\n opts.parallel = true;\n break;\n case '--entry':\n opts.entry = resolve(cwd, argv[++i] ?? '');\n break;\n case '--seed':\n opts.seedDir = resolve(cwd, argv[++i] ?? '');\n break;\n case '--state':\n opts.stateFile = resolve(cwd, argv[++i] ?? '');\n break;\n case '--no-persist':\n opts.persist = false;\n break;\n case '--port':\n // A missing or non-numeric value used to fall back to the default or reach\n // `listen(NaN)`; both hid a typo the user would rather be told about.\n opts.port = parsePort(argv[++i], '--port');\n opts.portExplicit = true;\n break;\n case '--ui':\n opts.uiDir = resolve(cwd, argv[++i] ?? '');\n break;\n case '--no-ui':\n opts.serveUi = false;\n break;\n case '--open':\n opts.open = true;\n break;\n // Both are consumed by loadEnvFile() before parsing; listed here so they\n // do not fall through to the unknown-option branch. A repeated `--env`\n // resolves to the last one, so each occurrence skips its own value.\n case '--env':\n i++;\n break;\n case '--no-env':\n break;\n case '--version':\n case '-v':\n command = 'version';\n break;\n default:\n // Node acts on `--env-file[-if-exists]` itself but still forwards it\n // here, so accept and skip it rather than rejecting the user's input.\n // loadEnvFile() has already pointed them at `--env`.\n if (arg?.startsWith('--env-file')) {\n if (!arg.includes('=')) {\n i++;\n }\n break;\n }\n if (arg?.startsWith('-')) {\n throw new CliError(`Unknown option: ${arg}`);\n }\n }\n }\n if (!opts.entry) {\n const src = resolve(cwd, 'src/index.ts');\n opts.entry = existsSync(src) ? src : resolve(cwd, 'dist/index.js');\n }\n return { command, options: opts };\n}\n","import type { Server } from 'node:http';\nimport { createServer } from 'node:net';\nimport { CliError } from './errors.js';\n\n/**\n * Port allocation for the mock API and the Nuxt dev server.\n *\n * Two rules shape this module:\n *\n * - **Bind, do not probe.** Asking \"is this port free?\" and then binding it is a\n * race against every other process on the machine. The mock therefore binds for\n * real and moves on only after an actual `EADDRINUSE`. (The Nuxt port cannot\n * work that way — a child process binds it — so `findFreePort` does probe, and\n * listhen's own fallback is the backstop for the window in between.)\n * - **A named port is a promise, not a preference.** `--port 4000` or `PORT=4000`\n * means 4000; if it is taken, that is an error, not an invitation to pick 4001.\n * Only the default may wander, because nothing outside devkit depends on it.\n */\n\n/** How many consecutive ports to try before giving up. */\nconst DEFAULT_LIMIT = 20;\n\nexport interface ListenOptions {\n port: number;\n /** True when the port was named explicitly (`--port` / `$PORT`): never relocate. */\n strict: boolean;\n limit?: number;\n}\n\n/**\n * Binds `server`, walking up from `options.port` on `EADDRINUSE`. Resolves with the\n * port actually bound — callers must use that value rather than the one they asked\n * for, since every URL they print or hand to a child process depends on it.\n */\nexport async function listenWithFallback(server: Server, options: ListenOptions): Promise<number> {\n const limit = options.strict ? 1 : (options.limit ?? DEFAULT_LIMIT);\n const first = options.port;\n for (let port = first; port < first + limit; port += 1) {\n const bound = await bind(server, port);\n if (bound !== null) {\n return bound;\n }\n }\n throw options.strict\n ? new CliError(`Port ${first} is already in use. Stop whatever is holding it, or pass a different --port.`)\n : new CliError(`No free port between ${first} and ${first + limit - 1}. Pass --port <n> to choose one explicitly.`);\n}\n\n/** Resolves with the bound port, or null when the port is taken. */\nfunction bind(server: Server, port: number): Promise<number | null> {\n return new Promise((resolvePort, reject) => {\n const onError = (err: NodeJS.ErrnoException) => {\n server.removeListener('listening', onListening);\n if (err.code === 'EADDRINUSE') {\n resolvePort(null);\n return;\n }\n reject(err);\n };\n const onListening = () => {\n server.removeListener('error', onError);\n const address = server.address();\n resolvePort(typeof address === 'object' && address !== null ? address.port : port);\n };\n server.once('error', onError);\n server.once('listening', onListening);\n server.listen(port);\n });\n}\n\n/**\n * First free port at or above `base`, found by binding a throwaway listener.\n *\n * For ports someone else will bind — the Nuxt dev server runs as a child process.\n * The gap between this check and that bind is a real (if narrow) race; Nuxt's own\n * listhen fallback covers it, which is why devkit no longer prints the UI URL\n * itself and lets Nuxt announce the port it truly got.\n */\nexport async function findFreePort(base: number, limit = DEFAULT_LIMIT): Promise<number> {\n for (let port = base; port < base + limit; port += 1) {\n if (await isFree(port)) {\n return port;\n }\n }\n throw new CliError(`No free port between ${base} and ${base + limit - 1} for the preview UI.`);\n}\n\nfunction isFree(port: number): Promise<boolean> {\n return new Promise(resolveFree => {\n const probe = createServer();\n probe.once('error', () => resolveFree(false));\n probe.once('listening', () => probe.close(() => resolveFree(true)));\n probe.listen(port);\n });\n}\n\n/** Parses a `--port` value, rejecting what would otherwise reach `listen()` as NaN. */\nexport function parsePort(value: string | undefined, flag: string): number {\n if (value === undefined || value.startsWith('-')) {\n throw new CliError(`${flag} needs a port number, e.g. \\`${flag} 4000\\`.`);\n }\n const port = Number(value);\n if (!Number.isInteger(port) || port < 1 || port > 65535) {\n throw new CliError(`${flag} expects an integer between 1 and 65535, got \\`${value}\\`.`);\n }\n return port;\n}\n","export interface PreviewChildEnvOptions {\n /** Usually `process.env`. */\n base: NodeJS.ProcessEnv;\n /** Mock API base URL, including the port actually bound. */\n apiUrl: string;\n /** Per-repo Nuxt build directory (`hostBuildDir`). */\n buildDir: string;\n /** Per-repo Vite dependency cache (`hostViteCacheDir`). */\n viteCacheDir: string;\n /** Port the Nuxt dev server should listen on. */\n uiPort: number;\n}\n\n/**\n * Environment for the `nuxt dev` child process.\n *\n * A pure function because the three things it gets right are all invisible at a\n * glance, and each of them was a bug:\n *\n * - **`PORT` is deleted.** It is the mock's variable, but Nuxt's listhen reads it\n * too, so `PORT=4000 integrations-devkit preview` used to have the mock *and*\n * the UI both claim 4000. Nuxt then relocated silently and every URL devkit\n * printed was wrong. `NUXT_PORT` outranks `PORT` anyway; deleting it as well\n * keeps the mock's port out of the child's namespace entirely.\n * - **`DEVKIT_VITE_CACHE_DIR` is set.** Without it Vite's dependency cache lands\n * in the *shared* host's `node_modules/.cache/vite`, and since Vite's config\n * hash includes the `#build` alias — i.e. the per-repo build dir — two repos\n * each consider the other's cache stale and `rm -rf` it while it is being\n * served from. Per-repo build dirs alone actively caused that.\n * - **`NUXT_PORT` is set explicitly**, so devkit knows the UI port instead of\n * guessing 3000 and hoping listhen agreed.\n */\nexport function previewChildEnv(options: PreviewChildEnvOptions): NodeJS.ProcessEnv {\n const env = { ...options.base };\n delete env.PORT;\n return {\n ...env,\n NUXT_PUBLIC_INTEGRATIONS_API: options.apiUrl,\n NUXT_PUBLIC_DEV_TOKEN: options.base.NUXT_PUBLIC_DEV_TOKEN ?? 'dev',\n NUXT_PUBLIC_DEV_TENANT: options.base.NUXT_PUBLIC_DEV_TENANT ?? 'dev-tenant',\n NUXT_PORT: String(options.uiPort),\n DEVKIT_NUXT_BUILD_DIR: options.buildDir,\n DEVKIT_VITE_CACHE_DIR: options.viteCacheDir,\n };\n}\n","import { createHash } from 'node:crypto';\nimport { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { CliError } from '../errors.js';\nimport { type IsAlive, pidIsAlive } from './pid.js';\n\n/**\n * The Nuxt preview host ships as real files in the devkit package (`preview-host/`)\n * and is copied into a version-keyed directory at run time. It is deliberately NOT\n * placed inside the consuming repo:\n *\n * - A per-repo copy is never refreshed (the old scaffold only checked whether\n * two filenames existed), so a devkit upgrade silently left a broken host\n * behind — unfixable for external node-package authors.\n * - Every repo paid for its own ~500 MB dependency tree of the same packages.\n * - Keying the directory by devkit version makes staleness structurally\n * impossible: a new devkit version means a new directory.\n *\n * The copy is therefore a disposable artifact, not something to edit. Authors who\n * want to hack on the host take an explicit unmanaged copy with\n * `integrations-devkit init-preview --dir ./my-preview`.\n */\n\n/** Marker written after a *successful* dependency install. */\nconst INSTALL_MARKER = '.devkit-install-complete';\n\n/**\n * Marker written after the file copy finished, holding a fingerprint of the source\n * it copied. Without it, \"is the host here?\" would again be \"do two filenames\n * exist\" — the same check whose weakness this module exists to fix, only for the\n * copy instead of the install: `cpSync` is not atomic, so an interrupted copy can\n * leave `package.json` and `nuxt.config.ts` behind while the rest is missing, and\n * that half-host would be treated as intact forever.\n *\n * The fingerprint covers the second half of the same problem. Keying the directory\n * by devkit version makes a stale host impossible *between releases*, but says\n * nothing while the version stands still — so anyone working on `preview-host/`\n * itself, this repo's own developers included, silently kept running the copy from\n * before their change. Comparing the source instead of trusting the version keeps\n * that honest, and costs nothing: the dependency install is keyed separately, so a\n * changed host file re-copies without reinstalling.\n */\nconst COPY_MARKER = '.devkit-copy-complete';\n\n/** Lock held while `npm install` runs, so two repos cannot install over each other. */\nconst INSTALL_LOCK = '.devkit-install.lock';\n\n/** Files generated into the target rather than shipped, since they carry runtime values. */\nconst HOST_GITIGNORE = `node_modules/\n.nuxt/\n.nuxt-*/\n.vite-*/\n.output/\n.data/\n.env*\npreviews/\n${COPY_MARKER}\n${INSTALL_MARKER}\n${INSTALL_LOCK}\n`;\n\nexport interface HostDirOptions {\n /** Devkit version; keys the cache directory. */\n version: string;\n /** Overrides the whole cache location (mainly for tests). */\n cacheRoot?: string;\n}\n\n/**\n * Cache location for the managed host: `<cache>/revenexx/devkit-preview/<version>`.\n * Honours `XDG_CACHE_HOME`, falling back to `~/.cache`.\n */\nexport function resolveHostDir(options: HostDirOptions): string {\n const root = options.cacheRoot ?? process.env.XDG_CACHE_HOME ?? join(homedir(), '.cache');\n return join(root, 'revenexx', 'devkit-preview', options.version);\n}\n\n/**\n * Absolute path of the `preview-host/` directory shipped inside this package.\n *\n * Walks up from this module rather than assuming a fixed depth, because the\n * module sits at `dist/cli.js` in the published package but at\n * `src/preview/host.ts` when running from source (tsx, vitest).\n */\nexport function shippedHostDir(): string {\n let dir = dirname(fileURLToPath(import.meta.url));\n for (let up = 0; up < 5; up += 1) {\n const candidate = join(dir, 'preview-host');\n if (existsSync(join(candidate, 'nuxt.config.ts'))) {\n return candidate;\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n throw new Error('Preview host not found: no preview-host/nuxt.config.ts above this module. Reinstall @revenexx/integrations-node-devkit.');\n}\n\nexport interface MaterializeHostOptions {\n /** Where to put the host. */\n targetDir: string;\n /** Overrides the shipped host to copy from (mainly for tests). */\n sourceDir?: string;\n /** Mock API base URL written into the generated `.env`. */\n integrationsApiUrl: string;\n /** Dev token/tenant written into the generated `.env`. */\n devToken?: string;\n devTenant?: string;\n /** Re-copy even when the target already looks complete. */\n force?: boolean;\n /**\n * Name of the generated dotenv file. Defaults to `.env`; `preview` passes a\n * per-repo name for the managed cache (see {@link hostDotenvName}).\n */\n dotenvName?: string;\n /**\n * True for the version-keyed cache directory devkit owns, false for a `--dir`\n * copy that belongs to the user. Decides two things: whether an incomplete copy\n * may be redone (safe when devkit owns the directory, destructive when the user\n * does), and whether the generated `.env` / `.gitignore` are rewritten on every\n * run or left alone once they exist.\n */\n managed?: boolean;\n log?: (msg: string) => void;\n}\n\nexport interface MaterializeHostResult {\n dir: string;\n /** True when files were (re-)copied; false when an intact copy was reused. */\n copied: boolean;\n}\n\n/**\n * Copies the shipped host into `targetDir` and writes the generated files.\n *\n * The copy is wholesale rather than per-file. For the managed cache that is free —\n * nothing in it is worth preserving — so an incomplete copy is simply redone. A\n * `--dir` copy belongs to the user, so there \"the defining files are present\" has\n * to be enough: re-copying over someone's edits to repair a hypothetical\n * interrupted copy would cost more than it saves.\n *\n * `node_modules/` and the install marker survive a re-copy so an unchanged\n * dependency set is not reinstalled for nothing — `hostNeedsInstall` compares the\n * manifest, so changed pins still reinstall.\n */\nexport function materializeHost(options: MaterializeHostOptions): MaterializeHostResult {\n const log = options.log ?? (() => {});\n const source = options.sourceDir ?? shippedHostDir();\n const dir = resolve(options.targetDir);\n const managed = options.managed ?? false;\n // A `--dir` copy belongs to the user: \"the defining files are present\" has to be\n // enough there, because a re-copy would overwrite their edits. The managed cache\n // is devkit's, so it is held to the stricter test — finished, and copied from\n // exactly this source.\n const intact = managed ? hostIsComplete(dir) && copyIsCurrent(dir, source) : hostExists(dir);\n const alreadyIntact = intact && !options.force;\n\n if (!alreadyIntact) {\n mkdirSync(dir, { recursive: true });\n // Never copy a node_modules/ that lives INSIDE the host (present when someone\n // is working on preview-host/ itself) — it is the expensive part and is\n // validated separately via the install marker.\n //\n // The filter must judge the path RELATIVE to the source. Testing the absolute\n // path breaks the moment devkit is installed as a dependency, because the\n // source is then `…/node_modules/@revenexx/integrations-node-devkit/preview-host`\n // and the filter rejects the source root itself — cpSync then copies nothing\n // at all, silently.\n rmSync(join(dir, COPY_MARKER), { force: true });\n cpSync(source, dir, { recursive: true, filter: src => !isInsideNodeModules(source, src) });\n writeFileSync(join(dir, COPY_MARKER), `${sourceFingerprint(source)}\\n${new Date().toISOString()}\\n`, 'utf-8');\n writeFileSync(join(dir, '.gitignore'), HOST_GITIGNORE, 'utf-8');\n log(`Preview host ready in ${dir}`);\n }\n\n // Managed: always refresh, because the API URL depends on --port and the\n // directory is devkit's to maintain. Unmanaged: write it only when it is\n // missing — that copy is the user's, and `preview` passes the same values to\n // the Nuxt child process anyway, so a hand-edited `.env` stays theirs.\n //\n // The managed name is per repo (`.env.<hash>`), and that is not cosmetic: Nuxt\n // watches its dotenv file and does a full respawn when it changes, so a single\n // shared `.env` rewritten on every run restarted every *other* preview running\n // out of this directory. The dedupe is mtime-based, so identical content did not\n // help. A per-repo filename ends the crossfire — instances only watch their own.\n const envPath = join(dir, options.dotenvName ?? '.env');\n if (managed || !existsSync(envPath)) {\n writeFileSync(envPath, envFile(options), 'utf-8');\n }\n\n return { dir, copied: !alreadyIntact };\n}\n\n/** True when `src` sits under a `node_modules/` *within* the copied tree. */\nfunction isInsideNodeModules(source: string, src: string): boolean {\n const rel = relative(source, src);\n return rel !== '' && rel.split(sep).includes('node_modules');\n}\n\n/**\n * Content hash of the shipped host, over paths and bytes. Deliberately not mtimes:\n * reinstalling the devkit rewrites those without changing a thing, and a 500 MB\n * cache directory should not be invalidated by a timestamp.\n */\nfunction sourceFingerprint(source: string): string {\n const hash = createHash('sha256');\n for (const file of listFiles(source, source).sort()) {\n hash.update(file);\n hash.update(readFileSync(join(source, file)));\n }\n return hash.digest('hex').slice(0, 16);\n}\n\nfunction listFiles(root: string, dir: string): string[] {\n const files: string[] = [];\n for (const entry of readdirSync(dir, { withFileTypes: true })) {\n if (entry.name === 'node_modules') {\n continue;\n }\n const full = join(dir, entry.name);\n if (entry.isDirectory()) {\n files.push(...listFiles(root, full));\n } else if (entry.isFile()) {\n files.push(relative(root, full));\n }\n }\n return files;\n}\n\n/** True when the copy in `dir` was made from this exact source. */\nfunction copyIsCurrent(dir: string, source: string): boolean {\n try {\n const recorded = readFileSync(join(dir, COPY_MARKER), 'utf-8').split('\\n')[0]?.trim();\n return recorded === sourceFingerprint(source);\n } catch {\n return false;\n }\n}\n\nfunction envFile(options: MaterializeHostOptions): string {\n const name = options.dotenvName ?? '.env';\n const manual = name === '.env' ? 'npm run dev' : `npm run dev -- --dotenv ${name}`;\n return `# Generated by integrations-devkit — overrides the Nuxt runtimeConfig.public.* values.\n# The \\`preview\\` command also passes these to the Nuxt child process; this file is\n# what makes a manual \\`${manual}\\` in this directory work.\nNUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}\nNUXT_PUBLIC_DEV_TOKEN=${options.devToken ?? 'dev'}\nNUXT_PUBLIC_DEV_TENANT=${options.devTenant ?? 'dev-tenant'}\n`;\n}\n\n/**\n * Stable per-repo key. One host directory serves every node package on the machine,\n * so everything that must not be shared is suffixed with this.\n */\nfunction consumerKey(consumerDir: string): string {\n return createHash('sha256').update(consumerDir).digest('hex').slice(0, 12);\n}\n\n/**\n * Per-consumer Nuxt build directory inside the shared host.\n *\n * The dependency tree is worth sharing; the compiled app is not. Two repos running\n * `preview` concurrently would otherwise build into the same `.nuxt/` and serve\n * each other's app. Keyed by a hash of the consumer's directory so it is stable\n * across runs — the build cache still pays off — and distinct per repo.\n *\n * Necessary but **not sufficient** on its own, and for a while it was worse than\n * that: see {@link hostViteCacheDir}.\n */\nexport function hostBuildDir(hostDir: string, consumerDir: string): string {\n return join(hostDir, `.nuxt-${consumerKey(consumerDir)}`);\n}\n\n/**\n * Per-consumer Vite dependency cache inside the shared host.\n *\n * Vite anchors its `cacheDir` on `rootDir`, not on the build dir, so every repo\n * previewing out of this directory shared one `node_modules/.cache/vite`. That\n * would have been merely wasteful were it not for how Vite invalidates it: the\n * `configHash` covers `resolve.alias`, which contains Nuxt's `#build` alias, which\n * is the per-repo build dir. Two repos therefore each computed a different hash,\n * each judged the other's cache stale, and each ran `rm -rf` on the dependency\n * directory the other was actively serving from — every time, in both directions,\n * until one of them was killed.\n *\n * Overriding `cacheDir` per repo is what actually isolates them. It also pays off\n * sequentially: switching between repos no longer re-optimizes from scratch.\n */\nexport function hostViteCacheDir(hostDir: string, consumerDir: string): string {\n return join(hostDir, `.vite-${consumerKey(consumerDir)}`);\n}\n\n/**\n * Per-consumer dotenv filename inside the shared host.\n *\n * Nuxt watches its dotenv file and treats a change as a reason to respawn, so one\n * shared `.env` — rewritten on every run, because it carries the mock's port —\n * restarted every other preview using this directory.\n */\nexport function hostDotenvName(consumerDir: string): string {\n return `.env.${consumerKey(consumerDir)}`;\n}\n\n/** True when `dir` holds something that looks like a host (its two defining files). */\nexport function hostExists(dir: string): boolean {\n return existsSync(join(dir, 'package.json')) && existsSync(join(dir, 'nuxt.config.ts'));\n}\n\n/**\n * True when `dir` holds a host this devkit finished copying. Stricter than\n * {@link hostExists}, which cannot tell a complete host from the first two files\n * of an interrupted one.\n */\nexport function hostIsComplete(dir: string): boolean {\n return hostExists(dir) && existsSync(join(dir, COPY_MARKER));\n}\n\n/**\n * True when dependencies must be installed.\n *\n * Deliberately not just `existsSync(node_modules)`: that was the root of a real\n * bug — `--force` rewrote `package.json` with new pins, the `node_modules/` check\n * then reported \"installed\", `npm install` was skipped, and Nuxt booted against\n * the old dependency tree. The marker records the manifest the install actually\n * succeeded for, so changed pins and interrupted installs both reinstall.\n */\nexport function hostNeedsInstall(dir: string): boolean {\n const marker = join(dir, INSTALL_MARKER);\n if (!existsSync(join(dir, 'node_modules')) || !existsSync(marker)) {\n return true;\n }\n try {\n return readFileSync(marker, 'utf-8').trim() !== manifestFingerprint(dir);\n } catch {\n return true;\n }\n}\n\n/** Records a successful install for the host's current manifest. */\nexport function markHostInstalled(dir: string): void {\n writeFileSync(join(dir, INSTALL_MARKER), `${manifestFingerprint(dir)}\\n`, 'utf-8');\n}\n\n/** Clears the install marker so the next run reinstalls. */\nexport function clearHostInstallMarker(dir: string): void {\n rmSync(join(dir, INSTALL_MARKER), { force: true });\n}\n\n/**\n * Runs `install` with an exclusive lock on the host directory.\n *\n * `npm install` in a directory another npm is installing into is a good way to end\n * up with a half-written dependency tree, and the shared cache makes that a normal\n * occurrence rather than an exotic one: two repos previewing for the first time\n * after a devkit upgrade both decide they need to install.\n *\n * The lock is a file created with `wx` — the exclusivity comes from the filesystem,\n * not from a check-then-write. It records a pid so a lock left behind by a killed\n * process can be identified and taken over, which matters because the alternative\n * is a cache directory that refuses to install ever again.\n *\n * `needsInstall` is re-checked while holding the lock: after waiting behind another\n * process, the install we were queuing for has usually already done the work.\n */\nexport async function withInstallLock<T>(\n dir: string,\n install: () => Promise<T>,\n options: { needsInstall?: () => boolean; isAlive?: IsAlive; log?: (msg: string) => void; timeoutMs?: number; pollMs?: number } = {},\n): Promise<T | null> {\n const isAlive = options.isAlive ?? pidIsAlive;\n const log = options.log ?? (() => {});\n const timeoutMs = options.timeoutMs ?? 20 * 60_000;\n const pollMs = options.pollMs ?? 500;\n const lockPath = join(dir, INSTALL_LOCK);\n const deadline = Date.now() + timeoutMs;\n let waitingFor: number | null = null;\n\n while (!acquire(lockPath)) {\n const holder = lockHolder(lockPath);\n if (holder === null || !isAlive(holder)) {\n // The holder is gone; the lock can never be released by anyone else.\n rmSync(lockPath, { force: true });\n continue;\n }\n if (holder !== waitingFor) {\n waitingFor = holder;\n log(`Another devkit (PID ${holder}) is installing the preview host's dependencies — waiting for it to finish…`);\n }\n if (Date.now() > deadline) {\n throw new CliError(`Timed out after ${Math.round(timeoutMs / 60_000)} min waiting for PID ${holder} to finish installing in ${dir}. If that process is gone, delete ${lockPath}.`);\n }\n await new Promise(done => setTimeout(done, pollMs));\n }\n\n try {\n if (options.needsInstall && !options.needsInstall()) {\n return null;\n }\n return await install();\n } finally {\n rmSync(lockPath, { force: true });\n }\n}\n\n/** True when the lock was created by us. `wx` fails if the file already exists. */\nfunction acquire(lockPath: string): boolean {\n try {\n mkdirSync(dirname(lockPath), { recursive: true });\n writeFileSync(lockPath, `${process.pid}\\n${new Date().toISOString()}\\n`, { encoding: 'utf-8', flag: 'wx' });\n return true;\n } catch {\n return false;\n }\n}\n\nfunction lockHolder(lockPath: string): number | null {\n try {\n const pid = Number.parseInt(readFileSync(lockPath, 'utf-8').split('\\n')[0] ?? '', 10);\n return Number.isInteger(pid) ? pid : null;\n } catch {\n // Vanished between the failed acquire and this read — treat as unheld.\n return null;\n }\n}\n\n/**\n * The dependency sets the install must match. Only the dependency blocks matter —\n * editing a script or the description should not trigger a 500 MB reinstall.\n */\nfunction manifestFingerprint(dir: string): string {\n const pkg = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf-8')) as {\n dependencies?: Record<string, string>;\n devDependencies?: Record<string, string>;\n };\n return JSON.stringify({ dependencies: pkg.dependencies ?? {}, devDependencies: pkg.devDependencies ?? {} });\n}\n","/**\n * Whether a process is still around.\n *\n * `kill(pid, 0)` sends no signal — it only asks the kernel whether the process\n * exists and whether we may signal it. `EPERM` therefore means \"alive, but not\n * yours\", which counts as alive: a preview started under another user still holds\n * the port.\n *\n * Both the preview registry and the install lock record a pid, and both need the\n * same answer, so this lives on its own rather than in either of them.\n */\nexport function pidIsAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) {\n return false;\n }\n try {\n process.kill(pid, 0);\n return true;\n } catch (err) {\n return (err as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/** Injectable liveness check, so tests need no real processes. */\nexport type IsAlive = (pid: number) => boolean;\n","import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';\nimport { basename, join } from 'node:path';\nimport { type IsAlive, pidIsAlive } from './pid.js';\n\n/**\n * Which previews are running out of a given host directory.\n *\n * One host directory is shared by every node package on the machine, so devkit has\n * to be able to answer \"is someone else already using it?\" — both to refuse a\n * second preview unless it was asked for, and to refuse a `--force` reinstall that\n * would swap `node_modules` out from under a running dev server.\n *\n * Stored as one file per pid rather than a single JSON document: two previews\n * starting at once would otherwise read-modify-write over each other, and the\n * failure mode of a lost registration is exactly the collision this prevents.\n */\n\nconst REGISTRY_DIR = 'previews';\n\nexport interface PreviewEntry {\n pid: number;\n /** The node package being previewed — what the user needs in order to recognise it. */\n cwd: string;\n mockPort: number;\n /**\n * The port the Nuxt child was told to use. Nuxt relocates on its own if it lost\n * the race for it, so this is the intended port, not a guaranteed one.\n */\n uiPort: number;\n startedAt: string;\n}\n\n/**\n * Live entries, with dead ones deleted as a side effect.\n *\n * Cleaning up on read is deliberate: a preview killed with SIGKILL never gets to\n * deregister, and a registry that only grows would refuse every future preview.\n */\nexport function readLivePreviews(hostDir: string, isAlive: IsAlive = pidIsAlive): PreviewEntry[] {\n const dir = join(hostDir, REGISTRY_DIR);\n if (!existsSync(dir)) {\n return [];\n }\n const live: PreviewEntry[] = [];\n for (const file of readdirSync(dir)) {\n if (!file.endsWith('.json')) {\n continue;\n }\n const path = join(dir, file);\n const entry = readEntry(path);\n if (entry && isAlive(entry.pid)) {\n live.push(entry);\n } else {\n // Unreadable or dead — either way it can never become valid again.\n rmSync(path, { force: true });\n }\n }\n return live.sort((a, b) => a.startedAt.localeCompare(b.startedAt));\n}\n\nfunction readEntry(path: string): PreviewEntry | null {\n try {\n const parsed = JSON.parse(readFileSync(path, 'utf-8')) as PreviewEntry;\n return Number.isInteger(parsed?.pid) ? parsed : null;\n } catch {\n return null;\n }\n}\n\nexport function registerPreview(hostDir: string, entry: PreviewEntry): void {\n const dir = join(hostDir, REGISTRY_DIR);\n mkdirSync(dir, { recursive: true });\n writeFileSync(join(dir, `${entry.pid}.json`), `${JSON.stringify(entry, null, 2)}\\n`, 'utf-8');\n}\n\nexport function unregisterPreview(hostDir: string, pid: number = process.pid): void {\n rmSync(join(hostDir, REGISTRY_DIR, `${pid}.json`), { force: true });\n}\n\n/** One line per running preview, for the refusal message and the startup banner. */\nexport function describePreview(entry: PreviewEntry): string {\n return `${basename(entry.cwd)} (PID ${entry.pid}, mock :${entry.mockPort}, UI :${entry.uiPort}) — ${entry.cwd}`;\n}\n\nexport interface ConflictOptions {\n /** The repo about to be previewed. */\n cwd: string;\n /** Whether `--parallel` was given. */\n parallel: boolean;\n /** Whether this run would reinstall the shared dependency tree. */\n force?: boolean;\n hostDir: string;\n}\n\n/**\n * Why this preview must not start, or null if it may.\n *\n * A pure function so the decision is testable — `preview` itself only turns the\n * message into a {@link CliError}. Three cases, in order of severity:\n */\nexport function previewConflict(running: PreviewEntry[], options: ConflictOptions): string | null {\n // Same repo twice: the build dir, Vite cache and dotenv file are all keyed by cwd,\n // so a second run would compile into the first one's build and serve its app. That\n // is the failure --parallel exists to make safe, so --parallel cannot license it.\n const sameRepo = running.find(entry => entry.cwd === options.cwd);\n if (sameRepo) {\n return [\n `A preview of this very package is already running: ${describePreview(sameRepo)}`,\n '',\n \"Two previews of one package share a build directory and would serve each other's\",\n 'output, so this is refused even with --parallel. Stop that one first.',\n ].join('\\n');\n }\n\n if (options.force && running.length > 0) {\n return `--force reinstalls the host's dependencies, which would pull node_modules out from under the preview still running in ${running[0]?.cwd}. Stop it first.`;\n }\n\n if (running.length > 0 && !options.parallel) {\n return [\n `A preview is already running out of ${options.hostDir}:`,\n ...running.map(entry => ` ${describePreview(entry)}`),\n '',\n 'Stop it (Ctrl-C in its terminal), or run this one alongside it with --parallel.',\n ].join('\\n');\n }\n\n return null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA8BA,SAAS,cAAAA,aAAY,eAAAC,cAAa,gBAAAC,eAAc,aAAa;AAE7D,SAAS,gBAAAC,qBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,YAAAC,WAAU,SAAS,QAAAC,OAAM,WAAAC,gBAAe;AACjD,SAAS,iBAAAC,sBAAqB;;;ACnC9B,SAAS,kBAAkB;AAC3B,SAAS,eAAe;;;ACAxB,SAAS,oBAAoB;AAmB7B,IAAM,gBAAgB;AActB,eAAsB,mBAAmB,QAAgB,SAAyC;AAChG,QAAM,QAAQ,QAAQ,SAAS,IAAK,QAAQ,SAAS;AACrD,QAAM,QAAQ,QAAQ;AACtB,WAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,QAAQ,GAAG;AACtD,UAAM,QAAQ,MAAM,KAAK,QAAQ,IAAI;AACrC,QAAI,UAAU,MAAM;AAClB,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,QAAQ,SACV,IAAI,SAAS,QAAQ,KAAK,8EAA8E,IACxG,IAAI,SAAS,wBAAwB,KAAK,QAAQ,QAAQ,QAAQ,CAAC,6CAA6C;AACtH;AAGA,SAAS,KAAK,QAAgB,MAAsC;AAClE,SAAO,IAAI,QAAQ,CAAC,aAAa,WAAW;AAC1C,UAAM,UAAU,CAAC,QAA+B;AAC9C,aAAO,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C;AACA,MAAI,YAAY,SAAS;AACvB,UAAM,EAAE,QAAAC,QAAO,IAAI,MAAM,OAAO,IAAS;AACzC,IAAAA,QAAO,QAAQ,WAAW,EAAE,OAAO,KAAK,CAAC;AACzC,YAAQ,IAAI,WAAW,QAAQ,SAAS,EAAE;AAC1C;AAAA,EACF;AACA,MAAI,YAAY,gBAAgB;AAG9B,QAAI,QAAQ,eAAe,MAAM;AAC/B,cAAQ,MAAM,+FAA+F;AAC7G,cAAQ,MAAM,8IAAyI;AACvJ,cAAQ,MAAM,8FAA8F;AAC5G,cAAQ,KAAK,CAAC;AAAA,IAChB;AACA,UAAM,EAAE,IAAI,IAAI,gBAAgB;AAAA,MAC9B,WAAW,QAAQ;AAAA,MACnB,oBAAoB,oBAAoB,QAAQ,IAAI;AAAA,MACpD,OAAO,QAAQ;AAAA,MACf,KAAK,SAAO,QAAQ,IAAI,GAAG;AAAA,IAC7B,CAAC;AACD,YAAQ,IAAI,kEAAkE;AAC9E,YAAQ,IAAI,qBAAqB,GAAG,uFAAuF;AAC3H,YAAQ,IAAI,0CAA0C,GAAG,kCAAkC;AAC3F;AAAA,EACF;AACA,MAAI,YAAY,WAAW;AACzB,UAAM,QAAQ,OAAO;AACrB;AAAA,EACF;AACA,QAAM,IAAI,OAAO;AACnB;AAEA,KAAK,EAAE,MAAM,SAAO;AAGlB,UAAQ,MAAM,eAAe,WAAW,IAAI,UAAU,GAAG;AACzD,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","readdirSync","readFileSync","createServer","basename","join","resolve","fileURLToPath","existsSync","resolve","existsSync","resolve","existsSync","mkdirSync","readFileSync","readdirSync","rmSync","writeFileSync","join","join","existsSync","readdirSync","rmSync","readFileSync","mkdirSync","writeFileSync","fileURLToPath","resolve","existsSync","readdirSync","readFileSync","join","relative","createServer","basename","envFile","rmSync"]}
|