@tailor-platform/sdk 1.46.0 → 1.47.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/dist/{actor-BmxQeMFP.d.mts → actor-jk4-f0yp.d.mts} +3 -3
  3. package/dist/{application-B4zVVNRS.mjs → application-C7H7y0hS.mjs} +66 -103
  4. package/dist/application-C7H7y0hS.mjs.map +1 -0
  5. package/dist/application-Csq5jxYP.mjs +4 -0
  6. package/dist/{brand-Ll48SMXe.mjs → brand-D-d15jx3.mjs} +1 -1
  7. package/dist/{brand-Ll48SMXe.mjs.map → brand-D-d15jx3.mjs.map} +1 -1
  8. package/dist/cli/index.mjs +36 -18
  9. package/dist/cli/index.mjs.map +1 -1
  10. package/dist/cli/lib.d.mts +6 -6
  11. package/dist/cli/lib.mjs +3 -3
  12. package/dist/cli/lib.mjs.map +1 -1
  13. package/dist/cli/skills.mjs.map +1 -1
  14. package/dist/{client-DTaArWQr.mjs → client-DCqdtFte.mjs} +1 -1
  15. package/dist/client-DbyKSN1F.mjs +1061 -0
  16. package/dist/client-DbyKSN1F.mjs.map +1 -0
  17. package/dist/configure/index.d.mts +4 -4
  18. package/dist/configure/index.mjs +8 -47
  19. package/dist/configure/index.mjs.map +1 -1
  20. package/dist/{crashreport-DGeGj9BF.mjs → crashreport-CNSw_BrJ.mjs} +2 -2
  21. package/dist/{crashreport-DGeGj9BF.mjs.map → crashreport-CNSw_BrJ.mjs.map} +1 -1
  22. package/dist/{crashreport-6mcMyWu4.mjs → crashreport-DXGFd16F.mjs} +1 -1
  23. package/dist/enum-constants-C3KSpsYj.mjs.map +1 -1
  24. package/dist/errors-wNQxQQBH.mjs.map +1 -1
  25. package/dist/{field-BY2vbJ8f.mjs → field-DLSIuMTu.mjs} +1 -1
  26. package/dist/{field-BY2vbJ8f.mjs.map → field-DLSIuMTu.mjs.map} +1 -1
  27. package/dist/file-utils-DjNi_3U_.mjs.map +1 -1
  28. package/dist/{index-DV-5OIEv.d.mts → index-BRvNi5q9.d.mts} +2 -2
  29. package/dist/{index-BBvPd9Uv.d.mts → index-BXyS7xKC.d.mts} +2 -2
  30. package/dist/{index-Dxe6alSZ.d.mts → index-BbOTbZFf.d.mts} +2 -2
  31. package/dist/{index-PB0otrDj.d.mts → index-DB8EapT-.d.mts} +7 -15
  32. package/dist/{index-B5_4Tzm2.d.mts → index-iy-hNfGp.d.mts} +2 -2
  33. package/dist/{interceptor-CrcDfLPq.mjs → interceptor-CBsqEWDK.mjs} +1 -1
  34. package/dist/{interceptor-CrcDfLPq.mjs.map → interceptor-CBsqEWDK.mjs.map} +1 -1
  35. package/dist/{job-BOvKyNdT.mjs → job-R5C2Hfcc.mjs} +2 -3
  36. package/dist/job-R5C2Hfcc.mjs.map +1 -0
  37. package/dist/kysely/index.mjs.map +1 -1
  38. package/dist/kysely-type-B8aRz_oC.mjs.map +1 -1
  39. package/dist/logger-DTNAMYGy.mjs.map +1 -1
  40. package/dist/mock-BP-9O5On.mjs +796 -0
  41. package/dist/mock-BP-9O5On.mjs.map +1 -0
  42. package/dist/multiline-e3IpANmS.mjs.map +1 -1
  43. package/dist/package-json-6Px8bDpG.mjs.map +1 -1
  44. package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
  45. package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
  46. package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
  47. package/dist/plugin/builtin/seed/index.d.mts +1 -1
  48. package/dist/plugin/index.d.mts +2 -2
  49. package/dist/plugin/index.mjs.map +1 -1
  50. package/dist/{repl-editor-BlT2dFtm.mjs → repl-editor-CZpLlOBj.mjs} +1 -1
  51. package/dist/{repl-editor-BlT2dFtm.mjs.map → repl-editor-CZpLlOBj.mjs.map} +1 -1
  52. package/dist/{runtime-B67skpW-.mjs → runtime-XjP6JMmP.mjs} +91 -10
  53. package/dist/runtime-XjP6JMmP.mjs.map +1 -0
  54. package/dist/seed/index.mjs.map +1 -1
  55. package/dist/seed-DrKY5yIF.mjs.map +1 -1
  56. package/dist/{service-CCgw66c6.mjs → service-obEU5gSM.mjs} +1 -1
  57. package/dist/{service-CCgw66c6.mjs.map → service-obEU5gSM.mjs.map} +1 -1
  58. package/dist/{tailor-db-field-Hx9OqPWY.d.mts → tailor-db-field-Bn8ZC5lK.d.mts} +1 -1
  59. package/dist/{schema-DBq6hr6h.mjs → tailordb-DjlNUV6u.mjs} +44 -4
  60. package/dist/tailordb-DjlNUV6u.mjs.map +1 -0
  61. package/dist/telemetry-DcL8Fsm_.mjs.map +1 -1
  62. package/dist/types-DoIG6Nij.mjs +5 -0
  63. package/dist/{types-Duhhsx3R.mjs → types-sir9UPht.mjs} +2 -2
  64. package/dist/{types-Duhhsx3R.mjs.map → types-sir9UPht.mjs.map} +1 -1
  65. package/dist/utils/test/index.d.mts +13 -4
  66. package/dist/utils/test/index.mjs +13 -4
  67. package/dist/utils/test/index.mjs.map +1 -1
  68. package/dist/vitest/environment.d.mts +12 -0
  69. package/dist/vitest/environment.mjs +44 -0
  70. package/dist/vitest/environment.mjs.map +1 -0
  71. package/dist/vitest/index.d.mts +345 -0
  72. package/dist/vitest/index.mjs +350 -0
  73. package/dist/vitest/index.mjs.map +1 -0
  74. package/dist/vitest/setup.d.mts +64 -0
  75. package/dist/vitest/setup.mjs +141 -0
  76. package/dist/vitest/setup.mjs.map +1 -0
  77. package/dist/{workflow.generated-DFljpJh7.d.mts → workflow.generated-i7PK4fg-.d.mts} +2 -2
  78. package/docs/cli/setup.md +1 -0
  79. package/docs/services/tailordb.md +43 -12
  80. package/docs/services/workflow.md +1 -6
  81. package/docs/testing.md +530 -243
  82. package/package.json +37 -10
  83. package/dist/application-B4zVVNRS.mjs.map +0 -1
  84. package/dist/application-Boa_11Nv.mjs +0 -4
  85. package/dist/client-BwXkoiMq.mjs +0 -16536
  86. package/dist/client-BwXkoiMq.mjs.map +0 -1
  87. package/dist/job-BOvKyNdT.mjs.map +0 -1
  88. package/dist/runtime-B67skpW-.mjs.map +0 -1
  89. package/dist/schema-DBq6hr6h.mjs.map +0 -1
  90. package/dist/types-BnphjkIJ.mjs +0 -5
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/vitest/blocked-modules.ts","../../src/vitest/plugin.ts","../../src/vitest/index.ts"],"sourcesContent":["/**\n * Blocked Node.js built-in modules and their Web Standard API alternatives.\n *\n * The Tailor Platform runtime only provides Web Standard APIs.\n * These Node.js modules are not available and should be replaced with\n * the suggested alternatives.\n */\nimport { builtinModules } from \"node:module\";\n\n// Suggestions keyed by bare specifier. Lookup also checks with \"node:\" prefix stripped.\nconst SUGGESTIONS: Record<string, string> = {\n crypto: \"Use the Web Crypto API (globalThis.crypto) instead.\",\n buffer: \"Use Uint8Array or ArrayBuffer instead.\",\n fs: \"File system access is not available in the Tailor Platform runtime.\",\n \"fs/promises\": \"File system access is not available in the Tailor Platform runtime.\",\n path: \"Use URL or URLPattern for path manipulation.\",\n http: \"Use the Fetch API (globalThis.fetch) for HTTP requests instead.\",\n https: \"Use the Fetch API (globalThis.fetch) for HTTPS requests instead.\",\n url: \"Use the URL and URLSearchParams Web APIs instead.\",\n util: \"Use Web Standard APIs instead.\",\n stream: \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n \"stream/web\": \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n events: \"Use EventTarget instead.\",\n zlib: \"Use CompressionStream and DecompressionStream Web APIs instead.\",\n querystring: \"Use URLSearchParams instead.\",\n string_decoder: \"Use TextDecoder instead.\",\n};\n\nconst BLOCKED_MODULES = new Set<string>();\nfor (const mod of builtinModules) {\n BLOCKED_MODULES.add(mod);\n BLOCKED_MODULES.add(`node:${mod}`);\n}\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 BLOCKED_MODULES.has(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 const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n const suggestion = SUGGESTIONS[bare];\n const base = `\"${specifier}\" is not available in the Tailor Platform runtime.`;\n return suggestion ? `${base} ${suggestion}` : base;\n}\n","import { 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 return ID_START.test(name[0] ?? \"\") && 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\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 const testConfig = (\n config as typeof config & {\n test?: HostFileTestConfig & {\n projects?: { test?: HostFileTestConfig }[];\n };\n }\n ).test;\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 (Array.isArray(value) ? value : value ? [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.sort((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/**\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 removes Vitest-dependent globals\n * (like `performance`) per-test via beforeEach/afterEach hooks.\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\n return {\n name: \"tailor-runtime-environment\",\n\n config(config) {\n const testConfig = config.test as\n | (Record<string, unknown> & {\n projects?: Record<string, unknown>[];\n setupFiles?: string | string[];\n })\n | undefined;\n\n // Rewrite environment name to absolute path at top-level\n let usesTailorRuntime = false;\n if (testConfig?.environment === ENVIRONMENT_NAME) {\n testConfig.environment = environmentPath;\n usesTailorRuntime = true;\n }\n\n // Rewrite in each project config\n if (testConfig?.projects) {\n for (const project of testConfig.projects) {\n const projectTest = project.test as Record<string, unknown> | undefined;\n if (projectTest?.environment === ENVIRONMENT_NAME) {\n projectTest.environment = environmentPath;\n usesTailorRuntime = true;\n }\n }\n }\n\n // Pass config path to setup.ts via env var (cross-process compatible).\n // Always clear first, then set only when tailor-runtime is actually\n // selected. This makes the env var deterministic across Vite config\n // reloads (watch mode, programmatic re-init): a stale value from a\n // prior iteration cannot make setup.ts load secrets from an old config.\n // The leading `__` marks this as plugin-private, so deleting any\n // pre-existing value is safe.\n delete process.env.__TAILOR_RUNTIME_CONFIG;\n if (options?.config && usesTailorRuntime) {\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 = (config.root as string | undefined) ?? process.cwd();\n const configAbsPath = resolve(configRoot, options.config);\n process.env.__TAILOR_RUNTIME_CONFIG = configAbsPath;\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 if (testConfig && typeof testConfig.setupFiles === \"string\") {\n testConfig.setupFiles = [testConfig.setupFiles];\n }\n\n return {\n test: {\n setupFiles: [setupPath],\n },\n };\n },\n };\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 + setup) — 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. `performance` is removed per-test\n * via beforeEach/afterEach since Vitest needs it during initialization.\n *\n * 3. **Platform API mocks** (environment) — All platform APIs are auto-injected with\n * control objects: `tailordbMock`, `workflowMock`, `secretmanagerMock`,\n * `authconnectionMock`, `idpMock`, `fileMock`, `iconvMock`. Each provides response\n * 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 (via `createImportMain()`) bypasses\n * the transform hook since those files are loaded through Node.js native loader.\n * ## Options\n *\n * - **`config`** — Path to `tailor.config.ts`. Loads `defineSecretManager()` values\n * into `secretmanagerMock` 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 tailordbMock,\n workflowMock,\n secretmanagerMock,\n authconnectionMock,\n idpMock,\n fileMock,\n iconvMock,\n} from \"./mock\";\n"],"mappings":";;;;;;;;;;;;;;AAUA,MAAM,cAAsC;CAC1C,QAAQ;CACR,QAAQ;CACR,IAAI;CACJ,eAAe;CACf,MAAM;CACN,MAAM;CACN,OAAO;CACP,KAAK;CACL,MAAM;CACN,QAAQ;CACR,cAAc;CACd,QAAQ;CACR,MAAM;CACN,aAAa;CACb,gBAAgB;CACjB;AAED,MAAM,kCAAkB,IAAI,KAAa;AACzC,KAAK,MAAM,OAAO,gBAAgB;CAChC,gBAAgB,IAAI,IAAI;CACxB,gBAAgB,IAAI,QAAQ,MAAM;;;;;;;AAQpC,SAAgB,gBAAgB,WAA4B;CAC1D,OAAO,gBAAgB,IAAI,UAAU;;;;;;;AAQvC,SAAgB,kBAAkB,WAA2B;CAE3D,MAAM,aAAa,YADN,UAAU,WAAW,QAAQ,GAAG,UAAU,MAAM,EAAE,GAAG;CAElE,MAAM,OAAO,IAAI,UAAU;CAC3B,OAAO,aAAa,GAAG,KAAK,GAAG,eAAe;;;;;AC/ChD,MAAM,uBAAuB,CAAC,mDAAmD;AAgBjF,MAAM,oBAAoB,IAAI,IAAI;CAChC;CACA;CACA;CACD,CAAC;AAQF,MAAM,uBAAuB,IAAI,IAAI;CAEnC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CAEA;CACA;CACD,CAAC;AAEF,MAAM,WAAW;AACjB,MAAM,UAAU;AAEhB,SAAS,kBAAkB,MAAuB;CAChD,IAAI,qBAAqB,IAAI,KAAK,EAAE,OAAO;CAC3C,IAAI,KAAK,WAAW,GAAG,OAAO;CAI9B,OAAO,SAAS,KAAK,KAAK,MAAM,GAAG,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jD,WAAW,aAAa,CAAC,WAAW,WAAW;GAGjD,OAAO,EACL,MAAM,EACJ,YAAY,CAAC,UAAU,EACxB,EACF;;EAEJ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnTH,SAAgB,cAAc,SAAyC;CACrE,OAAO,CAAC,mBAAmB,EAAE,wBAAwB,QAAQ,CAAC"}
@@ -0,0 +1,64 @@
1
+ /// <reference types="@tailor-platform/function-types" />
2
+ //#region src/vitest/setup.d.ts
3
+ type SavedGlobals = Record<string, PropertyDescriptor | undefined>;
4
+ /**
5
+ * Reference-counted lifecycle for blocked globals.
6
+ *
7
+ * Concurrent tests in the same Vitest worker (`test.concurrent`) interleave
8
+ * their beforeEach/afterEach hooks: a naive `let saved` shared across hooks
9
+ * would let one test's `afterEach` restore `performance` mid-execution of
10
+ * another test. Reference counting keeps the globals removed for the union
11
+ * of all overlapping test scopes — the property is removed on first entry
12
+ * and restored only when the last test exits.
13
+ * @returns Lifecycle hooks
14
+ */
15
+ declare function createBlockedGlobalsLifecycle(): {
16
+ enter: (globalObj: Record<string, unknown>, keys: readonly string[]) => void;
17
+ exit: (globalObj: Record<string, unknown>) => void;
18
+ readonly active: number;
19
+ };
20
+ /**
21
+ * Extract a vault store from a secrets-shaped value.
22
+ *
23
+ * `defineSecretManager()` returns `{ vaults, options, get, getAll }` (get/getAll
24
+ * are non-enumerable). When that shape is present, the actual vaults live
25
+ * under `.vaults`. Otherwise fall back to treating the object itself as the
26
+ * vault map (for plain object configs).
27
+ * @param secrets - Value from `appConfig.secrets` or `config.secrets`
28
+ * @returns Vault store, or null if the value is unusable
29
+ */
30
+ declare function extractVaultStore(secrets: unknown): Record<string, Record<string, string>> | null;
31
+ /**
32
+ * Load and parse secrets from a tailor.config.ts file.
33
+ *
34
+ * Returns a vault store on success, or `null` on any failure (missing config,
35
+ * import failure, missing/invalid secrets shape). Errors are swallowed so a
36
+ * misconfigured project still boots — the user can set secrets manually via
37
+ * `secretmanagerMock.setSecrets()`.
38
+ * @param configPath - Absolute path to tailor.config.ts
39
+ * @returns Vault store keyed by vault name, or null if unavailable
40
+ */
41
+ declare function loadSecretsFromConfig(configPath: string): Promise<Record<string, Record<string, string>> | null>;
42
+ /**
43
+ * Remove the given globals from `globalObj`, returning the descriptors that
44
+ * were actually deleted so `restoreBlockedGlobals` can put them back.
45
+ *
46
+ * Mirrors environment.ts: non-configurable properties are skipped instead of
47
+ * deleted, so `delete` never throws in strict-mode runtimes that lock them
48
+ * down. Only properties whose deletion actually happened are returned, so the
49
+ * caller restores nothing for the skipped case.
50
+ * @param globalObj - Target object (typically `globalThis`)
51
+ * @param keys - Property names to remove
52
+ * @returns Map of removed descriptors keyed by property name
53
+ */
54
+ declare function removeBlockedGlobals(globalObj: Record<string, unknown>, keys: readonly string[]): SavedGlobals;
55
+ /**
56
+ * Restore previously-removed globals onto `globalObj` from a `SavedGlobals`
57
+ * map produced by `removeBlockedGlobals`.
58
+ * @param globalObj - Target object (typically `globalThis`)
59
+ * @param saved - Descriptors to re-define
60
+ */
61
+ declare function restoreBlockedGlobals(globalObj: Record<string, unknown>, saved: SavedGlobals): void;
62
+ //#endregion
63
+ export { createBlockedGlobalsLifecycle, extractVaultStore, loadSecretsFromConfig, removeBlockedGlobals, restoreBlockedGlobals };
64
+ //# sourceMappingURL=setup.d.mts.map
@@ -0,0 +1,141 @@
1
+
2
+ import { l as secretmanagerMock, t as RUNTIME_FLAG_KEY } from "../mock-BP-9O5On.mjs";
3
+ import { pathToFileURL } from "node:url";
4
+ import { afterEach, beforeAll, beforeEach } from "vitest";
5
+
6
+ //#region src/vitest/setup.ts
7
+ /**
8
+ * Vitest setup file that removes Node.js globals which Vitest depends on
9
+ * but are not available in the Tailor Platform runtime.
10
+ *
11
+ * These globals cannot be removed in the environment's setup() because
12
+ * Vitest's runner needs them during initialization. By using beforeEach/afterEach,
13
+ * they are only removed during user test code execution.
14
+ *
15
+ * This file is auto-injected by tailorRuntime() but only activates when
16
+ * the tailor-runtime environment is active (detected via __tailorRuntimeActive,
17
+ * a flag set by injectMocks() during environment setup).
18
+ */
19
+ const BLOCKED_GLOBALS = ["performance"];
20
+ /**
21
+ * Reference-counted lifecycle for blocked globals.
22
+ *
23
+ * Concurrent tests in the same Vitest worker (`test.concurrent`) interleave
24
+ * their beforeEach/afterEach hooks: a naive `let saved` shared across hooks
25
+ * would let one test's `afterEach` restore `performance` mid-execution of
26
+ * another test. Reference counting keeps the globals removed for the union
27
+ * of all overlapping test scopes — the property is removed on first entry
28
+ * and restored only when the last test exits.
29
+ * @returns Lifecycle hooks
30
+ */
31
+ function createBlockedGlobalsLifecycle() {
32
+ let active = 0;
33
+ let saved = {};
34
+ return {
35
+ get active() {
36
+ return active;
37
+ },
38
+ enter(globalObj, keys) {
39
+ if (active === 0) saved = removeBlockedGlobals(globalObj, keys);
40
+ active++;
41
+ },
42
+ exit(globalObj) {
43
+ if (active === 0) return;
44
+ active--;
45
+ if (active === 0) {
46
+ restoreBlockedGlobals(globalObj, saved);
47
+ saved = {};
48
+ }
49
+ }
50
+ };
51
+ }
52
+ const lifecycle = createBlockedGlobalsLifecycle();
53
+ function isTailorRuntime() {
54
+ return RUNTIME_FLAG_KEY in globalThis;
55
+ }
56
+ /**
57
+ * Extract a vault store from a secrets-shaped value.
58
+ *
59
+ * `defineSecretManager()` returns `{ vaults, options, get, getAll }` (get/getAll
60
+ * are non-enumerable). When that shape is present, the actual vaults live
61
+ * under `.vaults`. Otherwise fall back to treating the object itself as the
62
+ * vault map (for plain object configs).
63
+ * @param secrets - Value from `appConfig.secrets` or `config.secrets`
64
+ * @returns Vault store, or null if the value is unusable
65
+ */
66
+ function extractVaultStore(secrets) {
67
+ if (!secrets || typeof secrets !== "object") return null;
68
+ const source = "vaults" in secrets && typeof secrets.vaults === "object" && secrets.vaults !== null ? secrets.vaults : secrets;
69
+ const store = {};
70
+ for (const [vaultName, vaultData] of Object.entries(source)) if (typeof vaultData === "object" && vaultData !== null) store[vaultName] = { ...vaultData };
71
+ return Object.keys(store).length > 0 ? store : null;
72
+ }
73
+ /**
74
+ * Load and parse secrets from a tailor.config.ts file.
75
+ *
76
+ * Returns a vault store on success, or `null` on any failure (missing config,
77
+ * import failure, missing/invalid secrets shape). Errors are swallowed so a
78
+ * misconfigured project still boots — the user can set secrets manually via
79
+ * `secretmanagerMock.setSecrets()`.
80
+ * @param configPath - Absolute path to tailor.config.ts
81
+ * @returns Vault store keyed by vault name, or null if unavailable
82
+ */
83
+ async function loadSecretsFromConfig(configPath) {
84
+ try {
85
+ const config = await import(pathToFileURL(configPath).href);
86
+ return extractVaultStore(config.default?.secrets ?? config.secrets);
87
+ } catch {
88
+ return null;
89
+ }
90
+ }
91
+ beforeAll(async () => {
92
+ if (!isTailorRuntime()) return;
93
+ const configPath = process.env.__TAILOR_RUNTIME_CONFIG;
94
+ if (!configPath) return;
95
+ const store = await loadSecretsFromConfig(configPath);
96
+ if (store) secretmanagerMock.setSecrets(store);
97
+ });
98
+ /**
99
+ * Remove the given globals from `globalObj`, returning the descriptors that
100
+ * were actually deleted so `restoreBlockedGlobals` can put them back.
101
+ *
102
+ * Mirrors environment.ts: non-configurable properties are skipped instead of
103
+ * deleted, so `delete` never throws in strict-mode runtimes that lock them
104
+ * down. Only properties whose deletion actually happened are returned, so the
105
+ * caller restores nothing for the skipped case.
106
+ * @param globalObj - Target object (typically `globalThis`)
107
+ * @param keys - Property names to remove
108
+ * @returns Map of removed descriptors keyed by property name
109
+ */
110
+ function removeBlockedGlobals(globalObj, keys) {
111
+ const removed = {};
112
+ for (const key of keys) {
113
+ const descriptor = Object.getOwnPropertyDescriptor(globalObj, key);
114
+ if (descriptor?.configurable) {
115
+ removed[key] = descriptor;
116
+ delete globalObj[key];
117
+ }
118
+ }
119
+ return removed;
120
+ }
121
+ /**
122
+ * Restore previously-removed globals onto `globalObj` from a `SavedGlobals`
123
+ * map produced by `removeBlockedGlobals`.
124
+ * @param globalObj - Target object (typically `globalThis`)
125
+ * @param saved - Descriptors to re-define
126
+ */
127
+ function restoreBlockedGlobals(globalObj, saved) {
128
+ for (const [key, descriptor] of Object.entries(saved)) if (descriptor) Object.defineProperty(globalObj, key, descriptor);
129
+ }
130
+ beforeEach(() => {
131
+ if (!isTailorRuntime()) return;
132
+ lifecycle.enter(globalThis, BLOCKED_GLOBALS);
133
+ });
134
+ afterEach(() => {
135
+ if (!isTailorRuntime()) return;
136
+ lifecycle.exit(globalThis);
137
+ });
138
+
139
+ //#endregion
140
+ export { createBlockedGlobalsLifecycle, extractVaultStore, loadSecretsFromConfig, removeBlockedGlobals, restoreBlockedGlobals };
141
+ //# sourceMappingURL=setup.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"setup.mjs","names":[],"sources":["../../src/vitest/setup.ts"],"sourcesContent":["/**\n * Vitest setup file that removes Node.js globals which Vitest depends on\n * but are not available in the Tailor Platform runtime.\n *\n * These globals cannot be removed in the environment's setup() because\n * Vitest's runner needs them during initialization. By using beforeEach/afterEach,\n * they are only removed during user test code execution.\n *\n * This file is auto-injected by tailorRuntime() but only activates when\n * the tailor-runtime environment is active (detected via __tailorRuntimeActive,\n * a flag set by injectMocks() during environment setup).\n */\nimport { pathToFileURL } from \"node:url\";\nimport { afterEach, beforeAll, beforeEach } from \"vitest\";\nimport { RUNTIME_FLAG_KEY, secretmanagerMock } from \"./mock\";\n\n// Globals that Vitest internals depend on but don't exist in the platform runtime.\n// Removed before each test, restored after.\nconst BLOCKED_GLOBALS = [\"performance\"] as const;\n\ntype SavedGlobals = Record<string, PropertyDescriptor | undefined>;\n\n/**\n * Reference-counted lifecycle for blocked globals.\n *\n * Concurrent tests in the same Vitest worker (`test.concurrent`) interleave\n * their beforeEach/afterEach hooks: a naive `let saved` shared across hooks\n * would let one test's `afterEach` restore `performance` mid-execution of\n * another test. Reference counting keeps the globals removed for the union\n * of all overlapping test scopes — the property is removed on first entry\n * and restored only when the last test exits.\n * @returns Lifecycle hooks\n */\nexport function createBlockedGlobalsLifecycle(): {\n enter: (globalObj: Record<string, unknown>, keys: readonly string[]) => void;\n exit: (globalObj: Record<string, unknown>) => void;\n readonly active: number;\n} {\n let active = 0;\n let saved: SavedGlobals = {};\n return {\n get active() {\n return active;\n },\n enter(globalObj, keys) {\n if (active === 0) saved = removeBlockedGlobals(globalObj, keys);\n active++;\n },\n exit(globalObj) {\n // Defensive guard — in practice every `enter` is paired with `exit`,\n // but a hook crash could desync the counter.\n if (active === 0) return;\n active--;\n if (active === 0) {\n restoreBlockedGlobals(globalObj, saved);\n saved = {};\n }\n },\n };\n}\n\nconst lifecycle = createBlockedGlobalsLifecycle();\n\nfunction isTailorRuntime(): boolean {\n return RUNTIME_FLAG_KEY in globalThis;\n}\n\n/**\n * Extract a vault store from a secrets-shaped value.\n *\n * `defineSecretManager()` returns `{ vaults, options, get, getAll }` (get/getAll\n * are non-enumerable). When that shape is present, the actual vaults live\n * under `.vaults`. Otherwise fall back to treating the object itself as the\n * vault map (for plain object configs).\n * @param secrets - Value from `appConfig.secrets` or `config.secrets`\n * @returns Vault store, or null if the value is unusable\n */\nexport function extractVaultStore(secrets: unknown): Record<string, Record<string, string>> | null {\n if (!secrets || typeof secrets !== \"object\") return null;\n\n const source =\n \"vaults\" in secrets &&\n typeof (secrets as { vaults?: unknown }).vaults === \"object\" &&\n (secrets as { vaults?: unknown }).vaults !== null\n ? ((secrets as { vaults: Record<string, unknown> }).vaults as Record<string, unknown>)\n : (secrets as Record<string, unknown>);\n\n const store: Record<string, Record<string, string>> = {};\n for (const [vaultName, vaultData] of Object.entries(source)) {\n if (typeof vaultData === \"object\" && vaultData !== null) {\n store[vaultName] = { ...(vaultData as Record<string, string>) };\n }\n }\n return Object.keys(store).length > 0 ? store : null;\n}\n\n/**\n * Load and parse secrets from a tailor.config.ts file.\n *\n * Returns a vault store on success, or `null` on any failure (missing config,\n * import failure, missing/invalid secrets shape). Errors are swallowed so a\n * misconfigured project still boots — the user can set secrets manually via\n * `secretmanagerMock.setSecrets()`.\n * @param configPath - Absolute path to tailor.config.ts\n * @returns Vault store keyed by vault name, or null if unavailable\n */\nexport async function loadSecretsFromConfig(\n configPath: string,\n): Promise<Record<string, Record<string, string>> | null> {\n try {\n // Convert to file URL so absolute Windows paths (e.g. \"C:\\...\") parse as\n // valid ESM specifiers.\n const config = await import(pathToFileURL(configPath).href);\n const appConfig = config.default;\n const secrets = appConfig?.secrets ?? config.secrets;\n return extractVaultStore(secrets);\n } catch {\n return null;\n }\n}\n\n// Load secrets from tailor.config.ts if config path is provided via env var\nbeforeAll(async () => {\n if (!isTailorRuntime()) return;\n const configPath = process.env.__TAILOR_RUNTIME_CONFIG;\n if (!configPath) return;\n\n const store = await loadSecretsFromConfig(configPath);\n if (store) {\n secretmanagerMock.setSecrets(store);\n }\n});\n\n/**\n * Remove the given globals from `globalObj`, returning the descriptors that\n * were actually deleted so `restoreBlockedGlobals` can put them back.\n *\n * Mirrors environment.ts: non-configurable properties are skipped instead of\n * deleted, so `delete` never throws in strict-mode runtimes that lock them\n * down. Only properties whose deletion actually happened are returned, so the\n * caller restores nothing for the skipped case.\n * @param globalObj - Target object (typically `globalThis`)\n * @param keys - Property names to remove\n * @returns Map of removed descriptors keyed by property name\n */\nexport function removeBlockedGlobals(\n globalObj: Record<string, unknown>,\n keys: readonly string[],\n): SavedGlobals {\n const removed: SavedGlobals = {};\n for (const key of keys) {\n const descriptor = Object.getOwnPropertyDescriptor(globalObj, key);\n if (descriptor?.configurable) {\n removed[key] = descriptor;\n delete globalObj[key];\n }\n }\n return removed;\n}\n\n/**\n * Restore previously-removed globals onto `globalObj` from a `SavedGlobals`\n * map produced by `removeBlockedGlobals`.\n * @param globalObj - Target object (typically `globalThis`)\n * @param saved - Descriptors to re-define\n */\nexport function restoreBlockedGlobals(\n globalObj: Record<string, unknown>,\n saved: SavedGlobals,\n): void {\n for (const [key, descriptor] of Object.entries(saved)) {\n if (descriptor) {\n Object.defineProperty(globalObj, key, descriptor);\n }\n }\n}\n\nbeforeEach(() => {\n if (!isTailorRuntime()) return;\n lifecycle.enter(globalThis as Record<string, unknown>, BLOCKED_GLOBALS);\n});\n\nafterEach(() => {\n if (!isTailorRuntime()) return;\n lifecycle.exit(globalThis as Record<string, unknown>);\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAM,kBAAkB,CAAC,cAAc;;;;;;;;;;;;AAevC,SAAgB,gCAId;CACA,IAAI,SAAS;CACb,IAAI,QAAsB,EAAE;CAC5B,OAAO;EACL,IAAI,SAAS;GACX,OAAO;;EAET,MAAM,WAAW,MAAM;GACrB,IAAI,WAAW,GAAG,QAAQ,qBAAqB,WAAW,KAAK;GAC/D;;EAEF,KAAK,WAAW;GAGd,IAAI,WAAW,GAAG;GAClB;GACA,IAAI,WAAW,GAAG;IAChB,sBAAsB,WAAW,MAAM;IACvC,QAAQ,EAAE;;;EAGf;;AAGH,MAAM,YAAY,+BAA+B;AAEjD,SAAS,kBAA2B;CAClC,OAAO,oBAAoB;;;;;;;;;;;;AAa7B,SAAgB,kBAAkB,SAAiE;CACjG,IAAI,CAAC,WAAW,OAAO,YAAY,UAAU,OAAO;CAEpD,MAAM,SACJ,YAAY,WACZ,OAAQ,QAAiC,WAAW,YACnD,QAAiC,WAAW,OACvC,QAAgD,SACjD;CAEP,MAAM,QAAgD,EAAE;CACxD,KAAK,MAAM,CAAC,WAAW,cAAc,OAAO,QAAQ,OAAO,EACzD,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,aAAa,EAAE,GAAI,WAAsC;CAGnE,OAAO,OAAO,KAAK,MAAM,CAAC,SAAS,IAAI,QAAQ;;;;;;;;;;;;AAajD,eAAsB,sBACpB,YACwD;CACxD,IAAI;EAGF,MAAM,SAAS,MAAM,OAAO,cAAc,WAAW,CAAC;EAGtD,OAAO,kBAFW,OAAO,SACE,WAAW,OAAO,QACZ;SAC3B;EACN,OAAO;;;AAKX,UAAU,YAAY;CACpB,IAAI,CAAC,iBAAiB,EAAE;CACxB,MAAM,aAAa,QAAQ,IAAI;CAC/B,IAAI,CAAC,YAAY;CAEjB,MAAM,QAAQ,MAAM,sBAAsB,WAAW;CACrD,IAAI,OACF,kBAAkB,WAAW,MAAM;EAErC;;;;;;;;;;;;;AAcF,SAAgB,qBACd,WACA,MACc;CACd,MAAM,UAAwB,EAAE;CAChC,KAAK,MAAM,OAAO,MAAM;EACtB,MAAM,aAAa,OAAO,yBAAyB,WAAW,IAAI;EAClE,IAAI,YAAY,cAAc;GAC5B,QAAQ,OAAO;GACf,OAAO,UAAU;;;CAGrB,OAAO;;;;;;;;AAST,SAAgB,sBACd,WACA,OACM;CACN,KAAK,MAAM,CAAC,KAAK,eAAe,OAAO,QAAQ,MAAM,EACnD,IAAI,YACF,OAAO,eAAe,WAAW,KAAK,WAAW;;AAKvD,iBAAiB;CACf,IAAI,CAAC,iBAAiB,EAAE;CACxB,UAAU,MAAM,YAAuC,gBAAgB;EACvE;AAEF,gBAAgB;CACd,IAAI,CAAC,iBAAiB,EAAE;CACxB,UAAU,KAAK,WAAsC;EACrD"}
@@ -1,5 +1,5 @@
1
1
  /// <reference types="@tailor-platform/function-types" />
