@xtr-dev/payload-automation 0.0.20 → 0.0.22
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.
|
@@ -187,11 +187,13 @@ export const createWorkflowCollection = ({ collectionTriggers, steps, triggers }
|
|
|
187
187
|
}
|
|
188
188
|
]
|
|
189
189
|
},
|
|
190
|
-
{
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
190
|
+
...(steps || []).flatMap((step)=>(step.inputSchema || []).map((field)=>({
|
|
191
|
+
...field,
|
|
192
|
+
admin: {
|
|
193
|
+
...field.admin || {},
|
|
194
|
+
condition: (...args)=>args[1]?.step === step.slug && (field.admin?.condition ? field.admin.condition.call(this, ...args) : true)
|
|
195
|
+
}
|
|
196
|
+
}))),
|
|
195
197
|
{
|
|
196
198
|
name: 'dependencies',
|
|
197
199
|
type: 'text',
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/collections/Workflow.ts"],"sourcesContent":["import type {CollectionConfig, Field} from 'payload'\n\nimport type {WorkflowsPluginConfig} from \"../plugin/config-types.js\"\n\nexport const createWorkflowCollection: <T extends string>(options: WorkflowsPluginConfig<T>) => CollectionConfig = ({\n collectionTriggers,\n steps,\n triggers\n }) => ({\n slug: 'workflows',\n access: {\n create: () => true,\n delete: () => true,\n read: () => true,\n update: () => true,\n },\n admin: {\n defaultColumns: ['name', 'updatedAt'],\n description: 'Create and manage automated workflows.',\n group: 'Automation',\n useAsTitle: 'name',\n },\n fields: [\n {\n name: 'name',\n type: 'text',\n admin: {\n description: 'Human-readable name for the workflow',\n },\n required: true,\n },\n {\n name: 'description',\n type: 'textarea',\n admin: {\n description: 'Optional description of what this workflow does',\n },\n },\n {\n name: 'triggers',\n type: 'array',\n fields: [\n {\n name: 'type',\n type: 'select',\n options: [\n 'collection-trigger',\n 'webhook-trigger',\n 'global-trigger',\n 'cron-trigger',\n ...(triggers || []).map(t => t.slug)\n ]\n },\n {\n name: 'collectionSlug',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'collection-trigger',\n description: 'Collection that triggers the workflow',\n },\n options: Object.keys(collectionTriggers || {})\n },\n {\n name: 'operation',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'collection-trigger',\n description: 'Collection operation that triggers the workflow',\n },\n options: [\n 'create',\n 'delete',\n 'read',\n 'update',\n ]\n },\n {\n name: 'webhookPath',\n type: 'text',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'webhook-trigger',\n description: 'URL path for the webhook (e.g., \"my-webhook\"). Full URL will be /api/workflows/webhook/my-webhook',\n },\n validate: (value: any, {siblingData}: any) => {\n if (siblingData?.type === 'webhook-trigger' && !value) {\n return 'Webhook path is required for webhook triggers'\n }\n return true\n }\n },\n {\n name: 'global',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'global-trigger',\n description: 'Global that triggers the workflow',\n },\n options: [] // Will be populated dynamically based on available globals\n },\n {\n name: 'globalOperation',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'global-trigger',\n description: 'Global operation that triggers the workflow',\n },\n options: [\n 'update'\n ]\n },\n {\n name: 'cronExpression',\n type: 'text',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'cron-trigger',\n description: 'Cron expression for scheduled execution (e.g., \"0 0 * * *\" for daily at midnight)',\n placeholder: '0 0 * * *'\n },\n validate: (value: any, {siblingData}: any) => {\n if (siblingData?.type === 'cron-trigger' && !value) {\n return 'Cron expression is required for cron triggers'\n }\n\n // Validate cron expression format if provided\n if (siblingData?.type === 'cron-trigger' && value) {\n // Basic format validation - should be 5 parts separated by spaces\n const cronParts = value.trim().split(/\\s+/)\n if (cronParts.length !== 5) {\n return 'Invalid cron expression format. Expected 5 parts: \"minute hour day month weekday\" (e.g., \"0 9 * * 1\")'\n }\n\n // Additional validation could use node-cron but we avoid dynamic imports here\n // The main validation happens at runtime in the cron scheduler\n }\n\n return true\n }\n },\n {\n name: 'timezone',\n type: 'text',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'cron-trigger',\n description: 'Timezone for cron execution (e.g., \"America/New_York\", \"Europe/London\"). Defaults to UTC.',\n placeholder: 'UTC'\n },\n defaultValue: 'UTC',\n validate: (value: any, {siblingData}: any) => {\n if (siblingData?.type === 'cron-trigger' && value) {\n try {\n // Test if timezone is valid by trying to create a date with it\n new Intl.DateTimeFormat('en', {timeZone: value})\n return true\n } catch {\n return `Invalid timezone: ${value}. Please use a valid IANA timezone identifier (e.g., \"America/New_York\", \"Europe/London\")`\n }\n }\n return true\n }\n },\n {\n name: 'condition',\n type: 'text',\n admin: {\n description: 'JSONPath expression that must evaluate to true for this trigger to execute the workflow (e.g., \"$.doc.status == \\'published\\'\")'\n },\n required: false\n },\n ...(triggers || []).flatMap(t => (t.inputs || []).map(f => ({\n ...f,\n admin: {\n ...(f.admin || {}),\n condition: (...args) => args[1]?.type === t.slug && (\n f.admin?.condition ?\n f.admin.condition.call(this, ...args) :\n true\n ),\n },\n } as Field)))\n ]\n },\n {\n name: 'steps',\n type: 'array',\n fields: [\n {\n type: 'row',\n fields: [\n {\n name: 'step',\n type: 'select',\n options: steps.map(t => t.slug)\n },\n {\n name: 'name',\n type: 'text',\n }\n ]\n },\n {\n name: 'input',\n type: 'json',\n required: false\n },\n {\n name: 'dependencies',\n type: 'text',\n admin: {\n description: 'Step names that must complete before this step can run'\n },\n hasMany: true,\n required: false\n },\n {\n name: 'condition',\n type: 'text',\n admin: {\n description: 'JSONPath expression that must evaluate to true for this step to execute (e.g., \"$.trigger.doc.status == \\'published\\'\")'\n },\n required: false\n },\n ],\n }\n ],\n versions: {\n drafts: {\n autosave: false,\n },\n maxPerDoc: 10,\n },\n})\n"],"names":["createWorkflowCollection","collectionTriggers","steps","triggers","slug","access","create","delete","read","update","admin","defaultColumns","description","group","useAsTitle","fields","name","type","required","options","map","t","condition","_","siblingData","Object","keys","validate","value","placeholder","cronParts","trim","split","length","defaultValue","Intl","DateTimeFormat","timeZone","flatMap","inputs","f","args","call","hasMany","versions","drafts","autosave","maxPerDoc"],"mappings":"AAIA,OAAO,MAAMA,2BAAsG,CAAC,EACZC,kBAAkB,EAClBC,KAAK,EACLC,QAAQ,EACT,GAAM,CAAA;QAC3GC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;YACdC,QAAQ,IAAM;YACdC,MAAM,IAAM;YACZC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,gBAAgB;gBAAC;gBAAQ;aAAY;YACrCC,aAAa;YACbC,OAAO;YACPC,YAAY;QACd;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;gBACNP,OAAO;oBACLE,aAAa;gBACf;gBACAM,UAAU;YACZ;YACA;gBACEF,MAAM;gBACNC,MAAM;gBACNP,OAAO;oBACLE,aAAa;gBACf;YACF;YACA;gBACEI,MAAM;gBACNC,MAAM;gBACNF,QAAQ;oBACN;wBACEC,MAAM;wBACNC,MAAM;wBACNE,SAAS;4BACP;4BACA;4BACA;4BACA;+BACG,AAAChB,CAAAA,YAAY,EAAE,AAAD,EAAGiB,GAAG,CAACC,CAAAA,IAAKA,EAAEjB,IAAI;yBACpC;oBACH;oBACA;wBACEY,MAAM;wBACNC,MAAM;wBACNP,OAAO;4BACLY,WAAW,CAACC,GAAGC,cAAgBA,aAAaP,SAAS;4BACrDL,aAAa;wBACf;wBACAO,SAASM,OAAOC,IAAI,CAACzB,sBAAsB,CAAC;oBAC9C;oBACA;wBACEe,MAAM;wBACNC,MAAM;wBACNP,OAAO;4BACLY,WAAW,CAACC,GAAGC,cAAgBA,aAAaP,SAAS;4BACrDL,aAAa;wBACf;wBACAO,SAAS;4BACP;4BACA;4BACA;4BACA;yBACD;oBACH;oBACA;wBACEH,MAAM;wBACNC,MAAM;wBACNP,OAAO;4BACLY,WAAW,CAACC,GAAGC,cAAgBA,aAAaP,SAAS;4BACrDL,aAAa;wBACf;wBACAe,UAAU,CAACC,OA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;IACF,CAAA,EAAE"}
|
|
1
|
+
{"version":3,"sources":["../../src/collections/Workflow.ts"],"sourcesContent":["import type {CollectionConfig, Field} from 'payload'\n\nimport type {WorkflowsPluginConfig} from \"../plugin/config-types.js\"\n\nexport const createWorkflowCollection: <T extends string>(options: WorkflowsPluginConfig<T>) => CollectionConfig = ({\n collectionTriggers,\n steps,\n triggers\n }) => ({\n slug: 'workflows',\n access: {\n create: () => true,\n delete: () => true,\n read: () => true,\n update: () => true,\n },\n admin: {\n defaultColumns: ['name', 'updatedAt'],\n description: 'Create and manage automated workflows.',\n group: 'Automation',\n useAsTitle: 'name',\n },\n fields: [\n {\n name: 'name',\n type: 'text',\n admin: {\n description: 'Human-readable name for the workflow',\n },\n required: true,\n },\n {\n name: 'description',\n type: 'textarea',\n admin: {\n description: 'Optional description of what this workflow does',\n },\n },\n {\n name: 'triggers',\n type: 'array',\n fields: [\n {\n name: 'type',\n type: 'select',\n options: [\n 'collection-trigger',\n 'webhook-trigger',\n 'global-trigger',\n 'cron-trigger',\n ...(triggers || []).map(t => t.slug)\n ]\n },\n {\n name: 'collectionSlug',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'collection-trigger',\n description: 'Collection that triggers the workflow',\n },\n options: Object.keys(collectionTriggers || {})\n },\n {\n name: 'operation',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'collection-trigger',\n description: 'Collection operation that triggers the workflow',\n },\n options: [\n 'create',\n 'delete',\n 'read',\n 'update',\n ]\n },\n {\n name: 'webhookPath',\n type: 'text',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'webhook-trigger',\n description: 'URL path for the webhook (e.g., \"my-webhook\"). Full URL will be /api/workflows/webhook/my-webhook',\n },\n validate: (value: any, {siblingData}: any) => {\n if (siblingData?.type === 'webhook-trigger' && !value) {\n return 'Webhook path is required for webhook triggers'\n }\n return true\n }\n },\n {\n name: 'global',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'global-trigger',\n description: 'Global that triggers the workflow',\n },\n options: [] // Will be populated dynamically based on available globals\n },\n {\n name: 'globalOperation',\n type: 'select',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'global-trigger',\n description: 'Global operation that triggers the workflow',\n },\n options: [\n 'update'\n ]\n },\n {\n name: 'cronExpression',\n type: 'text',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'cron-trigger',\n description: 'Cron expression for scheduled execution (e.g., \"0 0 * * *\" for daily at midnight)',\n placeholder: '0 0 * * *'\n },\n validate: (value: any, {siblingData}: any) => {\n if (siblingData?.type === 'cron-trigger' && !value) {\n return 'Cron expression is required for cron triggers'\n }\n\n // Validate cron expression format if provided\n if (siblingData?.type === 'cron-trigger' && value) {\n // Basic format validation - should be 5 parts separated by spaces\n const cronParts = value.trim().split(/\\s+/)\n if (cronParts.length !== 5) {\n return 'Invalid cron expression format. Expected 5 parts: \"minute hour day month weekday\" (e.g., \"0 9 * * 1\")'\n }\n\n // Additional validation could use node-cron but we avoid dynamic imports here\n // The main validation happens at runtime in the cron scheduler\n }\n\n return true\n }\n },\n {\n name: 'timezone',\n type: 'text',\n admin: {\n condition: (_, siblingData) => siblingData?.type === 'cron-trigger',\n description: 'Timezone for cron execution (e.g., \"America/New_York\", \"Europe/London\"). Defaults to UTC.',\n placeholder: 'UTC'\n },\n defaultValue: 'UTC',\n validate: (value: any, {siblingData}: any) => {\n if (siblingData?.type === 'cron-trigger' && value) {\n try {\n // Test if timezone is valid by trying to create a date with it\n new Intl.DateTimeFormat('en', {timeZone: value})\n return true\n } catch {\n return `Invalid timezone: ${value}. Please use a valid IANA timezone identifier (e.g., \"America/New_York\", \"Europe/London\")`\n }\n }\n return true\n }\n },\n {\n name: 'condition',\n type: 'text',\n admin: {\n description: 'JSONPath expression that must evaluate to true for this trigger to execute the workflow (e.g., \"$.doc.status == \\'published\\'\")'\n },\n required: false\n },\n ...(triggers || []).flatMap(t => (t.inputs || []).map(f => ({\n ...f,\n admin: {\n ...(f.admin || {}),\n condition: (...args) => args[1]?.type === t.slug && (\n f.admin?.condition ?\n f.admin.condition.call(this, ...args) :\n true\n ),\n },\n } as Field)))\n ]\n },\n {\n name: 'steps',\n type: 'array',\n fields: [\n {\n type: 'row',\n fields: [\n {\n name: 'step',\n type: 'select',\n options: steps.map(t => t.slug)\n },\n {\n name: 'name',\n type: 'text',\n }\n ]\n },\n ...(steps || []).flatMap(step => (step.inputSchema || []).map(field => ({\n ...field,\n admin: {\n ...(field.admin || {}),\n condition: (...args) => args[1]?.step === step.slug && (\n field.admin?.condition ?\n field.admin.condition.call(this, ...args) :\n true\n ),\n },\n } as Field))),\n {\n name: 'dependencies',\n type: 'text',\n admin: {\n description: 'Step names that must complete before this step can run'\n },\n hasMany: true,\n required: false\n },\n {\n name: 'condition',\n type: 'text',\n admin: {\n description: 'JSONPath expression that must evaluate to true for this step to execute (e.g., \"$.trigger.doc.status == \\'published\\'\")'\n },\n required: false\n },\n ],\n }\n ],\n versions: {\n drafts: {\n autosave: false,\n },\n maxPerDoc: 10,\n },\n})\n"],"names":["createWorkflowCollection","collectionTriggers","steps","triggers","slug","access","create","delete","read","update","admin","defaultColumns","description","group","useAsTitle","fields","name","type","required","options","map","t","condition","_","siblingData","Object","keys","validate","value","placeholder","cronParts","trim","split","length","defaultValue","Intl","DateTimeFormat","timeZone","flatMap","inputs","f","args","call","step","inputSchema","field","hasMany","versions","drafts","autosave","maxPerDoc"],"mappings":"AAIA,OAAO,MAAMA,2BAAsG,CAAC,EACZC,kBAAkB,EAClBC,KAAK,EACLC,QAAQ,EACT,GAAM,CAAA;QAC3GC,MAAM;QACNC,QAAQ;YACNC,QAAQ,IAAM;YACdC,QAAQ,IAAM;YACdC,MAAM,IAAM;YACZC,QAAQ,IAAM;QAChB;QACAC,OAAO;YACLC,gBAAgB;gBAAC;gBAAQ;aAAY;YACrCC,aAAa;YACbC,OAAO;YACPC,YAAY;QACd;QACAC,QAAQ;YACN;gBACEC,MAAM;gBACNC,MAAM;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package/dist/plugin/index.js
CHANGED
|
@@ -13,6 +13,11 @@ let globalExecutor = null;
|
|
|
13
13
|
const setWorkflowExecutor = (executor)=>{
|
|
14
14
|
console.log('🚨 SETTING GLOBAL EXECUTOR');
|
|
15
15
|
globalExecutor = executor;
|
|
16
|
+
// Also set on global object as fallback
|
|
17
|
+
if (typeof global !== 'undefined') {
|
|
18
|
+
global.__workflowExecutor = executor;
|
|
19
|
+
console.log('🚨 EXECUTOR ALSO SET ON GLOBAL OBJECT');
|
|
20
|
+
}
|
|
16
21
|
};
|
|
17
22
|
const getWorkflowExecutor = ()=>{
|
|
18
23
|
return globalExecutor;
|
|
@@ -53,30 +58,44 @@ export const workflowsPlugin = (pluginOptions)=>(config)=>{
|
|
|
53
58
|
if (!collection.hooks.afterChange) {
|
|
54
59
|
collection.hooks.afterChange = [];
|
|
55
60
|
}
|
|
56
|
-
//
|
|
57
|
-
//
|
|
58
|
-
const automationHook = async (args)
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
61
|
+
// Create a properly bound hook function that doesn't rely on closures
|
|
62
|
+
// Use a simple function that PayloadCMS can definitely execute
|
|
63
|
+
const automationHook = Object.assign(async function payloadAutomationHook(args) {
|
|
64
|
+
try {
|
|
65
|
+
// Use global console to ensure output
|
|
66
|
+
global.console.log('🔥🔥🔥 AUTOMATION HOOK EXECUTED! 🔥🔥🔥');
|
|
67
|
+
global.console.log('Collection:', args?.collection?.slug);
|
|
68
|
+
global.console.log('Operation:', args?.operation);
|
|
69
|
+
global.console.log('Doc ID:', args?.doc?.id);
|
|
70
|
+
// Try multiple ways to get the executor
|
|
71
|
+
let executor = null;
|
|
72
|
+
// Method 1: Global registry
|
|
73
|
+
if (typeof getWorkflowExecutor === 'function') {
|
|
74
|
+
executor = getWorkflowExecutor();
|
|
75
|
+
}
|
|
76
|
+
// Method 2: Global variable fallback
|
|
77
|
+
if (!executor && typeof global !== 'undefined' && global.__workflowExecutor) {
|
|
78
|
+
executor = global.__workflowExecutor;
|
|
79
|
+
global.console.log('Got executor from global variable');
|
|
80
|
+
}
|
|
81
|
+
if (executor) {
|
|
82
|
+
global.console.log('✅ Executor found - executing workflows!');
|
|
71
83
|
await executor.executeTriggeredWorkflows(args.collection.slug, args.operation, args.doc, args.previousDoc, args.req);
|
|
72
|
-
console.log('✅ Workflow execution completed!');
|
|
73
|
-
}
|
|
74
|
-
console.
|
|
84
|
+
global.console.log('✅ Workflow execution completed!');
|
|
85
|
+
} else {
|
|
86
|
+
global.console.log('⚠️ No executor available');
|
|
75
87
|
}
|
|
76
|
-
}
|
|
77
|
-
console.
|
|
88
|
+
} catch (error) {
|
|
89
|
+
global.console.error('❌ Hook execution error:', error);
|
|
90
|
+
// Don't throw - just log
|
|
78
91
|
}
|
|
79
|
-
|
|
92
|
+
// Always return undefined to match other hooks
|
|
93
|
+
return undefined;
|
|
94
|
+
}, {
|
|
95
|
+
// Add metadata to help debugging
|
|
96
|
+
__isAutomationHook: true,
|
|
97
|
+
__version: '0.0.21'
|
|
98
|
+
});
|
|
80
99
|
// Add the hook to the collection config
|
|
81
100
|
collection.hooks.afterChange.push(automationHook);
|
|
82
101
|
logger.info(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`);
|
package/dist/plugin/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type {Config} from 'payload'\n\nimport type {WorkflowsPluginConfig, CollectionTriggerConfigCrud} from \"./config-types.js\"\n\nimport {createWorkflowCollection} from '../collections/Workflow.js'\nimport {WorkflowRunsCollection} from '../collections/WorkflowRuns.js'\nimport {WorkflowExecutor} from '../core/workflow-executor.js'\nimport {generateCronTasks, registerCronJobs} from './cron-scheduler.js'\nimport {initCollectionHooks} from \"./init-collection-hooks.js\"\nimport {initGlobalHooks} from \"./init-global-hooks.js\"\nimport {initStepTasks} from \"./init-step-tasks.js\"\nimport {initWebhookEndpoint} from \"./init-webhook.js\"\nimport {initWorkflowHooks} from './init-workflow-hooks.js'\nimport {getConfigLogger, initializeLogger} from './logger.js'\n\nexport {getLogger} from './logger.js'\n\n// Global executor registry for config-phase hooks\nlet globalExecutor: WorkflowExecutor | null = null\n\nconst setWorkflowExecutor = (executor: WorkflowExecutor) => {\n console.log('🚨 SETTING GLOBAL EXECUTOR')\n globalExecutor = executor\n}\n\nconst getWorkflowExecutor = (): WorkflowExecutor | null => {\n return globalExecutor\n}\n\nconst applyCollectionsConfig = <T extends string>(pluginOptions: WorkflowsPluginConfig<T>, config: Config) => {\n // Add workflow collections\n if (!config.collections) {\n config.collections = []\n }\n\n config.collections.push(\n createWorkflowCollection(pluginOptions),\n WorkflowRunsCollection\n )\n}\n\n// Removed config-phase hook registration - user collections don't exist during config phase\n\n\nexport const workflowsPlugin =\n <TSlug extends string>(pluginOptions: WorkflowsPluginConfig<TSlug>) =>\n (config: Config): Config => {\n // If the plugin is disabled, return config unchanged\n if (pluginOptions.enabled === false) {\n return config\n }\n\n applyCollectionsConfig<TSlug>(pluginOptions, config)\n \n // CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them\n // This is the ONLY time we can add hooks that will actually work\n const logger = getConfigLogger()\n logger.info('Attempting to modify collection configs before PayloadCMS initialization...')\n \n if (config.collections && pluginOptions.collectionTriggers) {\n for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {\n if (!triggerConfig) continue\n \n // Find the collection config that matches\n const collectionIndex = config.collections.findIndex(c => c.slug === triggerSlug)\n if (collectionIndex === -1) {\n logger.warn(`Collection '${triggerSlug}' not found in config.collections`)\n continue\n }\n \n const collection = config.collections[collectionIndex]\n logger.info(`Found collection '${triggerSlug}' - modifying its hooks...`)\n \n // Initialize hooks if needed\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.afterChange) {\n collection.hooks.afterChange = []\n }\n \n // Add our hook DIRECTLY to the collection config\n // This happens BEFORE PayloadCMS processes the config\n const automationHook = async (args: any) => {\n console.log('🔥🔥🔥 AUTOMATION HOOK FROM CONFIG PHASE! 🔥🔥🔥')\n console.log('Collection:', args.collection.slug)\n console.log('Operation:', args.operation)\n console.log('Doc ID:', args.doc?.id)\n \n // We'll need to get the executor from somewhere\n // For now, just prove the hook works\n console.log('🔥🔥🔥 CONFIG-PHASE HOOK SUCCESSFULLY EXECUTED! 🔥🔥🔥')\n \n // Try to get executor from global registry\n const executor = getWorkflowExecutor()\n if (executor) {\n console.log('✅ Executor available - executing workflows!')\n try {\n await executor.executeTriggeredWorkflows(\n args.collection.slug,\n args.operation,\n args.doc,\n args.previousDoc,\n args.req\n )\n console.log('✅ Workflow execution completed!')\n } catch (error) {\n console.error('❌ Workflow execution failed:', error)\n }\n } else {\n console.log('⚠️ Executor not yet available')\n }\n }\n \n // Add the hook to the collection config\n collection.hooks.afterChange.push(automationHook)\n logger.info(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`)\n }\n }\n\n if (!config.jobs) {\n config.jobs = {tasks: []}\n }\n\n const configLogger = getConfigLogger()\n configLogger.info(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)\n\n // Generate cron tasks for workflows with cron triggers\n generateCronTasks(config)\n\n for (const step of pluginOptions.steps) {\n if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) {\n configLogger.debug(`Registering task: ${step.slug}`)\n config.jobs?.tasks?.push(step)\n } else {\n configLogger.debug(`Task ${step.slug} already registered, skipping`)\n }\n }\n\n // Initialize webhook endpoint\n initWebhookEndpoint(config, pluginOptions.webhookPrefix || 'webhook')\n\n // Set up onInit to register collection hooks and initialize features\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n configLogger.info(`onInit called - collections: ${Object.keys(payload.collections).length}`)\n \n // Execute any existing onInit functions first\n if (incomingOnInit) {\n configLogger.debug('Executing existing onInit function')\n await incomingOnInit(payload)\n }\n\n // Initialize the logger with the payload instance\n const logger = initializeLogger(payload)\n logger.info('Logger initialized with payload instance')\n\n // Log collection trigger configuration\n logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)\n\n // Create workflow executor instance\n console.log('🚨 CREATING WORKFLOW EXECUTOR INSTANCE')\n const executor = new WorkflowExecutor(payload, logger)\n console.log('🚨 EXECUTOR CREATED:', typeof executor)\n console.log('🚨 EXECUTOR METHODS:', Object.getOwnPropertyNames(Object.getPrototypeOf(executor)))\n \n // Register executor globally\n setWorkflowExecutor(executor)\n\n // Hooks are now registered during config phase - just log status\n logger.info('Hooks were registered during config phase - executor now available')\n \n logger.info('Initializing global hooks...')\n initGlobalHooks(payload, logger, executor)\n \n logger.info('Initializing workflow hooks...')\n initWorkflowHooks(payload, logger)\n \n logger.info('Initializing step tasks...')\n initStepTasks(pluginOptions, payload, logger)\n\n // Register cron jobs for workflows with cron triggers\n logger.info('Registering cron jobs...')\n await registerCronJobs(payload, logger)\n\n logger.info('Plugin initialized successfully - all hooks registered')\n }\n\n return config\n }\n"],"names":["createWorkflowCollection","WorkflowRunsCollection","WorkflowExecutor","generateCronTasks","registerCronJobs","initGlobalHooks","initStepTasks","initWebhookEndpoint","initWorkflowHooks","getConfigLogger","initializeLogger","getLogger","globalExecutor","setWorkflowExecutor","executor","console","log","getWorkflowExecutor","applyCollectionsConfig","pluginOptions","config","collections","push","workflowsPlugin","enabled","logger","info","collectionTriggers","triggerSlug","triggerConfig","Object","entries","collectionIndex","findIndex","c","slug","warn","collection","hooks","afterChange","automationHook","args","operation","doc","id","executeTriggeredWorkflows","previousDoc","req","error","length","jobs","tasks","configLogger","keys","step","steps","find","task","debug","webhookPrefix","incomingOnInit","onInit","payload","getOwnPropertyNames","getPrototypeOf"],"mappings":"AAIA,SAAQA,wBAAwB,QAAO,6BAA4B;AAC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AAOC,IAAI,CAAC,CAAC,sBAAsB,EAAEI,OAAOuB,IAAI,CAAClC,cAAcQ,kBAAkB,IAAI,CAAC,GAAGsB,MAAM,CAAC,sBAAsB,EAAE9B,cAAcoC,KAAK,EAAEN,UAAU,EAAE,MAAM,CAAC;YAEhK,oCAAoC;YACpClC,QAAQC,GAAG,CAAC;YACZ,MAAMF,WAAW,IAAIZ,iBAAiB4D,SAASrC;YAC/CV,QAAQC,GAAG,CAAC,wBAAwB,OAAOF;YAC3CC,QAAQC,GAAG,CAAC,wBAAwBc,OAAOiC,mBAAmB,CAACjC,OAAOkC,cAAc,CAAClD;YAErF,6BAA6B;YAC7BD,oBAAoBC;YAEpB,iEAAiE;YACjEW,OAAOC,IAAI,CAAC;YAEZD,OAAOC,IAAI,CAAC;YACZrB,gBAAgByD,SAASrC,QAAQX;YAEjCW,OAAOC,IAAI,CAAC;YACZlB,kBAAkBsD,SAASrC;YAE3BA,OAAOC,IAAI,CAAC;YACZpB,cAAca,eAAe2C,SAASrC;YAEtC,sDAAsD;YACtDA,OAAOC,IAAI,CAAC;YACZ,MAAMtB,iBAAiB0D,SAASrC;YAEhCA,OAAOC,IAAI,CAAC;QACd;QAEA,OAAON;IACT,EAAC"}
|
|
1
|
+
{"version":3,"sources":["../../src/plugin/index.ts"],"sourcesContent":["import type {Config} from 'payload'\n\nimport type {WorkflowsPluginConfig, CollectionTriggerConfigCrud} from \"./config-types.js\"\n\nimport {createWorkflowCollection} from '../collections/Workflow.js'\nimport {WorkflowRunsCollection} from '../collections/WorkflowRuns.js'\nimport {WorkflowExecutor} from '../core/workflow-executor.js'\nimport {generateCronTasks, registerCronJobs} from './cron-scheduler.js'\nimport {initCollectionHooks} from \"./init-collection-hooks.js\"\nimport {initGlobalHooks} from \"./init-global-hooks.js\"\nimport {initStepTasks} from \"./init-step-tasks.js\"\nimport {initWebhookEndpoint} from \"./init-webhook.js\"\nimport {initWorkflowHooks} from './init-workflow-hooks.js'\nimport {getConfigLogger, initializeLogger} from './logger.js'\n\nexport {getLogger} from './logger.js'\n\n// Global executor registry for config-phase hooks\nlet globalExecutor: WorkflowExecutor | null = null\n\nconst setWorkflowExecutor = (executor: WorkflowExecutor) => {\n console.log('🚨 SETTING GLOBAL EXECUTOR')\n globalExecutor = executor\n \n // Also set on global object as fallback\n if (typeof global !== 'undefined') {\n (global as any).__workflowExecutor = executor\n console.log('🚨 EXECUTOR ALSO SET ON GLOBAL OBJECT')\n }\n}\n\nconst getWorkflowExecutor = (): WorkflowExecutor | null => {\n return globalExecutor\n}\n\nconst applyCollectionsConfig = <T extends string>(pluginOptions: WorkflowsPluginConfig<T>, config: Config) => {\n // Add workflow collections\n if (!config.collections) {\n config.collections = []\n }\n\n config.collections.push(\n createWorkflowCollection(pluginOptions),\n WorkflowRunsCollection\n )\n}\n\n// Removed config-phase hook registration - user collections don't exist during config phase\n\n\nexport const workflowsPlugin =\n <TSlug extends string>(pluginOptions: WorkflowsPluginConfig<TSlug>) =>\n (config: Config): Config => {\n // If the plugin is disabled, return config unchanged\n if (pluginOptions.enabled === false) {\n return config\n }\n\n applyCollectionsConfig<TSlug>(pluginOptions, config)\n \n // CRITICAL: Modify existing collection configs BEFORE PayloadCMS processes them\n // This is the ONLY time we can add hooks that will actually work\n const logger = getConfigLogger()\n logger.info('Attempting to modify collection configs before PayloadCMS initialization...')\n \n if (config.collections && pluginOptions.collectionTriggers) {\n for (const [triggerSlug, triggerConfig] of Object.entries(pluginOptions.collectionTriggers)) {\n if (!triggerConfig) continue\n \n // Find the collection config that matches\n const collectionIndex = config.collections.findIndex(c => c.slug === triggerSlug)\n if (collectionIndex === -1) {\n logger.warn(`Collection '${triggerSlug}' not found in config.collections`)\n continue\n }\n \n const collection = config.collections[collectionIndex]\n logger.info(`Found collection '${triggerSlug}' - modifying its hooks...`)\n \n // Initialize hooks if needed\n if (!collection.hooks) {\n collection.hooks = {}\n }\n if (!collection.hooks.afterChange) {\n collection.hooks.afterChange = []\n }\n \n // Create a properly bound hook function that doesn't rely on closures\n // Use a simple function that PayloadCMS can definitely execute\n const automationHook = Object.assign(\n async function payloadAutomationHook(args: any) {\n try {\n // Use global console to ensure output\n global.console.log('🔥🔥🔥 AUTOMATION HOOK EXECUTED! 🔥🔥🔥')\n global.console.log('Collection:', args?.collection?.slug)\n global.console.log('Operation:', args?.operation)\n global.console.log('Doc ID:', args?.doc?.id)\n \n // Try multiple ways to get the executor\n let executor = null\n \n // Method 1: Global registry\n if (typeof getWorkflowExecutor === 'function') {\n executor = getWorkflowExecutor()\n }\n \n // Method 2: Global variable fallback\n if (!executor && typeof global !== 'undefined' && (global as any).__workflowExecutor) {\n executor = (global as any).__workflowExecutor\n global.console.log('Got executor from global variable')\n }\n \n if (executor) {\n global.console.log('✅ Executor found - executing workflows!')\n await executor.executeTriggeredWorkflows(\n args.collection.slug,\n args.operation,\n args.doc,\n args.previousDoc,\n args.req\n )\n global.console.log('✅ Workflow execution completed!')\n } else {\n global.console.log('⚠️ No executor available')\n }\n } catch (error) {\n global.console.error('❌ Hook execution error:', error)\n // Don't throw - just log\n }\n \n // Always return undefined to match other hooks\n return undefined\n },\n {\n // Add metadata to help debugging\n __isAutomationHook: true,\n __version: '0.0.21'\n }\n )\n \n // Add the hook to the collection config\n collection.hooks.afterChange.push(automationHook)\n logger.info(`Added automation hook to '${triggerSlug}' - hook count: ${collection.hooks.afterChange.length}`)\n }\n }\n\n if (!config.jobs) {\n config.jobs = {tasks: []}\n }\n\n const configLogger = getConfigLogger()\n configLogger.info(`Configuring workflow plugin with ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers`)\n\n // Generate cron tasks for workflows with cron triggers\n generateCronTasks(config)\n\n for (const step of pluginOptions.steps) {\n if (!config.jobs?.tasks?.find(task => task.slug === step.slug)) {\n configLogger.debug(`Registering task: ${step.slug}`)\n config.jobs?.tasks?.push(step)\n } else {\n configLogger.debug(`Task ${step.slug} already registered, skipping`)\n }\n }\n\n // Initialize webhook endpoint\n initWebhookEndpoint(config, pluginOptions.webhookPrefix || 'webhook')\n\n // Set up onInit to register collection hooks and initialize features\n const incomingOnInit = config.onInit\n config.onInit = async (payload) => {\n configLogger.info(`onInit called - collections: ${Object.keys(payload.collections).length}`)\n \n // Execute any existing onInit functions first\n if (incomingOnInit) {\n configLogger.debug('Executing existing onInit function')\n await incomingOnInit(payload)\n }\n\n // Initialize the logger with the payload instance\n const logger = initializeLogger(payload)\n logger.info('Logger initialized with payload instance')\n\n // Log collection trigger configuration\n logger.info(`Plugin configuration: ${Object.keys(pluginOptions.collectionTriggers || {}).length} collection triggers, ${pluginOptions.steps?.length || 0} steps`)\n\n // Create workflow executor instance\n console.log('🚨 CREATING WORKFLOW EXECUTOR INSTANCE')\n const executor = new WorkflowExecutor(payload, logger)\n console.log('🚨 EXECUTOR CREATED:', typeof executor)\n console.log('🚨 EXECUTOR METHODS:', Object.getOwnPropertyNames(Object.getPrototypeOf(executor)))\n \n // Register executor globally\n setWorkflowExecutor(executor)\n\n // Hooks are now registered during config phase - just log status\n logger.info('Hooks were registered during config phase - executor now available')\n \n logger.info('Initializing global hooks...')\n initGlobalHooks(payload, logger, executor)\n \n logger.info('Initializing workflow hooks...')\n initWorkflowHooks(payload, logger)\n \n logger.info('Initializing step tasks...')\n initStepTasks(pluginOptions, payload, logger)\n\n // Register cron jobs for workflows with cron triggers\n logger.info('Registering cron jobs...')\n await registerCronJobs(payload, logger)\n\n logger.info('Plugin initialized successfully - all hooks registered')\n }\n\n return config\n }\n"],"names":["createWorkflowCollection","WorkflowRunsCollection","WorkflowExecutor","generateCronTasks","registerCronJobs","initGlobalHooks","initStepTasks","initWebhookEndpoint","initWorkflowHooks","getConfigLogger","initializeLogger","getLogger","globalExecutor","setWorkflowExecutor","executor","console","log","global","__workflowExecutor","getWorkflowExecutor","applyCollectionsConfig","pluginOptions","config","collections","push","workflowsPlugin","enabled","logger","info","collectionTriggers","triggerSlug","triggerConfig","Object","entries","collectionIndex","findIndex","c","slug","warn","collection","hooks","afterChange","automationHook","assign","payloadAutomationHook","args","operation","doc","id","executeTriggeredWorkflows","previousDoc","req","error","undefined","__isAutomationHook","__version","length","jobs","tasks","configLogger","keys","step","steps","find","task","debug","webhookPrefix","incomingOnInit","onInit","payload","getOwnPropertyNames","getPrototypeOf"],"mappings":"AAIA,SAAQA,wBAAwB,QAAO,6BAA4B;AACnE,SAAQC,sBAAsB,QAAO,iCAAgC;AACrE,SAAQC,gBAAgB,QAAO,+BAA8B;AAC7D,SAAQC,iBAAiB,EAAEC,gBAAgB,QAAO,sBAAqB;AAEvE,SAAQC,eAAe,QAAO,yBAAwB;AACtD,SAAQC,aAAa,QAAO,uBAAsB;AAClD,SAAQC,mBAAmB,QAAO,oBAAmB;AACrD,SAAQC,iBAAiB,QAAO,2BAA0B;AAC1D,SAAQC,eAAe,EAAEC,gBAAgB,QAAO,cAAa;AAE7D,SAAQC,SAAS,QAAO,cAAa;AAErC,kDAAkD;AAClD,IAAIC,iBAA0C;AAE9C,MAAMC,sBAAsB,CAACC;IAC3BC,QAAQC,GAAG,CAAC;IACZJ,iBAAiBE;IAEjB,wCAAwC;IACxC,IAAI,OAAOG,WAAW,aAAa;QAChCA,OAAeC,kBAAkB,GAAGJ;QACrCC,QAAQC,GAAG,CAAC;IACd;AACF;AAEA,MAAMG,sBAAsB;IAC1B,OAAOP;AACT;AAEA,MAAMQ,yBAAyB,CAAmBC,eAAyCC;IACzF,2BAA2B;IAC3B,IAAI,CAACA,OAAOC,WAAW,EAAE;QACvBD,OAAOC,WAAW,GAAG,EAAE;IACzB;IAEAD,OAAOC,WAAW,CAACC,IAAI,CACrBxB,yBAAyBqB,gBACzBpB;AAEJ;AAEA,4FAA4F;AAG5F,OAAO,MAAMwB,kBACX,CAAuBJ,gBACrB,CAACC;QACC,qDAAqD;QACrD,IAAID,cAAcK,OAAO,KAAK,OAAO;YACnC,OAAOJ;QACT;QAEAF,uBAA8BC,eAAeC;QAE7C,gFAAgF;QAChF,iEAAiE;QACjE,MAAMK,SAASlB;QACfkB,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AAgBgE,SAAS1C,QAAQb;YAEjCa,OAAOC,IAAI,CAAC;YACZpB,kBAAkB6D,SAAS1C;YAE3BA,OAAOC,IAAI,CAAC;YACZtB,cAAce,eAAegD,SAAS1C;YAEtC,sDAAsD;YACtDA,OAAOC,IAAI,CAAC;YACZ,MAAMxB,iBAAiBiE,SAAS1C;YAEhCA,OAAOC,IAAI,CAAC;QACd;QAEA,OAAON;IACT,EAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@xtr-dev/payload-automation",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.22",
|
|
4
4
|
"description": "PayloadCMS Automation Plugin - Comprehensive workflow automation system with visual workflow building, execution tracking, and step types",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|