@tailor-platform/sdk 2.15.0 → 2.16.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 (75) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/dist/application-Dw3t9p2f.mjs +1 -0
  3. package/dist/{application-BpoMu4Af.mjs → application-wYQ-ivDg.mjs} +27 -27
  4. package/dist/application-wYQ-ivDg.mjs.map +1 -0
  5. package/dist/cli/commands/executor/jobs.d.mts +1 -0
  6. package/dist/cli/commands/generate/seed/bundler.d.mts +18 -0
  7. package/dist/cli/commands/tailordb/migrate/config.d.mts +1 -0
  8. package/dist/cli/commands/workflow/waiter.d.mts +1 -0
  9. package/dist/cli/commands/workspace/create.d.mts +16 -1
  10. package/dist/cli/commands/workspace/expiry.d.mts +5 -0
  11. package/dist/cli/commands/workspace/get.d.mts +6 -1
  12. package/dist/cli/commands/workspace/list.d.mts +1 -0
  13. package/dist/cli/lib.d.mts +3 -2
  14. package/dist/cli/lib.mjs +1 -1
  15. package/dist/cli/lib.mjs.map +1 -1
  16. package/dist/cli/main.mjs +50 -52
  17. package/dist/cli/main.mjs.map +1 -1
  18. package/dist/cli/shared/command.d.mts +1 -1
  19. package/dist/cli/shared/error-json.d.mts +2 -1
  20. package/dist/cli/shared/errors.d.mts +1 -0
  21. package/dist/cli/shared/github-actions.d.mts +13 -0
  22. package/dist/completion/zsh-worker.zsh +91 -3
  23. package/dist/crashreport-DF8YMIE5.mjs +1 -0
  24. package/dist/{crashreport-BN28xp5B.mjs → crashreport-Doz2Kuuq.mjs} +2 -2
  25. package/dist/{crashreport-BN28xp5B.mjs.map → crashreport-Doz2Kuuq.mjs.map} +1 -1
  26. package/dist/errors-BtTxkzgy.mjs +7 -0
  27. package/dist/errors-BtTxkzgy.mjs.map +1 -0
  28. package/dist/guards-ForsrxnH.mjs +2 -0
  29. package/dist/guards-ForsrxnH.mjs.map +1 -0
  30. package/dist/{logger-CCjs1DuH.mjs → logger-CEAxByN5.mjs} +3 -3
  31. package/dist/{logger-CCjs1DuH.mjs.map → logger-CEAxByN5.mjs.map} +1 -1
  32. package/dist/manager-E3ffRcCt.mjs +2 -0
  33. package/dist/manager-E3ffRcCt.mjs.map +1 -0
  34. package/dist/node-builtins-DYfhPBnz.mjs +2 -0
  35. package/dist/node-builtins-DYfhPBnz.mjs.map +1 -0
  36. package/dist/plugin/builtin/seed/index.mjs +1 -1
  37. package/dist/plugin/builtin/seed/seed-type-processor.d.mts +17 -0
  38. package/dist/plugin/get-generated-table.d.mts +13 -0
  39. package/dist/plugin/index.d.mts +2 -2
  40. package/dist/plugin/index.mjs +1 -1
  41. package/dist/plugin/index.mjs.map +1 -1
  42. package/dist/register-ts-hook-DrHS-J1k.mjs +878 -0
  43. package/dist/register-ts-hook-DrHS-J1k.mjs.map +1 -0
  44. package/dist/{seed-CCc9Xk66.mjs → seed-C3P_T_Eh.mjs} +28 -9
  45. package/dist/seed-C3P_T_Eh.mjs.map +1 -0
  46. package/dist/service-Cw7hb5HK.mjs +2 -0
  47. package/dist/service-Cw7hb5HK.mjs.map +1 -0
  48. package/dist/service-DaoW0kzo.mjs +7 -0
  49. package/dist/service-DaoW0kzo.mjs.map +1 -0
  50. package/dist/service-dn9jxC8c.mjs +1 -0
  51. package/dist/utils/test/index.d.mts +7 -5
  52. package/dist/utils/test/index.mjs +1 -1
  53. package/dist/utils/test/index.mjs.map +1 -1
  54. package/dist/vitest/index.mjs +1 -1
  55. package/docs/cli/tailordb.md +1 -1
  56. package/docs/cli/workspace.md +133 -20
  57. package/docs/cli-reference.md +94 -25
  58. package/docs/plugin/custom.md +36 -4
  59. package/docs/services/tailordb-migration.md +6 -4
  60. package/package.json +4 -4
  61. package/dist/application-BpoMu4Af.mjs.map +0 -1
  62. package/dist/application-fIhVKX78.mjs +0 -1
  63. package/dist/crashreport-By23O2k-.mjs +0 -1
  64. package/dist/errors-BlX4gUw5.mjs +0 -4
  65. package/dist/errors-BlX4gUw5.mjs.map +0 -1
  66. package/dist/node-builtins-TQHhwNzG.mjs +0 -2
  67. package/dist/node-builtins-TQHhwNzG.mjs.map +0 -1
  68. package/dist/register-ts-hook-CAUcxCt4.mjs +0 -711
  69. package/dist/register-ts-hook-CAUcxCt4.mjs.map +0 -1
  70. package/dist/seed-CCc9Xk66.mjs.map +0 -1
  71. package/dist/service-7SCy2bhm.mjs +0 -7
  72. package/dist/service-7SCy2bhm.mjs.map +0 -1
  73. package/dist/service-CWFQ8EVo.mjs +0 -1
  74. package/dist/service-CqbQXFDp.mjs +0 -2
  75. package/dist/service-CqbQXFDp.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"manager-E3ffRcCt.mjs","names":[],"sources":["../src/plugin/manager.ts"],"sourcesContent":["import { db, type TailorAnyDBType } from \"#/configure/services/tailordb/index\";\nimport {\n getPluginGenerationDependencies,\n getRawPluginTableName,\n hasGenerationHooks,\n} from \"#/plugin/guards\";\nimport { assertDefined } from \"#/utils/assert\";\nimport type {\n TailorTypePermission,\n TailorTypeGqlPermission,\n} from \"#/configure/services/tailordb/permission\";\nimport type {\n TailorAnyDBField,\n TypeHook,\n TypeValidateFn,\n} from \"#/configure/services/tailordb/types\";\nimport type {\n DependencyKind,\n Plugin,\n PluginAttachment,\n PluginGeneratedExecutor,\n PluginGeneratedTable,\n PluginNamespaceProcessContext,\n PluginOutput,\n TablePluginOutput,\n} from \"#/plugin/types\";\nimport type { TailorDBTypeRaw } from \"#/types/tailordb.generated\";\n\n/**\n * Context for processing a single plugin attachment on a raw TailorDBType\n */\nexport interface ProcessAttachmentContext {\n table: TailorAnyDBType;\n tableConfig: unknown;\n namespace: string;\n pluginId: string;\n}\n\n/**\n * Information about a plugin-generated table (for table file generation)\n */\nexport interface PluginGeneratedTableInfo {\n /** Plugin ID that generated this table */\n pluginId: string;\n /** Plugin import path for resolving executor files */\n pluginImportPath: string;\n /** Source table name that triggered the plugin */\n sourceTableName: string;\n /** Kind identifier for this generated table */\n kind: string;\n /** The generated TailorDB table object */\n table: PluginGeneratedTable;\n /** Namespace where this table was generated */\n namespace: string;\n /** Plugin config used to generate this table */\n pluginConfig?: unknown;\n}\n\n/**\n * Extended executor info with plugin import path\n */\nexport interface PluginExecutorInfoExtended extends PluginExecutorInfo {\n /** Plugin's import path for resolving executor files */\n pluginImportPath: string;\n}\n\n/**\n * Result of processing a table-attached plugin\n */\nexport type ProcessAttachmentResult =\n | { success: true; output: TablePluginOutput }\n | { success: false; error: string };\n\n/**\n * Result of processing a namespace plugin\n */\nexport type ProcessNamespaceResult =\n | { success: true; output: PluginOutput }\n | { success: false; error: string };\n\n/**\n * Parameters for processing all plugin attachments of a TailorDB table.\n */\nexport interface ProcessAttachmentsForTableParams {\n rawTable: TailorDBTypeRaw;\n attachments: PluginAttachment[];\n namespace: string;\n}\n\n/**\n * Progress event emitted while processing plugin attachments for a TailorDB table.\n * Plain data so the caller (typically the cli) can format and output it.\n */\ntype ProcessAttachmentEvent =\n | { kind: \"extended\"; tableName: string; fieldCount: number; pluginId: string }\n | { kind: \"generated\"; tableName: string; pluginId: string };\n\n/**\n * Generated table produced by a plugin during attachment processing.\n * `table` is raw plugin output; the caller must validate it before use.\n */\ninterface ProcessAttachmentsGeneratedTable {\n tableName: string;\n table: unknown;\n kind: string;\n pluginId: string;\n pluginImportPath: string;\n pluginConfig?: unknown;\n}\n\n/**\n * Result of {@link PluginManager.processAttachmentsForTable}.\n */\nexport interface ProcessAttachmentsForTableResult {\n /**\n * Final table after all extends are applied; undefined if no plugin extended the table.\n * Raw builder output; the caller must validate it before use.\n */\n extendedTable?: unknown;\n /** Tables newly generated by plugins for this attachment chain. */\n generatedTables: ProcessAttachmentsGeneratedTable[];\n /** Events for the caller to render. */\n events: ProcessAttachmentEvent[];\n}\n\n/**\n * Information about a plugin-generated executor\n */\nexport interface PluginExecutorInfo {\n /** The executor definition */\n executor: PluginGeneratedExecutor;\n /** Plugin ID that generated this executor */\n pluginId: string;\n /** Namespace where the executor was generated */\n namespace: string;\n /** Source table name (for table-attached executors, undefined for namespace) */\n sourceTableName?: string;\n}\n\n/**\n * Manages plugin registration and processing\n */\nexport class PluginManager {\n private plugins: Map<string, Plugin> = new Map();\n private generatedExecutors: PluginExecutorInfo[] = [];\n private generatedTables: PluginGeneratedTableInfo[] = [];\n private namespaceGeneratedTableKeys: Set<string> = new Set();\n private namespaceGeneratedExecutorKeys: Set<string> = new Set();\n\n /** Generated plugin executor file paths */\n private pluginExecutorFiles: string[] = [];\n\n constructor(plugins: Plugin[] = []) {\n for (const plugin of plugins) {\n if (this.plugins.has(plugin.id)) {\n throw new Error(\n `Duplicate plugin ID \"${plugin.id}\" detected. Each plugin must have a unique ID.`,\n );\n }\n this.plugins.set(plugin.id, plugin);\n }\n }\n\n /**\n * Process a single plugin attachment on a raw TailorDBType.\n * This method is called during table loading before parsing.\n * @param context - Context containing the raw table, config, namespace, and plugin ID\n * @returns Result with plugin output on success, or error message on failure\n */\n async processAttachment(context: ProcessAttachmentContext): Promise<ProcessAttachmentResult> {\n const plugin = this.plugins.get(context.pluginId);\n if (!plugin) {\n return {\n success: false,\n error: `Plugin \"${context.pluginId}\" not found`,\n };\n }\n\n const tableConfigRequired = plugin.tableConfigRequired;\n const resolvedRequired =\n typeof tableConfigRequired === \"function\"\n ? tableConfigRequired(plugin.pluginConfig)\n : tableConfigRequired === true;\n if (resolvedRequired && (context.tableConfig === undefined || context.tableConfig === null)) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" requires tableConfig, but none was provided for table \"${context.table.name}\".`,\n };\n }\n\n // Check if plugin supports table-attached processing\n if (!plugin.onTableLoaded) {\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" does not support table-attached processing (missing onTableLoaded method). Use onNamespaceLoaded via definePlugins() instead.`,\n };\n }\n\n // Execute plugin onTableLoaded with the raw TailorDB table\n let output: TablePluginOutput;\n try {\n output = await plugin.onTableLoaded({\n table: context.table,\n tableConfig: context.tableConfig,\n pluginConfig: plugin.pluginConfig,\n namespace: context.namespace,\n });\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error while processing table \"${context.table.name}\": ${message}`,\n };\n }\n\n // Collect generated tables\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n this.generatedTables.push({\n pluginId: context.pluginId,\n pluginImportPath: importPath,\n sourceTableName: context.table.name,\n kind,\n table,\n namespace: context.namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n // Collect generated executors\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n this.generatedExecutors.push({\n executor,\n pluginId: context.pluginId,\n namespace: context.namespace,\n sourceTableName: context.table.name,\n });\n }\n }\n\n return { success: true, output };\n }\n\n /**\n * Process namespace plugins that don't require a source table.\n * This method is called once per namespace for plugins with onNamespaceLoaded method.\n * @param namespace - The target namespace for generated tables\n * @returns Array of results with plugin outputs and configs\n */\n async processNamespacePlugins(\n namespace: string,\n ): Promise<Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }>> {\n const results: Array<{ pluginId: string; config: unknown; result: ProcessNamespaceResult }> =\n [];\n\n for (const [pluginId, plugin] of this.plugins) {\n // Skip plugins without onNamespaceLoaded method\n if (!plugin.onNamespaceLoaded) {\n continue;\n }\n\n // Use stored plugin config (from definePlugins)\n const config = plugin.pluginConfig;\n\n // Execute plugin onNamespaceLoaded\n const context: PluginNamespaceProcessContext = {\n pluginConfig: config,\n namespace,\n };\n\n let output: Awaited<ReturnType<NonNullable<Plugin[\"onNamespaceLoaded\"]>>>;\n try {\n output = await plugin.onNamespaceLoaded(context);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n results.push({\n pluginId,\n config,\n result: {\n success: false,\n error: `Plugin \"${plugin.id}\" threw an error during namespace processing for \"${namespace}\": ${message}`,\n },\n });\n continue;\n }\n\n // Collect generated executors (namespace - no source table)\n if (output.executors && output.executors.length > 0) {\n for (const executor of output.executors) {\n const executorKey = `${pluginId}:${executor.name}`;\n if (this.namespaceGeneratedExecutorKeys.has(executorKey)) {\n continue;\n }\n this.namespaceGeneratedExecutorKeys.add(executorKey);\n this.generatedExecutors.push({\n executor,\n pluginId,\n namespace,\n });\n }\n }\n\n // Collect generated tables (namespace - no source table)\n if (output.tables && Object.keys(output.tables).length > 0) {\n // importPath is guaranteed by schema validation for plugins with definition-time hooks\n const importPath = assertDefined(\n plugin.importPath,\n `plugin \"${plugin.id}\" missing importPath`,\n );\n for (const [kind, table] of Object.entries(output.tables)) {\n const tableKey = `${pluginId}:${kind}:${getRawPluginTableName(table) ?? \"\"}`;\n if (this.namespaceGeneratedTableKeys.has(tableKey)) {\n continue;\n }\n this.namespaceGeneratedTableKeys.add(tableKey);\n this.generatedTables.push({\n pluginId,\n pluginImportPath: importPath,\n sourceTableName: \"(namespace)\",\n kind,\n table,\n namespace,\n pluginConfig: plugin.pluginConfig,\n });\n }\n }\n\n results.push({\n pluginId,\n config,\n result: { success: true, output },\n });\n }\n\n return results;\n }\n\n /**\n * Run every plugin attachment for a single TailorDB table in order, threading the\n * extended table through the chain. Returns plain data (no logging, no shared state)\n * so the caller decides how to apply updates and render progress.\n * @param params - The raw table, its attachments, and the target namespace\n * @returns Final extended table (if any), generated tables, and render events\n */\n async processAttachmentsForTable(\n params: ProcessAttachmentsForTableParams,\n ): Promise<ProcessAttachmentsForTableResult> {\n const { rawTable, attachments, namespace } = params;\n // The runtime value is a configure-layer builder instance; we accept the structural\n // TailorDBTypeRaw at the boundary so callers (cli) don't need to depend on TailorAnyDBType.\n let currentTable: TailorAnyDBType = rawTable as unknown as TailorAnyDBType;\n let extendedTable: TailorAnyDBType | undefined;\n const generatedTables: ProcessAttachmentsGeneratedTable[] = [];\n const events: ProcessAttachmentEvent[] = [];\n\n for (const attachment of attachments) {\n const result = await this.processAttachment({\n table: currentTable,\n tableConfig: attachment.config,\n namespace,\n pluginId: attachment.pluginId,\n });\n if (!result.success) {\n throw new Error(result.error);\n }\n\n const output = result.output;\n const extendFields = output.extends?.fields;\n if (extendFields && Object.keys(extendFields).length > 0) {\n currentTable = this.extendTable({\n originalTable: currentTable,\n extendFields,\n pluginId: attachment.pluginId,\n });\n extendedTable = currentTable;\n events.push({\n kind: \"extended\",\n tableName: currentTable.name,\n fieldCount: Object.keys(extendFields).length,\n pluginId: attachment.pluginId,\n });\n }\n\n const plugin = this.getPlugin(attachment.pluginId);\n for (const [kind, table] of Object.entries(output.tables ?? {})) {\n const tableName = getRawPluginTableName(table) ?? \"\";\n generatedTables.push({\n tableName,\n table,\n kind,\n pluginId: attachment.pluginId,\n pluginImportPath: this.getPluginImportPath(attachment.pluginId) ?? \"\",\n pluginConfig: plugin?.pluginConfig,\n });\n events.push({ kind: \"generated\", tableName, pluginId: attachment.pluginId });\n }\n }\n\n return { extendedTable, generatedTables, events };\n }\n\n /**\n * Get plugins that have onNamespaceLoaded method\n * @returns Array of plugin IDs that support namespace processing\n */\n getNamespacePluginIds(): string[] {\n return Array.from(this.plugins.entries())\n .filter(([, plugin]) => plugin.onNamespaceLoaded !== undefined)\n .map(([id]) => id);\n }\n\n /**\n * Get the count of registered plugins\n * @returns Number of registered plugins\n */\n get pluginCount(): number {\n return this.plugins.size;\n }\n\n /**\n * Get a plugin by its ID\n * @param pluginId - The plugin ID to look up\n * @returns The plugin instance, or undefined if not found\n */\n getPlugin(pluginId: string): Plugin | undefined {\n return this.plugins.get(pluginId);\n }\n\n /**\n * Get the import path for a plugin\n * @param pluginId - The plugin ID to look up\n * @returns The plugin's import path, or undefined if not found\n */\n getPluginImportPath(pluginId: string): string | undefined {\n return this.plugins.get(pluginId)?.importPath;\n }\n\n /**\n * Get all plugin-generated executors\n * @returns Array of plugin-generated executor info\n */\n getPluginGeneratedExecutors(): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors;\n }\n\n /**\n * Get all plugin-generated executors with import paths\n * @returns Array of plugin-generated executor info with import paths\n */\n getPluginGeneratedExecutorsWithImportPath(): ReadonlyArray<PluginExecutorInfoExtended> {\n return this.generatedExecutors.map((info) => ({\n ...info,\n pluginImportPath: this.getPluginImportPath(info.pluginId) ?? \"\",\n }));\n }\n\n /**\n * Get all plugin-generated tables\n * @returns Array of plugin-generated table info\n */\n getPluginGeneratedTables(): ReadonlyArray<PluginGeneratedTableInfo> {\n return this.generatedTables;\n }\n\n /**\n * Get plugin-generated executors for a specific namespace\n * @param namespace - The namespace to filter by\n * @returns Array of plugin-generated executor info for the namespace\n */\n getPluginGeneratedExecutorsForNamespace(namespace: string): ReadonlyArray<PluginExecutorInfo> {\n return this.generatedExecutors.filter((info) => info.namespace === namespace);\n }\n\n /**\n * Get plugins that have any generation-time hooks.\n * @returns Array of plugins with generation hooks\n */\n getPluginsWithGenerationHooks(): Plugin[] {\n return Array.from(this.plugins.values()).filter((plugin) => hasGenerationHooks(plugin));\n }\n\n /**\n * Get the generation-time dependencies for a specific plugin.\n * @param pluginId - The plugin ID to look up\n * @returns Set of dependency kinds, or empty set if plugin not found\n */\n getPluginGenerationDependencies(pluginId: string): Set<DependencyKind> {\n const plugin = this.plugins.get(pluginId);\n if (!plugin) return new Set();\n return getPluginGenerationDependencies(plugin);\n }\n\n /**\n * Generate plugin files (tables and executors) and store the executor file paths.\n * @param params - Parameters for file generation\n * @returns Generated executor file paths\n */\n generatePluginFiles(params: GeneratePluginFilesParams): string[] {\n const { outputDir, sourceTableInfoMap, configPath, tableGenerator, executorGenerator } = params;\n\n // Generate table files\n const tableGenerationResult = tableGenerator(this.generatedTables, outputDir);\n\n // Generate executor files\n const pluginExecutors = this.getPluginGeneratedExecutorsWithImportPath();\n this.pluginExecutorFiles = executorGenerator(\n pluginExecutors,\n outputDir,\n tableGenerationResult,\n sourceTableInfoMap,\n configPath,\n );\n\n return this.pluginExecutorFiles;\n }\n\n /**\n * Extend a TailorDB table with new fields.\n * This method handles the `db.table()` call and metadata copying internally.\n * @param params - Parameters for table extension\n * @returns The extended TailorDB table\n */\n extendTable(params: ExtendTableParams): TailorAnyDBType {\n const { originalTable, extendFields, pluginId } = params;\n const existingFieldNames = Object.keys(originalTable.fields);\n const existingFileNames = Object.keys(originalTable.metadata.files);\n const newFieldNames = Object.keys(extendFields);\n const duplicateFields = newFieldNames.filter((name) => existingFieldNames.includes(name));\n const duplicateFiles = newFieldNames.filter((name) => existingFileNames.includes(name));\n\n if (duplicateFields.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that already exist in table \"${originalTable.name}\": ${duplicateFields.join(\", \")}. ` +\n `extendFields cannot overwrite existing fields.`,\n );\n }\n\n if (duplicateFiles.length > 0) {\n throw new Error(\n `Plugin \"${pluginId}\" attempted to add fields that collide with file keys already declared via .files() on table \"${originalTable.name}\": ${duplicateFiles.join(\", \")}.`,\n );\n }\n\n const mergedFields = {\n ...originalTable.fields,\n ...extendFields,\n };\n\n const { id: _id, ...fieldsWithoutId } = mergedFields;\n const pluralForm = originalTable.metadata.settings?.pluralForm;\n const tableName = pluralForm\n ? ([originalTable.name, pluralForm] as [string, string])\n : originalTable.name;\n const extendedTable = db.table(tableName, fieldsWithoutId);\n return copyMetadataToExtendedTable(originalTable, extendedTable);\n }\n}\n\n/**\n * Source info for user-defined tables\n */\nexport type SourceTableInfo = {\n filePath: string;\n exportName: string;\n};\n\n/**\n * Result of generating plugin table files\n */\nexport interface PluginTableGenerationResult {\n /** Map of table name to generated file path (relative to outputDir) */\n tableFilePaths: Map<string, string>;\n /** List of all generated file paths (absolute) */\n generatedFiles: string[];\n}\n\n/**\n * Parameters for generating plugin files\n */\nexport interface GeneratePluginFilesParams {\n /** Base output directory (e.g., .tailor/plugin) */\n outputDir: string;\n /** Map of source table names to their source info */\n sourceTableInfoMap: Map<string, SourceTableInfo>;\n /** Path to tailor.config.ts (used for resolving plugin import paths) */\n configPath: string;\n /** Function to generate table files */\n tableGenerator: (\n tables: ReadonlyArray<PluginGeneratedTableInfo>,\n outputDir: string,\n ) => PluginTableGenerationResult;\n /** Function to generate executor files */\n executorGenerator: (\n executors: ReadonlyArray<PluginExecutorInfoExtended>,\n outputDir: string,\n tableGenerationResult: PluginTableGenerationResult,\n sourceTableInfoMap: Map<string, SourceTableInfo>,\n configPath: string,\n ) => string[];\n}\n\n/**\n * Parameters for extending a TailorDB table\n */\nexport interface ExtendTableParams {\n /** The original TailorDB table to extend */\n originalTable: TailorAnyDBType;\n /** New fields to add to the table */\n extendFields: Record<string, unknown>;\n /** The ID of the plugin extending the table */\n pluginId: string;\n}\n\n/**\n * Copy metadata from original table to extended table.\n * Preserves files, settings, permissions, indexes, and plugins.\n * @param original - The original TailorDB table with metadata\n * @param extended - The newly created extended table\n * @returns The extended table with copied metadata\n */\nfunction copyMetadataToExtendedTable(\n original: TailorAnyDBType,\n extended: TailorAnyDBType,\n): TailorAnyDBType {\n let result = extended;\n\n // Copy description\n if (original._description) {\n result = result.description(original._description);\n }\n\n // Copy files metadata\n const metadata = original.metadata;\n if (Object.keys(metadata.files).length > 0) {\n result = result.files(metadata.files);\n }\n\n // Copy settings/features (excluding pluralForm which is set during construction)\n if (metadata.settings) {\n const { pluralForm: _pluralForm, ...features } = metadata.settings;\n if (Object.keys(features).length > 0) {\n result = result.features(\n features as typeof features & { aggregation?: true; bulkUpsert?: true },\n );\n }\n }\n\n // Copy permissions from metadata\n // Zod schema operand types are wider unions than the configure layer's discriminated PermissionCondition,\n // so type assertions are needed here.\n if (metadata.permissions.record) {\n result = result.permission(metadata.permissions.record as TailorTypePermission);\n }\n if (metadata.permissions.gql) {\n result = result.gqlPermission(metadata.permissions.gql as TailorTypeGqlPermission);\n }\n\n // Copy indexes from metadata (indexes are stored in metadata, not as a direct property)\n if (metadata.indexes && Object.keys(metadata.indexes).length > 0) {\n const indexDefs = Object.entries(metadata.indexes).map(([name, def]) => ({\n name,\n // Cast fields array to tuple type (IndexDef expects [T, T, ...T[]])\n fields: def.fields as [string, string, ...string[]],\n unique: def.unique,\n }));\n result = result.indexes(...indexDefs);\n }\n\n if (metadata.typeHook) {\n result = result.hooks(metadata.typeHook as TypeHook<Record<string, TailorAnyDBField>>);\n }\n if (metadata.typeValidate) {\n result = result.validate(\n metadata.typeValidate as TypeValidateFn<Record<string, TailorAnyDBField>>,\n );\n }\n\n // Copy plugins (but don't re-process them)\n if (original.plugins.length > 0) {\n for (const plugin of original.plugins) {\n // Use type assertion as plugin ID is dynamic at runtime\n result = result.plugin({\n [plugin.pluginId]: plugin.config,\n });\n }\n }\n\n return result;\n}\n"],"mappings":"6HA8IA,IAAa,cAAb,KAA2B,CACzB,QAAuC,IAAI,IAC3C,mBAAmD,CAAC,EACpD,gBAAsD,CAAC,EACvD,4BAAmD,IAAI,IACvD,+BAAsD,IAAI,IAG1D,oBAAwC,CAAC,EAEzC,YAAY,EAAoB,CAAC,EAAG,CAClC,IAAK,IAAM,KAAU,EAAS,CAC5B,GAAI,KAAK,QAAQ,IAAI,EAAO,EAAE,EAC5B,MAAU,MACR,wBAAwB,EAAO,GAAG,+CACpC,EAEF,KAAK,QAAQ,IAAI,EAAO,GAAI,CAAM,CACpC,CACF,CAQA,MAAM,kBAAkB,EAAqE,CAC3F,IAAM,EAAS,KAAK,QAAQ,IAAI,EAAQ,QAAQ,EAChD,GAAI,CAAC,EACH,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAQ,SAAS,YACrC,EAGF,IAAM,EAAsB,EAAO,oBAKnC,IAHE,OAAO,GAAwB,WAC3B,EAAoB,EAAO,YAAY,EACvC,IAAwB,MACL,EAAQ,cAAgB,IAAA,IAAa,EAAQ,cAAgB,MACpF,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAO,GAAG,2DAA2D,EAAQ,MAAM,KAAK,GAC5G,EAIF,GAAI,CAAC,EAAO,cACV,MAAO,CACL,QAAS,GACT,MAAO,WAAW,EAAO,GAAG,gIAC9B,EAIF,IAAI,EACJ,GAAI,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,EADb,EAAG,MAAM,EAAW,CACoB,CAAC,CACjE,CACF,EAgEA,SAAS,4BACP,EACA,EACiB,CACjB,IAAI,EAAS,EAGT,EAAS,eACX,EAAS,EAAO,YAAY,EAAS,YAAY,GAInD,IAAM,EAAW,EAAS,SAM1B,GALI,OAAO,KAAK,EAAS,KAAK,CAAC,CAAC,OAAS,IACvC,EAAS,EAAO,MAAM,EAAS,KAAK,GAIlC,EAAS,SAAU,CACrB,GAAM,CAAE,WAAY,EAAa,GAAG,GAAa,EAAS,SACtD,OAAO,KAAK,CAAQ,CAAC,CAAC,OAAS,IACjC,EAAS,EAAO,SACd,CACF,EAEJ,CAaA,GARI,EAAS,YAAY,SACvB,EAAS,EAAO,WAAW,EAAS,YAAY,MAA8B,GAE5E,EAAS,YAAY,MACvB,EAAS,EAAO,cAAc,EAAS,YAAY,GAA8B,GAI/E,EAAS,SAAW,OAAO,KAAK,EAAS,OAAO,CAAC,CAAC,OAAS,EAAG,CAChE,IAAM,EAAY,OAAO,QAAQ,EAAS,OAAO,CAAC,CAAC,KAAK,CAAC,EAAM,MAAU,CACvE,OAEA,OAAQ,EAAI,OACZ,OAAQ,EAAI,MACd,EAAE,EACF,EAAS,EAAO,QAAQ,GAAG,CAAS,CACtC,CAYA,GAVI,EAAS,WACX,EAAS,EAAO,MAAM,EAAS,QAAsD,GAEnF,EAAS,eACX,EAAS,EAAO,SACd,EAAS,YACX,GAIE,EAAS,QAAQ,OAAS,EAC5B,IAAK,IAAM,KAAU,EAAS,QAE5B,EAAS,EAAO,OAAO,EACpB,EAAO,UAAW,EAAO,MAC5B,CAAC,EAIL,OAAO,CACT"}