2
- import { A as RelationType, Bt as InferredAttributeMap, D as DefinedDBFieldMetadata, Dt as ArrayFieldOutput, E as DBFieldMetadata, F as AuthConfig, Ft as FieldValidateInput, Ht as TailorUser, It as Validators, Jt as output, M as TailorDBServiceInput, Mt as FieldOutput, O as GqlOperationsConfig, Pt as TailorToTs, Wt as InferFieldsOutput, Y as TailorField, c as PluginConfigs, ht as BuiltinIdP, i as TailorDBType$1, j as SerialConfig, jt as FieldOptions, k as IndexDef, kt as EnumValue, qt as Prettify, r as TailorDBField$1, t as TailorAnyDBField$1 } from "./tailor-db-field-Hx9OqPWY.mjs";
2
+ import { A as RelationType, Bt as InferredAttributeMap, D as DefinedDBFieldMetadata, Dt as ArrayFieldOutput, E as DBFieldMetadata, F as AuthConfig, Ft as FieldValidateInput, Ht as TailorUser, It as Validators, Jt as output, M as TailorDBServiceInput, Mt as FieldOutput, O as GqlOperationsConfig, Pt as TailorToTs, Wt as InferFieldsOutput, Y as TailorField, c as PluginConfigs, ht as BuiltinIdP, i as TailorDBType$1, j as SerialConfig, jt as FieldOptions, k as IndexDef, kt as EnumValue, qt as Prettify, r as TailorDBField$1, t as TailorAnyDBField$1 } from "./tailor-db-field-Bn8ZC5lK.mjs";
3
3
  import { NonEmptyObject } from "type-fest";
