@tailor-platform/sdk 1.35.2 → 1.37.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/dist/application-ILhZq_oW.mjs +4 -0
  3. package/dist/{application-BnJRroGX.mjs → application-qRGMV8Tr.mjs} +150 -35
  4. package/dist/application-qRGMV8Tr.mjs.map +1 -0
  5. package/dist/{brand-0SscafcY.mjs → brand-D-d15jx3.mjs} +1 -1
  6. package/dist/{brand-0SscafcY.mjs.map → brand-D-d15jx3.mjs.map} +1 -1
  7. package/dist/cli/index.mjs +247 -12
  8. package/dist/cli/index.mjs.map +1 -1
  9. package/dist/cli/lib.d.mts +190 -6
  10. package/dist/cli/lib.mjs +7 -7
  11. package/dist/{client-BmQP4kKS.mjs → client-424n_3T9.mjs} +1 -1
  12. package/dist/{client-CA2NM_4R.mjs → client-DllDLYmZ.mjs} +28 -11
  13. package/dist/client-DllDLYmZ.mjs.map +1 -0
  14. package/dist/configure/index.d.mts +5 -4
  15. package/dist/configure/index.mjs +42 -23
  16. package/dist/configure/index.mjs.map +1 -1
  17. package/dist/{crash-report-CPkI2-cp.mjs → crash-report-CDQ2JvgR.mjs} +4 -4
  18. package/dist/{crash-report-CPkI2-cp.mjs.map → crash-report-CDQ2JvgR.mjs.map} +1 -1
  19. package/dist/{crash-report-Bd2T8BhU.mjs → crash-report-aHnky_xH.mjs} +1 -1
  20. package/dist/{enum-constants-DI85-fPE.mjs → enum-constants-Dx82rSjf.mjs} +1 -1
  21. package/dist/{enum-constants-DI85-fPE.mjs.map → enum-constants-Dx82rSjf.mjs.map} +1 -1
  22. package/dist/env-04IQXqsl.d.mts +30 -0
  23. package/dist/{file-utils-C4rXlOVt.mjs → file-utils-DeWpvq3T.mjs} +1 -1
  24. package/dist/{file-utils-C4rXlOVt.mjs.map → file-utils-DeWpvq3T.mjs.map} +1 -1
  25. package/dist/{index-DTJkkO-t.d.mts → index-BUT18Kak.d.mts} +2 -2
  26. package/dist/{index--9iVDOXn.d.mts → index-BVJQLjyN.d.mts} +98 -12
  27. package/dist/{index-D4pBPp65.d.mts → index-C3kcXHXJ.d.mts} +2 -2
  28. package/dist/{index-niQ9Qblw.d.mts → index-CeS4FA9o.d.mts} +2 -2
  29. package/dist/{index-qVqjEYnr.d.mts → index-DnIg_LfT.d.mts} +2 -2
  30. package/dist/{interceptor-f7slMkCC.mjs → interceptor-dSNiQq71.mjs} +1 -1
  31. package/dist/{interceptor-f7slMkCC.mjs.map → interceptor-dSNiQq71.mjs.map} +1 -1
  32. package/dist/{job-CPKYCk_e.mjs → job-DkAklmE4.mjs} +2 -2
  33. package/dist/{job-CPKYCk_e.mjs.map → job-DkAklmE4.mjs.map} +1 -1
  34. package/dist/{kysely-type-DtnNdHn3.mjs → kysely-type-CwtvQuxh.mjs} +1 -1
  35. package/dist/{kysely-type-DtnNdHn3.mjs.map → kysely-type-CwtvQuxh.mjs.map} +1 -1
  36. package/dist/{logger-qz-Y4sBV.mjs → logger-C8qBDCKO.mjs} +1 -1
  37. package/dist/{logger-qz-Y4sBV.mjs.map → logger-C8qBDCKO.mjs.map} +1 -1
  38. package/dist/package-json--6dmp6-h.mjs +4 -0
  39. package/dist/{package-json-CfUqjJaQ.mjs → package-json-BHViVisJ.mjs} +1 -1
  40. package/dist/{package-json-CfUqjJaQ.mjs.map → package-json-BHViVisJ.mjs.map} +1 -1
  41. package/dist/plugin/builtin/enum-constants/index.d.mts +1 -1
  42. package/dist/plugin/builtin/enum-constants/index.mjs +1 -1
  43. package/dist/plugin/builtin/file-utils/index.d.mts +1 -1
  44. package/dist/plugin/builtin/file-utils/index.mjs +1 -1
  45. package/dist/plugin/builtin/kysely-type/index.d.mts +1 -1
  46. package/dist/plugin/builtin/kysely-type/index.mjs +1 -1
  47. package/dist/plugin/builtin/seed/index.d.mts +1 -1
  48. package/dist/plugin/builtin/seed/index.mjs +1 -1
  49. package/dist/plugin/index.d.mts +2 -1
  50. package/dist/{plugin-D8hKE6rZ.d.mts → plugin-D6P4g_2L.d.mts} +17 -36
  51. package/dist/{runtime-D4O-RfcH.mjs → runtime-D9ejnCm6.mjs} +788 -109
  52. package/dist/runtime-D9ejnCm6.mjs.map +1 -0
  53. package/dist/{schema-D27cW0Ca.mjs → schema-CnwUqPyM.mjs} +4 -361
  54. package/dist/schema-CnwUqPyM.mjs.map +1 -0
  55. package/dist/{seed-BZIFDG27.mjs → seed-DrbB1VXd.mjs} +1 -1
  56. package/dist/{seed-BZIFDG27.mjs.map → seed-DrbB1VXd.mjs.map} +1 -1
  57. package/dist/telemetry-4IOPW6wE.mjs +4 -0
  58. package/dist/{telemetry-CREcGK8y.mjs → telemetry-DwHuiNiR.mjs} +2 -2
  59. package/dist/{telemetry-CREcGK8y.mjs.map → telemetry-DwHuiNiR.mjs.map} +1 -1
  60. package/dist/types-B9ZMosul.mjs +372 -0
  61. package/dist/types-B9ZMosul.mjs.map +1 -0
  62. package/dist/types-C45jRrCM.mjs +4 -0
  63. package/dist/utils/test/index.d.mts +2 -2
  64. package/dist/utils/test/index.mjs +1 -1
  65. package/dist/{workflow.generated-DMt8PNVd.d.mts → workflow.generated-Bj_DVqGh.d.mts} +212 -4
  66. package/docs/services/auth.md +6 -5
  67. package/docs/services/executor.md +5 -12
  68. package/docs/services/idp.md +50 -0
  69. package/docs/services/resolver.md +6 -13
  70. package/docs/services/secret.md +25 -0
  71. package/docs/services/workflow.md +4 -3
  72. package/package.json +7 -6
  73. package/dist/application-BnJRroGX.mjs.map +0 -1
  74. package/dist/application-mGasp_EX.mjs +0 -4
  75. package/dist/client-CA2NM_4R.mjs.map +0 -1
  76. package/dist/package-json-D5Km1jjt.mjs +0 -4
  77. package/dist/runtime-D4O-RfcH.mjs.map +0 -1
  78. package/dist/schema-D27cW0Ca.mjs.map +0 -1
  79. package/dist/telemetry-C508zIi1.mjs +0 -4
