@revenexx/integrations-node-devkit 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -0
- package/dist/{chunk-YXIYTBOZ.js → chunk-4QB5F7RT.js} +112 -5
- package/dist/chunk-4QB5F7RT.js.map +1 -0
- package/dist/chunk-PME34X7E.js +30 -0
- package/dist/chunk-PME34X7E.js.map +1 -0
- package/dist/cli.cjs +133 -7
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +2 -1
- package/dist/cli.js.map +1 -1
- package/dist/index.cjs +133 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +38 -4
- package/dist/index.d.ts +38 -4
- package/dist/index.js +2 -1
- package/dist/testing/index.cjs +133 -3
- package/dist/testing/index.cjs.map +1 -1
- package/dist/testing/index.d.cts +62 -3
- package/dist/testing/index.d.ts +62 -3
- package/dist/testing/index.js +110 -0
- package/dist/testing/index.js.map +1 -1
- package/package.json +3 -3
- package/preview-host/package.json +1 -1
- package/dist/chunk-YXIYTBOZ.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../node_modules/tsup/assets/cjs_shims.js","../src/env.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"],"sourcesContent":["/**\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","// 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","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 * 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 { 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKA,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;;;ADH9D,IAAAA,kBAA6B;;;AET7B,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,CAAC,CAA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vD,IAAM,iBAAyB,KAAK,UAAM,8BAAa,aAAa,MAAM,CAAC,EAAE;","names":["import_node_fs","import_node_fs","import_node_path","import_node_fs","import_node_path","import_integrations_node_sdk","v","import_integrations_node_sdk","http"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../node_modules/tsup/assets/cjs_shims.js","../src/env.ts","../src/errors.ts","../src/loader.ts","../src/persistence.ts","../src/store.ts","../src/resolve.ts","../src/state-rules.ts","../src/server.ts","../src/http.ts","../src/projections.ts"],"sourcesContent":["/**\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","// 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","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 * 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 { 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\n/**\n * One entry of the tenant state store (PO-374), flattened across the four\n * roles: `key` is the mapping's left id, the cursor's partition key, the\n * claimed key or the digest's entity key, and `value` the partner id, the\n * watermark, the expiry or the hash.\n *\n * The mock keeps them in one list rather than four tables because nothing here\n * enforces integrity — the real store's constraints are the product, this is a\n * scratchpad that makes a node's second run behave like a second run.\n */\nexport interface StateEntryRecord {\n namespace: string;\n role: 'mapping' | 'cursor' | 'dedupe' | 'digest';\n key: string;\n value: unknown;\n updatedAt: string;\n}\n\nexport interface DevStoreSnapshot {\n schemaVersion: number;\n credentials: CredentialRecord[];\n secrets: SecretRecord[];\n workflows: WorkflowRecord[];\n triggers: TriggerRecord[];\n stateEntries?: StateEntryRecord[];\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`, and to 3 when the\n * state store (PO-374) arrived. `loadState` discards an overlay whose version\n * does not match, which is the migration: seeds are the source of truth, the\n * overlay is disposable session state.\n */\nexport const STORE_SCHEMA_VERSION = 3;\n\nfunction now(): string {\n return new Date().toISOString();\n}\n\n/**\n * The role is part of the identity, not a label on the record: the four roles\n * share a namespace and a key freely — the entity that was just correlated is\n * usually the one a digest is written for — and one slot per `(namespace, key)`\n * would let a digest become the answer a mapping lookup gives.\n */\nfunction stateKey(role: StateEntryRecord['role'], namespace: string, key: string): string {\n return `${role}\\u0000${namespace}\\u0000${key}`;\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 /** Keyed by `${role}\\u0000${namespace}\\u0000${key}` — a NUL occurs in no part. */\n private stateEntries = new Map<string, StateEntryRecord>();\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 // ------------------------------------------------------------------ state\n\n /** The stored entry for a role/namespace/key, or undefined when unknown. */\n getStateEntry(role: StateEntryRecord['role'], namespace: string, key: string): StateEntryRecord | undefined {\n return this.stateEntries.get(stateKey(role, namespace, key));\n }\n\n /** Every entry a namespace holds in one role — how a reverse mapping lookup is answered. */\n listStateEntries(role: StateEntryRecord['role'], namespace: string): StateEntryRecord[] {\n return [...this.stateEntries.values()].filter(e => e.role === role && e.namespace === namespace);\n }\n\n putStateEntry(entry: Omit<StateEntryRecord, 'updatedAt'>): StateEntryRecord {\n const record: StateEntryRecord = { ...entry, updatedAt: now() };\n this.stateEntries.set(stateKey(entry.role, entry.namespace, entry.key), record);\n this.onChange?.();\n return record;\n }\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 stateEntries: [...this.stateEntries.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.stateEntries = new Map((snapshot.stateEntries ?? []).map(e => [stateKey(e.role, e.namespace, e.key), e]));\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 for (const e of snapshot.stateEntries ?? []) {\n this.stateEntries.set(stateKey(e.role, e.namespace, e.key), e);\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 INodeState,\n type IOutputPort,\n isOAuthAuthorizeCredential,\n settingApplies,\n} from '@revenexx/integrations-node-sdk';\nimport { DevApiError } from './errors.js';\nimport { assertNotRepointed, assertTtlInRange, DEFAULT_CLAIM_TTL_SECONDS } from './state-rules.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\n/**\n * `ctx.state` for one preview run (PO-374), backed by the dev store — so a node\n * that correlates ids behaves on its second call like a second run.\n *\n * Returns the state surface together with the `commit` that ends the run. A\n * mapping and a claim go straight to the store, because a correlation dropped by\n * a later failure is how the next run creates a duplicate; a cursor and a digest\n * are staged here and written only when `commit` is called, so a read during the\n * run answers what the last *completed* run left. That is the store's visibility\n * rule, and it is the reason `INodeState` has four operations instead of a\n * generic get/set.\n *\n * **Deliberately divergent from production in one respect**, and the one place\n * this mock does not mirror the real API: there, author-time execution is\n * read-only, because a correlation created by a test click would be\n * indistinguishable from one a production run made and the next real run would\n * trust it. Locally there is no such stake — the whole store is a disposable\n * overlay in `.revenexx-dev/` — and refusing writes would make it impossible to\n * exercise the very nodes the state store exists for. The divergence is noted in\n * the README.\n */\nfunction createRunState(store: DevStore): { state: INodeState; commit: () => void } {\n /** Staged for this run: written to the store by `commit`, dropped otherwise. */\n const staged: Array<{ namespace: string; role: 'cursor' | 'digest'; key: string; value: unknown }> = [];\n const stage = (entry: (typeof staged)[number]): void => {\n staged.push(entry);\n };\n\n const state: INodeState = {\n mapping: {\n async get(namespace, key, side = 'left') {\n if (side === 'left') {\n const entry = store.getStateEntry('mapping', namespace, key);\n return entry ? String(entry.value) : null;\n }\n const match = store.listStateEntries('mapping', namespace).find(e => String(e.value) === key);\n return match ? match.key : null;\n },\n async put(namespace, left, right) {\n assertNotRepointed(\n namespace,\n store.listStateEntries('mapping', namespace).map(e => [e.key, String(e.value)] as [string, string]),\n left,\n right,\n );\n store.putStateEntry({ namespace, role: 'mapping', key: left, value: right });\n },\n },\n cursor: {\n async get(namespace, partitionKey = '') {\n return store.getStateEntry('cursor', namespace, partitionKey)?.value;\n },\n async set(namespace, value, partitionKey = '') {\n stage({ namespace, role: 'cursor', key: partitionKey, value });\n },\n },\n async claim(namespace, key, opts) {\n assertTtlInRange(opts?.ttlSeconds);\n const held = store.getStateEntry('dedupe', namespace, key);\n // Expiry is honoured so a short TTL can actually be exercised locally,\n // rather than a claim looking permanent for the whole session.\n if (held && Number(held.value) > Date.now()) {\n return false;\n }\n const ttlSeconds = opts?.ttlSeconds ?? DEFAULT_CLAIM_TTL_SECONDS;\n store.putStateEntry({ namespace, role: 'dedupe', key, value: Date.now() + ttlSeconds * 1000 });\n return true;\n },\n digest: {\n async unchanged(namespace, entityKey, digest) {\n return store.getStateEntry('digest', namespace, entityKey)?.value === digest;\n },\n async set(namespace, entityKey, digest) {\n stage({ namespace, role: 'digest', key: entityKey, value: digest });\n },\n },\n };\n\n return {\n state,\n commit() {\n for (const entry of staged) {\n store.putStateEntry(entry);\n }\n staged.length = 0;\n },\n };\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 // A `state-ref` carries the chosen namespace NAME, so a string is all there\n // is to check here: which names exist is the workflow's declaration, and\n // nothing declares one locally (see the README's fidelity caveats).\n case 'state-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 *\n * A field whose `showIf` does not hold (SDK 1.0.0, PO-410) is skipped whole —\n * not demanded when required, and not type-checked either. The editor does not\n * draw it, so whatever is left under its key is a leftover from a choice the\n * author has since changed, and refusing to save because of it would leave them\n * with an error against a field they cannot see. `settingApplies` comes from the\n * SDK rather than being re-implemented here: the editor drawing the field and\n * this validator deciding whether to demand it have to agree word for word.\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 if (!settingApplies(field, config)) {\n continue; // its `showIf` says it is not on screen — see the doc comment\n }\n validateField(field, config[field.key], errors);\n }\n\n // A `dynamic-schema` marker can carry a `showIf` of its own — the condition\n // sits on `IConfigFieldBase`, not on the leaf types — and then the whole group\n // it stands for is off screen. `resolveConfigSchema` is per node rather than\n // per field, so a node with several markers resolves as soon as one of them\n // applies: which children came from which marker is not something the callback\n // says, and demanding none of them would be the worse guess of the two.\n if (fields.some(f => f.type === 'dynamic-schema' && settingApplies(f, config)) && 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 if (!settingApplies(child, config)) {\n continue;\n }\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 run = createRunState(store);\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 state: run.state,\n };\n\n try {\n const result = await Promise.race([node.execute(ctx, { ...input.config, ...input.inputs }), expired]);\n // The run completed, so what it staged is adopted. A node that threw, or one\n // the timeout cut off, leaves its cursors and digests where they were — the\n // failed-run case the staging rule exists for, and the one an author is most\n // likely to have got wrong.\n run.commit();\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 { NodeError } from '@revenexx/integrations-node-sdk';\n\n/**\n * The two rules the tenant state store keeps that neither the mock context nor\n * the local preview would otherwise have any reason to keep — and both of which\n * a node author only finds out about in production if we do not.\n *\n * They live here rather than in either caller because the testing harness and\n * the preview must refuse the same things: a node that passes its unit tests and\n * then trips the store on its first preview run has learnt nothing from either.\n * The rest of what the store promises — that a granted claim really excludes a\n * parallel run, that an undeclared namespace is refused — is the engine's, and\n * `specs/workflow-state.md` in the SDK records it as such.\n */\n\n/** Mirrors the engine's default claim lifetime (7 days). */\nexport const DEFAULT_CLAIM_TTL_SECONDS = 604_800;\n\n/** The window the store accepts: one second to one year. */\nexport const MIN_CLAIM_TTL_SECONDS = 1;\nexport const MAX_CLAIM_TTL_SECONDS = 31_536_000;\n\n/**\n * A `ttlSeconds` outside the accepted window is refused rather than clamped: the\n * figure is the duplicate-suppression window *and* the retry window, so a node\n * quietly given a different one than it asked for would suppress deliveries for\n * a stretch its author never chose.\n */\nexport function assertTtlInRange(ttlSeconds: number | undefined): void {\n if (ttlSeconds === undefined) {\n return;\n }\n if (!Number.isFinite(ttlSeconds) || ttlSeconds < MIN_CLAIM_TTL_SECONDS || ttlSeconds > MAX_CLAIM_TTL_SECONDS) {\n throw new NodeError('INVALID_TTL', `ttlSeconds must be between ${MIN_CLAIM_TTL_SECONDS} and ${MAX_CLAIM_TTL_SECONDS}, got ${String(ttlSeconds)}.`);\n }\n}\n\n/**\n * Re-pointing one side of an existing pair is refused, in both directions: an id\n * correlated two ways is always a bug, and no later sync can untangle it —\n * whichever of the two answers a lookup happens to give, half the records it\n * touches are the wrong ones. Writing the same pair again is not a re-point and\n * is allowed, so a node that puts unconditionally on every run stays green.\n */\nexport function assertNotRepointed(namespace: string, pairs: Iterable<[string, string]>, left: string, right: string): void {\n for (const [existingLeft, existingRight] of pairs) {\n if (existingLeft === left && existingRight !== right) {\n throw new NodeError('MAPPING_CONFLICT', `'${left}' is already correlated with '${existingRight}' in namespace '${namespace}'.`);\n }\n if (existingRight === right && existingLeft !== left) {\n throw new NodeError('MAPPING_CONFLICT', `'${right}' is already correlated with '${existingLeft}' in namespace '${namespace}'.`);\n }\n }\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 ?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AACA,QAAI,WAAW,OAAO;AACpB,YAAM,OAAO,MAAM,SAA4B,GAAG;AAClD,YAAM,UAAU,MAAM,eAAe,IAAI;AAAA,QACvC,MAAM,KAAK;AAAA,QACX,MAAM,KAAK;AAAA,QACX,uBAAuB,KAAK;AAAA,QAC5B,aAAa,KAAK;AAAA,QAClB,QAAQ,KAAK;AAAA,QACb,eAAe,KAAK;AAAA,MACtB,CAAC;AACD,UAAI,CAAC,SAAS;AACZ,cAAM,IAAI,YAAY,KAAK,aAAa,EAAE,cAAc;AAAA,MAC1D;AACA,aAAO,KAAK,SAAS,KAAK,KAAK,cAAc,OAAO,CAAC;AAAA,IACvD;AACA,QAAI,WAAW,UAAU;AACvB,YAAM,eAAe,EAAE;AACvB,aAAO,KAAK,cAAc,GAAG;AAAA,IAC/B;AAAA,EACF;AAEA,OAAK,IAAI,CAAC,MAAM,iBAAiB,IAAI,CAAC,MAAM,uBAAuB,WAAW,OAAO;AACnF,WAAO,KAAK,SAAS,KAAK,KAAK,EAAE,MAAM,CAAC,EAAE,CAAC;AAAA,EAC7C;AAEA,QAAM,IAAI,YAAY,KAAK,0BAA0B,IAAI,MAAM,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE;AAC/E;;;AT3iBA,IAAM,cAAc,IAAI,IAAI,mBAAmB,aAAe;AACvD,IAAM,iBAAyB,KAAK,UAAM,8BAAa,aAAa,MAAM,CAAC,EAAE;","names":["import_node_fs","import_node_fs","import_node_path","import_node_fs","import_node_path","import_integrations_node_sdk","import_integrations_node_sdk","v","import_integrations_node_sdk","http"]}
|