{"version":3,"file":"index.mjs","names":[],"sources":["../../src/vitest/blocked-modules.ts","../../src/vitest/plugin.ts","../../src/vitest/mocks/aigateway.ts","../../src/vitest/mocks/authconnection.ts","../../src/vitest/mocks/file.ts","../../src/vitest/mocks/iconv.ts","../../src/vitest/mocks/idp.ts","../../src/vitest/mocks/logger.ts","../../src/vitest/mocks/tailordb.ts","../../src/vitest/mocks/workflow.ts","../../src/vitest/mocks/tailordb-pglite.ts","../../src/vitest/workflow-local.ts","../../src/vitest/mock-kysely.ts","../../src/vitest/pglite-kysely.ts","../../src/vitest/index.ts"],"sourcesContent":["import { getNodeBuiltinMessage, isNodeBuiltinImport } from \"#/utils/node-builtins\";\n\n/**\n * Check if a module specifier is a blocked Node.js built-in.\n * @param specifier - Module specifier to check (e.g. \"node:crypto\", \"fs\")\n * @returns Whether the specifier is blocked\n */\nexport function isBlockedModule(specifier: string): boolean {\n  return isNodeBuiltinImport(specifier);\n}\n\n/**\n * Get the error message for a blocked module import.\n * @param specifier - Module specifier that was blocked\n * @returns Error message with optional suggestion for the Web Standard API alternative\n */\nexport function getBlockedMessage(specifier: string): string {\n  return getNodeBuiltinMessage(specifier);\n}\n","import { createRequire } from \"node:module\";\nimport { dirname, isAbsolute, matchesGlob, relative, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { isBlockedModule, getBlockedMessage } from \"./blocked-modules\";\nimport type { Plugin } from \"vitest/config\";\n\nconst DEFAULT_TEST_INCLUDE = [\"**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}\"];\n\ninterface ExportSpecifierNode {\n  type?: string;\n  exported?: { name?: unknown } | null;\n}\n\ninterface ImportLikeNode {\n  type: string;\n  start: number;\n  end: number;\n  source?: { value?: unknown } | null;\n  specifiers?: ExportSpecifierNode[] | null;\n  exported?: { name?: unknown } | null;\n}\n\nconst IMPORT_LIKE_TYPES = new Set([\n  \"ImportDeclaration\",\n  \"ExportNamedDeclaration\",\n  \"ExportAllDeclaration\",\n]);\n\n// Re-export specifiers (`export { x as Y } from \"...\"`) accept any\n// `IdentifierName` for `Y` — including reserved words like `delete`. But\n// `export const Y = ...` requires a `BindingIdentifier`, which forbids\n// reserved words and the strict-mode-banned `arguments` / `eval`. Synthesizing\n// `export const delete = ...` would yield a syntax error, so we fall back to\n// plain `throw` for unsafe names.\nconst UNSAFE_BINDING_NAMES = new Set([\n  // ReservedWord (ES2022+)\n  \"break\",\n  \"case\",\n  \"catch\",\n  \"class\",\n  \"const\",\n  \"continue\",\n  \"debugger\",\n  \"default\",\n  \"delete\",\n  \"do\",\n  \"else\",\n  \"enum\",\n  \"export\",\n  \"extends\",\n  \"false\",\n  \"finally\",\n  \"for\",\n  \"function\",\n  \"if\",\n  \"import\",\n  \"in\",\n  \"instanceof\",\n  \"new\",\n  \"null\",\n  \"return\",\n  \"super\",\n  \"switch\",\n  \"this\",\n  \"throw\",\n  \"true\",\n  \"try\",\n  \"typeof\",\n  \"var\",\n  \"void\",\n  \"while\",\n  \"with\",\n  \"yield\",\n  // Strict-mode reserved (ESM is always strict)\n  \"let\",\n  \"static\",\n  \"implements\",\n  \"interface\",\n  \"package\",\n  \"private\",\n  \"protected\",\n  \"public\",\n  // Module-specific reserved\n  \"await\",\n  // Banned as binding names in strict mode\n  \"arguments\",\n  \"eval\",\n]);\n\nconst ID_START = /^[A-Za-z_$]/;\nconst ID_CONT = /^[A-Za-z0-9_$]*$/;\n\nfunction isSafeBindingName(name: string): boolean {\n  if (UNSAFE_BINDING_NAMES.has(name)) return false;\n  if (name.length === 0) return false;\n  // Restrict to ASCII identifiers — Unicode bindings are valid JS but rare\n  // for re-exports of node:* modules, and a regex over the full\n  // ID_Start/ID_Continue sets adds substantial weight for marginal gain.\n  const firstChar = name[0];\n  if (firstChar === undefined) return false;\n  return ID_START.test(firstChar) && ID_CONT.test(name.slice(1));\n}\n\nfunction buildBlockedReplacement(node: ImportLikeNode, message: string): string {\n  // JSON.stringify yields a fully-escaped string literal (including the\n  // surrounding quotes), so we don't need to manually handle backslashes,\n  // newlines, or other control characters that may appear in the message.\n  const literal = JSON.stringify(message);\n  const throwStmt = `throw new Error(${literal});`;\n  const throwExpr = `(() => { throw new Error(${literal}); })()`;\n\n  if (node.type === \"ExportNamedDeclaration\") {\n    const specs = node.specifiers ?? [];\n    const stubs: string[] = [];\n    for (const spec of specs) {\n      const exportedName = spec.exported?.name;\n      if (typeof exportedName !== \"string\") continue;\n      if (exportedName === \"default\") {\n        stubs.push(`export default ${throwExpr};`);\n        continue;\n      }\n      // Reserved words can be re-export names but not binding names.\n      // Bail to a plain throw rather than emit invalid syntax.\n      if (!isSafeBindingName(exportedName)) return throwStmt;\n      stubs.push(`export const ${exportedName} = ${throwExpr};`);\n    }\n    return stubs.length > 0 ? stubs.join(\" \") : throwStmt;\n  }\n\n  if (node.type === \"ExportAllDeclaration\") {\n    const exportedName = node.exported?.name;\n    if (typeof exportedName === \"string\" && isSafeBindingName(exportedName)) {\n      return `export const ${exportedName} = ${throwExpr};`;\n    }\n    return throwStmt;\n  }\n\n  return throwStmt;\n}\n\nconst toFileList = (value: string | string[] | undefined): string[] =>\n  Array.isArray(value) ? value : value ? [value] : [];\n\n// Vitest 5 inherits an inline project's config from its declaring config file\n// by default; Vitest 4 only does so when the project sets `extends: true`.\n// Reading the resolved peer's major lets a project that omits `extends` be\n// treated as inheriting the root environment on 5 without changing what the\n// same config resolved to on 4.\nlet cachedSupportsDefaultProjectInheritance: boolean | undefined;\nfunction supportsDefaultProjectInheritance(): boolean {\n  if (cachedSupportsDefaultProjectInheritance === undefined) {\n    try {\n      const { version } = createRequire(import.meta.url)(\"vitest/package.json\") as {\n        version: string;\n      };\n      cachedSupportsDefaultProjectInheritance = Number.parseInt(version, 10) >= 5;\n    } catch {\n      // Unresolvable peer: assume the explicit-opt-in model so a project that\n      // would not have inherited anything is never forced into tailor-runtime.\n      cachedSupportsDefaultProjectInheritance = false;\n    }\n  }\n  return cachedSupportsDefaultProjectInheritance;\n}\n\n/**\n * Vite plugin that blocks Node.js built-in module imports from production code.\n *\n * Uses the `transform` hook to walk the Rollup-provided AST of non-test source\n * files for static `node:*` imports and re-exports.\n * `ImportDeclaration` and bare `export * from \"...\"` are replaced with a\n * `throw new Error(...)` statement so the failure surfaces at evaluation time.\n * `ExportNamedDeclaration` (`export { x, y as z } from \"...\"`) and namespaced\n * `export * as ns from \"...\"` are rewritten to per-binding stub exports\n * (`export const x = (() => { throw new Error(...) })();`). The IIFE throws\n * eagerly during module evaluation (same timing as a top-level `throw`), but\n * preserving the declared export bindings ensures the surfaced error is the\n * actual \"node:* not available\" message rather than an opaque\n * \"missing export\" raised by the loader.\n * Vitest treats `node:*` as external SSR modules (skipping `resolveId`), so\n * source-level transformation is the only reliable interception point.\n * Runs in the default phase (no `enforce: \"pre\"`) so esbuild's TypeScript\n * transform strips `import type` first; only runtime imports reach this hook.\n * Node.js globals not in the platform runtime are removed by the environment (whitelist-based).\n * Test file patterns are read from the resolved Vitest config (`test.include`).\n * Vitest setup files (`test.setupFiles`) and global-setup files\n * (`test.globalSetup`) are also exempted: they run in the test runner host,\n * not in the emulated platform runtime, so they may freely use `node:*`\n * modules (e.g. `node:url` for `pathToFileURL`).\n * @returns Vite plugin\n */\nexport function createBlockPlugin(): Plugin {\n  let isTestFile: (id: string) => boolean = () => false;\n  let isUserSourceFile: (id: string) => boolean = () => false;\n\n  return {\n    name: \"tailor-runtime-block-node\",\n\n    configResolved(config) {\n      type HostFileTestConfig = {\n        include?: string[];\n        setupFiles?: string | string[];\n        globalSetup?: string | string[];\n        root?: string;\n      };\n      // Read `test` as the user-facing shape rather than Vitest's resolved\n      // config type: this hook may see the config before Vitest fills in\n      // defaults, so every field keeps its fallback.\n      const testConfig = (config as { test?: unknown }).test as\n        | (HostFileTestConfig & { projects?: { test?: HostFileTestConfig }[] })\n        | undefined;\n      const root = testConfig?.root ?? config.root;\n      // Setup files and global-setup files run in the Vitest host (not the\n      // emulated runtime), so they may freely import node:* modules. Collect\n      // them from the top-level config AND from each `test.projects[i]` —\n      // per-project setup files run in the host too and would otherwise be\n      // transformed as production code, breaking node:* imports inside them.\n      const toAbsolutePaths = (value: string | string[] | undefined, baseRoot: string) =>\n        toFileList(value).map((f) => resolve(baseRoot, f));\n      const exemptHostFiles = new Set<string>([\n        ...toAbsolutePaths(testConfig?.setupFiles, root),\n        ...toAbsolutePaths(testConfig?.globalSetup, root),\n      ]);\n      // Vitest projects can each define their own `test.include` (and root).\n      // A project that uses non-default patterns (e.g. `tests/**/*.spec.ts`)\n      // must also be considered when classifying test files — otherwise its\n      // tests would be treated as production code and have node:* imports\n      // rewritten. Build a list of (root, patterns) pairs covering top-level\n      // + every project, and accept a file if any pair matches.\n      const includePairs: { root: string; patterns: string[] }[] = [\n        { root, patterns: testConfig?.include ?? DEFAULT_TEST_INCLUDE },\n      ];\n      for (const project of testConfig?.projects ?? []) {\n        const projectTest = project.test;\n        if (!projectTest) continue;\n        const projectRoot = projectTest.root ?? root;\n        for (const f of toAbsolutePaths(projectTest.setupFiles, projectRoot)) {\n          exemptHostFiles.add(f);\n        }\n        for (const f of toAbsolutePaths(projectTest.globalSetup, projectRoot)) {\n          exemptHostFiles.add(f);\n        }\n        includePairs.push({\n          root: projectRoot,\n          patterns: projectTest.include ?? DEFAULT_TEST_INCLUDE,\n        });\n      }\n      isTestFile = (id: string) => {\n        if (exemptHostFiles.has(id)) return true;\n        return includePairs.some(({ root: r, patterns }) => {\n          const candidate = isAbsolute(id) ? relative(r, id) : id;\n          return patterns.some((pattern) => matchesGlob(candidate, pattern));\n        });\n      };\n      // Only transform files inside the project root. With pnpm workspaces,\n      // dependencies are symlinked and Vite resolves them to absolute paths\n      // outside `node_modules`, so the substring check alone is insufficient.\n      // Non-absolute ids are Vite-internal: virtual modules (`\\0...`,\n      // `virtual:...`), bare specifiers, etc. Those are never user source\n      // files and must not be parsed/transformed.\n      isUserSourceFile = (id: string) => {\n        if (!isAbsolute(id)) return false;\n        const rel = relative(root, id);\n        return rel !== \"\" && !rel.startsWith(\"..\") && !isAbsolute(rel);\n      };\n    },\n\n    transform(code, id) {\n      // Vite can pass ids with query/hash suffixes (e.g. `file.ts?import`,\n      // `file.ts?v=hash`). Strip them so exact-path lookups (Set membership,\n      // glob matching, absolute-path checks) match what callers configured.\n      const queryIdx = id.search(/[?#]/);\n      const cleanId = queryIdx === -1 ? id : id.slice(0, queryIdx);\n\n      if (isTestFile(cleanId)) return undefined;\n      if (cleanId.includes(\"node_modules\")) return undefined;\n      if (!isUserSourceFile(cleanId)) return undefined;\n\n      let ast: { body: ImportLikeNode[] };\n      try {\n        ast = this.parse(code) as unknown as { body: ImportLikeNode[] };\n      } catch {\n        // Not parseable as ESM (e.g. JSON, asset). Let other plugins handle it.\n        return undefined;\n      }\n\n      const replacements: { start: number; end: number; replacement: string }[] = [];\n      for (const node of ast.body) {\n        if (!IMPORT_LIKE_TYPES.has(node.type)) continue;\n        const specifier = node.source?.value;\n        if (typeof specifier !== \"string\") continue;\n        if (isBlockedModule(specifier)) {\n          replacements.push({\n            start: node.start,\n            end: node.end,\n            replacement: buildBlockedReplacement(node, getBlockedMessage(specifier)),\n          });\n        }\n      }\n\n      if (replacements.length === 0) return undefined;\n\n      let transformed = code;\n      for (const r of replacements.toSorted((a, b) => b.start - a.start)) {\n        transformed = transformed.slice(0, r.start) + r.replacement + transformed.slice(r.end);\n      }\n\n      return { code: transformed, map: null };\n    },\n  };\n}\n\nconst ENVIRONMENT_NAME = \"tailor-runtime\";\n\n// Channel that carries the resolved `tailor.config.ts` path to setup.ts, which\n// runs in a separate worker process. Set through Vitest's `test.env` rather\n// than `process.env` so each project carries its own value: the config hook\n// runs once per project in the same parent process, and a process-global slot\n// would let the last project resolved win for every worker. The leading `__`\n// marks it plugin-private, so overwriting a pre-existing value is safe.\nconst CONFIG_ENV_VAR = \"__TAILOR_RUNTIME_CONFIG\";\n\n// An empty value reads as \"no config\" in setup.ts and, unlike omitting the\n// key, overrides a stale value inherited from the root `test.env`.\nfunction setConfigEnv(\n  target: Record<string, unknown> & { env?: Record<string, string> },\n  configAbsPath: string,\n): void {\n  target.env = { ...target.env, [CONFIG_ENV_VAR]: configAbsPath };\n}\n\n/**\n * Vite plugin that resolves the tailor-runtime environment and injects setup files.\n *\n * Vitest resolves environments starting with \".\" or \"/\" as file paths.\n * This plugin rewrites `environment: \"tailor-runtime\"` to the absolute path\n * of the bundled environment module, both at the top-level and per-project.\n * It also injects the setup file that seeds the SecretManager mock from\n * `tailor.config.ts`.\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Vite plugin\n */\nexport function createEnvironmentPlugin(options?: { config?: string }): Plugin {\n  const currentDir = dirname(fileURLToPath(import.meta.url));\n  const environmentPath = resolve(currentDir, \"environment.mjs\");\n  const setupPath = resolve(currentDir, \"setup.mjs\");\n  // Vitest re-runs the config for inline projects that need their own Vite\n  // server, so a rewritten absolute path still counts as tailor-runtime.\n  const selectsTailorRuntime = (environment: unknown): boolean =>\n    environment === ENVIRONMENT_NAME || environment === environmentPath;\n\n  return {\n    name: \"tailor-runtime-environment\",\n\n    config(config) {\n      const testConfig = config.test as\n        | (Record<string, unknown> & {\n            projects?: (string | Record<string, unknown>)[];\n            setupFiles?: string | string[];\n            env?: Record<string, string>;\n          })\n        | undefined;\n\n      // Rewrite environment name to absolute path at top-level\n      const rootSelectsTailorRuntime = !!testConfig && selectsTailorRuntime(testConfig.environment);\n      if (testConfig && rootSelectsTailorRuntime) {\n        testConfig.environment = environmentPath;\n      }\n\n      // Rewrite in each inline project config. Since Vitest 5 inline projects\n      // no longer receive the `setupFiles` this hook returns for the root\n      // config, the setup file is added directly to whichever projects select\n      // the tailor-runtime environment — not to every project, since setup.ts\n      // statically imports \"node:url\" and would fail to even load in a\n      // project whose environment cannot resolve Node builtins (e.g. Vitest\n      // browser mode).\n      //\n      // A project that declares no `environment` of its own inherits the\n      // root's, but Vitest 5 inherits the literal name rather than the path\n      // this hook rewrote it to, so it has to be rewritten here as well —\n      // only when the project actually inherits from the root. A string\n      // `extends` points at another config file, whose environment must not\n      // be overridden here. Omitting `extends` only inherits on Vitest 5;\n      // on 4 such a project resolves independently and must be left alone.\n      if (testConfig?.projects) {\n        for (const project of testConfig.projects) {\n          if (typeof project === \"string\") continue;\n          const projectTest = (project.test ??= {}) as Record<string, unknown> & {\n            setupFiles?: string | string[];\n            env?: Record<string, string>;\n            root?: string;\n          };\n          const inheritsRootEnvironment =\n            projectTest.environment === undefined &&\n            rootSelectsTailorRuntime &&\n            (project.extends === true ||\n              (project.extends === undefined && supportsDefaultProjectInheritance()));\n          if (!inheritsRootEnvironment && !selectsTailorRuntime(projectTest.environment)) {\n            // Blank the key so a project on another environment cannot pick up\n            // the root's value through Vitest's root-into-project env merge.\n            if (options?.config) setConfigEnv(projectTest, \"\");\n            continue;\n          }\n          projectTest.environment = environmentPath;\n          const projectSetupFiles = toFileList(projectTest.setupFiles);\n          if (!projectSetupFiles.includes(setupPath)) {\n            projectTest.setupFiles = [...projectSetupFiles, setupPath];\n          }\n          if (options?.config) {\n            // A project may set its own `root`, so a relative options.config\n            // resolves per project rather than once against the root config.\n            const projectRoot =\n              (project.root as string | undefined) ??\n              projectTest.root ??\n              config.root ??\n              process.cwd();\n            setConfigEnv(projectTest, resolve(projectRoot, options.config));\n          }\n        }\n      }\n\n      // Seed the config path for setup.ts, which reads it in the worker. Each\n      // tailor-runtime project already carries its own value from the loop\n      // above; this covers a root config that selects tailor-runtime itself,\n      // including the standalone (no `projects`) case.\n      if (options?.config && testConfig) {\n        // Resolve against the user-provided Vite root when present (falling\n        // back to cwd). Vitest projects with a non-cwd `root` would otherwise\n        // resolve a relative options.config against the wrong directory.\n        const configRoot = (testConfig.root as string | undefined) ?? config.root ?? process.cwd();\n        setConfigEnv(\n          testConfig,\n          rootSelectsTailorRuntime ? resolve(configRoot, options.config) : \"\",\n        );\n      }\n\n      // Normalize a user-provided string `setupFiles` into an array so Vite's\n      // array-concat merge sees both sides as arrays (the string form would\n      // otherwise be replaced rather than concatenated by some merge paths).\n      // Vite then concatenates the user's array with our [setupPath].\n      const rootSetupFiles = toFileList(testConfig?.setupFiles);\n      if (testConfig && typeof testConfig.setupFiles === \"string\") {\n        testConfig.setupFiles = rootSetupFiles;\n      }\n\n      // A re-run for an inline project already carries the setup file added\n      // in the first pass; returning it again would register it twice. This\n      // merges into the root-level test config only (nested projects were\n      // already handled above), so it stays gated on the root's own\n      // environment selection — an unconditional return here would force\n      // setup.ts (and its static \"node:url\" import) onto a root/standalone\n      // config whose environment cannot resolve Node builtins.\n      if (!rootSelectsTailorRuntime || rootSetupFiles.includes(setupPath)) return {};\n      return {\n        test: {\n          setupFiles: [setupPath],\n        },\n      };\n    },\n  };\n}\n","import { vi } from \"vitest\";\nimport { tailorRoot, withDispose } from \"./shared\";\nimport type { AIGatewayName } from \"@tailor-platform/sdk\";\n\ninterface AigatewayCall {\n  name: AIGatewayName;\n}\n\n/** Initial fixtures for an AI Gateway mock. */\nexport interface MockAigatewayOptions {\n  /** AI Gateway URLs available when the mock is acquired. */\n  urls?: Partial<Record<AIGatewayName, string>>;\n}\n\n// ---------------------------------------------------------------------------\n// AI Gateway Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for `tailor.aigateway`. Restored on dispose.\n * @param options - Initial AI Gateway URL fixtures\n * @returns Disposable AI Gateway mock control object\n * @example\n * ```typescript\n * import { mockAigateway } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"resolves an AI Gateway URL\", async () => {\n *   using aigateway = mockAigateway({\n *     urls: { \"my-aigateway\": \"https://my-aigateway.example.com\" },\n *   });\n *   aigateway.setUrl(\"my-aigateway\", \"https://replacement.example.com\");\n *   // …\n * });\n * ```\n */\nexport function mockAigateway(options: MockAigatewayOptions = {}) {\n  const root = tailorRoot();\n  const prev = root.aigateway;\n\n  let urls: Partial<Record<AIGatewayName, string>> = { ...options.urls };\n\n  async function defaultGet(name: AIGatewayName): Promise<{ url: string }> {\n    const url = urls[name];\n    if (url === undefined) {\n      throw new Error(\n        `No AI Gateway registered for \"${name}\". Acquire mockAigateway() and call setUrls(...).`,\n      );\n    }\n    return { url };\n  }\n\n  const get = vi.fn(defaultGet);\n\n  root.aigateway = { get };\n\n  const facade = {\n    /** The `get` `vi.fn`. */\n    get,\n\n    setUrls(value: Partial<Record<AIGatewayName, string>>): void {\n      urls = value;\n    },\n\n    setUrl(name: AIGatewayName, url: string): void {\n      urls = { ...urls, [name]: url };\n    },\n\n    get calls(): AigatewayCall[] {\n      return get.mock.calls.map(([name]) => ({ name }));\n    },\n\n    clear(): void {\n      get.mockClear();\n    },\n\n    reset(): void {\n      urls = {};\n      get.mockReset();\n      get.mockImplementation(defaultGet);\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.aigateway = prev;\n  });\n}\n","import { vi } from \"vitest\";\nimport { tailorRoot, withDispose } from \"./shared\";\n// Import from the public entry (not `#/configure/...`) so this d.ts references\n// `@tailor-platform/sdk` externally instead of inlining the registry — the same\n// generated `declare module \"@tailor-platform/sdk\"` that narrows\n// `authconnection.getConnectionToken` then also narrows this mock's API.\nimport type { AuthConnectionTokenResult, ConnectionName } from \"@tailor-platform/sdk\";\n\ninterface AuthConnectionCall {\n  connectionName: ConnectionName;\n}\n\n/** Initial fixtures and fallback behavior for an AuthConnection mock. */\nexport interface MockAuthconnectionOptions {\n  /** Tokens available when the mock is acquired. */\n  tokens?: Partial<Record<ConnectionName, AuthConnectionTokenResult>>;\n  /** Return a placeholder token or throw when a connection has no configured token. */\n  onUnhandled?: \"fallback\" | \"error\";\n}\n\n// ---------------------------------------------------------------------------\n// AuthConnection Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for `tailor.authconnection`. Restored on dispose.\n * @param options - Initial token fixtures and fallback behavior\n * @returns Disposable AuthConnection mock control object\n * @example\n * ```typescript\n * import { mockAuthconnection } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"returns configured token\", async () => {\n *   using ac = mockAuthconnection({ tokens: { google: { access_token: \"ya29.xxx\" } } });\n *   ac.setToken(\"google\", { access_token: \"replacement\" });\n *   // …\n * });\n * ```\n */\nexport function mockAuthconnection(options: MockAuthconnectionOptions = {}) {\n  const root = tailorRoot();\n  const prev = root.authconnection;\n\n  let tokens: Partial<Record<ConnectionName, AuthConnectionTokenResult>> = {\n    ...options.tokens,\n  };\n\n  async function defaultGetConnectionToken(\n    connectionName: ConnectionName,\n  ): Promise<AuthConnectionTokenResult> {\n    const token = tokens[connectionName];\n    if (token) return token;\n    if (options.onUnhandled === \"error\") {\n      throw new Error(`No AuthConnection token configured for \"${connectionName}\"`);\n    }\n    return { access_token: \"mock-token\" };\n  }\n\n  const getConnectionToken = vi.fn(defaultGetConnectionToken);\n\n  root.authconnection = { getConnectionToken };\n\n  const facade = {\n    /** The `getConnectionToken` `vi.fn`. */\n    getConnectionToken,\n\n    setTokens(value: Partial<Record<ConnectionName, AuthConnectionTokenResult>>): void {\n      tokens = value;\n    },\n\n    setToken(connectionName: ConnectionName, token: AuthConnectionTokenResult): void {\n      tokens = { ...tokens, [connectionName]: token };\n    },\n\n    get calls(): AuthConnectionCall[] {\n      return getConnectionToken.mock.calls.map(([connectionName]) => ({\n        connectionName,\n      }));\n    },\n\n    clear(): void {\n      getConnectionToken.mockClear();\n    },\n\n    reset(): void {\n      tokens = {};\n      getConnectionToken.mockReset();\n      getConnectionToken.mockImplementation(defaultGetConnectionToken);\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.authconnection = prev;\n  });\n}\n","import { type Mock, vi } from \"vitest\";\nimport { tailordbRoot, withDispose } from \"./shared\";\nimport type {\n  FileDownloadAsBase64Response,\n  FileDownloadResponse,\n  FileDownloadStreamResponse,\n  FileMetadata,\n  FileUploadResponse,\n  TailorDBFileAPI,\n} from \"../../runtime/file\";\n\ntype FileMethod = keyof TailorDBFileAPI;\ntype FileResolver = (method: string, call: FileCall) => unknown;\n\ninterface FileCall {\n  method: string;\n  namespace: string;\n  tableName: string;\n  fieldName: string;\n  recordId: string;\n}\n\n/** Controls fallback behavior for File calls without a configured result. */\nexport interface MockFileOptions {\n  /** Return a type-compatible fixture or throw when no behavior is configured. */\n  onUnhandled?: \"fallback\" | \"error\";\n}\n\ntype FileMocks = {\n  [Method in FileMethod]: Mock<TailorDBFileAPI[Method]>;\n};\n\nconst FILE_METHODS = [\n  \"upload\",\n  \"download\",\n  \"downloadAsBase64\",\n  \"delete\",\n  \"getMetadata\",\n  \"downloadStream\",\n  \"uploadStream\",\n] as const satisfies readonly FileMethod[];\n\nconst FILE_DEFAULTS: Partial<Record<FileMethod, unknown>> = {\n  upload: { metadata: { fileSize: 0, sha256sum: \"\" } },\n  download: {\n    data: new Uint8Array(),\n    metadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", lastUploadedAt: \"\" },\n  },\n  downloadAsBase64: {\n    data: \"\",\n    metadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", lastUploadedAt: \"\" },\n  },\n  getMetadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", urlPath: \"\" },\n  downloadStream: null,\n  uploadStream: { metadata: { fileSize: 0, sha256sum: \"\" } },\n};\n\n/**\n * Acquire a disposable mock for `tailordb.file`. Restored on dispose.\n * @param options - Controls behavior for calls without a configured result\n * @returns Disposable File mock control object\n * @example\n * ```typescript\n * import { mockFile } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"mock file download\", async () => {\n *   using file = mockFile();\n *   file.download.mockResolvedValue({ data: new Uint8Array(), metadata: { ... } });\n *   // …\n * });\n * ```\n */\nexport function mockFile(options: MockFileOptions = {}) {\n  const root = tailordbRoot();\n  const prev = root.file;\n  const { onUnhandled = \"fallback\" } = options;\n\n  const queue: unknown[] = [];\n  const calls: FileCall[] = [];\n  let resolver: FileResolver = () => null;\n\n  function handle(\n    method: FileMethod,\n    namespace: string,\n    tableName: string,\n    fieldName: string,\n    recordId: string,\n  ): unknown {\n    if (queue.length > 0) return queue.shift();\n    const call: FileCall = { method, namespace, tableName, fieldName, recordId };\n    const resolved = resolver(method, call);\n    if (resolved != null) return resolved;\n    if (onUnhandled === \"error\") {\n      throw new Error(`No File mock configured for \"${method}\"`);\n    }\n    const fallback = FILE_DEFAULTS[method];\n    return fallback === undefined ? undefined : structuredClone(fallback);\n  }\n\n  const upload = vi.fn<TailorDBFileAPI[\"upload\"]>(async (...args) => {\n    const [namespace, tableName, fieldName, recordId] = args;\n    return handle(\"upload\", namespace, tableName, fieldName, recordId) as FileUploadResponse;\n  });\n  const download = vi.fn<TailorDBFileAPI[\"download\"]>(\n    async (...args) => handle(\"download\", ...args) as FileDownloadResponse,\n  );\n  const downloadAsBase64 = vi.fn<TailorDBFileAPI[\"downloadAsBase64\"]>(\n    async (...args) => handle(\"downloadAsBase64\", ...args) as FileDownloadAsBase64Response,\n  );\n  const deleteFile = vi.fn<TailorDBFileAPI[\"delete\"]>(async (...args) => {\n    handle(\"delete\", ...args);\n  });\n  const getMetadata = vi.fn<TailorDBFileAPI[\"getMetadata\"]>(\n    async (...args) => handle(\"getMetadata\", ...args) as FileMetadata,\n  );\n  const downloadStream = vi.fn<TailorDBFileAPI[\"downloadStream\"]>(async (...args) => {\n    const resolved = handle(\"downloadStream\", ...args);\n    if (resolved != null) return resolved as FileDownloadStreamResponse;\n    return {\n      body: new ReadableStream({\n        start(controller) {\n          controller.close();\n        },\n      }),\n      metadata: { contentType: \"\", fileSize: 0, sha256sum: \"\", lastUploadedAt: \"\" },\n    };\n  });\n  const uploadStream = vi.fn<TailorDBFileAPI[\"uploadStream\"]>(async (...args) => {\n    const [namespace, tableName, fieldName, recordId] = args;\n    return handle(\"uploadStream\", namespace, tableName, fieldName, recordId) as FileUploadResponse;\n  });\n\n  const mocks: FileMocks = {\n    upload,\n    download,\n    downloadAsBase64,\n    delete: deleteFile,\n    getMetadata,\n    downloadStream,\n    uploadStream,\n  };\n\n  function track<Method extends FileMethod>(\n    method: Method,\n    operation: TailorDBFileAPI[Method],\n  ): TailorDBFileAPI[Method] {\n    return function (this: unknown, ...args: Parameters<TailorDBFileAPI[Method]>) {\n      calls.push({\n        method,\n        namespace: args[0],\n        tableName: args[1],\n        fieldName: args[2],\n        recordId: args[3],\n      });\n      return (\n        operation as (\n          ...call: Parameters<TailorDBFileAPI[Method]>\n        ) => ReturnType<TailorDBFileAPI[Method]>\n      ).apply(this, args);\n    } as TailorDBFileAPI[Method];\n  }\n\n  root.file = {\n    upload: track(\"upload\", upload),\n    download: track(\"download\", download),\n    downloadAsBase64: track(\"downloadAsBase64\", downloadAsBase64),\n    delete: track(\"delete\", deleteFile),\n    getMetadata: track(\"getMetadata\", getMetadata),\n    downloadStream: track(\"downloadStream\", downloadStream),\n    uploadStream: track(\"uploadStream\", uploadStream),\n  };\n\n  function allMocks(): Mock[] {\n    return FILE_METHODS.map((method) => mocks[method] as Mock);\n  }\n\n  const facade = {\n    ...mocks,\n\n    setResolver(value: FileResolver): void {\n      resolver = value;\n    },\n\n    /**\n     * Enqueue a single result for the next `tailordb.file` call.\n     * The queue is shared across all methods and namespaces.\n     * @param result - Result to return from the next file call\n     */\n    enqueueResult(result: unknown): void {\n      queue.push(result);\n    },\n\n    /**\n     * Enqueue results for multiple subsequent `tailordb.file` calls.\n     * The queue is shared across all methods and namespaces.\n     * @param results - Results to enqueue, one per upcoming call\n     */\n    enqueueResults(...results: unknown[]): void {\n      queue.push(...results);\n    },\n\n    get calls(): FileCall[] {\n      return calls;\n    },\n\n    clear(): void {\n      calls.length = 0;\n      for (const mock of allMocks()) mock.mockClear();\n    },\n\n    reset(): void {\n      queue.length = 0;\n      calls.length = 0;\n      resolver = () => null;\n      for (const mock of allMocks()) mock.mockReset();\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.file = prev;\n  });\n}\n","import { type MockInstance, vi } from \"vitest\";\nimport { tailorRoot, withDispose } from \"./shared\";\nimport type { TailorIconvAPI } from \"#/runtime/iconv\";\n\ntype IconvResolver = (method: string, args: unknown[]) => unknown;\ntype IconvMethod = \"convert\" | \"convertBuffer\" | \"decode\" | \"encode\" | \"encodings\";\n\ninterface IconvCall {\n  method: IconvMethod;\n  args: unknown[];\n}\n\ntype ConversionResult = string | Uint8Array;\ntype ConvertMockProcedure = (\n  input: string | Uint8Array | ArrayBuffer,\n  fromEncoding: string,\n  toEncoding: string,\n) => ConversionResult;\ntype ConvertBufferMockProcedure = (\n  input: Uint8Array | ArrayBuffer,\n  fromEncoding: string,\n  toEncoding: string,\n) => ConversionResult;\ntype EncodeMockProcedure = (input: string, encoding: string) => ConversionResult;\ntype TypedOperationMock<\n  RuntimeProcedure,\n  MockProcedure extends (...args: never[]) => unknown,\n> = RuntimeProcedure & MockInstance<MockProcedure>;\n\n/** Controls how unconfigured Iconv operations are handled. */\nexport interface MockIconvOptions {\n  /** Return an empty type-compatible value or throw when no behavior is configured. */\n  onUnhandled?: \"fallback\" | \"error\";\n}\n\n// ---------------------------------------------------------------------------\n// Iconv Mock\n// ---------------------------------------------------------------------------\n\nfunction isUtf8(encoding: unknown): boolean {\n  return encoding === \"UTF8\" || encoding === \"UTF-8\";\n}\n\nfunction defaultIconvResult(method: IconvMethod, args: unknown[]): unknown {\n  switch (method) {\n    case \"convert\":\n    case \"convertBuffer\":\n      return isUtf8(args[2]) ? \"\" : new Uint8Array();\n    case \"decode\":\n      return \"\";\n    case \"encode\":\n      return isUtf8(args[1]) ? \"\" : new Uint8Array();\n    case \"encodings\":\n      return [];\n  }\n}\n\n/**\n * Acquire a disposable mock for `tailor.iconv`. Restored on dispose.\n * @param options - Fallback behavior for unconfigured operations\n * @returns Disposable Iconv mock control object\n * @example\n * ```typescript\n * import { mockIconv } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"mock encoding conversion\", () => {\n *   using iconv = mockIconv();\n *   iconv.decode.mockReturnValue(\"decoded-text\");\n *   // …\n * });\n * ```\n */\nexport function mockIconv(options: MockIconvOptions = {}) {\n  const root = tailorRoot();\n  const prev = root.iconv;\n\n  let resolver: IconvResolver | null = null;\n  const calls: IconvCall[] = [];\n\n  function resolve(method: IconvMethod, args: unknown[]): unknown {\n    if (resolver) {\n      const result = resolver(method, args);\n      if (result != null) return result;\n    }\n    if (options.onUnhandled === \"error\") {\n      throw new Error(`No Iconv mock behavior configured for \"${method}\"`);\n    }\n    return defaultIconvResult(method, args);\n  }\n\n  function defaultConvert<T extends string>(\n    input: string | Uint8Array | ArrayBuffer,\n    fromEncoding: string,\n    toEncoding: T,\n  ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array {\n    return resolve(\"convert\", [input, fromEncoding, toEncoding]) as T extends \"UTF8\" | \"UTF-8\"\n      ? string\n      : Uint8Array;\n  }\n\n  function defaultConvertBuffer<T extends string>(\n    input: Uint8Array | ArrayBuffer,\n    fromEncoding: string,\n    toEncoding: T,\n  ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array {\n    return resolve(\"convertBuffer\", [input, fromEncoding, toEncoding]) as T extends \"UTF8\" | \"UTF-8\"\n      ? string\n      : Uint8Array;\n  }\n\n  function defaultDecode(input: Uint8Array | ArrayBuffer, encoding: string): string {\n    return resolve(\"decode\", [input, encoding]) as string;\n  }\n\n  function defaultEncode<T extends string>(\n    input: string,\n    encoding: T,\n  ): T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array {\n    return resolve(\"encode\", [input, encoding]) as T extends \"UTF8\" | \"UTF-8\" ? string : Uint8Array;\n  }\n\n  function defaultEncodings(): string[] {\n    return resolve(\"encodings\", []) as string[];\n  }\n\n  const convert = vi.fn(defaultConvert) as TypedOperationMock<\n    TailorIconvAPI[\"convert\"],\n    ConvertMockProcedure\n  >;\n  const convertBuffer = vi.fn(defaultConvertBuffer) as TypedOperationMock<\n    TailorIconvAPI[\"convertBuffer\"],\n    ConvertBufferMockProcedure\n  >;\n  const decode = vi.fn(defaultDecode);\n  const encode = vi.fn(defaultEncode) as TypedOperationMock<\n    TailorIconvAPI[\"encode\"],\n    EncodeMockProcedure\n  >;\n  const encodings = vi.fn(defaultEncodings);\n\n  function track<Method extends IconvMethod>(\n    method: Method,\n    operation: TailorIconvAPI[Method],\n  ): TailorIconvAPI[Method] {\n    return function (this: unknown, ...args: Parameters<TailorIconvAPI[Method]>) {\n      calls.push({ method, args: [...args] });\n      return (\n        operation as (\n          ...call: Parameters<TailorIconvAPI[Method]>\n        ) => ReturnType<TailorIconvAPI[Method]>\n      ).apply(this, args);\n    } as TailorIconvAPI[Method];\n  }\n\n  const trackedConvert = track(\"convert\", convert);\n  const trackedConvertBuffer = track(\"convertBuffer\", convertBuffer);\n  const trackedDecode = track(\"decode\", decode);\n  const trackedEncode = track(\"encode\", encode);\n  const trackedEncodings = track(\"encodings\", encodings);\n\n  class MockIconv {\n    #fromEncoding: string;\n    #toEncoding: string;\n\n    constructor(fromEncoding: string, toEncoding: string) {\n      this.#fromEncoding = fromEncoding;\n      this.#toEncoding = toEncoding;\n    }\n\n    convert(input: string | Uint8Array | ArrayBuffer): string | Uint8Array {\n      return trackedConvert.call(this, input, this.#fromEncoding, this.#toEncoding);\n    }\n  }\n\n  const iconv: TailorIconvAPI = {\n    convert: trackedConvert,\n    convertBuffer: trackedConvertBuffer,\n    decode: trackedDecode,\n    encode: trackedEncode,\n    encodings: trackedEncodings,\n    Iconv: MockIconv,\n  };\n  root.iconv = iconv;\n\n  function clear(): void {\n    calls.length = 0;\n    convert.mockClear();\n    convertBuffer.mockClear();\n    decode.mockClear();\n    encode.mockClear();\n    encodings.mockClear();\n  }\n\n  const facade = {\n    /** The `convert` `vi.fn`. */\n    convert,\n    /** The `convertBuffer` `vi.fn`. */\n    convertBuffer,\n    /** The `decode` `vi.fn`. */\n    decode,\n    /** The `encode` `vi.fn`. */\n    encode,\n    /** The `encodings` `vi.fn`. */\n    encodings,\n\n    setResolver(value: IconvResolver): void {\n      resolver = value;\n    },\n\n    get calls(): IconvCall[] {\n      return calls;\n    },\n\n    clear,\n\n    reset(): void {\n      resolver = null;\n      calls.length = 0;\n      convert.mockReset();\n      convert.mockImplementation(defaultConvert);\n      convertBuffer.mockReset();\n      convertBuffer.mockImplementation(defaultConvertBuffer);\n      decode.mockReset();\n      decode.mockImplementation(defaultDecode);\n      encode.mockReset();\n      encode.mockImplementation(defaultEncode);\n      encodings.mockReset();\n      encodings.mockImplementation(defaultEncodings);\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.iconv = prev;\n  });\n}\n","import { type Mock, vi } from \"vitest\";\nimport { tailorRoot, withDispose } from \"./shared\";\nimport type { ClientConfig, IdpClientConstructor, IdpClientInstance } from \"../../runtime/idp\";\n\ntype IdpMethod = keyof IdpClientInstance;\ntype IdpResult<Method extends IdpMethod> = Awaited<ReturnType<IdpClientInstance[Method]>>;\ntype IdpResolver = (method: string, args: unknown[], namespace: string) => unknown;\n\ninterface IdpCall {\n  method: string;\n  args: unknown[];\n  namespace: string;\n}\n\n/** Controls fallback behavior for IdP calls without a configured result. */\nexport interface MockIdpOptions {\n  /** Return a type-compatible fixture or throw when no behavior is configured. */\n  onUnhandled?: \"fallback\" | \"error\";\n}\n\ntype IdpNamespaceMocks = {\n  [Method in IdpMethod]: Mock<IdpClientInstance[Method]>;\n};\n\nconst IDP_METHODS = [\n  \"users\",\n  \"user\",\n  \"userByName\",\n  \"createUser\",\n  \"updateUser\",\n  \"deleteUser\",\n  \"sendPasswordResetEmail\",\n  \"unenrollMfa\",\n] as const satisfies readonly IdpMethod[];\n\nconst IDP_USER_DEFAULT = {\n  id: \"mock-id\",\n  name: \"mock-user\",\n  disabled: false,\n  mfaEnrolled: false,\n  mfaFactorIds: [],\n};\n\nconst IDP_DEFAULTS: Record<IdpMethod, unknown> = {\n  users: { users: [], nextPageToken: null, totalCount: 0 },\n  user: IDP_USER_DEFAULT,\n  userByName: IDP_USER_DEFAULT,\n  createUser: IDP_USER_DEFAULT,\n  updateUser: IDP_USER_DEFAULT,\n  deleteUser: true,\n  sendPasswordResetEmail: true,\n  unenrollMfa: true,\n};\n\n/**\n * Acquire a disposable mock for `tailor.idp`. Restored on dispose.\n * @param options - Controls behavior for calls without a configured result\n * @returns Disposable IDP mock control object\n * @example\n * ```typescript\n * import { mockIdp } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"returns a user\", async () => {\n *   using idp = mockIdp();\n *   idp.namespace(\"my-idp\").user.mockResolvedValue({\n *     id: \"u-1\",\n *     name: \"alice\",\n *     disabled: false,\n *     mfaEnrolled: false,\n *     mfaFactorIds: [],\n *   });\n *   // …\n * });\n * ```\n */\nexport function mockIdp(options: MockIdpOptions = {}) {\n  const root = tailorRoot();\n  const prev = root.idp;\n  const { onUnhandled = \"fallback\" } = options;\n\n  const queue: unknown[] = [];\n  const calls: IdpCall[] = [];\n  let resolver: IdpResolver = () => null;\n  const namespaces = new Map<string, IdpNamespaceMocks>();\n\n  function compatibilityArgs(method: IdpMethod, args: unknown[]): unknown[] {\n    return method === \"users\" && args.length === 0 ? [undefined] : args;\n  }\n\n  function handle<Method extends IdpMethod>(\n    method: Method,\n    args: unknown[],\n    namespace: string,\n  ): IdpResult<Method> {\n    if (queue.length > 0) return queue.shift() as IdpResult<Method>;\n    const resolved = resolver(method, compatibilityArgs(method, args), namespace);\n    if (resolved != null) return resolved as IdpResult<Method>;\n    if (onUnhandled === \"error\") {\n      throw new Error(`No IdP mock configured for \"${namespace}.${method}\"`);\n    }\n    return structuredClone(IDP_DEFAULTS[method]) as IdpResult<Method>;\n  }\n\n  function createNamespaceMocks(namespace: string): IdpNamespaceMocks {\n    return {\n      users: vi.fn<IdpClientInstance[\"users\"]>(async (...args) => handle(\"users\", args, namespace)),\n      user: vi.fn<IdpClientInstance[\"user\"]>(async (...args) => handle(\"user\", args, namespace)),\n      userByName: vi.fn<IdpClientInstance[\"userByName\"]>(async (...args) =>\n        handle(\"userByName\", args, namespace),\n      ),\n      createUser: vi.fn<IdpClientInstance[\"createUser\"]>(async (...args) =>\n        handle(\"createUser\", args, namespace),\n      ),\n      updateUser: vi.fn<IdpClientInstance[\"updateUser\"]>(async (...args) =>\n        handle(\"updateUser\", args, namespace),\n      ),\n      deleteUser: vi.fn<IdpClientInstance[\"deleteUser\"]>(async (...args) =>\n        handle(\"deleteUser\", args, namespace),\n      ),\n      sendPasswordResetEmail: vi.fn<IdpClientInstance[\"sendPasswordResetEmail\"]>(async (...args) =>\n        handle(\"sendPasswordResetEmail\", args, namespace),\n      ),\n      unenrollMfa: vi.fn<IdpClientInstance[\"unenrollMfa\"]>(async (...args) =>\n        handle(\"unenrollMfa\", args, namespace),\n      ),\n    };\n  }\n\n  function namespace(name: string): IdpNamespaceMocks {\n    const existing = namespaces.get(name);\n    if (existing) return existing;\n    const mocks = createNamespaceMocks(name);\n    namespaces.set(name, mocks);\n    return mocks;\n  }\n\n  function track<Method extends IdpMethod>(\n    method: Method,\n    mock: IdpNamespaceMocks[Method],\n    namespaceName: string,\n  ): IdpClientInstance[Method] {\n    return function (this: unknown, ...args: Parameters<IdpClientInstance[Method]>) {\n      calls.push({\n        method,\n        args: [...compatibilityArgs(method, args)],\n        namespace: namespaceName,\n      });\n      return (\n        mock as unknown as (\n          ...call: Parameters<IdpClientInstance[Method]>\n        ) => ReturnType<IdpClientInstance[Method]>\n      ).apply(this, args);\n    } as IdpClientInstance[Method];\n  }\n\n  const defaultClient = function (this: IdpClientInstance, config: ClientConfig) {\n    const mocks = namespace(config.namespace);\n    this.users = track(\"users\", mocks.users, config.namespace);\n    this.user = track(\"user\", mocks.user, config.namespace);\n    this.userByName = track(\"userByName\", mocks.userByName, config.namespace);\n    this.createUser = track(\"createUser\", mocks.createUser, config.namespace);\n    this.updateUser = track(\"updateUser\", mocks.updateUser, config.namespace);\n    this.deleteUser = track(\"deleteUser\", mocks.deleteUser, config.namespace);\n    this.sendPasswordResetEmail = track(\n      \"sendPasswordResetEmail\",\n      mocks.sendPasswordResetEmail,\n      config.namespace,\n    );\n    this.unenrollMfa = track(\"unenrollMfa\", mocks.unenrollMfa, config.namespace);\n  };\n  const Client = vi.fn(defaultClient) as unknown as Mock<IdpClientConstructor>;\n\n  root.idp = { Client };\n\n  function allMocks(): Mock[] {\n    return [...namespaces.values()].flatMap((mocks) =>\n      IDP_METHODS.map((method) => mocks[method] as Mock),\n    );\n  }\n\n  const facade = {\n    /** The mock IDP `Client` constructor (`vi.fn`). */\n    Client,\n\n    namespace,\n\n    setResolver(value: IdpResolver): void {\n      resolver = value;\n    },\n\n    /**\n     * Enqueue a single result for the next IDP call.\n     * The queue is shared across all methods and namespaces.\n     * @param result - Result to return from the next IDP call\n     */\n    enqueueResult(result: unknown): void {\n      queue.push(result);\n    },\n\n    /**\n     * Enqueue results for multiple subsequent IDP calls.\n     * The queue is shared across all methods and namespaces.\n     * @param results - Results to enqueue, one per upcoming call\n     */\n    enqueueResults(...results: unknown[]): void {\n      queue.push(...results);\n    },\n\n    get calls(): IdpCall[] {\n      return calls;\n    },\n\n    clear(): void {\n      calls.length = 0;\n      Client.mockClear();\n      for (const mock of allMocks()) mock.mockClear();\n    },\n\n    reset(): void {\n      queue.length = 0;\n      calls.length = 0;\n      resolver = () => null;\n      Client.mockReset();\n      Client.mockImplementation(defaultClient);\n      for (const mock of allMocks()) mock.mockReset();\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.idp = prev;\n  });\n}\n","import { vi } from \"vitest\";\nimport { tailorRoot, withDispose } from \"./shared\";\nimport type { LogAttributes } from \"#/runtime/logger\";\n\ntype LogSeverity = \"debug\" | \"info\" | \"warn\" | \"error\";\n\n/** A recorded `debug`/`info`/`warn`/`error` call. */\ninterface LogCall {\n  severity: LogSeverity;\n  message: string;\n  attributes?: LogAttributes;\n}\n\n/** Initial fixtures for a logger mock. */\n// eslint-disable-next-line @typescript-eslint/no-empty-object-type\nexport interface MockLoggerOptions {}\n\n// ---------------------------------------------------------------------------\n// Logger Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for `tailor.logger`. Each method is a `vi.fn`, so\n * calls can be asserted directly; `calls` returns the `debug`/`info`/`warn`/\n * `error` entries in the order they were emitted. Restored on dispose.\n * @param _options - Reserved for future initial fixtures\n * @returns Disposable logger mock control object\n * @example\n * ```typescript\n * import { mockLogger } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"logs the processed order\", () => {\n *   using logger = mockLogger();\n *   // …run code that calls tailor.logger.info…\n *   expect(logger.info).toHaveBeenCalledWith(\"order processed\", { orderId: \"o-1\" });\n * });\n * ```\n */\nexport function mockLogger(_options: MockLoggerOptions = {}) {\n  const root = tailorRoot();\n  const prev = root.logger;\n\n  const debug = vi.fn((_message: string, _attributes?: LogAttributes): void => {});\n  const info = vi.fn((_message: string, _attributes?: LogAttributes): void => {});\n  const warn = vi.fn((_message: string, _attributes?: LogAttributes): void => {});\n  const error = vi.fn((_message: string, _attributes?: LogAttributes): void => {});\n  const setAttributes = vi.fn((_attributes: LogAttributes): void => {});\n\n  root.logger = { debug, info, warn, error, setAttributes };\n\n  const severityFns: Record<LogSeverity, typeof debug> = { debug, info, warn, error };\n\n  const facade = {\n    /** The `debug` `vi.fn`. */\n    debug,\n    /** The `info` `vi.fn`. */\n    info,\n    /** The `warn` `vi.fn`. */\n    warn,\n    /** The `error` `vi.fn`. */\n    error,\n    /** The `setAttributes` `vi.fn`. */\n    setAttributes,\n\n    get calls(): LogCall[] {\n      // Merge all severities back into chronological order via vi.fn's global\n      // invocationCallOrder, so a test mixing severities sees them in the order\n      // they actually ran (not grouped by method).\n      const entries = (Object.entries(severityFns) as [LogSeverity, typeof debug][]).flatMap(\n        ([severity, fn]) =>\n          fn.mock.calls.map((args, i) => ({\n            order: fn.mock.invocationCallOrder[i] ?? 0,\n            call: { severity, message: args[0], attributes: args[1] },\n          })),\n      );\n      return entries.toSorted((a, b) => a.order - b.order).map((e) => e.call);\n    },\n\n    clear(): void {\n      debug.mockClear();\n      info.mockClear();\n      warn.mockClear();\n      error.mockClear();\n      setAttributes.mockClear();\n    },\n\n    reset(): void {\n      debug.mockReset();\n      info.mockReset();\n      warn.mockReset();\n      error.mockReset();\n      setAttributes.mockReset();\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.logger = prev;\n  });\n}\n","import { isEqual } from \"es-toolkit\";\nimport { vi } from \"vitest\";\nimport { tailordbRoot, withDispose } from \"./shared\";\n\ntype QueryResolver = (query: string, params: unknown[]) => unknown[] | undefined;\n\n/** Controls how unmatched TailorDB queries are handled. */\nexport interface MockTailordbOptions {\n  /** Return an empty result or throw when no configured query behavior matches. */\n  onUnhandled?: \"fallback\" | \"error\";\n}\n\n/** Matches a TailorDB query by SQL text and optionally by parameters. */\nexport interface QueryMatch {\n  /** Exact SQL text or regular expression to match. */\n  sql: string | RegExp;\n  /** Exact parameters or a predicate for parameter matching. */\n  params?: readonly unknown[] | ((params: unknown[]) => boolean);\n}\n\n/** Selects TailorDB queries that receive a configured response. */\nexport type QueryMatcher =\n  | string\n  | RegExp\n  | QueryMatch\n  | ((query: string, params: unknown[]) => boolean);\n\n/** Configures persistent and one-time responses for matched queries. */\nexport interface QueryBehavior<Row> {\n  /** Return these rows for every matching query after one-time responses are consumed. */\n  returnsRows(rows: Row[]): QueryBehavior<Row>;\n  /** Return these rows for the next matching query. */\n  returnsRowsOnce(rows: Row[]): QueryBehavior<Row>;\n  /** Reject every matching query after one-time responses are consumed. */\n  rejects(error: unknown): QueryBehavior<Row>;\n  /** Reject the next matching query. */\n  rejectsOnce(error: unknown): QueryBehavior<Row>;\n}\n\ninterface ExecutedQuery {\n  query: string;\n  params: unknown[];\n}\n\ninterface CreatedClient {\n  namespace: string | undefined;\n  ended: boolean;\n}\n\ntype QueryResponse = { type: \"rows\"; rows: unknown[] } | { type: \"error\"; error: unknown };\n\ninterface QueryRule {\n  matcher: QueryMatcher;\n  once: QueryResponse[];\n  fallback?: QueryResponse;\n}\n\nfunction testRegex(regex: RegExp, value: string): boolean {\n  const lastIndex = regex.lastIndex;\n  regex.lastIndex = 0;\n  try {\n    return regex.test(value);\n  } finally {\n    regex.lastIndex = lastIndex;\n  }\n}\n\nclass MockQueryResult {\n  command: string;\n  rowCount: number;\n  rows: unknown[];\n\n  constructor(rows: unknown[]) {\n    this.command = \"\";\n    this.rowCount = rows.length;\n    this.rows = rows;\n  }\n}\n\n// ---------------------------------------------------------------------------\n// TailorDB Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for TailorDB operations. Installs a mock\n * `tailordb.Client` whose `queryObject` is a shared `vi.fn()` (so query\n * responses can be staged before the client is constructed). Restored on\n * dispose.\n * @param options - Query fallback behavior\n * @returns Disposable TailorDB mock control object\n * @example\n * ```typescript\n * import { mockTailordb } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"query-based\", async () => {\n *   using db = mockTailordb();\n *   db.onQuery({ sql: /FROM users/, params: [\"u-1\"] }).returnsRows([{ age: 30 }]);\n *   // …\n *   expect(db.queryObject).toHaveBeenCalled();\n *   expect(db.Client).toHaveBeenCalledWith({ namespace: \"tailordb\" });\n * });\n * ```\n */\nexport function mockTailordb(options: MockTailordbOptions = {}) {\n  const root = tailordbRoot();\n  const prevClient = root.Client;\n\n  const rules: QueryRule[] = [];\n  let queryResolver: QueryResolver | undefined;\n\n  function matchesQuery(matcher: QueryMatcher, query: string, params: unknown[]): boolean {\n    if (typeof matcher === \"function\") return matcher(query, params);\n    if (typeof matcher === \"string\") return query === matcher;\n    if (matcher instanceof RegExp) return testRegex(matcher, query);\n\n    let sqlMatches: boolean;\n    if (typeof matcher.sql === \"string\") {\n      sqlMatches = query === matcher.sql;\n    } else {\n      sqlMatches = testRegex(matcher.sql, query);\n    }\n    if (!sqlMatches || matcher.params === undefined) return sqlMatches;\n    if (typeof matcher.params === \"function\") return matcher.params(params);\n    const expectedParams = matcher.params;\n    return (\n      params.length === expectedParams.length &&\n      params.every((value, index) => isEqual(value, expectedParams[index]))\n    );\n  }\n\n  function queryResponse(response: QueryResponse): MockQueryResult {\n    if (response.type === \"error\") throw response.error;\n    return new MockQueryResult(response.rows);\n  }\n\n  async function defaultQuery(query: string, params: unknown[] = []): Promise<MockQueryResult> {\n    for (let i = rules.length - 1; i >= 0; i -= 1) {\n      const rule = rules[i];\n      if (!rule || !matchesQuery(rule.matcher, query, params)) continue;\n      const once = rule.once.shift();\n      if (once) return queryResponse(once);\n      if (rule.fallback) return queryResponse(rule.fallback);\n    }\n\n    if (queryResolver) return new MockQueryResult(queryResolver(query, params) ?? []);\n    if (options.onUnhandled === \"error\") {\n      throw new Error(`No TailorDB query behavior matched: ${query}`);\n    }\n    return new MockQueryResult([]);\n  }\n\n  const queryObject = vi.fn(defaultQuery);\n  const defaultConnect = async (): Promise<void> => {};\n  const connect = vi.fn(defaultConnect);\n  const createdClients: CreatedClient[] = [];\n\n  function enqueueRowsList(rowsList: unknown[][]): void {\n    for (const rows of rowsList) {\n      queryObject.mockImplementationOnce(async () => new MockQueryResult(rows));\n    }\n  }\n\n  const defaultClient = function (\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    this: any,\n    config?: { namespace?: string },\n  ) {\n    const record: CreatedClient = { namespace: config?.namespace, ended: false };\n    createdClients.push(record);\n    this.connect = connect;\n    this.end = vi.fn(async (): Promise<void> => {\n      record.ended = true;\n    });\n    this.queryObject = queryObject;\n    this.createTransaction = (name: string) => {\n      if (!name) {\n        throw new Error(\"Transaction name must be a non-empty string\");\n      }\n      return {\n        begin: async (): Promise<void> => {},\n        commit: async (): Promise<void> => {},\n        rollback: async (): Promise<void> => {},\n        queryObject,\n      };\n    };\n  };\n  const Client = vi.fn(defaultClient);\n\n  root.Client = Client;\n\n  const facade = {\n    /** The mock `tailordb.Client` constructor (`vi.fn`). */\n    Client,\n    /** The shared `queryObject` `vi.fn` used by every client and transaction. */\n    queryObject,\n\n    /**\n     * Set a fallback query resolver. Called when the enqueue queue is empty.\n     * @param resolver - Function that returns rows for a given query and params\n     */\n    setQueryResolver(resolver: QueryResolver): void {\n      queryResolver = resolver;\n      queryObject.mockImplementation(defaultQuery);\n    },\n\n    /**\n     * Configure responses for queries matching SQL text, parameters, or a predicate.\n     * More recently registered matchers take precedence.\n     * Do not combine matchers with a direct `queryObject.mockImplementation()` override.\n     * @param matcher - Query matcher\n     * @returns Chainable query behavior\n     */\n    onQuery<Row = unknown>(matcher: QueryMatcher): QueryBehavior<Row> {\n      const rule: QueryRule = { matcher, once: [] };\n      rules.push(rule);\n      const behavior: QueryBehavior<Row> = {\n        returnsRows(rows) {\n          rule.fallback = { type: \"rows\", rows };\n          return behavior;\n        },\n        returnsRowsOnce(rows) {\n          rule.once.push({ type: \"rows\", rows });\n          return behavior;\n        },\n        rejects(error) {\n          rule.fallback = { type: \"error\", error };\n          return behavior;\n        },\n        rejectsOnce(error) {\n          rule.once.push({ type: \"error\", error });\n          return behavior;\n        },\n      };\n      return behavior;\n    },\n\n    /**\n     * Enqueue rows for the next `queryObject` call (FIFO; takes priority over\n     * `setQueryResolver`). Call with no arguments for an empty result.\n     * @param rows - Row objects to return from the next `queryObject` call\n     */\n    enqueueResult(...rows: unknown[]): void {\n      enqueueRowsList([rows]);\n    },\n\n    /**\n     * Enqueue rows for multiple subsequent `queryObject` calls (FIFO).\n     * @param rowsList - Rows arrays, one per upcoming query\n     */\n    enqueueResults(...rowsList: unknown[][]): void {\n      enqueueRowsList(rowsList);\n    },\n\n    /**\n     * Enqueue row arrays for subsequent queries whose exact order is under test.\n     * @param rowsList - Rows arrays, one per upcoming query\n     */\n    enqueueRows(...rowsList: unknown[][]): void {\n      enqueueRowsList(rowsList);\n    },\n\n    /**\n     * All queries executed via `queryObject`, in order, derived from the vi.fn\n     * call records.\n     * @returns Executed queries array\n     */\n    get executedQueries(): ExecutedQuery[] {\n      return queryObject.mock.calls.map(([query, params]) => ({\n        query: query,\n        // vitest records an omitted argument as undefined\n        // oxlint-disable-next-line typescript/no-unnecessary-condition\n        params: (params as unknown[]) ?? [],\n      }));\n    },\n\n    /**\n     * All TailorDB clients created, with their namespace and end state.\n     * @returns Created clients array\n     */\n    get createdClients(): CreatedClient[] {\n      return createdClients;\n    },\n\n    /** Clear recorded calls while preserving configured query behavior. */\n    clear(): void {\n      queryObject.mockClear();\n      connect.mockClear();\n      Client.mockClear();\n      createdClients.length = 0;\n    },\n\n    /** Reset query responses and recorded calls (keeps the mock installed). */\n    reset(): void {\n      queryObject.mockReset();\n      queryObject.mockImplementation(defaultQuery);\n      connect.mockReset();\n      connect.mockImplementation(defaultConnect);\n      Client.mockReset();\n      Client.mockImplementation(defaultClient);\n      createdClients.length = 0;\n      rules.length = 0;\n      queryResolver = undefined;\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.Client = prevClient;\n  });\n}\n","import { type Mock, vi } from \"vitest\";\nimport { START_DEFAULT } from \"#/configure/services/workflow/registry\";\nimport {\n  getWaitPointInvoker,\n  getWaitPointKey,\n} from \"#/configure/services/workflow/wait-point-invoker\";\nimport { platformSerialize } from \"#/utils/test/platform-serialize\";\nimport {\n  clearWorkflowTestEnv,\n  readWorkflowTestEnv,\n  writeWorkflowTestEnv,\n} from \"../../configure/services/workflow/test-env-key\";\nimport { tailorRoot, withDispose } from \"./shared\";\nimport type { WorkflowJob } from \"#/configure/services/workflow/job\";\nimport type {\n  ParameterizedWaitPointInstance,\n  WaitPointInstance,\n} from \"#/configure/services/workflow/wait-point\";\nimport type { WaitPointInvoker } from \"#/configure/services/workflow/wait-point-invoker\";\nimport type { Workflow } from \"#/configure/services/workflow/workflow\";\nimport type { ExecJobFunctionOptions, StartWorkflowOptions } from \"#/runtime/workflow\";\nimport type { TailorEnv } from \"../../runtime/types\";\n\ntype JobHandler = (jobName: string, args: unknown, options?: ExecJobFunctionOptions) => unknown;\n\ntype StartHandlerFn = (\n  workflowName: string,\n  args: unknown,\n  options?: StartWorkflowOptions,\n) => string;\ntype ResumeHandlerFn = (executionId: string) => string;\ntype WaitHandlerFn = (key: string, payload: unknown) => unknown;\ntype ResolveHandler = (\n  executionId: string,\n  key: string,\n  callback: (payload: unknown) => unknown,\n) => unknown | Promise<unknown>;\n\n// Overloaded so TypeScript narrows to WaitHandlerFn first (giving inferred\n// `(key: string, payload: unknown) => …` for callers) before falling back\n// to the static-value form. A union type would let `unknown` swallow the\n// function variant and break inference.\ntype SetWaitHandler = {\n  (handler: WaitHandlerFn): void;\n  (handler: unknown): void;\n};\n\ninterface StartedJob {\n  jobName: string;\n  args: unknown;\n  options?: ExecJobFunctionOptions;\n}\n\ntype InvokerWait = WaitPointInvoker[\"wait\"];\ntype InvokerResolve = WaitPointInvoker[\"resolve\"];\n\ninterface KeyDispatcherSlot {\n  perKey: Map<string, unknown>;\n  originalWait: (key: string, payload: unknown) => unknown;\n  originalResolve: (\n    key: string,\n    executionId: string,\n    callback: (payload: unknown) => unknown | Promise<unknown>,\n  ) => Promise<void>;\n}\n\n// `invoker.wait`/`resolve` may already be an enclosing scope's dispatcher. Keep\n// the base methods so a nested scope falls through to the platform mock rather\n// than to the outer scope's per-key mocks — the same split `replaceProcedure`\n// makes, where the default implementation calls the base while `restore` puts\n// back the immediately preceding scope.\nconst baseInvokerWait = new WeakMap<InvokerWait, InvokerWait>();\nconst baseInvokerResolve = new WeakMap<InvokerResolve, InvokerResolve>();\n\ninterface ScopedMock {\n  mockClear(): unknown;\n  mockReset(): unknown;\n  restore(): void;\n}\n\ntype WaitPayload<Payload> = [Payload] extends [undefined] ? undefined : Payload;\ntype ProcedureFn = (...args: never[]) => unknown;\n// `vi.spyOn` reuses an existing spy for the same property. Keep the base\n// procedure separately so nested mockWorkflow scopes get independent mocks\n// while disposal can still restore the immediately preceding scope.\nconst originalProcedures = new WeakMap<ProcedureFn, ProcedureFn>();\n\nfunction replaceProcedure<Procedure extends ProcedureFn>(\n  target: object,\n  key: string,\n  current: Procedure,\n): { mock: Mock<Procedure>; scoped: ScopedMock } {\n  const original = (originalProcedures.get(current) ?? current) as Procedure;\n  const defaultImplementation = function (\n    this: unknown,\n    ...args: Parameters<Procedure>\n  ): ReturnType<Procedure> {\n    return Reflect.apply(original, this, args) as ReturnType<Procedure>;\n  };\n  const mock = vi.fn(defaultImplementation) as unknown as Mock<Procedure>;\n  originalProcedures.set(mock, original);\n\n  const record = target as Record<string, unknown>;\n  record[key] = mock;\n\n  return {\n    mock,\n    scoped: {\n      mockClear: () => mock.mockClear(),\n      mockReset: () => mock.mockReset(),\n      restore: () => {\n        if (record[key] === mock) record[key] = current;\n      },\n    },\n  };\n}\n\nfunction replaceStart<Start extends ProcedureFn>(definition: {\n  start: Start;\n}): { mock: Mock<Start>; scoped: ScopedMock } {\n  return replaceProcedure(definition, \"start\", definition.start);\n}\n\n// ---------------------------------------------------------------------------\n// Workflow Mock\n// ---------------------------------------------------------------------------\n\n/**\n * Acquire a disposable mock for workflow operations (`tailor.workflow`).\n * Restored on dispose.\n\n * @returns Disposable workflow mock control object\n * @example\n * ```typescript\n * import { mockWorkflow } from \"@tailor-platform/sdk/vitest\";\n *\n * test(\"job start\", async () => {\n *   using wf = mockWorkflow();\n *   const job = wf.job(validateOrder);\n *   job.mockResolvedValue({ valid: true });\n *   await runWorkflowUnderTest();\n *   expect(job).toHaveBeenCalled();\n * });\n * ```\n */\nexport function mockWorkflow() {\n  const root = tailorRoot();\n  const prev = root.workflow;\n  const prevEnv = readWorkflowTestEnv();\n  const jobSpies = new Map<object, unknown>();\n  const workflowSpies = new Map<object, unknown>();\n  const waitPointMocks = new Map<object, unknown>();\n  const keyDispatchers = new Map<object, KeyDispatcherSlot>();\n  const scopedMocks = new Set<ScopedMock>();\n\n  // A parameterized wait point's `wait`/`resolve` live on the throwaway object\n  // returned by `.with()`, so there is nothing stable to spy on. Intercept the\n  // definition's invoker instead and dispatch on the resolved key.\n  const installKeyDispatcher = (definition: object): KeyDispatcherSlot => {\n    const cached = keyDispatchers.get(definition);\n    if (cached) return cached;\n\n    const invoker = getWaitPointInvoker(definition);\n    if (!invoker) {\n      throw new Error(\n        \"waitPointWith expects a wait point definition created by createWaitPoint or createWaitPoints.\",\n      );\n    }\n    const record = invoker as unknown as Record<string, unknown>;\n    const prevWait = invoker.wait;\n    const prevResolve = invoker.resolve;\n    const baseWait = baseInvokerWait.get(prevWait) ?? prevWait;\n    const baseResolve = baseInvokerResolve.get(prevResolve) ?? prevResolve;\n    const slot: KeyDispatcherSlot = {\n      perKey: new Map(),\n      originalWait: (key, payload) => baseWait.call(invoker, key, payload),\n      originalResolve: (key, executionId, callback) =>\n        baseResolve.call(invoker, key, executionId, callback),\n    };\n\n    const dispatchWait: InvokerWait = (key, payload) => {\n      const mock = slot.perKey.get(key) as { wait: Mock } | undefined;\n      if (!mock) return slot.originalWait(key, payload);\n      // A bound wait point always fills the payload slot, so `.wait()` arrives\n      // here as an explicit `undefined`. Drop it, or the recorded call would be\n      // `[undefined]` where `waitPoint()` — whose mock replaces `.wait` itself —\n      // records no argument, and `toHaveBeenCalledWith()` would fail.\n      return payload === undefined ? mock.wait() : mock.wait(payload);\n    };\n    const dispatchResolve: InvokerResolve = async (key, executionId, callback) => {\n      const mock = slot.perKey.get(key) as { resolve: Mock } | undefined;\n      if (!mock) return slot.originalResolve(key, executionId, callback);\n      await mock.resolve(executionId, callback);\n    };\n    baseInvokerWait.set(dispatchWait, baseWait);\n    baseInvokerResolve.set(dispatchResolve, baseResolve);\n    record.wait = dispatchWait;\n    record.resolve = dispatchResolve;\n\n    const eachSpy = (fn: (spy: Mock) => unknown) => {\n      for (const mock of slot.perKey.values()) {\n        const pair = mock as { wait: Mock; resolve: Mock };\n        fn(pair.wait);\n        fn(pair.resolve);\n      }\n    };\n    scopedMocks.add({\n      mockClear: () => eachSpy((spy) => spy.mockClear()),\n      mockReset: () => eachSpy((spy) => spy.mockReset()),\n      restore: () => {\n        record.wait = prevWait;\n        record.resolve = prevResolve;\n        keyDispatchers.delete(definition);\n      },\n    });\n\n    keyDispatchers.set(definition, slot);\n    return slot;\n  };\n\n  const defaultExecJob = (\n    jobName: string,\n    _args?: unknown,\n    _options?: ExecJobFunctionOptions,\n  ): unknown => {\n    throw new Error(\n      `No workflow job mock for \"${jobName}\". Call mockWorkflow().setJobHandler(...) or enqueueResult(...), or use runWorkflowLocally() for local workflow execution.`,\n    );\n  };\n  const defaultStartWorkflow = async (\n    _workflowName: string,\n    _args?: unknown,\n    _options?: StartWorkflowOptions,\n  ): Promise<string> => {\n    return START_DEFAULT;\n  };\n  const defaultResumeWorkflowExecution = async (executionId: string): Promise<string> =>\n    executionId;\n\n  // Inner vi.fns hold the overridable behavior + call recording; the installed\n  // shims below cross the platform JSON boundary (serialize args + results) once.\n  const execJobFunction = vi.fn(defaultExecJob);\n  const startWorkflow = vi.fn(defaultStartWorkflow);\n  const resumeWorkflowExecution = vi.fn(defaultResumeWorkflowExecution);\n  const wait = vi.fn((_key: string, _payload?: unknown): unknown => null);\n  const resolve = vi.fn(\n    async (\n      _executionId: string,\n      _key: string,\n      _callback: (payload: unknown) => unknown,\n    ): Promise<void> => {},\n  );\n\n  const setWaitHandler: SetWaitHandler = (handler: unknown) => {\n    wait.mockImplementation(\n      typeof handler === \"function\"\n        ? (key, payload) => (handler as WaitHandlerFn)(key, payload)\n        : () => handler,\n    );\n  };\n\n  // Preserve arity: recording `undefined` as the third element only when the\n  // caller supplied it, mirroring `.execJobFunction(name, args, options)`.\n  const jobFunctionShim = (...call: [string, unknown?, ExecJobFunctionOptions?]) => {\n    const out =\n      call.length >= 3\n        ? execJobFunction(call[0], platformSerialize(call[1]), call[2])\n        : execJobFunction(call[0], platformSerialize(call[1]));\n    return out instanceof Promise ? out.then((v) => platformSerialize(v)) : platformSerialize(out);\n  };\n  // Preserve arity so a forwarded third `options` arg — even `undefined` — is\n  // recorded, matching the real `.start(args, options)` call shape.\n  const workflowShim = (...call: [string, unknown?, StartWorkflowOptions?]) =>\n    call.length >= 3\n      ? startWorkflow(call[0], platformSerialize(call[1]), call[2])\n      : startWorkflow(call[0], platformSerialize(call[1]));\n  const resumeShim = (executionId: string) => resumeWorkflowExecution(executionId);\n  root.workflow = {\n    execJobFunction: jobFunctionShim,\n    startWorkflow: workflowShim,\n    resumeWorkflowExecution: resumeShim,\n    wait: (key: string, payload?: unknown) => wait(key, platformSerialize(payload)),\n    resolve: (executionId: string, key: string, callback: (payload: unknown) => unknown) =>\n      resolve(executionId, key, (payload: unknown) => {\n        const out = callback(payload);\n        return out instanceof Promise\n          ? out.then((v) => platformSerialize(v))\n          : platformSerialize(out);\n      }),\n  };\n\n  const facade = {\n    /** The `execJobFunction` `vi.fn`. */\n    execJobFunction,\n    /** The `startWorkflow` `vi.fn`. */\n    startWorkflow,\n    /** The `resumeWorkflowExecution` `vi.fn`. */\n    resumeWorkflowExecution,\n    /** The `wait` `vi.fn`. */\n    wait,\n    /** The `resolve` `vi.fn`. */\n    resolve,\n\n    /**\n     * Get a stable, typed mock for a workflow job's `start` method.\n     * The real start behavior is used until an implementation or result is configured.\n     * @param definition - Workflow job definition to mock\n     * @returns Typed `start` mock for the definition\n     */\n    job<Name extends string, Input, Output>(\n      definition: WorkflowJob<Name, Input, Output>,\n    ): Mock<WorkflowJob<Name, Input, Output>[\"start\"]> {\n      const existing = jobSpies.get(definition);\n      if (existing) {\n        return existing as Mock<WorkflowJob<Name, Input, Output>[\"start\"]>;\n      }\n\n      const { mock, scoped } = replaceStart<WorkflowJob<Name, Input, Output>[\"start\"]>(definition);\n      scopedMocks.add(scoped);\n      jobSpies.set(definition, mock);\n      return mock;\n    },\n\n    /**\n     * Get a stable, typed mock for a workflow definition's `start` method.\n     * The real start behavior is used until an implementation or result is configured.\n     * @param definition - Workflow definition to mock\n     * @returns Typed `start` mock for the definition\n     */\n    workflow<Definition extends Workflow>(definition: Definition): Mock<Definition[\"start\"]> {\n      const existing = workflowSpies.get(definition);\n      if (existing) return existing as Mock<Definition[\"start\"]>;\n\n      const { mock, scoped } = replaceStart<Definition[\"start\"]>(definition);\n      workflowSpies.set(definition, mock);\n      scopedMocks.add(scoped);\n      return mock;\n    },\n\n    /**\n     * Get stable, typed mocks for a wait point's `wait` and `resolve` methods.\n     * @param definition - Wait point definition to mock\n     * @returns Typed wait point mock control object\n     */\n    waitPoint<Payload, Result>(definition: WaitPointInstance<Payload, Result>) {\n      const existing = waitPointMocks.get(definition);\n      if (existing) {\n        return existing as {\n          wait: Mock<WaitPointInstance<Payload, Result>[\"wait\"]>;\n          resolve: Mock<WaitPointInstance<Payload, Result>[\"resolve\"]>;\n          setResolvePayload(payload: WaitPayload<Payload>): void;\n        };\n      }\n\n      const waitReplacement = replaceProcedure(definition, \"wait\", definition.wait);\n      const resolveReplacement = replaceProcedure(definition, \"resolve\", definition.resolve);\n      const waitSpy = waitReplacement.mock;\n      const resolveSpy = resolveReplacement.mock;\n      scopedMocks.add(waitReplacement.scoped);\n      scopedMocks.add(resolveReplacement.scoped);\n\n      const waitPointMock = {\n        wait: waitSpy,\n        resolve: resolveSpy,\n\n        /**\n         * Invoke the next and subsequent resolve callbacks with a wait payload.\n         * @param payload - Payload originally supplied to the wait point\n         */\n        setResolvePayload(payload: WaitPayload<Payload>): void {\n          resolveSpy.mockImplementation(async (_executionId, callback) => {\n            const result = await callback(platformSerialize(payload));\n            platformSerialize(result);\n          });\n        },\n      };\n\n      waitPointMocks.set(definition, waitPointMock);\n      return waitPointMock;\n    },\n\n    /**\n     * Get stable, typed mocks for one param binding of a parameterized wait point.\n     * Calls made with other bindings fall through to the platform mock.\n     * @param definition - Parameterized wait point definition to mock\n     * @param params - Param binding to intercept, as passed to `.with()`\n     * @returns Typed wait point mock control object\n     */\n    waitPointWith<Params extends object, Payload, Result>(\n      definition: ParameterizedWaitPointInstance<Params, Payload, Result>,\n      params: Params,\n    ) {\n      const key = getWaitPointKey(definition.with(params));\n      if (key === undefined) {\n        throw new Error(\n          \"waitPointWith expects a wait point declared with $params. Use waitPoint() for a wait point with a fixed key.\",\n        );\n      }\n      const slot = installKeyDispatcher(definition);\n\n      const existing = slot.perKey.get(key);\n      if (existing) {\n        return existing as {\n          wait: Mock<WaitPointInstance<Payload, Result>[\"wait\"]>;\n          resolve: Mock<WaitPointInstance<Payload, Result>[\"resolve\"]>;\n          setResolvePayload(payload: WaitPayload<Payload>): void;\n        };\n      }\n\n      // A bound wait point resolves what the invoker returns, so an unmocked\n      // spy has to hand back a promise too — otherwise calling this mock\n      // directly yields a raw value where its type promises one.\n      const waitSpy = vi.fn((payload?: unknown) =>\n        Promise.resolve(slot.originalWait(key, payload)),\n      ) as unknown as Mock<WaitPointInstance<Payload, Result>[\"wait\"]>;\n      const resolveSpy = vi.fn(\n        (executionId: string, callback: (payload: unknown) => unknown | Promise<unknown>) =>\n          slot.originalResolve(key, executionId, callback),\n      ) as unknown as Mock<WaitPointInstance<Payload, Result>[\"resolve\"]>;\n      const waitPointMock = {\n        wait: waitSpy,\n        resolve: resolveSpy,\n\n        /**\n         * Invoke the next and subsequent resolve callbacks with a wait payload.\n         * @param payload - Payload originally supplied to the wait point\n         */\n        setResolvePayload(payload: WaitPayload<Payload>): void {\n          (resolveSpy as unknown as Mock).mockImplementation(\n            async (_executionId: string, callback: (p: unknown) => unknown) => {\n              const result = await callback(platformSerialize(payload));\n              platformSerialize(result);\n            },\n          );\n        },\n      };\n      slot.perKey.set(key, waitPointMock);\n      return waitPointMock;\n    },\n\n    /**\n     * Set a fallback job handler. Called when the enqueue queue is empty.\n     * @param handler - Function returning a result for a job name, args, and options\n     */\n    setJobHandler(handler: JobHandler): void {\n      execJobFunction.mockImplementation((name, args, options) => handler(name, args, options));\n    },\n\n    /**\n     * Enqueue a single result for the next `execJobFunction` call (FIFO;\n     * takes priority over `setJobHandler`).\n     * @param result - Result to return from the next call\n     */\n    enqueueResult(result: unknown): void {\n      execJobFunction.mockImplementationOnce(() => result);\n    },\n\n    /**\n     * Enqueue results for multiple subsequent `execJobFunction` calls (FIFO).\n     * @param results - Results to enqueue, one per upcoming call\n     */\n    enqueueResults(...results: unknown[]): void {\n      for (const result of results) {\n        execJobFunction.mockImplementationOnce(() => result);\n      }\n    },\n\n    /**\n     * All jobs executed via `execJobFunction`, in order.\n     * @returns Started jobs array\n     */\n    get startedJobs(): StartedJob[] {\n      return execJobFunction.mock.calls.map(([jobName, args, options]) => ({\n        jobName: jobName,\n        args,\n        ...(options !== undefined && { options: options }),\n      }));\n    },\n\n    /**\n     * Configure what `startWorkflow` returns. Pass a string (same id every\n     * call) or `(name, args, options) => string`. Default: a placeholder UUID.\n     * @param handler - Static execution ID or a function returning one\n     */\n    setStartHandler(handler: string | StartHandlerFn): void {\n      startWorkflow.mockImplementation(\n        typeof handler === \"function\"\n          ? async (name, args, options) => handler(name, args, options)\n          : async () => handler,\n      );\n    },\n\n    /**\n     * Configure what `resumeWorkflowExecution` returns. Pass a string (same id\n     * every call) or `(executionId) => string`. Default: echoes the input executionId.\n     * @param handler - Static execution ID or a function returning one\n     */\n    setResumeHandler(handler: string | ResumeHandlerFn): void {\n      resumeWorkflowExecution.mockImplementation(\n        typeof handler === \"function\"\n          ? async (executionId) => handler(executionId)\n          : async () => handler,\n      );\n    },\n\n    /**\n     * Configure what `wait` returns. Pass `(key, payload) => unknown` or any\n     * other value to return it for every call. Default: `null`.\n     * @param handler - Static value or a function returning one\n     */\n    setWaitHandler,\n\n    /**\n     * Set the `env` passed to job bodies invoked via `createWorkflowJob().start()`.\n     * Cleared on dispose / reset.\n     * @param env - Env passed to job bodies.\n     */\n    setEnv(env: TailorEnv): void {\n      writeWorkflowTestEnv({ ...env });\n    },\n\n    /**\n     * Configure how `resolve` runs the user-supplied callback. Default: callback\n     * is not invoked (records the call only).\n     * @param handler - Function invoked per `resolve` call\n     */\n    setResolveHandler(handler: ResolveHandler): void {\n      resolve.mockImplementation(async (executionId, key, callback) => {\n        await handler(executionId, key, callback);\n      });\n    },\n\n    /**\n     * `wait` calls reshaped as `{ key, payload }` for assertions.\n     * @returns Wait call records\n     */\n    get waitCalls(): { key: string; payload: unknown }[] {\n      return wait.mock.calls.map(([key, payload]) => ({ key: key, payload }));\n    },\n\n    /**\n     * `resolve` calls reshaped as `{ executionId, key }` for assertions.\n     * @returns Resolve call records\n     */\n    get resolveCalls(): { executionId: string; key: string }[] {\n      return resolve.mock.calls.map(([executionId, key]) => ({\n        executionId: executionId,\n        key: key,\n      }));\n    },\n\n    /** Clear recorded calls while preserving configured responses. */\n    clear(): void {\n      execJobFunction.mockClear();\n      startWorkflow.mockClear();\n      resumeWorkflowExecution.mockClear();\n      wait.mockClear();\n      resolve.mockClear();\n      for (const mock of scopedMocks) mock.mockClear();\n    },\n\n    /** Reset all workflow responses and recorded calls (keeps the mock installed). */\n    reset(): void {\n      execJobFunction.mockReset();\n      execJobFunction.mockImplementation(defaultExecJob);\n      startWorkflow.mockReset();\n      startWorkflow.mockImplementation(defaultStartWorkflow);\n      resumeWorkflowExecution.mockReset();\n      resumeWorkflowExecution.mockImplementation(defaultResumeWorkflowExecution);\n      wait.mockReset();\n      wait.mockImplementation(() => null);\n      resolve.mockReset();\n      resolve.mockImplementation(async () => {});\n      for (const mock of scopedMocks) mock.mockReset();\n      clearWorkflowTestEnv();\n    },\n  };\n\n  return withDispose(facade, () => {\n    for (const mock of scopedMocks) mock.restore();\n    root.workflow = prev;\n    if (prevEnv !== undefined) writeWorkflowTestEnv(prevEnv);\n    else clearWorkflowTestEnv();\n  });\n}\n","import { vi } from \"vitest\";\nimport { tailordbRoot, withDispose } from \"./shared\";\nimport type { PGliteClient, PGliteQueryResult } from \"../pglite-kysely\";\n\n/** A query executed through the PGlite-backed TailorDB client. */\nexport interface ExecutedPGliteQuery {\n  /** Namespace of the `getDB` call that issued the query. */\n  namespace: string;\n  /** SQL text with positional (`$1`, `$2`, ...) placeholders. */\n  query: string;\n  /** Parameter values bound to the placeholders. */\n  params: unknown[];\n}\n\n/** Options for {@link mockTailordbWithPGlite}. */\nexport interface MockTailordbPGliteOptions {\n  /**\n   * PGlite instance per `getDB` namespace. A `getDB` call for a namespace\n   * missing here throws instead of falling back to another instance. Pass the\n   * same instance under several namespaces to share one database between them.\n   */\n  namespaces: Record<string, PGliteClient>;\n}\n\ninterface CreatedClient {\n  namespace: string;\n  ended: boolean;\n}\n\n// One transaction at a time per PGlite instance: PGlite is a single Postgres\n// session, so statements from another getDB instance would otherwise run\n// inside an open transaction.\nclass TransactionLock {\n  #holder: unknown = null;\n  #waiters: Array<() => void> = [];\n\n  holds(owner: unknown): boolean {\n    return this.#holder === owner;\n  }\n\n  async acquire(owner: unknown): Promise<void> {\n    while (this.#holder !== null) {\n      await new Promise<void>((resolve) => this.#waiters.push(resolve));\n    }\n    this.#holder = owner;\n  }\n\n  release(owner: unknown): void {\n    if (this.#holder !== owner) return;\n    this.#holder = null;\n    this.#waiters.shift()?.();\n  }\n}\n\nconst BEGIN_PATTERN = /^\\s*(?:begin|start\\s+transaction)\\b/i;\n// `rollback to savepoint` stays inside the transaction, so it must not\n// release the lock.\nconst END_PATTERN = /^\\s*(?:commit\\b|rollback\\b(?!(?:\\s+(?:work|transaction))?\\s+to\\b))/i;\n\nfunction toQueryObjectResult(result: PGliteQueryResult) {\n  return {\n    // getDB's Kysely dialect only membership-tests the tag against the DML\n    // verbs, so any of the three works when an older PGlite omits it.\n    command: result.command ?? (result.affectedRows ? \"UPDATE\" : \"SELECT\"),\n    rowCount: result.rowCount ?? (result.affectedRows || result.rows.length),\n    rows: result.rows,\n  };\n}\n\n/**\n * Acquire a disposable mock that backs the generated `getDB(namespace)` with\n * PGlite, so resolver/executor/workflow code runs unchanged and its queries\n * execute as real SQL on an in-memory Postgres. Restored on dispose; the\n * PGlite instances are borrowed, never closed — close them yourself (e.g. in\n * `afterAll`).\n *\n * Create the tables a test needs up front: run the script `kyselyTypePlugin`\n * writes when `pgliteSchemaPath` is set, or your own `CREATE TABLE`\n * statements matching the generated Kysely types. PGlite runs full PostgreSQL\n * while TailorDB supports a subset of it, so a statement passing here can\n * still be rejected by the platform.\n *\n * Transactions on a shared instance are serialized: while one is open,\n * queries from other `getDB` instances on the same PGlite instance wait for\n * it to finish. Do not run such tests with `test.concurrent`, and do not\n * query the same instance through a second `getDB` from inside a transaction\n * — that waits on itself.\n * @param options - PGlite instance registration per namespace\n * @returns Disposable TailorDB mock control object\n * @example\n * ```typescript\n * import { PGlite } from \"@electric-sql/pglite\";\n * import { mockTailordbWithPGlite } from \"@tailor-platform/sdk/vitest\";\n * import { getDB } from \"../generated/tailordb\";\n *\n * const pglite = new PGlite();\n * afterAll(() => pglite.close());\n *\n * test(\"real SQL\", async () => {\n *   using _db = mockTailordbWithPGlite({ namespaces: { tailordb: pglite } });\n *   await pglite.query(`CREATE TABLE \"User\" (\"id\" uuid PRIMARY KEY, \"name\" text NOT NULL)`);\n *   await getDB(\"tailordb\").insertInto(\"User\").values({ id: crypto.randomUUID(), name: \"a\" }).execute();\n * });\n * ```\n */\nexport function mockTailordbWithPGlite(options: MockTailordbPGliteOptions) {\n  const root = tailordbRoot();\n  const prevClient = root.Client;\n\n  const executedQueries: ExecutedPGliteQuery[] = [];\n  const createdClients: CreatedClient[] = [];\n  const locks = new Map<PGliteClient, TransactionLock>();\n  const activeTransactions = new Set<CreatedClient>();\n\n  const assertNoOpenTransaction = (method: \"clear\" | \"reset\") => {\n    if (activeTransactions.size > 0) {\n      throw new Error(\n        `mockTailordbWithPGlite: ${method}() cannot run while a transaction is open; commit, roll back, or end() its client first`,\n      );\n    }\n  };\n\n  const defaultClient = function (\n    // eslint-disable-next-line @typescript-eslint/no-explicit-any\n    this: any,\n    config?: { namespace?: string },\n  ) {\n    const namespace = config?.namespace;\n    const pglite =\n      namespace !== undefined && Object.hasOwn(options.namespaces, namespace)\n        ? options.namespaces[namespace]\n        : undefined;\n    if (namespace === undefined || !pglite) {\n      throw new Error(\n        `mockTailordbWithPGlite: no PGlite instance registered for namespace \"${namespace}\"`,\n      );\n    }\n    const lock = locks.get(pglite) ?? new TransactionLock();\n    locks.set(pglite, lock);\n\n    const record: CreatedClient = { namespace, ended: false };\n    createdClients.push(record);\n\n    const self = this as object;\n    const run = async (query: string, params?: unknown[]) => {\n      executedQueries.push({ namespace, query, params: params ?? [] });\n      return toQueryObjectResult(await pglite.query(query, params ?? []));\n    };\n\n    const throwEnded = (): never => {\n      throw new Error(\"mockTailordbWithPGlite: query after end() on this client\");\n    };\n    // Rechecked after every acquire: end() can resolve while the query is\n    // still waiting for the lock.\n    const acquire = async () => {\n      await lock.acquire(self);\n      if (record.ended) {\n        lock.release(self);\n        throwEnded();\n      }\n    };\n\n    const queryObject = async (query: string, params?: unknown[]) => {\n      if (record.ended) throwEnded();\n      if (BEGIN_PATTERN.test(query)) {\n        if (lock.holds(self)) {\n          throw new Error(\n            \"mockTailordbWithPGlite: transaction already open on this client — run nested statements on the transaction callback's trx\",\n          );\n        }\n        await acquire();\n        try {\n          const result = await run(query, params);\n          activeTransactions.add(record);\n          return result;\n        } catch (error) {\n          lock.release(self);\n          throw error;\n        }\n      }\n      if (END_PATTERN.test(query)) {\n        if (lock.holds(self)) {\n          try {\n            return await run(query, params);\n          } finally {\n            activeTransactions.delete(record);\n            lock.release(self);\n          }\n        }\n        // A commit/rollback from a client with no open transaction must not\n        // land inside another client's — wait until the instance is free.\n        await acquire();\n        try {\n          return await run(query, params);\n        } finally {\n          lock.release(self);\n        }\n      }\n      if (lock.holds(self)) {\n        return await run(query, params);\n      }\n      await acquire();\n      try {\n        return await run(query, params);\n      } finally {\n        lock.release(self);\n      }\n    };\n\n    this.connect = async (): Promise<void> => {};\n    this.end = async (): Promise<void> => {\n      record.ended = true;\n      if (lock.holds(self)) {\n        try {\n          await run(\"rollback\");\n        } finally {\n          activeTransactions.delete(record);\n          lock.release(self);\n        }\n      }\n    };\n    this.queryObject = queryObject;\n    this.createTransaction = (name: string) => {\n      if (!name) {\n        throw new Error(\"Transaction name must be a non-empty string\");\n      }\n      return {\n        begin: () => queryObject(\"begin\"),\n        commit: () => queryObject(\"commit\"),\n        rollback: () => queryObject(\"rollback\"),\n        queryObject,\n      };\n    };\n  };\n  const Client = vi.fn(defaultClient);\n\n  root.Client = Client;\n\n  const facade = {\n    /** The mock `tailordb.Client` constructor (`vi.fn`). */\n    Client,\n\n    /**\n     * All queries executed on the PGlite instances, in order, with the\n     * namespace that issued each.\n     * @returns Executed queries array\n     */\n    get executedQueries(): ExecutedPGliteQuery[] {\n      return executedQueries;\n    },\n\n    /**\n     * All TailorDB clients created, with their namespace and end state.\n     * @returns Created clients array\n     */\n    get createdClients(): CreatedClient[] {\n      return createdClients;\n    },\n\n    /**\n     * Clear recorded queries and clients while keeping the mock installed.\n     * Throws if a transaction is open.\n     */\n    clear(): void {\n      assertNoOpenTransaction(\"clear\");\n      Client.mockClear();\n      executedQueries.length = 0;\n      createdClients.length = 0;\n    },\n\n    /**\n     * Reset recorded state and restore the default client behavior.\n     * Throws if a transaction is open.\n     */\n    reset(): void {\n      assertNoOpenTransaction(\"reset\");\n      Client.mockReset();\n      Client.mockImplementation(defaultClient);\n      executedQueries.length = 0;\n      createdClients.length = 0;\n    },\n  };\n\n  return withDispose(facade, () => {\n    root.Client = prevClient;\n  });\n}\n","/* oxlint-disable typescript/no-explicit-any */\nimport { START_DEFAULT, getRegisteredJob } from \"../configure/services/workflow/registry\";\nimport {\n  buildJobContext,\n  clearWorkflowTestEnv,\n  readWorkflowTestEnv,\n  writeWorkflowTestEnv,\n} from \"../configure/services/workflow/test-env-key\";\nimport { platformSerialize } from \"../utils/test/platform-serialize\";\nimport type { Workflow, WorkflowJob } from \"../configure/services/workflow\";\nimport type { TailorEnv } from \"../runtime/types\";\nimport type { PlatformWorkflowAPI } from \"../runtime/workflow\";\n\ntype AnyWorkflowJob = WorkflowJob<string, any, any>;\ntype AnyWorkflow = Workflow<AnyWorkflowJob>;\n\ntype WorkflowInput<W extends AnyWorkflow> =\n  W[\"mainJob\"] extends WorkflowJob<string, infer I, any> ? I : never;\ntype WorkflowOutput<W extends AnyWorkflow> =\n  W[\"mainJob\"] extends WorkflowJob<string, any, infer O> ? Awaited<O> : never;\n\ntype GlobalWithTailor = {\n  tailor?: {\n    workflow?: PlatformWorkflowAPI;\n  };\n};\n\ntype StartRecord = {\n  jobName: string;\n  args: unknown;\n} & (\n  | {\n      status: \"fulfilled\";\n      result: unknown;\n    }\n  | {\n      status: \"rejected\";\n      error: unknown;\n    }\n);\n\ninterface LocalExecution {\n  records: StartRecord[];\n  cursor: number;\n  pending?: PendingStart;\n}\n\nclass PendingStart {\n  constructor(\n    readonly jobName: string,\n    readonly args: unknown,\n  ) {}\n}\n\nexport interface RunWorkflowLocallyOptions {\n  /** Env passed to workflow job bodies during this local run. */\n  env?: TailorEnv;\n}\n\n/**\n * Run a workflow's main job and dependent job starts locally with real job bodies.\n *\n * Use this for local full-chain workflow tests. Regular `.start()` calls\n * delegate to the platform workflow runtime and should be mocked with\n * `mockWorkflow()` when you are not intentionally running the local chain.\n * @param workflow - Workflow definition to run\n * @returns The main job output\n */\nexport function runWorkflowLocally<W extends Workflow<WorkflowJob<string, undefined, any>>>(\n  workflow: W,\n): Promise<WorkflowOutput<W>>;\n/**\n * Run a no-input workflow locally with optional runner settings.\n * @param workflow - Workflow definition to run\n * @param args - Must be `undefined` for no-input workflows\n * @param options - Local runner options\n * @returns The main job output\n */\nexport function runWorkflowLocally<W extends Workflow<WorkflowJob<string, undefined, any>>>(\n  workflow: W,\n  args: undefined,\n  options?: RunWorkflowLocallyOptions,\n): Promise<WorkflowOutput<W>>;\n/**\n * Run a workflow locally with real job bodies.\n * @param workflow - Workflow definition to run\n * @param args - Arguments passed to the workflow's main job\n * @param options - Local runner options\n * @returns The main job output\n */\nexport function runWorkflowLocally<W extends AnyWorkflow>(\n  workflow: W,\n  args: WorkflowInput<W>,\n  options?: RunWorkflowLocallyOptions,\n): Promise<WorkflowOutput<W>>;\nexport async function runWorkflowLocally<W extends AnyWorkflow>(\n  workflow: W,\n  args?: WorkflowInput<W>,\n  options?: RunWorkflowLocallyOptions,\n): Promise<WorkflowOutput<W>> {\n  const root = globalThis as unknown as GlobalWithTailor;\n  const previousTailor = root.tailor;\n  const previousEnv = readWorkflowTestEnv();\n  const hasPreviousEnv = previousEnv !== undefined;\n  const runner = createLocalJobRunner();\n\n  if (options?.env !== undefined) {\n    writeWorkflowTestEnv({ ...options.env });\n  }\n\n  root.tailor = {\n    ...previousTailor,\n    workflow: createLocalWorkflowRuntime(previousTailor?.workflow, runner.execJobFunction),\n  };\n\n  try {\n    return (await runner.runJob(workflow.mainJob.name, args)) as WorkflowOutput<W>;\n  } finally {\n    if (previousTailor) {\n      root.tailor = previousTailor;\n    } else {\n      delete root.tailor;\n    }\n\n    if (options?.env !== undefined) {\n      if (hasPreviousEnv) {\n        writeWorkflowTestEnv(previousEnv);\n      } else {\n        clearWorkflowTestEnv();\n      }\n    }\n  }\n}\n\nfunction createLocalJobRunner(): {\n  runJob: (name: string, args?: unknown) => Promise<unknown>;\n  execJobFunction: (name: string, args?: unknown) => unknown;\n} {\n  let activeExecution: LocalExecution | undefined;\n\n  const execJobFunction = (jobName: string, args?: unknown): unknown => {\n    if (!activeExecution) {\n      throw new Error(\n        `Cannot start workflow job \"${jobName}\" outside runWorkflowLocally() job execution.`,\n      );\n    }\n    if (activeExecution.pending) {\n      throw activeExecution.pending;\n    }\n\n    const serializedArgs = platformSerialize(args);\n    const index = activeExecution.cursor;\n    activeExecution.cursor += 1;\n\n    const cached = activeExecution.records[index];\n    if (cached) {\n      assertSameStart(cached, jobName, serializedArgs);\n      if (cached.status === \"rejected\") {\n        throw cached.error;\n      }\n      return platformSerialize(cached.result);\n    }\n\n    const pending = new PendingStart(jobName, serializedArgs);\n    activeExecution.pending = pending;\n    throw pending;\n  };\n\n  const runJob = async (name: string, args?: unknown): Promise<unknown> => {\n    const body = getRegisteredJob(name);\n    if (!body) {\n      return null;\n    }\n\n    const records: StartRecord[] = [];\n\n    for (;;) {\n      const execution: LocalExecution = { records, cursor: 0 };\n      const previousExecution = activeExecution;\n      activeExecution = execution;\n\n      try {\n        const out = await body(platformSerialize(args), buildJobContext());\n        if (execution.pending) {\n          await settlePendingStart(records, execution.pending, runJob);\n          continue;\n        }\n        if (execution.cursor !== records.length) {\n          throw new Error(\n            `Workflow job start sequence changed while replaying \"${name}\". Expected ${records.length} start(s), but replay reached ${execution.cursor}.`,\n          );\n        }\n        return platformSerialize(out);\n      } catch (cause) {\n        const pending = cause instanceof PendingStart ? cause : execution.pending;\n        if (pending) {\n          await settlePendingStart(records, pending, runJob);\n          continue;\n        }\n        throw cause;\n      } finally {\n        activeExecution = previousExecution;\n      }\n    }\n  };\n\n  return { runJob, execJobFunction };\n}\n\nasync function settlePendingStart(\n  records: StartRecord[],\n  pending: PendingStart,\n  runJob: (name: string, args?: unknown) => Promise<unknown>,\n): Promise<void> {\n  try {\n    records.push({\n      jobName: pending.jobName,\n      args: pending.args,\n      status: \"fulfilled\",\n      result: await runJob(pending.jobName, pending.args),\n    });\n  } catch (error) {\n    records.push({\n      jobName: pending.jobName,\n      args: pending.args,\n      status: \"rejected\",\n      error,\n    });\n  }\n}\n\nfunction assertSameStart(record: StartRecord, jobName: string, args: unknown): void {\n  if (record.jobName === jobName && JSON.stringify(record.args) === JSON.stringify(args)) {\n    return;\n  }\n\n  throw new Error(\n    `Workflow job start sequence changed while replaying. Expected ${record.jobName}(${JSON.stringify(record.args)}), but got ${jobName}(${JSON.stringify(args)}).`,\n  );\n}\n\nfunction createLocalWorkflowRuntime(\n  previous: PlatformWorkflowAPI | undefined,\n  execJobFunction: (name: string, args?: unknown) => unknown,\n): PlatformWorkflowAPI {\n  const startWorkflow: PlatformWorkflowAPI[\"startWorkflow\"] = async (name, args, options) => {\n    if (previous) {\n      return await previous.startWorkflow(name, args, options);\n    }\n    platformSerialize(args);\n    return START_DEFAULT;\n  };\n  const resumeWorkflowExecution: PlatformWorkflowAPI[\"resumeWorkflowExecution\"] = async (\n    executionId,\n  ) => {\n    if (previous) {\n      return await previous.resumeWorkflowExecution(executionId);\n    }\n    return executionId;\n  };\n\n  return {\n    execJobFunction,\n    startWorkflow,\n    resumeWorkflowExecution,\n    wait: (key, payload) => {\n      if (previous) {\n        return previous.wait(key, payload);\n      }\n      throw new Error(\n        `No wait handler for \"${key}\". Acquire mockWorkflow() and call setWaitHandler(...).`,\n      );\n    },\n    resolve: async (executionId, key, callback) => {\n      if (previous) {\n        await previous.resolve(executionId, key, callback);\n        return;\n      }\n      throw new Error(\n        \"No resolve handler. Acquire mockWorkflow() and call setResolveHandler(...).\",\n      );\n    },\n  };\n}\n","/**\n * Kysely-layer mock for unit testing.\n *\n * Builds a real Kysely instance backed by a mock driver: queries compile and\n * type-check normally, but execution returns staged rows and records every\n * query for assertions.\n */\n\nimport {\n  ColumnNode,\n  type CompiledQuery,\n  type DatabaseConnection,\n  type Dialect,\n  type Driver,\n  InsertQueryNode,\n  Kysely,\n  type OperationNode,\n  type OperationNodeKind,\n  PostgresAdapter,\n  PostgresIntrospector,\n  PostgresQueryCompiler,\n  PrimitiveValueListNode,\n  type QueryResult,\n  ReferenceNode,\n  type Transaction,\n  UpdateQueryNode,\n  ValueListNode,\n  ValueNode,\n  ValuesNode,\n} from \"kysely\";\nimport { assertDefined } from \"#/utils/assert\";\n\nfunction unwrapValue(node: OperationNode): unknown {\n  return ValueNode.is(node) ? node.value : node;\n}\n\nfunction insertRows(node: OperationNode): Record<string, unknown>[] {\n  if (!InsertQueryNode.is(node)) {\n    throw new Error(`insertRows: expected InsertQueryNode, got ${node.kind}`);\n  }\n  const columns = node.columns;\n  const valuesNode = node.values;\n  if (columns === undefined || valuesNode === undefined || !ValuesNode.is(valuesNode)) {\n    throw new Error(\"insertRows: unsupported insert shape; inspect query.node instead\");\n  }\n  return valuesNode.values.map((row) => {\n    if (!PrimitiveValueListNode.is(row) && !ValueListNode.is(row)) {\n      throw new Error(\"insertRows: unsupported insert shape; inspect query.node instead\");\n    }\n    const values = PrimitiveValueListNode.is(row) ? row.values : row.values.map(unwrapValue);\n    const result: Record<string, unknown> = {};\n    columns.forEach((col, i) => {\n      result[col.column.name] = values[i];\n    });\n    return result;\n  });\n}\n\nfunction insertValues(node: OperationNode): Record<string, unknown> {\n  const rows = insertRows(node);\n  if (rows.length !== 1) {\n    throw new Error(\n      `insertValues: query inserts ${rows.length} rows; use insertRows() for multi-row inserts`,\n    );\n  }\n  return assertDefined(rows[0], \"insertValues: first row missing\");\n}\n\nfunction updateValues(node: OperationNode): Record<string, unknown> {\n  if (!UpdateQueryNode.is(node)) {\n    throw new Error(`updateValues: expected UpdateQueryNode, got ${node.kind}`);\n  }\n  if (node.updates === undefined) {\n    throw new Error(\"updateValues: unsupported update shape; inspect query.node instead\");\n  }\n  const result: Record<string, unknown> = {};\n  for (const update of node.updates) {\n    const col = update.column;\n    const name = ColumnNode.is(col)\n      ? col.column.name\n      : ReferenceNode.is(col) && ColumnNode.is(col.column)\n        ? col.column.column.name\n        : undefined;\n    if (name === undefined) {\n      throw new Error(\"updateValues: unsupported update shape; inspect query.node instead\");\n    }\n    result[name] = unwrapValue(update.value);\n  }\n  return result;\n}\n\n/** A single statement executed against the mock, captured in order. */\nexport interface ExecutedQuery {\n  /** The Kysely operation node kind, e.g. `\"SelectQueryNode\"`. */\n  kind: OperationNodeKind;\n  /** The compiled SQL string. */\n  sql: string;\n  /** The bound parameter values, in positional order. */\n  parameters: readonly unknown[];\n  /** The compiled Kysely operation node. */\n  node: OperationNode;\n  /** One `{ column: value }` map per row written by an insert. */\n  insertRows: () => Record<string, unknown>[];\n  /** The `{ column: value }` map written by a single-row insert. */\n  insertValues: () => Record<string, unknown>;\n  /** The `{ column: value }` map written by an update's SET clause. */\n  updateValues: () => Record<string, unknown>;\n}\n\nfunction toExecutedQuery(compiledQuery: CompiledQuery): ExecutedQuery {\n  const node = compiledQuery.query;\n  return {\n    kind: node.kind,\n    sql: compiledQuery.sql,\n    parameters: compiledQuery.parameters,\n    node,\n    insertRows: () => insertRows(node),\n    insertValues: () => insertValues(node),\n    updateValues: () => updateValues(node),\n  };\n}\n\ntype MockRow = Record<string, unknown>;\ntype MockResult = MockRow[] | { rows?: MockRow[]; numAffectedRows?: number | bigint };\ntype QueryResolver = (query: ExecutedQuery) => MockResult | undefined;\n\ninterface StagedResult {\n  rows: MockRow[];\n  numAffectedRows: bigint | undefined;\n}\n\nfunction toStagedResult(result: MockResult): StagedResult {\n  if (Array.isArray(result)) return { rows: result, numAffectedRows: undefined };\n  return {\n    rows: result.rows ?? [],\n    numAffectedRows:\n      result.numAffectedRows === undefined ? undefined : BigInt(result.numAffectedRows),\n  };\n}\n\n/** Controls and assertions for a {@link createKyselyMock} instance. */\nexport interface KyselyMock<DB> {\n  /** The mock Kysely instance to run queries against. */\n  db: Kysely<DB>;\n  /** Every recorded query, in execution order. */\n  executedQueries: ExecutedQuery[];\n  /** Recorded SELECT queries. */\n  selects: ExecutedQuery[];\n  /** Recorded INSERT queries. */\n  inserts: ExecutedQuery[];\n  /** Recorded UPDATE queries. */\n  updates: ExecutedQuery[];\n  /** Recorded DELETE queries. */\n  deletes: ExecutedQuery[];\n  /** Stage the rows the next query returns. */\n  enqueueResult: (result: MockResult) => void;\n  /** Stage the rows for several upcoming queries, consumed in order. */\n  enqueueResults: (...results: MockResult[]) => void;\n  /** Set a resolver that returns rows by inspecting each query. */\n  setQueryResolver: (resolver: QueryResolver) => void;\n  /** Run `fn` inside a real transaction and return its result. */\n  withTx: <R>(fn: (trx: Transaction<DB>) => Promise<R>) => Promise<R>;\n  /** Clear recorded queries and staged results. */\n  reset: () => void;\n  /** Same as {@link KyselyMock.reset}; enables `using` disposal. */\n  [Symbol.dispose]: () => void;\n}\n\nclass MockState {\n  readonly executed: ExecutedQuery[] = [];\n  private readonly queue: MockResult[] = [];\n  private resolver: QueryResolver | undefined;\n\n  enqueue(...results: MockResult[]): void {\n    this.queue.push(...results);\n  }\n\n  setResolver(resolver: QueryResolver): void {\n    this.resolver = resolver;\n  }\n\n  next(query: ExecutedQuery): StagedResult {\n    const resolved = this.resolver?.(query);\n    if (resolved !== undefined) return toStagedResult(resolved);\n    const queued = this.queue.shift();\n    return queued === undefined ? { rows: [], numAffectedRows: undefined } : toStagedResult(queued);\n  }\n\n  reset(): void {\n    this.executed.length = 0;\n    this.queue.length = 0;\n    this.resolver = undefined;\n  }\n}\n\nclass MockConnection implements DatabaseConnection {\n  constructor(private readonly state: MockState) {}\n\n  async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {\n    const query = toExecutedQuery(compiledQuery);\n    this.state.executed.push(query);\n    const { rows, numAffectedRows } = this.state.next(query);\n    return {\n      rows: rows as R[],\n      numAffectedRows: numAffectedRows ?? BigInt(rows.length),\n    };\n  }\n\n  streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {\n    throw new Error(\"createKyselyMock: streaming is not supported\");\n  }\n}\n\nclass MockDriver implements Driver {\n  constructor(private readonly state: MockState) {}\n\n  async init(): Promise<void> {}\n\n  async acquireConnection(): Promise<DatabaseConnection> {\n    return new MockConnection(this.state);\n  }\n\n  // No-ops so begin/commit/rollback never enter `executed` and pollute counts.\n  async beginTransaction(): Promise<void> {}\n  async commitTransaction(): Promise<void> {}\n  async rollbackTransaction(): Promise<void> {}\n\n  async releaseConnection(): Promise<void> {}\n  async destroy(): Promise<void> {}\n}\n\nfunction byKind(state: MockState, kind: OperationNodeKind): ExecutedQuery[] {\n  return state.executed.filter((query) => query.kind === kind);\n}\n\n/**\n * Create a mock Kysely instance for unit-testing code that runs Kysely queries.\n * Pass the namespace schema as the type argument, e.g.\n * `createKyselyMock<Namespace[\"main-db\"]>()`.\n * @returns A {@link KyselyMock} with the mock `db`, recorded queries, and result staging.\n */\nexport function createKyselyMock<DB = Record<string, never>>(): KyselyMock<DB> {\n  const state = new MockState();\n  const dialect: Dialect = {\n    createDriver: () => new MockDriver(state),\n    createQueryCompiler: () => new PostgresQueryCompiler(),\n    createAdapter: () => new PostgresAdapter(),\n    createIntrospector: (db) => new PostgresIntrospector(db),\n  };\n  const kysely = new Kysely<DB>({ dialect });\n\n  return {\n    db: kysely,\n    get executedQueries() {\n      return state.executed;\n    },\n    get selects() {\n      return byKind(state, \"SelectQueryNode\");\n    },\n    get inserts() {\n      return byKind(state, \"InsertQueryNode\");\n    },\n    get updates() {\n      return byKind(state, \"UpdateQueryNode\");\n    },\n    get deletes() {\n      return byKind(state, \"DeleteQueryNode\");\n    },\n    enqueueResult: (result) => state.enqueue(result),\n    enqueueResults: (...results) => state.enqueue(...results),\n    setQueryResolver: (resolver) => state.setResolver(resolver),\n    withTx: (fn) => kysely.transaction().execute(fn),\n    reset: () => state.reset(),\n    [Symbol.dispose]: () => state.reset(),\n  };\n}\n","/**\n * Kysely adapter for running migration scripts against PGlite.\n *\n * Accepts the PGlite client structurally so the SDK does not depend on\n * `@electric-sql/pglite`; users install it themselves as a devDependency.\n */\n\nimport {\n  type ColumnType,\n  CompiledQuery,\n  type DatabaseConnection,\n  type Dialect,\n  type Driver,\n  Kysely,\n  PostgresAdapter,\n  PostgresIntrospector,\n  PostgresQueryCompiler,\n  type QueryResult,\n  type TransactionSettings,\n} from \"kysely\";\n\n/** Result of a {@link PGliteClient.query} call. */\nexport interface PGliteQueryResult {\n  /** Rows returned by the statement. */\n  rows: unknown[];\n  /** Number of rows an INSERT/UPDATE/DELETE touched. */\n  affectedRows?: number;\n  /** Postgres command tag of the statement (`\"SELECT\"`, `\"INSERT\"`, ...). */\n  command?: string;\n  /** Row count reported alongside the command tag. */\n  rowCount?: number;\n}\n\n/**\n * The subset of a `@electric-sql/pglite` `PGlite` instance used by\n * {@link createKyselyPGlite}. Any client with a compatible `query`/`close`\n * pair works.\n */\nexport interface PGliteClient {\n  /** Run a single SQL statement with positional (`$1`, `$2`, ...) parameters. */\n  query(query: string, params?: unknown[]): Promise<PGliteQueryResult>;\n  /** Release the underlying database. Called by `db.destroy()`. */\n  close(): Promise<void>;\n}\n\nclass PGliteConnection implements DatabaseConnection {\n  readonly #client: PGliteClient;\n\n  constructor(client: PGliteClient) {\n    this.#client = client;\n  }\n\n  async executeQuery<R>(compiledQuery: CompiledQuery): Promise<QueryResult<R>> {\n    const result = await this.#client.query(compiledQuery.sql, [...compiledQuery.parameters]);\n    return {\n      rows: result.rows as R[],\n      numAffectedRows: BigInt(result.affectedRows ?? 0),\n    };\n  }\n\n  streamQuery(): AsyncIterableIterator<QueryResult<never>> {\n    throw new Error(\"createKyselyPGlite: streaming is not supported\");\n  }\n}\n\nclass PGliteDriver implements Driver {\n  readonly #client: PGliteClient;\n\n  constructor(client: PGliteClient) {\n    this.#client = client;\n  }\n\n  async init(): Promise<void> {}\n\n  async acquireConnection(): Promise<DatabaseConnection> {\n    return new PGliteConnection(this.#client);\n  }\n\n  async beginTransaction(\n    connection: DatabaseConnection,\n    settings: TransactionSettings,\n  ): Promise<void> {\n    const parts = settings.isolationLevel\n      ? [\"start transaction\", `isolation level ${settings.isolationLevel}`]\n      : [\"begin\"];\n    if (settings.accessMode) {\n      parts.push(settings.accessMode);\n    }\n    await connection.executeQuery(CompiledQuery.raw(parts.join(\" \")));\n  }\n\n  async commitTransaction(connection: DatabaseConnection): Promise<void> {\n    await connection.executeQuery(CompiledQuery.raw(\"commit\"));\n  }\n\n  async rollbackTransaction(connection: DatabaseConnection): Promise<void> {\n    await connection.executeQuery(CompiledQuery.raw(\"rollback\"));\n  }\n\n  async releaseConnection(): Promise<void> {}\n\n  async destroy(): Promise<void> {\n    await this.#client.close();\n  }\n}\n\ntype WritableAs<S, W> = [S] extends [W] ? W : [W] extends [S] ? S : W | Exclude<S, W>;\ntype UnmigratedColumn<C> =\n  C extends ColumnType<infer S, infer I, infer U>\n    ? ColumnType<S, WritableAs<S, I>, WritableAs<S, U>>\n    : C;\n\n/**\n * `DB` as its rows stand before the migration script has run: every column\n * accepts on insert and update whatever it can still hold on read.\n *\n * The generated `db.ts` types a column the migration makes required as\n * `ColumnType<T | null, T, T>`, and an enum whose values it narrows as\n * `ColumnType<Before, After, After>`, so `migrate.ts` cannot write a null\n * or a removed value into them — and neither can a test that has to stage\n * the rows the script converts. Type the PGlite instance with\n * `Unmigrated<Database>` to stage them; `main` still receives a\n * `Transaction<Database>`.\n * @example\n * ```typescript\n * const db = createKyselyPGlite<Unmigrated<Database>>(new PGlite());\n * await db.insertInto(\"User\").values({ name: \"a\", email: null }).execute();\n * await db.transaction().execute((trx) => main(trx));\n * ```\n */\nexport type Unmigrated<DB> = {\n  [T in keyof DB]: { [C in keyof DB[T]]: UnmigratedColumn<DB[T][C]> };\n};\n\n/**\n * Create a Kysely instance backed by a PGlite in-memory Postgres, for\n * executing a migration script's queries against real data in tests.\n * Pass the migration's schema as the type argument — wrapped in\n * {@link Unmigrated} so the test can stage the rows the script has not yet\n * backfilled: `createKyselyPGlite<Unmigrated<Database>>(new PGlite())`.\n *\n * PGlite runs full PostgreSQL while TailorDB supports a subset of it, so a\n * statement passing here can still be rejected by the platform; keep a\n * statement-level test (see `createKyselyMock`) alongside.\n * @param client - A `PGlite` instance from `@electric-sql/pglite`\n * @returns A Kysely instance that executes queries on the client and closes it on `destroy()`\n * @example\n * ```typescript\n * // migrations/0005/migrate.pglite.test.ts\n * import { PGlite } from \"@electric-sql/pglite\";\n * import { createKyselyPGlite, type Unmigrated } from \"@tailor-platform/sdk/vitest\";\n * import type { Database } from \"./db\";\n * import { main } from \"./migrate\";\n *\n * const db = createKyselyPGlite<Unmigrated<Database>>(new PGlite());\n * // create tables matching db.ts, insert rows, then:\n * await db.transaction().execute((trx) => main(trx));\n * ```\n */\nexport function createKyselyPGlite<DB = Record<string, never>>(client: PGliteClient): Kysely<DB> {\n  const dialect: Dialect = {\n    createAdapter: () => new PostgresAdapter(),\n    createDriver: () => new PGliteDriver(client),\n    createIntrospector: (db) => new PostgresIntrospector(db),\n    createQueryCompiler: () => new PostgresQueryCompiler(),\n  };\n  return new Kysely<DB>({ dialect });\n}\n","import { createBlockPlugin, createEnvironmentPlugin } from \"./plugin\";\nimport type { Plugin } from \"vitest/config\";\n\n/**\n * Creates Vitest plugins that emulate the Tailor Platform function runtime environment.\n *\n * **Beta:** This API may change in future releases.\n *\n * ## What it does\n *\n * 1. **Node.js module blocking** (transform hook) — Imports of `node:*` modules\n *    (and bare builtins like `crypto`, `fs`) in non-test source files are replaced\n *    with code that throws an error with a suggestion for the Web Standard API alternative.\n *    Test files are exempt and can use `node:*` freely. Test file patterns are read\n *    from the resolved Vitest config (`test.include`).\n *\n * 2. **Node.js globals removal** (environment) — Only globals available in the\n *    Tailor Platform runtime are kept (whitelist: ECMAScript standard, Web Standard APIs\n *    from bootstrap.js, platform mocks). All others (`Buffer`, `global`, `setImmediate`,\n *    `__dirname`, `__filename`, etc.) are removed.\n *\n * 3. **Platform API mocks** (environment) — All platform APIs are auto-injected with\n *    control objects: `mockTailordb`, `mockWorkflow`, `mockSecretmanager`,\n *    `mockAuthconnection`, `mockIdp`, `mockFile`, `mockIconv`, `mockAigateway`,\n *    `mockLogger`. Each\n *    provides response configuration, call recording, and reset.\n *\n * 4. **Environment resolution** — Rewrites `environment: \"tailor-runtime\"` to the\n *    absolute path of the bundled environment module via the config hook.\n *\n * ## Known limitations\n *\n * - **`process`** and **`require`** are NOT removed or blocked. Vitest's internal\n *   runner depends on them. On the real Tailor Platform runtime, they do not exist.\n * - **Dynamic `import()`** of bundled files bypasses the transform hook since\n *   those files are loaded through Node.js native loader.\n * ## Options\n *\n * - **`config`** — Path to `tailor.config.ts`. Loads `defineSecretManager()` values\n *   into `mockSecretmanager` so `getSecret()` returns the configured values.\n * @example\n * ```typescript\n * // vitest.config.ts\n * import { defineConfig } from \"vitest/config\";\n * import { tailorRuntime } from \"@tailor-platform/sdk/vitest\";\n *\n * export default defineConfig({\n *   plugins: [tailorRuntime({ config: \"./tailor.config.ts\" })],\n *   test: {\n *     environment: \"tailor-runtime\",\n *   },\n * });\n * ```\n * @param options - Optional configuration\n * @param options.config - Path to tailor.config.ts to load SecretManager values into mock\n * @returns Array of Vite plugins\n */\nexport function tailorRuntime(options?: { config?: string }): Plugin[] {\n  return [createBlockPlugin(), createEnvironmentPlugin(options)];\n}\n\nexport {\n  mockTailordb,\n  mockWorkflow,\n  mockSecretmanager,\n  mockAuthconnection,\n  mockIdp,\n  mockFile,\n  mockIconv,\n  mockAigateway,\n  mockLogger,\n  type MockAigatewayOptions,\n  type MockAuthconnectionOptions,\n  type MockFileOptions,\n  type MockIconvOptions,\n  type MockIdpOptions,\n  type MockLoggerOptions,\n  type MockSecretmanagerOptions,\n  type MockTailordbOptions,\n  type QueryBehavior,\n  type QueryMatch,\n  type QueryMatcher,\n} from \"./mock\";\n\nexport {\n  mockTailordbWithPGlite,\n  type ExecutedPGliteQuery,\n  type MockTailordbPGliteOptions,\n} from \"./mocks/tailordb-pglite\";\n\nexport { runWorkflowLocally, type RunWorkflowLocallyOptions } from \"./workflow-local\";\nexport { createKyselyMock, type KyselyMock, type ExecutedQuery } from \"./mock-kysely\";\nexport {\n  createKyselyPGlite,\n  type PGliteClient,\n  type PGliteQueryResult,\n  type Unmigrated,\n} from \"./pglite-kysely\";\n"],"mappings":"o3BAOA,SAAgB,gBAAgB,EAA4B,CAC1D,OAAO,EAAoB,CAAS,CACtC,CAOA,SAAgB,kBAAkB,EAA2B,CAC3D,OAAO,EAAsB,CAAS,CACxC,CCZA,MAAM,EAAuB,CAAC,kDAAkD,EAgB1E,EAAoB,IAAI,IAAI,CAChC,oBACA,yBACA,sBACF,CAAC,EAQK,EAAuB,IAAI,IAAI,gUAqDrC,CAAC,EAEK,EAAW,cACX,EAAU,mBAEhB,SAAS,kBAAkB,EAAuB,CAEhD,GADI,EAAqB,IAAI,CAAI,GAC7B,EAAK,SAAW,EAAG,MAAO,GAI9B,IAAM,EAAY,EAAK,GAEvB,OADI,IAAc,IAAA,IACX,EAAS,KAAK,CAAS,GAAK,EAAQ,KAAK,EAAK,MAAM,CAAC,CAAC,CAC/D,CAEA,SAAS,wBAAwB,EAAsB,EAAyB,CAI9E,IAAM,EAAU,KAAK,UAAU,CAAO,EAChC,EAAY,mBAAmB,EAAQ,IACvC,EAAY,4BAA4B,EAAQ,SAEtD,GAAI,EAAK,OAAS,yBAA0B,CAC1C,IAAM,EAAQ,EAAK,YAAc,CAAC,EAC5B,EAAkB,CAAC,EACzB,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAe,EAAK,UAAU,KAChC,UAAO,GAAiB,SAC5B,IAAI,IAAiB,UAAW,CAC9B,EAAM,KAAK,kBAAkB,EAAU,EAAE,EACzC,QACF,CAGA,GAAI,CAAC,kBAAkB,CAAY,EAAG,OAAO,EAC7C,EAAM,KAAK,gBAAgB,EAA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