@@ -1 +1 @@
1
- {"version":3,"file":"crash-report-CPkI2-cp.mjs","names":[],"sources":["../src/cli/crash-report/config.ts","../src/cli/crash-report/writer.ts","../src/cli/crash-report/sender.ts","../src/cli/crash-report/sanitize.ts","../src/cli/crash-report/report.ts","../src/cli/crash-report/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .sort()\n .reverse();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n fs.mkdirSync(dir, { recursive: true });\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n fs.writeFileSync(filePath, content, \"utf-8\");\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { sanitizeArgv, sanitizeMessage, sanitizeStackTrace } from \"./sanitize\";\n\nexport type ErrorType = \"uncaughtException\" | \"unhandledRejection\" | \"handledError\";\n\nexport interface CrashReport {\n id: string;\n timestamp: string;\n sdkVersion: string;\n nodeVersion: string;\n osPlatform: string;\n osRelease: string;\n arch: string;\n command: string;\n argv: string[];\n errorName: string;\n errorMessage: string;\n stackTrace: string;\n errorType: ErrorType;\n userId: string | null;\n userEmail: string | null;\n}\n\ninterface BuildCrashReportOptions {\n error: unknown;\n sdkVersion: string;\n errorType: ErrorType;\n}\n\n// Maximum subcommand depth to keep (e.g., \"tailordb migrate generate\" = 3 tokens).\n// Positional arguments beyond this are potentially sensitive user input.\n// Accepted trade-off: plain-text positional args that don't match known patterns\n// (UUIDs, hex tokens, emails, paths) pass through to `command` and `argv`.\n// Full redaction would require embedding the CLI command tree here, which is fragile.\nconst MAX_COMMAND_TOKENS = 3;\n\n/**\n * Parse the command name from process.argv.\n * Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.\n * @returns Parsed command string\n */\nfunction parseCommand(): string {\n const args = process.argv.slice(2);\n const commandParts: string[] = [];\n for (const arg of args) {\n if (arg.startsWith(\"-\") || commandParts.length >= MAX_COMMAND_TOKENS) break;\n commandParts.push(arg);\n }\n return commandParts.join(\" \") || \"<unknown>\";\n}\n\n/**\n * Build a CrashReport data structure from an error and context.\n * All sensitive data is sanitized before inclusion.\n * @param options - Error, SDK version, and crash type\n * @returns Sanitized crash report\n */\nexport function buildCrashReport(options: BuildCrashReportOptions): CrashReport {\n const { error, sdkVersion, errorType } = options;\n\n const isError = error instanceof Error;\n const rawMessage = isError ? error.message : String(error);\n const rawStack = isError && error.stack ? error.stack : \"\";\n const errorName = isError ? error.name : \"UnknownError\";\n\n const currentUser = readCurrentUser();\n\n return {\n id: crypto.randomUUID(),\n timestamp: new Date().toISOString(),\n sdkVersion,\n nodeVersion: process.version,\n osPlatform: process.platform,\n osRelease: os.release(),\n arch: process.arch,\n command: sanitizeMessage(parseCommand()),\n argv: sanitizeArgv(process.argv),\n errorName,\n errorMessage: sanitizeMessage(rawMessage),\n stackTrace: sanitizeStackTrace(rawStack),\n errorType,\n userId: currentUser,\n userEmail: currentUser,\n };\n}\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user email, or null if unavailable\n */\nfunction readCurrentUser(): string | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as { current_user?: string | null };\n return raw?.current_user ?? null;\n } catch {\n return null;\n }\n}\n","import { logger } from \"@/cli/shared/logger\";\nimport { readPackageJson } from \"@/cli/shared/package-json\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor-sdk crash-report send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n // Lazy import: client.ts pulls in heavy dependencies (OAuth2, Connect, Protobuf)\n // that should not be loaded on the startup critical path via initCrashReporting().\n const { userAgent } = await import(\"@/cli/shared/client\");\n const ua = await userAgent();\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;AAC1D,KAAI,KACF,QAAO;EACL,cAAc;EACd,eAAe;EACf,UAAU;EACX;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3,"file":"crash-report-CDQ2JvgR.mjs","names":[],"sources":["../src/cli/crash-report/config.ts","../src/cli/crash-report/writer.ts","../src/cli/crash-report/sender.ts","../src/cli/crash-report/sanitize.ts","../src/cli/crash-report/report.ts","../src/cli/crash-report/index.ts"],"sourcesContent":["import * as path from \"pathe\";\nimport { isCI } from \"std-env\";\nimport { xdgConfig } from \"xdg-basedir\";\n\nexport interface CrashReportConfig {\n readonly localEnabled: boolean;\n readonly remoteEnabled: boolean;\n readonly localDir: string;\n}\n\n/**\n * Parse crash report configuration from environment variables.\n * Local crash log writing is enabled by default (opt-out via TAILOR_CRASH_REPORTS_LOCAL=off).\n * Remote sending is disabled by default (opt-in via TAILOR_CRASH_REPORTS_REMOTE=on).\n * Both are auto-disabled in CI environments.\n * @returns Crash report configuration\n */\nexport function parseCrashReportConfig(): CrashReportConfig {\n if (isCI) {\n return {\n localEnabled: false,\n remoteEnabled: false,\n localDir: \"\",\n };\n }\n\n const localEnabled = (process.env.TAILOR_CRASH_REPORTS_LOCAL ?? \"on\").toLowerCase() !== \"off\";\n const remoteEnabled = (process.env.TAILOR_CRASH_REPORTS_REMOTE ?? \"off\").toLowerCase() === \"on\";\n const localDir = xdgConfig ? path.join(xdgConfig, \"tailor-platform\", \"crash-reports\") : \"\";\n\n return {\n localEnabled: localEnabled && localDir !== \"\",\n remoteEnabled,\n localDir,\n };\n}\n","import * as fs from \"node:fs\";\nimport * as path from \"pathe\";\nimport type { CrashReport } from \"./report\";\n\nconst MAX_CRASH_FILES = 10;\n\n/** Marker line that separates human-readable content from the JSON footer. */\nexport const JSON_FOOTER_MARKER = \"--- JSON ---\";\n\n/** File extension for crash log files. */\nexport const CRASH_LOG_EXTENSION = \".crash.log\";\n\n/**\n * Format a CrashReport as human-readable text for local crash log files.\n * @param report - Crash report to format\n * @returns Formatted text content\n */\nexport function formatCrashReport(report: CrashReport): string {\n const lines = [\n `Crash Report: ${report.id}`,\n `Timestamp: ${report.timestamp}`,\n `Error Type: ${report.errorType}`,\n \"\",\n \"--- Environment ---\",\n `SDK Version: ${report.sdkVersion}`,\n `Node Version: ${report.nodeVersion}`,\n `OS: ${report.osPlatform} ${report.osRelease}`,\n `Arch: ${report.arch}`,\n \"\",\n \"--- Command ---\",\n `Command: ${report.command}`,\n `Arguments: ${JSON.stringify(report.argv)}`,\n \"\",\n \"--- Error ---\",\n `Name: ${report.errorName}`,\n `Message: ${report.errorMessage}`,\n \"\",\n \"--- Stack Trace ---\",\n report.stackTrace || \"(no stack trace available)\",\n \"\",\n JSON_FOOTER_MARKER,\n JSON.stringify(report),\n \"\",\n ];\n return lines.join(\"\\n\");\n}\n\n/**\n * Generate a filename for a crash log file.\n * Format: {timestamp}-{shortId}.crash.log\n * @param report - Crash report to generate filename for\n * @returns Filename string\n */\nfunction generateFilename(report: CrashReport): string {\n const safeTimestamp = report.timestamp.replace(/[:.]/g, \"-\");\n const shortId = report.id.slice(0, 8);\n return `${safeTimestamp}-${shortId}${CRASH_LOG_EXTENSION}`;\n}\n\n/**\n * Remove old crash log files, keeping only the most recent ones.\n * @param dir - Crash log directory\n */\nfunction cleanupOldFiles(dir: string): void {\n try {\n const files = fs\n .readdirSync(dir)\n .filter((f) => f.endsWith(CRASH_LOG_EXTENSION))\n .sort()\n .reverse();\n\n for (const file of files.slice(MAX_CRASH_FILES)) {\n fs.unlinkSync(path.join(dir, file));\n }\n } catch {\n // Best-effort cleanup, ignore errors\n }\n}\n\n/**\n * Write a crash report to a local file.\n * Creates the directory if it doesn't exist. Keeps only the last 10 crash files.\n * Never throws - returns the file path on success or undefined on failure.\n * @param report - Crash report to write\n * @param dir - Directory to write the crash log file to\n * @returns File path on success, undefined on failure\n */\nexport function writeCrashReport(report: CrashReport, dir: string): string | undefined {\n try {\n fs.mkdirSync(dir, { recursive: true });\n\n const filename = generateFilename(report);\n const filePath = path.join(dir, filename);\n const content = formatCrashReport(report);\n\n fs.writeFileSync(filePath, content, \"utf-8\");\n cleanupOldFiles(dir);\n\n return filePath;\n } catch {\n return undefined;\n }\n}\n","import type { CrashReport } from \"./report\";\n\nconst SEND_TIMEOUT_MS = 5000;\nconst PRODUCTION_ENDPOINT = \"https://sdk-error-tracking-926vh9t4cl.erp.dev/query\";\n\nconst SUBMIT_MUTATION = `\nmutation SubmitCrashReport(\n $id: String!\n $timestamp: String!\n $sdkVersion: String!\n $nodeVersion: String!\n $osPlatform: String!\n $osRelease: String!\n $arch: String!\n $command: String!\n $argv: [String]\n $errorName: String!\n $errorMessage: String!\n $stackTrace: String\n $errorType: String!\n $userId: String\n $userEmail: String\n) {\n submitCrashReport(\n id: $id\n timestamp: $timestamp\n sdkVersion: $sdkVersion\n nodeVersion: $nodeVersion\n osPlatform: $osPlatform\n osRelease: $osRelease\n arch: $arch\n command: $command\n argv: $argv\n errorName: $errorName\n errorMessage: $errorMessage\n stackTrace: $stackTrace\n errorType: $errorType\n userId: $userId\n userEmail: $userEmail\n ) {\n success\n }\n}`;\n\n/**\n * Send a crash report to the remote endpoint via GraphQL mutation.\n * Best-effort: never throws, returns boolean success.\n * @param report - Crash report to send\n * @param ua - User-Agent header value\n * @returns true if the request succeeded, false otherwise\n */\nexport async function sendCrashReport(report: CrashReport, ua: string): Promise<boolean> {\n try {\n const endpoint = process.env.TAILOR_CRASH_REPORT_ENDPOINT || PRODUCTION_ENDPOINT;\n const response = await fetch(endpoint, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"User-Agent\": ua,\n },\n body: JSON.stringify({\n query: SUBMIT_MUTATION,\n variables: report,\n }),\n signal: AbortSignal.timeout(SEND_TIMEOUT_MS),\n });\n\n if (!response.ok) return false;\n\n const data = (await response.json()) as {\n errors?: unknown[];\n data?: { submitCrashReport: { success: boolean } };\n };\n if (data.errors?.length) return false;\n return data.data?.submitCrashReport.success === true;\n } catch {\n return false;\n }\n}\n","import * as os from \"node:os\";\n\nconst HOME_DIR = os.homedir();\n\n// Patterns for sanitization (global variants for use with .replace())\nconst UUID_PATTERN = /\\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\b/gi;\nconst LONG_HEX_PATTERN = /\\b[0-9a-fA-F]{32,}\\b/g;\nconst EMAIL_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/g;\nconst ABSOLUTE_PATH_PATTERN = /(?:\\/(?:[\\w.@\\- ]+\\/)+[\\w.@\\- ]+)/g;\nconst WINDOWS_PATH_PATTERN = /(?:[A-Za-z]:\\\\(?:[\\w.@\\- ]+\\\\)+[\\w.@\\- ]+)/g;\nconst URL_QUERY_PATTERN = /[?&][^?\\s]*/g;\n\n// Non-global variants for single-match .test() calls (avoids lastIndex state issues)\nconst EMAIL_TEST_PATTERN = /\\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}\\b/;\nconst WINDOWS_DRIVE_TEST_PATTERN = /^[A-Za-z]:\\\\/;\n\n// SDK package path marker for relative paths\nconst SDK_PACKAGE_MARKER = \"packages/sdk/\";\n\nfunction lastSegment(filePath: string, separator: string): string {\n return filePath.split(separator).pop() ?? filePath;\n}\n\n/**\n * Sanitize a stack trace by replacing absolute paths with relative SDK paths.\n * External paths are replaced with `<external>/filename.ext`.\n * Home directories are replaced with `~/<redacted>/`.\n * @param stack - Raw stack trace string\n * @returns Sanitized stack trace\n */\nexport function sanitizeStackTrace(stack: string): string {\n // V8 stack traces start with \"ErrorType: message\\n at ...\".\n // The error message may span multiple lines before the first \" at \" frame.\n // Apply message sanitization to all message lines so secrets embedded in\n // multiline error messages are redacted consistently with errorMessage.\n const firstFrameIndex = stack.search(/\\n\\s+at /);\n let result: string;\n if (firstFrameIndex !== -1) {\n result = sanitizeMessage(stack.slice(0, firstFrameIndex)) + stack.slice(firstFrameIndex);\n } else {\n result = sanitizeMessage(stack);\n }\n\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => {\n const sdkIndex = match.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return match.slice(sdkIndex);\n }\n\n if (match.startsWith(HOME_DIR)) {\n return `~/<redacted>/${lastSegment(match, \"/\")}`;\n }\n\n return `<external>/${lastSegment(match, \"/\")}`;\n });\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => {\n const normalized = match.replace(/\\\\/g, \"/\");\n const sdkIndex = normalized.indexOf(SDK_PACKAGE_MARKER);\n if (sdkIndex !== -1) {\n return normalized.slice(sdkIndex);\n }\n return `<external>/${lastSegment(match, \"\\\\\")}`;\n });\n return result;\n}\n\n/**\n * Sanitize an error message by redacting sensitive information.\n * Redacts: UUIDs, long hex tokens, email addresses, absolute paths, URL query strings.\n * @param message - Raw error message\n * @returns Sanitized error message\n */\nexport function sanitizeMessage(message: string): string {\n let result = message;\n // Strip serialized request/response bodies that may contain secrets\n result = result.replace(/\\nRequest:\\s*[\\s\\S]*$/, \"\\nRequest: <redacted>\");\n result = result.replace(UUID_PATTERN, \"<uuid>\");\n result = result.replace(LONG_HEX_PATTERN, \"<redacted>\");\n result = result.replace(EMAIL_PATTERN, \"<email>\");\n result = result.replace(URL_QUERY_PATTERN, \"?<redacted>\");\n result = result.replace(ABSOLUTE_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"/\")}`);\n result = result.replace(WINDOWS_PATH_PATTERN, (match) => `<path>/${lastSegment(match, \"\\\\\")}`);\n\n return result;\n}\n\n/**\n * Sanitize process.argv by keeping command/subcommand names and redacting\n * values of sensitive flags.\n * @param argv - Raw process.argv array\n * @returns Sanitized argv array\n */\nexport function sanitizeArgv(argv: string[]): string[] {\n const result: string[] = [];\n let redactNext = false;\n\n for (const arg of argv) {\n if (redactNext) {\n // If the next token is itself a flag, treat it as a new flag rather\n // than consuming it as the previous flag's value. This avoids leaking\n // the *next* flag's value (e.g., `--verbose --workspace-id secret`\n // would otherwise expose `secret`).\n if (!arg.startsWith(\"-\")) {\n result.push(\"<redacted>\");\n redactNext = false;\n continue;\n }\n redactNext = false;\n }\n\n if (arg.startsWith(\"-\")) {\n // --flag=value: keep flag name, redact value\n const eqIndex = arg.indexOf(\"=\");\n if (eqIndex !== -1) {\n result.push(`${arg.slice(0, eqIndex)}=<redacted>`);\n continue;\n }\n\n // --flag / -f: keep flag name, redact next arg as its value\n result.push(arg);\n redactNext = true;\n continue;\n }\n\n // Redact absolute paths\n if (arg.startsWith(\"/\") && arg.includes(\"/\", 1)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact Windows-style absolute paths\n if (WINDOWS_DRIVE_TEST_PATTERN.test(arg)) {\n result.push(\"<path>\");\n continue;\n }\n\n // Redact email addresses\n if (EMAIL_TEST_PATTERN.test(arg)) {\n result.push(\"<email>\");\n continue;\n }\n\n result.push(arg);\n }\n\n return result;\n}\n","import * as crypto from \"node:crypto\";\nimport * as fs from \"node:fs\";\nimport * as os from \"node:os\";\nimport { parseYAML } from \"confbox\";\nimport * as path from \"pathe\";\nimport { xdgConfig } from \"xdg-basedir\";\nimport { sanitizeArgv, sanitizeMessage, sanitizeStackTrace } from \"./sanitize\";\n\nexport type ErrorType = \"uncaughtException\" | \"unhandledRejection\" | \"handledError\";\n\nexport interface CrashReport {\n id: string;\n timestamp: string;\n sdkVersion: string;\n nodeVersion: string;\n osPlatform: string;\n osRelease: string;\n arch: string;\n command: string;\n argv: string[];\n errorName: string;\n errorMessage: string;\n stackTrace: string;\n errorType: ErrorType;\n userId: string | null;\n userEmail: string | null;\n}\n\ninterface BuildCrashReportOptions {\n error: unknown;\n sdkVersion: string;\n errorType: ErrorType;\n}\n\n// Maximum subcommand depth to keep (e.g., \"tailordb migrate generate\" = 3 tokens).\n// Positional arguments beyond this are potentially sensitive user input.\n// Accepted trade-off: plain-text positional args that don't match known patterns\n// (UUIDs, hex tokens, emails, paths) pass through to `command` and `argv`.\n// Full redaction would require embedding the CLI command tree here, which is fragile.\nconst MAX_COMMAND_TOKENS = 3;\n\n/**\n * Parse the command name from process.argv.\n * Extracts up to MAX_COMMAND_TOKENS non-flag arguments after the script name.\n * @returns Parsed command string\n */\nfunction parseCommand(): string {\n const args = process.argv.slice(2);\n const commandParts: string[] = [];\n for (const arg of args) {\n if (arg.startsWith(\"-\") || commandParts.length >= MAX_COMMAND_TOKENS) break;\n commandParts.push(arg);\n }\n return commandParts.join(\" \") || \"<unknown>\";\n}\n\n/**\n * Build a CrashReport data structure from an error and context.\n * All sensitive data is sanitized before inclusion.\n * @param options - Error, SDK version, and crash type\n * @returns Sanitized crash report\n */\nexport function buildCrashReport(options: BuildCrashReportOptions): CrashReport {\n const { error, sdkVersion, errorType } = options;\n\n const isError = error instanceof Error;\n const rawMessage = isError ? error.message : String(error);\n const rawStack = isError && error.stack ? error.stack : \"\";\n const errorName = isError ? error.name : \"UnknownError\";\n\n const currentUser = readCurrentUser();\n\n return {\n id: crypto.randomUUID(),\n timestamp: new Date().toISOString(),\n sdkVersion,\n nodeVersion: process.version,\n osPlatform: process.platform,\n osRelease: os.release(),\n arch: process.arch,\n command: sanitizeMessage(parseCommand()),\n argv: sanitizeArgv(process.argv),\n errorName,\n errorMessage: sanitizeMessage(rawMessage),\n stackTrace: sanitizeStackTrace(rawStack),\n errorType,\n userId: currentUser,\n userEmail: currentUser,\n };\n}\n\n/**\n * Read current_user from Tailor Platform config without side effects.\n * Unlike readPlatformConfig(), this never triggers migration or logs warnings.\n * @returns The current user email, or null if unavailable\n */\nfunction readCurrentUser(): string | null {\n try {\n if (!xdgConfig) return null;\n const configPath = path.join(xdgConfig, \"tailor-platform\", \"config.yaml\");\n if (!fs.existsSync(configPath)) return null;\n const raw = parseYAML(fs.readFileSync(configPath, \"utf-8\")) as { current_user?: string | null };\n return raw?.current_user ?? null;\n } catch {\n return null;\n }\n}\n","import { logger } from \"@/cli/shared/logger\";\nimport { readPackageJson } from \"@/cli/shared/package-json\";\nimport { parseCrashReportConfig } from \"./config\";\nimport { buildCrashReport, type ErrorType } from \"./report\";\nimport { sendCrashReport } from \"./sender\";\nimport { writeCrashReport } from \"./writer\";\n\n/**\n * Report an unexpected crash. Writes a local crash log file and optionally\n * sends the report to a remote endpoint. Displays a user-facing message\n * with the crash log path and a command to submit the report.\n *\n * Never throws - all errors are silently caught.\n * @param error - The error that caused the crash\n * @param errorType - How the error was caught\n */\nexport async function reportCrash(error: unknown, errorType: ErrorType): Promise<void> {\n try {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const packageJson = await readPackageJson();\n const sdkVersion = packageJson.version ?? \"unknown\";\n\n const report = buildCrashReport({ error, sdkVersion, errorType });\n\n if (config.localEnabled) {\n const filePath = writeCrashReport(report, config.localDir);\n if (filePath) {\n logger.log(\n [\n \"\",\n \"An unexpected error occurred. A crash report has been saved to:\",\n ` ${filePath}`,\n \"\",\n \"To submit this report:\",\n ` tailor-sdk crash-report send --file \"${filePath}\"`,\n ].join(\"\\n\"),\n );\n }\n }\n\n if (config.remoteEnabled) {\n // Lazy import: client.ts pulls in heavy dependencies (OAuth2, Connect, Protobuf)\n // that should not be loaded on the startup critical path via initCrashReporting().\n const { userAgent } = await import(\"@/cli/shared/client\");\n const ua = await userAgent();\n await sendCrashReport(report, ua);\n }\n } catch {\n // Never throw from crash reporting\n }\n}\n\n/**\n * Register global uncaughtException and unhandledRejection handlers.\n * These catch errors outside the normal cleanup flow (e.g., during\n * argument parsing). Should be called once at CLI startup before runMain.\n */\nexport function initCrashReporting(): void {\n const config = parseCrashReportConfig();\n if (!config.localEnabled && !config.remoteEnabled) return;\n\n const handleFatal = (error: unknown, errorType: ErrorType) => {\n const message = error instanceof Error ? error.message : String(error);\n logger.error(message);\n void reportCrash(error, errorType).finally(() => {\n process.exit(1);\n });\n };\n\n process.on(\"uncaughtException\", (error) => handleFatal(error, \"uncaughtException\"));\n process.on(\"unhandledRejection\", (reason) => handleFatal(reason, \"unhandledRejection\"));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAiBA,SAAgB,yBAA4C;AAC1D,KAAI,KACF,QAAO;EACL,cAAc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,qBAAqB,CAAC"}
@@ -1,4 +1,4 @@
1
1
 
2
- import { n as reportCrash, t as initCrashReporting } from "./crash-report-CPkI2-cp.mjs";
2
+ import { n as reportCrash, t as initCrashReporting } from "./crash-report-CDQ2JvgR.mjs";
3
3
 
4
4
  export { reportCrash };
@@ -114,4 +114,4 @@ function enumConstantsPlugin(options) {
114
114
 
115
115
  //#endregion
116
116
  export { enumConstantsPlugin as n, EnumConstantsGeneratorID as t };
117
- //# sourceMappingURL=enum-constants-DI85-fPE.mjs.map
117
+ //# sourceMappingURL=enum-constants-Dx82rSjf.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"enum-constants-DI85-fPE.mjs","names":[],"sources":["../src/plugin/builtin/enum-constants/generate-enum-constants.ts","../src/plugin/builtin/enum-constants/process-enum-type.ts","../src/plugin/builtin/enum-constants/index.ts"],"sourcesContent":["import type { EnumDefinition } from \"./types\";\n\n/**\n * Generate enum constant definitions from collected metadata.\n * @param allEnums - All collected enum definitions\n * @returns Generated enum constant definitions\n */\nexport function generateUnifiedEnumConstants(allEnums: EnumDefinition[]): string {\n if (allEnums.length === 0) {\n return \"\";\n }\n\n const enumMap = new Map<string, EnumDefinition>();\n for (const enumDef of allEnums) {\n enumMap.set(enumDef.name, enumDef);\n }\n\n const enumDefs = Array.from(enumMap.values())\n .map((e) => {\n const members = e.values\n .map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` \"${key}\": \"${v.value}\"`;\n })\n .join(\",\\n\");\n\n const hasDescriptions = e.values.some((v) => v.description);\n let jsDoc = \"\";\n if (e.fieldDescription || hasDescriptions) {\n const lines: string[] = [];\n\n if (e.fieldDescription) {\n lines.push(` * ${e.fieldDescription}`);\n if (hasDescriptions) {\n lines.push(\" *\");\n }\n }\n\n if (hasDescriptions) {\n const propertyDocs = e.values.map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` * @property ${[key, v.description].filter(Boolean).join(\" - \")}`;\n });\n lines.push(...propertyDocs);\n }\n\n if (lines.length > 0) {\n jsDoc = `/**\\n${lines.join(\"\\n\")}\\n */\\n`;\n }\n }\n\n const constDef = `${jsDoc}export const ${e.name} = {\\n${members}\\n} as const;`;\n const typeDef = `export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`;\n return `${constDef}\\n${typeDef}`;\n })\n .join(\"\\n\\n\");\n\n if (!enumDefs) {\n return \"\";\n }\n\n return enumDefs + \"\\n\";\n}\n","import type { EnumConstantMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/types/tailordb\";\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nfunction collectEnums(type: TailorDBType): EnumConstantMetadata[\"enums\"] {\n const enums: EnumConstantMetadata[\"enums\"] = [];\n\n for (const [fieldName, parsedField] of Object.entries(type.fields)) {\n if (parsedField.config.type === \"enum\" && parsedField.config.allowedValues) {\n const enumTypeName = `${type.name}${capitalizeFirst(fieldName)}`;\n enums.push({\n name: enumTypeName,\n values: parsedField.config.allowedValues,\n fieldDescription: parsedField.config.description,\n });\n }\n\n // Process nested fields\n if (parsedField.config.type === \"nested\" && parsedField.config.fields) {\n for (const [nestedFieldName, nestedFieldConfig] of Object.entries(\n parsedField.config.fields,\n )) {\n if (nestedFieldConfig.type === \"enum\" && nestedFieldConfig.allowedValues) {\n const fullFieldName = `${fieldName}${capitalizeFirst(nestedFieldName)}`;\n const enumTypeName = `${type.name}${capitalizeFirst(fullFieldName)}`;\n enums.push({\n name: enumTypeName,\n values: nestedFieldConfig.allowedValues,\n fieldDescription: nestedFieldConfig.description,\n });\n }\n }\n }\n }\n\n return enums;\n}\n\n/**\n * Process a TailorDB type and extract enum metadata.\n * @param type - The parsed TailorDB type to process\n * @returns Enum constant metadata for the type\n */\nexport async function processEnumType(type: TailorDBType): Promise<EnumConstantMetadata> {\n const enums = collectEnums(type);\n\n return {\n name: type.name,\n enums,\n };\n}\n","import { generateUnifiedEnumConstants } from \"./generate-enum-constants\";\nimport { processEnumType } from \"./process-enum-type\";\nimport type { EnumDefinition } from \"./types\";\nimport type { Plugin } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\n/** Unique identifier for the enum constants generator plugin. */\nexport const EnumConstantsGeneratorID = \"@tailor-platform/enum-constants\";\n\ntype EnumConstantsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates enum constants from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated constants\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function enumConstantsPlugin(\n options: EnumConstantsPluginOptions,\n): Plugin<unknown, EnumConstantsPluginOptions> {\n return {\n id: EnumConstantsGeneratorID,\n description: \"Generates enum constants from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<EnumConstantsPluginOptions>,\n ): Promise<GeneratorResult> {\n const allEnums: EnumDefinition[] = [];\n\n for (const ns of ctx.tailordb) {\n for (const type of Object.values(ns.types)) {\n const metadata = await processEnumType(type);\n allEnums.push(...metadata.enums);\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allEnums.length > 0) {\n const content = generateUnifiedEnumConstants(allEnums);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,6BAA6B,UAAoC;AAC/E,KAAI,SAAS,WAAW,EACtB,QAAO;CAGT,MAAM,0BAAU,IAAI,KAA6B;AACjD,MAAK,MAAM,WAAW,SACpB,SAAQ,IAAI,QAAQ,MAAM,QAAQ;CAGpC,MAAM,WAAW,MAAM,KAAK,QAAQ,QAAQ,CAAC,CAC1C,KAAK,MAAM;EACV,MAAM,UAAU,EAAE,OACf,KAAK,MAAM;AAEV,UAAO,MADK,EAAE,MAAM,QAAQ,UAAU,IAAI,CACzB,MAAM,EAAE,MAAM;IAC/B,CACD,KAAK,MAAM;EAEd,MAAM,kBAAkB,EAA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YAAY,OAAO,OACpB,CACC,KAAI,kBAAkB,SAAS,UAAU,kBAAkB,eAAe;IACxE,MAAM,gBAAgB,GAAG,YAAY,gBAAgB,gBAAgB;IACrE,MAAM,eAAe,GAAG,KAAK,OAAO,gBAAgB,cAAc;AAClE,UAAM,KAAK;KACT,MAAM;KACN,QAAQ,kBAAkB;KAC1B,kBAAkB,kBAAkB;KACrC,CAAC;;;;AAMV,QAAO;;;;;;;AAQT,eAAsB,gBAAgB,MAAmD;CACvF,MAAM,QAAQ,aAAa,KAAK;AAEhC,QAAO;EACL,MAAM,KAAK;EACX;EACD;;;;;;AC7CH,MAAa,2BAA2B;;;;;;;AAYxC,SAAgB,oBACd,SAC6C;AAC7C,QAAO;EACL,IAAI;EACJ,aAAa;EACb,cAAc;EAEd,MAAM,gBACJ,KAC0B;GAC1B,MAAM,WAA6B,EAAE;AAErC,QAAK,MAAM,MAAM,IAAI,SACnB,MAAK,MAAM,QAAQ,OAAO,OAAO,GAAG,MAAM,EAAE;IAC1C,MAAM,WAAW,MAAM,gBAAgB,KAAK;AAC5C,aAAS,KAAK,GAAG,SAAS,MAAM;;GAIpC,MAAM,QAAkC,EAAE;AAC1C,OAAI,SAAS,SAAS,GAAG;IACvB,MAAM,UAAU,6BAA6B,SAAS;AACtD,UAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAGJ,UAAO,EAAE,OAAO;;EAEnB"}
1
+ {"version":3,"file":"enum-constants-Dx82rSjf.mjs","names":[],"sources":["../src/plugin/builtin/enum-constants/generate-enum-constants.ts","../src/plugin/builtin/enum-constants/process-enum-type.ts","../src/plugin/builtin/enum-constants/index.ts"],"sourcesContent":["import type { EnumDefinition } from \"./types\";\n\n/**\n * Generate enum constant definitions from collected metadata.\n * @param allEnums - All collected enum definitions\n * @returns Generated enum constant definitions\n */\nexport function generateUnifiedEnumConstants(allEnums: EnumDefinition[]): string {\n if (allEnums.length === 0) {\n return \"\";\n }\n\n const enumMap = new Map<string, EnumDefinition>();\n for (const enumDef of allEnums) {\n enumMap.set(enumDef.name, enumDef);\n }\n\n const enumDefs = Array.from(enumMap.values())\n .map((e) => {\n const members = e.values\n .map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` \"${key}\": \"${v.value}\"`;\n })\n .join(\",\\n\");\n\n const hasDescriptions = e.values.some((v) => v.description);\n let jsDoc = \"\";\n if (e.fieldDescription || hasDescriptions) {\n const lines: string[] = [];\n\n if (e.fieldDescription) {\n lines.push(` * ${e.fieldDescription}`);\n if (hasDescriptions) {\n lines.push(\" *\");\n }\n }\n\n if (hasDescriptions) {\n const propertyDocs = e.values.map((v) => {\n const key = v.value.replace(/[-\\s]/g, \"_\");\n return ` * @property ${[key, v.description].filter(Boolean).join(\" - \")}`;\n });\n lines.push(...propertyDocs);\n }\n\n if (lines.length > 0) {\n jsDoc = `/**\\n${lines.join(\"\\n\")}\\n */\\n`;\n }\n }\n\n const constDef = `${jsDoc}export const ${e.name} = {\\n${members}\\n} as const;`;\n const typeDef = `export type ${e.name} = (typeof ${e.name})[keyof typeof ${e.name}];`;\n return `${constDef}\\n${typeDef}`;\n })\n .join(\"\\n\\n\");\n\n if (!enumDefs) {\n return \"\";\n }\n\n return enumDefs + \"\\n\";\n}\n","import type { EnumConstantMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/types/tailordb\";\n\nfunction capitalizeFirst(str: string): string {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\nfunction collectEnums(type: TailorDBType): EnumConstantMetadata[\"enums\"] {\n const enums: EnumConstantMetadata[\"enums\"] = [];\n\n for (const [fieldName, parsedField] of Object.entries(type.fields)) {\n if (parsedField.config.type === \"enum\" && parsedField.config.allowedValues) {\n const enumTypeName = `${type.name}${capitalizeFirst(fieldName)}`;\n enums.push({\n name: enumTypeName,\n values: parsedField.config.allowedValues,\n fieldDescription: parsedField.config.description,\n });\n }\n\n // Process nested fields\n if (parsedField.config.type === \"nested\" && parsedField.config.fields) {\n for (const [nestedFieldName, nestedFieldConfig] of Object.entries(\n parsedField.config.fields,\n )) {\n if (nestedFieldConfig.type === \"enum\" && nestedFieldConfig.allowedValues) {\n const fullFieldName = `${fieldName}${capitalizeFirst(nestedFieldName)}`;\n const enumTypeName = `${type.name}${capitalizeFirst(fullFieldName)}`;\n enums.push({\n name: enumTypeName,\n values: nestedFieldConfig.allowedValues,\n fieldDescription: nestedFieldConfig.description,\n });\n }\n }\n }\n }\n\n return enums;\n}\n\n/**\n * Process a TailorDB type and extract enum metadata.\n * @param type - The parsed TailorDB type to process\n * @returns Enum constant metadata for the type\n */\nexport async function processEnumType(type: TailorDBType): Promise<EnumConstantMetadata> {\n const enums = collectEnums(type);\n\n return {\n name: type.name,\n enums,\n };\n}\n","import { generateUnifiedEnumConstants } from \"./generate-enum-constants\";\nimport { processEnumType } from \"./process-enum-type\";\nimport type { EnumDefinition } from \"./types\";\nimport type { Plugin } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\n/** Unique identifier for the enum constants generator plugin. */\nexport const EnumConstantsGeneratorID = \"@tailor-platform/enum-constants\";\n\ntype EnumConstantsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates enum constants from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated constants\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function enumConstantsPlugin(\n options: EnumConstantsPluginOptions,\n): Plugin<unknown, EnumConstantsPluginOptions> {\n return {\n id: EnumConstantsGeneratorID,\n description: \"Generates enum constants from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<EnumConstantsPluginOptions>,\n ): Promise<GeneratorResult> {\n const allEnums: EnumDefinition[] = [];\n\n for (const ns of ctx.tailordb) {\n for (const type of Object.values(ns.types)) {\n const metadata = await processEnumType(type);\n allEnums.push(...metadata.enums);\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (allEnums.length > 0) {\n const content = generateUnifiedEnumConstants(allEnums);\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;AAOA,SAAgB,6BAA6B,UAAoC;AAC/E,KAAI,SAAS,WAAW,EACtB,QAAO;CAGT,MAAM,0BAAU,IAAI,KAA6B;AACjD,MAAK,MAAM,WAAW,SACpB,SAAQ,IAAI,QAAQ,MAAM,QAAQ;CAGpC,MAAM,WAAW,MAAM,KAAK,QAAQ,QAAQ,CAAC,CAC1C,KAAK,MAAM;EACV,MAAM,UAAU,EAAE,OACf,KAAK,MAAM;AAEV,UAAO,MADK,EAAE,MAAM,QAAQ,UAAU,IAAI,CACzB,MAAM,EAAE,MAAM;IAC/B,CACD,KAAK,MAAM;EAEd,MAAM,kBAAkB,EAAE,OAAO,MAAM,MAAM,EAAE,YAAY;EAC3D,IAAI,QAAQ;AACZ,MAAI,EAAE,oBAAoB,iBAAiB;GACzC,MAAM,QAAkB,EAAE;AAE1B,OAAI,EAAE,kBAAkB;AACtB,UAAM,KAAK,MAAM,EAAE,mBAAmB;AACtC,QAAI,gBACF,OAAM,KAAK,KAAK;;AAIpB,OAAI,iBAAiB;IACnB,MAAM,eAAe,EAAE,OAAO,KAAK,MAAM;AAEvC,YAAO,gBAAgB,CADX,EAAE,MAAM,QAAQ,UAAU,IAAI,EACb,EAAE,YAAY,CAAC,OAAO,QAAQ,CAAC,KAAK,MAAM;MACvE;AACF,UAAM,KAAK,GAAG,aAAa;;AAG7B,OAAI,MAAM,SAAS,EACjB,SAAQ,QAAQ,MAAM,KAAK,KAAK,CAAC;;AAMrC,SAAO,GAFU,GAAG,MAAM,eAAe,EAAE,KAAK,QAAQ,QAAQ,eAE7C,IADH,eAAe,EAAE,KAAK,aAAa,EAAE,KAAK,iBAAiB,EAAE,KAAK;GAElF,CACD,KAAK,OAAO;AAEf,KAAI,CAAC,SACH,QAAO;AAGT,QAAO,WAAW;;;;;AC1DpB,SAAS,gBAAgB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1C,OAAI,SAAS,SAAS,GAAG;IACvB,MAAM,UAAU,6BAA6B,SAAS;AACtD,UAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAGJ,UAAO,EAAE,OAAO;;EAEnB"}
@@ -0,0 +1,30 @@
1
+ /// <reference types="@tailor-platform/function-types" />
2
+ import { lt as InferredAttributeList, ut as InferredAttributeMap } from "./plugin-D6P4g_2L.mjs";
3
+
4
+ //#region src/configure/types/actor.d.ts
5
+ /** User type enum values from the Tailor Platform server. */
6
+ type TailorActorType = "USER_TYPE_USER" | "USER_TYPE_MACHINE_USER" | "USER_TYPE_UNSPECIFIED";
7
+ /** Represents an actor in event triggers. */
8
+ type TailorActor = {
9
+ /** The ID of the workspace the user belongs to. */workspaceId: string; /** The ID of the user. */
10
+ userId: string;
11
+ /**
12
+ * A map of the user's attributes.
13
+ * Maps from server's `attributeMap` field.
14
+ */
15
+ attributes: InferredAttributeMap | null;
16
+ /**
17
+ * A list of the user's attributes.
18
+ * Maps from server's `attributes` field.
19
+ */
20
+ attributeList: InferredAttributeList; /** The type of the user. */
21
+ userType: TailorActorType;
22
+ };
23
+ //#endregion
24
+ //#region src/configure/types/env.d.ts
25
+ interface Env {}
26
+ /** Represents environment variables in the Tailor platform. */
27
+ type TailorEnv = keyof Env extends never ? Record<string, string> : Env;
28
+ //#endregion
29
+ export { TailorEnv as n, TailorActor as r, Env as t };
30
+ //# sourceMappingURL=env-04IQXqsl.d.mts.map
@@ -138,4 +138,4 @@ function fileUtilsPlugin(options) {
138
138
 
139
139
  //#endregion
140
140
  export { fileUtilsPlugin as n, FileUtilsGeneratorID as t };
141
- //# sourceMappingURL=file-utils-C4rXlOVt.mjs.map
141
+ //# sourceMappingURL=file-utils-DeWpvq3T.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"file-utils-C4rXlOVt.mjs","names":[],"sources":["../src/plugin/builtin/file-utils/generate-file-utils.ts","../src/plugin/builtin/file-utils/process-file-type.ts","../src/plugin/builtin/file-utils/index.ts"],"sourcesContent":["import multiline from \"multiline-ts\";\nimport type { FileUtilMetadata } from \"./types\";\n\n/**\n * Generate unified file utility functions from collected metadata.\n * @param namespaceData - Namespace data with file utility metadata\n * @returns Generated file utility code\n */\nexport function generateUnifiedFileUtils(\n namespaceData: { namespace: string; types: FileUtilMetadata[] }[],\n): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Collect all types with their namespace\n const typeNamespaceMap = new Map<string, string>();\n const typeFieldsMap = new Map<string, string[]>();\n\n for (const { namespace, types } of namespaceData) {\n for (const type of types) {\n typeNamespaceMap.set(type.name, namespace);\n typeFieldsMap.set(type.name, type.fileFields);\n }\n }\n\n if (typeNamespaceMap.size === 0) {\n return \"\";\n }\n\n // Generate interface fields\n const interfaceFields = Array.from(typeFieldsMap.entries())\n .map(([typeName, fields]) => {\n const fieldNamesUnion = fields.map((field) => `\"${field}\"`).join(\" | \");\n return ` ${typeName}: {\\n fields: ${fieldNamesUnion};\\n };`;\n })\n .join(\"\\n\");\n\n const interfaceDefinition =\n multiline /* ts */ `\n export interface TypeWithFiles {\n ${interfaceFields}\n }\n ` + \"\\n\";\n\n // Generate namespaces object\n const namespaceEntries = Array.from(typeNamespaceMap.entries())\n .map(([typeName, namespace]) => ` ${typeName}: \"${namespace}\"`)\n .join(\",\\n\");\n\n const namespacesDefinition =\n multiline /* ts */ `\n const namespaces: Record<keyof TypeWithFiles, string> = {\n ${namespaceEntries},\n };\n ` + \"\\n\";\n\n // Generate downloadFile helper function\n const downloadFunction =\n multiline /* ts */ `\n export async function downloadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ) {\n return await tailordb.file.download(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate uploadFile helper function\n const uploadFunction =\n multiline /* ts */ `\n export async function uploadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n data: string | ArrayBuffer | Uint8Array<ArrayBufferLike> | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse> {\n return await tailordb.file.upload(namespaces[type], type, field, recordId, data, options);\n }\n ` + \"\\n\";\n\n // Generate deleteFile helper function\n const deleteFunction =\n multiline /* ts */ `\n export async function deleteFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<void> {\n return await tailordb.file.delete(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate getFileMetadata helper function\n const getMetadataFunction =\n multiline /* ts */ `\n export async function getFileMetadata<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileMetadata> {\n return await tailordb.file.getMetadata(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate openFileDownloadStream helper function\n const openDownloadStreamFunction =\n multiline /* ts */ `\n export async function openFileDownloadStream<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileStreamIterator> {\n return await tailordb.file.openDownloadStream(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n return [\n interfaceDefinition,\n namespacesDefinition,\n downloadFunction,\n uploadFunction,\n deleteFunction,\n getMetadataFunction,\n openDownloadStreamFunction,\n ].join(\"\\n\");\n}\n","import type { FileUtilMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/types/tailordb\";\n\n/**\n * Process a TailorDB type and extract file field metadata.\n * @param type - The parsed TailorDB type to process\n * @returns File utility metadata for the type\n */\nexport async function processFileType(type: TailorDBType): Promise<FileUtilMetadata> {\n const fileFields: string[] = [];\n\n if (type.files) {\n for (const fileFieldName of Object.keys(type.files)) {\n fileFields.push(fileFieldName);\n }\n }\n\n return {\n name: type.name,\n fileFields,\n };\n}\n","import { generateUnifiedFileUtils } from \"./generate-file-utils\";\nimport { processFileType } from \"./process-file-type\";\nimport type { FileUtilMetadata } from \"./types\";\nimport type { Plugin } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\n/** Unique identifier for the file utilities generator plugin. */\nexport const FileUtilsGeneratorID = \"@tailor-platform/file-utils\";\n\ntype FileUtilsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates TypeWithFiles interface from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated file utilities\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function fileUtilsPlugin(\n options: FileUtilsPluginOptions,\n): Plugin<unknown, FileUtilsPluginOptions> {\n return {\n id: FileUtilsGeneratorID,\n description: \"Generates TypeWithFiles interface from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<FileUtilsPluginOptions>,\n ): Promise<GeneratorResult> {\n const namespaceData: { namespace: string; types: FileUtilMetadata[] }[] = [];\n\n for (const ns of ctx.tailordb) {\n const typesWithFiles: FileUtilMetadata[] = [];\n\n for (const type of Object.values(ns.types)) {\n const metadata = await processFileType(type);\n if (metadata.fileFields.length > 0) {\n typesWithFiles.push(metadata);\n }\n }\n\n if (typesWithFiles.length > 0) {\n namespaceData.push({\n namespace: ns.namespace,\n types: typesWithFiles,\n });\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (namespaceData.length > 0) {\n const content = generateUnifiedFileUtils(namespaceData);\n if (content) {\n files.push({\n path: ctx.pluginConfig.distPath,\n content,\n });\n }\n }\n\n return { files };\n },\n };\n}\n"],"mappings":";;;;;;;;;AAQA,SAAgB,yBACd,eACQ;AACR,KAAI,cAAc,WAAW,EAC3B,QAAO;CAIT,MAAM,mCAAmB,IAAI,KAAqB;CAClD,MAAM,gCAAgB,IAAI,KAAuB;AAEjD,MAAK,MAAM,EAAE,WAAW,WAAW,cACjC,MAAK,MAAM,QAAQ,OAAO;AACxB,mBAAiB,IAAI,KAAK,MAAM,UAAU;AAC1C,gBAAc,IAAI,KAAK,M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W,GAAG;KACd,OAAO;KACR,CAAC;;GAIN,MAAM,QAAkC,EAAE;AAC1C,OAAI,cAAc,SAAS,GAAG;IAC5B,MAAM,UAAU,yBAAyB,cAAc;AACvD,QAAI,QACF,OAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAIN,UAAO,EAAE,OAAO;;EAEnB"}
1
+ {"version":3,"file":"file-utils-DeWpvq3T.mjs","names":[],"sources":["../src/plugin/builtin/file-utils/generate-file-utils.ts","../src/plugin/builtin/file-utils/process-file-type.ts","../src/plugin/builtin/file-utils/index.ts"],"sourcesContent":["import multiline from \"multiline-ts\";\nimport type { FileUtilMetadata } from \"./types\";\n\n/**\n * Generate unified file utility functions from collected metadata.\n * @param namespaceData - Namespace data with file utility metadata\n * @returns Generated file utility code\n */\nexport function generateUnifiedFileUtils(\n namespaceData: { namespace: string; types: FileUtilMetadata[] }[],\n): string {\n if (namespaceData.length === 0) {\n return \"\";\n }\n\n // Collect all types with their namespace\n const typeNamespaceMap = new Map<string, string>();\n const typeFieldsMap = new Map<string, string[]>();\n\n for (const { namespace, types } of namespaceData) {\n for (const type of types) {\n typeNamespaceMap.set(type.name, namespace);\n typeFieldsMap.set(type.name, type.fileFields);\n }\n }\n\n if (typeNamespaceMap.size === 0) {\n return \"\";\n }\n\n // Generate interface fields\n const interfaceFields = Array.from(typeFieldsMap.entries())\n .map(([typeName, fields]) => {\n const fieldNamesUnion = fields.map((field) => `\"${field}\"`).join(\" | \");\n return ` ${typeName}: {\\n fields: ${fieldNamesUnion};\\n };`;\n })\n .join(\"\\n\");\n\n const interfaceDefinition =\n multiline /* ts */ `\n export interface TypeWithFiles {\n ${interfaceFields}\n }\n ` + \"\\n\";\n\n // Generate namespaces object\n const namespaceEntries = Array.from(typeNamespaceMap.entries())\n .map(([typeName, namespace]) => ` ${typeName}: \"${namespace}\"`)\n .join(\",\\n\");\n\n const namespacesDefinition =\n multiline /* ts */ `\n const namespaces: Record<keyof TypeWithFiles, string> = {\n ${namespaceEntries},\n };\n ` + \"\\n\";\n\n // Generate downloadFile helper function\n const downloadFunction =\n multiline /* ts */ `\n export async function downloadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ) {\n return await tailordb.file.download(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate uploadFile helper function\n const uploadFunction =\n multiline /* ts */ `\n export async function uploadFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n data: string | ArrayBuffer | Uint8Array<ArrayBufferLike> | number[],\n options?: FileUploadOptions,\n ): Promise<FileUploadResponse> {\n return await tailordb.file.upload(namespaces[type], type, field, recordId, data, options);\n }\n ` + \"\\n\";\n\n // Generate deleteFile helper function\n const deleteFunction =\n multiline /* ts */ `\n export async function deleteFile<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<void> {\n return await tailordb.file.delete(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate getFileMetadata helper function\n const getMetadataFunction =\n multiline /* ts */ `\n export async function getFileMetadata<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileMetadata> {\n return await tailordb.file.getMetadata(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n // Generate openFileDownloadStream helper function\n const openDownloadStreamFunction =\n multiline /* ts */ `\n export async function openFileDownloadStream<T extends keyof TypeWithFiles>(\n type: T,\n field: TypeWithFiles[T][\"fields\"],\n recordId: string,\n ): Promise<FileStreamIterator> {\n return await tailordb.file.openDownloadStream(namespaces[type], type, field, recordId);\n }\n ` + \"\\n\";\n\n return [\n interfaceDefinition,\n namespacesDefinition,\n downloadFunction,\n uploadFunction,\n deleteFunction,\n getMetadataFunction,\n openDownloadStreamFunction,\n ].join(\"\\n\");\n}\n","import type { FileUtilMetadata } from \"./types\";\nimport type { TailorDBType } from \"@/types/tailordb\";\n\n/**\n * Process a TailorDB type and extract file field metadata.\n * @param type - The parsed TailorDB type to process\n * @returns File utility metadata for the type\n */\nexport async function processFileType(type: TailorDBType): Promise<FileUtilMetadata> {\n const fileFields: string[] = [];\n\n if (type.files) {\n for (const fileFieldName of Object.keys(type.files)) {\n fileFields.push(fileFieldName);\n }\n }\n\n return {\n name: type.name,\n fileFields,\n };\n}\n","import { generateUnifiedFileUtils } from \"./generate-file-utils\";\nimport { processFileType } from \"./process-file-type\";\nimport type { FileUtilMetadata } from \"./types\";\nimport type { Plugin } from \"@/types/plugin\";\nimport type { GeneratorResult, TailorDBReadyContext } from \"@/types/plugin-generation\";\n\n/** Unique identifier for the file utilities generator plugin. */\nexport const FileUtilsGeneratorID = \"@tailor-platform/file-utils\";\n\ntype FileUtilsPluginOptions = {\n distPath: string;\n};\n\n/**\n * Plugin that generates TypeWithFiles interface from TailorDB type definitions.\n * @param options - Plugin options\n * @param options.distPath - Output file path for generated file utilities\n * @returns Plugin instance with onTailorDBReady hook\n */\nexport function fileUtilsPlugin(\n options: FileUtilsPluginOptions,\n): Plugin<unknown, FileUtilsPluginOptions> {\n return {\n id: FileUtilsGeneratorID,\n description: \"Generates TypeWithFiles interface from TailorDB type definitions\",\n pluginConfig: options,\n\n async onTailorDBReady(\n ctx: TailorDBReadyContext<FileUtilsPluginOptions>,\n ): Promise<GeneratorResult> {\n const namespaceData: { namespace: string; types: FileUtilMetadata[] }[] = [];\n\n for (const ns of ctx.tailordb) {\n const typesWithFiles: FileUtilMetadata[] = [];\n\n for (const type of Object.values(ns.types)) {\n const metadata = await processFileType(type);\n if (metadata.fileFields.length > 0) {\n typesWithFiles.push(metadata);\n }\n }\n\n if (typesWithFiles.length > 0) {\n namespaceData.push({\n namespace: ns.namespace,\n types: typesWithFiles,\n });\n }\n }\n\n const files: GeneratorResult[\"files\"] = [];\n if (namespaceData.length > 0) {\n const content = generateUnifiedFileUtils(namespaceData);\n if (content) {\n files.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,aAAa;EACb,cAAc;EAEd,MAAM,gBACJ,KAC0B;GAC1B,MAAM,gBAAoE,EAAE;AAE5E,QAAK,MAAM,MAAM,IAAI,UAAU;IAC7B,MAAM,iBAAqC,EAAE;AAE7C,SAAK,MAAM,QAAQ,OAAO,OAAO,GAAG,MAAM,EAAE;KAC1C,MAAM,WAAW,MAAM,gBAAgB,KAAK;AAC5C,SAAI,SAAS,WAAW,SAAS,EAC/B,gBAAe,KAAK,SAAS;;AAIjC,QAAI,eAAe,SAAS,EAC1B,eAAc,KAAK;KACjB,WAAW,GAAG;KACd,OAAO;KACR,CAAC;;GAIN,MAAM,QAAkC,EAAE;AAC1C,OAAI,cAAc,SAAS,GAAG;IAC5B,MAAM,UAAU,yBAAyB,cAAc;AACvD,QAAI,QACF,OAAM,KAAK;KACT,MAAM,IAAI,aAAa;KACvB;KACD,CAAC;;AAIN,UAAO,EAAE,OAAO;;EAEnB"}
@@ -1,5 +1,5 @@
1
1
  /// <reference types="@tailor-platform/function-types" />
2
- import { n as Plugin } from "./plugin-D8hKE6rZ.mjs";
2
+ import { n as Plugin } from "./plugin-D6P4g_2L.mjs";
3
3
 
4
4
  //#region src/plugin/builtin/kysely-type/index.d.ts
5
5
  /** Unique identifier for the Kysely type generator plugin. */
@@ -16,4 +16,4 @@ type KyselyTypePluginOptions = {
16
16
  declare function kyselyTypePlugin(options: KyselyTypePluginOptions): Plugin<unknown, KyselyTypePluginOptions>;
17
17
  //#endregion
18
18
  export { kyselyTypePlugin as n, KyselyGeneratorID as t };
19
- //# sourceMappingURL=index-DTJkkO-t.d.mts.map
19
+ //# sourceMappingURL=index-BUT18Kak.d.mts.map
@@ -1,12 +1,24 @@
1
1
  /// <reference types="@tailor-platform/function-types" />
2
- import { $ as FieldOptions, At as TailorDBTrigger$1, Ct as ExecutorInput, Dt as IncomingWebhookTrigger$1, Et as IdpUserTrigger$1, F as UserAttributeListKey, H as TailorDBInstance, I as UserAttributeMap, Mt as WorkflowOperation$1, Nt as AuthInvoker$1, Ot as ResolverExecutedTrigger$1, Q as FieldMetadata, Tt as GqlOperation$1, U as TailorDBType, X as ArrayFieldOutput, Z as DefinedFieldMetadata, at as JsonCompatible, bt as GeneratorConfig, ct as TailorEnv, et as FieldOutput, ft as TailorUser, ht as AllowedValuesOutput, it as InferFieldsOutput, j as DefinedAuth, jt as WebhookOperation$1, k as AuthServiceInput, kt as ScheduleTriggerInput, lt as TailorActor, mt as AllowedValues, n as Plugin, nt as TailorAnyField, ot as output$1, rt as TailorField, tt as TailorFieldType, vt as Resolver, wt as FunctionOperation$1, xt as AuthAccessTokenTrigger$1, yt as ResolverInput } from "./plugin-D8hKE6rZ.mjs";
3
- import { b as IdPInput, g as IdpDefinitionBrand, n as AppConfig, t as RetryPolicy } from "./workflow.generated-DMt8PNVd.mjs";
2
+ import { $ as FieldOptions, At as WebhookOperation$1, Ct as FunctionOperation$1, Dt as ResolverExecutedTrigger$1, Et as IncomingWebhookTrigger$1, F as UserAttributeListKey, H as TailorDBInstance, I as UserAttributeMap, Mt as AuthInvoker$1, Ot as ScheduleTriggerInput, Q as FieldMetadata, St as ExecutorInput, Tt as IdpUserTrigger$1, U as TailorDBType, X as ArrayFieldOutput, Z as DefinedFieldMetadata, _t as Resolver, at as JsonCompatible, bt as AuthAccessTokenTrigger$1, dt as TailorUser, et as FieldOutput, it as InferFieldsOutput, j as DefinedAuth, jt as WorkflowOperation$1, k as AuthServiceInput, kt as TailorDBTrigger$1, mt as AllowedValuesOutput, n as Plugin, nt as TailorAnyField, ot as output$1, pt as AllowedValues, rt as TailorField, tt as TailorFieldType, ut as InferredAttributeMap, vt as ResolverInput, wt as GqlOperation$1, yt as GeneratorConfig } from "./plugin-D6P4g_2L.mjs";
3
+ import { n as TailorEnv, r as TailorActor } from "./env-04IQXqsl.mjs";
4
+ import { _ as IdpDefinitionBrand, g as IdPUserField, n as AppConfig, t as RetryPolicy, x as IdPInput } from "./workflow.generated-Bj_DVqGh.mjs";
4
5
  import * as _$zod from "zod";
5
6
  import { JsonPrimitive, Jsonifiable, Jsonify } from "type-fest";
6
7
  import { Client } from "@urql/core";
7
8
  import { StandardCRON } from "ts-cron-validator";
8
9
  import * as _$zod_v4_core0 from "zod/v4/core";
9
10
 
11
+ //#region src/configure/types/machine-user.d.ts
12
+ interface MachineUserNameRegistry {}
13
+ /**
14
+ * Machine user name.
15
+ *
16
+ * When `tailor.d.ts` is generated (via `tailor-sdk apply`/`generate`), this is narrowed
17
+ * to the union of defined machine user names. When no machine users are registered yet,
18
+ * falls back to `string` to avoid blocking editing before the first generate run.
19
+ */
20
+ type MachineUserName = keyof MachineUserNameRegistry extends never ? string : keyof MachineUserNameRegistry & string;
21
+ //#endregion
10
22
  //#region src/configure/services/auth/index.d.ts
11
23
  type MachineUserAttributeFields = Record<string, TailorField<DefinedFieldMetadata, unknown, FieldMetadata, TailorFieldType>>;
12
24
  type PlaceholderUser = TailorDBInstance<Record<string, never>, Record<string, never>>;
@@ -59,10 +71,11 @@ type NormalizedOutput<Output extends TailorAnyField | Record<string, TailorAnyFi
59
71
  type: "nested";
60
72
  array: false;
61
73
  }, InferFieldsOutput<Extract<Output, Record<string, TailorAnyField>>>>;
62
- type ResolverReturn<Input extends Record<string, TailorAnyField> | undefined, Output extends TailorAnyField | Record<string, TailorAnyField>> = Omit<ResolverInput, "input" | "output" | "body"> & Readonly<{
74
+ type ResolverReturn<Input extends Record<string, TailorAnyField> | undefined, Output extends TailorAnyField | Record<string, TailorAnyField>> = Omit<ResolverInput, "input" | "output" | "body" | "authInvoker"> & Readonly<{
63
75
  input?: Input;
64
76
  output: NormalizedOutput<Output>;
65
77
  body: (context: Context<Input>) => OutputType<Output> | Promise<OutputType<Output>>;
78
+ authInvoker?: AuthInvoker<string> | MachineUserName;
66
79
  }>;
67
80
  /**
68
81
  * Create a resolver definition for the Tailor SDK.
@@ -102,10 +115,11 @@ type ResolverReturn<Input extends Record<string, TailorAnyField> | undefined, Ou
102
115
  * }),
103
116
  * });
104
117
  */
105
- declare function createResolver<Input extends Record<string, TailorAnyField> | undefined = undefined, Output extends TailorAnyField | Record<string, TailorAnyField> = TailorAnyField>(config: Omit<ResolverInput, "input" | "output" | "body"> & Readonly<{
118
+ declare function createResolver<Input extends Record<string, TailorAnyField> | undefined = undefined, Output extends TailorAnyField | Record<string, TailorAnyField> = TailorAnyField>(config: Omit<ResolverInput, "input" | "output" | "body" | "authInvoker"> & Readonly<{
106
119
  input?: Input;
107
120
  output: Output;
108
121
  body: (context: Context<Input>) => OutputType<Output> | Promise<OutputType<Output>>;
122
+ authInvoker?: AuthInvoker<string> | MachineUserName;
109
123
  }>): ResolverReturn<Input, Output>;
110
124
  type ResolverConfig = ReturnType<typeof createResolver<any, any>>;
111
125
  //#endregion
@@ -267,7 +281,7 @@ interface Workflow<Job extends WorkflowJob<any, any, any> = WorkflowJob<any, any
267
281
  mainJob: Job;
268
282
  retryPolicy?: RetryPolicy;
269
283
  trigger: (args: Parameters<Job["trigger"]>[0], options?: {
270
- authInvoker: AuthInvoker<string>;
284
+ authInvoker: AuthInvoker<string> | MachineUserName;
271
285
  }) => Promise<string>;
272
286
  }
273
287
  interface WorkflowDefinition<Job extends WorkflowJob<any, any, any>> {
@@ -304,14 +318,16 @@ declare function createWorkflow<Job extends WorkflowJob<any, any, any>>(config:
304
318
  //#endregion
305
319
  //#region src/configure/services/executor/operation.d.ts
306
320
  /** Function-based executor operation. The body receives the trigger args. */
307
- type FunctionOperation<Args> = Omit<FunctionOperation$1, "body"> & {
321
+ type FunctionOperation<Args> = Omit<FunctionOperation$1, "body" | "authInvoker"> & {
308
322
  body: (args: Args) => void | Promise<void>;
323
+ authInvoker?: AuthInvoker<string> | MachineUserName;
309
324
  };
310
325
  type UrqlOperationArgs = Parameters<Client["query"] | Client["mutation"]>;
311
326
  /** GraphQL-based executor operation. Executes a GraphQL query or mutation. */
312
- type GqlOperation<Args> = Omit<GqlOperation$1, "query" | "variables"> & {
327
+ type GqlOperation<Args> = Omit<GqlOperation$1, "query" | "variables" | "authInvoker"> & {
313
328
  query: UrqlOperationArgs[0];
314
329
  variables?: (args: Args) => UrqlOperationArgs[1];
330
+ authInvoker?: AuthInvoker<string> | MachineUserName;
315
331
  };
316
332
  type RequestHeader = "A-IM" | "Accept" | "Accept-Additions" | "Accept-CH" | "Accept-Charset" | "Accept-Datetime" | "Accept-Encoding" | "Accept-Features" | "Accept-Language" | "Accept-Patch" | "Accept-Post" | "Accept-Ranges" | "Accept-Signature" | "Access-Control" | "Access-Control-Allow-Credentials" | "Access-Control-Allow-Headers" | "Access-Control-Allow-Methods" | "Access-Control-Allow-Origin" | "Access-Control-Expose-Headers" | "Access-Control-Max-Age" | "Access-Control-Request-Headers" | "Access-Control-Request-Method" | "Age" | "Allow" | "ALPN" | "Alt-Svc" | "Alt-Used" | "Alternates" | "AMP-Cache-Transform" | "Apply-To-Redirect-Ref" | "Authentication-Control" | "Authentication-Info" | "Authorization" | "Available-Dictionary" | "C-Ext" | "C-Man" | "C-Opt" | "C-PEP" | "C-PEP-Info" | "Cache-Control" | "Cache-Status" | "Cal-Managed-ID" | "CalDAV-Timezones" | "Capsule-Protocol" | "CDN-Cache-Control" | "CDN-Loop" | "Cert-Not-After" | "Cert-Not-Before" | "Clear-Site-Data" | "Client-Cert" | "Client-Cert-Chain" | "Close" | "CMCD-Object" | "CMCD-Request" | "CMCD-Session" | "CMCD-Status" | "CMSD-Dynamic" | "CMSD-Static" | "Concealed-Auth-Export" | "Configuration-Context" | "Connection" | "Content-Base" | "Content-Digest" | "Content-Disposition" | "Content-Encoding" | "Content-ID" | "Content-Language" | "Content-Length" | "Content-Location" | "Content-MD5" | "Content-Range" | "Content-Script-Type" | "Content-Security-Policy" | "Content-Security-Policy-Report-Only" | "Content-Style-Type" | "Content-Type" | "Content-Version" | "Cookie" | "Cookie2" | "Cross-Origin-Embedder-Policy" | "Cross-Origin-Embedder-Policy-Report-Only" | "Cross-Origin-Opener-Policy" | "Cross-Origin-Opener-Policy-Report-Only" | "Cross-Origin-Resource-Policy" | "CTA-Common-Access-Token" | "DASL" | "Date" | "DAV" | "Default-Style" | "Delta-Base" | "Deprecation" | "Depth" | "Derived-From" | "Destination" | "Differential-ID" | "Dictionary-ID" | "Digest" | "DPoP" | "DPoP-Nonce" | "Early-Data" | "EDIINT-Features" | "ETag" | "Expect" | "Expect-CT" | "Expires" | "Ext" | "Forwarded" | "From" | "GetProfile" | "Hobareg" | "Host" | "HTTP2-Settings" | "If" | "If-Match" | "If-Modified-Since" | "If-None-Match" | "If-Range" | "If-Schedule-Tag-Match" | "If-Unmodified-Since" | "IM" | "Include-Referred-Token-Binding-ID" | "Isolation" | "Keep-Alive" | "Label" | "Last-Event-ID" | "Last-Modified" | "Link" | "Link-Template" | "Location" | "Lock-Token" | "Man" | "Max-Forwards" | "Memento-Datetime" | "Meter" | "Method-Check" | "Method-Check-Expires" | "MIME-Version" | "Negotiate" | "NEL" | "OData-EntityId" | "OData-Isolation" | "OData-MaxVersion" | "OData-Version" | "Opt" | "Optional-WWW-Authenticate" | "Ordering-Type" | "Origin" | "Origin-Agent-Cluster" | "OSCORE" | "OSLC-Core-Version" | "Overwrite" | "P3P" | "PEP" | "PEP-Info" | "Permissions-Policy" | "PICS-Label" | "Ping-From" | "Ping-To" | "Position" | "Pragma" | "Prefer" | "Preference-Applied" | "Priority" | "ProfileObject" | "Protocol" | "Protocol-Info" | "Protocol-Query" | "Protocol-Request" | "Proxy-Authenticate" | "Proxy-Authentication-Info" | "Proxy-Authorization" | "Proxy-Features" | "Proxy-Instruction" | "Proxy-Status" | "Public" | "Public-Key-Pins" | "Public-Key-Pins-Report-Only" | "Range" | "Redirect-Ref" | "Referer" | "Referer-Root" | "Referrer-Policy" | "Refresh" | "Repeatability-Client-ID" | "Repeatability-First-Sent" | "Repeatability-Request-ID" | "Repeatability-Result" | "Replay-Nonce" | "Reporting-Endpoints" | "Repr-Digest" | "Retry-After" | "Safe" | "Schedule-Reply" | "Schedule-Tag" | "Sec-GPC" | "Sec-Purpose" | "Sec-Token-Binding" | "Sec-WebSocket-Accept" | "Sec-WebSocket-Extensions" | "Sec-WebSocket-Key" | "Sec-WebSocket-Protocol" | "Sec-WebSocket-Version" | "Security-Scheme" | "Server" | "Server-Timing" | "Set-Cookie" | "Set-Cookie2" | "SetProfile" | "Signature" | "Signature-Input" | "SLUG" | "SoapAction" | "Status-URI" | "Strict-Transport-Security" | "Sunset" | "Surrogate-Capability" | "Surrogate-Control" | "TCN" | "TE" | "Timeout" | "Timing-Allow-Origin" | "Topic" | "Traceparent" | "Tracestate" | "Trailer" | "Transfer-Encoding" | "TTL" | "Upgrade" | "Urgency" | "URI" | "Use-As-Dictionary" | "User-Agent" | "Variant-Vary" | "Vary" | "Via" | "Want-Content-Digest" | "Want-Digest" | "Want-Repr-Digest" | "Warning" | "WWW-Authenticate" | "X-Content-Type-Options" | "X-Frame-Options" | (string & {});
317
333
  /** Outbound webhook executor operation. Sends HTTP requests to external URLs. */
@@ -332,7 +348,7 @@ type WorkflowInput$1<W extends Workflow> = Parameters<W["trigger"]>[0];
332
348
  type WorkflowOperation<Args, W extends Workflow = Workflow> = Omit<WorkflowOperation$1, "workflowName" | "args" | "authInvoker"> & {
333
349
  workflow: W;
334
350
  args?: WorkflowInput$1<W> | ((args: Args) => WorkflowInput$1<W>);
335
- authInvoker?: AuthInvoker<string>;
351
+ authInvoker?: AuthInvoker<string> | MachineUserName;
336
352
  };
337
353
  type Operation<Args> = FunctionOperation<Args> | GqlOperation<Args> | WebhookOperation<Args> | WorkflowOperation<Args>;
338
354
  //#endregion
@@ -647,7 +663,7 @@ type Executor<T extends Trigger<unknown>, O> = O extends {
647
663
  kind: "workflow";
648
664
  workflow: W;
649
665
  args?: WorkflowInput<W> | ((args: TriggerArgs<T>) => WorkflowInput<W>);
650
- authInvoker?: AuthInvoker<string>;
666
+ authInvoker?: AuthInvoker<string> | MachineUserName;
651
667
  };
652
668
  } : ExecutorBase<T> & {
653
669
  operation: O;
@@ -697,6 +713,74 @@ declare function createExecutor<Args, O extends Operation<Args> | {
697
713
  workflow: Workflow;
698
714
  }>(config: Executor<Trigger<Args>, O>): Executor<Trigger<Args>, O>;
699
715
  //#endregion
716
+ //#region src/configure/services/idp/permission.d.ts
717
+ type EqualityOperator = "=" | "!=";
718
+ type ContainsOperator = "in" | "not in";
719
+ type StringFieldKeys<User extends object> = { [K in keyof User]: User[K] extends string ? K : never }[keyof User];
720
+ type StringArrayFieldKeys<User extends object> = { [K in keyof User]: User[K] extends string[] ? K : never }[keyof User];
721
+ type BooleanFieldKeys<User extends object> = { [K in keyof User]: User[K] extends boolean ? K : never }[keyof User];
722
+ type BooleanArrayFieldKeys<User extends object> = { [K in keyof User]: User[K] extends boolean[] ? K : never }[keyof User];
723
+ type UserStringOperand<User extends object = InferredAttributeMap> = {
724
+ user: StringFieldKeys<User> | "id";
725
+ };
726
+ type UserStringArrayOperand<User extends object = InferredAttributeMap> = {
727
+ user: StringArrayFieldKeys<User>;
728
+ };
729
+ type UserBooleanOperand<User extends object = InferredAttributeMap> = {
730
+ user: BooleanFieldKeys<User> | "_loggedIn";
731
+ };
732
+ type UserBooleanArrayOperand<User extends object = InferredAttributeMap> = {
733
+ user: BooleanArrayFieldKeys<User>;
734
+ };
735
+ type IdPUserOperand<Update extends boolean = false> = Update extends true ? {
736
+ oldIdpUser: IdPUserField;
737
+ } | {
738
+ newIdpUser: IdPUserField;
739
+ } : {
740
+ idpUser: IdPUserField;
741
+ };
742
+ type StringEqualityCondition<User extends object, Update extends boolean> = readonly [string, EqualityOperator, string] | readonly [UserStringOperand<User>, EqualityOperator, string] | readonly [string, EqualityOperator, UserStringOperand<User>] | readonly [IdPUserOperand<Update>, EqualityOperator, string | UserStringOperand<User> | IdPUserOperand<Update>] | readonly [string | UserStringOperand<User>, EqualityOperator, IdPUserOperand<Update>];
743
+ type BooleanEqualityCondition<User extends object, Update extends boolean> = readonly [boolean, EqualityOperator, boolean] | readonly [UserBooleanOperand<User>, EqualityOperator, boolean] | readonly [boolean, EqualityOperator, UserBooleanOperand<User>] | readonly [IdPUserOperand<Update>, EqualityOperator, boolean | UserBooleanOperand<User> | IdPUserOperand<Update>] | readonly [boolean | UserBooleanOperand<User>, EqualityOperator, IdPUserOperand<Update>];
744
+ type EqualityCondition<User extends object = InferredAttributeMap, Update extends boolean = boolean> = StringEqualityCondition<User, Update> | BooleanEqualityCondition<User, Update>;
745
+ type StringContainsCondition<User extends object, Update extends boolean> = readonly [string, ContainsOperator, string[]] | readonly [UserStringOperand<User>, ContainsOperator, string[]] | readonly [string, ContainsOperator, UserStringArrayOperand<User>] | readonly [IdPUserOperand<Update>, ContainsOperator, string[] | UserStringArrayOperand<User>];
746
+ type BooleanContainsCondition<User extends object, Update extends boolean> = readonly [boolean, ContainsOperator, boolean[]] | readonly [UserBooleanOperand<User>, ContainsOperator, boolean[]] | readonly [boolean, ContainsOperator, UserBooleanArrayOperand<User>] | readonly [IdPUserOperand<Update>, ContainsOperator, boolean[] | UserBooleanArrayOperand<User>];
747
+ type ContainsCondition<User extends object = InferredAttributeMap, Update extends boolean = boolean> = StringContainsCondition<User, Update> | BooleanContainsCondition<User, Update>;
748
+ type IdPPermissionCondition<User extends object = InferredAttributeMap, Update extends boolean = boolean> = EqualityCondition<User, Update> | ContainsCondition<User, Update>;
749
+ type IdPActionPermission<User extends object = InferredAttributeMap, Update extends boolean = boolean> = {
750
+ conditions: IdPPermissionCondition<User, Update> | readonly IdPPermissionCondition<User, Update>[];
751
+ description?: string | undefined;
752
+ permit?: boolean;
753
+ } | readonly [...IdPPermissionCondition<User, Update>, ...([] | [boolean])] | readonly [...IdPPermissionCondition<User, Update>[], ...([] | [boolean])];
754
+ /**
755
+ * Per-operation permission policies for an IdP service.
756
+ * Defines create, read, update, delete, and sendPasswordResetEmail permissions.
757
+ *
758
+ * For update operations, use `newIdpUser`/`oldIdpUser` operands instead of `idpUser`.
759
+ * @example
760
+ * const permission: IdPPermission = {
761
+ * create: [{ conditions: [[{ user: "role" }, "=", "ADMIN"]], permit: true }],
762
+ * read: [{ conditions: [[{ user: "_loggedIn" }, "=", true]], permit: true }],
763
+ * update: [{ conditions: [[{ newIdpUser: "name" }, "=", { user: "id" }]], permit: true }],
764
+ * delete: [{ conditions: [[{ user: "role" }, "=", "ADMIN"]], permit: true }],
765
+ * sendPasswordResetEmail: [{ conditions: [], permit: true }],
766
+ * };
767
+ */
768
+ type IdPPermission<User extends object = InferredAttributeMap> = {
769
+ create: readonly IdPActionPermission<User, false>[];
770
+ read: readonly IdPActionPermission<User, false>[];
771
+ update: readonly IdPActionPermission<User, true>[];
772
+ delete: readonly IdPActionPermission<User, false>[];
773
+ sendPasswordResetEmail: readonly IdPActionPermission<User, false>[];
774
+ };
775
+ /**
776
+ * Grants full IdP permission access without any conditions.
777
+ *
778
+ * Unsafe and intended only for local development, prototyping, or tests.
779
+ * Do not use this in production environments, as it effectively disables
780
+ * authorization checks.
781
+ */
782
+ declare const unsafeAllowAllIdPPermission: IdPPermission;
783
+ //#endregion
700
784
  //#region src/configure/services/idp/index.d.ts
701
785
  /**
702
786
  * Define an IdP service configuration for the Tailor SDK.
@@ -705,8 +789,9 @@ declare function createExecutor<Args, O extends Operation<Args> | {
705
789
  * @param config - IdP configuration
706
790
  * @returns Defined IdP service
707
791
  */
708
- declare function defineIdp<const TClients extends string[]>(name: string, config: Omit<IdPInput, "name" | "clients"> & {
792
+ declare function defineIdp<const TClients extends string[]>(name: string, config: Omit<IdPInput, "name" | "clients" | "permission"> & {
709
793
  clients: TClients;
794
+ permission?: IdPPermission;
710
795
  }): {
711
796
  readonly name: string;
712
797
  readonly provider: (providerName: string, clientName: TClients[number]) => {
@@ -746,6 +831,7 @@ declare function defineIdp<const TClients extends string[]>(name: string, config
746
831
  passwordResetSubject?: string | undefined;
747
832
  } | undefined;
748
833
  readonly clients: TClients;
834
+ readonly permission?: IdPPermission;
749
835
  } & IdpDefinitionBrand;
750
836
  //#endregion
751
837
  //#region src/configure/config.d.ts
@@ -869,5 +955,5 @@ declare namespace t {
869
955
  type infer<T> = TailorOutput<T>;
870
956
  }
871
957
  //#endregion
872
- export { createWorkflow as $, ResolverExecutedArgs as A, idpUserUpdatedTrigger as B, IdpUserCreatedArgs as C, RecordCreatedArgs as D, IdpUserUpdatedArgs as E, authAccessTokenRevokedTrigger as F, resolverExecutedTrigger as G, recordDeletedTrigger as H, authAccessTokenTrigger as I, Operation as J, FunctionOperation as K, idpUserCreatedTrigger as L, TailorDBTrigger as M, authAccessTokenIssuedTrigger as N, RecordDeletedArgs as O, authAccessTokenRefreshedTrigger as P, WorkflowConfig as Q, idpUserDeletedTrigger as R, IdpUserArgs as S, IdpUserTrigger as T, recordTrigger as U, recordCreatedTrigger as V, recordUpdatedTrigger as W, WorkflowOperation as X, WebhookOperation as Y, Workflow as Z, AuthAccessTokenArgs as _, defineGenerators as a, createWorkflowJob as at, AuthAccessTokenRevokedArgs as b, createExecutor as c, AuthInvoker as ct, IncomingWebhookRequest as d, WORKFLOW_TEST_ENV_KEY as et, IncomingWebhookTrigger as f, scheduleTrigger as g, ScheduleTrigger as h, defineConfig as i, WorkflowJobOutput as it, ResolverExecutedTrigger as j, RecordUpdatedArgs as k, Trigger as l, defineAuth as lt, ScheduleArgs as m, output as n, WorkflowJobContext as nt, definePlugins as o, QueryType as ot, incomingWebhookTrigger as p, GqlOperation as q, t as r, WorkflowJobInput as rt, defineIdp as s, createResolver as st, infer as t, WorkflowJob as tt, IncomingWebhookArgs as u, AuthAccessTokenIssuedArgs as v, IdpUserDeletedArgs as w, AuthAccessTokenTrigger as x, AuthAccessTokenRefreshedArgs as y, idpUserTrigger as z };
873
- //# sourceMappingURL=index--9iVDOXn.d.mts.map
958
+ export { WorkflowOperation as $, RecordCreatedArgs as A, idpUserCreatedTrigger as B, AuthAccessTokenRevokedArgs as C, IdpUserDeletedArgs as D, IdpUserCreatedArgs as E, TailorDBTrigger as F, recordDeletedTrigger as G, idpUserTrigger as H, authAccessTokenIssuedTrigger as I, resolverExecutedTrigger as J, recordTrigger as K, authAccessTokenRefreshedTrigger as L, RecordUpdatedArgs as M, ResolverExecutedArgs as N, IdpUserTrigger as O, ResolverExecutedTrigger as P, WebhookOperation as Q, authAccessTokenRevokedTrigger as R, AuthAccessTokenRefreshedArgs as S, IdpUserArgs as T, idpUserUpdatedTrigger as U, idpUserDeletedTrigger as V, recordCreatedTrigger as W, GqlOperation as X, FunctionOperation as Y, Operation as Z, ScheduleArgs as _, defineGenerators as a, WorkflowJobContext as at, AuthAccessTokenArgs as b, IdPPermission as c, createWorkflowJob as ct, createExecutor as d, AuthInvoker as dt, Workflow as et, Trigger as f, defineAuth as ft, incomingWebhookTrigger as g, IncomingWebhookTrigger as h, defineConfig as i, WorkflowJob as it, RecordDeletedArgs as j, IdpUserUpdatedArgs as k, IdPPermissionCondition as l, QueryType as lt, IncomingWebhookRequest as m, MachineUserNameRegistry as mt, output as n, createWorkflow as nt, definePlugins as o, WorkflowJobInput as ot, IncomingWebhookArgs as p, MachineUserName as pt, recordUpdatedTrigger as q, t as r, WORKFLOW_TEST_ENV_KEY as rt, defineIdp as s, WorkflowJobOutput as st, infer as t, WorkflowConfig as tt, unsafeAllowAllIdPPermission as u, createResolver as ut, ScheduleTrigger as v, AuthAccessTokenTrigger as w, AuthAccessTokenIssuedArgs as x, scheduleTrigger as y, authAccessTokenTrigger as z };
959
+ //# sourceMappingURL=index-BVJQLjyN.d.mts.map
@@ -1,5 +1,5 @@
1
1
  /// <reference types="@tailor-platform/function-types" />
2
- import { n as Plugin } from "./plugin-D8hKE6rZ.mjs";
2
+ import { n as Plugin } from "./plugin-D6P4g_2L.mjs";
3
3
 
4
4
  //#region src/plugin/builtin/file-utils/index.d.ts
5
5
  /** Unique identifier for the file utilities generator plugin. */
@@ -16,4 +16,4 @@ type FileUtilsPluginOptions = {
16
16
  declare function fileUtilsPlugin(options: FileUtilsPluginOptions): Plugin<unknown, FileUtilsPluginOptions>;
17
17
  //#endregion
18
18
  export { fileUtilsPlugin as n, FileUtilsGeneratorID as t };
19
- //# sourceMappingURL=index-D4pBPp65.d.mts.map
19
+ //# sourceMappingURL=index-C3kcXHXJ.d.mts.map
@@ -1,5 +1,5 @@
1
1
  /// <reference types="@tailor-platform/function-types" />
2
- import { n as Plugin } from "./plugin-D8hKE6rZ.mjs";
2
+ import { n as Plugin } from "./plugin-D6P4g_2L.mjs";
3
3
 
4
4
  //#region src/plugin/builtin/enum-constants/index.d.ts
5
5
  /** Unique identifier for the enum constants generator plugin. */
@@ -16,4 +16,4 @@ type EnumConstantsPluginOptions = {
16
16
  declare function enumConstantsPlugin(options: EnumConstantsPluginOptions): Plugin<unknown, EnumConstantsPluginOptions>;
17
17
  //#endregion
18
18
  export { enumConstantsPlugin as n, EnumConstantsGeneratorID as t };
19
- //# sourceMappingURL=index-niQ9Qblw.d.mts.map
19
+ //# sourceMappingURL=index-CeS4FA9o.d.mts.map
@@ -1,5 +1,5 @@
1
1
  /// <reference types="@tailor-platform/function-types" />
2
- import { n as Plugin } from "./plugin-D8hKE6rZ.mjs";
2
+ import { n as Plugin } from "./plugin-D6P4g_2L.mjs";
3
3
 
4
4
  //#region src/plugin/builtin/seed/index.d.ts
5
5
  /** Unique identifier for the seed generator plugin. */
@@ -18,4 +18,4 @@ type SeedPluginOptions = {
18
18
  declare function seedPlugin(options: SeedPluginOptions): Plugin<unknown, SeedPluginOptions>;
19
19
  //#endregion
20
20
  export { seedPlugin as n, SeedGeneratorID as t };
21
- //# sourceMappingURL=index-qVqjEYnr.d.mts.map
21
+ //# sourceMappingURL=index-DnIg_LfT.d.mts.map
@@ -31,4 +31,4 @@ function createTracingInterceptor() {
31
31
 
32
32
  //#endregion
33
33
  export { createTracingInterceptor };
34
- //# sourceMappingURL=interceptor-f7slMkCC.mjs.map
34
+ //# sourceMappingURL=interceptor-dSNiQq71.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"interceptor-f7slMkCC.mjs","names":[],"sources":["../src/cli/telemetry/interceptor.ts"],"sourcesContent":["import { trace, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Interceptor } from \"@connectrpc/connect\";\n\n/**\n * Create a Connect-RPC interceptor that records OTLP spans for each RPC call.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @returns Tracing interceptor\n */\nexport function createTracingInterceptor(): Interceptor {\n return (next) => async (req) => {\n const tracer = trace.getTracer(\"tailor-sdk\");\n\n return tracer.startActiveSpan(`rpc.${req.method.name}`, async (span) => {\n span.setAttribute(\"rpc.method\", req.method.name);\n span.setAttribute(\"rpc.service\", \"OperatorService\");\n span.setAttribute(\"rpc.system\", \"connect-rpc\");\n\n try {\n const response = await next(req);\n span.setStatus({ code: SpanStatusCode.OK });\n return response;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,2BAAwC;AACtD,SAAQ,SAAS,OAAO,QAAQ;AAG9B,SAFe,MAAM,UAAU,aAAa,CAE9B,gBAAgB,OAAO,IAAI,OAAO,QAAQ,OAAO,SAAS;AACtE,QAAK,aAAa,cAAc,IAAI,OAAO,KAAK;AAChD,QAAK,aAAa,eAAe,kBAAkB;AACnD,QAAK,aAAa,cAAc,cAAc;AAE9C,OAAI;IACF,MAAM,WAAW,MAAM,KAAK,IAAI;AAChC,SAAK,UAAU,EAAE,MAAM,eAAe,IAAI,CAAC;AAC3C,WAAO;YACA,OAAO;AACd,SAAK,UAAU,EAAE,MAAM,eAAe,OAAO,CAAC;AAC9C,QAAI,iBAAiB,MACnB,MAAK,gBAAgB,MAAM;AAE7B,UAAM;aACE;AACR,SAAK,KAAK;;IAEZ"}
1
+ {"version":3,"file":"interceptor-dSNiQq71.mjs","names":[],"sources":["../src/cli/telemetry/interceptor.ts"],"sourcesContent":["import { trace, SpanStatusCode } from \"@opentelemetry/api\";\nimport type { Interceptor } from \"@connectrpc/connect\";\n\n/**\n * Create a Connect-RPC interceptor that records OTLP spans for each RPC call.\n * When no TracerProvider is registered, the OTel API automatically provides\n * noop spans with zero overhead.\n * @returns Tracing interceptor\n */\nexport function createTracingInterceptor(): Interceptor {\n return (next) => async (req) => {\n const tracer = trace.getTracer(\"tailor-sdk\");\n\n return tracer.startActiveSpan(`rpc.${req.method.name}`, async (span) => {\n span.setAttribute(\"rpc.method\", req.method.name);\n span.setAttribute(\"rpc.service\", \"OperatorService\");\n span.setAttribute(\"rpc.system\", \"connect-rpc\");\n\n try {\n const response = await next(req);\n span.setStatus({ code: SpanStatusCode.OK });\n return response;\n } catch (error) {\n span.setStatus({ code: SpanStatusCode.ERROR });\n if (error instanceof Error) {\n span.recordException(error);\n }\n throw error;\n } finally {\n span.end();\n }\n });\n };\n}\n"],"mappings":";;;;;;;;;;AASA,SAAgB,2BAAwC;AACtD,SAAQ,SAAS,OAAO,QAAQ;AAG9B,SAFe,MAAM,UAAU,aAAa,CAE9B,gBAAgB,OAAO,IAAI,OAAO,QAAQ,OAAO,SAAS;AACtE,QAAK,aAAa,cAAc,IAAI,OAAO,KAAK;AAChD,QAAK,aAAa,eAAe,kBAAkB;AACnD,QAAK,aAAa,cAAc,cAAc;AAE9C,OAAI;IACF,MAAM,WAAW,MAAM,KAAK,IAAI;AAChC,SAAK,UAAU,EAAE,MAAM,eAAe,IAAI,CAAC;AAC3C,WAAO;YACA,OAAO;AACd,SAAK,UAAU,EAAE,MAAM,eAAe,OAAO,CAAC;AAC9C,QAAI,iBAAiB,MACnB,MAAK,gBAAgB,MAAM;AAE7B,UAAM;aACE;AACR,SAAK,KAAK;;IAEZ"}
@@ -1,5 +1,5 @@
1
1
 
2
- import { t as brandValue } from "./brand-0SscafcY.mjs";
2
+ import { t as brandValue } from "./brand-D-d15jx3.mjs";
3
3
 
4
4
  //#region src/configure/services/workflow/job.ts
5
5
  /**
@@ -51,4 +51,4 @@ const createWorkflowJob = (config) => {
51
51
 
52
52
  //#endregion
53
53
  export { createWorkflowJob as n, WORKFLOW_TEST_ENV_KEY as t };
54
- //# sourceMappingURL=job-CPKYCk_e.mjs.map
54
+ //# sourceMappingURL=job-DkAklmE4.mjs.map