4
4
  import { StandardSchemaV1 } from "@standard-schema/spec";
5
5
 
@@ -1207,4 +1207,4 @@ type ConcurrencyPolicy = {
1207
1207
  };
1208
1208
  //#endregion
1209
1209
  export { PermissionCondition as A, IdPInput as C, TailorDBInstance as D, TailorDBField as E, AllowedValues as F, AllowedValuesOutput as I, TailorTypePermission as M, unsafeAllowAllGqlPermission as N, TailorDBType as O, unsafeAllowAllTypePermission as P, IdPGqlOperationsInput as S, TailorAnyDBType as T, IdPExternalConfig as _, ExecutorServiceInput as a, IdPEmailConfig as b, ResolverServiceInput as c, StaticWebsiteConfig as d, StaticWebsiteDefinitionBrand as f, IdPConfig as g, SecretsDefinitionBrand as h, ExecutorServiceConfig as i, TailorTypeGqlPermission as j, db as k, WorkflowServiceConfig as l, SecretsConfig as m, RetryPolicy as n, ResolverExternalConfig as o, StaticWebsiteInput as p, AppConfig as r, ResolverServiceConfig as s, ConcurrencyPolicy as t, WorkflowServiceInput as u, IdPUserField as v, TailorAnyDBField as w, IdPGqlOperations as x, IdpDefinitionBrand as y };