@@ -0,0 +1,2 @@
1
+ import{isBuiltin as e}from"node:module";const t={crypto:`Use the Web Crypto API (globalThis.crypto) instead.`,buffer:`Use Uint8Array or ArrayBuffer instead.`,fs:`File system access is not available in the Tailor Platform runtime.`,"fs/promises":`File system access is not available in the Tailor Platform runtime.`,path:`Use URL or URLPattern for path manipulation.`,http:`Use the Fetch API (globalThis.fetch) for HTTP requests instead.`,https:`Use the Fetch API (globalThis.fetch) for HTTPS requests instead.`,url:`Use the URL and URLSearchParams Web APIs instead.`,util:`Use Web Standard APIs instead.`,stream:`Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.`,"stream/web":`Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.`,events:`Use EventTarget instead.`,zlib:`Use CompressionStream and DecompressionStream Web APIs instead.`,querystring:`Use URLSearchParams instead.`,string_decoder:`Use TextDecoder instead.`},n={process:"Use `defineConfig({ env })` and the `env` argument passed into the body function instead.",Buffer:`Use Uint8Array or ArrayBuffer instead.`,global:`Use globalThis instead.`,__dirname:`File system paths are not available in the Tailor Platform runtime.`,__filename:`File system paths are not available in the Tailor Platform runtime.`,require:"Use a static `import` instead.",module:`CommonJS module semantics are not available in the Tailor Platform runtime.`,exports:`CommonJS module semantics are not available in the Tailor Platform runtime.`,setImmediate:`Use setTimeout instead.`,clearImmediate:`Use clearTimeout instead.`};function describeUnavailable(e){return`"${e}" is not available in the Tailor Platform runtime.`}function withSuggestion(e,t){let n=describeUnavailable(e);return t?`${n} ${t}`:n}function isNodeBuiltinImport(t){return e(t)}function getNodeBuiltinMessage(e){let n=e.startsWith(`node:`)?e.slice(5):e;return withSuggestion(e,t[n])}function getForbiddenGlobalMessage(e){return withSuggestion(e,Object.hasOwn(n,e)?n[e]:void 0)}export{getNodeBuiltinMessage as n,isNodeBuiltinImport as r,getForbiddenGlobalMessage as t};
2
+ //# sourceMappingURL=node-builtins-DYfhPBnz.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"node-builtins-DYfhPBnz.mjs","names":[],"sources":["../../shared/src/node-builtins.ts"],"sourcesContent":["import { isBuiltin } from \"node:module\";\n\n/**\n * Node-only ambient globals that the Tailor Platform runtime never defines.\n * The SDK derives the same set from the `globals` package at runtime and pins\n * it to this list in its tests, so the lint plugin can ship the names without\n * depending on `globals`.\n */\nexport const NODE_ONLY_GLOBAL_NAMES: readonly string[] = [\n \"__dirname\",\n \"__filename\",\n \"Buffer\",\n \"clearImmediate\",\n \"exports\",\n \"global\",\n \"module\",\n \"process\",\n \"require\",\n \"setImmediate\",\n];\n\nconst SUGGESTIONS: Record<string, string> = {\n crypto: \"Use the Web Crypto API (globalThis.crypto) instead.\",\n buffer: \"Use Uint8Array or ArrayBuffer instead.\",\n fs: \"File system access is not available in the Tailor Platform runtime.\",\n \"fs/promises\": \"File system access is not available in the Tailor Platform runtime.\",\n path: \"Use URL or URLPattern for path manipulation.\",\n http: \"Use the Fetch API (globalThis.fetch) for HTTP requests instead.\",\n https: \"Use the Fetch API (globalThis.fetch) for HTTPS requests instead.\",\n url: \"Use the URL and URLSearchParams Web APIs instead.\",\n util: \"Use Web Standard APIs instead.\",\n stream: \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n \"stream/web\": \"Use Web Streams API (ReadableStream, WritableStream, TransformStream) instead.\",\n events: \"Use EventTarget instead.\",\n zlib: \"Use CompressionStream and DecompressionStream Web APIs instead.\",\n querystring: \"Use URLSearchParams instead.\",\n string_decoder: \"Use TextDecoder instead.\",\n};\n\n// Friendly suggestions for the most common members of NODE_ONLY_GLOBAL_NAMES.\n// A name without an entry here still gets flagged, just with the generic\n// message below instead of a targeted one.\nconst GLOBAL_SUGGESTIONS: Record<string, string> = {\n process:\n \"Use `defineConfig({ env })` and the `env` argument passed into the body function instead.\",\n Buffer: \"Use Uint8Array or ArrayBuffer instead.\",\n global: \"Use globalThis instead.\",\n __dirname: \"File system paths are not available in the Tailor Platform runtime.\",\n __filename: \"File system paths are not available in the Tailor Platform runtime.\",\n require: \"Use a static `import` instead.\",\n module: \"CommonJS module semantics are not available in the Tailor Platform runtime.\",\n exports: \"CommonJS module semantics are not available in the Tailor Platform runtime.\",\n setImmediate: \"Use setTimeout instead.\",\n clearImmediate: \"Use clearTimeout instead.\",\n};\n\nexport function describeUnavailable(name: string): string {\n return `\"${name}\" is not available in the Tailor Platform runtime.`;\n}\n\nfunction withSuggestion(name: string, suggestion: string | undefined): string {\n const base = describeUnavailable(name);\n return suggestion ? `${base} ${suggestion}` : base;\n}\n\nexport function isNodeBuiltinImport(specifier: string): boolean {\n return isBuiltin(specifier);\n}\n\nexport function getNodeBuiltinMessage(specifier: string): string {\n const bare = specifier.startsWith(\"node:\") ? specifier.slice(5) : specifier;\n return withSuggestion(specifier, SUGGESTIONS[bare]);\n}\n\nexport function getForbiddenGlobalMessage(name: string): string {\n return withSuggestion(\n name,\n Object.hasOwn(GLOBAL_SUGGESTIONS, name) ? GLOBAL_SUGGESTIONS[name] : undefined,\n );\n}\n"],"mappings":"wCAqBA,MAAM,EAAsC,CAC1C,OAAQ,sDACR,OAAQ,yCACR,GAAI,sEACJ,cAAe,sEACf,KAAM,+CACN,KAAM,kEACN,MAAO,mEACP,IAAK,oDACL,KAAM,iCACN,OAAQ,iFACR,aAAc,iFACd,OAAQ,2BACR,KAAM,kEACN,YAAa,+BACb,eAAgB,0BAClB,EAKM,EAA6C,CACjD,QACE,4FACF,OAAQ,yCACR,OAAQ,0BACR,UAAW,sEACX,WAAY,sEACZ,QAAS,iCACT,OAAQ,8EACR,QAAS,8EACT,aAAc,0BACd,eAAgB,2BAClB,EAEA,SAAgB,oBAAoB,EAAsB,CACxD,MAAO,IAAI,EAAK,mDAClB,CAEA,SAAS,eAAe,EAAc,EAAwC,CAC5E,IAAM,EAAO,oBAAoB,CAAI,EACrC,OAAO,EAAa,GAAG,EAAK,GAAG,IAAe,CAChD,CAEA,SAAgB,oBAAoB,EAA4B,CAC9D,OAAO,EAAU,CAAS,CAC5B,CAEA,SAAgB,sBAAsB,EAA2B,CAC/D,IAAM,EAAO,EAAU,WAAW,OAAO,EAAI,EAAU,MAAM,CAAC,EAAI,EAClE,OAAO,eAAe,EAAW,EAAY,EAAK,CACpD,CAEA,SAAgB,0BAA0B,EAAsB,CAC9D,OAAO,eACL,EACA,OAAO,OAAO,EAAoB,CAAI,EAAI,EAAmB,GAAQ,IAAA,EACvE,CACF"}
@@ -1 +1 @@
1
- import{n as e,t}from"../../../seed-CCc9Xk66.mjs";export{t as SeedGeneratorID,e as seedPlugin};
1
+ import{n as e,t}from"../../../seed-C3P_T_Eh.mjs";export{t as SeedGeneratorID,e as seedPlugin};
@@ -14,5 +14,22 @@ export interface SeedNamespaceConfig {
14
14
  selfRefTypes: string[];
15
15
  /** Field names a seed row must supply per table, enforced with `--upsert`. */
16
16
  requiredFields: Record<string, string[]>;
17
+ /** Field names the platform assigns rather than the seed row, per table. */
18
+ omitFields?: Record<string, string[]>;
19
+ /**
20
+ * Self-referencing field names per table (a subset of the table's own
21
+ * fields, e.g. `parentId`). Lets the seed script order same-table inserts
22
+ * so a row is never inserted before the row it points to.
23
+ */
24
+ selfRefFields?: Record<string, string[]>;
25
+ /**
26
+ * The field each self-referencing field is keyed to, per table (e.g.
27
+ * `{ Category: { parentCode: "code" } }`). A self-reference does not
28
+ * always target the row's `id` — `toward.key` (or a `keyOnly` relation's
29
+ * `foreignKeyField`) can point at another unique field — so the seed
30
+ * script needs this to resolve parent/child edges by the right value
31
+ * instead of assuming `id`.
32
+ */
33
+ selfRefKeys?: Record<string, Record<string, string>>;
17
34
  }
