nvent 0.4.5 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/module.d.mts +1 -1
  2. package/dist/module.mjs +433 -180
  3. package/dist/runtime/adapters/base/index.d.ts +6 -0
  4. package/dist/runtime/adapters/base/index.js +1 -0
  5. package/dist/runtime/adapters/base/store-validator.d.ts +48 -0
  6. package/dist/runtime/adapters/base/store-validator.js +147 -0
  7. package/dist/runtime/adapters/builtin/file-queue.d.ts +15 -1
  8. package/dist/runtime/adapters/builtin/file-queue.js +70 -6
  9. package/dist/runtime/adapters/builtin/file-store.d.ts +4 -18
  10. package/dist/runtime/adapters/builtin/file-store.js +90 -109
  11. package/dist/runtime/adapters/builtin/memory-queue.js +4 -0
  12. package/dist/runtime/adapters/builtin/memory-store.d.ts +42 -31
  13. package/dist/runtime/adapters/builtin/memory-store.js +253 -183
  14. package/dist/runtime/adapters/factory.d.ts +2 -2
  15. package/dist/runtime/adapters/factory.js +54 -20
  16. package/dist/runtime/adapters/interfaces/store.d.ts +177 -113
  17. package/dist/runtime/config/index.d.ts +2 -2
  18. package/dist/runtime/config/index.js +14 -6
  19. package/dist/runtime/config/types.d.ts +32 -2
  20. package/dist/runtime/events/eventBus.d.ts +1 -1
  21. package/dist/runtime/events/types.d.ts +31 -2
  22. package/dist/runtime/events/utils/scheduleTrigger.d.ts +8 -0
  23. package/dist/runtime/events/utils/scheduleTrigger.js +69 -0
  24. package/dist/runtime/events/utils/stallDetector.d.ts +44 -3
  25. package/dist/runtime/events/utils/stallDetector.js +288 -89
  26. package/dist/runtime/events/utils/triggerRuntime.d.ts +58 -0
  27. package/dist/runtime/events/utils/triggerRuntime.js +212 -0
  28. package/dist/runtime/events/wiring/flowWiring.d.ts +11 -5
  29. package/dist/runtime/events/wiring/flowWiring.js +620 -92
  30. package/dist/runtime/events/wiring/registry.d.ts +2 -2
  31. package/dist/runtime/events/wiring/registry.js +8 -6
  32. package/dist/runtime/events/wiring/streamWiring.d.ts +15 -11
  33. package/dist/runtime/events/wiring/streamWiring.js +88 -11
  34. package/dist/runtime/events/wiring/triggerWiring.d.ts +21 -0
  35. package/dist/runtime/events/wiring/triggerWiring.js +412 -0
  36. package/dist/runtime/{server → nitro}/plugins/00.adapters.js +8 -4
  37. package/dist/runtime/{server → nitro}/plugins/02.workers.js +21 -3
  38. package/dist/runtime/nitro/plugins/03.triggers.d.ts +12 -0
  39. package/dist/runtime/nitro/plugins/03.triggers.js +55 -0
  40. package/dist/runtime/nitro/routes/webhook.await.d.ts +23 -0
  41. package/dist/runtime/nitro/routes/webhook.await.js +90 -0
  42. package/dist/runtime/nitro/routes/webhook.trigger.d.ts +69 -0
  43. package/dist/runtime/nitro/routes/webhook.trigger.js +64 -0
  44. package/dist/runtime/{utils → nitro/utils}/adapters.d.ts +6 -6
  45. package/dist/runtime/nitro/utils/awaitPatterns/event.d.ts +15 -0
  46. package/dist/runtime/nitro/utils/awaitPatterns/event.js +120 -0
  47. package/dist/runtime/nitro/utils/awaitPatterns/index.d.ts +28 -0
  48. package/dist/runtime/nitro/utils/awaitPatterns/index.js +55 -0
  49. package/dist/runtime/nitro/utils/awaitPatterns/schedule.d.ts +16 -0
  50. package/dist/runtime/nitro/utils/awaitPatterns/schedule.js +78 -0
  51. package/dist/runtime/nitro/utils/awaitPatterns/time.d.ts +15 -0
  52. package/dist/runtime/nitro/utils/awaitPatterns/time.js +67 -0
  53. package/dist/runtime/nitro/utils/awaitPatterns/webhook.d.ts +15 -0
  54. package/dist/runtime/nitro/utils/awaitPatterns/webhook.js +120 -0
  55. package/dist/runtime/{utils → nitro/utils}/defineFunction.d.ts +2 -2
  56. package/dist/runtime/{utils → nitro/utils}/defineFunction.js +3 -3
  57. package/dist/runtime/{utils → nitro/utils}/defineFunctionConfig.d.ts +156 -0
  58. package/dist/runtime/{utils → nitro/utils}/defineFunctionConfig.js +1 -0
  59. package/dist/runtime/nitro/utils/defineHooks.d.ts +41 -0
  60. package/dist/runtime/nitro/utils/defineHooks.js +6 -0
  61. package/dist/runtime/{utils → nitro/utils}/registerAdapter.d.ts +3 -3
  62. package/dist/runtime/{utils → nitro/utils}/registerAdapter.js +1 -1
  63. package/dist/runtime/nitro/utils/useAwait.d.ts +71 -0
  64. package/dist/runtime/nitro/utils/useAwait.js +139 -0
  65. package/dist/runtime/{utils → nitro/utils}/useEventManager.d.ts +2 -2
  66. package/dist/runtime/{utils → nitro/utils}/useEventManager.js +1 -1
  67. package/dist/runtime/nitro/utils/useFlow.d.ts +68 -0
  68. package/dist/runtime/nitro/utils/useFlow.js +226 -0
  69. package/dist/runtime/nitro/utils/useHookRegistry.d.ts +34 -0
  70. package/dist/runtime/nitro/utils/useHookRegistry.js +25 -0
  71. package/dist/runtime/nitro/utils/useRunContext.d.ts +6 -0
  72. package/dist/runtime/nitro/utils/useRunContext.js +102 -0
  73. package/dist/runtime/nitro/utils/useStreamTopics.d.ts +83 -0
  74. package/dist/runtime/nitro/utils/useStreamTopics.js +94 -0
  75. package/dist/runtime/nitro/utils/useTrigger.d.ts +150 -0
  76. package/dist/runtime/nitro/utils/useTrigger.js +320 -0
  77. package/dist/runtime/scheduler/index.d.ts +33 -0
  78. package/dist/runtime/scheduler/index.js +38 -0
  79. package/dist/runtime/scheduler/scheduler.d.ts +113 -0
  80. package/dist/runtime/scheduler/scheduler.js +623 -0
  81. package/dist/runtime/scheduler/types.d.ts +116 -0
  82. package/dist/runtime/scheduler/types.js +0 -0
  83. package/dist/runtime/worker/node/runner.d.ts +12 -2
  84. package/dist/runtime/worker/node/runner.js +141 -37
  85. package/package.json +6 -6
  86. package/dist/runtime/server/api/_flows/[name]/clear-history.delete.d.ts +0 -10
  87. package/dist/runtime/server/api/_flows/[name]/clear-history.delete.js +0 -55
  88. package/dist/runtime/server/api/_flows/[name]/runs/[runId]/cancel.post.d.ts +0 -2
  89. package/dist/runtime/server/api/_flows/[name]/runs/[runId]/cancel.post.js +0 -21
  90. package/dist/runtime/server/api/_flows/[name]/runs.get.d.ts +0 -17
  91. package/dist/runtime/server/api/_flows/[name]/runs.get.js +0 -64
  92. package/dist/runtime/server/api/_flows/[name]/schedule.post.d.ts +0 -2
  93. package/dist/runtime/server/api/_flows/[name]/schedule.post.js +0 -66
  94. package/dist/runtime/server/api/_flows/[name]/schedules/[id].delete.d.ts +0 -2
  95. package/dist/runtime/server/api/_flows/[name]/schedules/[id].delete.js +0 -47
  96. package/dist/runtime/server/api/_flows/[name]/schedules.get.d.ts +0 -2
  97. package/dist/runtime/server/api/_flows/[name]/schedules.get.js +0 -50
  98. package/dist/runtime/server/api/_flows/[name]/start.post.d.ts +0 -2
  99. package/dist/runtime/server/api/_flows/[name]/start.post.js +0 -9
  100. package/dist/runtime/server/api/_flows/index.get.d.ts +0 -6
  101. package/dist/runtime/server/api/_flows/index.get.js +0 -5
  102. package/dist/runtime/server/api/_flows/ws.d.ts +0 -60
  103. package/dist/runtime/server/api/_flows/ws.js +0 -209
  104. package/dist/runtime/server/api/_queues/[name]/job/[id].get.d.ts +0 -2
  105. package/dist/runtime/server/api/_queues/[name]/job/[id].get.js +0 -14
  106. package/dist/runtime/server/api/_queues/[name]/job/index.get.d.ts +0 -2
  107. package/dist/runtime/server/api/_queues/[name]/job/index.get.js +0 -27
  108. package/dist/runtime/server/api/_queues/index.get.d.ts +0 -2
  109. package/dist/runtime/server/api/_queues/index.get.js +0 -106
  110. package/dist/runtime/server/api/_queues/ws.d.ts +0 -48
  111. package/dist/runtime/server/api/_queues/ws.js +0 -215
  112. package/dist/runtime/utils/useFlowEngine.d.ts +0 -19
  113. package/dist/runtime/utils/useFlowEngine.js +0 -108
  114. package/dist/runtime/utils/useStreamTopics.d.ts +0 -72
  115. package/dist/runtime/utils/useStreamTopics.js +0 -47
  116. /package/dist/runtime/{server → nitro}/plugins/00.adapters.d.ts +0 -0
  117. /package/dist/runtime/{server → nitro}/plugins/01.ws-lifecycle.d.ts +0 -0
  118. /package/dist/runtime/{server → nitro}/plugins/01.ws-lifecycle.js +0 -0
  119. /package/dist/runtime/{server → nitro}/plugins/02.workers.d.ts +0 -0
  120. /package/dist/runtime/{utils → nitro/utils}/adapters.js +0 -0
  121. /package/dist/runtime/{utils → nitro/utils}/useNventLogger.d.ts +0 -0
  122. /package/dist/runtime/{utils → nitro/utils}/useNventLogger.js +0 -0
  123. /package/dist/runtime/{utils → nitro/utils}/wsPeerManager.d.ts +0 -0
  124. /package/dist/runtime/{utils → nitro/utils}/wsPeerManager.js +0 -0