1210
- //# sourceMappingURL=workflow.generated-DFljpJh7.d.mts.map
1210
+ //# sourceMappingURL=workflow.generated-i7PK4fg-.d.mts.map
package/docs/cli/setup.md CHANGED
@@ -72,6 +72,7 @@ tailor-sdk setup github [options]
72
72
  | `--organization-id <ORGANIZATION_ID>` | `-o` | Organization ID | Yes | - |
73
73
  | `--folder-id <FOLDER_ID>` | `-f` | Folder ID | Yes | - |
74
74
  | `--dir <DIR>` | `-d` | App directory (for monorepo setups) | No | `"."` |
75
+ | `--with-plan` | `-p` | Include plan job for PR previews | No | `false` |
75
76
 
76
77
  <!-- politty:command:setup github:options:end -->
77
78
 
@@ -62,18 +62,19 @@ db.type("User", "User in the system", {
62
62
 
63
63
  ## Field Types
64
64
 
65
- | Method | TailorDB | TypeScript |
66
- | ------------------------------- | -------- | -------------- |
67
- | `db.string()` | String | string |
68
- | `db.int()` | Integer | number |
69
- | `db.float()` | Float | number |
70
- | `db.bool()` | Boolean | boolean |
71
- | `db.date()` | Date | string |
72
- | `db.datetime()` | DateTime | string \| Date |
73
- | `db.time()` | Time | string |
74
- | `db.uuid()` | UUID | string |
75
- | [`db.enum()`](#enum-fields) | Enum | string |
76
- | [`db.object()`](#object-fields) | Nested | object |
65
+ | Method | TailorDB | TypeScript |
66
+ | --------------------------------- | -------- | -------------- |
67
+ | `db.string()` | String | string |
68
+ | `db.int()` | Integer | number |
69
+ | `db.float()` | Float | number |
70
+ | [`db.decimal()`](#decimal-fields) | Decimal | string |
71
+ | `db.bool()` | Boolean | boolean |
72
+ | `db.date()` | Date | string |
73
+ | `db.datetime()` | DateTime | string \| Date |
74
+ | `db.time()` | Time | string |
75
+ | `db.uuid()` | UUID | string |
76
+ | [`db.enum()`](#enum-fields) | Enum | string |
77
+ | [`db.object()`](#object-fields) | Nested | object |
77
78
 
78
79
  ### Optional and Array Fields
79
80
 
@@ -83,6 +84,36 @@ db.string({ array: true });
83
84
  db.string({ optional: true, array: true });
84
85
  ```
85
86
 
87
+ ### Decimal Fields
88
+
89
+ Decimal fields are stored as strings to preserve precision. The optional `scale`
90
+ parameter sets the number of digits after the decimal point and must be an
91
+ integer between 0 and 12. When `scale` is omitted, the platform default of 6 is
92
+ used.
93
+
94
+ ```typescript
95
+ // Default scale (6 decimal places)
96
+ db.decimal();
97
+
98
+ // Custom scale (2 decimal places)
99
+ db.decimal({ scale: 2 });
100
+
101
+ // Optional with custom scale
102
+ db.decimal({ scale: 4, optional: true });
103
+ ```
104
+
105
+ Values are rounded half-up to fit the configured scale before being stored.
106
+ Negative values follow the same rule based on absolute magnitude:
107
+
108
+ | Input | Scale | Stored |
109
+ | ------------- | ----- | ------------ |
110
+ | `"1.234"` | 2 | `"1.23"` |
111
+ | `"1.235"` | 2 | `"1.24"` |
112
+ | `"-1.235"` | 2 | `"-1.24"` |
113
+ | `"1.5"` | 0 | `"2"` |
114
+ | `"1.123456"` | 6 | `"1.123456"` |
115
+ | `"1.1234567"` | 6 | `"1.123457"` |
116
+
86
117
  ### Enum Fields
87
118
 
88
119
  ```typescript
@@ -106,9 +106,6 @@ import { sendNotification } from "./jobs/send-notification";
106
106
  export const mainJob = createWorkflowJob({
107
107
  name: "main-job",
108
108
  body: async (input: { customerId: string }) => {
109
- // You can write `await` for type-safety in your source.
110
- // During deployment bundling, job.trigger() calls are transformed to a synchronous
111
- // runtime call and `await` is removed.
112
109
  const customer = await fetchCustomer.trigger({
113
110
  customerId: input.customerId,
114
111
  });
@@ -121,8 +118,6 @@ export const mainJob = createWorkflowJob({
121
118
  });
122
119
  ```
123
120
 
124
- **Important:** On the Tailor runtime, job triggers are executed synchronously. This means `Promise.all([jobA.trigger(), jobB.trigger()])` will not run jobs in parallel.
125
-
126
121
  ### Deterministic Execution Requirement
127
122
 
128
123
  Workflow jobs use a **suspend/resume execution model**. When a job calls `.trigger()`, the runtime suspends the current job, executes the triggered job, and then **re-executes the calling job from the beginning** with cached results from previous triggers.
@@ -308,7 +303,7 @@ export default createResolver({
308
303
  });
309
304
  ```
310
305
 
311
- Wait points can be imported and used in any file (workflow jobs, resolvers, executors). For local testing, see [Testing Wait Points](../testing.md#testing-wait-points).
306
+ Wait points can be imported and used in any file (workflow jobs, resolvers, executors). For local testing, see [Jobs that wait on approval](../testing.md#jobs-that-wait-on-approval) in the testing guide.
312
307
 
313
308
  ## Retry Policy
314
309