18
35
  //#endregion
@@ -12,4 +12,17 @@ import { TailorAnyDBType } from "../configure/services/tailordb/types.mjs";
12
12
  * @returns The generated TailorDB table
13
13
  */
14
14
  export declare function getGeneratedTable(configPath: string, pluginId: string, sourceTable: TailorAnyDBType | null, kind: string): Promise<TailorAnyDBType>;
15
+ /**
16
+ * Get a table with the fields its attached plugins add to it, as `tailor generate` sees it.
17
+ * The plugins attached with `.plugin()` run in order, each seeing the fields the ones before
18
+ * it added, and the result is cached per config path and table.
19
+ * The table exported from the source file is not changed; the returned table is a new object.
20
+ * Returns the source table itself when no plugin is attached to it, or when the config is
21
+ * not available (e.g. in a bundled executor on the platform server).
22
+ * @template T - The source table's own type, which the returned table keeps
23
+ * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)
24
+ * @param sourceTable - The TailorDB table as exported from its source file
25
+ * @returns The table with every plugin-added field
26
+ */
27
+ export declare function getExtendedTable<T extends TailorAnyDBType>(configPath: string, sourceTable: T): Promise<T>;
15
28
  //#endregion
@@ -1,4 +1,4 @@
1
1
  import { PluginConfigRegistry } from "./types.mjs";
