@motiadev/core 0.8.2-beta.140-306759 → 0.8.2-beta.140-131607

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.
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createQueueSchema = exports.createInfrastructureSchema = exports.infrastructureSchema = exports.queueSchema = exports.handlerSchema = exports.handlerBaseSchema = exports.AWS_LAMBDA_CPU_RATIO = exports.AWS_LAMBDA_LIMITS = void 0;
4
+ exports.getProportionalCpu = getProportionalCpu;
5
+ const zod_1 = require("zod");
6
+ exports.AWS_LAMBDA_LIMITS = {
7
+ MIN_RAM_MB: 128,
8
+ MAX_RAM_MB: 10240,
9
+ MIN_TIMEOUT_SECONDS: 1,
10
+ MAX_TIMEOUT_SECONDS: 900,
11
+ };
12
+ exports.AWS_LAMBDA_CPU_RATIO = {
13
+ 128: 0.0625,
14
+ 256: 0.125,
15
+ 512: 0.25,
16
+ 1024: 0.5,
17
+ 1536: 0.75,
18
+ 2048: 1,
19
+ 3008: 1.5,
20
+ 4096: 2,
21
+ 5120: 2.5,
22
+ 6144: 3,
23
+ 7168: 3.5,
24
+ 8192: 4,
25
+ 9216: 4.5,
26
+ 10240: 5,
27
+ };
28
+ function getProportionalCpu(ramMb) {
29
+ const ramValues = Object.keys(exports.AWS_LAMBDA_CPU_RATIO)
30
+ .map(Number)
31
+ .sort((a, b) => a - b);
32
+ const exact = exports.AWS_LAMBDA_CPU_RATIO[ramMb];
33
+ if (exact !== undefined) {
34
+ return exact;
35
+ }
36
+ for (let i = 0; i < ramValues.length - 1; i++) {
37
+ const lower = ramValues[i];
38
+ const upper = ramValues[i + 1];
39
+ if (ramMb > lower && ramMb < upper) {
40
+ const lowerCpu = exports.AWS_LAMBDA_CPU_RATIO[lower];
41
+ const upperCpu = exports.AWS_LAMBDA_CPU_RATIO[upper];
42
+ const ratio = (ramMb - lower) / (upper - lower);
43
+ return lowerCpu + (upperCpu - lowerCpu) * ratio;
44
+ }
45
+ }
46
+ return ramMb <= ramValues[0]
47
+ ? exports.AWS_LAMBDA_CPU_RATIO[ramValues[0]]
48
+ : exports.AWS_LAMBDA_CPU_RATIO[ramValues[ramValues.length - 1]];
49
+ }
50
+ exports.handlerBaseSchema = zod_1.z.object({
51
+ ram: zod_1.z
52
+ .number()
53
+ .min(exports.AWS_LAMBDA_LIMITS.MIN_RAM_MB, `RAM must be at least ${exports.AWS_LAMBDA_LIMITS.MIN_RAM_MB} MB`)
54
+ .max(exports.AWS_LAMBDA_LIMITS.MAX_RAM_MB, `RAM cannot exceed ${exports.AWS_LAMBDA_LIMITS.MAX_RAM_MB} MB`),
55
+ timeout: zod_1.z
56
+ .number()
57
+ .min(exports.AWS_LAMBDA_LIMITS.MIN_TIMEOUT_SECONDS, `Timeout must be at least ${exports.AWS_LAMBDA_LIMITS.MIN_TIMEOUT_SECONDS}s`)
58
+ .max(exports.AWS_LAMBDA_LIMITS.MAX_TIMEOUT_SECONDS, `Timeout cannot exceed ${exports.AWS_LAMBDA_LIMITS.MAX_TIMEOUT_SECONDS}s`),
59
+ cpu: zod_1.z.number().optional(),
60
+ });
61
+ exports.handlerSchema = exports.handlerBaseSchema.partial().superRefine((handler, ctx) => {
62
+ if (handler.cpu === undefined || handler.ram === undefined) {
63
+ return;
64
+ }
65
+ const expectedCpu = getProportionalCpu(handler.ram);
66
+ const tolerance = 0.1;
67
+ if (Math.abs(handler.cpu - expectedCpu) > tolerance) {
68
+ ctx.addIssue({
69
+ code: zod_1.z.ZodIssueCode.custom,
70
+ path: ['handler', 'cpu'],
71
+ message: `CPU (${handler.cpu} vCPU) is not proportional to RAM (${handler.ram} MB). Expected approximately ${expectedCpu.toFixed(2)} vCPU`,
72
+ });
73
+ }
74
+ });
75
+ exports.queueSchema = zod_1.z.object({
76
+ type: zod_1.z.enum(['standard', 'fifo']),
77
+ visibilityTimeout: zod_1.z.number(),
78
+ messageGroupId: zod_1.z.string().nullable().optional(),
79
+ maxRetries: zod_1.z.number().min(0, 'maxRetries cannot be negative'),
80
+ delaySeconds: zod_1.z
81
+ .number()
82
+ .min(0, 'delaySeconds cannot be negative')
83
+ .max(900, 'delaySeconds cannot exceed 900 seconds (15 minutes)')
84
+ .optional(),
85
+ });
86
+ exports.infrastructureSchema = zod_1.z
87
+ .object({
88
+ handler: exports.handlerSchema.optional(),
89
+ queue: exports.queueSchema.partial().optional(),
90
+ })
91
+ .superRefine((config, ctx) => {
92
+ if (config.queue?.visibilityTimeout !== undefined && config.handler?.timeout !== undefined) {
93
+ if (config.queue.visibilityTimeout <= config.handler.timeout) {
94
+ ctx.addIssue({
95
+ code: zod_1.z.ZodIssueCode.custom,
96
+ path: ['queue', 'visibilityTimeout'],
97
+ message: `Visibility timeout (${config.queue.visibilityTimeout}s) must be greater than handler timeout (${config.handler.timeout}s) to prevent premature message redelivery`,
98
+ });
99
+ }
100
+ }
101
+ if (config.queue?.type === 'fifo' && !config.queue?.messageGroupId) {
102
+ ctx.addIssue({
103
+ code: zod_1.z.ZodIssueCode.custom,
104
+ path: ['queue', 'messageGroupId'],
105
+ message: 'messageGroupId is required when queue type is "fifo"',
106
+ });
107
+ }
108
+ });
109
+ function validateMessageGroupId(messageGroupId, inputSchema, ctx, pathPrefix = ['queue', 'messageGroupId']) {
110
+ if (!messageGroupId || messageGroupId === 'traceId') {
111
+ return;
112
+ }
113
+ if (!inputSchema) {
114
+ ctx.addIssue({
115
+ code: zod_1.z.ZodIssueCode.custom,
116
+ path: pathPrefix,
117
+ message: `Cannot validate messageGroupId "${messageGroupId}" - step has no input schema defined`,
118
+ });
119
+ return;
120
+ }
121
+ if (messageGroupId.includes('.') || messageGroupId.includes('[')) {
122
+ ctx.addIssue({
123
+ code: zod_1.z.ZodIssueCode.custom,
124
+ path: pathPrefix,
125
+ message: `messageGroupId "${messageGroupId}" must be a simple field path. Nested paths and template expressions are not supported`,
126
+ });
127
+ return;
128
+ }
129
+ try {
130
+ if (inputSchema instanceof zod_1.z.ZodObject) {
131
+ const shape = inputSchema.shape;
132
+ if (!shape || !(messageGroupId in shape)) {
133
+ ctx.addIssue({
134
+ code: zod_1.z.ZodIssueCode.custom,
135
+ path: pathPrefix,
136
+ message: `messageGroupId "${messageGroupId}" does not exist in step's input schema`,
137
+ });
138
+ }
139
+ }
140
+ else if (typeof inputSchema === 'object' && inputSchema !== null && 'properties' in inputSchema) {
141
+ const properties = inputSchema.properties;
142
+ if (!properties || typeof properties !== 'object' || !(messageGroupId in properties)) {
143
+ ctx.addIssue({
144
+ code: zod_1.z.ZodIssueCode.custom,
145
+ path: pathPrefix,
146
+ message: `messageGroupId "${messageGroupId}" does not exist in step's input schema`,
147
+ });
148
+ }
149
+ }
150
+ else {
151
+ ctx.addIssue({
152
+ code: zod_1.z.ZodIssueCode.custom,
153
+ path: pathPrefix,
154
+ message: `Failed to validate messageGroupId "${messageGroupId}" against input schema: inputSchema is not a valid schema object`,
155
+ });
156
+ }
157
+ }
158
+ catch (error) {
159
+ ctx.addIssue({
160
+ code: zod_1.z.ZodIssueCode.custom,
161
+ path: pathPrefix,
162
+ message: `Failed to validate messageGroupId "${messageGroupId}" against input schema: ${error instanceof Error ? error.message : 'Unknown error'}`,
163
+ });
164
+ }
165
+ }
166
+ const createInfrastructureSchema = (inputSchema) => {
167
+ return exports.infrastructureSchema.superRefine((config, ctx) => {
168
+ validateMessageGroupId(config.queue?.messageGroupId, inputSchema, ctx, ['queue', 'messageGroupId']);
169
+ });
170
+ };
171
+ exports.createInfrastructureSchema = createInfrastructureSchema;
172
+ const createQueueSchema = (inputSchema) => {
173
+ return exports.queueSchema.superRefine((config, ctx) => {
174
+ validateMessageGroupId(config.messageGroupId, inputSchema, ctx, ['messageGroupId']);
175
+ });
176
+ };
177
+ exports.createQueueSchema = createQueueSchema;
@@ -0,0 +1,20 @@
1
+ export type InfrastructureValidationError = {
2
+ path: string;
3
+ message: string;
4
+ };
5
+ export type InfrastructureValidationResult = {
6
+ success: true;
7
+ } | {
8
+ success: false;
9
+ errors?: InfrastructureValidationError[];
10
+ };
11
+ export type QueueValidationError = {
12
+ path: string;
13
+ message: string;
14
+ };
15
+ export type QueueValidationResult = {
16
+ success: true;
17
+ } | {
18
+ success: false;
19
+ errors?: QueueValidationError[];
20
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,4 @@
1
+ import { InfrastructureValidationResult, QueueValidationResult } from './types';
2
+ import { ZodInput } from '../types';
3
+ export declare const validateQueueConfig: (queueConfig: unknown) => QueueValidationResult;
4
+ export declare const validateInfrastructureConfig: (infrastructureConfig: unknown, inputSchema?: ZodInput) => InfrastructureValidationResult;
@@ -0,0 +1,60 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateInfrastructureConfig = exports.validateQueueConfig = void 0;
4
+ const zod_1 = require("zod");
5
+ const schemas_1 = require("./schemas");
6
+ const validateQueueConfig = (queueConfig) => {
7
+ try {
8
+ const schema = (0, schemas_1.createQueueSchema)();
9
+ schema.parse(queueConfig);
10
+ return { success: true };
11
+ }
12
+ catch (error) {
13
+ if (error instanceof zod_1.z.ZodError) {
14
+ const errors = error.errors.map((err) => ({
15
+ path: err.path.length > 0 ? err.path.join('.') : 'queue',
16
+ message: err.message,
17
+ }));
18
+ return {
19
+ success: false,
20
+ errors,
21
+ };
22
+ }
23
+ return {
24
+ success: false,
25
+ errors: [
26
+ { path: 'queue', message: `Unexpected validation error: ${error instanceof Error ? error.message : 'Unknown error'}` },
27
+ ],
28
+ };
29
+ }
30
+ };
31
+ exports.validateQueueConfig = validateQueueConfig;
32
+ const validateInfrastructureConfig = (infrastructureConfig, inputSchema) => {
33
+ try {
34
+ const schema = (0, schemas_1.createInfrastructureSchema)(inputSchema);
35
+ schema.parse(infrastructureConfig);
36
+ return { success: true };
37
+ }
38
+ catch (error) {
39
+ if (error instanceof zod_1.z.ZodError) {
40
+ const errors = error.errors.map((err) => ({
41
+ path: err.path.length > 0 ? err.path.join('.') : 'infrastructure',
42
+ message: err.message,
43
+ }));
44
+ return {
45
+ success: false,
46
+ errors,
47
+ };
48
+ }
49
+ return {
50
+ success: false,
51
+ errors: [
52
+ {
53
+ path: 'infrastructure',
54
+ message: `Unexpected validation error: ${error instanceof Error ? error.message : 'Unknown error'}`,
55
+ },
56
+ ],
57
+ };
58
+ }
59
+ };
60
+ exports.validateInfrastructureConfig = validateInfrastructureConfig;
@@ -6,7 +6,7 @@ export declare class Printer {
6
6
  constructor(baseDir: string);
7
7
  stepTag: string;
8
8
  flowTag: string;
9
- created: string;
9
+ registered: string;
10
10
  building: string;
11
11
  built: string;
12
12
  updated: string;
@@ -10,7 +10,7 @@ const guards_1 = require("./guards");
10
10
  const stepTag = colors_1.default.bold(colors_1.default.magenta('Step'));
11
11
  const flowTag = colors_1.default.bold(colors_1.default.blue('Flow'));
12
12
  const streamTag = colors_1.default.bold(colors_1.default.green('Stream'));
13
- const created = colors_1.default.green('➜ [CREATED]');
13
+ const registered = colors_1.default.green('➜ [REGISTERED]');
14
14
  const building = colors_1.default.yellow('⚡ [BUILDING]');
15
15
  const built = colors_1.default.green('✓ [BUILT]');
16
16
  const updated = colors_1.default.yellow('➜ [UPDATED]');
@@ -23,7 +23,7 @@ class Printer {
23
23
  this.baseDir = baseDir;
24
24
  this.stepTag = stepTag;
25
25
  this.flowTag = flowTag;
26
- this.created = created;
26
+ this.registered = registered;
27
27
  this.building = building;
28
28
  this.built = built;
29
29
  this.updated = updated;
@@ -33,7 +33,7 @@ class Printer {
33
33
  console.log(`${invalidEmit} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} tried to emit an event not defined in the step config: ${colors_1.default.yellow(emit)}`);
34
34
  }
35
35
  printStepCreated(step) {
36
- console.log(`${created} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} created`);
36
+ console.log(`${registered} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} registered`);
37
37
  }
38
38
  printStepUpdated(step) {
39
39
  console.log(`${updated} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} updated`);
@@ -42,7 +42,7 @@ class Printer {
42
42
  console.log(`${removed} ${stepTag} ${this.getStepType(step)} ${this.getStepPath(step)} removed`);
43
43
  }
44
44
  printFlowCreated(flowName) {
45
- console.log(`${created} ${flowTag} ${colors_1.default.bold(colors_1.default.cyan(flowName))} created`);
45
+ console.log(`${registered} ${flowTag} ${colors_1.default.bold(colors_1.default.cyan(flowName))} registered`);
46
46
  }
47
47
  printFlowUpdated(flowName) {
48
48
  console.log(`${updated} ${flowTag} ${colors_1.default.bold(colors_1.default.cyan(flowName))} updated`);
@@ -51,7 +51,7 @@ class Printer {
51
51
  console.log(`${removed} ${flowTag} ${colors_1.default.bold(colors_1.default.cyan(flowName))} removed`);
52
52
  }
53
53
  printStreamCreated(stream) {
54
- console.log(`${created} ${streamTag} ${this.getStreamPath(stream)} created`);
54
+ console.log(`${registered} ${streamTag} ${this.getStreamPath(stream)} registered`);
55
55
  }
56
56
  printStreamUpdated(stream) {
57
57
  console.log(`${updated} ${streamTag} ${this.getStreamPath(stream)} updated`);
@@ -0,0 +1,17 @@
1
+ import { Event, QueueConfig, Handler } from './types';
2
+ declare class QueueManager {
3
+ private queues;
4
+ private subscriptions;
5
+ private lockedGroups;
6
+ private processingTimers;
7
+ private processQueue;
8
+ private processMessage;
9
+ private removeMessageFromQueue;
10
+ private startQueueProcessor;
11
+ enqueue<TData>(topic: string, event: Event<TData>): Promise<void>;
12
+ subscribe(topic: string, handler: Handler, queueConfig: QueueConfig, subscriptionId: string): void;
13
+ unsubscribe(topic: string, handler: Handler): void;
14
+ reset(): void;
15
+ }
16
+ export declare const queueManager: QueueManager;
17
+ export {};
@@ -0,0 +1,176 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.queueManager = void 0;
4
+ const crypto_1 = require("crypto");
5
+ const logger_1 = require("./logger");
6
+ function extractMessageGroupId(event, messageGroupId) {
7
+ if (!messageGroupId) {
8
+ return undefined;
9
+ }
10
+ if (messageGroupId === 'traceId') {
11
+ return event.traceId;
12
+ }
13
+ try {
14
+ const data = event.data;
15
+ const value = data[messageGroupId];
16
+ return value !== undefined && value !== null ? String(value) : undefined;
17
+ }
18
+ catch {
19
+ return undefined;
20
+ }
21
+ }
22
+ class QueueManager {
23
+ constructor() {
24
+ this.queues = {};
25
+ this.subscriptions = {};
26
+ this.lockedGroups = new Set();
27
+ this.processingTimers = {};
28
+ }
29
+ processQueue(topic) {
30
+ const queue = this.queues[topic];
31
+ if (!queue || queue.length === 0) {
32
+ return;
33
+ }
34
+ const now = Date.now();
35
+ const visibleMessages = queue.filter((msg) => msg.visibleAt <= now);
36
+ for (const message of visibleMessages) {
37
+ if (message.queueConfig.type === 'fifo' && message.messageGroupId) {
38
+ const lockKey = `${topic}:${message.messageGroupId}`;
39
+ if (this.lockedGroups.has(lockKey)) {
40
+ continue;
41
+ }
42
+ this.lockedGroups.add(lockKey);
43
+ this.processMessage(topic, message, lockKey);
44
+ }
45
+ else {
46
+ this.processMessage(topic, message);
47
+ }
48
+ }
49
+ }
50
+ processMessage(topic, message, lockKey) {
51
+ const handlers = this.subscriptions[topic] || [];
52
+ const handler = handlers.find((s) => s.internalSubscriptionId === message.internalSubscriptionId) ||
53
+ handlers.find((s) => s.subscriptionId === message.subscriptionId) ||
54
+ handlers[0];
55
+ if (!handler) {
56
+ this.removeMessageFromQueue(topic, message.id);
57
+ if (lockKey) {
58
+ this.lockedGroups.delete(lockKey);
59
+ }
60
+ return;
61
+ }
62
+ const visibilityTimeoutMs = handler.queueConfig.visibilityTimeout * 1000;
63
+ message.visibleAt = Date.now() + visibilityTimeoutMs;
64
+ handler.handler(message.event)
65
+ .then(() => {
66
+ this.removeMessageFromQueue(topic, message.id);
67
+ if (lockKey) {
68
+ this.lockedGroups.delete(lockKey);
69
+ }
70
+ })
71
+ .catch((error) => {
72
+ message.attempts++;
73
+ if (message.attempts >= handler.queueConfig.maxRetries) {
74
+ logger_1.globalLogger.error('[Queue DLQ] Message moved to dead-letter queue after max retries', {
75
+ topic,
76
+ messageId: message.id,
77
+ attempts: message.attempts,
78
+ error: error instanceof Error ? error.message : 'Unknown error',
79
+ });
80
+ this.removeMessageFromQueue(topic, message.id);
81
+ if (lockKey) {
82
+ this.lockedGroups.delete(lockKey);
83
+ }
84
+ }
85
+ else {
86
+ message.visibleAt = Date.now() + handler.queueConfig.visibilityTimeout * 1000;
87
+ if (lockKey) {
88
+ this.lockedGroups.delete(lockKey);
89
+ }
90
+ }
91
+ });
92
+ }
93
+ removeMessageFromQueue(topic, messageId) {
94
+ const queue = this.queues[topic];
95
+ if (!queue) {
96
+ return;
97
+ }
98
+ const index = queue.findIndex((msg) => msg.id === messageId);
99
+ if (index !== -1) {
100
+ queue.splice(index, 1);
101
+ }
102
+ if (queue.length === 0) {
103
+ delete this.queues[topic];
104
+ if (this.processingTimers[topic]) {
105
+ clearInterval(this.processingTimers[topic]);
106
+ delete this.processingTimers[topic];
107
+ }
108
+ }
109
+ }
110
+ startQueueProcessor(topic) {
111
+ if (this.processingTimers[topic]) {
112
+ return;
113
+ }
114
+ this.processingTimers[topic] = setInterval(() => {
115
+ this.processQueue(topic);
116
+ }, 100);
117
+ }
118
+ async enqueue(topic, event) {
119
+ const handlers = this.subscriptions[topic] || [];
120
+ if (handlers.length === 0) {
121
+ return;
122
+ }
123
+ for (const subscription of handlers) {
124
+ const messageGroupId = extractMessageGroupId(event, subscription.queueConfig.messageGroupId);
125
+ const delayMs = subscription.queueConfig.delaySeconds * 1000;
126
+ const visibleAt = Date.now() + delayMs;
127
+ const queuedMessage = {
128
+ id: (0, crypto_1.randomUUID)(),
129
+ event,
130
+ attempts: 0,
131
+ visibleAt,
132
+ messageGroupId,
133
+ queueConfig: subscription.queueConfig,
134
+ subscriptionId: subscription.subscriptionId,
135
+ internalSubscriptionId: subscription.internalSubscriptionId,
136
+ };
137
+ if (!this.queues[topic]) {
138
+ this.queues[topic] = [];
139
+ }
140
+ this.queues[topic].push(queuedMessage);
141
+ this.startQueueProcessor(topic);
142
+ }
143
+ setImmediate(() => this.processQueue(topic));
144
+ }
145
+ subscribe(topic, handler, queueConfig, subscriptionId) {
146
+ if (!this.subscriptions[topic]) {
147
+ this.subscriptions[topic] = [];
148
+ }
149
+ const internalSubscriptionId = (0, crypto_1.randomUUID)();
150
+ this.subscriptions[topic].push({ handler, queueConfig, subscriptionId, internalSubscriptionId });
151
+ if (this.queues[topic] && this.queues[topic].length > 0) {
152
+ this.startQueueProcessor(topic);
153
+ }
154
+ }
155
+ unsubscribe(topic, handler) {
156
+ if (!this.subscriptions[topic]) {
157
+ return;
158
+ }
159
+ this.subscriptions[topic] = this.subscriptions[topic].filter((sub) => sub.handler !== handler);
160
+ if (this.subscriptions[topic].length === 0) {
161
+ delete this.subscriptions[topic];
162
+ if (this.processingTimers[topic]) {
163
+ clearInterval(this.processingTimers[topic]);
164
+ delete this.processingTimers[topic];
165
+ }
166
+ }
167
+ }
168
+ reset() {
169
+ Object.values(this.processingTimers).forEach((timer) => clearInterval(timer));
170
+ this.queues = {};
171
+ this.subscriptions = {};
172
+ this.lockedGroups = new Set();
173
+ this.processingTimers = {};
174
+ }
175
+ }
176
+ exports.queueManager = new QueueManager();
@@ -3,6 +3,7 @@ import http from 'http';
3
3
  import { Server as WsServer } from 'ws';
4
4
  import { CronManager } from './cron-handler';
5
5
  import { LockedData } from './locked-data';
6
+ import { Motia } from './motia';
6
7
  import { Printer } from './printer';
7
8
  import { StateAdapter } from './state/state-adapter';
8
9
  import { MotiaEventManager } from './step-handlers';
@@ -16,6 +17,7 @@ export type MotiaServer = {
16
17
  addRoute: (step: Step<ApiRouteConfig>) => void;
17
18
  cronManager: CronManager;
18
19
  motiaEventManager: MotiaEventManager;
20
+ motia: Motia;
19
21
  };
20
22
  type MotiaServerConfig = {
21
23
  isVerbose: boolean;
@@ -140,7 +140,13 @@ const createServer = (lockedData, eventManager, state, config) => {
140
140
  Object.entries(result.headers).forEach(([key, value]) => res.setHeader(key, value));
141
141
  }
142
142
  res.status(result.status);
143
- res.json(result.body);
143
+ // Handle different body types
144
+ if (Buffer.isBuffer(result.body) || typeof result.body === 'string') {
145
+ res.send(result.body);
146
+ }
147
+ else {
148
+ res.json(result.body);
149
+ }
144
150
  }
145
151
  catch (error) {
146
152
  (0, utils_1.trackEvent)('api_call_error', {
@@ -223,6 +229,6 @@ const createServer = (lockedData, eventManager, state, config) => {
223
229
  cronManager.close();
224
230
  socketServer.close();
225
231
  };
226
- return { app, server, socketServer, close, removeRoute, addRoute, cronManager, motiaEventManager };
232
+ return { app, server, socketServer, close, removeRoute, addRoute, cronManager, motiaEventManager, motia };
227
233
  };
228
234
  exports.createServer = createServer;
@@ -3,11 +3,14 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createStepHandlers = void 0;
4
4
  const call_step_file_1 = require("./call-step-file");
5
5
  const logger_1 = require("./logger");
6
+ const defaults_1 = require("./infrastructure-validator/defaults");
7
+ const validations_1 = require("./infrastructure-validator/validations");
8
+ const queue_manager_1 = require("./queue-manager");
6
9
  const createStepHandlers = (motia) => {
7
10
  const eventSteps = motia.lockedData.eventSteps();
11
+ const handlerMap = new Map();
8
12
  logger_1.globalLogger.debug(`[step handler] creating step handlers for ${eventSteps.length} steps`);
9
13
  const removeLogger = (event) => {
10
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
11
14
  const { logger, tracer, ...rest } = event;
12
15
  return rest;
13
16
  };
@@ -15,34 +18,50 @@ const createStepHandlers = (motia) => {
15
18
  const { config, filePath } = step;
16
19
  const { subscribes, name } = config;
17
20
  logger_1.globalLogger.debug('[step handler] establishing step subscriptions', { filePath, step: step.config.name });
18
- subscribes.forEach((subscribe) => {
19
- motia.eventManager.subscribe({
20
- filePath,
21
- event: subscribe,
22
- handlerName: step.config.name,
23
- handler: async (event) => {
24
- const { data, traceId } = event;
25
- const logger = event.logger.child({ step: step.config.name });
26
- const tracer = event.tracer.child(step, logger);
27
- logger_1.globalLogger.debug('[step handler] received event', { event: removeLogger(event), step: name });
28
- try {
29
- await (0, call_step_file_1.callStepFile)({ step, data, traceId, tracer, logger }, motia);
30
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
31
- }
32
- catch (error) {
33
- const message = typeof error === 'string' ? error : error.message;
34
- logger.error(message);
35
- }
36
- },
21
+ if (config.infrastructure) {
22
+ logger_1.globalLogger.debug('[step handler] validating infrastructure config', {
23
+ step: name,
24
+ hasInputSchema: !!config.input,
25
+ infrastructure: config.infrastructure,
26
+ });
27
+ const validationResult = (0, validations_1.validateInfrastructureConfig)(config.infrastructure, config.input);
28
+ if (!validationResult.success && validationResult.errors) {
29
+ logger_1.globalLogger.error('[step handler] Infrastructure configuration validation failed', {
30
+ step: name,
31
+ filePath,
32
+ errors: validationResult.errors,
33
+ });
34
+ return;
35
+ }
36
+ logger_1.globalLogger.debug('[step handler] infrastructure config validated successfully', {
37
+ step: name,
37
38
  });
39
+ }
40
+ const queueConfig = (0, defaults_1.getQueueConfigWithDefaults)(config.infrastructure);
41
+ const handlers = [];
42
+ subscribes.forEach((subscribe) => {
43
+ const handler = async (event) => {
44
+ const { data, traceId } = event;
45
+ const logger = event.logger.child({ step: step.config.name });
46
+ const tracer = event.tracer.child(step, logger);
47
+ logger_1.globalLogger.debug('[step handler] received event', { event: removeLogger(event), step: name });
48
+ await (0, call_step_file_1.callStepFile)({ step, data, traceId, tracer, logger, infrastructure: config.infrastructure }, motia);
49
+ };
50
+ queue_manager_1.queueManager.subscribe(subscribe, handler, queueConfig, subscribe);
51
+ handlers.push({ topic: subscribe, handler });
38
52
  });
53
+ handlerMap.set(filePath, handlers);
39
54
  };
40
55
  const removeHandler = (step) => {
41
- const { config, filePath } = step;
42
- const { subscribes } = config;
43
- subscribes.forEach((subscribe) => {
44
- motia.eventManager.unsubscribe({ filePath, event: subscribe });
45
- });
56
+ const { filePath } = step;
57
+ const handlers = handlerMap.get(filePath);
58
+ if (handlers) {
59
+ handlers.forEach(({ topic, handler }) => {
60
+ queue_manager_1.queueManager.unsubscribe(topic, handler);
61
+ logger_1.globalLogger.debug('[step handler] unsubscribed handler', { filePath, topic, step: step.config.name });
62
+ });
63
+ handlerMap.delete(filePath);
64
+ }
46
65
  };
47
66
  eventSteps.forEach(createHandler);
48
67
  return { removeHandler, createHandler };
@@ -2,6 +2,7 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.validateStep = void 0;
4
4
  const zod_1 = require("zod");
5
+ const schemas_1 = require("./infrastructure-validator/schemas");
5
6
  const objectSchema = zod_1.z.object({
6
7
  type: zod_1.z.literal('object'),
7
8
  properties: zod_1.z.record(zod_1.z.any()),
@@ -60,6 +61,7 @@ const eventSchema = zod_1.z
60
61
  input: zod_1.z.union([jsonSchema, zod_1.z.object({}), zod_1.z.null()]).optional(),
61
62
  flows: zod_1.z.array(zod_1.z.string()).optional(),
62
63
  includeFiles: zod_1.z.array(zod_1.z.string()).optional(),
64
+ infrastructure: schemas_1.infrastructureSchema.optional(),
63
65
  })
64
66
  .strict();
65
67
  const apiSchema = zod_1.z