@tailor-platform/sdk 2.24.0 → 2.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +48 -0
- package/dist/application-ChqHuhZW.mjs +1 -0
- package/dist/{application-CfqvzV3I.mjs → application-DS0XKBtK.mjs} +4 -4
- package/dist/application-DS0XKBtK.mjs.map +1 -0
- package/dist/cli/commands/deploy/deployment-target.d.mts +1 -0
- package/dist/cli/commands/machineuser/list.d.mts +1 -0
- package/dist/cli/commands/show.d.mts +13 -1
- package/dist/cli/lib.d.mts +2 -2
- package/dist/cli/lib.mjs +1 -1
- package/dist/cli/lib.mjs.map +1 -1
- package/dist/cli/main.mjs +46 -46
- package/dist/cli/main.mjs.map +1 -1
- package/dist/completion/zsh-worker.zsh +3 -3
- package/dist/configure/index.d.mts +2 -2
- package/dist/configure/index.mjs.map +1 -1
- package/dist/plugin/index.mjs +1 -1
- package/dist/plugin/index.mjs.map +1 -1
- package/dist/plugin/types.d.mts +97 -0
- package/dist/register-ts-hook-DPAW0Z4M.mjs +924 -0
- package/dist/register-ts-hook-DPAW0Z4M.mjs.map +1 -0
- package/docs/cli/application.md +23 -0
- package/docs/cli/secret.md +24 -16
- package/docs/cli-reference.md +25 -13
- package/docs/github-actions.md +69 -4
- package/docs/plugin/custom.md +76 -1
- package/docs/plugin/frontend.md +124 -0
- package/docs/plugin/index.md +24 -2
- package/docs/services/auth.md +2 -0
- package/docs/services/secret.md +5 -4
- package/docs/services/staticwebsite.md +2 -0
- package/docs/services/tailordb-migration.md +1 -1
- package/package.json +5 -5
- package/dist/application-BDqze-wy.mjs +0 -1
- package/dist/application-CfqvzV3I.mjs.map +0 -1
- package/dist/register-ts-hook-CVlI9Jzl.mjs +0 -922
- package/dist/register-ts-hook-CVlI9Jzl.mjs.map +0 -1
package/dist/plugin/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"../manager-8-JOvuLl.mjs";import*as t from"pathe";import*as n from"node:fs";import{pathToFileURL as r}from"node:url";function withPluginContext(e){return e}const i=/* @__PURE__ */ new Map,a=[`onTableLoaded`,`onNamespaceLoaded`,`onTailorDBReady`,`onResolverReady`,`onExecutorReady`];function isPlugin(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.id!=`string`||typeof t.description!=`string`||t.importPath!==void 0&&typeof t.importPath!=`string`||t.tableConfigRequired!==void 0&&typeof t.tableConfigRequired!=`boolean`&&typeof t.tableConfigRequired!=`function`)return!1;for(let e of a)if(t[e]!==void 0&&typeof t[e]!=`function`)return!1;return!((t.onTableLoaded||t.onNamespaceLoaded)&&!t.importPath)}async function loadAndCacheConfig(e){let a=t.resolve(e),o=i.get(a);if(o)return o;if(!n.existsSync(a))return null;let s=await import(r(a).href);if(!s?.default)throw Error(`Invalid config module at "${a}": default export not found`);let c=s.default,l=t.dirname(a),u=/* @__PURE__ */ new Map;if(Object.hasOwn(s,`plugins`)){let e=s.plugins;if(!Array.isArray(e))throw Error(`Invalid \`plugins\` export in "${a}": expected an array returned by definePlugins(), got ${typeof e}`);for(let t of e){if(!isPlugin(t))throw Error(`Invalid \`plugins\` export in "${a}": every item must be a plugin created by definePlugins()`);if(u.has(t.id))throw Error(`Duplicate plugin ID "${t.id}" detected in "${a}". Each plugin must have a unique ID.`);u.set(t.id,{plugin:t,pluginConfig:t.pluginConfig})}}let d={config:c,plugins:u,configDir:l};return i.set(a,d),d}async function resolveNamespaceForTable(e,i,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=t.resolve(i,s),c;try{c=n.globSync(e)}catch{continue}for(let e of c){let t=await import(r(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=/* @__PURE__ */ new WeakMap,s=/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ new Map;async function getExtendedTable(e,n){if(n.plugins.length===0)return n;let r=t.resolve(e),i=c.get(r);i||(i=/* @__PURE__ */ new WeakMap,c.set(r,i));let a=i.get(n);if(a)return a;let o=applyPluginExtensions(r,n);return i.set(n,o),o.catch(()=>i.delete(n)),o}async function applyPluginExtensions(t,n){let r=await loadAndCacheConfig(t);if(!r)return n;let{config:i,configDir:a,plugins:o}=r,s=await resolveNamespaceForTable(i,a,n),{extendedTable:c}=await new e([...o.values()].map(e=>e.plugin)).processAttachmentsForTable({rawTable:n,attachments:[...n.plugins],namespace:s});return c??n}export{getExtendedTable,getGeneratedTable,withPluginContext};
|
|
1
|
+
import{t as e}from"../manager-8-JOvuLl.mjs";import*as t from"pathe";import*as n from"node:fs";import{pathToFileURL as r}from"node:url";function withPluginContext(e){return e}const i=/* @__PURE__ */ new Map,a=[`onTableLoaded`,`onNamespaceLoaded`,`onTailorDBReady`,`onResolverReady`,`onExecutorReady`,`onDeployed`];function isPlugin(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=e;if(typeof t.id!=`string`||typeof t.description!=`string`||t.importPath!==void 0&&typeof t.importPath!=`string`||t.tableConfigRequired!==void 0&&typeof t.tableConfigRequired!=`boolean`&&typeof t.tableConfigRequired!=`function`)return!1;for(let e of a)if(t[e]!==void 0&&typeof t[e]!=`function`)return!1;return!((t.onTableLoaded||t.onNamespaceLoaded)&&!t.importPath)}async function loadAndCacheConfig(e){let a=t.resolve(e),o=i.get(a);if(o)return o;if(!n.existsSync(a))return null;let s=await import(r(a).href);if(!s?.default)throw Error(`Invalid config module at "${a}": default export not found`);let c=s.default,l=t.dirname(a),u=/* @__PURE__ */ new Map;if(Object.hasOwn(s,`plugins`)){let e=s.plugins;if(!Array.isArray(e))throw Error(`Invalid \`plugins\` export in "${a}": expected an array returned by definePlugins(), got ${typeof e}`);for(let t of e){if(!isPlugin(t))throw Error(`Invalid \`plugins\` export in "${a}": every item must be a plugin created by definePlugins()`);if(u.has(t.id))throw Error(`Duplicate plugin ID "${t.id}" detected in "${a}". Each plugin must have a unique ID.`);u.set(t.id,{plugin:t,pluginConfig:t.pluginConfig})}}let d={config:c,plugins:u,configDir:l};return i.set(a,d),d}async function resolveNamespaceForTable(e,i,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=t.resolve(i,s),c;try{c=n.globSync(e)}catch{continue}for(let e of c){let t=await import(r(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=/* @__PURE__ */ new WeakMap,s=/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ new Map;async function getExtendedTable(e,n){if(n.plugins.length===0)return n;let r=t.resolve(e),i=c.get(r);i||(i=/* @__PURE__ */ new WeakMap,c.set(r,i));let a=i.get(n);if(a)return a;let o=applyPluginExtensions(r,n);return i.set(n,o),o.catch(()=>i.delete(n)),o}async function applyPluginExtensions(t,n){let r=await loadAndCacheConfig(t);if(!r)return n;let{config:i,configDir:a,plugins:o}=r,s=await resolveNamespaceForTable(i,a,n),{extendedTable:c}=await new e([...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":["PluginManager","path","fs","factory","configCacheMap","OPTIONAL_HOOK_KEYS","value","candidate","key","resolvedPath","configPath","cached","configModule","pathToFileURL","config","configDir","plugins","pluginsExport","item","result","namespace","nsConfig","dbConfig","pattern","absolutePattern","matchedFiles","file","mod","exported","sourceTable","plugin","output","kind","processCache","namespaceProcessCache","pluginConfig","baseKey","cache","pluginEntry","pluginId","pluginCache","cacheKey","tableConfig","p","generatedTable","extendedTableCache","tables","pending","entry","extendedTable"],"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 { 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\nconst OPTIONAL_HOOK_KEYS = [\n \"onTableLoaded\",\n \"onNamespaceLoaded\",\n \"onTailorDBReady\",\n \"onResolverReady\",\n \"onExecutorReady\",\n] as const;\n\n/**\n * Check if a value is a Plugin instance. Mirrors PluginConfigSchema's shape without\n * depending on zod, since this module must stay usable from a bundled executor.\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 if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const candidate = value as Record<string, unknown>;\n if (typeof candidate.id !== \"string\" || typeof candidate.description !== \"string\") return false;\n if (candidate.importPath !== undefined && typeof candidate.importPath !== \"string\") return false;\n if (\n candidate.tableConfigRequired !== undefined &&\n typeof candidate.tableConfigRequired !== \"boolean\" &&\n typeof candidate.tableConfigRequired !== \"function\"\n )\n return false;\n for (const key of OPTIONAL_HOOK_KEYS) {\n if (candidate[key] !== undefined && typeof candidate[key] !== \"function\") return false;\n }\n const hasDefinitionTimeHooks = candidate.onTableLoaded || candidate.onNamespaceLoaded;\n if (hasDefinitionTimeHooks && !candidate.importPath) return false;\n return true;\n}\n\n/**\n * Load and cache config module from the given path.\n * Reads plugins from the config module's `plugins` export (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 if (Object.hasOwn(configModule, \"plugins\")) {\n const pluginsExport: unknown = configModule.plugins;\n if (!Array.isArray(pluginsExport)) {\n throw new Error(\n `Invalid \\`plugins\\` export in \"${resolvedPath}\": expected an array returned by definePlugins(), got ${typeof pluginsExport}`,\n );\n }\n for (const item of pluginsExport) {\n if (!isPlugin(item)) {\n throw new Error(\n `Invalid \\`plugins\\` export in \"${resolvedPath}\": every item must be a plugin created by definePlugins()`,\n );\n }\n if (plugins.has(item.id)) {\n throw new Error(\n `Duplicate plugin ID \"${item.id}\" detected in \"${resolvedPath}\". Each plugin must have a unique ID.`,\n );\n }\n plugins.set(item.id, { plugin: item, pluginConfig: item.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":"uIAiHA,SAAgB,kBACd,EAC4B,CAC5B,OAAOG,CACT,CC7FA,MAAMC,kBAAiB,IAAI,IAErBC,EAAqB,CACzB,gBACA,oBACA,kBACA,kBACA,iBACF,EAQA,SAAS,SAAS,EAAiC,CACjD,GAAI,OAAOC,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMC,EAAYD,EAGlB,GAFI,OAAOC,EAAU,IAAO,UAAY,OAAOA,EAAU,aAAgB,UACrEA,EAAU,aAAe,IAAA,IAAa,OAAOA,EAAU,YAAe,UAExEA,EAAU,sBAAwB,IAAA,IAClC,OAAOA,EAAU,qBAAwB,WACzC,OAAOA,EAAU,qBAAwB,WAEzC,MAAO,GACT,IAAK,IAAMC,KAAOH,EAChB,GAAIE,EAAUC,KAAS,IAAA,IAAa,OAAOD,EAAUC,IAAS,WAAY,MAAO,GAInF,MADA,GAD+BD,EAAU,eAAiBA,EAAU,oBACtC,CAACA,EAAU,WAE3C,CASA,eAAe,mBAAmB,E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K,GAAUgC,EAAM,MAAM,CAC7C,CAAC,CAAC,2BAA2B,CACjE,SAAUnB,EACV,YAAa,CAAC,GAAGA,EAAY,OAAO,EACpC,WACF,CAAC,EACD,OAAQoB,GAAiDpB,CAC3D"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":["PluginManager","path","fs","factory","configCacheMap","OPTIONAL_HOOK_KEYS","value","candidate","key","resolvedPath","configPath","cached","configModule","pathToFileURL","config","configDir","plugins","pluginsExport","item","result","namespace","nsConfig","dbConfig","pattern","absolutePattern","matchedFiles","file","mod","exported","sourceTable","plugin","output","kind","processCache","namespaceProcessCache","pluginConfig","baseKey","cache","pluginEntry","pluginId","pluginCache","cacheKey","tableConfig","p","generatedTable","extendedTableCache","tables","pending","entry","extendedTable"],"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 { 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\nconst OPTIONAL_HOOK_KEYS = [\n \"onTableLoaded\",\n \"onNamespaceLoaded\",\n \"onTailorDBReady\",\n \"onResolverReady\",\n \"onExecutorReady\",\n \"onDeployed\",\n] as const;\n\n/**\n * Check if a value is a Plugin instance. Mirrors PluginConfigSchema's shape without\n * depending on zod, since this module must stay usable from a bundled executor.\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 if (typeof value !== \"object\" || value === null || Array.isArray(value)) return false;\n const candidate = value as Record<string, unknown>;\n if (typeof candidate.id !== \"string\" || typeof candidate.description !== \"string\") return false;\n if (candidate.importPath !== undefined && typeof candidate.importPath !== \"string\") return false;\n if (\n candidate.tableConfigRequired !== undefined &&\n typeof candidate.tableConfigRequired !== \"boolean\" &&\n typeof candidate.tableConfigRequired !== \"function\"\n )\n return false;\n for (const key of OPTIONAL_HOOK_KEYS) {\n if (candidate[key] !== undefined && typeof candidate[key] !== \"function\") return false;\n }\n const hasDefinitionTimeHooks = candidate.onTableLoaded || candidate.onNamespaceLoaded;\n if (hasDefinitionTimeHooks && !candidate.importPath) return false;\n return true;\n}\n\n/**\n * Load and cache config module from the given path.\n * Reads plugins from the config module's `plugins` export (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 if (Object.hasOwn(configModule, \"plugins\")) {\n const pluginsExport: unknown = configModule.plugins;\n if (!Array.isArray(pluginsExport)) {\n throw new Error(\n `Invalid \\`plugins\\` export in \"${resolvedPath}\": expected an array returned by definePlugins(), got ${typeof pluginsExport}`,\n );\n }\n for (const item of pluginsExport) {\n if (!isPlugin(item)) {\n throw new Error(\n `Invalid \\`plugins\\` export in \"${resolvedPath}\": every item must be a plugin created by definePlugins()`,\n );\n }\n if (plugins.has(item.id)) {\n throw new Error(\n `Duplicate plugin ID \"${item.id}\" detected in \"${resolvedPath}\". Each plugin must have a unique ID.`,\n );\n }\n plugins.set(item.id, { plugin: item, pluginConfig: item.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":"uIAiHA,SAAgB,kBACd,EAC4B,CAC5B,OAAOG,CACT,CC7FA,MAAMC,kBAAiB,IAAI,IAErBC,EAAqB,CACzB,gBACA,oBACA,kBACA,kBACA,kBACA,YACF,EAQA,SAAS,SAAS,EAAiC,CACjD,GAAI,OAAOC,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMC,EAAYD,EAGlB,GAFI,OAAOC,EAAU,IAAO,UAAY,OAAOA,EAAU,aAAgB,UACrEA,EAAU,aAAe,IAAA,IAAa,OAAOA,EAAU,YAAe,UAExEA,EAAU,sBAAwB,IAAA,IAClC,OAAOA,EAAU,qBAAwB,WACzC,OAAOA,EAAU,qBAAwB,WAEzC,MAAO,GACT,IAAK,IAAMC,KAAOH,EAChB,GAAIE,EAAUC,KAAS,IAAA,IAAa,OAAOD,EAAUC,IAAS,WAA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AW,EAEzE,CAAE,iBAAkB,MAAM,IADZ7B,EAAc,CAAC,GAAGgB,EAAQ,OAAO,CAAC,CAAC,CAAC,IAAK,GAAUgC,EAAM,MAAM,CAC7C,CAAC,CAAC,2BAA2B,CACjE,SAAUnB,EACV,YAAa,CAAC,GAAGA,EAAY,OAAO,EACpC,WACF,CAAC,EACD,OAAQoB,GAAiDpB,CAC3D"}
|
package/dist/plugin/types.d.mts
CHANGED
|
@@ -254,6 +254,103 @@ export interface Plugin<TableConfig = unknown, PluginConfig = unknown, FieldExte
|
|
|
254
254
|
onTailorDBReady?(context: TailorDBReadyContext<PluginConfig>): GeneratorResult | Promise<GeneratorResult>;
|
|
255
255
|
onResolverReady?(context: ResolverReadyContext<PluginConfig>): GeneratorResult | Promise<GeneratorResult>;
|
|
256
256
|
onExecutorReady?(context: ExecutorReadyContext<PluginConfig>): GeneratorResult | Promise<GeneratorResult>;
|
|
257
|
+
/** Runs after a successful deploy, including deploys with no resource changes. */
|
|
258
|
+
onDeployed?(context: DeployedContext<PluginConfig>): void | DeployedHookResult | Promise<void | DeployedHookResult>;
|
|
259
|
+
}
|
|
260
|
+
export interface PublishStaticWebsiteResult {
|
|
261
|
+
url: string;
|
|
262
|
+
skippedFiles: string[];
|
|
263
|
+
}
|
|
264
|
+
export interface DeployedStaticWebsite {
|
|
265
|
+
name: string;
|
|
266
|
+
url: string;
|
|
267
|
+
}
|
|
268
|
+
/** A static website declared in the config that registers the plugin, which the plugin can publish to. */
|
|
269
|
+
export interface PublishableStaticWebsite extends DeployedStaticWebsite {
|
|
270
|
+
/** Uploads the directory at the absolute path `dir` and publishes it to this website. */
|
|
271
|
+
publish(dir: string): Promise<PublishStaticWebsiteResult>;
|
|
272
|
+
}
|
|
273
|
+
export interface DeployedOAuth2Client {
|
|
274
|
+
name: string;
|
|
275
|
+
clientId: string;
|
|
276
|
+
}
|
|
277
|
+
export interface DeployedApplication<StaticWebsite extends DeployedStaticWebsite = DeployedStaticWebsite> {
|
|
278
|
+
/** SDK-managed application ID from defineConfig(); undefined when the config has none. */
|
|
279
|
+
id?: string;
|
|
280
|
+
name: string;
|
|
281
|
+
configPath: string;
|
|
282
|
+
/** Application endpoint URL, present when a matching Platform Application exists. */
|
|
283
|
+
url?: string;
|
|
284
|
+
domain?: string;
|
|
285
|
+
aiGateways: {
|
|
286
|
+
name: string;
|
|
287
|
+
url: string;
|
|
288
|
+
}[];
|
|
289
|
+
/** Static websites declared in this application's config, keyed by name. */
|
|
290
|
+
staticWebsites: Readonly<Partial<Record<string, StaticWebsite>>>;
|
|
291
|
+
auth?: {
|
|
292
|
+
namespace: string;
|
|
293
|
+
oauth2Clients: DeployedOAuth2Client[];
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
export interface PluginLogger {
|
|
297
|
+
info(message: string): void;
|
|
298
|
+
warn(message: string): void;
|
|
299
|
+
success(message: string): void;
|
|
300
|
+
}
|
|
301
|
+
export interface PluginExecOptions {
|
|
302
|
+
/** Directory to run the command in. */
|
|
303
|
+
workingDir: string;
|
|
304
|
+
/** Environment variables added to the environment `tailor` runs with. */
|
|
305
|
+
env?: Record<string, string>;
|
|
306
|
+
/**
|
|
307
|
+
* Where the command's output goes. `"stream"` (default) writes both stdout and stderr to stderr
|
|
308
|
+
* so `--json` results on stdout stay parseable, `"capture"` returns them, and `"ignore"` discards them.
|
|
309
|
+
*/
|
|
310
|
+
output?: "stream" | "capture" | "ignore";
|
|
311
|
+
}
|
|
312
|
+
export interface PluginExecResult {
|
|
313
|
+
/** Captured stdout. Empty unless `output` is `"capture"`. */
|
|
314
|
+
stdout: string;
|
|
315
|
+
/** Captured stderr. Empty unless `output` is `"capture"`. */
|
|
316
|
+
stderr: string;
|
|
317
|
+
}
|
|
318
|
+
/** Values available after all applications in this deploy run have been applied. */
|
|
319
|
+
export interface DeployedContext<PluginConfig = unknown> {
|
|
320
|
+
workspaceId: string;
|
|
321
|
+
/** Application whose config registers this plugin. Only its static websites can be published. */
|
|
322
|
+
application: DeployedApplication<PublishableStaticWebsite>;
|
|
323
|
+
/** Every application in this deploy run, including the registering one. */
|
|
324
|
+
applications: readonly DeployedApplication[];
|
|
325
|
+
/** Absolute path of the config registering this plugin. */
|
|
326
|
+
configPath: string;
|
|
327
|
+
pluginConfig: PluginConfig;
|
|
328
|
+
logger: PluginLogger;
|
|
329
|
+
/**
|
|
330
|
+
* Run a shell command on the machine running `tailor deploy`. Rejects when the command exits with a non-zero code.
|
|
331
|
+
* @param command - Shell command, such as `pnpm build`
|
|
332
|
+
* @param options - Working directory, added environment variables, and output handling
|
|
333
|
+
* @returns Captured output when `options.output` is `"capture"`
|
|
334
|
+
*/
|
|
335
|
+
exec(command: string, options: PluginExecOptions): Promise<PluginExecResult>;
|
|
336
|
+
}
|
|
337
|
+
type OutputObject = object & {
|
|
338
|
+
[Symbol.iterator]?: never;
|
|
339
|
+
[Symbol.toStringTag]?: never;
|
|
340
|
+
[Symbol.hasInstance]?: never;
|
|
341
|
+
[Symbol.toPrimitive]?: never;
|
|
342
|
+
[Symbol.match]?: never;
|
|
343
|
+
};
|
|
344
|
+
/**
|
|
345
|
+
* A value a plugin hook can return in `outputs`. Interface-typed objects are accepted;
|
|
346
|
+
* a `Date` or class instance nested inside one is rejected when the deploy runs.
|
|
347
|
+
*/
|
|
348
|
+
export type PluginOutputValue = string | number | boolean | null | readonly PluginOutputValue[] | {
|
|
349
|
+
[key: string]: PluginOutputValue;
|
|
350
|
+
} | OutputObject;
|
|
351
|
+
export interface DeployedHookResult {
|
|
352
|
+
/** Values included in deploy's JSON result. Interface-typed values are accepted, but a `Date` or class instance nested inside one fails the deploy instead of the type check. */
|
|
353
|
+
outputs?: Record<string, PluginOutputValue>;
|
|
257
354
|
}
|
|
258
355
|
//#endregion
|
|
259
356
|
export type { PluginAttachment };
|