@revenexx/integrations-node-devkit 0.2.2 → 0.3.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/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/cli.ts","../src/preview/scaffold.ts","../src/preview/templates.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 # scaffold+install+run the Nuxt host together with the mock\n * integrations-devkit init-preview # only scaffold the Nuxt preview host\n * integrations-devkit reset # delete the persisted session overlay\n *\n * Options:\n * --dir <path> preview host dir (default: .revenexx-dev/preview)\n * --force overwrite existing scaffold files\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)\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 { extname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { loadEnvFile } from './env.js';\nimport { DEVKIT_VERSION } from './index.js';\nimport { type LoadedPackage, loadPackageFromEntry } from './loader.js';\nimport { applySeeds, loadSeedsFromDir, loadState, saveState } from './persistence.js';\nimport { previewDepsInstalled, previewExists, scaffoldPreview } from './preview/scaffold.js';\nimport { createRequestListener } from './server.js';\nimport { DevStore } from './store.js';\n\ninterface CliOptions {\n entry: string;\n seedDir: string;\n stateFile: string;\n persist: boolean;\n port: number;\n uiDir: string | null;\n serveUi: boolean;\n open: boolean;\n /** Preview host directory (default `.revenexx-dev/preview`). */\n previewDir: string;\n /** Overwrite existing scaffold files. */\n force: boolean;\n}\n\nfunction parseArgs(argv: string[]): { 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: Number.parseInt(process.env.PORT ?? '3555', 10),\n uiDir: null,\n serveUi: true,\n open: false,\n previewDir: resolve(cwd, '.revenexx-dev/preview'),\n force: 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 '--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 opts.port = Number.parseInt(argv[++i] ?? '3555', 10);\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 console.error(`Unknown option: ${arg}`);\n process.exit(1);\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\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 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 await new Promise<void>(r => server.listen(options.port, r));\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 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:${options.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 && /\\.[cm]?tsx?$|\\.js$/.test(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/** Scaffolds (if needed), installs, and runs the Nuxt preview host + the mock together. */\nasync function preview(options: CliOptions): Promise<void> {\n const dir = options.previewDir;\n const apiUrl = `http://localhost:${options.port}/api/v1`;\n\n if (!previewExists(dir) || options.force) {\n scaffoldPreview({ dir, integrationsApiUrl: apiUrl, force: options.force, log: msg => console.log(msg) });\n }\n if (!previewDepsInstalled(dir)) {\n console.log('Installing preview-host dependencies (first run — this pulls Nuxt + the studio packages and may take a while)…');\n await runNpmInstall(dir);\n }\n\n const mock = await startMock({ ...options, serveUi: false });\n console.log(`\\n Mock Integrations API ${apiUrl}`);\n console.log(' Preview UI http://localhost:3000/integrations (Nuxt starting…)\\n');\n\n const { spawn } = await import('node:child_process');\n const child = spawn('npm', ['run', 'dev'], {\n cwd: dir,\n stdio: 'inherit',\n env: {\n ...process.env,\n NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,\n NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? 'dev',\n NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? 'dev-tenant',\n },\n });\n\n const shutdown = () => {\n child.kill('SIGTERM');\n mock.dispose();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n child.on('exit', code => {\n mock.dispose();\n process.exit(code ?? 0);\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 scaffoldPreview({\n dir: options.previewDir,\n integrationsApiUrl: `http://localhost:${options.port}/api/v1`,\n force: options.force,\n log: msg => console.log(msg),\n });\n console.log(`\\nNext: \\`integrations-devkit preview\\` (installs deps + starts mock + Nuxt), or \\`cd ${options.previewDir} && npm install && npm run dev\\`.`);\n return;\n }\n if (command === 'preview') {\n await preview(options);\n return;\n }\n await run(options);\n}\n\nmain().catch(err => {\n console.error(err);\n process.exit(1);\n});\n","import { existsSync, mkdirSync, writeFileSync } from 'node:fs';\nimport { dirname, join, resolve } from 'node:path';\nimport { previewTemplates } from './templates.js';\n\nexport interface ScaffoldPreviewOptions {\n /** Target directory for the host (default `.revenexx-dev/preview`). */\n dir: string;\n /** Mock API base URL baked into `.env`. */\n integrationsApiUrl: string;\n /** Overwrite existing files. */\n force?: boolean;\n log?: (msg: string) => void;\n}\n\nexport interface ScaffoldResult {\n dir: string;\n written: string[];\n skipped: string[];\n}\n\n/**\n * Writes the Nuxt preview host into `dir`. Idempotent: existing files are left\n * untouched unless `force` is set. Returns which files were written vs skipped.\n */\nexport function scaffoldPreview(options: ScaffoldPreviewOptions): ScaffoldResult {\n const log = options.log ?? (() => {});\n const files = previewTemplates({ integrationsApiUrl: options.integrationsApiUrl });\n const written: string[] = [];\n const skipped: string[] = [];\n\n for (const [relative, content] of Object.entries(files)) {\n const target = resolve(options.dir, relative);\n if (existsSync(target) && !options.force) {\n skipped.push(relative);\n continue;\n }\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, content, 'utf-8');\n written.push(relative);\n }\n\n if (written.length > 0) {\n log(`Scaffolded preview host in ${options.dir} (${written.length} file(s)).`);\n }\n if (skipped.length > 0) {\n log(`Kept ${skipped.length} existing file(s) (use --force to overwrite).`);\n }\n return { dir: options.dir, written, skipped };\n}\n\n/** True when the preview host has its dependencies installed. */\nexport function previewDepsInstalled(dir: string): boolean {\n return existsSync(join(dir, 'node_modules'));\n}\n\n/** True when a preview host has been scaffolded in `dir`. */\nexport function previewExists(dir: string): boolean {\n return existsSync(join(dir, 'package.json')) && existsSync(join(dir, 'nuxt.config.ts'));\n}\n","/**\n * File templates for the on-demand Nuxt preview host. The host is a minimal\n * Nuxt 4 SPA that registers the `@revenexx/studio-shared` and\n * `@revenexx/studio-integrations` Nuxt modules (the latter ships its own pages\n * under `/integrations`), pointed at the devkit's mock API. No custom auth shim is\n * needed — studio-shared's standalone `usePlatformAuth`/`usePlatformTenant`\n * read a dev token/tenant from `NUXT_PUBLIC_DEV_TOKEN` / `NUXT_PUBLIC_DEV_TENANT`.\n */\n\n/** Peer versions mirrored from `@revenexx/studio-integrations`'s peerDependencies. */\nconst VERSIONS = {\n nuxt: '^4.0.0',\n vue: '^3.5.0',\n studio: '^0.1.3',\n studioShared: '^0.2.0',\n studioIntegrations: '^0.5.1',\n vueFlowCore: '^1.48.2',\n vueFlowBackground: '^1.3.2',\n vueFlowControls: '^1.1.3',\n vueFlowMinimap: '^1.5.4',\n vueFlowNodeToolbar: '^1.1.1',\n dagre: '^3.0.0',\n lucide: '^1.0.0',\n solarIcons: '^1.2.1',\n // studio-integrations 0.5.x embeds a TipTap rich-text editor and vue-sonner toasts.\n tiptap: '^3.28.0',\n vueSonner: '^2.0.0',\n tailwindVite: '^4.0.0',\n tailwind: '^4.0.0',\n};\n\nexport interface PreviewTemplateOptions {\n /** Default mock API base URL baked into `.env` (runtime env still overrides). */\n integrationsApiUrl: string;\n}\n\nconst PACKAGE_JSON = `{\n \"name\": \"integrations-preview-host\",\n \"private\": true,\n \"type\": \"module\",\n \"scripts\": {\n \"dev\": \"nuxt dev\",\n \"build\": \"nuxt build\"\n },\n \"dependencies\": {\n \"@revenexx/studio\": \"${VERSIONS.studio}\",\n \"@revenexx/studio-integrations\": \"${VERSIONS.studioIntegrations}\",\n \"@revenexx/studio-shared\": \"${VERSIONS.studioShared}\",\n \"@solar-icons/nuxt\": \"${VERSIONS.solarIcons}\",\n \"@dagrejs/dagre\": \"${VERSIONS.dagre}\",\n \"@tiptap/core\": \"${VERSIONS.tiptap}\",\n \"@tiptap/extension-document\": \"${VERSIONS.tiptap}\",\n \"@tiptap/extension-history\": \"${VERSIONS.tiptap}\",\n \"@tiptap/extension-paragraph\": \"${VERSIONS.tiptap}\",\n \"@tiptap/extension-text\": \"${VERSIONS.tiptap}\",\n \"@tiptap/pm\": \"${VERSIONS.tiptap}\",\n \"@tiptap/vue-3\": \"${VERSIONS.tiptap}\",\n \"@vue-flow/background\": \"${VERSIONS.vueFlowBackground}\",\n \"@vue-flow/controls\": \"${VERSIONS.vueFlowControls}\",\n \"@vue-flow/core\": \"${VERSIONS.vueFlowCore}\",\n \"@vue-flow/minimap\": \"${VERSIONS.vueFlowMinimap}\",\n \"@vue-flow/node-toolbar\": \"${VERSIONS.vueFlowNodeToolbar}\",\n \"lucide-vue-next\": \"${VERSIONS.lucide}\",\n \"nuxt\": \"${VERSIONS.nuxt}\",\n \"vue\": \"${VERSIONS.vue}\",\n \"vue-sonner\": \"${VERSIONS.vueSonner}\"\n },\n \"devDependencies\": {\n \"@tailwindcss/vite\": \"${VERSIONS.tailwindVite}\",\n \"tailwindcss\": \"${VERSIONS.tailwind}\"\n }\n}\n`;\n\nconst NUXT_CONFIG = `import tailwindcss from '@tailwindcss/vite';\n\n// Minimal preview host for local integration-node development.\n// Generated by \\`integrations-devkit init-preview\\` — safe to edit or delete\n// (it lives under the gitignored .revenexx-dev/).\nexport default defineNuxtConfig({\n compatibilityDate: '2025-01-01',\n // SPA: no SSR, so the studio's browser-only composables (localStorage etc.)\n // behave exactly as in the real cockpit, and boot is fast.\n ssr: false,\n // studio-shared 0.2.x ships as a Nuxt MODULE (not a layer) — it must be\n // registered in 'modules', before studio-integrations which builds on it.\n // @solar-icons/nuxt provides the #solar-icons alias the studio components import.\n modules: ['@revenexx/studio-shared', '@solar-icons/nuxt', '@revenexx/studio-integrations'],\n css: ['~/assets/css/main.css'],\n vite: { plugins: [tailwindcss()] },\n runtimeConfig: {\n public: {\n // Overridden at runtime by NUXT_PUBLIC_* env (see .env / the preview command).\n integrationsApi: '',\n devToken: '',\n devTenant: '',\n },\n },\n});\n`;\n\n// Tailwind v4 wiring per @revenexx/studio's README. @source globs are relative\n// to THIS file; they tell Tailwind's JIT to scan the shipped component classes\n// of studio + studio-shared + studio-integrations, or they render unstyled.\nconst MAIN_CSS = `@import \"tailwindcss\";\n@import \"@revenexx/studio/tokens\";\n@import \"@revenexx/studio/fonts\";\n\n@source \"../../node_modules/@revenexx/studio/dist\";\n@source \"../../node_modules/@revenexx/studio-shared/components\";\n@source \"../../node_modules/@revenexx/studio-integrations/dist/runtime\";\n\n/* Phase 1: workflow EXECUTION is not wired up in the devkit preview yet, so the\n Workflows surface is hidden until phase 2. This hides the sidebar nav entry\n and any deep links to the workflow editor; the routes are also redirected by\n middleware/hide-workflows.global.ts. */\na[href^=\"/integrations/workflows\"] { display: none !important; }\nli:has(> a[href^=\"/integrations/workflows\"]) { display: none !important; }\n`;\n\n// Shell mirrors services/integrations/studio-ui's app.vue: the studio pages size\n// themselves against a definite height (h-svh), the brand background is #f3f1fa,\n// and the module's pages call toast.* (vue-sonner) so a global <Toaster> mount is\n// required. NuxtLoadingIndicator covers the on-demand route compile in dev.\nconst APP_VUE = `<script setup lang=\"ts\">\nimport { Toaster } from '@revenexx/studio'\n\nuseHead({ title: 'Integration Studio — devkit preview' })\n</script>\n\n<template>\n <div class=\"flex h-svh flex-col overflow-hidden bg-[#f3f1fa] text-foreground\">\n <NuxtLoadingIndicator color=\"var(--color-primary, #620DFF)\" :height=\"3\" />\n <div class=\"min-h-0 flex-1 pt-3\">\n <NuxtPage />\n </div>\n <Toaster rich-colors position=\"bottom-right\" :duration=\"3500\" close-button />\n </div>\n</template>\n`;\n\n// Landing page styled after services/integrations/studio-ui's pages/index.vue —\n// same studio design tokens (bg-card, text-mono, bg-primary, muted) so `/` looks\n// like the real dev host. No token gate: the devkit bakes a fixed dev token.\nconst INDEX_VUE = `<template>\n <div class=\"mx-auto flex min-h-full max-w-xl flex-col justify-center gap-6 px-6 py-12\">\n <div>\n <p class=\"text-mono text-muted-foreground\">Integrations · node devkit</p>\n <h1 class=\"mt-1 text-2xl font-medium\">Integration Studio — Preview</h1>\n <p class=\"mt-2 text-sm text-muted-foreground\">\n Lokaler Host für <code>@revenexx/studio-integrations</code> gegen die Mock-API\n deines Node-Pakets. Authentifizierung ist ein festes Dev-Token — nichts einzugeben.\n </p>\n </div>\n\n <div class=\"rounded-lg border border-black/[0.06] bg-card p-5 text-sm shadow-sm\">\n <p class=\"text-mono text-muted-foreground\">Session</p>\n <dl class=\"mt-2 grid grid-cols-[7rem_1fr] gap-y-1\">\n <dt class=\"text-muted-foreground\">Mock API</dt>\n <dd class=\"truncate font-mono text-xs leading-5\">{{ api }}</dd>\n <dt class=\"text-muted-foreground\">Tenant</dt>\n <dd class=\"font-mono text-xs leading-5\">{{ tenant }}</dd>\n </dl>\n </div>\n\n <div class=\"rounded-lg border border-black/[0.06] bg-card p-5 shadow-sm\">\n <p class=\"text-mono text-muted-foreground\">Einstieg</p>\n <div class=\"mt-3 flex flex-col gap-4\">\n <NuxtLink\n to=\"/nodes\"\n class=\"inline-flex w-fit items-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-primary-foreground hover:opacity-90\"\n >\n Lokale Nodes öffnen — Preview + Validierung\n </NuxtLink>\n <div class=\"flex flex-wrap gap-x-4 gap-y-1.5\">\n <NuxtLink\n v-for=\"link in quickLinks\"\n :key=\"link.to\"\n :to=\"link.to\"\n class=\"text-sm text-primary hover:underline\"\n >\n {{ link.label }}\n </NuxtLink>\n </div>\n </div>\n </div>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nconst rc = useRuntimeConfig().public\nconst api = rc.integrationsApi\nconst tenant = (rc.devTenant as string) || 'dev-tenant'\n\nconst quickLinks = [\n { to: '/integrations', label: 'Overview' },\n { to: '/integrations/credentials', label: 'Credentials' },\n { to: '/integrations/secrets', label: 'Secrets' },\n { to: '/nodes', label: 'Local nodes' },\n]\n</script>\n`;\n\n// Custom devkit page: lists the package's local nodes and, on click, opens the\n// REAL editor edit-view by REUSE — the exact studio <Dialog> lightbox from\n// WorkflowEditor.vue wrapping <IntegrationsNodeInspector> (the inspector is only\n// the dialog CONTENT; the studio Dialog owns the modal chrome/overlay). Config\n// fields + dynamic resolving run against the mock. On Save the dialog is kept\n// OPEN and the verdict shown: a success strip, or per-field errors fed back\n// through the inspector's `refusedFields` prop (wrong fields highlighted). The\n// page lives inside a template literal, so no backtick / ${ literals inside —\n// API paths use string concatenation.\nconst NODES_VUE = `<template>\n <div class=\"ndx-page\">\n <div class=\"ndx-inner\">\n <header class=\"ndx-head\">\n <h1>Lokale Nodes</h1>\n <p>Mock-API: <code>{{ apiUrl }}</code></p>\n <p v-if=\"loadError\" class=\"ndx-err\">{{ loadError }}</p>\n </header>\n\n <p v-if=\"loading\">Lade Nodes…</p>\n <p v-else-if=\"nodes.length === 0\">Keine Nodes gefunden. Exportiert dein Paket <code>NODES</code>?</p>\n\n <ul v-else class=\"ndx-grid\">\n <li v-for=\"n in nodes\" :key=\"n.slug + '@' + n.version\" class=\"ndx-card\" @click=\"openNode(n)\">\n <div class=\"ndx-card-title\">{{ label(n) }}</div>\n <div class=\"ndx-card-slug\">{{ n.slug }} · v{{ n.version }}</div>\n <div class=\"ndx-badges\">\n <span v-if=\"n.has_dynamic_options\" class=\"ndx-badge\">dynamic options</span>\n <span v-if=\"n.has_dynamic_schema\" class=\"ndx-badge\">dynamic schema</span>\n <span v-if=\"n.has_dynamic_outputs\" class=\"ndx-badge\">dynamic outputs</span>\n </div>\n </li>\n </ul>\n </div>\n\n <!-- REUSE of the exact editor lightbox: studio <Dialog> owns the modal\n chrome, <IntegrationsNodeInspector> is the content — mirrors\n WorkflowEditor.vue's <Dialog><DialogContent><NodeInspector/> block. -->\n <Dialog :open=\"!!selection\" @update:open=\"(v) => { if (!v) requestClose() }\">\n <DialogContent :show-close-button=\"false\" class=\"flex h-[min(680px,86vh)] w-[min(1100px,94vw)] max-w-none flex-col gap-0 overflow-hidden rounded-lg p-0 sm:max-w-none\">\n <div v-if=\"result === 'ok'\" class=\"ndx-strip ndx-strip-ok\">✓ Payload gültig — alles gut.</div>\n <div v-else-if=\"result === 'err'\" class=\"ndx-strip ndx-strip-err\">✗ Payload ungültig — {{ errorCount }} Feld(er) prüfen (rot markiert).</div>\n <div v-else-if=\"formError\" class=\"ndx-strip ndx-strip-err\">{{ formError }}</div>\n <IntegrationsNodeInspector\n v-if=\"selection\"\n :selection=\"selection\"\n :secret-keys=\"secretKeys\"\n :refused-fields=\"refused\"\n @update=\"onSubmit\"\n @close=\"requestClose\" />\n </DialogContent>\n </Dialog>\n </div>\n</template>\n\n<script setup lang=\"ts\">\nimport { computed, onMounted, ref } from 'vue'\nimport { Dialog, DialogContent } from '@revenexx/studio'\n\ninterface ApiNode {\n name: string | Record<string, string>\n slug: string\n version: string\n manifest?: { name?: string | Record<string, string> }\n has_dynamic_options?: boolean\n has_dynamic_schema?: boolean\n has_dynamic_outputs?: boolean\n}\n\nconst apiUrl = useRuntimeConfig().public.integrationsApi\nconst client = useIntegrationsApi()\n// load() fills the reactive catalog the inspector reads via findManifest();\n// resolveLocalized() turns a LocalizedString into the active-locale string.\nconst { load, resolveLocalized } = useIntegrationsNodes()\n\nconst nodes = ref<ApiNode[]>([])\nconst loading = ref(true)\nconst loadError = ref<string | null>(null)\n\nconst selection = ref<any>(null)\nconst secretKeys = ref<string[]>([])\nconst refused = ref<Record<string, string>>({})\nconst result = ref<string | null>(null)\nconst formError = ref<string | null>(null)\n// Set synchronously in onSubmit so the inspector's own Save (it emits update THEN\n// close) does NOT close the dialog — we keep it open to show the verdict.\nconst validating = ref(false)\n\nconst errorCount = computed(() => Object.keys(refused.value).length)\n\nfunction label(n: ApiNode): string {\n return resolveLocalized(n.manifest?.name ?? n.name) || n.slug\n}\n\nonMounted(async () => {\n await load()\n try {\n const res = await client.get<any>('/nodes')\n nodes.value = (Array.isArray(res) ? res : res?.data ?? []) as ApiNode[]\n } catch (e: any) {\n loadError.value = e?.message ?? 'Nodes konnten nicht geladen werden.'\n } finally {\n loading.value = false\n }\n try {\n const secrets = await client.get<any>('/secrets')\n const list = (Array.isArray(secrets) ? secrets : secrets?.data ?? []) as Array<{ key: string }>\n secretKeys.value = list.map(s => s.key).filter(Boolean)\n } catch {\n // secrets are optional for the preview\n }\n})\n\nfunction openNode(n: ApiNode) {\n refused.value = {}\n result.value = null\n formError.value = null\n // Synthetic WorkflowNode selection (distinguished by nodeSlug); the inspector\n // resolves its manifest from the catalog load() populated above.\n selection.value = { id: 'preview', nodeSlug: n.slug, nodeVersion: n.version, name: label(n), config: {} }\n}\n\nasync function onSubmit(draft: any) {\n validating.value = true\n refused.value = {}\n result.value = null\n formError.value = null\n try {\n const slug = encodeURIComponent(draft.nodeSlug)\n const version = encodeURIComponent(draft.nodeVersion || 'latest')\n const res = await client.post<any>(\n '/nodes/' + slug + '/' + version + '/config:validate',\n { config: draft.config ?? {} },\n )\n if (res.valid) {\n result.value = 'ok'\n } else {\n refused.value = Object.fromEntries(\n Object.entries(res.errors ?? {}).map(([k, msgs]) => [k, (msgs as string[]).join(' ')]),\n )\n result.value = 'err'\n }\n } catch (e: any) {\n formError.value = e?.message ?? 'Validierung fehlgeschlagen.'\n } finally {\n validating.value = false\n }\n}\n\n// The inspector emits close on both Save and Cancel; the studio Dialog emits it\n// on Esc / backdrop. Hold the close while a Save-validation is in flight so the\n// dialog stays open to show the result; otherwise close (discard).\nfunction requestClose() {\n if (validating.value) return\n selection.value = null\n refused.value = {}\n result.value = null\n formError.value = null\n}\n</script>\n\n<style scoped>\n/* The app shell (app.vue) is h-svh + overflow-hidden, so this page must own its\n own vertical scroll — otherwise the node list is clipped and can't scroll. */\n.ndx-page { height: 100%; overflow-y: auto; }\n.ndx-inner { max-width: 60rem; margin: 0 auto; padding: 2rem; font-family: sans-serif; }\n.ndx-head h1 { font-size: 1.5rem; font-weight: 600; }\n.ndx-err { color: #b91c1c; }\n.ndx-grid { list-style: none; padding: 0; display: grid; grid-template-columns: repeat(auto-fill, minmax(15rem, 1fr)); gap: 1rem; margin-top: 1.5rem; }\n.ndx-card { border: 1px solid #d1d5db; border-radius: 0.5rem; padding: 1rem; cursor: pointer; transition: border-color .15s, box-shadow .15s; }\n.ndx-card:hover { border-color: #6366f1; box-shadow: 0 1px 6px rgba(0,0,0,.08); }\n.ndx-card-title { font-weight: 600; }\n.ndx-card-slug { color: #6b7280; font-size: .85rem; margin-top: .25rem; }\n.ndx-badges { margin-top: .5rem; display: flex; flex-wrap: wrap; gap: .35rem; }\n.ndx-badge { font-size: .7rem; background: #eef2ff; color: #4338ca; border-radius: .25rem; padding: .1rem .4rem; }\n\n/* Verdict strip shown at the top of the reused dialog content (does not close). */\n.ndx-strip { flex: 0 0 auto; padding: .5rem 1rem; font-size: .85rem; font-weight: 600; }\n.ndx-strip-ok { background: #dcfce7; color: #166534; }\n.ndx-strip-err { background: #fee2e2; color: #991b1b; }\n</style>\n`;\n\nconst GITIGNORE = `node_modules/\n.nuxt/\n.output/\n.data/\n`;\n\n// Auto-imported no-op stubs for the full-cockpit \"console\" composables that some\n// studio-integrations components (notably CredentialRevenexxSource, the \"Use\n// revenexx managed source\" picker in the credential dialog) reach for. The\n// slimmed preview has no console gateways (tenants, markets, managed SFTP / mail\n// / API keys), so without these the component throws \"useConsoleTenants is not\n// defined\" at setup and takes its sibling manual-config fields down with it —\n// leaving the credential dialog with NO input fields. These stubs let that\n// picker render empty instead of crashing, so manual credential creation works.\nconst CONSOLE_STUBS = `import { ref } from 'vue'\n\nexport function useConsoleTenants() {\n return { tenants: ref([]), onlyTenantSlug: ref(null), load: async () => {} }\n}\nexport function useActiveMarket() {\n return {\n markets: ref([]),\n activeCode: ref(''),\n isGlobal: ref(true),\n GLOBAL_MARKET_CODE: '__global__',\n fetchMarkets: async () => {},\n }\n}\nexport function useConsoleSftp() {\n return {\n accounts: ref([]),\n load: async () => {},\n revealPassword: async () => ({}),\n create: async () => ({}),\n refresh: async () => ({}),\n }\n}\nexport function useMailAdmin() {\n return {\n listCredentials: async () => [],\n getCredential: async () => ({}),\n createCredential: async () => ({}),\n }\n}\nexport function useConsoleApiKeys() {\n return { create: async () => ({ secret: '' }) }\n}\n`;\n\n// Phase 1: workflow execution isn't available in the devkit preview, so the\n// Workflows editor pages are off-limits until phase 2. Any navigation to them\n// (deep links from the dashboard, direct URLs) bounces back to the Integrations\n// dashboard. The nav entry itself is hidden via assets/css/main.css.\nconst HIDE_WORKFLOWS_MW = `export default defineNuxtRouteMiddleware((to) => {\n if (to.path === '/integrations/workflows' || to.path.startsWith('/integrations/workflows/')) {\n return navigateTo('/integrations')\n }\n})\n`;\n\nexport function previewTemplates(options: PreviewTemplateOptions): Record<string, string> {\n const env = `# Overrides the Nuxt runtimeConfig.public.* values.\nNUXT_PUBLIC_INTEGRATIONS_API=${options.integrationsApiUrl}\nNUXT_PUBLIC_DEV_TOKEN=dev\nNUXT_PUBLIC_DEV_TENANT=dev-tenant\n`;\n return {\n 'package.json': PACKAGE_JSON,\n 'nuxt.config.ts': NUXT_CONFIG,\n 'assets/css/main.css': MAIN_CSS,\n 'app.vue': APP_VUE,\n 'pages/index.vue': INDEX_VUE,\n 'pages/nodes.vue': NODES_VUE,\n 'composables/devkit-console-stubs.ts': CONSOLE_STUBS,\n 'middle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AAK,EAAE,MAAM,SAAO;AAClB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["existsSync","join","resolve","resolve","existsSync","join"]}
1
+ {"version":3,"sources":["../src/cli.ts","../src/preview/host.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 * --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)\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 { extname, join, resolve } from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport { loadEnvFile } from './env.js';\nimport { DEVKIT_VERSION } from './index.js';\nimport { isReloadableSource, type LoadedPackage, loadPackageFromEntry } from './loader.js';\nimport { applySeeds, loadSeedsFromDir, loadState, saveState } from './persistence.js';\nimport { clearHostInstallMarker, hostBuildDir, hostNeedsInstall, markHostInstalled, materializeHost, resolveHostDir } from './preview/host.js';\nimport { createRequestListener } from './server.js';\nimport { DevStore } from './store.js';\n\ninterface CliOptions {\n entry: string;\n seedDir: string;\n stateFile: string;\n persist: boolean;\n port: number;\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}\n\nfunction parseArgs(argv: string[]): { 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: Number.parseInt(process.env.PORT ?? '3555', 10),\n uiDir: null,\n serveUi: true,\n open: false,\n previewDir: null,\n force: 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 '--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 opts.port = Number.parseInt(argv[++i] ?? '3555', 10);\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 console.error(`Unknown option: ${arg}`);\n process.exit(1);\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\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 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 await new Promise<void>(r => server.listen(options.port, r));\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 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:${options.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/** Materializes (if needed), installs, and runs the Nuxt preview host + the mock together. */\nasync function preview(options: CliOptions): Promise<void> {\n const apiUrl = `http://localhost:${options.port}/api/v1`;\n const managed = options.previewDir === null;\n const targetDir = options.previewDir ?? resolveHostDir({ version: DEVKIT_VERSION });\n\n noteLegacyPreviewDir();\n const { dir } = materializeHost({\n targetDir,\n integrationsApiUrl: apiUrl,\n force: options.force,\n managed,\n log: msg => console.log(msg),\n });\n if (managed) {\n console.log(` Host (devkit ${DEVKIT_VERSION}, shared across repos) ${dir}`);\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 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\n const mock = await startMock({ ...options, serveUi: false });\n console.log(`\\n Mock Integrations API ${apiUrl}`);\n console.log(' Preview UI http://localhost:3000/integrations (Nuxt starting…)\\n');\n\n const { spawn } = await import('node:child_process');\n const child = spawn('npm', ['run', 'dev'], {\n cwd: dir,\n stdio: 'inherit',\n env: {\n ...process.env,\n NUXT_PUBLIC_INTEGRATIONS_API: apiUrl,\n NUXT_PUBLIC_DEV_TOKEN: process.env.NUXT_PUBLIC_DEV_TOKEN ?? 'dev',\n NUXT_PUBLIC_DEV_TENANT: process.env.NUXT_PUBLIC_DEV_TENANT ?? 'dev-tenant',\n // Keep the shared host's dependency install shared but its BUILD per repo,\n // so two node packages previewing at once do not compile over each other.\n DEVKIT_NUXT_BUILD_DIR: hostBuildDir(dir, process.cwd()),\n },\n });\n\n const shutdown = () => {\n child.kill('SIGTERM');\n mock.dispose();\n process.exit(0);\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n child.on('exit', code => {\n mock.dispose();\n process.exit(code ?? 0);\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 console.error(err);\n process.exit(1);\n});\n","import { createHash } from 'node:crypto';\nimport { cpSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';\nimport { homedir } from 'node:os';\nimport { dirname, join, relative, resolve, sep } from 'node:path';\nimport { fileURLToPath } from 'node:url';\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. Without it, \"is the host here?\"\n * would again be \"do two filenames exist\" — the same check whose weakness this\n * module exists to fix, only for the copy instead of the install: `cpSync` is not\n * atomic, so an interrupted copy can leave `package.json` and `nuxt.config.ts`\n * behind while the rest is missing, and that half-host would be treated as intact\n * forever.\n */\nconst COPY_MARKER = '.devkit-copy-complete';\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.output/\n.data/\n.env\n${COPY_MARKER}\n${INSTALL_MARKER}\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 * 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 const intact = managed ? hostIsComplete(dir) : 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), `${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 const envPath = join(dir, '.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\nfunction envFile(options: MaterializeHostOptions): string {\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 \\`npm run dev\\` 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 * 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 */\nexport function hostBuildDir(hostDir: string, consumerDir: string): string {\n const key = createHash('sha256').update(consumerDir).digest('hex').slice(0, 12);\n return join(hostDir, `.nuxt-${key}`);\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 * 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"],"mappings":";;;;;;;;;;;;;;;AA4BA,SAAS,cAAAA,aAAY,aAAa,gBAAAC,eAAc,aAAa;AAE7D,SAAS,oBAAoB;AAC7B,SAAS,qBAAqB;AAC9B,SAAS,SAAS,QAAAC,OAAM,WAAAC,gBAAe;AACvC,SAAS,iBAAAC,sBAAqB;;;ACjC9B,SAAS,kBAAkB;AAC3B,SAAS,QAAQ,YAAY,WAAW,cAAc,QAAQ,qBAAqB;AACnF,SAAS,eAAe;AACxB,SAAS,SAAS,MAAM,UAAU,SAAS,WAAW;AACtD,SAAS,qBAAqB;AAoB9B,IAAM,iBAAiB;AAUvB,IAAM,cAAc;AAGpB,IAAM,iBAAiB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMrB,WAAW;AAAA,EACX,cAAc;AAAA;A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