2
2
  import { PluginDBSchema, PluginExecutorFactory, PluginFunctionArgs, PluginRecord, PluginRecordCreatedArgs, PluginRecordDeletedArgs, PluginRecordUpdatedArgs, withPluginContext } from "./with-context.mjs";
3
- import { getGeneratedTable } from "./get-generated-table.mjs";
4
- export { type PluginConfigRegistry, type PluginDBSchema, type PluginExecutorFactory, type PluginFunctionArgs, type PluginRecord, type PluginRecordCreatedArgs, type PluginRecordDeletedArgs, type PluginRecordUpdatedArgs, getGeneratedTable, withPluginContext };
3
+ import { getExtendedTable, getGeneratedTable } from "./get-generated-table.mjs";
4
+ export { type PluginConfigRegistry, type PluginDBSchema, type PluginExecutorFactory, type PluginFunctionArgs, type PluginRecord, type PluginRecordCreatedArgs, type PluginRecordDeletedArgs, type PluginRecordUpdatedArgs, getExtendedTable, getGeneratedTable, withPluginContext };
@@ -1,2 +1,2 @@
1
- import*as e from"pathe";import*as t from"node:fs";import{pathToFileURL as n}from"node:url";function withPluginContext(e){return e}const r=new Map;function isPlugin(e){return typeof e==`object`&&!!e&&typeof e.id==`string`&&typeof e.description==`string`}async function loadAndCacheConfig(i){let a=e.resolve(i),o=r.get(a);if(o)return o;if(!t.existsSync(a))return null;let s=await import(n(a).href);if(!s?.default)throw Error(`Invalid config module at "${a}": default export not found`);let c=s.default,l=e.dirname(a),u=new Map;for(let e of Object.values(s))if(Array.isArray(e))for(let t of e)isPlugin(t)&&u.set(t.id,{plugin:t,pluginConfig:t.pluginConfig});let d={config:c,plugins:u,configDir:l};return r.set(a,d),d}async function resolveNamespaceForTable(r,i,a){if(!r.db)throw Error(`No db configuration found in config`);for(let[o,s]of Object.entries(r.db)){let r=s;if(!r.external&&r.files)for(let s of r.files){let r=e.resolve(i,s),c;try{c=t.globSync(r)}catch{continue}for(let e of c){let t=await import(n(e).href);for(let e of Object.values(t))if(e===a)return o}}}throw Error(`Could not resolve namespace for table "${a.name}". Ensure the table file is included in a db namespace's files pattern.`)}async function resolveNamespaceForNamespacePlugin(e,t,n,r){if(!e.db)throw Error(`No db configuration found in config`);if(!t.onNamespaceLoaded)throw Error(`Plugin "${t.id}" does not have a onNamespaceLoaded() method`);for(let i of Object.keys(e.db)){if(e.db[i].external)continue;let a=await t.onNamespaceLoaded({pluginConfig:r,namespace:i});if(a.tables?.[n])return{namespace:i,output:a}}throw Error(`Could not resolve namespace for plugin "${t.id}" with kind "${n}". No namespace produced a table with that kind.`)}const i=new WeakMap,a=new WeakMap;function getCacheKey(e,t){if(t===void 0)return e;try{return`${e}:${JSON.stringify(t)}`}catch{throw Error(`pluginConfig must be JSON-serializable for caching. Received non-serializable value.`)}}async function getGeneratedTable(e,t,n,r){let i=await loadAndCacheConfig(e);if(!i)return{name:`__placeholder_${r}__`,fields:{}};let{config:a,configDir:o,plugins:s}=i,c=s.get(t);if(!c)throw Error(`Plugin "${t}" not found in config at "${e}". Ensure the plugin is registered via definePlugins().`);let{plugin:l,pluginConfig:u}=c;return n===null?getGeneratedTableForNamespacePlugin(a,l,r,u):getGeneratedTableForTableAttachedPlugin(l,n,r,u,await resolveNamespaceForTable(a,o,n))}async function getGeneratedTableForTableAttachedPlugin(e,t,n,r,a){if(!e.onTableLoaded)throw Error(`Plugin "${e.id}" does not have an onTableLoaded() method`);let o=i.get(e);o||(o=new Map,i.set(e,o));let s=getCacheKey(`${t.name}:ns=${a}`,r),c=o.get(s);if(!c){let n=t.plugins.find(t=>t.pluginId===e.id)?.config;c=await e.onTableLoaded({table:t,tableConfig:n??{},pluginConfig:r,namespace:a}),o.set(s,c)}let l=c.tables?.[n];if(!l)throw Error(`Generated table not found: plugin=${e.id}, sourceTable=${t.name}, kind=${n}`);return l}async function getGeneratedTableForNamespacePlugin(e,t,n,r){if(!t.onNamespaceLoaded)throw Error(`Plugin "${t.id}" does not have a onNamespaceLoaded() method`);let i=a.get(t);if(i||(i=new Map,a.set(t,i)),e.db)for(let t of Object.keys(e.db)){if(e.db[t].external)continue;let a=getCacheKey(`namespace:ns=${t}`,r),o=i.get(a);if(o?.tables?.[n])return o.tables[n]}let{namespace:o,output:s}=await resolveNamespaceForNamespacePlugin(e,t,n,r),c=getCacheKey(`namespace:ns=${o}`,r);i.set(c,s);let l=s.tables?.[n];if(!l)throw Error(`Generated table not found: plugin=${t.id}, kind=${n}`);return l}export{getGeneratedTable,withPluginContext};
1
+ import{a as e}from"../guards-ForsrxnH.mjs";import{t}from"../manager-E3ffRcCt.mjs";import*as n from"pathe";import*as r from"node:fs";import{pathToFileURL as i}from"node:url";function withPluginContext(e){return e}const a=new Map;async function loadAndCacheConfig(t){let o=n.resolve(t),s=a.get(o);if(s)return s;if(!r.existsSync(o))return null;let c=await import(i(o).href);if(!c?.default)throw Error(`Invalid config module at "${o}": default export not found`);let l=c.default,u=n.dirname(o),d=new Map;for(let t of e(c))for(let e of t){let t=e;d.set(t.id,{plugin:t,pluginConfig:t.pluginConfig})}let f={config:l,plugins:d,configDir:u};return a.set(o,f),f}async function resolveNamespaceForTable(e,t,a){if(!e.db)throw Error(`No db configuration found in config`);for(let[o,s]of Object.entries(e.db)){let e=s;if(!e.external&&e.files)for(let s of e.files){let e=n.resolve(t,s),c;try{c=r.globSync(e)}catch{continue}for(let e of c){let t=await import(i(e).href);for(let e of Object.values(t))if(e===a)return o}}}throw Error(`Could not resolve namespace for table "${a.name}". Ensure the table file is included in a db namespace's files pattern.`)}async function resolveNamespaceForNamespacePlugin(e,t,n,r){if(!e.db)throw Error(`No db configuration found in config`);if(!t.onNamespaceLoaded)throw Error(`Plugin "${t.id}" does not have a onNamespaceLoaded() method`);for(let i of Object.keys(e.db)){if(e.db[i].external)continue;let a=await t.onNamespaceLoaded({pluginConfig:r,namespace:i});if(a.tables?.[n])return{namespace:i,output:a}}throw Error(`Could not resolve namespace for plugin "${t.id}" with kind "${n}". No namespace produced a table with that kind.`)}const o=new WeakMap,s=new WeakMap;function getCacheKey(e,t){if(t===void 0)return e;try{return`${e}:${JSON.stringify(t)}`}catch{throw Error(`pluginConfig must be JSON-serializable for caching. Received non-serializable value.`)}}async function getGeneratedTable(e,t,n,r){let i=await loadAndCacheConfig(e);if(!i)return{name:`__placeholder_${r}__`,fields:{}};let{config:a,configDir:o,plugins:s}=i,c=s.get(t);if(!c)throw Error(`Plugin "${t}" not found in config at "${e}". Ensure the plugin is registered via definePlugins().`);let{plugin:l,pluginConfig:u}=c;return n===null?getGeneratedTableForNamespacePlugin(a,l,r,u):getGeneratedTableForTableAttachedPlugin(l,n,r,u,await resolveNamespaceForTable(a,o,n))}async function getGeneratedTableForTableAttachedPlugin(e,t,n,r,i){if(!e.onTableLoaded)throw Error(`Plugin "${e.id}" does not have an onTableLoaded() method`);let a=o.get(e);a||(a=new Map,o.set(e,a));let s=getCacheKey(`${t.name}:ns=${i}`,r),c=a.get(s);if(!c){let n=t.plugins.find(t=>t.pluginId===e.id)?.config;c=await e.onTableLoaded({table:t,tableConfig:n??{},pluginConfig:r,namespace:i}),a.set(s,c)}let l=c.tables?.[n];if(!l)throw Error(`Generated table not found: plugin=${e.id}, sourceTable=${t.name}, kind=${n}`);return l}async function getGeneratedTableForNamespacePlugin(e,t,n,r){if(!t.onNamespaceLoaded)throw Error(`Plugin "${t.id}" does not have a onNamespaceLoaded() method`);let i=s.get(t);if(i||(i=new Map,s.set(t,i)),e.db)for(let t of Object.keys(e.db)){if(e.db[t].external)continue;let a=getCacheKey(`namespace:ns=${t}`,r),o=i.get(a);if(o?.tables?.[n])return o.tables[n]}let{namespace:a,output:o}=await resolveNamespaceForNamespacePlugin(e,t,n,r),c=getCacheKey(`namespace:ns=${a}`,r);i.set(c,o);let l=o.tables?.[n];if(!l)throw Error(`Generated table not found: plugin=${t.id}, kind=${n}`);return l}const c=new Map;async function getExtendedTable(e,t){if(t.plugins.length===0)return t;let r=n.resolve(e),i=c.get(r);i||(i=new WeakMap,c.set(r,i));let a=i.get(t);if(a)return a;let o=applyPluginExtensions(r,t);return i.set(t,o),o.catch(()=>i.delete(t)),o}async function applyPluginExtensions(e,n){let r=await loadAndCacheConfig(e);if(!r)return n;let{config:i,configDir:a,plugins:o}=r,s=await resolveNamespaceForTable(i,a,n),{extendedTable:c}=await new t([...o.values()].map(e=>e.plugin)).processAttachmentsForTable({rawTable:n,attachments:[...n.plugins],namespace:s});return c??n}export{getExtendedTable,getGeneratedTable,withPluginContext};
2
2
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/with-context.ts","../../src/plugin/get-generated-table.ts"],"sourcesContent":["/**\n * Plugin executor context support for defining plugin executors in separate files.\n * This module provides utilities for creating type-safe plugin executors that receive\n * context (like table references and namespace) at runtime.\n */\n\nimport type { TailorEnv, TailorPrincipal } from \"#/runtime/types\";\n\n/**\n * Plugin executor factory function type.\n * Takes context and returns an executor configuration.\n * Returns unknown since the exact return type depends on createExecutor's generic params.\n */\nexport type PluginExecutorFactory<Ctx> = (ctx: Ctx) => unknown;\n\n// ============================================================================\n// Plugin Executor Args Types\n// ============================================================================\n\n/**\n * Base args for plugin executor function operations.\n * Provides typed access to runtime context without requiring specific record types.\n */\nexport interface PluginFunctionArgs {\n /** Workspace ID where the executor runs */\n workspaceId: string;\n /** Application namespace */\n appNamespace: string;\n /** Environment variables */\n env: TailorEnv;\n /** Principal that triggered the event, null for system events */\n actor: TailorPrincipal | null;\n /** Name of the TailorDB table */\n typeName: string;\n /** TailorDB connections by namespace */\n tailordb: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record creation.\n */\nexport interface PluginRecordCreatedArgs extends PluginFunctionArgs {\n /** The newly created record */\n newRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record update.\n */\nexport interface PluginRecordUpdatedArgs extends PluginFunctionArgs {\n /** The record after update */\n newRecord: Record<string, unknown>;\n /** The record before update */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record deletion.\n */\nexport interface PluginRecordDeletedArgs extends PluginFunctionArgs {\n /** The deleted record */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Database schema type for plugins.\n * Since plugins work with dynamic types, the schema uses Record types.\n */\nexport type PluginDBSchema = Record<string, Record<string, unknown>>;\n\n/**\n * Base record type for TailorDB records.\n * All records have an id field.\n */\nexport type PluginRecord = { id: string } & Record<string, unknown>;\n\n/**\n * Define a plugin executor that receives context at runtime.\n * This allows executor definitions to be in separate files while\n * still receiving dynamic values like typeName, generated types, and namespace.\n * @param factory - Function that takes context and returns executor configuration\n * @returns The same factory function (for type inference)\n * @example\n * ```typescript\n * // executors/on-create.ts\n * import { withPluginContext } from \"@tailor-platform/sdk/plugin\";\n * import { createExecutor, recordCreatedTrigger } from \"@tailor-platform/sdk\";\n * import { getDB } from \"@tailor-platform/function-kysely-tailordb\";\n *\n * interface MyContext {\n * sourceTable: TailorAnyDBType;\n * historyType: TailorAnyDBType;\n * namespace: string;\n * }\n *\n * export default withPluginContext<MyContext>((ctx) =>\n * createExecutor({\n * name: `${ctx.sourceTable.name.toLowerCase()}-on-create`,\n * trigger: recordCreatedTrigger({ type: ctx.sourceTable }),\n * operation: {\n * kind: \"function\",\n * body: async (args) => {\n * const db = getDB(ctx.namespace);\n * await db.insertInto(ctx.historyType.name).values({\n * recordId: args.newRecord.id,\n * // ...\n * }).execute();\n * },\n * },\n * })\n * );\n * ```\n */\nexport function withPluginContext<Ctx>(\n factory: PluginExecutorFactory<Ctx>,\n): PluginExecutorFactory<Ctx> {\n return factory;\n}\n","import * as fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport type { TailorAnyDBType } from \"#/configure/services/tailordb/types\";\nimport type { Plugin, PluginOutput, TablePluginOutput } from \"#/plugin/types\";\n\n// ========================================\n// Config loading and caching\n// ========================================\n\ninterface PluginEntry {\n plugin: Plugin;\n pluginConfig: unknown;\n}\n\ninterface ConfigCache {\n config: { db?: Record<string, unknown> };\n plugins: Map<string, PluginEntry>;\n configDir: string;\n}\n\n/** Cache: resolved config path -> loaded config data */\nconst configCacheMap = new Map<string, ConfigCache>();\n\n/**\n * Check if a value is a Plugin instance.\n * @param value - Value to check\n * @returns True if value has the shape of Plugin\n */\nfunction isPlugin(value: unknown): value is Plugin {\n return (\n typeof value === \"object\" &&\n value !== null &&\n typeof (value as Record<string, unknown>).id === \"string\" &&\n typeof (value as Record<string, unknown>).description === \"string\"\n );\n}\n\n/**\n * Load and cache config module from the given path.\n * Extracts plugins from all array exports using definePlugins() format.\n * Returns null if the config file does not exist (e.g., in bundled executor on platform server).\n * @param configPath - Absolute or relative path to tailor.config.ts\n * @returns Cached config data with plugins map, or null if config file is not available\n */\nasync function loadAndCacheConfig(configPath: string): Promise<ConfigCache | null> {\n const resolvedPath = path.resolve(configPath);\n\n const cached = configCacheMap.get(resolvedPath);\n if (cached) return cached;\n\n // Config file may not exist in bundled environments (e.g., platform server)\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n\n const configModule = await import(pathToFileURL(resolvedPath).href);\n if (!configModule?.default) {\n throw new Error(`Invalid config module at \"${resolvedPath}\": default export not found`);\n }\n\n const config = configModule.default as { db?: Record<string, unknown> };\n const configDir = path.dirname(resolvedPath);\n const plugins = new Map<string, PluginEntry>();\n\n // Find plugin arrays from exports (definePlugins returns PluginConfig[])\n for (const value of Object.values(configModule)) {\n if (!Array.isArray(value)) continue;\n\n for (const item of value) {\n if (isPlugin(item)) {\n plugins.set(item.id, { plugin: item, pluginConfig: item.pluginConfig });\n }\n }\n }\n\n const result: ConfigCache = { config, plugins, configDir };\n configCacheMap.set(resolvedPath, result);\n return result;\n}\n\n// ========================================\n// Namespace resolution\n// ========================================\n\ninterface DbNamespaceConfig {\n files?: string[];\n external?: boolean;\n}\n\n/**\n * Resolve the namespace for a table-attached source table by checking config.db file patterns.\n * Uses ESM module cache identity: same file path yields same object references.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param configDir - Directory containing the config file\n * @param sourceTable - The TailorDB table to look up\n * @returns The namespace name\n */\nasync function resolveNamespaceForTable(\n config: { db?: Record<string, unknown> },\n configDir: string,\n sourceTable: TailorAnyDBType,\n): Promise<string> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n for (const [namespace, nsConfig] of Object.entries(config.db)) {\n const dbConfig = nsConfig as DbNamespaceConfig;\n // Skip external namespaces (no files to resolve)\n if (dbConfig.external || !dbConfig.files) continue;\n\n for (const pattern of dbConfig.files) {\n const absolutePattern = path.resolve(configDir, pattern);\n let matchedFiles: string[];\n try {\n matchedFiles = fs.globSync(absolutePattern);\n } catch {\n continue;\n }\n\n for (const file of matchedFiles) {\n const mod = await import(pathToFileURL(file).href);\n for (const exported of Object.values(mod)) {\n if (exported === sourceTable) {\n return namespace;\n }\n }\n }\n }\n }\n\n throw new Error(\n `Could not resolve namespace for table \"${sourceTable.name}\". ` +\n `Ensure the table file is included in a db namespace's files pattern.`,\n );\n}\n\n/**\n * Resolve the namespace for a namespace plugin by trying each namespace.\n * Calls onNamespaceLoaded() for each and returns the first whose output contains the requested kind.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - Plugin instance\n * @param kind - The generated table kind to look for\n * @param pluginConfig - Plugin-level configuration\n * @returns The namespace name\n */\nasync function resolveNamespaceForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<{ namespace: string; output: PluginOutput }> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const output = await plugin.onNamespaceLoaded({\n pluginConfig,\n namespace,\n });\n\n if (output.tables?.[kind]) {\n return { namespace, output };\n }\n }\n\n throw new Error(\n `Could not resolve namespace for plugin \"${plugin.id}\" with kind \"${kind}\". ` +\n `No namespace produced a table with that kind.`,\n );\n}\n\n// ========================================\n// Process caching\n// ========================================\n\n// Cache: plugin -> cacheKey -> TablePluginOutput\nconst processCache = new WeakMap<Plugin, Map<string, TablePluginOutput>>();\n\n// Cache for namespace plugins: plugin -> cacheKey -> PluginOutput\nconst namespaceProcessCache = new WeakMap<Plugin, Map<string, PluginOutput>>();\n\n/**\n * Generate a cache key that includes pluginConfig.\n * @param baseKey - Base key for the cache\n * @param pluginConfig - Plugin configuration to include in the key\n * @returns Cache key string\n */\nfunction getCacheKey(baseKey: string, pluginConfig: unknown): string {\n if (pluginConfig === undefined) {\n return baseKey;\n }\n try {\n return `${baseKey}:${JSON.stringify(pluginConfig)}`;\n } catch {\n throw new Error(\n `pluginConfig must be JSON-serializable for caching. Received non-serializable value.`,\n );\n }\n}\n\n// ========================================\n// Main API\n// ========================================\n\n/**\n * Get a generated table from a plugin by loading the config and resolving everything automatically.\n * For table-attached plugins, calls onTableLoaded() with the source table.\n * For namespace plugins, calls onNamespaceLoaded() with auto-resolved namespace.\n * Results are cached per config path, plugin, namespace, and pluginConfig to avoid redundant processing.\n * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)\n * @param pluginId - The plugin's unique identifier\n * @param sourceTable - The source TailorDB table (null for namespace plugins)\n * @param kind - The generated table kind (e.g., \"request\", \"step\")\n * @returns The generated TailorDB table\n */\nexport async function getGeneratedTable(\n configPath: string,\n pluginId: string,\n sourceTable: TailorAnyDBType | null,\n kind: string,\n): Promise<TailorAnyDBType> {\n const cache = await loadAndCacheConfig(configPath);\n\n if (!cache) {\n // Config not available (e.g., running in bundled executor on platform server).\n // Return a placeholder. The actual table is resolved at generate/apply time.\n return { name: `__placeholder_${kind}__`, fields: {} } as TailorAnyDBType;\n }\n\n const { config, configDir, plugins } = cache;\n\n const pluginEntry = plugins.get(pluginId);\n if (!pluginEntry) {\n throw new Error(\n `Plugin \"${pluginId}\" not found in config at \"${configPath}\". ` +\n `Ensure the plugin is registered via definePlugins().`,\n );\n }\n\n const { plugin, pluginConfig } = pluginEntry;\n\n if (sourceTable === null) {\n return getGeneratedTableForNamespacePlugin(config, plugin, kind, pluginConfig);\n }\n\n const namespace = await resolveNamespaceForTable(config, configDir, sourceTable);\n return getGeneratedTableForTableAttachedPlugin(\n plugin,\n sourceTable,\n kind,\n pluginConfig,\n namespace,\n );\n}\n\n/**\n * Get a generated table from a table-attached plugin.\n * @param plugin - The plugin instance (must have onTableLoaded() method)\n * @param sourceTable - The source TailorDB table\n * @param kind - The generated table kind\n * @param pluginConfig - Plugin-level configuration\n * @param namespace - Resolved namespace\n * @returns The generated TailorDB table\n */\nasync function getGeneratedTableForTableAttachedPlugin(\n plugin: Plugin,\n sourceTable: TailorAnyDBType,\n kind: string,\n pluginConfig: unknown,\n namespace: string,\n): Promise<TailorAnyDBType> {\n if (!plugin.onTableLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have an onTableLoaded() method`);\n }\n\n // Check cache first\n let pluginCache = processCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n processCache.set(plugin, pluginCache);\n }\n\n const cacheKey = getCacheKey(`${sourceTable.name}:ns=${namespace}`, pluginConfig);\n let output = pluginCache.get(cacheKey);\n\n if (!output) {\n const tableConfig = sourceTable.plugins.find((p) => p.pluginId === plugin.id)?.config;\n output = await plugin.onTableLoaded({\n table: sourceTable,\n tableConfig: tableConfig ?? {},\n pluginConfig,\n namespace,\n });\n pluginCache.set(cacheKey, output);\n }\n\n const generatedTable = output.tables?.[kind];\n if (!generatedTable) {\n throw new Error(\n `Generated table not found: plugin=${plugin.id}, sourceTable=${sourceTable.name}, kind=${kind}`,\n );\n }\n\n return generatedTable as TailorAnyDBType;\n}\n\n/**\n * Get a generated table from a namespace plugin.\n * Auto-resolves the namespace by trying each one.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - The plugin instance (must have onNamespaceLoaded() method)\n * @param kind - The generated table kind\n * @param pluginConfig - Plugin-level configuration\n * @returns The generated TailorDB table\n */\nasync function getGeneratedTableForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<TailorAnyDBType> {\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n // Check cache first - try all namespaces\n let pluginCache = namespaceProcessCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n namespaceProcessCache.set(plugin, pluginCache);\n }\n\n // Try cached results first\n if (config.db) {\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n const cached = pluginCache.get(cacheKey);\n if (cached?.tables?.[kind]) {\n return cached.tables[kind] as TailorAnyDBType;\n }\n }\n }\n\n // Not in cache - resolve namespace and process\n const { namespace, output } = await resolveNamespaceForNamespacePlugin(\n config,\n plugin,\n kind,\n pluginConfig,\n );\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n pluginCache.set(cacheKey, output);\n\n const generatedTable = output.tables?.[kind];\n if (!generatedTable) {\n throw new Error(`Generated table not found: plugin=${plugin.id}, kind=${kind}`);\n }\n\n return generatedTable as TailorAnyDBType;\n}\n\n/**\n * Clear all internal caches. For testing only.\n */\nexport function _clearCacheForTesting(): void {\n configCacheMap.clear();\n}\n"],"mappings":"2FAiHA,SAAgB,kBACd,EAC4B,CAC5B,OAAO,CACT,CC/FA,MAAM,EAAiB,IAAI,IAO3B,SAAS,SAAS,EAAiC,CACjD,OACE,OAAO,GAAU,YACjB,GACA,OAAQ,EAAkC,IAAO,UACjD,OAAQ,EAAkC,aAA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G,SAAS,GAAM,EAGhF,OAAO,CACT"}
1
+ {"version":3,"file":"index.mjs","names":[],"sources":["../../src/plugin/with-context.ts","../../src/plugin/get-generated-table.ts"],"sourcesContent":["/**\n * Plugin executor context support for defining plugin executors in separate files.\n * This module provides utilities for creating type-safe plugin executors that receive\n * context (like table references and namespace) at runtime.\n */\n\nimport type { TailorEnv, TailorPrincipal } from \"#/runtime/types\";\n\n/**\n * Plugin executor factory function type.\n * Takes context and returns an executor configuration.\n * Returns unknown since the exact return type depends on createExecutor's generic params.\n */\nexport type PluginExecutorFactory<Ctx> = (ctx: Ctx) => unknown;\n\n// ============================================================================\n// Plugin Executor Args Types\n// ============================================================================\n\n/**\n * Base args for plugin executor function operations.\n * Provides typed access to runtime context without requiring specific record types.\n */\nexport interface PluginFunctionArgs {\n /** Workspace ID where the executor runs */\n workspaceId: string;\n /** Application namespace */\n appNamespace: string;\n /** Environment variables */\n env: TailorEnv;\n /** Principal that triggered the event, null for system events */\n actor: TailorPrincipal | null;\n /** Name of the TailorDB table */\n typeName: string;\n /** TailorDB connections by namespace */\n tailordb: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record creation.\n */\nexport interface PluginRecordCreatedArgs extends PluginFunctionArgs {\n /** The newly created record */\n newRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record update.\n */\nexport interface PluginRecordUpdatedArgs extends PluginFunctionArgs {\n /** The record after update */\n newRecord: Record<string, unknown>;\n /** The record before update */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Args for plugin executors triggered on record deletion.\n */\nexport interface PluginRecordDeletedArgs extends PluginFunctionArgs {\n /** The deleted record */\n oldRecord: Record<string, unknown>;\n}\n\n/**\n * Database schema type for plugins.\n * Since plugins work with dynamic types, the schema uses Record types.\n */\nexport type PluginDBSchema = Record<string, Record<string, unknown>>;\n\n/**\n * Base record type for TailorDB records.\n * All records have an id field.\n */\nexport type PluginRecord = { id: string } & Record<string, unknown>;\n\n/**\n * Define a plugin executor that receives context at runtime.\n * This allows executor definitions to be in separate files while\n * still receiving dynamic values like typeName, generated types, and namespace.\n * @param factory - Function that takes context and returns executor configuration\n * @returns The same factory function (for type inference)\n * @example\n * ```typescript\n * // executors/on-create.ts\n * import { withPluginContext } from \"@tailor-platform/sdk/plugin\";\n * import { createExecutor, recordCreatedTrigger } from \"@tailor-platform/sdk\";\n * import { getDB } from \"@tailor-platform/function-kysely-tailordb\";\n *\n * interface MyContext {\n * sourceTable: TailorAnyDBType;\n * historyType: TailorAnyDBType;\n * namespace: string;\n * }\n *\n * export default withPluginContext<MyContext>((ctx) =>\n * createExecutor({\n * name: `${ctx.sourceTable.name.toLowerCase()}-on-create`,\n * trigger: recordCreatedTrigger({ type: ctx.sourceTable }),\n * operation: {\n * kind: \"function\",\n * body: async (args) => {\n * const db = getDB(ctx.namespace);\n * await db.insertInto(ctx.historyType.name).values({\n * recordId: args.newRecord.id,\n * // ...\n * }).execute();\n * },\n * },\n * })\n * );\n * ```\n */\nexport function withPluginContext<Ctx>(\n factory: PluginExecutorFactory<Ctx>,\n): PluginExecutorFactory<Ctx> {\n return factory;\n}\n","import * as fs from \"node:fs\";\nimport { pathToFileURL } from \"node:url\";\nimport * as path from \"pathe\";\nimport { pickPluginArrays } from \"./guards\";\nimport { PluginManager } from \"./manager\";\nimport type { TailorAnyDBType } from \"#/configure/services/tailordb/types\";\nimport type { Plugin, PluginOutput, TablePluginOutput } from \"#/plugin/types\";\nimport type { TailorDBTypeRaw } from \"#/types/tailordb.generated\";\n\n// ========================================\n// Config loading and caching\n// ========================================\n\ninterface PluginEntry {\n plugin: Plugin;\n pluginConfig: unknown;\n}\n\ninterface ConfigCache {\n config: { db?: Record<string, unknown> };\n plugins: Map<string, PluginEntry>;\n configDir: string;\n}\n\n/** Cache: resolved config path -> loaded config data */\nconst configCacheMap = new Map<string, ConfigCache>();\n\n/**\n * Load and cache config module from the given path.\n * Extracts plugins from all array exports using definePlugins() format.\n * Returns null if the config file does not exist (e.g., in bundled executor on platform server).\n * @param configPath - Absolute or relative path to tailor.config.ts\n * @returns Cached config data with plugins map, or null if config file is not available\n */\nasync function loadAndCacheConfig(configPath: string): Promise<ConfigCache | null> {\n const resolvedPath = path.resolve(configPath);\n\n const cached = configCacheMap.get(resolvedPath);\n if (cached) return cached;\n\n // Config file may not exist in bundled environments (e.g., platform server)\n if (!fs.existsSync(resolvedPath)) {\n return null;\n }\n\n const configModule = await import(pathToFileURL(resolvedPath).href);\n if (!configModule?.default) {\n throw new Error(`Invalid config module at \"${resolvedPath}\": default export not found`);\n }\n\n const config = configModule.default as { db?: Record<string, unknown> };\n const configDir = path.dirname(resolvedPath);\n const plugins = new Map<string, PluginEntry>();\n\n for (const items of pickPluginArrays(configModule)) {\n for (const item of items) {\n const plugin = item as Plugin;\n plugins.set(plugin.id, { plugin, pluginConfig: plugin.pluginConfig });\n }\n }\n\n const result: ConfigCache = { config, plugins, configDir };\n configCacheMap.set(resolvedPath, result);\n return result;\n}\n\n// ========================================\n// Namespace resolution\n// ========================================\n\ninterface DbNamespaceConfig {\n files?: string[];\n external?: boolean;\n}\n\n/**\n * Resolve the namespace for a table-attached source table by checking config.db file patterns.\n * Uses ESM module cache identity: same file path yields same object references.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param configDir - Directory containing the config file\n * @param sourceTable - The TailorDB table to look up\n * @returns The namespace name\n */\nasync function resolveNamespaceForTable(\n config: { db?: Record<string, unknown> },\n configDir: string,\n sourceTable: TailorAnyDBType,\n): Promise<string> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n for (const [namespace, nsConfig] of Object.entries(config.db)) {\n const dbConfig = nsConfig as DbNamespaceConfig;\n // Skip external namespaces (no files to resolve)\n if (dbConfig.external || !dbConfig.files) continue;\n\n for (const pattern of dbConfig.files) {\n const absolutePattern = path.resolve(configDir, pattern);\n let matchedFiles: string[];\n try {\n matchedFiles = fs.globSync(absolutePattern);\n } catch {\n continue;\n }\n\n for (const file of matchedFiles) {\n const mod = await import(pathToFileURL(file).href);\n for (const exported of Object.values(mod)) {\n if (exported === sourceTable) {\n return namespace;\n }\n }\n }\n }\n }\n\n throw new Error(\n `Could not resolve namespace for table \"${sourceTable.name}\". ` +\n `Ensure the table file is included in a db namespace's files pattern.`,\n );\n}\n\n/**\n * Resolve the namespace for a namespace plugin by trying each namespace.\n * Calls onNamespaceLoaded() for each and returns the first whose output contains the requested kind.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - Plugin instance\n * @param kind - The generated table kind to look for\n * @param pluginConfig - Plugin-level configuration\n * @returns The namespace name\n */\nasync function resolveNamespaceForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<{ namespace: string; output: PluginOutput }> {\n if (!config.db) {\n throw new Error(`No db configuration found in config`);\n }\n\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const output = await plugin.onNamespaceLoaded({\n pluginConfig,\n namespace,\n });\n\n if (output.tables?.[kind]) {\n return { namespace, output };\n }\n }\n\n throw new Error(\n `Could not resolve namespace for plugin \"${plugin.id}\" with kind \"${kind}\". ` +\n `No namespace produced a table with that kind.`,\n );\n}\n\n// ========================================\n// Process caching\n// ========================================\n\n// Cache: plugin -> cacheKey -> TablePluginOutput\nconst processCache = new WeakMap<Plugin, Map<string, TablePluginOutput>>();\n\n// Cache for namespace plugins: plugin -> cacheKey -> PluginOutput\nconst namespaceProcessCache = new WeakMap<Plugin, Map<string, PluginOutput>>();\n\n/**\n * Generate a cache key that includes pluginConfig.\n * @param baseKey - Base key for the cache\n * @param pluginConfig - Plugin configuration to include in the key\n * @returns Cache key string\n */\nfunction getCacheKey(baseKey: string, pluginConfig: unknown): string {\n if (pluginConfig === undefined) {\n return baseKey;\n }\n try {\n return `${baseKey}:${JSON.stringify(pluginConfig)}`;\n } catch {\n throw new Error(\n `pluginConfig must be JSON-serializable for caching. Received non-serializable value.`,\n );\n }\n}\n\n// ========================================\n// Main API\n// ========================================\n\n/**\n * Get a generated table from a plugin by loading the config and resolving everything automatically.\n * For table-attached plugins, calls onTableLoaded() with the source table.\n * For namespace plugins, calls onNamespaceLoaded() with auto-resolved namespace.\n * Results are cached per config path, plugin, namespace, and pluginConfig to avoid redundant processing.\n * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)\n * @param pluginId - The plugin's unique identifier\n * @param sourceTable - The source TailorDB table (null for namespace plugins)\n * @param kind - The generated table kind (e.g., \"request\", \"step\")\n * @returns The generated TailorDB table\n */\nexport async function getGeneratedTable(\n configPath: string,\n pluginId: string,\n sourceTable: TailorAnyDBType | null,\n kind: string,\n): Promise<TailorAnyDBType> {\n const cache = await loadAndCacheConfig(configPath);\n\n if (!cache) {\n // Config not available (e.g., running in bundled executor on platform server).\n // Return a placeholder. The actual table is resolved at generate/apply time.\n return { name: `__placeholder_${kind}__`, fields: {} } as TailorAnyDBType;\n }\n\n const { config, configDir, plugins } = cache;\n\n const pluginEntry = plugins.get(pluginId);\n if (!pluginEntry) {\n throw new Error(\n `Plugin \"${pluginId}\" not found in config at \"${configPath}\". ` +\n `Ensure the plugin is registered via definePlugins().`,\n );\n }\n\n const { plugin, pluginConfig } = pluginEntry;\n\n if (sourceTable === null) {\n return getGeneratedTableForNamespacePlugin(config, plugin, kind, pluginConfig);\n }\n\n const namespace = await resolveNamespaceForTable(config, configDir, sourceTable);\n return getGeneratedTableForTableAttachedPlugin(\n plugin,\n sourceTable,\n kind,\n pluginConfig,\n namespace,\n );\n}\n\n/**\n * Get a generated table from a table-attached plugin.\n * @param plugin - The plugin instance (must have onTableLoaded() method)\n * @param sourceTable - The source TailorDB table\n * @param kind - The generated table kind\n * @param pluginConfig - Plugin-level configuration\n * @param namespace - Resolved namespace\n * @returns The generated TailorDB table\n */\nasync function getGeneratedTableForTableAttachedPlugin(\n plugin: Plugin,\n sourceTable: TailorAnyDBType,\n kind: string,\n pluginConfig: unknown,\n namespace: string,\n): Promise<TailorAnyDBType> {\n if (!plugin.onTableLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have an onTableLoaded() method`);\n }\n\n // Check cache first\n let pluginCache = processCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n processCache.set(plugin, pluginCache);\n }\n\n const cacheKey = getCacheKey(`${sourceTable.name}:ns=${namespace}`, pluginConfig);\n let output = pluginCache.get(cacheKey);\n\n if (!output) {\n const tableConfig = sourceTable.plugins.find((p) => p.pluginId === plugin.id)?.config;\n output = await plugin.onTableLoaded({\n table: sourceTable,\n tableConfig: tableConfig ?? {},\n pluginConfig,\n namespace,\n });\n pluginCache.set(cacheKey, output);\n }\n\n const generatedTable = output.tables?.[kind];\n if (!generatedTable) {\n throw new Error(\n `Generated table not found: plugin=${plugin.id}, sourceTable=${sourceTable.name}, kind=${kind}`,\n );\n }\n\n return generatedTable as TailorAnyDBType;\n}\n\n/**\n * Get a generated table from a namespace plugin.\n * Auto-resolves the namespace by trying each one.\n * @param config - App config with db namespace definitions\n * @param config.db - DB namespace definitions\n * @param plugin - The plugin instance (must have onNamespaceLoaded() method)\n * @param kind - The generated table kind\n * @param pluginConfig - Plugin-level configuration\n * @returns The generated TailorDB table\n */\nasync function getGeneratedTableForNamespacePlugin(\n config: { db?: Record<string, unknown> },\n plugin: Plugin,\n kind: string,\n pluginConfig: unknown,\n): Promise<TailorAnyDBType> {\n if (!plugin.onNamespaceLoaded) {\n throw new Error(`Plugin \"${plugin.id}\" does not have a onNamespaceLoaded() method`);\n }\n\n // Check cache first - try all namespaces\n let pluginCache = namespaceProcessCache.get(plugin);\n if (!pluginCache) {\n pluginCache = new Map();\n namespaceProcessCache.set(plugin, pluginCache);\n }\n\n // Try cached results first\n if (config.db) {\n for (const namespace of Object.keys(config.db)) {\n const dbConfig = config.db[namespace] as DbNamespaceConfig;\n if (dbConfig.external) continue;\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n const cached = pluginCache.get(cacheKey);\n if (cached?.tables?.[kind]) {\n return cached.tables[kind] as TailorAnyDBType;\n }\n }\n }\n\n // Not in cache - resolve namespace and process\n const { namespace, output } = await resolveNamespaceForNamespacePlugin(\n config,\n plugin,\n kind,\n pluginConfig,\n );\n\n const cacheKey = getCacheKey(`namespace:ns=${namespace}`, pluginConfig);\n pluginCache.set(cacheKey, output);\n\n const generatedTable = output.tables?.[kind];\n if (!generatedTable) {\n throw new Error(`Generated table not found: plugin=${plugin.id}, kind=${kind}`);\n }\n\n return generatedTable as TailorAnyDBType;\n}\n\n// Cache: resolved config path -> source table -> the table with plugin fields applied.\n// Holds the pending promise so concurrent callers share one plugin run.\nconst extendedTableCache = new Map<string, WeakMap<TailorAnyDBType, Promise<TailorAnyDBType>>>();\n\n/**\n * Get a table with the fields its attached plugins add to it, as `tailor generate` sees it.\n * The plugins attached with `.plugin()` run in order, each seeing the fields the ones before\n * it added, and the result is cached per config path and table.\n * The table exported from the source file is not changed; the returned table is a new object.\n * Returns the source table itself when no plugin is attached to it, or when the config is\n * not available (e.g. in a bundled executor on the platform server).\n * @template T - The source table's own type, which the returned table keeps\n * @param configPath - Path to tailor.config.ts (absolute or relative to cwd)\n * @param sourceTable - The TailorDB table as exported from its source file\n * @returns The table with every plugin-added field\n */\nexport async function getExtendedTable<T extends TailorAnyDBType>(\n configPath: string,\n sourceTable: T,\n): Promise<T> {\n if (sourceTable.plugins.length === 0) {\n return sourceTable;\n }\n const resolvedPath = path.resolve(configPath);\n let tables = extendedTableCache.get(resolvedPath);\n if (!tables) {\n tables = new WeakMap();\n extendedTableCache.set(resolvedPath, tables);\n }\n const cached = tables.get(sourceTable);\n if (cached) {\n return cached as Promise<T>;\n }\n const pending = applyPluginExtensions(resolvedPath, sourceTable);\n tables.set(sourceTable, pending);\n pending.catch(() => tables.delete(sourceTable));\n return pending as Promise<T>;\n}\n\nasync function applyPluginExtensions(\n configPath: string,\n sourceTable: TailorAnyDBType,\n): Promise<TailorAnyDBType> {\n const cache = await loadAndCacheConfig(configPath);\n if (!cache) {\n return sourceTable;\n }\n const { config, configDir, plugins } = cache;\n const namespace = await resolveNamespaceForTable(config, configDir, sourceTable);\n const manager = new PluginManager([...plugins.values()].map((entry) => entry.plugin));\n const { extendedTable } = await manager.processAttachmentsForTable({\n rawTable: sourceTable as unknown as TailorDBTypeRaw,\n attachments: [...sourceTable.plugins],\n namespace,\n });\n return (extendedTable as TailorAnyDBType | undefined) ?? sourceTable;\n}\n\n/**\n * Clear all internal caches. For testing only.\n */\nexport function _clearCacheForTesting(): void {\n configCacheMap.clear();\n extendedTableCache.clear();\n}\n"],"mappings":"6KAiHA,SAAgB,kBACd,EAC4B,CAC5B,OAAO,CACT,CC5FA,MAAM,EAAiB,IAAI,IAS3B,eAAe,mBAAmB,EAAiD,CACjF,IAAM,EAAe,EAAK,QAAQ,CAAU,EAEtC,EAAS,EAAe,IAAI,CAAY,EAC9C,GAAI,EAAQ,OAAO,EAGnB,GAAI,CAAC,EAAG,WAAW,CAAY,EAC7B,OAAO,KAGT,IAAM,EAAe,MAAM,OAAO,EAAc,CAAY,CAAC,CAAC,MAC9D,GAAI,CAAC,GAAc,QACjB,MAAU,MAAM,6BAA6B,EAAa,4BAA4B,EAGxF,IAAM,EAAS,EAAa,QACtB,EAAY,EAAK,QAAQ,CAAY,EACrC,EAAU,IAAI,IAEpB,IAAK,IAAM,KAAS,EAAiB,CAAY,EAC/C,IAAK,IAAM,KAAQ,EAAO,CACxB,IAAM,EAAS,EACf,EAAQ,IAAI,EAAO,GAAI,CAAE,SAAQ,aAAc,EAAO,YAAa,CAAC,CACtE,CAGF,IAAM,EAAsB,CAAE,SAAQ,UAAS,WAAU,EAEzD,OADA,EAAe,IAAI,EAAc,CAAM,EAChC,CACT,CAoBA,eAAe,yBACb,EACA,EACA,EACiB,CACj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