@revenexx/integrations-node-devkit 0.3.0 → 0.5.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 +2 -1
- package/dist/{chunk-PS3HCKE7.js → chunk-YXIYTBOZ.js} +9 -2
- package/dist/chunk-YXIYTBOZ.js.map +1 -0
- package/dist/cli.cjs +530 -222
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +474 -171
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/preview-host/nuxt.config.ts +17 -1
- package/preview-host/package.json +1 -1
- package/preview-host/pages/nodes.vue +47 -12
- package/dist/chunk-PS3HCKE7.js.map +0 -1
package/dist/cli.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/cli.ts","../src/env.ts","../src/index.ts","../src/errors.ts","../src/loader.ts","../src/persistence.ts","../src/store.ts","../src/resolve.ts","../src/server.ts","../src/http.ts","../src/projections.ts","../src/preview/host.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","#!/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 { existsSync } from 'node:fs';\nimport { basename, resolve } from 'node:path';\n\n/**\n * `.env` loading for the CLI.\n *\n * Seeds reference secrets as `${VAR}` and {@link interpolateEnv} resolves those\n * from `process.env`, so without this the documented workflow — commit the\n * reference, keep the value in `.env` — only worked if the developer exported\n * the variables by hand.\n *\n * Loading happens before option parsing, because the CLI reads `PORT` for its\n * default port; a `.env` that sets `PORT` would otherwise be read too late.\n *\n * Exactly one file is ever loaded: `.env` by default, or the one named by\n * `--env`, which *replaces* the default rather than layering on top of it.\n * \"Use this env file\" is what the flag reads like, so leaving `.env` in play\n * would be the surprise. `--no-env` loads none.\n *\n * `process.loadEnvFile` deliberately does not overwrite variables that are\n * already set, so a shell-provided value always beats the file:\n *\n * REVENEXX_DEV_API_KEY=… npm run preview\n *\n * The flag is `--env`, *not* `--env-file`: Node reserves `--env-file` and\n * `--env-file-if-exists` and acts on them wherever they appear, including after\n * the script path. `node cli.js --env-file missing` therefore dies inside Node\n * with exit code 9 before this module is ever reached, so the devkit cannot own\n * that name. {@link nodeOwnedEnvFlag} spots the mistake and explains it.\n *\n * `--env` takes a path rather than Laravel's bare environment name, because it\n * mirrors Node's flag and because a path can point outside the package. A value\n * that looks like it was meant as a name still gets a pointed error — see\n * {@link missingFileMessage}.\n */\n\n/** Minimum Node version shipping `process.loadEnvFile`. */\nexport const ENV_FILE_MIN_NODE = '20.12';\n\n/** Flags Node itself consumes, positionally, and which the devkit must not reuse. */\nconst NODE_OWNED_FLAGS = ['--env-file', '--env-file-if-exists'];\n\nexport interface EnvFileChoice {\n /** Absolute path to load, or `null` when `--no-env` disabled loading. */\n path: string | null;\n /** True when the file was named with `--env` rather than defaulted to. */\n explicit: boolean;\n /** The `--env` value exactly as typed, kept for {@link missingFileMessage}. */\n raw?: string;\n}\n\n/**\n * Returns the Node-owned env flag present in `argv`, if any. Node has already\n * acted on it by the time the CLI runs — this exists only so the CLI can say so\n * instead of leaving the user wondering why `--env-file` behaved oddly.\n */\nexport function nodeOwnedEnvFlag(argv: string[]): string | null {\n return NODE_OWNED_FLAGS.find(flag => argv.includes(flag) || argv.some(arg => arg.startsWith(`${flag}=`))) ?? null;\n}\n\n/**\n * Decides which env file to load. Pure — touches neither disk nor `process.env`.\n *\n * A repeated `--env` resolves to the last one, matching every other option in\n * the CLI, whose parse loop simply overwrites. Every occurrence is still\n * validated, so a malformed earlier one is reported rather than skipped.\n */\nexport function resolveEnvFile(argv: string[], cwd: string = process.cwd()): EnvFileChoice {\n if (argv.includes('--no-env')) {\n return { path: null, explicit: false };\n }\n\n let named: EnvFileChoice | null = null;\n for (let i = 0; i < argv.length; i++) {\n // Strict equality: `--env-file` belongs to Node, and `--env-file=x` must\n // not be mistaken for a value-carrying `--env`.\n if (argv[i] !== '--env') {\n continue;\n }\n const value = argv[++i];\n if (!value || value.startsWith('-')) {\n throw new Error('--env requires a path.');\n }\n named = { path: resolve(cwd, value), explicit: true, raw: value };\n }\n\n return named ?? { path: resolve(cwd, '.env'), explicit: false };\n}\n\n/**\n * Explains a named-but-missing env file. When the value looks like a Laravel\n * environment name and the matching `.env.<name>` is right there, say so — the\n * bare \"does not exist\" would leave the user re-reading the flag's docs.\n */\nfunction missingFileMessage(choice: EnvFileChoice, cwd: string): string {\n const raw = choice.raw;\n if (raw && raw === basename(raw) && existsSync(resolve(cwd, `.env.${raw}`))) {\n return `--env: ${choice.path} does not exist. Did you mean --env .env.${raw}? The flag takes a path, not an environment name.`;\n }\n return `--env: ${choice.path} does not exist.`;\n}\n\nexport interface LoadEnvFileOptions {\n cwd?: string;\n warn?: (message: string) => void;\n}\n\n/**\n * Loads the env file chosen by {@link resolveEnvFile} into `process.env` and\n * returns its path, or `null` when nothing was loaded.\n *\n * A missing *default* `.env` is fine — most packages do not have one. A file\n * asked for by name and missing is an error: ignoring it would hide a typo and\n * resurface much later as a puzzling `Seed references ${X}` failure. There is no\n * fallback to `.env` in that case, since naming a file replaces the default.\n */\nexport function loadEnvFile(argv: string[], options: LoadEnvFileOptions = {}): string | null {\n const { cwd = process.cwd(), warn = (message: string) => console.warn(message) } = options;\n\n const nodeFlag = nodeOwnedEnvFlag(argv);\n if (nodeFlag) {\n warn(`Note: ${nodeFlag} is a Node flag and Node has already applied it. The devkit's own flag is --env <path>.`);\n }\n\n const choice = resolveEnvFile(argv, cwd);\n if (!choice.path) {\n return null;\n }\n if (!existsSync(choice.path)) {\n if (choice.explicit) {\n throw new Error(missingFileMessage(choice, cwd));\n }\n return null;\n }\n // npm's `engines` field is advisory, so an old runtime reaches this far.\n if (typeof process.loadEnvFile !== 'function') {\n warn(`Ignoring ${choice.path}: env-file support needs Node >= ${ENV_FILE_MIN_NODE} (running ${process.version}).`);\n return null;\n }\n\n process.loadEnvFile(choice.path);\n return choice.path;\n}\n","/**\n * `@revenexx/integrations-node-devkit` — local development kit for Revenexx\n * integration node packages. Dev/CI only; never bundled into a node package.\n *\n * Two surfaces:\n * - `@revenexx/integrations-node-devkit` → the mock-API preview server (this entry)\n * - `@revenexx/integrations-node-devkit/testing` → the unit-testing harness\n */\n\nimport { readFileSync } from 'node:fs';\n\n// Read from package.json rather than hardcoded, so the released version can\n// never drift from what `integrations-devkit --version` prints. `../` resolves\n// to the package root from both `src/` and the bundled `dist/`. The CJS build\n// needs tsup's `shims: true` for `import.meta.url`.\nconst manifestUrl = new URL('../package.json', import.meta.url);\nexport const DEVKIT_VERSION: string = JSON.parse(readFileSync(manifestUrl, 'utf8')).version;\n\nexport {\n ENV_FILE_MIN_NODE,\n type EnvFileChoice,\n loadEnvFile,\n type LoadEnvFileOptions,\n nodeOwnedEnvFlag,\n resolveEnvFile,\n} from './env.js';\nexport { DevApiError } from './errors.js';\nexport {\n ensureTsxRegistered,\n importFresh,\n type LoadedPackage,\n loadPackageFromEntry,\n resolveExports,\n} from './loader.js';\nexport {\n applySeeds,\n type CredentialSeed,\n type DevSeeds,\n interpolateEnv,\n loadSeedsFromDir,\n loadState,\n saveState,\n type SecretSeed,\n type WorkflowSeed,\n} from './persistence.js';\nexport {\n buildOAuthAuthorizeUrl,\n exchangeOAuthCode,\n findCredential,\n findCredentialType,\n findNode,\n nodeVersions,\n type ResolveNodeConfigInput,\n type ResolveNodeConfigResult,\n resolveCredentialInstance,\n resolveNodeConfig,\n testCredentialConfig,\n testCredentialInstance,\n type ValidateNodeConfigInput,\n type ValidateNodeConfigResult,\n validateNodeConfig,\n} from './resolve.js';\nexport {\n createDevServer,\n createRequestListener,\n type DevServerDeps,\n} from './server.js';\nexport {\n type CredentialRecord,\n DEV_TENANT_ID,\n DevStore,\n type DevStoreSnapshot,\n type SecretRecord,\n STORE_SCHEMA_VERSION,\n type TriggerRecord,\n type WorkflowRecord,\n} from './store.js';\n","/**\n * An error that maps to an HTTP status + JSON body in the mock API, mirroring\n * Laravel's `{message}` / `{message, errors}` envelopes.\n */\nexport class DevApiError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly errors?: Record<string, string[]>,\n ) {\n super(message);\n this.name = 'DevApiError';\n }\n}\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { buildManifest, type ICredential, type INode, type ITemplateDescription, type NodeManifest } from '@revenexx/integrations-node-sdk';\n\n/** Identity of the npm package the nodes came from, as `GET /nodes` reports it. */\nexport interface PackageInfo {\n name: string;\n version: string;\n label: string;\n}\n\nconst UNKNOWN_PACKAGE: PackageInfo = { name: 'unknown', version: '0.0.0', label: 'Local package' };\n\n/**\n * A node package loaded into the dev process: its live `NODES` / `CREDENTIALS`\n * / `TEMPLATES` instances (so author-time resolvers, `test`, and `resolve` can\n * be invoked in-process — no bundle, no sandbox) plus the derived manifest the\n * mock API serves.\n */\nexport interface LoadedPackage {\n nodes: INode[];\n credentials: ICredential[];\n templates: ITemplateDescription[];\n manifest: NodeManifest;\n /** Reported as each node's `package`; the contract declares it non-null. */\n packageInfo: PackageInfo;\n /** Stands in for the service's per-node `created_at`/`updated_at`. */\n loadedAt: string;\n}\n\n/**\n * Reads the nearest `package.json` above `entryPath` for the node package's\n * identity. The real service knows this from the published bundle; here it comes\n * from the developer's own manifest.\n */\nexport function readPackageInfo(entryPath: string): PackageInfo {\n let dir = dirname(entryPath);\n for (let up = 0; up < 6; up += 1) {\n const candidate = join(dir, 'package.json');\n if (existsSync(candidate)) {\n try {\n const pkg = JSON.parse(readFileSync(candidate, 'utf-8')) as { name?: string; version?: string; description?: string };\n if (pkg.name) {\n return { name: pkg.name, version: pkg.version ?? '0.0.0', label: pkg.name.split('/').pop() ?? pkg.name };\n }\n } catch {\n // Unreadable package.json is not worth failing the preview over.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return UNKNOWN_PACKAGE;\n}\n\ninterface PackageExports {\n NODES?: unknown;\n CREDENTIALS?: unknown;\n TEMPLATES?: unknown;\n}\n\n/**\n * Validates a package's module exports and builds a {@link LoadedPackage}.\n * Mirrors the checks in the SDK's `rvnxx-nodes manifest` CLI so the dev loop\n * and the build produce identical manifests.\n */\nexport function resolveExports(mod: PackageExports, packageInfo: PackageInfo = UNKNOWN_PACKAGE): LoadedPackage {\n if (!Array.isArray(mod.NODES)) {\n throw new Error('Package entry does not export a `NODES` array. Export `NODES: INode[]`.');\n }\n if (mod.CREDENTIALS !== undefined && !Array.isArray(mod.CREDENTIALS)) {\n throw new Error('Package entry exports `CREDENTIALS` but it is not an array.');\n }\n if (mod.TEMPLATES !== undefined && !Array.isArray(mod.TEMPLATES)) {\n throw new Error('Package entry exports `TEMPLATES` but it is not an array.');\n }\n\n const nodes = mod.NODES as INode[];\n const credentials = (mod.CREDENTIALS as ICredential[] | undefined) ?? [];\n const templates = (mod.TEMPLATES as ITemplateDescription[] | undefined) ?? [];\n\n return {\n nodes,\n credentials,\n templates,\n manifest: buildManifest(nodes, credentials, templates),\n packageInfo,\n loadedAt: new Date().toISOString(),\n };\n}\n\nlet tsxRegistered = false;\n\n/**\n * Registers the `tsx` ESM loader once per process so `import()` can load\n * TypeScript sources directly. Idempotent.\n */\nexport async function ensureTsxRegistered(): Promise<void> {\n if (tsxRegistered) {\n return;\n }\n const { register } = await import('tsx/esm/api');\n register();\n tsxRegistered = true;\n}\n\n/**\n * File extensions whose change should reload the package.\n *\n * `[cm]?[jt]sx?` covers the whole matrix — `.ts .tsx .cts .mts .js .jsx .cjs .mjs`\n * — rather than the `.ts`-family-plus-bare-`.js` it used to be. That older pattern\n * silently ignored `.mjs` and `.cjs`, so a package whose entry is a built ESM\n * `dist/index.mjs` never hot-reloaded at all: edits landed, nothing happened, and\n * nothing said why.\n *\n * `.json` is in because a node that imports locale strings or lookup data from one\n * has to re-evaluate when it changes. A reload it did not need costs a few ms and\n * keeps the previous package on failure, so erring towards reloading is free.\n */\nconst RELOADABLE_SOURCE = /\\.(?:[cm]?[jt]sx?|json)$/;\n\n/** True when a changed file is package source the mock should reload for. */\nexport function isReloadableSource(file: string): boolean {\n return RELOADABLE_SOURCE.test(file);\n}\n\n/** Imports a module by path, registering tsx first for TypeScript sources. */\nexport async function importFresh<T = unknown>(entryPath: string): Promise<T> {\n if (/\\.[cm]?tsx?$/.test(entryPath)) {\n await ensureTsxRegistered();\n }\n const href = `${pathToFileURL(entryPath).href}?t=${Date.now()}`;\n return (await import(href)) as T;\n}\n\n/**\n * Imports a package entry and resolves its exports. Supports TypeScript\n * sources directly (via `tsx`) so the preview runs against the developer's\n * live `src/`, not a built artifact. A cache-busting query is appended so\n * repeated calls (hot-reload) re-evaluate the module.\n */\nexport async function loadPackageFromEntry(entryPath: string): Promise<LoadedPackage> {\n return resolveExports(await importFresh<PackageExports>(entryPath), readPackageInfo(entryPath));\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { importFresh } from './loader.js';\nimport { type DevStore, type DevStoreSnapshot, STORE_SCHEMA_VERSION } from './store.js';\n\n/**\n * Layered persistence for the preview session:\n * 1. committed seeds (this module's {@link applySeeds}) — the durable base,\n * with `${ENV_VAR}` references interpolated from the environment;\n * 2. `.revenexx-dev/state.json` overlay ({@link loadState}/{@link saveState}) —\n * interactive session state, versioned and disposable.\n */\n\nexport interface CredentialSeed {\n credentialTypeSlug: string;\n name: string;\n config: Record<string, unknown>;\n /** Stable id so workflows can reference the credential across restarts. */\n id?: string;\n status?: string;\n durableCreds?: Record<string, unknown> | null;\n}\n\nexport interface SecretSeed {\n key: string;\n value: string;\n}\n\nexport interface WorkflowSeed {\n name: string;\n /** The workflow graph, named as the service names it. */\n blob?: Record<string, unknown>;\n /**\n * @deprecated The mock called this `definition` before it was aligned to the\n * service contract. Still accepted so existing seed files keep working.\n */\n definition?: Record<string, unknown>;\n description?: string | null;\n active?: boolean;\n executionMode?: string;\n}\n\nexport interface DevSeeds {\n credentials?: CredentialSeed[];\n secrets?: SecretSeed[];\n workflows?: WorkflowSeed[];\n}\n\nconst ENV_REF = /\\$\\{([A-Z0-9_]+)\\}/g;\n\n/**\n * Recursively replaces `${ENV_VAR}` references in string values from `env`.\n * Throws a clear error when a referenced variable is unset so a developer\n * knows to add it to their `.env` — keeping secrets out of committed seeds.\n */\nexport function interpolateEnv<T>(value: T, env: NodeJS.ProcessEnv = process.env): T {\n if (typeof value === 'string') {\n return value.replace(ENV_REF, (_match, name: string) => {\n const resolved = env[name];\n if (resolved === undefined) {\n throw new Error(`Seed references \\${${name}} but that environment variable is not set (add it to your .env).`);\n }\n return resolved;\n }) as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map(item => interpolateEnv(item, env)) as unknown as T;\n }\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n out[key] = interpolateEnv(val, env);\n }\n return out as T;\n }\n return value;\n}\n\n/** Applies committed seeds to the store (env-interpolated). */\nexport function applySeeds(store: DevStore, seeds: DevSeeds, env: NodeJS.ProcessEnv = process.env): void {\n for (const secret of seeds.secrets ?? []) {\n const { key, value } = interpolateEnv(secret, env);\n store.setSecret(key, value);\n }\n for (const credential of seeds.credentials ?? []) {\n const resolved = interpolateEnv(credential, env);\n store.createCredential({\n credentialTypeSlug: resolved.credentialTypeSlug,\n name: resolved.name,\n config: resolved.config,\n id: resolved.id,\n status: resolved.status,\n durableCreds: resolved.durableCreds ?? null,\n });\n }\n for (const workflow of seeds.workflows ?? []) {\n const resolved = interpolateEnv(workflow, env);\n store.createWorkflow({\n name: resolved.name,\n blob: resolved.blob ?? resolved.definition ?? {},\n description: resolved.description,\n active: resolved.active,\n executionMode: resolved.executionMode,\n });\n }\n}\n\n/**\n * Reads a persisted session snapshot. Returns `null` (and warns) when the file\n * is absent or its `schemaVersion` no longer matches — the overlay is\n * disposable, so a mismatch is discarded rather than migrated.\n */\nexport function loadState(file: string, log: (msg: string) => void = console.warn): DevStoreSnapshot | null {\n if (!existsSync(file)) {\n return null;\n }\n let parsed: DevStoreSnapshot;\n try {\n parsed = JSON.parse(readFileSync(file, 'utf-8')) as DevStoreSnapshot;\n } catch {\n log(`Ignoring ${file}: not valid JSON.`);\n return null;\n }\n if (parsed.schemaVersion !== STORE_SCHEMA_VERSION) {\n log(`Ignoring ${file}: schemaVersion ${parsed.schemaVersion} != ${STORE_SCHEMA_VERSION} (discarded, seeds are the source of truth).`);\n return null;\n }\n return parsed;\n}\n\nexport function saveState(file: string, snapshot: DevStoreSnapshot): void {\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, JSON.stringify(snapshot, null, 2), 'utf-8');\n}\n\nconst SEED_ENTRY_CANDIDATES = ['index.ts', 'index.mjs', 'index.js', 'seeds.ts', 'seeds.js'];\n\n/**\n * Loads committed seeds from a directory (default `dev/seeds`). Resolves the\n * first present entry file and reads its `default` or named `seeds` export.\n * Returns empty seeds when no seed directory/entry exists.\n */\nexport async function loadSeedsFromDir(dir: string): Promise<DevSeeds> {\n for (const candidate of SEED_ENTRY_CANDIDATES) {\n const path = resolve(dir, candidate);\n if (existsSync(path)) {\n const mod = await importFresh<{ default?: DevSeeds; seeds?: DevSeeds }>(path);\n return mod.default ?? mod.seeds ?? {};\n }\n }\n return {};\n}\n","import { randomUUID } from 'node:crypto';\n\n/**\n * In-memory data store backing the mock Integrations API. Holds the tenant-\n * scoped resources a developer creates in the preview (credentials, secrets,\n * workflows, triggers). Serializable so a session can be persisted to and\n * rehydrated from `.revenexx-dev/state.json`.\n */\n\nexport const DEV_TENANT_ID = 'dev-tenant';\n\nexport interface CredentialRecord {\n id: string;\n tenantId: string;\n credentialTypeSlug: string;\n name: string;\n status: string;\n /** Full user-entered config, including secret fields (never sent to the UI verbatim). */\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth refresh token). */\n durableCreds: Record<string, unknown> | null;\n /** Outcome of the last `POST /credentials/{id}/test`, which the contract reports. */\n lastTestAt: string | null;\n lastTestOk: boolean | null;\n lastTestMessage: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface SecretRecord {\n key: string;\n value: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Field names follow the service's contract: the graph is `blob`, tagged with the\n * `blob_definition_version` it was written against. The mock used to call it\n * `definition`, which meant a workflow saved from the real UI silently lost its\n * graph — the UI sends `blob`, so `body.definition` was always undefined.\n */\nexport interface WorkflowRecord {\n id: number;\n name: string;\n description: string | null;\n blob: Record<string, unknown>;\n blobDefinitionVersion: string;\n active: boolean;\n executionMode: string;\n /** Bumped on every update, like the service's revision counter. */\n revision: number;\n buildStatus: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/** The only `blob_definition_version` the contract currently allows. */\nexport const BLOB_DEFINITION_VERSION = 'v0-draft';\n\n/** `execution_mode` values the contract allows; the first is the default. */\nexport const EXECUTION_MODES = ['async_only', 'sync_only', 'caller_decides'] as const;\n\nexport interface TriggerRecord {\n id: string;\n workflowId: number;\n type: string;\n name: string | null;\n config: Record<string, unknown>;\n active: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface DevStoreSnapshot {\n schemaVersion: number;\n credentials: CredentialRecord[];\n secrets: SecretRecord[];\n workflows: WorkflowRecord[];\n triggers: TriggerRecord[];\n nextWorkflowId: number;\n}\n\n/**\n * Bumped to 2 when workflows moved from `definition` to the contract's `blob` /\n * `blob_definition_version` / `active` / `execution_mode`. `loadState` discards an\n * overlay whose version does not match, which is the migration: seeds are the\n * source of truth, the overlay is disposable session state.\n */\nexport const STORE_SCHEMA_VERSION = 2;\n\nfunction now(): string {\n return new Date().toISOString();\n}\n\nexport class DevStore {\n private credentials = new Map<string, CredentialRecord>();\n private secrets = new Map<string, SecretRecord>();\n private workflows = new Map<number, WorkflowRecord>();\n private triggers = new Map<string, TriggerRecord>();\n private nextWorkflowId = 1;\n\n /**\n * @param onChange fired after any mutation so a caller (the CLI) can persist\n * the session to `.revenexx-dev/state.json`.\n */\n constructor(private onChange?: () => void) {}\n\n /** (Re)wire the post-mutation callback — e.g. attach it only after seeding. */\n setOnMutation(onChange: (() => void) | undefined): void {\n this.onChange = onChange;\n }\n\n private touch(): void {\n this.onChange?.();\n }\n\n // ------------------------------------------------------------- credentials\n\n listCredentials(typeSlug?: string): CredentialRecord[] {\n const all = [...this.credentials.values()];\n return typeSlug ? all.filter(c => c.credentialTypeSlug === typeSlug) : all;\n }\n\n getCredential(id: string): CredentialRecord | undefined {\n return this.credentials.get(id);\n }\n\n createCredential(input: {\n credentialTypeSlug: string;\n name: string;\n config: Record<string, unknown>;\n status?: string;\n /** Stable id — pass to keep a seeded credential's id fixed across restarts. */\n id?: string;\n durableCreds?: Record<string, unknown> | null;\n }): CredentialRecord {\n const ts = now();\n const record: CredentialRecord = {\n id: input.id ?? randomUUID(),\n tenantId: DEV_TENANT_ID,\n credentialTypeSlug: input.credentialTypeSlug,\n name: input.name,\n status: input.status ?? 'active',\n config: input.config,\n durableCreds: input.durableCreds ?? null,\n lastTestAt: null,\n lastTestOk: null,\n lastTestMessage: null,\n createdAt: ts,\n updatedAt: ts,\n };\n this.credentials.set(record.id, record);\n this.touch();\n return record;\n }\n\n updateCredential(id: string, patch: Partial<Pick<CredentialRecord, 'name' | 'config' | 'status' | 'durableCreds'>>): CredentialRecord | undefined {\n const record = this.credentials.get(id);\n if (!record) {\n return undefined;\n }\n if (patch.name !== undefined) {\n record.name = patch.name;\n }\n if (patch.config !== undefined) {\n record.config = patch.config;\n }\n if (patch.status !== undefined) {\n record.status = patch.status;\n }\n if (patch.durableCreds !== undefined) {\n record.durableCreds = patch.durableCreds;\n }\n record.updatedAt = now();\n this.touch();\n return record;\n }\n\n /**\n * Records the outcome of a credential test. The service persists this on the\n * record and reports it back from `POST /credentials/{id}/test`.\n */\n recordCredentialTest(id: string, result: { ok: boolean; message?: string | null }): CredentialRecord | undefined {\n const record = this.credentials.get(id);\n if (!record) {\n return undefined;\n }\n record.lastTestAt = now();\n record.lastTestOk = result.ok;\n record.lastTestMessage = result.message ?? null;\n this.touch();\n return record;\n }\n\n deleteCredential(id: string): boolean {\n const deleted = this.credentials.delete(id);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // ----------------------------------------------------------------- secrets\n\n listSecrets(): SecretRecord[] {\n return [...this.secrets.values()];\n }\n\n getSecret(key: string): SecretRecord | undefined {\n return this.secrets.get(key);\n }\n\n setSecret(key: string, value: string): SecretRecord {\n const existing = this.secrets.get(key);\n const ts = now();\n const record: SecretRecord = {\n key,\n value,\n createdAt: existing?.createdAt ?? ts,\n updatedAt: ts,\n };\n this.secrets.set(key, record);\n this.touch();\n return record;\n }\n\n deleteSecret(key: string): boolean {\n const deleted = this.secrets.delete(key);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // --------------------------------------------------------------- workflows\n\n listWorkflows(): WorkflowRecord[] {\n return [...this.workflows.values()];\n }\n\n getWorkflow(id: number): WorkflowRecord | undefined {\n return this.workflows.get(id);\n }\n\n createWorkflow(input: {\n name: string;\n blob: Record<string, unknown>;\n blobDefinitionVersion?: string;\n description?: string | null;\n active?: boolean;\n executionMode?: string;\n }): WorkflowRecord {\n const ts = now();\n const record: WorkflowRecord = {\n id: this.nextWorkflowId++,\n name: input.name,\n description: input.description ?? null,\n blob: input.blob,\n blobDefinitionVersion: input.blobDefinitionVersion ?? BLOB_DEFINITION_VERSION,\n active: input.active ?? true,\n executionMode: input.executionMode ?? EXECUTION_MODES[0],\n revision: 1,\n buildStatus: 'ready',\n createdAt: ts,\n updatedAt: ts,\n };\n this.workflows.set(record.id, record);\n this.touch();\n return record;\n }\n\n updateWorkflow(id: number, patch: Partial<Pick<WorkflowRecord, 'name' | 'description' | 'blob' | 'blobDefinitionVersion' | 'active' | 'executionMode' | 'buildStatus'>>): WorkflowRecord | undefined {\n const record = this.workflows.get(id);\n if (!record) {\n return undefined;\n }\n // Drop undefined so a partial PUT does not blank fields the caller omitted.\n const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined));\n Object.assign(record, defined, { revision: record.revision + 1, updatedAt: now() });\n this.touch();\n return record;\n }\n\n deleteWorkflow(id: number): boolean {\n for (const trigger of this.triggers.values()) {\n if (trigger.workflowId === id) {\n this.triggers.delete(trigger.id);\n }\n }\n const deleted = this.workflows.delete(id);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // ---------------------------------------------------------------- triggers\n\n listTriggers(workflowId: number): TriggerRecord[] {\n return [...this.triggers.values()].filter(t => t.workflowId === workflowId);\n }\n\n getTrigger(id: string): TriggerRecord | undefined {\n return this.triggers.get(id);\n }\n\n createTrigger(input: {\n workflowId: number;\n type: string;\n name?: string | null;\n config?: Record<string, unknown>;\n active?: boolean;\n id?: string;\n }): TriggerRecord {\n const ts = now();\n const record: TriggerRecord = {\n id: input.id ?? randomUUID(),\n workflowId: input.workflowId,\n type: input.type,\n name: input.name ?? null,\n config: input.config ?? {},\n active: input.active ?? true,\n createdAt: ts,\n updatedAt: ts,\n };\n this.triggers.set(record.id, record);\n this.touch();\n return record;\n }\n\n replaceTrigger(id: string, input: { type: string; name?: string | null; config?: Record<string, unknown>; active?: boolean }): TriggerRecord | undefined {\n const record = this.triggers.get(id);\n if (!record) {\n return undefined;\n }\n record.type = input.type;\n record.name = input.name ?? null;\n record.config = input.config ?? {};\n record.active = input.active ?? true;\n record.updatedAt = now();\n this.touch();\n return record;\n }\n\n deleteTrigger(id: string): boolean {\n const deleted = this.triggers.delete(id);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // ------------------------------------------------------------- persistence\n\n toSnapshot(): DevStoreSnapshot {\n return {\n schemaVersion: STORE_SCHEMA_VERSION,\n credentials: [...this.credentials.values()],\n secrets: [...this.secrets.values()],\n workflows: [...this.workflows.values()],\n triggers: [...this.triggers.values()],\n nextWorkflowId: this.nextWorkflowId,\n };\n }\n\n loadSnapshot(snapshot: DevStoreSnapshot): void {\n this.credentials = new Map(snapshot.credentials.map(c => [c.id, c]));\n this.secrets = new Map(snapshot.secrets.map(s => [s.key, s]));\n this.workflows = new Map(snapshot.workflows.map(w => [w.id, w]));\n this.triggers = new Map(snapshot.triggers.map(t => [t.id, t]));\n this.nextWorkflowId = snapshot.nextWorkflowId ?? Math.max(0, ...snapshot.workflows.map(w => w.id)) + 1;\n }\n\n /**\n * Overlays a snapshot on top of the current contents (upsert by id/key), used\n * to layer the persisted `.revenexx-dev/state.json` session over the freshly\n * applied committed seeds. State entries win over seed entries with the same\n * id/key; seed-only entries are preserved.\n */\n mergeSnapshot(snapshot: DevStoreSnapshot): void {\n for (const c of snapshot.credentials) {\n this.credentials.set(c.id, c);\n }\n for (const s of snapshot.secrets) {\n this.secrets.set(s.key, s);\n }\n for (const w of snapshot.workflows) {\n this.workflows.set(w.id, w);\n }\n for (const t of snapshot.triggers) {\n this.triggers.set(t.id, t);\n }\n this.nextWorkflowId = Math.max(this.nextWorkflowId, snapshot.nextWorkflowId ?? 0, ...snapshot.workflows.map(w => w.id + 1));\n }\n}\n","import {\n type IConfigField,\n type IConfigOption,\n type ICredential,\n type ICredentialContext,\n type ICredentialDescription,\n type ICredentialResolveResult,\n type ICredentialTestResult,\n type INode,\n type INodeAuthorContext,\n type IOutputPort,\n isOAuthAuthorizeCredential,\n} from '@revenexx/integrations-node-sdk';\nimport { DevApiError } from './errors.js';\nimport type { LoadedPackage } from './loader.js';\nimport type { DevStore } from './store.js';\n\n/**\n * The fidelity centre of the mock API: instead of the production sandbox +\n * content-addressed bundle, the developer's live node/credential instances are\n * invoked directly in-process. Author-time resolvers, credential `test`, and\n * `resolve` run exactly as the developer wrote them. The PO-145 grant/security\n * model is intentionally omitted — this is dev-only.\n */\n\nconst noopLogger = {\n info() {},\n warn() {},\n error() {},\n};\n\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split('.').map(n => Number.parseInt(n, 10) || 0);\n const pb = b.split('.').map(n => Number.parseInt(n, 10) || 0);\n for (let i = 0; i < 3; i++) {\n const diff = (pa[i] ?? 0) - (pb[i] ?? 0);\n if (diff !== 0) {\n return diff;\n }\n }\n return 0;\n}\n\nexport function nodeVersions(loaded: LoadedPackage, slug: string): string[] {\n return loaded.nodes\n .filter(n => n.description.slug === slug)\n .map(n => n.description.version)\n .sort((a, b) => compareSemver(b, a));\n}\n\nexport function findNode(loaded: LoadedPackage, slug: string, version?: string): INode {\n const matches = loaded.nodes.filter(n => n.description.slug === slug);\n if (matches.length === 0) {\n throw new DevApiError(404, `Node '${slug}' not found.`);\n }\n if (!version || version === 'latest') {\n return [...matches].sort((a, b) => compareSemver(b.description.version, a.description.version))[0]!;\n }\n const exact = matches.find(n => n.description.version === version);\n if (!exact) {\n throw new DevApiError(404, `Node '${slug}' has no version '${version}'.`);\n }\n return exact;\n}\n\nexport function findCredential(loaded: LoadedPackage, slug: string): ICredential {\n const cred = loaded.credentials.find(c => c.description.slug === slug);\n if (!cred) {\n throw new DevApiError(404, `Credential type '${slug}' not found.`);\n }\n return cred;\n}\n\nexport function findCredentialType(loaded: LoadedPackage, slug: string): ICredentialDescription {\n return findCredential(loaded, slug).description;\n}\n\nfunction credentialContext(store: DevStore, credentialId?: string): ICredentialContext {\n return {\n signal: new AbortController().signal,\n logger: noopLogger,\n persistDurableCreds: credentialId\n ? async (durableCreds: Record<string, unknown>) => {\n store.updateCredential(credentialId, { durableCreds });\n }\n : undefined,\n };\n}\n\n/** Resolves a credential instance's access data by running its real `resolve`. */\nexport async function resolveCredentialInstance(loaded: LoadedPackage, store: DevStore, credentialId: string): Promise<ICredentialResolveResult> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n const ctx = credentialContext(store, credentialId);\n return cred.resolve(ctx, instance.config, instance.durableCreds);\n}\n\nfunction authorContext(loaded: LoadedPackage, store: DevStore, config: Record<string, unknown>, locale?: string): INodeAuthorContext {\n return {\n signal: new AbortController().signal,\n logger: noopLogger,\n config,\n secrets: {\n async get(key: string): Promise<string> {\n const secret = store.getSecret(key);\n if (!secret) {\n throw new DevApiError(404, `Secret '${key}' not found.`);\n }\n return secret.value;\n },\n },\n credentials: {\n async get(id: string): Promise<Record<string, unknown>> {\n return (await resolveCredentialInstance(loaded, store, id)).credentials;\n },\n },\n locale,\n };\n}\n\nexport interface ResolveNodeConfigInput {\n slug: string;\n version?: string;\n /** `\"*\"` (all), `\"outputs\"`, or a specific config field key. */\n target: string;\n config: Record<string, unknown>;\n locale?: string;\n}\n\nexport interface ResolveNodeConfigResult {\n options?: IConfigOption[];\n fields?: IConfigField[];\n outputs?: IOutputPort[];\n}\n\n/**\n * Runs a node's author-time resolvers for the requested `target`, mirroring\n * the server's `config:resolve` semantics.\n */\nexport async function resolveNodeConfig(loaded: LoadedPackage, store: DevStore, input: ResolveNodeConfigInput): Promise<ResolveNodeConfigResult> {\n const node = findNode(loaded, input.slug, input.version);\n const ctx = authorContext(loaded, store, input.config ?? {}, input.locale);\n\n try {\n if (input.target === 'outputs') {\n if (!node.resolveOutputs) {\n return { outputs: [] };\n }\n return { outputs: await node.resolveOutputs(ctx) };\n }\n\n if (input.target === '*') {\n const result: ResolveNodeConfigResult = {};\n if (node.resolveConfigSchema) {\n result.fields = await node.resolveConfigSchema(ctx);\n }\n if (node.resolveOutputs) {\n result.outputs = await node.resolveOutputs(ctx);\n }\n return result;\n }\n\n // A specific config field key.\n const field = node.description.config?.find(f => f.key === input.target);\n if (field?.type === 'dynamic-schema') {\n if (!node.resolveConfigSchema) {\n return { fields: [] };\n }\n return { fields: await node.resolveConfigSchema(ctx) };\n }\n if (!node.loadOptions) {\n return { options: [] };\n }\n return { options: await node.loadOptions(ctx, input.target) };\n } catch (err) {\n if (err instanceof DevApiError) {\n throw err;\n }\n throw new DevApiError(502, `Node resolve failed: ${(err as Error).message}`);\n }\n}\n\nexport interface ValidateNodeConfigInput {\n slug: string;\n version?: string;\n config: Record<string, unknown>;\n locale?: string;\n}\n\nexport interface ValidateNodeConfigResult {\n valid: boolean;\n /** Config field key → human-readable messages. Empty object when valid. */\n errors: Record<string, string[]>;\n}\n\n/** True when a value counts as \"provided\" (mirrors the UI's `isResolvableValue`). */\nfunction isProvided(value: unknown): boolean {\n if (value === undefined || value === null) {\n return false;\n }\n if (typeof value === 'string') {\n return value.trim().length > 0;\n }\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n return true;\n}\n\n/** An expression placeholder (`${{…}}` / leading `=`) is \"set\" but not statically checkable. */\nfunction isExpression(value: unknown): boolean {\n return typeof value === 'string' && (value.startsWith('=') || value.includes('${{'));\n}\n\n/** Applies one field's static rules to `value`, pushing messages under `field.key`. */\nfunction validateField(field: IConfigField, value: unknown, errors: Record<string, string[]>): void {\n const push = (msg: string): void => {\n (errors[field.key] ??= []).push(msg);\n };\n const provided = isProvided(value);\n if (field.required && !provided) {\n push('This field is required.');\n return;\n }\n if (!provided || isExpression(value)) {\n // Optional-and-empty, or an expression the mock cannot evaluate — skip type/rules.\n return;\n }\n\n switch (field.type) {\n case 'string':\n case 'secret-ref':\n case 'expression':\n if (typeof value !== 'string') {\n push('Expected a string.');\n }\n break;\n case 'number':\n if (typeof value !== 'number' || Number.isNaN(value)) {\n push('Expected a number.');\n }\n break;\n case 'boolean':\n if (typeof value !== 'boolean') {\n push('Expected a boolean.');\n }\n break;\n case 'select':\n // Dynamic options are only known after resolve — can't check membership here.\n if (!field.dynamic && field.options && !field.options.some(o => o.value === value)) {\n push('Not one of the allowed options.');\n }\n break;\n case 'multiselect':\n if (!Array.isArray(value)) {\n push('Expected an array.');\n } else if (!field.dynamic && field.options) {\n const allowed = new Set(field.options.map(o => o.value));\n for (const v of value) {\n if (!allowed.has(v as string | number | boolean)) {\n push(`Value '${String(v)}' is not an allowed option.`);\n }\n }\n }\n break;\n case 'array':\n if (!Array.isArray(value)) {\n push('Expected an array.');\n }\n break;\n case 'object':\n if (typeof value !== 'object' || Array.isArray(value)) {\n push('Expected an object.');\n }\n break;\n // credentials-ref / dynamic-schema carry no scalar type check here.\n }\n\n const v = field.validation;\n if (v) {\n if (typeof value === 'string') {\n if (v.pattern !== undefined && !new RegExp(v.pattern).test(value)) {\n push(`Does not match pattern ${v.pattern}.`);\n }\n if (v.minLength !== undefined && value.length < v.minLength) {\n push(`Must be at least ${v.minLength} characters.`);\n }\n if (v.maxLength !== undefined && value.length > v.maxLength) {\n push(`Must be at most ${v.maxLength} characters.`);\n }\n }\n if (typeof value === 'number') {\n if (v.min !== undefined && value < v.min) {\n push(`Must be >= ${v.min}.`);\n }\n if (v.max !== undefined && value > v.max) {\n push(`Must be <= ${v.max}.`);\n }\n }\n if (Array.isArray(value)) {\n if (v.minLength !== undefined && value.length < v.minLength) {\n push(`Must have at least ${v.minLength} items.`);\n }\n if (v.maxLength !== undefined && value.length > v.maxLength) {\n push(`Must have at most ${v.maxLength} items.`);\n }\n }\n }\n}\n\n/**\n * Validates a submitted node `config` against the field rules in its manifest\n * (`required`, `IConfigValidation`, types, static options). For `dynamic-schema`\n * fields the resolved child schema is fetched and its rules applied to the\n * flattened keys. Deep cross-field validation is intentionally out of scope\n * (the production service does that on save); this mirrors the mock's\n * \"light, schema-based\" fidelity. Unknown extra keys are ignored.\n */\nexport async function validateNodeConfig(loaded: LoadedPackage, store: DevStore, input: ValidateNodeConfigInput): Promise<ValidateNodeConfigResult> {\n const node = findNode(loaded, input.slug, input.version);\n const config = input.config ?? {};\n const errors: Record<string, string[]> = {};\n const fields = node.description.config ?? [];\n\n for (const field of fields) {\n if (field.type === 'dynamic-schema') {\n continue; // resolved child fields are validated below\n }\n validateField(field, config[field.key], errors);\n }\n\n if (fields.some(f => f.type === 'dynamic-schema') && node.resolveConfigSchema) {\n const ctx = authorContext(loaded, store, config, input.locale);\n let children: IConfigField[];\n try {\n children = await node.resolveConfigSchema(ctx);\n } catch (err) {\n if (err instanceof DevApiError) {\n throw err;\n }\n throw new DevApiError(502, `Node resolve failed: ${(err as Error).message}`);\n }\n for (const child of children) {\n validateField(child, config[child.key], errors);\n }\n }\n\n return { valid: Object.keys(errors).length === 0, errors };\n}\n\nexport interface ExecuteNodeTestInput {\n slug: string;\n version?: string;\n /** The node's config values to run with. */\n config: Record<string, unknown>;\n /** Simulated input payloads, merged OVER the config (the contract's wording). */\n inputs: Record<string, unknown>;\n /** Wall-clock limit; clamped to >= 1000 ms like the real runtime. */\n timeoutMs?: number;\n}\n\nexport interface ExecuteNodeTestResult {\n outputs: Record<string, unknown>;\n branch: string | null;\n logs: Array<{ level: string; message: string; meta?: Record<string, unknown> }>;\n}\n\n/** Floor the contract puts on `timeout_ms`, and the default when none is given. */\nconst MIN_TIMEOUT_MS = 1000;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Thrown by the timeout arm of the race; never leaves `executeNodeTest`. */\nclass ExecuteTimeout extends Error {}\n\n/**\n * Runs a node's real `execute` in-process — the closest the mock gets to the\n * production sandbox, and the endpoint node authors care about most.\n *\n * `execute(ctx, inputs)` takes a single merged object, so `config` and `inputs`\n * are merged here with `inputs` winning, matching how the service describes it.\n * Logger calls are collected and returned as `logs` instead of being dropped.\n *\n * The timeout is enforced by racing, not just by aborting `ctx.signal`. A node\n * that never looks at the signal — an accidental infinite loop's `await`, a\n * third-party client that takes no `AbortSignal` — would otherwise hang the\n * request until Node's own 300 s `requestTimeout`, which is the opposite of what\n * \"honours timeout_ms\" should mean for someone debugging their own node. The\n * signal is still aborted first, so a well-behaved node fails fast and its own\n * error wins the race.\n */\nexport async function executeNodeTest(loaded: LoadedPackage, store: DevStore, input: ExecuteNodeTestInput): Promise<ExecuteNodeTestResult> {\n const node = findNode(loaded, input.slug, input.version);\n const logs: ExecuteNodeTestResult['logs'] = [];\n const record = (level: string) => (message: string, meta?: Record<string, unknown>) => {\n logs.push(meta === undefined ? { level, message } : { level, message, meta });\n };\n\n const timeoutMs = Math.max(MIN_TIMEOUT_MS, input.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n const controller = new AbortController();\n let timer: NodeJS.Timeout | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new ExecuteTimeout());\n }, timeoutMs);\n });\n\n const ctx = {\n signal: controller.signal,\n logger: { info: record('info'), warn: record('warn'), error: record('error') },\n secrets: {\n async get(key: string): Promise<string> {\n const secret = store.getSecret(key);\n if (!secret) {\n throw new DevApiError(404, `Secret '${key}' not found.`);\n }\n return secret.value;\n },\n },\n credentials: {\n async get(id: string): Promise<Record<string, unknown>> {\n return (await resolveCredentialInstance(loaded, store, id)).credentials;\n },\n },\n };\n\n try {\n const result = await Promise.race([node.execute(ctx, { ...input.config, ...input.inputs }), expired]);\n return { outputs: result.outputs ?? {}, branch: result.branch ?? null, logs };\n } catch (err) {\n if (err instanceof DevApiError) {\n throw err;\n }\n // The node itself threw, or the race expired. 502 mirrors how the mock reports a\n // failing author-time resolver, and the collected logs go along so the failure is\n // diagnosable — a timeout in particular is usually only readable from the logs\n // the node managed to emit before it stalled.\n const reason = err instanceof ExecuteTimeout || controller.signal.aborted ? `timed out after ${timeoutMs} ms` : (err as Error).message;\n throw new DevApiError(502, `Node execution failed: ${reason}`, { logs: logs.map(l => `${l.level}: ${l.message}`) });\n } finally {\n // Also stops the timer from holding the event loop open when the node won.\n clearTimeout(timer);\n }\n}\n\n/** Runs a credential type's `test` against inline (unsaved) config. */\nexport async function testCredentialConfig(loaded: LoadedPackage, store: DevStore, typeSlug: string, config: Record<string, unknown>): Promise<ICredentialTestResult> {\n const cred = findCredential(loaded, typeSlug);\n return cred.test(credentialContext(store), config);\n}\n\n/** Runs `test` against a saved credential instance's stored config. */\nexport async function testCredentialInstance(loaded: LoadedPackage, store: DevStore, credentialId: string): Promise<ICredentialTestResult> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n return cred.test(credentialContext(store, credentialId), instance.config);\n}\n\nexport async function buildOAuthAuthorizeUrl(\n loaded: LoadedPackage,\n store: DevStore,\n credentialId: string,\n params: { redirectUri: string; state: string },\n): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n if (!isOAuthAuthorizeCredential(cred)) {\n throw new DevApiError(422, `Credential type '${instance.credentialTypeSlug}' is not a 3-legged OAuth type.`);\n }\n return cred.buildAuthorizeUrl(credentialContext(store, credentialId), instance.config, params);\n}\n\nexport async function exchangeOAuthCode(\n loaded: LoadedPackage,\n store: DevStore,\n credentialId: string,\n params: { code: string; redirectUri: string; codeVerifier?: string },\n): Promise<{ durableCreds: Record<string, unknown> }> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n if (!isOAuthAuthorizeCredential(cred)) {\n throw new DevApiError(422, `Credential type '${instance.credentialTypeSlug}' is not a 3-legged OAuth type.`);\n }\n const out = await cred.exchangeCode(credentialContext(store, credentialId), instance.config, params);\n store.updateCredential(credentialId, { durableCreds: out.durableCreds, status: 'active' });\n return out;\n}\n","import http from 'node:http';\nimport { DevApiError } from './errors.js';\nimport { readJson, sendError, sendJson, sendNoContent } from './http.js';\nimport type { LoadedPackage } from './loader.js';\nimport { credentialInstanceToApi, credentialTypeToApi, nodeToApi, secretToApi, templateFullToApi, templateSummaryToApi, triggerToApi, workflowToApi } from './projections.js';\nimport {\n buildOAuthAuthorizeUrl,\n exchangeOAuthCode,\n executeNodeTest,\n findCredential,\n findCredentialType,\n nodeVersions,\n resolveNodeConfig,\n testCredentialConfig,\n testCredentialInstance,\n validateNodeConfig,\n} from './resolve.js';\nimport { DEV_TENANT_ID, type DevStore } from './store.js';\n\nexport interface DevServerDeps {\n /** Returns the currently-loaded package; a function so hot-reload can swap it. */\n getPackage(): LoadedPackage;\n store: DevStore;\n /** JSON schemas served at `/schemas/{domain}[/{version}]`, keyed by `domain` and `domain/version`. */\n schemas?: Record<string, unknown>;\n}\n\nconst SEGMENT = (s: string | undefined): string => decodeURIComponent(s ?? '');\n\n/** Builds the `(req, res)` request listener implementing the mock `/api/v1` surface. */\nexport function createRequestListener(deps: DevServerDeps): http.RequestListener {\n return (req, res) => {\n handle(req, res, deps).catch(err => sendError(res, err));\n };\n}\n\nexport function createDevServer(deps: DevServerDeps): http.Server {\n return http.createServer(createRequestListener(deps));\n}\n\nasync function handle(req: http.IncomingMessage, res: http.ServerResponse, deps: DevServerDeps): Promise<void> {\n const method = (req.method ?? 'GET').toUpperCase();\n if (method === 'OPTIONS') {\n sendJson(res, 204, {});\n return;\n }\n\n const url = new URL(req.url ?? '/', 'http://localhost');\n let pathname = url.pathname;\n if (pathname.startsWith('/api/v1')) {\n pathname = pathname.slice('/api/v1'.length);\n }\n const seg = pathname.split('/').filter(Boolean).map(SEGMENT);\n const loaded = deps.getPackage();\n const store = deps.store;\n\n switch (seg[0]) {\n case undefined:\n case 'health':\n // The service's health route is `/up` (Laravel's default); `/health` is kept\n // because the devkit has always answered there.\n case 'up':\n return void sendJson(res, 200, { status: 'ok' });\n\n case 'me':\n // Shape per the contract: { user, context, claims }. The mock used to send a\n // flat { id, name, email, tenant_id }, which no real client could consume.\n return void sendJson(res, 200, {\n user: { id: 1, zitadel_id: 'dev-user', email: 'dev@revenexx.test', name: 'Dev User' },\n context: { tenant_id: DEV_TENANT_ID, active_plane: 'public', roles: ['admin', 'user'] },\n claims: { iss: 'https://id.revenexx.test', sub: 'dev-user', aud: ['devkit'] },\n });\n\n case 'schemas':\n return handleSchemas(res, deps, seg);\n\n case 'nodes':\n return handleNodes(req, res, method, loaded, store, seg);\n\n case 'credential-types':\n return handleCredentialTypes(res, loaded, seg);\n\n case 'credentials':\n return handleCredentials(req, res, method, loaded, store, seg, url);\n\n case 'secrets':\n return handleSecrets(req, res, method, store, seg);\n\n case 'templates':\n return handleTemplates(req, res, method, loaded, store, seg);\n\n case 'workflows':\n return handleWorkflows(req, res, method, store, seg);\n\n default:\n return void sendJson(res, 404, { message: `No route for /${seg.join('/')}` });\n }\n}\n\n// --------------------------------------------------------------------- schemas\n\n/**\n * The two schema routes have DIFFERENT shapes in the contract, which the mock\n * previously collapsed into one (it served the raw schema at both paths):\n *\n * GET /schemas/{domain} -> { domain, versions: string[] } (a listing)\n * GET /schemas/{domain}/{version} -> { domain, version, schema: {…} } (wrapped)\n *\n * Keys in `deps.schemas` are `domain` and `domain/version`, from the\n * `<domain>-<version>.json` files in assets/schemas.\n */\nfunction handleSchemas(res: http.ServerResponse, deps: DevServerDeps, seg: string[]): void {\n const domain = seg[1];\n const version = seg[2];\n if (!domain) {\n throw new DevApiError(404, 'Schema domain required.');\n }\n const schemas = deps.schemas ?? {};\n\n if (!version) {\n const versions = Object.keys(schemas)\n .filter(key => key.startsWith(`${domain}/`))\n .map(key => key.slice(domain.length + 1))\n .sort();\n if (versions.length === 0 && !schemas[domain]) {\n throw new DevApiError(404, `Unknown schema domain '${domain}'. Vendor it into assets/schemas.`);\n }\n return void sendJson(res, 200, { domain, versions });\n }\n\n // Exact match only. Falling back to the bare-domain (latest) entry would answer\n // 200 for EVERY version string — a node author asking for a version that does not\n // exist would be handed the latest schema and told it was the one they asked for.\n const schema = schemas[`${domain}/${version}`];\n if (!schema) {\n throw new DevApiError(404, `Unknown schema version '${domain}/${version}'. Vendor it into assets/schemas.`);\n }\n sendJson(res, 200, { domain, version, schema });\n}\n\n// ----------------------------------------------------------------------- nodes\n\nasync function handleNodes(req: http.IncomingMessage, res: http.ServerResponse, method: string, loaded: LoadedPackage, store: DevStore, seg: string[]): Promise<void> {\n // GET /nodes\n if (seg.length === 1 && method === 'GET') {\n return void sendJson(res, 200, { data: loaded.manifest.nodes.map(n => nodeToApi(n, nodeApiContext(loaded))) });\n }\n const slug = seg[1];\n if (!slug) {\n throw new DevApiError(404, 'Node slug required.');\n }\n\n // GET /nodes/{slug}/versions\n if (seg[2] === 'versions' && method === 'GET') {\n const versions = nodeVersions(loaded, slug);\n if (versions.length === 0) {\n throw new DevApiError(404, `Node '${slug}' not found.`);\n }\n return void sendJson(res, 200, { data: versions });\n }\n\n const version = seg[2];\n if (!version) {\n throw new DevApiError(404, 'Node version required.');\n }\n\n // POST /nodes/{slug}/{version}/config:resolve\n if (seg[3] === 'config:resolve' && method === 'POST') {\n const body = await readJson<{ target?: string; config?: Record<string, unknown>; locale?: string }>(req);\n if (!body.target) {\n throw new DevApiError(422, 'Field `target` is required.', { target: ['The target field is required.'] });\n }\n const result = await resolveNodeConfig(loaded, store, {\n slug,\n version,\n target: body.target,\n config: body.config ?? {},\n locale: body.locale,\n });\n return void sendJson(res, 200, result);\n }\n\n // POST /nodes/{slug}/{version}/config:validate\n //\n // DEVKIT-ONLY: this endpoint does NOT exist in the real integrations API. It\n // backs the preview host's `/nodes` page (Save → verdict + refused fields).\n // Listed in DEVKIT_ONLY in tests/contract.test.ts; do not build node code that\n // depends on it existing in production.\n if (seg[3] === 'config:validate' && method === 'POST') {\n const body = await readJson<{ config?: Record<string, unknown>; locale?: string }>(req);\n const result = await validateNodeConfig(loaded, store, {\n slug,\n version,\n config: body.config ?? {},\n locale: body.locale,\n });\n // 200 even when invalid — the `{ valid, errors }` body carries the verdict.\n return void sendJson(res, 200, result);\n }\n\n // POST /nodes/{slug}/{version}/execute:test\n if (seg[3] === 'execute:test' && method === 'POST') {\n const body = await readJson<{ config?: Record<string, unknown>; inputs?: Record<string, unknown>; timeout_ms?: number }>(req);\n const result = await executeNodeTest(loaded, store, {\n slug,\n version,\n config: body.config ?? {},\n inputs: body.inputs ?? {},\n timeoutMs: body.timeout_ms,\n });\n return void sendJson(res, 200, result);\n }\n\n // GET /nodes/{slug}/{version}\n if (seg.length === 3 && method === 'GET') {\n return void sendJson(res, 200, nodeToApi(findManifestNode(loaded, slug, version), nodeApiContext(loaded)));\n }\n\n // DELETE /nodes/{slug}/{version}\n //\n // The mock has no node registry to delete from — nodes come from the package\n // entry on disk. The route exists so the shape of a real deletion (404 for an\n // unknown node, 204 for a known one) is what an author sees.\n if (seg.length === 3 && method === 'DELETE') {\n findManifestNode(loaded, slug, version);\n return void sendNoContent(res);\n }\n\n throw new DevApiError(404, `No route for nodes/${seg.slice(1).join('/')}`);\n}\n\n/** The package identity + load time `GET /nodes` reports alongside each node. */\nfunction nodeApiContext(loaded: LoadedPackage) {\n return { packageInfo: loaded.packageInfo, loadedAt: loaded.loadedAt };\n}\n\n/**\n * Resolves a node's MANIFEST entry (what `GET /nodes` projects), or throws 404.\n * Distinct from resolve.ts's `findNode`, which returns the live INode instance.\n */\nfunction findManifestNode(loaded: LoadedPackage, slug: string, version: string) {\n const node = loaded.manifest.nodes.find(n => n.slug === slug && (version === 'latest' || n.version === version));\n if (!node) {\n throw new DevApiError(404, `Node '${slug}@${version}' not found.`);\n }\n return node;\n}\n\n// ------------------------------------------------------------- credential-types\n\nfunction handleCredentialTypes(res: http.ServerResponse, loaded: LoadedPackage, seg: string[]): void {\n if (seg.length === 1) {\n return void sendJson(res, 200, {\n data: (loaded.manifest.credentials ?? []).map(credentialTypeToApi),\n });\n }\n const slug = seg[1]!;\n const type = findCredentialType(loaded, slug); // throws 404\n sendJson(res, 200, { data: credentialTypeToApi(type) });\n}\n\n// ----------------------------------------------------------------- credentials\n\nasync function handleCredentials(req: http.IncomingMessage, res: http.ServerResponse, method: string, loaded: LoadedPackage, store: DevStore, seg: string[], url: URL): Promise<void> {\n const typeOf = (slug: string) => {\n try {\n return findCredentialType(loaded, slug);\n } catch {\n return undefined;\n }\n };\n\n // Collection-level routes.\n if (seg.length === 1) {\n if (method === 'GET') {\n const filter = url.searchParams.get('type') ?? undefined;\n const data = store.listCredentials(filter).map(c => credentialInstanceToApi(c, typeOf(c.credentialTypeSlug)));\n return void sendJson(res, 200, { data });\n }\n if (method === 'POST') {\n const body = await readJson<{ credential_type_slug?: string; name?: string; config?: Record<string, unknown> }>(req);\n if (!body.credential_type_slug || !body.name) {\n throw new DevApiError(422, 'Fields `credential_type_slug` and `name` are required.');\n }\n findCredential(loaded, body.credential_type_slug); // 404 if unknown type\n const record = store.createCredential({\n credentialTypeSlug: body.credential_type_slug,\n name: body.name,\n config: body.config ?? {},\n });\n return void sendJson(res, 201, credentialInstanceToApi(record, typeOf(record.credentialTypeSlug)));\n }\n }\n\n // POST /credentials/test (inline, unsaved)\n if (seg[1] === 'test' && method === 'POST') {\n const body = await readJson<{ credential_type_slug?: string; config?: Record<string, unknown> }>(req);\n if (!body.credential_type_slug) {\n throw new DevApiError(422, 'Field `credential_type_slug` is required.');\n }\n const result = await testCredentialConfig(loaded, store, body.credential_type_slug, body.config ?? {});\n return void sendJson(res, 200, result);\n }\n\n // GET /credentials/oauth/callback\n if (seg[1] === 'oauth' && seg[2] === 'callback' && method === 'GET') {\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n if (!code || !state) {\n throw new DevApiError(422, 'OAuth callback requires `code` and `state`.');\n }\n // The state carries the credential id in the dev flow (see authorize-url below).\n const credentialId = state;\n const redirectUri = `${url.origin}/api/v1/credentials/oauth/callback`;\n await exchangeOAuthCode(loaded, store, credentialId, { code, redirectUri });\n return void sendJson(res, 200, { status: 'connected', credential_id: credentialId });\n }\n\n const id = seg[1];\n if (!id) {\n throw new DevApiError(404, 'Credential id required.');\n }\n\n // POST /credentials/{id}/test\n if (seg[2] === 'test' && method === 'POST') {\n const result = await testCredentialInstance(loaded, store, id);\n // The contract reports the recorded outcome alongside the verdict — the\n // service persists it on the credential. (The inline variant,\n // POST /credentials/test, returns the bare `{ ok }` and records nothing,\n // because there is no record yet.)\n const record = store.recordCredentialTest(id, { ok: result.ok, message: result.message ?? null });\n return void sendJson(res, 200, {\n ok: result.ok,\n message: result.message ?? null,\n last_test_at: record?.lastTestAt ?? null,\n last_test_ok: record?.lastTestOk ?? result.ok,\n });\n }\n\n // POST /credentials/{id}/oauth/authorize-url\n if (seg[2] === 'oauth' && seg[3] === 'authorize-url' && method === 'POST') {\n const redirectUri = 'http://localhost/api/v1/credentials/oauth/callback';\n // Dev flow: carry the credential id in `state` so the callback can find it.\n const result = await buildOAuthAuthorizeUrl(loaded, store, id, { redirectUri, state: id });\n return void sendJson(res, 200, { authorize_url: result.authorizeUrl });\n }\n\n // Item-level routes.\n if (seg.length === 2) {\n const record = store.getCredential(id);\n if (method === 'GET') {\n if (!record) {\n throw new DevApiError(404, `Credential '${id}' not found.`);\n }\n return void sendJson(res, 200, credentialInstanceToApi(record, typeOf(record.credentialTypeSlug)));\n }\n if (method === 'PATCH') {\n if (!record) {\n throw new DevApiError(404, `Credential '${id}' not found.`);\n }\n const body = await readJson<{ name?: string; config?: Record<string, unknown> }>(req);\n const updated = store.updateCredential(id, { name: body.name, config: body.config });\n return void sendJson(res, 200, credentialInstanceToApi(updated!, typeOf(updated!.credentialTypeSlug)));\n }\n if (method === 'DELETE') {\n store.deleteCredential(id);\n return void sendNoContent(res);\n }\n }\n\n throw new DevApiError(404, `No route for credentials/${seg.slice(1).join('/')}`);\n}\n\n// --------------------------------------------------------------------- secrets\n\nasync function handleSecrets(req: http.IncomingMessage, res: http.ServerResponse, method: string, store: DevStore, seg: string[]): Promise<void> {\n if (seg.length === 1) {\n if (method === 'GET') {\n // The contract's top-level property is `keys: string[]` — a bare key list,\n // not records. The mock used to send `{ data: [{key, created_at, …}] }`,\n // which is why the UI carries a three-way envelope fallback.\n return void sendJson(res, 200, { keys: store.listSecrets().map(s => s.key) });\n }\n if (method === 'POST') {\n const body = await readJson<{ key?: string; value?: string }>(req);\n if (!body.key || body.value === undefined) {\n throw new DevApiError(422, 'Fields `key` and `value` are required.');\n }\n const record = store.setSecret(body.key, body.value);\n return void sendJson(res, 201, secretToApi(record));\n }\n }\n const key = seg[1];\n if (key) {\n if (method === 'PATCH') {\n const body = await readJson<{ value?: string }>(req);\n if (body.value === undefined) {\n throw new DevApiError(422, 'Field `value` is required.');\n }\n return void sendJson(res, 200, secretToApi(store.setSecret(key, body.value)));\n }\n if (method === 'DELETE') {\n store.deleteSecret(key);\n return void sendNoContent(res);\n }\n }\n throw new DevApiError(404, `No route for secrets/${seg.slice(1).join('/')}`);\n}\n\n// ------------------------------------------------------------------- templates\n\nasync function handleTemplates(req: http.IncomingMessage, res: http.ServerResponse, method: string, loaded: LoadedPackage, store: DevStore, seg: string[]): Promise<void> {\n const templates = loaded.manifest.templates ?? [];\n if (seg.length === 1 && method === 'GET') {\n return void sendJson(res, 200, { data: templates.map(templateSummaryToApi) });\n }\n const slug = seg[1];\n const template = templates.find(t => t.slug === slug);\n if (!template) {\n throw new DevApiError(404, `Template '${slug}' not found.`);\n }\n if (seg.length === 2 && method === 'GET') {\n // Wrapped in `data` per the contract; the mock used to return it bare.\n return void sendJson(res, 200, { data: templateFullToApi(template) });\n }\n if (seg[2] === 'requirements' && method === 'GET') {\n // The contract's key is `credentialTypes` (the mock said `credentials`).\n // Resolving what a template's blob actually references is not implemented —\n // an empty requirement set is honest, not a stand-in for real analysis.\n return void sendJson(res, 200, { data: { credentialTypes: [], secrets: [] } });\n }\n if (seg[2] === 'instantiate' && method === 'POST') {\n const body = await readJson<{ name?: string }>(req);\n // A template's `definition` IS a workflow blob authored against its\n // `blobVersion` (see ITemplateDescription), so it maps straight onto the\n // workflow's blob + blob_definition_version.\n const workflow = store.createWorkflow({\n name: body.name ?? String(template.name),\n blob: template.definition,\n blobDefinitionVersion: template.blobVersion,\n });\n for (const trigger of template.triggers ?? []) {\n store.createTrigger({\n workflowId: workflow.id,\n type: trigger.type,\n name: trigger.name ?? null,\n config: trigger.config ?? {},\n active: trigger.active ?? true,\n id: trigger.handle,\n });\n }\n return void sendJson(res, 201, workflowToApi(workflow));\n }\n throw new DevApiError(404, `No route for templates/${seg.slice(1).join('/')}`);\n}\n\n// ------------------------------------------------------------------- workflows\n\n/**\n * Body of POST /workflows and PUT /workflows/{id}, in the contract's snake_case.\n * Note `blob` — NOT `definition`. The mock read `body.definition` until 0.2.2,\n * so every workflow saved from the real UI silently stored an empty graph.\n */\ninterface WorkflowWriteBody {\n name?: string;\n description?: string | null;\n blob?: Record<string, unknown>;\n blob_definition_version?: string;\n active?: boolean;\n execution_mode?: string;\n}\n\nasync function handleWorkflows(req: http.IncomingMessage, res: http.ServerResponse, method: string, store: DevStore, seg: string[]): Promise<void> {\n if (seg.length === 1) {\n if (method === 'GET') {\n return void sendJson(res, 200, { data: store.listWorkflows().map(workflowToApi) });\n }\n if (method === 'POST') {\n const body = await readJson<WorkflowWriteBody>(req);\n const workflow = store.createWorkflow({\n name: body.name ?? 'Untitled workflow',\n blob: body.blob ?? {},\n blobDefinitionVersion: body.blob_definition_version,\n description: body.description,\n active: body.active,\n executionMode: body.execution_mode,\n });\n return void sendJson(res, 201, workflowToApi(workflow));\n }\n }\n\n // Collection sub-routes registered before {id}.\n if (seg[1] === 'used-credentials' && method === 'GET') {\n return void sendJson(res, 200, { data: [] });\n }\n if (seg[1] === 'used-credential-types' && method === 'GET') {\n return void sendJson(res, 200, { data: [] });\n }\n\n const id = Number.parseInt(seg[1] ?? '', 10);\n if (Number.isNaN(id)) {\n throw new DevApiError(404, `No route for workflows/${seg.slice(1).join('/')}`);\n }\n\n // Triggers\n if (seg[2] === 'triggers') {\n if (seg.length === 3 && method === 'GET') {\n return void sendJson(res, 200, { data: store.listTriggers(id).map(triggerToApi) });\n }\n if (seg.length === 3 && method === 'POST') {\n const body = await readJson<{ type?: string; name?: string; config?: Record<string, unknown>; active?: boolean }>(req);\n if (!body.type) {\n throw new DevApiError(422, 'Field `type` is required.');\n }\n const trigger = store.createTrigger({ workflowId: id, type: body.type, name: body.name, config: body.config, active: body.active });\n return void sendJson(res, 201, triggerToApi(trigger));\n }\n const triggerId = seg[3];\n if (triggerId && method === 'PUT') {\n const body = await readJson<{ type?: string; name?: string; config?: Record<string, unknown>; active?: boolean }>(req);\n if (!body.type) {\n throw new DevApiError(422, 'Field `type` is required.');\n }\n const trigger = store.replaceTrigger(triggerId, { type: body.type, name: body.name, config: body.config, active: body.active });\n if (!trigger) {\n throw new DevApiError(404, `Trigger '${triggerId}' not found.`);\n }\n return void sendJson(res, 200, triggerToApi(trigger));\n }\n if (triggerId && method === 'DELETE') {\n store.deleteTrigger(triggerId);\n return void sendNoContent(res);\n }\n }\n\n // Item-level workflow routes.\n if (seg.length === 2) {\n const record = store.getWorkflow(id);\n if (method === 'GET') {\n if (!record) {\n throw new DevApiError(404, `Workflow '${id}' not found.`);\n }\n return void sendJson(res, 200, workflowToApi(record));\n }\n if (method === 'PUT') {\n const body = await readJson<WorkflowWriteBody>(req);\n const updated = store.updateWorkflow(id, {\n name: body.name,\n blob: body.blob,\n blobDefinitionVersion: body.blob_definition_version,\n description: body.description,\n active: body.active,\n executionMode: body.execution_mode,\n });\n if (!updated) {\n throw new DevApiError(404, `Workflow '${id}' not found.`);\n }\n return void sendJson(res, 200, workflowToApi(updated));\n }\n if (method === 'DELETE') {\n store.deleteWorkflow(id);\n return void sendNoContent(res);\n }\n }\n\n if ((seg[2] === 'credentials' || seg[2] === 'credential-types') && method === 'GET') {\n return void sendJson(res, 200, { data: [] });\n }\n\n throw new DevApiError(404, `No route for workflows/${seg.slice(1).join('/')}`);\n}\n","import type http from 'node:http';\nimport { DevApiError } from './errors.js';\n\n/**\n * The `/api/v1` contract version this mock implements. Mirrors what the real\n * service reports via its `SetApiVersion` middleware.\n *\n * Kept as a constant rather than read from the vendored spec so nothing 357 KB\n * has to ship in the package; `tests/contract.test.ts` asserts it equals\n * `info.version` of `contract/integrations-v1.json`, so the two cannot drift.\n */\nexport const API_VERSION = '1.0.0';\n\nconst BASE_HEADERS = {\n 'X-Api-Version': API_VERSION,\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',\n};\n\nexport function sendJson(res: http.ServerResponse, status: number, body: unknown): void {\n const payload = JSON.stringify(body);\n res.writeHead(status, { 'Content-Type': 'application/json', ...BASE_HEADERS });\n res.end(payload);\n}\n\n/**\n * 204 with no body, which is what the service returns from every DELETE. The mock\n * used to answer `200 {deleted:true}`; per ADR-0036 §3 a changed status code is a\n * breaking difference, so that was training node authors on behaviour the real API\n * does not have.\n */\nexport function sendNoContent(res: http.ServerResponse): void {\n res.writeHead(204, BASE_HEADERS);\n res.end();\n}\n\n/** Maps a thrown error to the Laravel-style `{message}` / `{message, errors}` body. */\nexport function sendError(res: http.ServerResponse, err: unknown): void {\n if (err instanceof DevApiError) {\n sendJson(res, err.status, err.errors ? { message: err.message, errors: err.errors } : { message: err.message });\n return;\n }\n sendJson(res, 500, { message: (err as Error)?.message ?? 'Internal error' });\n}\n\nexport async function readBody(req: http.IncomingMessage): Promise<string> {\n let body = '';\n for await (const chunk of req) {\n body += chunk;\n }\n return body;\n}\n\n/** Reads + parses a JSON body; throws {@link DevApiError} 400 on malformed input. */\nexport async function readJson<T>(req: http.IncomingMessage): Promise<T> {\n const raw = await readBody(req);\n if (raw.trim() === '') {\n return {} as T;\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n throw new DevApiError(400, 'Invalid JSON body.');\n }\n}\n","import type { ICredentialDescription, INodeDescription, ITemplateDescription } from '@revenexx/integrations-node-sdk';\nimport type { PackageInfo } from './loader.js';\nimport { MANIFEST_VERSION } from '@revenexx/integrations-node-sdk';\nimport type { CredentialRecord, SecretRecord, TriggerRecord, WorkflowRecord } from './store.js';\n\n/**\n * Maps internal records + manifest descriptions to the exact JSON shapes the\n * production Laravel `/api/v1` surface returns, so the Cockpit UI consumes the\n * mock API without any awareness that it is mocked.\n */\n\nexport function hasDynamicOptions(desc: INodeDescription): boolean {\n return (desc.config ?? []).some(f => f.dynamic === true);\n}\n\nexport function hasDynamicSchema(desc: INodeDescription): boolean {\n return (desc.config ?? []).some(f => f.type === 'dynamic-schema');\n}\n\nexport function hasDynamicOutputs(desc: INodeDescription): boolean {\n return (desc.outputs ?? []).some(o => o.resolveOutputs === true);\n}\n\nexport interface NodeApiContext {\n packageInfo: PackageInfo;\n loadedAt: string;\n}\n\nexport function nodeToApi(desc: INodeDescription, ctx?: NodeApiContext): Record<string, unknown> {\n const [namespace] = desc.slug.split(':');\n return {\n name: desc.name,\n namespace: namespace ?? null,\n slug: desc.slug,\n version: desc.version,\n // The contract declares `package` and both timestamps as present. Nodes here\n // come from the developer's working tree, so the package identity is read from\n // their package.json and the timestamps are when the mock loaded the entry.\n package: ctx?.packageInfo ?? null,\n manifest_version: MANIFEST_VERSION,\n manifest: desc,\n has_dynamic_options: hasDynamicOptions(desc),\n has_dynamic_schema: hasDynamicSchema(desc),\n has_dynamic_outputs: hasDynamicOutputs(desc),\n created_at: ctx?.loadedAt ?? null,\n updated_at: ctx?.loadedAt ?? null,\n };\n}\n\nexport function credentialTypeToApi(desc: ICredentialDescription): Record<string, unknown> {\n return {\n slug: desc.slug,\n version: desc.version,\n name: desc.name,\n description: desc.description ?? null,\n icon: desc.icon ?? null,\n images: desc.images ?? [],\n auth_kind: desc.authKind,\n fields: desc.fields,\n };\n}\n\n/** Projects a credential instance to its masked public API shape (no secrets). */\nexport function credentialInstanceToApi(record: CredentialRecord, type: ICredentialDescription | undefined): Record<string, unknown> {\n const secretKeys = new Set((type?.fields ?? []).filter(f => f.type === 'secret').map(f => f.key));\n const knownKeys = new Set((type?.fields ?? []).map(f => f.key));\n const publicConfig: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record.config)) {\n // Only surface known, non-secret fields; drop everything else defensively.\n if (knownKeys.has(key) && !secretKeys.has(key)) {\n publicConfig[key] = value;\n }\n }\n return {\n id: record.id,\n tenant_id: record.tenantId,\n credential_type_slug: record.credentialTypeSlug,\n name: record.name,\n status: record.status,\n public_config: publicConfig,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\nexport function secretToApi(record: SecretRecord): Record<string, unknown> {\n return {\n key: record.key,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\n/**\n * NOTE the asymmetry, which is the contract's and not a mistake here: a WORKFLOW\n * carries its graph as `blob` + `blob_definition_version`, while a TEMPLATE\n * carries its graph as `definition` + `blob_version`.\n */\nexport function workflowToApi(record: WorkflowRecord): Record<string, unknown> {\n return {\n id: record.id,\n name: record.name,\n description: record.description,\n blob_definition_version: record.blobDefinitionVersion,\n blob: record.blob,\n active: record.active,\n execution_mode: record.executionMode,\n revision: record.revision,\n // The service reports blob-validation warnings here. The mock's validation is\n // schema-light (see the fidelity caveats), so it never has any — but the field\n // is part of the contract and clients may read it.\n warnings: [],\n build_status: record.buildStatus,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\nexport function triggerToApi(record: TriggerRecord): Record<string, unknown> {\n return {\n handle: record.id,\n id: record.id,\n workflow_id: record.workflowId,\n type: record.type,\n name: record.name,\n config: record.config,\n active: record.active,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\nexport function templateSummaryToApi(t: ITemplateDescription): Record<string, unknown> {\n return {\n slug: t.slug,\n version: t.version,\n category: t.category,\n level: t.level,\n name: t.name,\n shortDescription: t.shortDescription ?? null,\n description: t.description ?? null,\n icon: t.icon ?? null,\n images: t.images ?? [],\n industries: t.industries ?? [],\n vendors: t.vendors ?? [],\n triggerTypes: (t.triggers ?? []).map(tr => tr.type),\n };\n}\n\nexport function templateFullToApi(t: ITemplateDescription): Record<string, unknown> {\n return {\n ...templateSummaryToApi(t),\n // snake_case per the contract, even though the surrounding template fields are\n // camelCase and the SDK's own field is `blobVersion`.\n blob_version: t.blobVersion,\n definition: t.definition,\n // `config` is optional in the SDK (a manual trigger has none) but declared in\n // the contract, so normalise it to an object rather than omitting it.\n triggers: (t.triggers ?? []).map(tr => ({ ...tr, config: tr.config ?? {} })),\n };\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACgB9D,IAAAA,kBAA6D;AAE7D,IAAAC,oBAA6B;AAC7B,yBAA8B;AAC9B,IAAAC,oBAAuC;AACvC,IAAAC,mBAA8B;;;ACjC9B,qBAA2B;AAC3B,uBAAkC;AAoC3B,IAAM,oBAAoB;AAGjC,IAAM,mBAAmB,CAAC,cAAc,sBAAsB;AAgBvD,SAAS,iBAAiB,MAA+B;AAC9D,SAAO,iBAAiB,KAAK,UAAQ,KAAK,SAAS,IAAI,KAAK,KAAK,KAAK,SAAO,IAAI,WAAW,GAAG,IAAI,GAAG,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AA,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;AAClB,UAAQ,MAAM,GAAG;AACjB,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["import_node_fs","import_node_http","import_node_path","import_node_url","import_node_fs","import_node_fs","import_node_path","import_node_fs","import_node_path","import_integrations_node_sdk","v","import_integrations_node_sdk","import_node_crypto","import_node_fs","import_node_path","import_node_url","relative","envFile","rmSync"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/tsup/assets/cjs_shims.js","../src/cli.ts","../src/cli-args.ts","../src/errors.ts","../src/ports.ts","../src/env.ts","../src/index.ts","../src/loader.ts","../src/persistence.ts","../src/store.ts","../src/resolve.ts","../src/server.ts","../src/http.ts","../src/projections.ts","../src/preview/child-env.ts","../src/preview/host.ts","../src/preview/pid.ts","../src/preview/registry.ts"],"sourcesContent":["// Shim globals in cjs bundle\n// There's a weird bug that esbuild will always inject importMetaUrl\n// if we export it as `const importMetaUrl = ... __filename ...`\n// But using a function will not cause this issue\n\nconst getImportMetaUrl = () => \n typeof document === \"undefined\" \n ? new URL(`file:${__filename}`).href \n : (document.currentScript && document.currentScript.tagName.toUpperCase() === 'SCRIPT') \n ? document.currentScript.src \n : new URL(\"main.js\", document.baseURI).href;\n\nexport const importMetaUrl = /* @__PURE__ */ getImportMetaUrl()\n","#!/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","/**\n * An error that maps to an HTTP status + JSON body in the mock API, mirroring\n * Laravel's `{message}` / `{message, errors}` envelopes.\n */\nexport class DevApiError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n public readonly errors?: Record<string, string[]>,\n ) {\n super(message);\n this.name = 'DevApiError';\n }\n}\n\n/**\n * An error whose message is the whole story for the user — a wrong flag, an\n * occupied port, a refused second preview.\n *\n * The CLI's top-level handler prints these as a single line and exits 1, rather\n * than the stack trace it prints for a genuine defect. That distinction is the\n * point: a stack trace on `--port abc` teaches the reader nothing and buries the\n * one line that matters.\n */\nexport class CliError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'CliError';\n }\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","import { existsSync } from 'node:fs';\nimport { basename, resolve } from 'node:path';\n\n/**\n * `.env` loading for the CLI.\n *\n * Seeds reference secrets as `${VAR}` and {@link interpolateEnv} resolves those\n * from `process.env`, so without this the documented workflow — commit the\n * reference, keep the value in `.env` — only worked if the developer exported\n * the variables by hand.\n *\n * Loading happens before option parsing, because the CLI reads `PORT` for its\n * default port; a `.env` that sets `PORT` would otherwise be read too late.\n *\n * Exactly one file is ever loaded: `.env` by default, or the one named by\n * `--env`, which *replaces* the default rather than layering on top of it.\n * \"Use this env file\" is what the flag reads like, so leaving `.env` in play\n * would be the surprise. `--no-env` loads none.\n *\n * `process.loadEnvFile` deliberately does not overwrite variables that are\n * already set, so a shell-provided value always beats the file:\n *\n * REVENEXX_DEV_API_KEY=… npm run preview\n *\n * The flag is `--env`, *not* `--env-file`: Node reserves `--env-file` and\n * `--env-file-if-exists` and acts on them wherever they appear, including after\n * the script path. `node cli.js --env-file missing` therefore dies inside Node\n * with exit code 9 before this module is ever reached, so the devkit cannot own\n * that name. {@link nodeOwnedEnvFlag} spots the mistake and explains it.\n *\n * `--env` takes a path rather than Laravel's bare environment name, because it\n * mirrors Node's flag and because a path can point outside the package. A value\n * that looks like it was meant as a name still gets a pointed error — see\n * {@link missingFileMessage}.\n */\n\n/** Minimum Node version shipping `process.loadEnvFile`. */\nexport const ENV_FILE_MIN_NODE = '20.12';\n\n/** Flags Node itself consumes, positionally, and which the devkit must not reuse. */\nconst NODE_OWNED_FLAGS = ['--env-file', '--env-file-if-exists'];\n\nexport interface EnvFileChoice {\n /** Absolute path to load, or `null` when `--no-env` disabled loading. */\n path: string | null;\n /** True when the file was named with `--env` rather than defaulted to. */\n explicit: boolean;\n /** The `--env` value exactly as typed, kept for {@link missingFileMessage}. */\n raw?: string;\n}\n\n/**\n * Returns the Node-owned env flag present in `argv`, if any. Node has already\n * acted on it by the time the CLI runs — this exists only so the CLI can say so\n * instead of leaving the user wondering why `--env-file` behaved oddly.\n */\nexport function nodeOwnedEnvFlag(argv: string[]): string | null {\n return NODE_OWNED_FLAGS.find(flag => argv.includes(flag) || argv.some(arg => arg.startsWith(`${flag}=`))) ?? null;\n}\n\n/**\n * Decides which env file to load. Pure — touches neither disk nor `process.env`.\n *\n * A repeated `--env` resolves to the last one, matching every other option in\n * the CLI, whose parse loop simply overwrites. Every occurrence is still\n * validated, so a malformed earlier one is reported rather than skipped.\n */\nexport function resolveEnvFile(argv: string[], cwd: string = process.cwd()): EnvFileChoice {\n if (argv.includes('--no-env')) {\n return { path: null, explicit: false };\n }\n\n let named: EnvFileChoice | null = null;\n for (let i = 0; i < argv.length; i++) {\n // Strict equality: `--env-file` belongs to Node, and `--env-file=x` must\n // not be mistaken for a value-carrying `--env`.\n if (argv[i] !== '--env') {\n continue;\n }\n const value = argv[++i];\n if (!value || value.startsWith('-')) {\n throw new Error('--env requires a path.');\n }\n named = { path: resolve(cwd, value), explicit: true, raw: value };\n }\n\n return named ?? { path: resolve(cwd, '.env'), explicit: false };\n}\n\n/**\n * Explains a named-but-missing env file. When the value looks like a Laravel\n * environment name and the matching `.env.<name>` is right there, say so — the\n * bare \"does not exist\" would leave the user re-reading the flag's docs.\n */\nfunction missingFileMessage(choice: EnvFileChoice, cwd: string): string {\n const raw = choice.raw;\n if (raw && raw === basename(raw) && existsSync(resolve(cwd, `.env.${raw}`))) {\n return `--env: ${choice.path} does not exist. Did you mean --env .env.${raw}? The flag takes a path, not an environment name.`;\n }\n return `--env: ${choice.path} does not exist.`;\n}\n\nexport interface LoadEnvFileOptions {\n cwd?: string;\n warn?: (message: string) => void;\n}\n\n/**\n * Loads the env file chosen by {@link resolveEnvFile} into `process.env` and\n * returns its path, or `null` when nothing was loaded.\n *\n * A missing *default* `.env` is fine — most packages do not have one. A file\n * asked for by name and missing is an error: ignoring it would hide a typo and\n * resurface much later as a puzzling `Seed references ${X}` failure. There is no\n * fallback to `.env` in that case, since naming a file replaces the default.\n */\nexport function loadEnvFile(argv: string[], options: LoadEnvFileOptions = {}): string | null {\n const { cwd = process.cwd(), warn = (message: string) => console.warn(message) } = options;\n\n const nodeFlag = nodeOwnedEnvFlag(argv);\n if (nodeFlag) {\n warn(`Note: ${nodeFlag} is a Node flag and Node has already applied it. The devkit's own flag is --env <path>.`);\n }\n\n const choice = resolveEnvFile(argv, cwd);\n if (!choice.path) {\n return null;\n }\n if (!existsSync(choice.path)) {\n if (choice.explicit) {\n throw new Error(missingFileMessage(choice, cwd));\n }\n return null;\n }\n // npm's `engines` field is advisory, so an old runtime reaches this far.\n if (typeof process.loadEnvFile !== 'function') {\n warn(`Ignoring ${choice.path}: env-file support needs Node >= ${ENV_FILE_MIN_NODE} (running ${process.version}).`);\n return null;\n }\n\n process.loadEnvFile(choice.path);\n return choice.path;\n}\n","/**\n * `@revenexx/integrations-node-devkit` — local development kit for Revenexx\n * integration node packages. Dev/CI only; never bundled into a node package.\n *\n * Two surfaces:\n * - `@revenexx/integrations-node-devkit` → the mock-API preview server (this entry)\n * - `@revenexx/integrations-node-devkit/testing` → the unit-testing harness\n */\n\nimport { readFileSync } from 'node:fs';\n\n// Read from package.json rather than hardcoded, so the released version can\n// never drift from what `integrations-devkit --version` prints. `../` resolves\n// to the package root from both `src/` and the bundled `dist/`. The CJS build\n// needs tsup's `shims: true` for `import.meta.url`.\nconst manifestUrl = new URL('../package.json', import.meta.url);\nexport const DEVKIT_VERSION: string = JSON.parse(readFileSync(manifestUrl, 'utf8')).version;\n\nexport {\n ENV_FILE_MIN_NODE,\n type EnvFileChoice,\n loadEnvFile,\n type LoadEnvFileOptions,\n nodeOwnedEnvFlag,\n resolveEnvFile,\n} from './env.js';\nexport { DevApiError } from './errors.js';\nexport {\n ensureTsxRegistered,\n importFresh,\n type LoadedPackage,\n loadPackageFromEntry,\n resolveExports,\n} from './loader.js';\nexport {\n applySeeds,\n type CredentialSeed,\n type DevSeeds,\n interpolateEnv,\n loadSeedsFromDir,\n loadState,\n saveState,\n type SecretSeed,\n type WorkflowSeed,\n} from './persistence.js';\nexport {\n buildOAuthAuthorizeUrl,\n exchangeOAuthCode,\n findCredential,\n findCredentialType,\n findNode,\n nodeVersions,\n type ResolveNodeConfigInput,\n type ResolveNodeConfigResult,\n resolveCredentialInstance,\n resolveNodeConfig,\n testCredentialConfig,\n testCredentialInstance,\n type ValidateNodeConfigInput,\n type ValidateNodeConfigResult,\n validateNodeConfig,\n} from './resolve.js';\nexport {\n createDevServer,\n createRequestListener,\n type DevServerDeps,\n} from './server.js';\nexport {\n type CredentialRecord,\n DEV_TENANT_ID,\n DevStore,\n type DevStoreSnapshot,\n type SecretRecord,\n STORE_SCHEMA_VERSION,\n type TriggerRecord,\n type WorkflowRecord,\n} from './store.js';\n","import { existsSync, readFileSync } from 'node:fs';\nimport { dirname, join } from 'node:path';\nimport { pathToFileURL } from 'node:url';\nimport { buildManifest, type ICredential, type INode, type ITemplateDescription, type NodeManifest } from '@revenexx/integrations-node-sdk';\n\n/** Identity of the npm package the nodes came from, as `GET /nodes` reports it. */\nexport interface PackageInfo {\n name: string;\n version: string;\n label: string;\n}\n\nconst UNKNOWN_PACKAGE: PackageInfo = { name: 'unknown', version: '0.0.0', label: 'Local package' };\n\n/**\n * A node package loaded into the dev process: its live `NODES` / `CREDENTIALS`\n * / `TEMPLATES` instances (so author-time resolvers, `test`, and `resolve` can\n * be invoked in-process — no bundle, no sandbox) plus the derived manifest the\n * mock API serves.\n */\nexport interface LoadedPackage {\n nodes: INode[];\n credentials: ICredential[];\n templates: ITemplateDescription[];\n manifest: NodeManifest;\n /** Reported as each node's `package`; the contract declares it non-null. */\n packageInfo: PackageInfo;\n /** Stands in for the service's per-node `created_at`/`updated_at`. */\n loadedAt: string;\n}\n\n/**\n * Reads the nearest `package.json` above `entryPath` for the node package's\n * identity. The real service knows this from the published bundle; here it comes\n * from the developer's own manifest.\n */\nexport function readPackageInfo(entryPath: string): PackageInfo {\n let dir = dirname(entryPath);\n for (let up = 0; up < 6; up += 1) {\n const candidate = join(dir, 'package.json');\n if (existsSync(candidate)) {\n try {\n const pkg = JSON.parse(readFileSync(candidate, 'utf-8')) as { name?: string; version?: string; description?: string };\n if (pkg.name) {\n return { name: pkg.name, version: pkg.version ?? '0.0.0', label: pkg.name.split('/').pop() ?? pkg.name };\n }\n } catch {\n // Unreadable package.json is not worth failing the preview over.\n }\n }\n const parent = dirname(dir);\n if (parent === dir) break;\n dir = parent;\n }\n return UNKNOWN_PACKAGE;\n}\n\ninterface PackageExports {\n NODES?: unknown;\n CREDENTIALS?: unknown;\n TEMPLATES?: unknown;\n}\n\n/**\n * Validates a package's module exports and builds a {@link LoadedPackage}.\n * Mirrors the checks in the SDK's `rvnxx-nodes manifest` CLI so the dev loop\n * and the build produce identical manifests.\n */\nexport function resolveExports(mod: PackageExports, packageInfo: PackageInfo = UNKNOWN_PACKAGE): LoadedPackage {\n if (!Array.isArray(mod.NODES)) {\n throw new Error('Package entry does not export a `NODES` array. Export `NODES: INode[]`.');\n }\n if (mod.CREDENTIALS !== undefined && !Array.isArray(mod.CREDENTIALS)) {\n throw new Error('Package entry exports `CREDENTIALS` but it is not an array.');\n }\n if (mod.TEMPLATES !== undefined && !Array.isArray(mod.TEMPLATES)) {\n throw new Error('Package entry exports `TEMPLATES` but it is not an array.');\n }\n\n const nodes = mod.NODES as INode[];\n const credentials = (mod.CREDENTIALS as ICredential[] | undefined) ?? [];\n const templates = (mod.TEMPLATES as ITemplateDescription[] | undefined) ?? [];\n\n return {\n nodes,\n credentials,\n templates,\n manifest: buildManifest(nodes, credentials, templates),\n packageInfo,\n loadedAt: new Date().toISOString(),\n };\n}\n\nlet tsxRegistered = false;\n\n/**\n * Registers the `tsx` ESM loader once per process so `import()` can load\n * TypeScript sources directly. Idempotent.\n */\nexport async function ensureTsxRegistered(): Promise<void> {\n if (tsxRegistered) {\n return;\n }\n const { register } = await import('tsx/esm/api');\n register();\n tsxRegistered = true;\n}\n\n/**\n * File extensions whose change should reload the package.\n *\n * `[cm]?[jt]sx?` covers the whole matrix — `.ts .tsx .cts .mts .js .jsx .cjs .mjs`\n * — rather than the `.ts`-family-plus-bare-`.js` it used to be. That older pattern\n * silently ignored `.mjs` and `.cjs`, so a package whose entry is a built ESM\n * `dist/index.mjs` never hot-reloaded at all: edits landed, nothing happened, and\n * nothing said why.\n *\n * `.json` is in because a node that imports locale strings or lookup data from one\n * has to re-evaluate when it changes. A reload it did not need costs a few ms and\n * keeps the previous package on failure, so erring towards reloading is free.\n */\nconst RELOADABLE_SOURCE = /\\.(?:[cm]?[jt]sx?|json)$/;\n\n/** True when a changed file is package source the mock should reload for. */\nexport function isReloadableSource(file: string): boolean {\n return RELOADABLE_SOURCE.test(file);\n}\n\n/** Imports a module by path, registering tsx first for TypeScript sources. */\nexport async function importFresh<T = unknown>(entryPath: string): Promise<T> {\n if (/\\.[cm]?tsx?$/.test(entryPath)) {\n await ensureTsxRegistered();\n }\n const href = `${pathToFileURL(entryPath).href}?t=${Date.now()}`;\n return (await import(href)) as T;\n}\n\n/**\n * Imports a package entry and resolves its exports. Supports TypeScript\n * sources directly (via `tsx`) so the preview runs against the developer's\n * live `src/`, not a built artifact. A cache-busting query is appended so\n * repeated calls (hot-reload) re-evaluate the module.\n */\nexport async function loadPackageFromEntry(entryPath: string): Promise<LoadedPackage> {\n return resolveExports(await importFresh<PackageExports>(entryPath), readPackageInfo(entryPath));\n}\n","import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';\nimport { dirname, resolve } from 'node:path';\nimport { importFresh } from './loader.js';\nimport { type DevStore, type DevStoreSnapshot, STORE_SCHEMA_VERSION } from './store.js';\n\n/**\n * Layered persistence for the preview session:\n * 1. committed seeds (this module's {@link applySeeds}) — the durable base,\n * with `${ENV_VAR}` references interpolated from the environment;\n * 2. `.revenexx-dev/state.json` overlay ({@link loadState}/{@link saveState}) —\n * interactive session state, versioned and disposable.\n */\n\nexport interface CredentialSeed {\n credentialTypeSlug: string;\n name: string;\n config: Record<string, unknown>;\n /** Stable id so workflows can reference the credential across restarts. */\n id?: string;\n status?: string;\n durableCreds?: Record<string, unknown> | null;\n}\n\nexport interface SecretSeed {\n key: string;\n value: string;\n}\n\nexport interface WorkflowSeed {\n name: string;\n /** The workflow graph, named as the service names it. */\n blob?: Record<string, unknown>;\n /**\n * @deprecated The mock called this `definition` before it was aligned to the\n * service contract. Still accepted so existing seed files keep working.\n */\n definition?: Record<string, unknown>;\n description?: string | null;\n active?: boolean;\n executionMode?: string;\n}\n\nexport interface DevSeeds {\n credentials?: CredentialSeed[];\n secrets?: SecretSeed[];\n workflows?: WorkflowSeed[];\n}\n\nconst ENV_REF = /\\$\\{([A-Z0-9_]+)\\}/g;\n\n/**\n * Recursively replaces `${ENV_VAR}` references in string values from `env`.\n * Throws a clear error when a referenced variable is unset so a developer\n * knows to add it to their `.env` — keeping secrets out of committed seeds.\n */\nexport function interpolateEnv<T>(value: T, env: NodeJS.ProcessEnv = process.env): T {\n if (typeof value === 'string') {\n return value.replace(ENV_REF, (_match, name: string) => {\n const resolved = env[name];\n if (resolved === undefined) {\n throw new Error(`Seed references \\${${name}} but that environment variable is not set (add it to your .env).`);\n }\n return resolved;\n }) as unknown as T;\n }\n if (Array.isArray(value)) {\n return value.map(item => interpolateEnv(item, env)) as unknown as T;\n }\n if (value && typeof value === 'object') {\n const out: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value)) {\n out[key] = interpolateEnv(val, env);\n }\n return out as T;\n }\n return value;\n}\n\n/** Applies committed seeds to the store (env-interpolated). */\nexport function applySeeds(store: DevStore, seeds: DevSeeds, env: NodeJS.ProcessEnv = process.env): void {\n for (const secret of seeds.secrets ?? []) {\n const { key, value } = interpolateEnv(secret, env);\n store.setSecret(key, value);\n }\n for (const credential of seeds.credentials ?? []) {\n const resolved = interpolateEnv(credential, env);\n store.createCredential({\n credentialTypeSlug: resolved.credentialTypeSlug,\n name: resolved.name,\n config: resolved.config,\n id: resolved.id,\n status: resolved.status,\n durableCreds: resolved.durableCreds ?? null,\n });\n }\n for (const workflow of seeds.workflows ?? []) {\n const resolved = interpolateEnv(workflow, env);\n store.createWorkflow({\n name: resolved.name,\n blob: resolved.blob ?? resolved.definition ?? {},\n description: resolved.description,\n active: resolved.active,\n executionMode: resolved.executionMode,\n });\n }\n}\n\n/**\n * Reads a persisted session snapshot. Returns `null` (and warns) when the file\n * is absent or its `schemaVersion` no longer matches — the overlay is\n * disposable, so a mismatch is discarded rather than migrated.\n */\nexport function loadState(file: string, log: (msg: string) => void = console.warn): DevStoreSnapshot | null {\n if (!existsSync(file)) {\n return null;\n }\n let parsed: DevStoreSnapshot;\n try {\n parsed = JSON.parse(readFileSync(file, 'utf-8')) as DevStoreSnapshot;\n } catch {\n log(`Ignoring ${file}: not valid JSON.`);\n return null;\n }\n if (parsed.schemaVersion !== STORE_SCHEMA_VERSION) {\n log(`Ignoring ${file}: schemaVersion ${parsed.schemaVersion} != ${STORE_SCHEMA_VERSION} (discarded, seeds are the source of truth).`);\n return null;\n }\n return parsed;\n}\n\nexport function saveState(file: string, snapshot: DevStoreSnapshot): void {\n mkdirSync(dirname(file), { recursive: true });\n writeFileSync(file, JSON.stringify(snapshot, null, 2), 'utf-8');\n}\n\nconst SEED_ENTRY_CANDIDATES = ['index.ts', 'index.mjs', 'index.js', 'seeds.ts', 'seeds.js'];\n\n/**\n * Loads committed seeds from a directory (default `dev/seeds`). Resolves the\n * first present entry file and reads its `default` or named `seeds` export.\n * Returns empty seeds when no seed directory/entry exists.\n */\nexport async function loadSeedsFromDir(dir: string): Promise<DevSeeds> {\n for (const candidate of SEED_ENTRY_CANDIDATES) {\n const path = resolve(dir, candidate);\n if (existsSync(path)) {\n const mod = await importFresh<{ default?: DevSeeds; seeds?: DevSeeds }>(path);\n return mod.default ?? mod.seeds ?? {};\n }\n }\n return {};\n}\n","import { randomUUID } from 'node:crypto';\n\n/**\n * In-memory data store backing the mock Integrations API. Holds the tenant-\n * scoped resources a developer creates in the preview (credentials, secrets,\n * workflows, triggers). Serializable so a session can be persisted to and\n * rehydrated from `.revenexx-dev/state.json`.\n */\n\nexport const DEV_TENANT_ID = 'dev-tenant';\n\nexport interface CredentialRecord {\n id: string;\n tenantId: string;\n credentialTypeSlug: string;\n name: string;\n status: string;\n /** Full user-entered config, including secret fields (never sent to the UI verbatim). */\n config: Record<string, unknown>;\n /** System-managed long-lived secrets (e.g. an OAuth refresh token). */\n durableCreds: Record<string, unknown> | null;\n /** Outcome of the last `POST /credentials/{id}/test`, which the contract reports. */\n lastTestAt: string | null;\n lastTestOk: boolean | null;\n lastTestMessage: string | null;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface SecretRecord {\n key: string;\n value: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/**\n * Field names follow the service's contract: the graph is `blob`, tagged with the\n * `blob_definition_version` it was written against. The mock used to call it\n * `definition`, which meant a workflow saved from the real UI silently lost its\n * graph — the UI sends `blob`, so `body.definition` was always undefined.\n */\nexport interface WorkflowRecord {\n id: number;\n name: string;\n description: string | null;\n blob: Record<string, unknown>;\n blobDefinitionVersion: string;\n active: boolean;\n executionMode: string;\n /** Bumped on every update, like the service's revision counter. */\n revision: number;\n buildStatus: string;\n createdAt: string;\n updatedAt: string;\n}\n\n/** The only `blob_definition_version` the contract currently allows. */\nexport const BLOB_DEFINITION_VERSION = 'v0-draft';\n\n/** `execution_mode` values the contract allows; the first is the default. */\nexport const EXECUTION_MODES = ['async_only', 'sync_only', 'caller_decides'] as const;\n\nexport interface TriggerRecord {\n id: string;\n workflowId: number;\n type: string;\n name: string | null;\n config: Record<string, unknown>;\n active: boolean;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface DevStoreSnapshot {\n schemaVersion: number;\n credentials: CredentialRecord[];\n secrets: SecretRecord[];\n workflows: WorkflowRecord[];\n triggers: TriggerRecord[];\n nextWorkflowId: number;\n}\n\n/**\n * Bumped to 2 when workflows moved from `definition` to the contract's `blob` /\n * `blob_definition_version` / `active` / `execution_mode`. `loadState` discards an\n * overlay whose version does not match, which is the migration: seeds are the\n * source of truth, the overlay is disposable session state.\n */\nexport const STORE_SCHEMA_VERSION = 2;\n\nfunction now(): string {\n return new Date().toISOString();\n}\n\nexport class DevStore {\n private credentials = new Map<string, CredentialRecord>();\n private secrets = new Map<string, SecretRecord>();\n private workflows = new Map<number, WorkflowRecord>();\n private triggers = new Map<string, TriggerRecord>();\n private nextWorkflowId = 1;\n\n /**\n * @param onChange fired after any mutation so a caller (the CLI) can persist\n * the session to `.revenexx-dev/state.json`.\n */\n constructor(private onChange?: () => void) {}\n\n /** (Re)wire the post-mutation callback — e.g. attach it only after seeding. */\n setOnMutation(onChange: (() => void) | undefined): void {\n this.onChange = onChange;\n }\n\n private touch(): void {\n this.onChange?.();\n }\n\n // ------------------------------------------------------------- credentials\n\n listCredentials(typeSlug?: string): CredentialRecord[] {\n const all = [...this.credentials.values()];\n return typeSlug ? all.filter(c => c.credentialTypeSlug === typeSlug) : all;\n }\n\n getCredential(id: string): CredentialRecord | undefined {\n return this.credentials.get(id);\n }\n\n createCredential(input: {\n credentialTypeSlug: string;\n name: string;\n config: Record<string, unknown>;\n status?: string;\n /** Stable id — pass to keep a seeded credential's id fixed across restarts. */\n id?: string;\n durableCreds?: Record<string, unknown> | null;\n }): CredentialRecord {\n const ts = now();\n const record: CredentialRecord = {\n id: input.id ?? randomUUID(),\n tenantId: DEV_TENANT_ID,\n credentialTypeSlug: input.credentialTypeSlug,\n name: input.name,\n status: input.status ?? 'active',\n config: input.config,\n durableCreds: input.durableCreds ?? null,\n lastTestAt: null,\n lastTestOk: null,\n lastTestMessage: null,\n createdAt: ts,\n updatedAt: ts,\n };\n this.credentials.set(record.id, record);\n this.touch();\n return record;\n }\n\n updateCredential(id: string, patch: Partial<Pick<CredentialRecord, 'name' | 'config' | 'status' | 'durableCreds'>>): CredentialRecord | undefined {\n const record = this.credentials.get(id);\n if (!record) {\n return undefined;\n }\n if (patch.name !== undefined) {\n record.name = patch.name;\n }\n if (patch.config !== undefined) {\n record.config = patch.config;\n }\n if (patch.status !== undefined) {\n record.status = patch.status;\n }\n if (patch.durableCreds !== undefined) {\n record.durableCreds = patch.durableCreds;\n }\n record.updatedAt = now();\n this.touch();\n return record;\n }\n\n /**\n * Records the outcome of a credential test. The service persists this on the\n * record and reports it back from `POST /credentials/{id}/test`.\n */\n recordCredentialTest(id: string, result: { ok: boolean; message?: string | null }): CredentialRecord | undefined {\n const record = this.credentials.get(id);\n if (!record) {\n return undefined;\n }\n record.lastTestAt = now();\n record.lastTestOk = result.ok;\n record.lastTestMessage = result.message ?? null;\n this.touch();\n return record;\n }\n\n deleteCredential(id: string): boolean {\n const deleted = this.credentials.delete(id);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // ----------------------------------------------------------------- secrets\n\n listSecrets(): SecretRecord[] {\n return [...this.secrets.values()];\n }\n\n getSecret(key: string): SecretRecord | undefined {\n return this.secrets.get(key);\n }\n\n setSecret(key: string, value: string): SecretRecord {\n const existing = this.secrets.get(key);\n const ts = now();\n const record: SecretRecord = {\n key,\n value,\n createdAt: existing?.createdAt ?? ts,\n updatedAt: ts,\n };\n this.secrets.set(key, record);\n this.touch();\n return record;\n }\n\n deleteSecret(key: string): boolean {\n const deleted = this.secrets.delete(key);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // --------------------------------------------------------------- workflows\n\n listWorkflows(): WorkflowRecord[] {\n return [...this.workflows.values()];\n }\n\n getWorkflow(id: number): WorkflowRecord | undefined {\n return this.workflows.get(id);\n }\n\n createWorkflow(input: {\n name: string;\n blob: Record<string, unknown>;\n blobDefinitionVersion?: string;\n description?: string | null;\n active?: boolean;\n executionMode?: string;\n }): WorkflowRecord {\n const ts = now();\n const record: WorkflowRecord = {\n id: this.nextWorkflowId++,\n name: input.name,\n description: input.description ?? null,\n blob: input.blob,\n blobDefinitionVersion: input.blobDefinitionVersion ?? BLOB_DEFINITION_VERSION,\n active: input.active ?? true,\n executionMode: input.executionMode ?? EXECUTION_MODES[0],\n revision: 1,\n buildStatus: 'ready',\n createdAt: ts,\n updatedAt: ts,\n };\n this.workflows.set(record.id, record);\n this.touch();\n return record;\n }\n\n updateWorkflow(id: number, patch: Partial<Pick<WorkflowRecord, 'name' | 'description' | 'blob' | 'blobDefinitionVersion' | 'active' | 'executionMode' | 'buildStatus'>>): WorkflowRecord | undefined {\n const record = this.workflows.get(id);\n if (!record) {\n return undefined;\n }\n // Drop undefined so a partial PUT does not blank fields the caller omitted.\n const defined = Object.fromEntries(Object.entries(patch).filter(([, v]) => v !== undefined));\n Object.assign(record, defined, { revision: record.revision + 1, updatedAt: now() });\n this.touch();\n return record;\n }\n\n deleteWorkflow(id: number): boolean {\n for (const trigger of this.triggers.values()) {\n if (trigger.workflowId === id) {\n this.triggers.delete(trigger.id);\n }\n }\n const deleted = this.workflows.delete(id);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // ---------------------------------------------------------------- triggers\n\n listTriggers(workflowId: number): TriggerRecord[] {\n return [...this.triggers.values()].filter(t => t.workflowId === workflowId);\n }\n\n getTrigger(id: string): TriggerRecord | undefined {\n return this.triggers.get(id);\n }\n\n createTrigger(input: {\n workflowId: number;\n type: string;\n name?: string | null;\n config?: Record<string, unknown>;\n active?: boolean;\n id?: string;\n }): TriggerRecord {\n const ts = now();\n const record: TriggerRecord = {\n id: input.id ?? randomUUID(),\n workflowId: input.workflowId,\n type: input.type,\n name: input.name ?? null,\n config: input.config ?? {},\n active: input.active ?? true,\n createdAt: ts,\n updatedAt: ts,\n };\n this.triggers.set(record.id, record);\n this.touch();\n return record;\n }\n\n replaceTrigger(id: string, input: { type: string; name?: string | null; config?: Record<string, unknown>; active?: boolean }): TriggerRecord | undefined {\n const record = this.triggers.get(id);\n if (!record) {\n return undefined;\n }\n record.type = input.type;\n record.name = input.name ?? null;\n record.config = input.config ?? {};\n record.active = input.active ?? true;\n record.updatedAt = now();\n this.touch();\n return record;\n }\n\n deleteTrigger(id: string): boolean {\n const deleted = this.triggers.delete(id);\n if (deleted) {\n this.touch();\n }\n return deleted;\n }\n\n // ------------------------------------------------------------- persistence\n\n toSnapshot(): DevStoreSnapshot {\n return {\n schemaVersion: STORE_SCHEMA_VERSION,\n credentials: [...this.credentials.values()],\n secrets: [...this.secrets.values()],\n workflows: [...this.workflows.values()],\n triggers: [...this.triggers.values()],\n nextWorkflowId: this.nextWorkflowId,\n };\n }\n\n loadSnapshot(snapshot: DevStoreSnapshot): void {\n this.credentials = new Map(snapshot.credentials.map(c => [c.id, c]));\n this.secrets = new Map(snapshot.secrets.map(s => [s.key, s]));\n this.workflows = new Map(snapshot.workflows.map(w => [w.id, w]));\n this.triggers = new Map(snapshot.triggers.map(t => [t.id, t]));\n this.nextWorkflowId = snapshot.nextWorkflowId ?? Math.max(0, ...snapshot.workflows.map(w => w.id)) + 1;\n }\n\n /**\n * Overlays a snapshot on top of the current contents (upsert by id/key), used\n * to layer the persisted `.revenexx-dev/state.json` session over the freshly\n * applied committed seeds. State entries win over seed entries with the same\n * id/key; seed-only entries are preserved.\n */\n mergeSnapshot(snapshot: DevStoreSnapshot): void {\n for (const c of snapshot.credentials) {\n this.credentials.set(c.id, c);\n }\n for (const s of snapshot.secrets) {\n this.secrets.set(s.key, s);\n }\n for (const w of snapshot.workflows) {\n this.workflows.set(w.id, w);\n }\n for (const t of snapshot.triggers) {\n this.triggers.set(t.id, t);\n }\n this.nextWorkflowId = Math.max(this.nextWorkflowId, snapshot.nextWorkflowId ?? 0, ...snapshot.workflows.map(w => w.id + 1));\n }\n}\n","import {\n type IConfigField,\n type IConfigOption,\n type ICredential,\n type ICredentialContext,\n type ICredentialDescription,\n type ICredentialResolveResult,\n type ICredentialTestResult,\n type INode,\n type INodeAuthorContext,\n type IOutputPort,\n isOAuthAuthorizeCredential,\n} from '@revenexx/integrations-node-sdk';\nimport { DevApiError } from './errors.js';\nimport type { LoadedPackage } from './loader.js';\nimport type { DevStore } from './store.js';\n\n/**\n * The fidelity centre of the mock API: instead of the production sandbox +\n * content-addressed bundle, the developer's live node/credential instances are\n * invoked directly in-process. Author-time resolvers, credential `test`, and\n * `resolve` run exactly as the developer wrote them. The PO-145 grant/security\n * model is intentionally omitted — this is dev-only.\n */\n\nconst noopLogger = {\n info() {},\n warn() {},\n error() {},\n};\n\nfunction compareSemver(a: string, b: string): number {\n const pa = a.split('.').map(n => Number.parseInt(n, 10) || 0);\n const pb = b.split('.').map(n => Number.parseInt(n, 10) || 0);\n for (let i = 0; i < 3; i++) {\n const diff = (pa[i] ?? 0) - (pb[i] ?? 0);\n if (diff !== 0) {\n return diff;\n }\n }\n return 0;\n}\n\nexport function nodeVersions(loaded: LoadedPackage, slug: string): string[] {\n return loaded.nodes\n .filter(n => n.description.slug === slug)\n .map(n => n.description.version)\n .sort((a, b) => compareSemver(b, a));\n}\n\nexport function findNode(loaded: LoadedPackage, slug: string, version?: string): INode {\n const matches = loaded.nodes.filter(n => n.description.slug === slug);\n if (matches.length === 0) {\n throw new DevApiError(404, `Node '${slug}' not found.`);\n }\n if (!version || version === 'latest') {\n return [...matches].sort((a, b) => compareSemver(b.description.version, a.description.version))[0]!;\n }\n const exact = matches.find(n => n.description.version === version);\n if (!exact) {\n throw new DevApiError(404, `Node '${slug}' has no version '${version}'.`);\n }\n return exact;\n}\n\nexport function findCredential(loaded: LoadedPackage, slug: string): ICredential {\n const cred = loaded.credentials.find(c => c.description.slug === slug);\n if (!cred) {\n throw new DevApiError(404, `Credential type '${slug}' not found.`);\n }\n return cred;\n}\n\nexport function findCredentialType(loaded: LoadedPackage, slug: string): ICredentialDescription {\n return findCredential(loaded, slug).description;\n}\n\nfunction credentialContext(store: DevStore, credentialId?: string): ICredentialContext {\n return {\n signal: new AbortController().signal,\n logger: noopLogger,\n persistDurableCreds: credentialId\n ? async (durableCreds: Record<string, unknown>) => {\n store.updateCredential(credentialId, { durableCreds });\n }\n : undefined,\n };\n}\n\n/** Resolves a credential instance's access data by running its real `resolve`. */\nexport async function resolveCredentialInstance(loaded: LoadedPackage, store: DevStore, credentialId: string): Promise<ICredentialResolveResult> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n const ctx = credentialContext(store, credentialId);\n return cred.resolve(ctx, instance.config, instance.durableCreds);\n}\n\nfunction authorContext(loaded: LoadedPackage, store: DevStore, config: Record<string, unknown>, locale?: string): INodeAuthorContext {\n return {\n signal: new AbortController().signal,\n logger: noopLogger,\n config,\n secrets: {\n async get(key: string): Promise<string> {\n const secret = store.getSecret(key);\n if (!secret) {\n throw new DevApiError(404, `Secret '${key}' not found.`);\n }\n return secret.value;\n },\n },\n credentials: {\n async get(id: string): Promise<Record<string, unknown>> {\n return (await resolveCredentialInstance(loaded, store, id)).credentials;\n },\n },\n locale,\n };\n}\n\nexport interface ResolveNodeConfigInput {\n slug: string;\n version?: string;\n /** `\"*\"` (all), `\"outputs\"`, or a specific config field key. */\n target: string;\n config: Record<string, unknown>;\n locale?: string;\n}\n\nexport interface ResolveNodeConfigResult {\n options?: IConfigOption[];\n fields?: IConfigField[];\n outputs?: IOutputPort[];\n}\n\n/**\n * Runs a node's author-time resolvers for the requested `target`, mirroring\n * the server's `config:resolve` semantics.\n */\nexport async function resolveNodeConfig(loaded: LoadedPackage, store: DevStore, input: ResolveNodeConfigInput): Promise<ResolveNodeConfigResult> {\n const node = findNode(loaded, input.slug, input.version);\n const ctx = authorContext(loaded, store, input.config ?? {}, input.locale);\n\n try {\n if (input.target === 'outputs') {\n if (!node.resolveOutputs) {\n return { outputs: [] };\n }\n return { outputs: await node.resolveOutputs(ctx) };\n }\n\n if (input.target === '*') {\n const result: ResolveNodeConfigResult = {};\n if (node.resolveConfigSchema) {\n result.fields = await node.resolveConfigSchema(ctx);\n }\n if (node.resolveOutputs) {\n result.outputs = await node.resolveOutputs(ctx);\n }\n return result;\n }\n\n // A specific config field key.\n const field = node.description.config?.find(f => f.key === input.target);\n if (field?.type === 'dynamic-schema') {\n if (!node.resolveConfigSchema) {\n return { fields: [] };\n }\n return { fields: await node.resolveConfigSchema(ctx) };\n }\n if (!node.loadOptions) {\n return { options: [] };\n }\n return { options: await node.loadOptions(ctx, input.target) };\n } catch (err) {\n if (err instanceof DevApiError) {\n throw err;\n }\n throw new DevApiError(502, `Node resolve failed: ${(err as Error).message}`);\n }\n}\n\nexport interface ValidateNodeConfigInput {\n slug: string;\n version?: string;\n config: Record<string, unknown>;\n locale?: string;\n}\n\nexport interface ValidateNodeConfigResult {\n valid: boolean;\n /** Config field key → human-readable messages. Empty object when valid. */\n errors: Record<string, string[]>;\n}\n\n/** True when a value counts as \"provided\" (mirrors the UI's `isResolvableValue`). */\nfunction isProvided(value: unknown): boolean {\n if (value === undefined || value === null) {\n return false;\n }\n if (typeof value === 'string') {\n return value.trim().length > 0;\n }\n if (Array.isArray(value)) {\n return value.length > 0;\n }\n return true;\n}\n\n/** An expression placeholder (`${{…}}` / leading `=`) is \"set\" but not statically checkable. */\nfunction isExpression(value: unknown): boolean {\n return typeof value === 'string' && (value.startsWith('=') || value.includes('${{'));\n}\n\n/** Applies one field's static rules to `value`, pushing messages under `field.key`. */\nfunction validateField(field: IConfigField, value: unknown, errors: Record<string, string[]>): void {\n const push = (msg: string): void => {\n (errors[field.key] ??= []).push(msg);\n };\n const provided = isProvided(value);\n if (field.required && !provided) {\n push('This field is required.');\n return;\n }\n if (!provided || isExpression(value)) {\n // Optional-and-empty, or an expression the mock cannot evaluate — skip type/rules.\n return;\n }\n\n switch (field.type) {\n case 'string':\n case 'secret-ref':\n case 'expression':\n if (typeof value !== 'string') {\n push('Expected a string.');\n }\n break;\n case 'number':\n if (typeof value !== 'number' || Number.isNaN(value)) {\n push('Expected a number.');\n }\n break;\n case 'boolean':\n if (typeof value !== 'boolean') {\n push('Expected a boolean.');\n }\n break;\n case 'select':\n // Dynamic options are only known after resolve — can't check membership here.\n if (!field.dynamic && field.options && !field.options.some(o => o.value === value)) {\n push('Not one of the allowed options.');\n }\n break;\n case 'multiselect':\n if (!Array.isArray(value)) {\n push('Expected an array.');\n } else if (!field.dynamic && field.options) {\n const allowed = new Set(field.options.map(o => o.value));\n for (const v of value) {\n if (!allowed.has(v as string | number | boolean)) {\n push(`Value '${String(v)}' is not an allowed option.`);\n }\n }\n }\n break;\n case 'array':\n if (!Array.isArray(value)) {\n push('Expected an array.');\n }\n break;\n case 'object':\n if (typeof value !== 'object' || Array.isArray(value)) {\n push('Expected an object.');\n }\n break;\n // credentials-ref / dynamic-schema carry no scalar type check here.\n }\n\n const v = field.validation;\n if (v) {\n if (typeof value === 'string') {\n if (v.pattern !== undefined && !new RegExp(v.pattern).test(value)) {\n push(`Does not match pattern ${v.pattern}.`);\n }\n if (v.minLength !== undefined && value.length < v.minLength) {\n push(`Must be at least ${v.minLength} characters.`);\n }\n if (v.maxLength !== undefined && value.length > v.maxLength) {\n push(`Must be at most ${v.maxLength} characters.`);\n }\n }\n if (typeof value === 'number') {\n if (v.min !== undefined && value < v.min) {\n push(`Must be >= ${v.min}.`);\n }\n if (v.max !== undefined && value > v.max) {\n push(`Must be <= ${v.max}.`);\n }\n }\n if (Array.isArray(value)) {\n if (v.minLength !== undefined && value.length < v.minLength) {\n push(`Must have at least ${v.minLength} items.`);\n }\n if (v.maxLength !== undefined && value.length > v.maxLength) {\n push(`Must have at most ${v.maxLength} items.`);\n }\n }\n }\n}\n\n/**\n * Validates a submitted node `config` against the field rules in its manifest\n * (`required`, `IConfigValidation`, types, static options). For `dynamic-schema`\n * fields the resolved child schema is fetched and its rules applied to the\n * flattened keys. Deep cross-field validation is intentionally out of scope\n * (the production service does that on save); this mirrors the mock's\n * \"light, schema-based\" fidelity. Unknown extra keys are ignored.\n */\nexport async function validateNodeConfig(loaded: LoadedPackage, store: DevStore, input: ValidateNodeConfigInput): Promise<ValidateNodeConfigResult> {\n const node = findNode(loaded, input.slug, input.version);\n const config = input.config ?? {};\n const errors: Record<string, string[]> = {};\n const fields = node.description.config ?? [];\n\n for (const field of fields) {\n if (field.type === 'dynamic-schema') {\n continue; // resolved child fields are validated below\n }\n validateField(field, config[field.key], errors);\n }\n\n if (fields.some(f => f.type === 'dynamic-schema') && node.resolveConfigSchema) {\n const ctx = authorContext(loaded, store, config, input.locale);\n let children: IConfigField[];\n try {\n children = await node.resolveConfigSchema(ctx);\n } catch (err) {\n if (err instanceof DevApiError) {\n throw err;\n }\n throw new DevApiError(502, `Node resolve failed: ${(err as Error).message}`);\n }\n for (const child of children) {\n validateField(child, config[child.key], errors);\n }\n }\n\n return { valid: Object.keys(errors).length === 0, errors };\n}\n\nexport interface ExecuteNodeTestInput {\n slug: string;\n version?: string;\n /** The node's config values to run with. */\n config: Record<string, unknown>;\n /** Simulated input payloads, merged OVER the config (the contract's wording). */\n inputs: Record<string, unknown>;\n /** Wall-clock limit; clamped to >= 1000 ms like the real runtime. */\n timeoutMs?: number;\n}\n\nexport interface ExecuteNodeTestResult {\n outputs: Record<string, unknown>;\n branch: string | null;\n logs: Array<{ level: string; message: string; meta?: Record<string, unknown> }>;\n}\n\n/** Floor the contract puts on `timeout_ms`, and the default when none is given. */\nconst MIN_TIMEOUT_MS = 1000;\nconst DEFAULT_TIMEOUT_MS = 30_000;\n\n/** Thrown by the timeout arm of the race; never leaves `executeNodeTest`. */\nclass ExecuteTimeout extends Error {}\n\n/**\n * Runs a node's real `execute` in-process — the closest the mock gets to the\n * production sandbox, and the endpoint node authors care about most.\n *\n * `execute(ctx, inputs)` takes a single merged object, so `config` and `inputs`\n * are merged here with `inputs` winning, matching how the service describes it.\n * Logger calls are collected and returned as `logs` instead of being dropped.\n *\n * The timeout is enforced by racing, not just by aborting `ctx.signal`. A node\n * that never looks at the signal — an accidental infinite loop's `await`, a\n * third-party client that takes no `AbortSignal` — would otherwise hang the\n * request until Node's own 300 s `requestTimeout`, which is the opposite of what\n * \"honours timeout_ms\" should mean for someone debugging their own node. The\n * signal is still aborted first, so a well-behaved node fails fast and its own\n * error wins the race.\n */\nexport async function executeNodeTest(loaded: LoadedPackage, store: DevStore, input: ExecuteNodeTestInput): Promise<ExecuteNodeTestResult> {\n const node = findNode(loaded, input.slug, input.version);\n const logs: ExecuteNodeTestResult['logs'] = [];\n const record = (level: string) => (message: string, meta?: Record<string, unknown>) => {\n logs.push(meta === undefined ? { level, message } : { level, message, meta });\n };\n\n const timeoutMs = Math.max(MIN_TIMEOUT_MS, input.timeoutMs ?? DEFAULT_TIMEOUT_MS);\n const controller = new AbortController();\n let timer: NodeJS.Timeout | undefined;\n const expired = new Promise<never>((_resolve, reject) => {\n timer = setTimeout(() => {\n controller.abort();\n reject(new ExecuteTimeout());\n }, timeoutMs);\n });\n\n const ctx = {\n signal: controller.signal,\n logger: { info: record('info'), warn: record('warn'), error: record('error') },\n secrets: {\n async get(key: string): Promise<string> {\n const secret = store.getSecret(key);\n if (!secret) {\n throw new DevApiError(404, `Secret '${key}' not found.`);\n }\n return secret.value;\n },\n },\n credentials: {\n async get(id: string): Promise<Record<string, unknown>> {\n return (await resolveCredentialInstance(loaded, store, id)).credentials;\n },\n },\n };\n\n try {\n const result = await Promise.race([node.execute(ctx, { ...input.config, ...input.inputs }), expired]);\n return { outputs: result.outputs ?? {}, branch: result.branch ?? null, logs };\n } catch (err) {\n if (err instanceof DevApiError) {\n throw err;\n }\n // The node itself threw, or the race expired. 502 mirrors how the mock reports a\n // failing author-time resolver, and the collected logs go along so the failure is\n // diagnosable — a timeout in particular is usually only readable from the logs\n // the node managed to emit before it stalled.\n const reason = err instanceof ExecuteTimeout || controller.signal.aborted ? `timed out after ${timeoutMs} ms` : (err as Error).message;\n throw new DevApiError(502, `Node execution failed: ${reason}`, { logs: logs.map(l => `${l.level}: ${l.message}`) });\n } finally {\n // Also stops the timer from holding the event loop open when the node won.\n clearTimeout(timer);\n }\n}\n\n/** Runs a credential type's `test` against inline (unsaved) config. */\nexport async function testCredentialConfig(loaded: LoadedPackage, store: DevStore, typeSlug: string, config: Record<string, unknown>): Promise<ICredentialTestResult> {\n const cred = findCredential(loaded, typeSlug);\n return cred.test(credentialContext(store), config);\n}\n\n/** Runs `test` against a saved credential instance's stored config. */\nexport async function testCredentialInstance(loaded: LoadedPackage, store: DevStore, credentialId: string): Promise<ICredentialTestResult> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n return cred.test(credentialContext(store, credentialId), instance.config);\n}\n\nexport async function buildOAuthAuthorizeUrl(\n loaded: LoadedPackage,\n store: DevStore,\n credentialId: string,\n params: { redirectUri: string; state: string },\n): Promise<{ authorizeUrl: string; codeVerifier?: string }> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n if (!isOAuthAuthorizeCredential(cred)) {\n throw new DevApiError(422, `Credential type '${instance.credentialTypeSlug}' is not a 3-legged OAuth type.`);\n }\n return cred.buildAuthorizeUrl(credentialContext(store, credentialId), instance.config, params);\n}\n\nexport async function exchangeOAuthCode(\n loaded: LoadedPackage,\n store: DevStore,\n credentialId: string,\n params: { code: string; redirectUri: string; codeVerifier?: string },\n): Promise<{ durableCreds: Record<string, unknown> }> {\n const instance = store.getCredential(credentialId);\n if (!instance) {\n throw new DevApiError(404, `Credential instance '${credentialId}' not found.`);\n }\n const cred = findCredential(loaded, instance.credentialTypeSlug);\n if (!isOAuthAuthorizeCredential(cred)) {\n throw new DevApiError(422, `Credential type '${instance.credentialTypeSlug}' is not a 3-legged OAuth type.`);\n }\n const out = await cred.exchangeCode(credentialContext(store, credentialId), instance.config, params);\n store.updateCredential(credentialId, { durableCreds: out.durableCreds, status: 'active' });\n return out;\n}\n","import http from 'node:http';\nimport { DevApiError } from './errors.js';\nimport { readJson, sendError, sendJson, sendNoContent } from './http.js';\nimport type { LoadedPackage } from './loader.js';\nimport { credentialInstanceToApi, credentialTypeToApi, nodeToApi, secretToApi, templateFullToApi, templateSummaryToApi, triggerToApi, workflowToApi } from './projections.js';\nimport {\n buildOAuthAuthorizeUrl,\n exchangeOAuthCode,\n executeNodeTest,\n findCredential,\n findCredentialType,\n nodeVersions,\n resolveNodeConfig,\n testCredentialConfig,\n testCredentialInstance,\n validateNodeConfig,\n} from './resolve.js';\nimport { DEV_TENANT_ID, type DevStore } from './store.js';\n\nexport interface DevServerDeps {\n /** Returns the currently-loaded package; a function so hot-reload can swap it. */\n getPackage(): LoadedPackage;\n store: DevStore;\n /** JSON schemas served at `/schemas/{domain}[/{version}]`, keyed by `domain` and `domain/version`. */\n schemas?: Record<string, unknown>;\n}\n\nconst SEGMENT = (s: string | undefined): string => decodeURIComponent(s ?? '');\n\n/** Builds the `(req, res)` request listener implementing the mock `/api/v1` surface. */\nexport function createRequestListener(deps: DevServerDeps): http.RequestListener {\n return (req, res) => {\n handle(req, res, deps).catch(err => sendError(res, err));\n };\n}\n\nexport function createDevServer(deps: DevServerDeps): http.Server {\n return http.createServer(createRequestListener(deps));\n}\n\nasync function handle(req: http.IncomingMessage, res: http.ServerResponse, deps: DevServerDeps): Promise<void> {\n const method = (req.method ?? 'GET').toUpperCase();\n if (method === 'OPTIONS') {\n sendJson(res, 204, {});\n return;\n }\n\n const url = new URL(req.url ?? '/', 'http://localhost');\n let pathname = url.pathname;\n if (pathname.startsWith('/api/v1')) {\n pathname = pathname.slice('/api/v1'.length);\n }\n const seg = pathname.split('/').filter(Boolean).map(SEGMENT);\n const loaded = deps.getPackage();\n const store = deps.store;\n\n switch (seg[0]) {\n case undefined:\n case 'health':\n // The service's health route is `/up` (Laravel's default); `/health` is kept\n // because the devkit has always answered there.\n case 'up':\n return void sendJson(res, 200, { status: 'ok' });\n\n case 'me':\n // Shape per the contract: { user, context, claims }. The mock used to send a\n // flat { id, name, email, tenant_id }, which no real client could consume.\n return void sendJson(res, 200, {\n user: { id: 1, zitadel_id: 'dev-user', email: 'dev@revenexx.test', name: 'Dev User' },\n context: { tenant_id: DEV_TENANT_ID, active_plane: 'public', roles: ['admin', 'user'] },\n claims: { iss: 'https://id.revenexx.test', sub: 'dev-user', aud: ['devkit'] },\n });\n\n case 'schemas':\n return handleSchemas(res, deps, seg);\n\n case 'nodes':\n return handleNodes(req, res, method, loaded, store, seg);\n\n case 'credential-types':\n return handleCredentialTypes(res, loaded, seg);\n\n case 'credentials':\n return handleCredentials(req, res, method, loaded, store, seg, url);\n\n case 'secrets':\n return handleSecrets(req, res, method, store, seg);\n\n case 'templates':\n return handleTemplates(req, res, method, loaded, store, seg);\n\n case 'workflows':\n return handleWorkflows(req, res, method, store, seg);\n\n default:\n return void sendJson(res, 404, { message: `No route for /${seg.join('/')}` });\n }\n}\n\n// --------------------------------------------------------------------- schemas\n\n/**\n * The two schema routes have DIFFERENT shapes in the contract, which the mock\n * previously collapsed into one (it served the raw schema at both paths):\n *\n * GET /schemas/{domain} -> { domain, versions: string[] } (a listing)\n * GET /schemas/{domain}/{version} -> { domain, version, schema: {…} } (wrapped)\n *\n * Keys in `deps.schemas` are `domain` and `domain/version`, from the\n * `<domain>-<version>.json` files in assets/schemas.\n */\nfunction handleSchemas(res: http.ServerResponse, deps: DevServerDeps, seg: string[]): void {\n const domain = seg[1];\n const version = seg[2];\n if (!domain) {\n throw new DevApiError(404, 'Schema domain required.');\n }\n const schemas = deps.schemas ?? {};\n\n if (!version) {\n const versions = Object.keys(schemas)\n .filter(key => key.startsWith(`${domain}/`))\n .map(key => key.slice(domain.length + 1))\n .sort();\n if (versions.length === 0 && !schemas[domain]) {\n throw new DevApiError(404, `Unknown schema domain '${domain}'. Vendor it into assets/schemas.`);\n }\n return void sendJson(res, 200, { domain, versions });\n }\n\n // Exact match only. Falling back to the bare-domain (latest) entry would answer\n // 200 for EVERY version string — a node author asking for a version that does not\n // exist would be handed the latest schema and told it was the one they asked for.\n const schema = schemas[`${domain}/${version}`];\n if (!schema) {\n throw new DevApiError(404, `Unknown schema version '${domain}/${version}'. Vendor it into assets/schemas.`);\n }\n sendJson(res, 200, { domain, version, schema });\n}\n\n// ----------------------------------------------------------------------- nodes\n\nasync function handleNodes(req: http.IncomingMessage, res: http.ServerResponse, method: string, loaded: LoadedPackage, store: DevStore, seg: string[]): Promise<void> {\n // GET /nodes\n if (seg.length === 1 && method === 'GET') {\n return void sendJson(res, 200, { data: loaded.manifest.nodes.map(n => nodeToApi(n, nodeApiContext(loaded))) });\n }\n const slug = seg[1];\n if (!slug) {\n throw new DevApiError(404, 'Node slug required.');\n }\n\n // GET /nodes/{slug}/versions\n if (seg[2] === 'versions' && method === 'GET') {\n const versions = nodeVersions(loaded, slug);\n if (versions.length === 0) {\n throw new DevApiError(404, `Node '${slug}' not found.`);\n }\n return void sendJson(res, 200, { data: versions });\n }\n\n const version = seg[2];\n if (!version) {\n throw new DevApiError(404, 'Node version required.');\n }\n\n // POST /nodes/{slug}/{version}/config:resolve\n if (seg[3] === 'config:resolve' && method === 'POST') {\n const body = await readJson<{ target?: string; config?: Record<string, unknown>; locale?: string }>(req);\n if (!body.target) {\n throw new DevApiError(422, 'Field `target` is required.', { target: ['The target field is required.'] });\n }\n const result = await resolveNodeConfig(loaded, store, {\n slug,\n version,\n target: body.target,\n config: body.config ?? {},\n locale: body.locale,\n });\n return void sendJson(res, 200, result);\n }\n\n // POST /nodes/{slug}/{version}/config:validate\n //\n // DEVKIT-ONLY: this endpoint does NOT exist in the real integrations API. It\n // backs the preview host's `/nodes` page (Save → verdict + refused fields).\n // Listed in DEVKIT_ONLY in tests/contract.test.ts; do not build node code that\n // depends on it existing in production.\n if (seg[3] === 'config:validate' && method === 'POST') {\n const body = await readJson<{ config?: Record<string, unknown>; locale?: string }>(req);\n const result = await validateNodeConfig(loaded, store, {\n slug,\n version,\n config: body.config ?? {},\n locale: body.locale,\n });\n // 200 even when invalid — the `{ valid, errors }` body carries the verdict.\n return void sendJson(res, 200, result);\n }\n\n // POST /nodes/{slug}/{version}/execute:test\n if (seg[3] === 'execute:test' && method === 'POST') {\n const body = await readJson<{ config?: Record<string, unknown>; inputs?: Record<string, unknown>; timeout_ms?: number }>(req);\n const result = await executeNodeTest(loaded, store, {\n slug,\n version,\n config: body.config ?? {},\n inputs: body.inputs ?? {},\n timeoutMs: body.timeout_ms,\n });\n return void sendJson(res, 200, result);\n }\n\n // GET /nodes/{slug}/{version}\n if (seg.length === 3 && method === 'GET') {\n return void sendJson(res, 200, nodeToApi(findManifestNode(loaded, slug, version), nodeApiContext(loaded)));\n }\n\n // DELETE /nodes/{slug}/{version}\n //\n // The mock has no node registry to delete from — nodes come from the package\n // entry on disk. The route exists so the shape of a real deletion (404 for an\n // unknown node, 204 for a known one) is what an author sees.\n if (seg.length === 3 && method === 'DELETE') {\n findManifestNode(loaded, slug, version);\n return void sendNoContent(res);\n }\n\n throw new DevApiError(404, `No route for nodes/${seg.slice(1).join('/')}`);\n}\n\n/** The package identity + load time `GET /nodes` reports alongside each node. */\nfunction nodeApiContext(loaded: LoadedPackage) {\n return { packageInfo: loaded.packageInfo, loadedAt: loaded.loadedAt };\n}\n\n/**\n * Resolves a node's MANIFEST entry (what `GET /nodes` projects), or throws 404.\n * Distinct from resolve.ts's `findNode`, which returns the live INode instance.\n */\nfunction findManifestNode(loaded: LoadedPackage, slug: string, version: string) {\n const node = loaded.manifest.nodes.find(n => n.slug === slug && (version === 'latest' || n.version === version));\n if (!node) {\n throw new DevApiError(404, `Node '${slug}@${version}' not found.`);\n }\n return node;\n}\n\n// ------------------------------------------------------------- credential-types\n\nfunction handleCredentialTypes(res: http.ServerResponse, loaded: LoadedPackage, seg: string[]): void {\n if (seg.length === 1) {\n return void sendJson(res, 200, {\n data: (loaded.manifest.credentials ?? []).map(credentialTypeToApi),\n });\n }\n const slug = seg[1]!;\n const type = findCredentialType(loaded, slug); // throws 404\n sendJson(res, 200, { data: credentialTypeToApi(type) });\n}\n\n// ----------------------------------------------------------------- credentials\n\nasync function handleCredentials(req: http.IncomingMessage, res: http.ServerResponse, method: string, loaded: LoadedPackage, store: DevStore, seg: string[], url: URL): Promise<void> {\n const typeOf = (slug: string) => {\n try {\n return findCredentialType(loaded, slug);\n } catch {\n return undefined;\n }\n };\n\n // Collection-level routes.\n if (seg.length === 1) {\n if (method === 'GET') {\n const filter = url.searchParams.get('type') ?? undefined;\n const data = store.listCredentials(filter).map(c => credentialInstanceToApi(c, typeOf(c.credentialTypeSlug)));\n return void sendJson(res, 200, { data });\n }\n if (method === 'POST') {\n const body = await readJson<{ credential_type_slug?: string; name?: string; config?: Record<string, unknown> }>(req);\n if (!body.credential_type_slug || !body.name) {\n throw new DevApiError(422, 'Fields `credential_type_slug` and `name` are required.');\n }\n findCredential(loaded, body.credential_type_slug); // 404 if unknown type\n const record = store.createCredential({\n credentialTypeSlug: body.credential_type_slug,\n name: body.name,\n config: body.config ?? {},\n });\n return void sendJson(res, 201, credentialInstanceToApi(record, typeOf(record.credentialTypeSlug)));\n }\n }\n\n // POST /credentials/test (inline, unsaved)\n if (seg[1] === 'test' && method === 'POST') {\n const body = await readJson<{ credential_type_slug?: string; config?: Record<string, unknown> }>(req);\n if (!body.credential_type_slug) {\n throw new DevApiError(422, 'Field `credential_type_slug` is required.');\n }\n const result = await testCredentialConfig(loaded, store, body.credential_type_slug, body.config ?? {});\n return void sendJson(res, 200, result);\n }\n\n // GET /credentials/oauth/callback\n if (seg[1] === 'oauth' && seg[2] === 'callback' && method === 'GET') {\n const code = url.searchParams.get('code');\n const state = url.searchParams.get('state');\n if (!code || !state) {\n throw new DevApiError(422, 'OAuth callback requires `code` and `state`.');\n }\n // The state carries the credential id in the dev flow (see authorize-url below).\n const credentialId = state;\n const redirectUri = `${url.origin}/api/v1/credentials/oauth/callback`;\n await exchangeOAuthCode(loaded, store, credentialId, { code, redirectUri });\n return void sendJson(res, 200, { status: 'connected', credential_id: credentialId });\n }\n\n const id = seg[1];\n if (!id) {\n throw new DevApiError(404, 'Credential id required.');\n }\n\n // POST /credentials/{id}/test\n if (seg[2] === 'test' && method === 'POST') {\n const result = await testCredentialInstance(loaded, store, id);\n // The contract reports the recorded outcome alongside the verdict — the\n // service persists it on the credential. (The inline variant,\n // POST /credentials/test, returns the bare `{ ok }` and records nothing,\n // because there is no record yet.)\n const record = store.recordCredentialTest(id, { ok: result.ok, message: result.message ?? null });\n return void sendJson(res, 200, {\n ok: result.ok,\n message: result.message ?? null,\n last_test_at: record?.lastTestAt ?? null,\n last_test_ok: record?.lastTestOk ?? result.ok,\n });\n }\n\n // POST /credentials/{id}/oauth/authorize-url\n if (seg[2] === 'oauth' && seg[3] === 'authorize-url' && method === 'POST') {\n const redirectUri = 'http://localhost/api/v1/credentials/oauth/callback';\n // Dev flow: carry the credential id in `state` so the callback can find it.\n const result = await buildOAuthAuthorizeUrl(loaded, store, id, { redirectUri, state: id });\n return void sendJson(res, 200, { authorize_url: result.authorizeUrl });\n }\n\n // Item-level routes.\n if (seg.length === 2) {\n const record = store.getCredential(id);\n if (method === 'GET') {\n if (!record) {\n throw new DevApiError(404, `Credential '${id}' not found.`);\n }\n return void sendJson(res, 200, credentialInstanceToApi(record, typeOf(record.credentialTypeSlug)));\n }\n if (method === 'PATCH') {\n if (!record) {\n throw new DevApiError(404, `Credential '${id}' not found.`);\n }\n const body = await readJson<{ name?: string; config?: Record<string, unknown> }>(req);\n const updated = store.updateCredential(id, { name: body.name, config: body.config });\n return void sendJson(res, 200, credentialInstanceToApi(updated!, typeOf(updated!.credentialTypeSlug)));\n }\n if (method === 'DELETE') {\n store.deleteCredential(id);\n return void sendNoContent(res);\n }\n }\n\n throw new DevApiError(404, `No route for credentials/${seg.slice(1).join('/')}`);\n}\n\n// --------------------------------------------------------------------- secrets\n\nasync function handleSecrets(req: http.IncomingMessage, res: http.ServerResponse, method: string, store: DevStore, seg: string[]): Promise<void> {\n if (seg.length === 1) {\n if (method === 'GET') {\n // The contract's top-level property is `keys: string[]` — a bare key list,\n // not records. The mock used to send `{ data: [{key, created_at, …}] }`,\n // which is why the UI carries a three-way envelope fallback.\n return void sendJson(res, 200, { keys: store.listSecrets().map(s => s.key) });\n }\n if (method === 'POST') {\n const body = await readJson<{ key?: string; value?: string }>(req);\n if (!body.key || body.value === undefined) {\n throw new DevApiError(422, 'Fields `key` and `value` are required.');\n }\n const record = store.setSecret(body.key, body.value);\n return void sendJson(res, 201, secretToApi(record));\n }\n }\n const key = seg[1];\n if (key) {\n if (method === 'PATCH') {\n const body = await readJson<{ value?: string }>(req);\n if (body.value === undefined) {\n throw new DevApiError(422, 'Field `value` is required.');\n }\n return void sendJson(res, 200, secretToApi(store.setSecret(key, body.value)));\n }\n if (method === 'DELETE') {\n store.deleteSecret(key);\n return void sendNoContent(res);\n }\n }\n throw new DevApiError(404, `No route for secrets/${seg.slice(1).join('/')}`);\n}\n\n// ------------------------------------------------------------------- templates\n\nasync function handleTemplates(req: http.IncomingMessage, res: http.ServerResponse, method: string, loaded: LoadedPackage, store: DevStore, seg: string[]): Promise<void> {\n const templates = loaded.manifest.templates ?? [];\n if (seg.length === 1 && method === 'GET') {\n return void sendJson(res, 200, { data: templates.map(templateSummaryToApi) });\n }\n const slug = seg[1];\n const template = templates.find(t => t.slug === slug);\n if (!template) {\n throw new DevApiError(404, `Template '${slug}' not found.`);\n }\n if (seg.length === 2 && method === 'GET') {\n // Wrapped in `data` per the contract; the mock used to return it bare.\n return void sendJson(res, 200, { data: templateFullToApi(template) });\n }\n if (seg[2] === 'requirements' && method === 'GET') {\n // The contract's key is `credentialTypes` (the mock said `credentials`).\n // Resolving what a template's blob actually references is not implemented —\n // an empty requirement set is honest, not a stand-in for real analysis.\n return void sendJson(res, 200, { data: { credentialTypes: [], secrets: [] } });\n }\n if (seg[2] === 'instantiate' && method === 'POST') {\n const body = await readJson<{ name?: string }>(req);\n // A template's `definition` IS a workflow blob authored against its\n // `blobVersion` (see ITemplateDescription), so it maps straight onto the\n // workflow's blob + blob_definition_version.\n const workflow = store.createWorkflow({\n name: body.name ?? String(template.name),\n blob: template.definition,\n blobDefinitionVersion: template.blobVersion,\n });\n for (const trigger of template.triggers ?? []) {\n store.createTrigger({\n workflowId: workflow.id,\n type: trigger.type,\n name: trigger.name ?? null,\n config: trigger.config ?? {},\n active: trigger.active ?? true,\n id: trigger.handle,\n });\n }\n return void sendJson(res, 201, workflowToApi(workflow));\n }\n throw new DevApiError(404, `No route for templates/${seg.slice(1).join('/')}`);\n}\n\n// ------------------------------------------------------------------- workflows\n\n/**\n * Body of POST /workflows and PUT /workflows/{id}, in the contract's snake_case.\n * Note `blob` — NOT `definition`. The mock read `body.definition` until 0.2.2,\n * so every workflow saved from the real UI silently stored an empty graph.\n */\ninterface WorkflowWriteBody {\n name?: string;\n description?: string | null;\n blob?: Record<string, unknown>;\n blob_definition_version?: string;\n active?: boolean;\n execution_mode?: string;\n}\n\nasync function handleWorkflows(req: http.IncomingMessage, res: http.ServerResponse, method: string, store: DevStore, seg: string[]): Promise<void> {\n if (seg.length === 1) {\n if (method === 'GET') {\n return void sendJson(res, 200, { data: store.listWorkflows().map(workflowToApi) });\n }\n if (method === 'POST') {\n const body = await readJson<WorkflowWriteBody>(req);\n const workflow = store.createWorkflow({\n name: body.name ?? 'Untitled workflow',\n blob: body.blob ?? {},\n blobDefinitionVersion: body.blob_definition_version,\n description: body.description,\n active: body.active,\n executionMode: body.execution_mode,\n });\n return void sendJson(res, 201, workflowToApi(workflow));\n }\n }\n\n // Collection sub-routes registered before {id}.\n if (seg[1] === 'used-credentials' && method === 'GET') {\n return void sendJson(res, 200, { data: [] });\n }\n if (seg[1] === 'used-credential-types' && method === 'GET') {\n return void sendJson(res, 200, { data: [] });\n }\n\n const id = Number.parseInt(seg[1] ?? '', 10);\n if (Number.isNaN(id)) {\n throw new DevApiError(404, `No route for workflows/${seg.slice(1).join('/')}`);\n }\n\n // Triggers\n if (seg[2] === 'triggers') {\n if (seg.length === 3 && method === 'GET') {\n return void sendJson(res, 200, { data: store.listTriggers(id).map(triggerToApi) });\n }\n if (seg.length === 3 && method === 'POST') {\n const body = await readJson<{ type?: string; name?: string; config?: Record<string, unknown>; active?: boolean }>(req);\n if (!body.type) {\n throw new DevApiError(422, 'Field `type` is required.');\n }\n const trigger = store.createTrigger({ workflowId: id, type: body.type, name: body.name, config: body.config, active: body.active });\n return void sendJson(res, 201, triggerToApi(trigger));\n }\n const triggerId = seg[3];\n if (triggerId && method === 'PUT') {\n const body = await readJson<{ type?: string; name?: string; config?: Record<string, unknown>; active?: boolean }>(req);\n if (!body.type) {\n throw new DevApiError(422, 'Field `type` is required.');\n }\n const trigger = store.replaceTrigger(triggerId, { type: body.type, name: body.name, config: body.config, active: body.active });\n if (!trigger) {\n throw new DevApiError(404, `Trigger '${triggerId}' not found.`);\n }\n return void sendJson(res, 200, triggerToApi(trigger));\n }\n if (triggerId && method === 'DELETE') {\n store.deleteTrigger(triggerId);\n return void sendNoContent(res);\n }\n }\n\n // Item-level workflow routes.\n if (seg.length === 2) {\n const record = store.getWorkflow(id);\n if (method === 'GET') {\n if (!record) {\n throw new DevApiError(404, `Workflow '${id}' not found.`);\n }\n return void sendJson(res, 200, workflowToApi(record));\n }\n if (method === 'PUT') {\n const body = await readJson<WorkflowWriteBody>(req);\n const updated = store.updateWorkflow(id, {\n name: body.name,\n blob: body.blob,\n blobDefinitionVersion: body.blob_definition_version,\n description: body.description,\n active: body.active,\n executionMode: body.execution_mode,\n });\n if (!updated) {\n throw new DevApiError(404, `Workflow '${id}' not found.`);\n }\n return void sendJson(res, 200, workflowToApi(updated));\n }\n if (method === 'DELETE') {\n store.deleteWorkflow(id);\n return void sendNoContent(res);\n }\n }\n\n if ((seg[2] === 'credentials' || seg[2] === 'credential-types') && method === 'GET') {\n return void sendJson(res, 200, { data: [] });\n }\n\n throw new DevApiError(404, `No route for workflows/${seg.slice(1).join('/')}`);\n}\n","import type http from 'node:http';\nimport { DevApiError } from './errors.js';\n\n/**\n * The `/api/v1` contract version this mock implements. Mirrors what the real\n * service reports via its `SetApiVersion` middleware.\n *\n * Kept as a constant rather than read from the vendored spec so nothing 357 KB\n * has to ship in the package; `tests/contract.test.ts` asserts it equals\n * `info.version` of `contract/integrations-v1.json`, so the two cannot drift.\n */\nexport const API_VERSION = '1.0.0';\n\nconst BASE_HEADERS = {\n 'X-Api-Version': API_VERSION,\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Headers': '*',\n 'Access-Control-Allow-Methods': 'GET,POST,PUT,PATCH,DELETE,OPTIONS',\n};\n\nexport function sendJson(res: http.ServerResponse, status: number, body: unknown): void {\n const payload = JSON.stringify(body);\n res.writeHead(status, { 'Content-Type': 'application/json', ...BASE_HEADERS });\n res.end(payload);\n}\n\n/**\n * 204 with no body, which is what the service returns from every DELETE. The mock\n * used to answer `200 {deleted:true}`; per ADR-0036 §3 a changed status code is a\n * breaking difference, so that was training node authors on behaviour the real API\n * does not have.\n */\nexport function sendNoContent(res: http.ServerResponse): void {\n res.writeHead(204, BASE_HEADERS);\n res.end();\n}\n\n/** Maps a thrown error to the Laravel-style `{message}` / `{message, errors}` body. */\nexport function sendError(res: http.ServerResponse, err: unknown): void {\n if (err instanceof DevApiError) {\n sendJson(res, err.status, err.errors ? { message: err.message, errors: err.errors } : { message: err.message });\n return;\n }\n sendJson(res, 500, { message: (err as Error)?.message ?? 'Internal error' });\n}\n\nexport async function readBody(req: http.IncomingMessage): Promise<string> {\n let body = '';\n for await (const chunk of req) {\n body += chunk;\n }\n return body;\n}\n\n/** Reads + parses a JSON body; throws {@link DevApiError} 400 on malformed input. */\nexport async function readJson<T>(req: http.IncomingMessage): Promise<T> {\n const raw = await readBody(req);\n if (raw.trim() === '') {\n return {} as T;\n }\n try {\n return JSON.parse(raw) as T;\n } catch {\n throw new DevApiError(400, 'Invalid JSON body.');\n }\n}\n","import type { ICredentialDescription, INodeDescription, ITemplateDescription } from '@revenexx/integrations-node-sdk';\nimport type { PackageInfo } from './loader.js';\nimport { MANIFEST_VERSION } from '@revenexx/integrations-node-sdk';\nimport type { CredentialRecord, SecretRecord, TriggerRecord, WorkflowRecord } from './store.js';\n\n/**\n * Maps internal records + manifest descriptions to the exact JSON shapes the\n * production Laravel `/api/v1` surface returns, so the Cockpit UI consumes the\n * mock API without any awareness that it is mocked.\n */\n\nexport function hasDynamicOptions(desc: INodeDescription): boolean {\n return (desc.config ?? []).some(f => f.dynamic === true);\n}\n\nexport function hasDynamicSchema(desc: INodeDescription): boolean {\n return (desc.config ?? []).some(f => f.type === 'dynamic-schema');\n}\n\nexport function hasDynamicOutputs(desc: INodeDescription): boolean {\n return (desc.outputs ?? []).some(o => o.resolveOutputs === true);\n}\n\nexport interface NodeApiContext {\n packageInfo: PackageInfo;\n loadedAt: string;\n}\n\nexport function nodeToApi(desc: INodeDescription, ctx?: NodeApiContext): Record<string, unknown> {\n const [namespace] = desc.slug.split(':');\n return {\n name: desc.name,\n namespace: namespace ?? null,\n slug: desc.slug,\n version: desc.version,\n // The contract declares `package` and both timestamps as present. Nodes here\n // come from the developer's working tree, so the package identity is read from\n // their package.json and the timestamps are when the mock loaded the entry.\n package: ctx?.packageInfo ?? null,\n manifest_version: MANIFEST_VERSION,\n manifest: desc,\n has_dynamic_options: hasDynamicOptions(desc),\n has_dynamic_schema: hasDynamicSchema(desc),\n has_dynamic_outputs: hasDynamicOutputs(desc),\n created_at: ctx?.loadedAt ?? null,\n updated_at: ctx?.loadedAt ?? null,\n };\n}\n\nexport function credentialTypeToApi(desc: ICredentialDescription): Record<string, unknown> {\n return {\n slug: desc.slug,\n version: desc.version,\n name: desc.name,\n description: desc.description ?? null,\n icon: desc.icon ?? null,\n images: desc.images ?? [],\n auth_kind: desc.authKind,\n fields: desc.fields,\n };\n}\n\n/** Projects a credential instance to its masked public API shape (no secrets). */\nexport function credentialInstanceToApi(record: CredentialRecord, type: ICredentialDescription | undefined): Record<string, unknown> {\n const secretKeys = new Set((type?.fields ?? []).filter(f => f.type === 'secret').map(f => f.key));\n const knownKeys = new Set((type?.fields ?? []).map(f => f.key));\n const publicConfig: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(record.config)) {\n // Only surface known, non-secret fields; drop everything else defensively.\n if (knownKeys.has(key) && !secretKeys.has(key)) {\n publicConfig[key] = value;\n }\n }\n return {\n id: record.id,\n tenant_id: record.tenantId,\n credential_type_slug: record.credentialTypeSlug,\n name: record.name,\n status: record.status,\n public_config: publicConfig,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\nexport function secretToApi(record: SecretRecord): Record<string, unknown> {\n return {\n key: record.key,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\n/**\n * NOTE the asymmetry, which is the contract's and not a mistake here: a WORKFLOW\n * carries its graph as `blob` + `blob_definition_version`, while a TEMPLATE\n * carries its graph as `definition` + `blob_version`.\n */\nexport function workflowToApi(record: WorkflowRecord): Record<string, unknown> {\n return {\n id: record.id,\n name: record.name,\n description: record.description,\n blob_definition_version: record.blobDefinitionVersion,\n blob: record.blob,\n active: record.active,\n execution_mode: record.executionMode,\n revision: record.revision,\n // The service reports blob-validation warnings here. The mock's validation is\n // schema-light (see the fidelity caveats), so it never has any — but the field\n // is part of the contract and clients may read it.\n warnings: [],\n build_status: record.buildStatus,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\nexport function triggerToApi(record: TriggerRecord): Record<string, unknown> {\n return {\n handle: record.id,\n id: record.id,\n workflow_id: record.workflowId,\n type: record.type,\n name: record.name,\n config: record.config,\n active: record.active,\n created_at: record.createdAt,\n updated_at: record.updatedAt,\n };\n}\n\nexport function templateSummaryToApi(t: ITemplateDescription): Record<string, unknown> {\n return {\n slug: t.slug,\n version: t.version,\n category: t.category,\n level: t.level,\n name: t.name,\n shortDescription: t.shortDescription ?? null,\n description: t.description ?? null,\n icon: t.icon ?? null,\n images: t.images ?? [],\n industries: t.industries ?? [],\n vendors: t.vendors ?? [],\n triggerTypes: (t.triggers ?? []).map(tr => tr.type),\n };\n}\n\nexport function templateFullToApi(t: ITemplateDescription): Record<string, unknown> {\n return {\n ...templateSummaryToApi(t),\n // snake_case per the contract, even though the surrounding template fields are\n // camelCase and the SDK's own field is `blobVersion`.\n blob_version: t.blobVersion,\n definition: t.definition,\n // `config` is optional in the SDK (a manual trigger has none) but declared in\n // the contract, so normalise it to an object rather than omitting it.\n triggers: (t.triggers ?? []).map(tr => ({ ...tr, config: tr.config ?? {} })),\n };\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":";;;;;;;;;;;;;;;;;;;;;;;;;;AAKA,IAAM,mBAAmB,MACvB,OAAO,aAAa,cAChB,IAAI,IAAI,QAAQ,UAAU,EAAE,EAAE,OAC7B,SAAS,iBAAiB,SAAS,cAAc,QAAQ,YAAY,MAAM,WAC1E,SAAS,cAAc,MACvB,IAAI,IAAI,WAAW,SAAS,OAAO,EAAE;AAEtC,IAAM,gBAAgC,iCAAiB;;;ACkB9D,IAAAA,kBAA6D;AAE7D,IAAAC,oBAA6B;AAC7B,yBAA8B;AAC9B,IAAAC,oBAAiD;AACjD,IAAAC,mBAA8B;;;ACnC9B,qBAA2B;AAC3B,uBAAwB;;;ACGjB,IAAM,cAAN,cAA0B,MAAM;AAAA,EACrC,YACkB,QAChB,SACgB,QAChB;AACA,UAAM,OAAO;AAJG;AAEA;AAGhB,SAAK,OAAO;AAAA,EACd;AAAA,EANkB;AAAA,EAEA;AAKpB;AAWO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YAAY,SAAiB;AAC3B,UAAM,OAAO;AACb,SAAK,OAAO;AAAA,EACd;AACF;;;AC5BA,sBAA6B;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,QAA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C;","names":["import_node_fs","import_node_http","import_node_path","import_node_url","import_node_fs","import_node_path","import_node_fs","import_node_fs","import_node_path","import_node_fs","import_node_path","import_integrations_node_sdk","v","import_integrations_node_sdk","import_node_crypto","import_node_fs","import_node_path","import_node_url","import_node_fs","import_node_path","relative","envFile","rmSync"]}
|