@@ -0,0 +1,83 @@
1
+ export declare function useStreamTopics(): {
2
+ StoreSubjects: {
3
+ /**
4
+ * Flow run event stream
5
+ * Pattern: {prefix}:flow:run:{runId}
6
+ * Type: Redis Stream (XADD/XRANGE)
7
+ * Contains: All events for a specific flow run
8
+ */
9
+ readonly flowRun: (runId: string) => string;
10
+ /**
11
+ * Flow runs index (sorted set)
12
+ * Pattern: {prefix}:flow:runs:{flowName}
13
+ * Type: Sorted Set + Hash metadata
14
+ * Contains: List of run IDs for a flow, sorted by timestamp
15
+ */
16
+ readonly flowRunIndex: (flowName: string) => string;
17
+ /**
18
+ * Flows index (sorted set)
19
+ * Pattern: {prefix}:flows
20
+ * Type: Sorted Set + Hash metadata
21
+ * Contains: Flow metadata and statistics
22
+ */
23
+ readonly flowIndex: () => string;
24
+ /**
25
+ * Trigger event stream
26
+ * Pattern: {prefix}:trigger:event:{triggerName}
27
+ * Type: Redis Stream (XADD/XRANGE)
28
+ * Contains: All events for a specific trigger
29
+ */
30
+ readonly triggerStream: (triggerName: string) => string;
31
+ /**
32
+ * Triggers index (sorted set)
33
+ * Pattern: {prefix}:triggers
34
+ * Type: Sorted Set + Hash metadata
35
+ * Contains: Trigger metadata, subscriptions, and statistics
36
+ */
37
+ readonly triggerIndex: () => string;
38
+ /**
39
+ * Scheduler job index
40
+ * Pattern: {prefix}:scheduler:jobs
41
+ * Type: Sorted Set + Hash metadata
42
+ * Contains: Scheduled job metadata
43
+ */
44
+ readonly schedulerJobs: () => string;
45
+ /**
46
+ * Scheduler lock index
47
+ * Pattern: {prefix}:scheduler:locks
48
+ * Type: Sorted Set + Hash metadata
49
+ * Contains: Distributed scheduler lock metadata
50
+ */
51
+ readonly schedulerLocks: () => string;
52
+ };
53
+ StreamTopics: {
54
+ /**
55
+ * Flow events for a specific run
56
+ * Pattern: {prefix}:stream:flow:events:{runId}
57
+ * Published: When flow events occur (StreamWiring)
58
+ * Subscribed: By WebSocket clients watching a specific flow run
59
+ */
60
+ readonly flowEvents: (runId: string) => string;
61
+ /**
62
+ * Flow statistics updates
63
+ * Pattern: {prefix}:stream:flow:stats
64
+ * Published: When flow stats change (StreamWiring)
65
+ * Subscribed: By WebSocket clients watching flow overview
66
+ */
67
+ readonly flowStats: () => string;
68
+ /**
69
+ * Trigger events for a specific trigger
70
+ * Pattern: {prefix}:stream:trigger:events:{triggerName}
71
+ * Published: When trigger events occur (StreamWiring)
72
+ * Subscribed: By WebSocket clients watching a specific trigger
73
+ */
74
+ readonly triggerEvents: (triggerName: string) => string;
75
+ /**
76
+ * Trigger statistics updates
77
+ * Pattern: {prefix}:stream:trigger:stats
78
+ * Published: When trigger stats change (StreamWiring)
79
+ * Subscribed: By WebSocket clients watching trigger overview
80
+ */
81
+ readonly triggerStats: () => string;
82
+ };
83
+ };
@@ -0,0 +1,94 @@
1
+ import { useRuntimeConfig } from "#imports";
2
+ function getStoreSubjects(prefix) {
3
+ return {
4
+ /**
5
+ * Flow run event stream
6
+ * Pattern: {prefix}:flow:run:{runId}
7
+ * Type: Redis Stream (XADD/XRANGE)
8
+ * Contains: All events for a specific flow run
9
+ */
10
+ flowRun: (runId) => `${prefix}:flow:run:${runId}`,
11
+ /**
12
+ * Flow runs index (sorted set)
13
+ * Pattern: {prefix}:flow:runs:{flowName}
14
+ * Type: Sorted Set + Hash metadata
15
+ * Contains: List of run IDs for a flow, sorted by timestamp
16
+ */
17
+ flowRunIndex: (flowName) => `${prefix}:flow:runs:${flowName}`,
18
+ /**
19
+ * Flows index (sorted set)
20
+ * Pattern: {prefix}:flows
21
+ * Type: Sorted Set + Hash metadata
22
+ * Contains: Flow metadata and statistics
23
+ */
24
+ flowIndex: () => `${prefix}:flows`,
25
+ /**
26
+ * Trigger event stream
27
+ * Pattern: {prefix}:trigger:event:{triggerName}
28
+ * Type: Redis Stream (XADD/XRANGE)
29
+ * Contains: All events for a specific trigger
30
+ */
31
+ triggerStream: (triggerName) => `${prefix}:trigger:event:${triggerName}`,
32
+ /**
33
+ * Triggers index (sorted set)
34
+ * Pattern: {prefix}:triggers
35
+ * Type: Sorted Set + Hash metadata
36
+ * Contains: Trigger metadata, subscriptions, and statistics
37
+ */
38
+ triggerIndex: () => `${prefix}:triggers`,
39
+ /**
40
+ * Scheduler job index
41
+ * Pattern: {prefix}:scheduler:jobs
42
+ * Type: Sorted Set + Hash metadata
43
+ * Contains: Scheduled job metadata
44
+ */
45
+ schedulerJobs: () => `${prefix}:scheduler:jobs`,
46
+ /**
47
+ * Scheduler lock index
48
+ * Pattern: {prefix}:scheduler:locks
49
+ * Type: Sorted Set + Hash metadata
50
+ * Contains: Distributed scheduler lock metadata
51
+ */
52
+ schedulerLocks: () => `${prefix}:scheduler:locks`
53
+ };
54
+ }
55
+ function getStreamTopics(prefix) {
56
+ return {
57
+ /**
58
+ * Flow events for a specific run
59
+ * Pattern: {prefix}:stream:flow:events:{runId}
60
+ * Published: When flow events occur (StreamWiring)
61
+ * Subscribed: By WebSocket clients watching a specific flow run
62
+ */
63
+ flowEvents: (runId) => `${prefix}:stream:flow:events:${runId}`,
64
+ /**
65
+ * Flow statistics updates
66
+ * Pattern: {prefix}:stream:flow:stats
67
+ * Published: When flow stats change (StreamWiring)
68
+ * Subscribed: By WebSocket clients watching flow overview
69
+ */
70
+ flowStats: () => `${prefix}:stream:flow:stats`,
71
+ /**
72
+ * Trigger events for a specific trigger
73
+ * Pattern: {prefix}:stream:trigger:events:{triggerName}
74
+ * Published: When trigger events occur (StreamWiring)
75
+ * Subscribed: By WebSocket clients watching a specific trigger
76
+ */
77
+ triggerEvents: (triggerName) => `${prefix}:stream:trigger:events:${triggerName}`,
78
+ /**
79
+ * Trigger statistics updates
80
+ * Pattern: {prefix}:stream:trigger:stats
81
+ * Published: When trigger stats change (StreamWiring)
82
+ * Subscribed: By WebSocket clients watching trigger overview
83
+ */
84
+ triggerStats: () => `${prefix}:stream:trigger:stats`
85
+ };
86
+ }
87
+ export function useStreamTopics() {
88
+ const config = useRuntimeConfig();
89
+ const prefix = config.nvent.store?.prefix || "nvent";
90
+ return {
91
+ StoreSubjects: getStoreSubjects(prefix),
92
+ StreamTopics: getStreamTopics(prefix)
93
+ };
94
+ }
@@ -0,0 +1,150 @@
1
+ import type { TriggerEntry, TriggerSubscription } from '../../../registry/types.js';
2
+ /**
3
+ * Public export for resolving payload references
4
+ * Allows external code to resolve references if needed
5
+ */
6
+ export declare function resolvePayload(data: any): Promise<any>;
7
+ export interface RegisterTriggerOptions {
8
+ name: string;
9
+ type: 'event' | 'webhook' | 'schedule' | 'manual';
10
+ scope: 'flow' | 'run';
11
+ status?: 'active' | 'inactive' | 'retired';
12
+ displayName?: string;
13
+ description?: string;
14
+ source?: string;
15
+ expectedSubscribers?: string[];
16
+ webhook?: {
17
+ path: string;
18
+ method?: string;
19
+ auth?: any;
20
+ };
21
+ schedule?: {
22
+ cron: string;
23
+ timezone?: string;
24
+ enabled?: boolean;
25
+ };
26
+ schema?: any;
27
+ transform?: (data: any) => any;
28
+ config?: {
29
+ persistData?: boolean;
30
+ payloadThreshold?: number;
31
+ retentionDays?: number;
32
+ rateLimit?: {
33
+ max: number;
34
+ window: number;
35
+ };
36
+ };
37
+ }
38
+ export interface SubscribeTriggerOptions {
39
+ trigger: string;
40
+ flow: string;
41
+ mode?: 'auto' | 'manual';
42
+ filter?: (data: any) => boolean;
43
+ transform?: (data: any) => any;
44
+ }
45
+ /**
46
+ * Core trigger composable
47
+ * Provides runtime API for trigger registration and emission
48
+ */
49
+ export declare function useTrigger(): {
50
+ /**
51
+ * Register a trigger (programmatic)
52
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
53
+ */
54
+ registerTrigger(opts: RegisterTriggerOptions): Promise<void>;
55
+ /**
56
+ * Subscribe flow to trigger (programmatic)
57
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
58
+ */
59
+ subscribeTrigger(opts: SubscribeTriggerOptions): Promise<void>;
60
+ /**
61
+ * Unsubscribe flow from trigger
62
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
63
+ */
64
+ unsubscribeTrigger(trigger: string, flow: string): Promise<void>;
65
+ /**
66
+ * Emit trigger (fire event)
67
+ * Publishes event to bus - triggerWiring handles persistence, stats, and orchestration
68
+ *
69
+ * Large payloads are automatically stored in KV store and replaced with references
70
+ * to keep stream events small and memory-efficient.
71
+ */
72
+ emitTrigger(name: string, data: any, opts?: {
73
+ payloadThreshold?: number;
74
+ }): Promise<void>;
75
+ /**
76
+ * Query methods
77
+ */
78
+ /**
79
+ * Check if a trigger exists in the registry
80
+ */
81
+ hasTrigger(name: string): boolean;
82
+ /**
83
+ * Get trigger entry by name
84
+ */
85
+ getTrigger(name: string): TriggerEntry | undefined;
86
+ /**
87
+ * Get all registered triggers
88
+ * @param options - Sorting and pagination options
89
+ * @param options.sortBy - Field to sort by
90
+ * @param options.order - Sort order (asc or desc)
91
+ * @param options.limit - Maximum number of results
92
+ * @param options.offset - Number of results to skip
93
+ */
94
+ getAllTriggers(options?: {
95
+ sortBy?: "registeredAt" | "lastActivityAt" | "name";
96
+ order?: "asc" | "desc";
97
+ limit?: number;
98
+ offset?: number;
99
+ }): TriggerEntry[];
100
+ /**
101
+ * Get all flows subscribed to a specific trigger
102
+ */
103
+ getSubscribedFlows(trigger: string): string[];
104
+ /**
105
+ * Get all triggers that a flow is subscribed to
106
+ */
107
+ getFlowTriggers(flow: string): string[];
108
+ /**
109
+ * Get subscription details for a specific trigger-flow pair
110
+ */
111
+ getSubscription(trigger: string, flow: string): TriggerSubscription | undefined;
112
+ getAllSubscriptions(): TriggerSubscription[];
113
+ /**
114
+ * Initialize runtime from store (called on startup)
115
+ * Uses index + stream architecture (v0.5.1)
116
+ */
117
+ initialize(): Promise<void>;
118
+ /**
119
+ * Get runtime state (for debugging)
120
+ */
121
+ getRuntime(): {
122
+ triggerCount: number;
123
+ subscriptionCount: number;
124
+ flowCount: number;
125
+ initialized: boolean;
126
+ };
127
+ /**
128
+ * Delete a trigger completely (removes all data)
129
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
130
+ */
131
+ deleteTrigger(name: string): Promise<void>;
132
+ /**
133
+ * Update trigger status (active/inactive/retired)
134
+ * For future status management UI
135
+ */
136
+ updateTriggerStatus(name: string, status: "active" | "inactive" | "retired"): Promise<void>;
137
+ /**
138
+ * Get trigger statistics
139
+ * v0.5.1: New analytics method
140
+ */
141
+ getTriggerStats(name: string): Promise<any>;
142
+ /**
143
+ * Get trigger history from stream
144
+ * v0.5.1: New analytics method
145
+ */
146
+ getTriggerHistory(name: string, opts?: {
147
+ limit?: number;
148
+ types?: string[];
149
+ }): Promise<any>;
150
+ };
@@ -0,0 +1,320 @@
1
+ import { useStoreAdapter, useNventLogger, useStreamTopics } from "#imports";
2
+ import { getEventBus } from "../../events/eventBus.js";
3
+ import { getTriggerRuntime } from "../../events/utils/triggerRuntime.js";
4
+ export async function resolvePayload(data) {
5
+ const logger = useNventLogger("trigger");
6
+ const store = useStoreAdapter();
7
+ const runtime = getTriggerRuntime(store, logger);
8
+ return runtime.resolvePayload(data);
9
+ }
10
+ export function useTrigger() {
11
+ const logger = useNventLogger("trigger");
12
+ const store = useStoreAdapter();
13
+ const runtime = getTriggerRuntime(store, logger);
14
+ return {
15
+ /**
16
+ * Register a trigger (programmatic)
17
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
18
+ */
19
+ async registerTrigger(opts) {
20
+ const eventBus = getEventBus();
21
+ const existing = runtime.getTrigger(opts.name);
22
+ const isUpdate = !!existing;
23
+ if (isUpdate) {
24
+ logger.info(`Updating trigger: ${opts.name}`);
25
+ await eventBus.publish({
26
+ type: "trigger.updated",
27
+ triggerName: opts.name,
28
+ data: {
29
+ type: opts.type,
30
+ scope: opts.scope,
31
+ status: opts.status,
32
+ displayName: opts.displayName,
33
+ description: opts.description,
34
+ source: opts.source || "programmatic",
35
+ webhook: opts.webhook,
36
+ schedule: opts.schedule,
37
+ config: opts.config,
38
+ expectedSubscribers: opts.expectedSubscribers
39
+ }
40
+ });
41
+ } else {
42
+ logger.info(`Registering trigger: ${opts.name}`);
43
+ await eventBus.publish({
44
+ type: "trigger.registered",
45
+ triggerName: opts.name,
46
+ data: {
47
+ name: opts.name,
48
+ type: opts.type,
49
+ scope: opts.scope,
50
+ displayName: opts.displayName,
51
+ description: opts.description,
52
+ source: opts.source || "programmatic",
53
+ expectedSubscribers: opts.expectedSubscribers,
54
+ webhook: opts.webhook,
55
+ schedule: opts.schedule,
56
+ config: opts.config
57
+ }
58
+ });
59
+ }
60
+ },
61
+ /**
62
+ * Subscribe flow to trigger (programmatic)
63
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
64
+ */
65
+ async subscribeTrigger(opts) {
66
+ const eventBus = getEventBus();
67
+ const { trigger, flow, mode = "auto" } = opts;
68
+ const existingSub = runtime.getSubscription(trigger, flow);
69
+ const isUpdate = !!existingSub;
70
+ logger.info(`${isUpdate ? "Updating" : "Subscribing"} flow '${flow}' to trigger '${trigger}' (${mode})`);
71
+ await eventBus.publish({
72
+ type: "subscription.added",
73
+ triggerName: trigger,
74
+ data: {
75
+ trigger,
76
+ flow,
77
+ mode,
78
+ isUpdate
79
+ }
80
+ });
81
+ },
82
+ /**
83
+ * Unsubscribe flow from trigger
84
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
85
+ */
86
+ async unsubscribeTrigger(trigger, flow) {
87
+ const eventBus = getEventBus();
88
+ logger.info(`Unsubscribing flow '${flow}' from trigger '${trigger}'`);
89
+ await eventBus.publish({
90
+ type: "subscription.removed",
91
+ triggerName: trigger,
92
+ data: {
93
+ trigger,
94
+ flow
95
+ }
96
+ });
97
+ },
98
+ /**
99
+ * Emit trigger (fire event)
100
+ * Publishes event to bus - triggerWiring handles persistence, stats, and orchestration
101
+ *
102
+ * Large payloads are automatically stored in KV store and replaced with references
103
+ * to keep stream events small and memory-efficient.
104
+ */
105
+ async emitTrigger(name, data, opts) {
106
+ const eventBus = getEventBus();
107
+ const trigger = runtime.getTrigger(name);
108
+ if (!trigger) {
109
+ logger.warn(
110
+ `Emitting unregistered trigger '${name}'. Consider registering it first with registerTrigger().`
111
+ );
112
+ }
113
+ const threshold = opts?.payloadThreshold || trigger?.config?.payloadThreshold || 10 * 1024;
114
+ const eventData = await runtime.handleLargePayload(name, data, threshold);
115
+ logger.debug(`Emitting trigger: ${name}`, {
116
+ hasReference: !!eventData.__payloadRef,
117
+ size: eventData.__size
118
+ });
119
+ await eventBus.publish({
120
+ type: "trigger.fired",
121
+ triggerName: name,
122
+ data: eventData
123
+ });
124
+ },
125
+ /**
126
+ * Query methods
127
+ */
128
+ /**
129
+ * Check if a trigger exists in the registry
130
+ */
131
+ hasTrigger(name) {
132
+ return runtime.hasTrigger(name);
133
+ },
134
+ /**
135
+ * Get trigger entry by name
136
+ */
137
+ getTrigger(name) {
138
+ return runtime.getTrigger(name);
139
+ },
140
+ /**
141
+ * Get all registered triggers
142
+ * @param options - Sorting and pagination options
143
+ * @param options.sortBy - Field to sort by
144
+ * @param options.order - Sort order (asc or desc)
145
+ * @param options.limit - Maximum number of results
146
+ * @param options.offset - Number of results to skip
147
+ */
148
+ getAllTriggers(options) {
149
+ return runtime.getAllTriggers(options);
150
+ },
151
+ /**
152
+ * Get all flows subscribed to a specific trigger
153
+ */
154
+ getSubscribedFlows(trigger) {
155
+ return runtime.getSubscribedFlows(trigger);
156
+ },
157
+ /**
158
+ * Get all triggers that a flow is subscribed to
159
+ */
160
+ getFlowTriggers(flow) {
161
+ return runtime.getFlowTriggers(flow);
162
+ },
163
+ /**
164
+ * Get subscription details for a specific trigger-flow pair
165
+ */
166
+ getSubscription(trigger, flow) {
167
+ return runtime.getSubscription(trigger, flow);
168
+ },
169
+ getAllSubscriptions() {
170
+ return runtime.getAllSubscriptions();
171
+ },
172
+ /**
173
+ * Initialize runtime from store (called on startup)
174
+ * Uses index + stream architecture (v0.5.1)
175
+ */
176
+ async initialize() {
177
+ if (runtime.initialized) return;
178
+ const { StoreSubjects } = useStreamTopics();
179
+ const indexKey = StoreSubjects.triggerIndex();
180
+ logger.info("Initializing trigger runtime from index...");
181
+ if (store.index.read) {
182
+ const entries = await store.index.read(indexKey, { limit: 1e3 });
183
+ let activeCount = 0;
184
+ let totalSubscriptions = 0;
185
+ for (const entry of entries) {
186
+ const metadata = entry.metadata;
187
+ const triggerEntry = {
188
+ name: metadata.name,
189
+ type: metadata.type,
190
+ scope: metadata.scope,
191
+ status: metadata.status || "active",
192
+ displayName: metadata.displayName,
193
+ description: metadata.description,
194
+ source: metadata.source,
195
+ registeredAt: metadata.registeredAt,
196
+ registeredBy: metadata.registeredBy,
197
+ lastActivityAt: metadata.lastActivityAt,
198
+ subscriptions: metadata.subscriptions || {},
199
+ stats: metadata.stats || { totalFires: 0, activeSubscribers: 0 },
200
+ webhook: metadata.webhook,
201
+ schedule: metadata.schedule,
202
+ config: metadata.config,
203
+ version: metadata.version || 1
204
+ };
205
+ runtime.addTrigger(entry.id, triggerEntry);
206
+ if (metadata.status === "active") {
207
+ activeCount++;
208
+ }
209
+ if (metadata.subscriptions) {
210
+ for (const [flowName, subData] of Object.entries(metadata.subscriptions)) {
211
+ const subscription = {
212
+ triggerName: entry.id,
213
+ flowName,
214
+ mode: subData.mode || "auto",
215
+ source: "programmatic",
216
+ registeredAt: subData.subscribedAt
217
+ };
218
+ runtime.addSubscription(entry.id, flowName, subscription);
219
+ totalSubscriptions++;
220
+ }
221
+ }
222
+ }
223
+ logger.info(
224
+ `Loaded ${activeCount} active triggers with ${totalSubscriptions} subscriptions from index`
225
+ );
226
+ } else {
227
+ logger.warn("Store does not support indexRead, falling back to doc-based loading");
228
+ if (store.list) {
229
+ const triggers = await store.list("triggers");
230
+ for (const { id, doc } of triggers) {
231
+ runtime.addTrigger(id, doc);
232
+ }
233
+ const subscriptions = await store.list("trigger-subscriptions");
234
+ for (const { doc } of subscriptions) {
235
+ const sub = doc;
236
+ runtime.addSubscription(sub.triggerName, sub.flowName, sub);
237
+ }
238
+ logger.info(
239
+ `Loaded ${triggers.length} triggers and ${subscriptions.length} subscriptions from doc store (legacy)`
240
+ );
241
+ }
242
+ }
243
+ runtime.setInitialized(true);
244
+ },
245
+ /**
246
+ * Get runtime state (for debugging)
247
+ */
248
+ getRuntime() {
249
+ return runtime.getRuntimeStats();
250
+ },
251
+ /**
252
+ * Delete a trigger completely (removes all data)
253
+ * Publishes event to bus - triggerWiring handles persistence and orchestration
254
+ */
255
+ async deleteTrigger(name) {
256
+ const eventBus = getEventBus();
257
+ const trigger = runtime.getTrigger(name);
258
+ if (!trigger) {
259
+ logger.warn(`Cannot delete non-existent trigger: ${name}`);
260
+ return;
261
+ }
262
+ logger.info(`Deleting trigger: ${name}`);
263
+ await eventBus.publish({
264
+ type: "trigger.deleted",
265
+ triggerName: name,
266
+ data: {}
267
+ });
268
+ },
269
+ /**
270
+ * Update trigger status (active/inactive/retired)
271
+ * For future status management UI
272
+ */
273
+ async updateTriggerStatus(name, status) {
274
+ const eventBus = getEventBus();
275
+ const trigger = runtime.getTrigger(name);
276
+ if (!trigger) {
277
+ logger.warn(`Cannot update status of non-existent trigger: ${name}`);
278
+ return;
279
+ }
280
+ logger.info(`Updating trigger ${name} status to: ${status}`);
281
+ await eventBus.publish({
282
+ type: "trigger.updated",
283
+ triggerName: name,
284
+ data: {
285
+ ...trigger,
286
+ status
287
+ }
288
+ });
289
+ },
290
+ /**
291
+ * Get trigger statistics
292
+ * v0.5.1: New analytics method
293
+ */
294
+ async getTriggerStats(name) {
295
+ const { StoreSubjects } = useStreamTopics();
296
+ const indexKey = StoreSubjects.triggerIndex();
297
+ if (!store.index.get) {
298
+ const trigger = runtime.getTrigger(name);
299
+ return trigger?.stats;
300
+ }
301
+ const entry = await store.index.get(indexKey, name);
302
+ if (!entry?.metadata) return null;
303
+ return entry.metadata.stats;
304
+ },
305
+ /**
306
+ * Get trigger history from stream
307
+ * v0.5.1: New analytics method
308
+ */
309
+ async getTriggerHistory(name, opts) {
310
+ const { StoreSubjects } = useStreamTopics();
311
+ const streamName = StoreSubjects.triggerStream(name);
312
+ const events = await store.stream.read(streamName, {
313
+ limit: opts?.limit || 100,
314
+ types: opts?.types,
315
+ order: "desc"
316
+ });
317
+ return events;
318
+ }
319
+ };
320
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Scheduler Factory and Composable
3
+ *
4
+ * Provides a unified scheduler interface for the entire application.
5
+ * Uses Scheduler with store adapter (supports both distributed and single-instance modes).
6
+ */
7
+ import type { SchedulerAdapter } from './types.js';
8
+ /**
9
+ * Create a scheduler instance
10
+ * Uses Scheduler which adapts based on store capabilities:
11
+ * - With indexAdd/indexGet: Full distributed locking
12
+ * - Without: Degrades gracefully to KV-based locking (single instance)
13
+ */
14
+ export declare function createScheduler(store: any): SchedulerAdapter;
15
+ /**
16
+ * Get the global scheduler instance
17
+ * Must be initialized first with initializeScheduler()
18
+ */
19
+ export declare function useScheduler(): SchedulerAdapter;
20
+ /**
21
+ * Initialize the scheduler
22
+ * Should be called once during app startup
23
+ */
24
+ export declare function initializeScheduler(store: any): Promise<SchedulerAdapter>;
25
+ /**
26
+ * Shutdown the scheduler
27
+ * Should be called during app shutdown
28
+ */
29
+ export declare function shutdownScheduler(): Promise<void>;
30
+ /**
31
+ * Reset the scheduler instance (for testing)
32
+ */
33
+ export declare function resetScheduler(): void;