@motiadev/core 0.0.6 → 0.0.7-build.20250529215343

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/LICENSE +21 -0
  2. package/README.md +142 -0
  3. package/dist/index.d.ts +13 -8
  4. package/dist/index.js +28 -8
  5. package/dist/src/call-step-file.d.ts +17 -2
  6. package/dist/src/call-step-file.js +88 -47
  7. package/dist/src/cron-handler.d.ts +13 -0
  8. package/dist/src/cron-handler.js +98 -0
  9. package/dist/src/event-manager.js +10 -5
  10. package/dist/src/flows-config-endpoint.d.ts +2 -0
  11. package/dist/src/flows-config-endpoint.js +51 -0
  12. package/dist/src/flows-endpoint.d.ts +11 -7
  13. package/dist/src/flows-endpoint.js +53 -22
  14. package/dist/src/generate-trace-id.d.ts +2 -0
  15. package/dist/src/generate-trace-id.js +14 -0
  16. package/dist/src/get-step-config.d.ts +4 -0
  17. package/dist/src/get-step-config.js +88 -0
  18. package/dist/src/guards.d.ts +3 -2
  19. package/dist/src/guards.js +3 -1
  20. package/dist/src/locked-data.d.ts +60 -0
  21. package/dist/src/locked-data.js +278 -0
  22. package/dist/src/logger-factory.d.ts +15 -0
  23. package/dist/src/logger-factory.js +14 -0
  24. package/dist/src/logger.d.ts +21 -15
  25. package/dist/src/logger.js +49 -29
  26. package/dist/src/mermaid-generator.d.ts +4 -0
  27. package/dist/src/mermaid-generator.js +203 -0
  28. package/dist/src/node/get-config.d.ts +1 -2
  29. package/dist/src/node/get-config.js +51 -8
  30. package/dist/src/node/logger.d.ts +10 -6
  31. package/dist/src/node/logger.js +27 -16
  32. package/dist/src/node/middleware-compose.d.ts +1 -0
  33. package/dist/src/node/middleware-compose.js +12 -0
  34. package/dist/src/node/node-runner.js +28 -9
  35. package/dist/src/node/rpc-state-manager.d.ts +3 -2
  36. package/dist/src/node/rpc-state-manager.js +5 -2
  37. package/dist/src/node/rpc.d.ts +3 -1
  38. package/dist/src/node/rpc.js +21 -3
  39. package/dist/src/pretty-print.d.ts +1 -0
  40. package/dist/src/pretty-print.js +66 -0
  41. package/dist/src/printer.d.ts +45 -0
  42. package/dist/src/printer.js +121 -0
  43. package/dist/src/process-communication/communication-config.d.ts +7 -0
  44. package/dist/src/process-communication/communication-config.js +12 -0
  45. package/dist/src/process-communication/process-manager.d.ts +30 -0
  46. package/dist/src/process-communication/process-manager.js +88 -0
  47. package/dist/src/process-communication/rpc-processor-interface.d.ts +9 -0
  48. package/dist/src/process-communication/rpc-processor-interface.js +2 -0
  49. package/dist/src/python/communication_factory.py +35 -0
  50. package/dist/src/python/context.py +21 -0
  51. package/dist/src/python/get-config.py +31 -13
  52. package/dist/src/python/ipc_communication.py +145 -0
  53. package/dist/src/python/logger.py +4 -6
  54. package/dist/src/python/middleware.py +17 -0
  55. package/dist/src/python/python-runner.py +105 -39
  56. package/dist/src/python/rpc.py +33 -68
  57. package/dist/src/python/rpc_communication.py +125 -0
  58. package/dist/src/python/rpc_state_manager.py +49 -11
  59. package/dist/src/python/type_definitions.py +34 -0
  60. package/dist/src/python/validation.py +56 -0
  61. package/dist/src/ruby/get-config.rb +61 -0
  62. package/dist/src/ruby/logger.rb +21 -16
  63. package/dist/src/ruby/rpc.rb +118 -0
  64. package/dist/src/ruby/rpc_state_manager.rb +41 -0
  65. package/dist/src/ruby/ruby-runner.rb +94 -0
  66. package/dist/src/server.d.ts +14 -12
  67. package/dist/src/server.js +149 -28
  68. package/dist/src/socket-server.d.ts +39 -0
  69. package/dist/src/socket-server.js +76 -0
  70. package/dist/src/state/adapters/default-state-adapter.d.ts +7 -3
  71. package/dist/src/state/adapters/default-state-adapter.js +37 -14
  72. package/dist/src/state/adapters/memory-state-adapter.d.ts +14 -0
  73. package/dist/src/state/adapters/memory-state-adapter.js +58 -0
  74. package/dist/src/state/create-state-adapter.d.ts +5 -6
  75. package/dist/src/state/create-state-adapter.js +2 -10
  76. package/dist/src/state/state-adapter.d.ts +4 -4
  77. package/dist/src/state-stream.d.ts +19 -0
  78. package/dist/src/state-stream.js +28 -0
  79. package/dist/src/step-handler-rpc-processor.d.ts +13 -4
  80. package/dist/src/step-handler-rpc-processor.js +33 -3
  81. package/dist/src/step-handler-rpc-stdin-processor.d.ts +22 -0
  82. package/dist/src/step-handler-rpc-stdin-processor.js +84 -0
  83. package/dist/src/step-handlers.d.ts +7 -2
  84. package/dist/src/step-handlers.js +47 -19
  85. package/dist/src/step-validator.d.ts +14 -0
  86. package/dist/src/step-validator.js +138 -0
  87. package/dist/src/steps/emit.step.d.ts +11 -0
  88. package/dist/src/steps/emit.step.js +27 -0
  89. package/dist/src/steps/emit.step.ts +34 -0
  90. package/dist/src/steps/index.d.ts +2 -0
  91. package/dist/src/steps/index.js +16 -0
  92. package/dist/src/streams/api-endpoints.d.ts +2 -0
  93. package/dist/src/streams/api-endpoints.js +71 -0
  94. package/dist/src/streams/flows-stream.d.ts +14 -0
  95. package/dist/src/streams/flows-stream.js +29 -0
  96. package/dist/src/streams/logs-stream.d.ts +16 -0
  97. package/dist/src/streams/logs-stream.js +22 -0
  98. package/dist/src/types/generate-type-from-schema.d.ts +2 -0
  99. package/dist/src/types/generate-type-from-schema.js +28 -0
  100. package/dist/src/types/generate-types-from-response.d.ts +2 -0
  101. package/dist/src/types/generate-types-from-response.js +13 -0
  102. package/dist/src/types/generate-types.d.ts +12 -0
  103. package/dist/src/types/generate-types.js +108 -0
  104. package/dist/src/types/merge-schemas.d.ts +3 -0
  105. package/dist/src/types/merge-schemas.js +59 -0
  106. package/dist/src/types/schema.types.d.ts +20 -0
  107. package/dist/src/types/schema.types.js +10 -0
  108. package/dist/src/types-stream.d.ts +34 -0
  109. package/dist/src/types-stream.js +2 -0
  110. package/dist/src/types.d.ts +93 -47
  111. package/dist/src/utils.d.ts +2 -0
  112. package/dist/src/utils.js +12 -0
  113. package/package.json +20 -9
  114. package/requirements.txt +1 -0
  115. package/dist/src/node/get-module-export.d.ts +0 -1
  116. package/dist/src/node/get-module-export.js +0 -63
  117. package/dist/src/python/get-python-config.d.ts +0 -2
  118. package/dist/src/python/get-python-config.js +0 -34
  119. package/dist/src/ruby/get_config.rb +0 -78
  120. package/dist/src/ruby/ruby_runner.rb +0 -80
  121. package/dist/src/ruby/state_adapter.rb +0 -62
  122. package/dist/src/state/adapters/redis-state-adapter.d.ts +0 -19
  123. package/dist/src/state/adapters/redis-state-adapter.js +0 -44
  124. package/tsconfig.json +0 -20
@@ -4,11 +4,16 @@ exports.RpcProcessor = void 0;
4
4
  class RpcProcessor {
5
5
  constructor(child) {
6
6
  this.child = child;
7
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
7
8
  this.handlers = {};
9
+ this.isClosed = false;
8
10
  }
9
11
  handler(method, handler) {
10
12
  this.handlers[method] = handler;
11
13
  }
14
+ onMessage(callback) {
15
+ this.messageCallback = callback;
16
+ }
12
17
  async handle(method, input) {
13
18
  const handler = this.handlers[method];
14
19
  if (!handler) {
@@ -17,19 +22,44 @@ class RpcProcessor {
17
22
  return handler(input);
18
23
  }
19
24
  response(id, result, error) {
20
- if (id) {
21
- this.child.send?.({ type: 'rpc_response', id, result, error });
25
+ if (id && !this.isClosed && this.child.send && this.child.connected) {
26
+ const responseMessage = {
27
+ type: 'rpc_response',
28
+ id,
29
+ result: error ? undefined : result,
30
+ error: error ? String(error) : undefined,
31
+ };
32
+ this.child.send(responseMessage);
22
33
  }
23
34
  }
24
35
  async init() {
36
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
37
  this.child.on('message', (msg) => {
26
- if (msg.type === 'rpc_request') {
38
+ // Call generic message callback if registered
39
+ if (this.messageCallback) {
40
+ this.messageCallback(msg);
41
+ }
42
+ // Handle RPC requests specifically
43
+ if (msg && msg.type === 'rpc_request') {
27
44
  const { id, method, args } = msg;
28
45
  this.handle(method, args)
29
46
  .then((result) => this.response(id, result, null))
30
47
  .catch((error) => this.response(id, null, error));
31
48
  }
32
49
  });
50
+ this.child.on('exit', () => {
51
+ this.isClosed = true;
52
+ });
53
+ this.child.on('close', () => {
54
+ this.isClosed = true;
55
+ });
56
+ this.child.on('disconnect', () => {
57
+ this.isClosed = true;
58
+ });
59
+ }
60
+ close() {
61
+ this.isClosed = true;
62
+ this.messageCallback = undefined;
33
63
  }
34
64
  }
35
65
  exports.RpcProcessor = RpcProcessor;
@@ -0,0 +1,22 @@
1
+ import { ChildProcess } from 'child_process';
2
+ import { RpcProcessorInterface, RpcHandler, MessageCallback } from './process-communication/rpc-processor-interface';
3
+ export type RpcMessage = {
4
+ type: 'rpc_request';
5
+ id: string | undefined;
6
+ method: string;
7
+ args: unknown;
8
+ };
9
+ export declare class RpcStdinProcessor implements RpcProcessorInterface {
10
+ private child;
11
+ private handlers;
12
+ private messageCallback?;
13
+ private isClosed;
14
+ private rl?;
15
+ constructor(child: ChildProcess);
16
+ handler<TInput, TOutput = unknown>(method: string, handler: RpcHandler<TInput, TOutput>): void;
17
+ onMessage<T = unknown>(callback: MessageCallback<T>): void;
18
+ handle(method: string, input: unknown): Promise<any>;
19
+ private response;
20
+ init(): Promise<void>;
21
+ close(): void;
22
+ }
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.RpcStdinProcessor = void 0;
7
+ const readline_1 = __importDefault(require("readline"));
8
+ class RpcStdinProcessor {
9
+ constructor(child) {
10
+ this.child = child;
11
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
12
+ this.handlers = {};
13
+ this.isClosed = false;
14
+ }
15
+ handler(method, handler) {
16
+ this.handlers[method] = handler;
17
+ }
18
+ onMessage(callback) {
19
+ this.messageCallback = callback;
20
+ }
21
+ async handle(method, input) {
22
+ const handler = this.handlers[method];
23
+ if (!handler) {
24
+ throw new Error(`Handler for method ${method} not found`);
25
+ }
26
+ return handler(input);
27
+ }
28
+ response(id, result, error) {
29
+ if (id && !this.isClosed && this.child.stdin && !this.child.killed) {
30
+ const responseMessage = {
31
+ type: 'rpc_response',
32
+ id,
33
+ result: error ? undefined : result,
34
+ error: error ? String(error) : undefined,
35
+ };
36
+ const messageStr = JSON.stringify(responseMessage);
37
+ this.child.stdin.write(messageStr + '\n');
38
+ }
39
+ }
40
+ async init() {
41
+ if (this.child.stdout) {
42
+ this.rl = readline_1.default.createInterface({
43
+ input: this.child.stdout,
44
+ crlfDelay: Infinity,
45
+ });
46
+ this.rl.on('line', (line) => {
47
+ try {
48
+ const msg = JSON.parse(line.trim());
49
+ // Call generic message callback if registered
50
+ if (this.messageCallback) {
51
+ this.messageCallback(msg);
52
+ }
53
+ // Handle RPC requests specifically
54
+ if (msg && msg.type === 'rpc_request') {
55
+ const { id, method, args } = msg;
56
+ this.handle(method, args)
57
+ .then((result) => this.response(id, result, null))
58
+ .catch((error) => this.response(id, null, error));
59
+ }
60
+ }
61
+ catch (error) {
62
+ console.error('Failed to parse RPC message:', error, 'Raw line:', line);
63
+ }
64
+ });
65
+ this.rl.on('close', () => {
66
+ this.isClosed = true;
67
+ });
68
+ }
69
+ this.child.on('exit', () => {
70
+ this.isClosed = true;
71
+ });
72
+ this.child.on('close', () => {
73
+ this.isClosed = true;
74
+ });
75
+ }
76
+ close() {
77
+ this.isClosed = true;
78
+ this.messageCallback = undefined;
79
+ if (this.rl) {
80
+ this.rl.close();
81
+ }
82
+ }
83
+ }
84
+ exports.RpcStdinProcessor = RpcStdinProcessor;
@@ -1,2 +1,7 @@
1
- import { EventManager, InternalStateManager, Step } from './types';
2
- export declare const createStepHandlers: (steps: Step[], eventManager: EventManager, state: InternalStateManager) => void;
1
+ import { EventConfig, EventManager, InternalStateManager, Step } from './types';
2
+ import { LockedData } from './locked-data';
3
+ export type MotiaEventManager = {
4
+ createHandler: (step: Step<EventConfig>) => void;
5
+ removeHandler: (step: Step<EventConfig>) => void;
6
+ };
7
+ export declare const createStepHandlers: (lockedData: LockedData, eventManager: EventManager, state: InternalStateManager) => MotiaEventManager;
@@ -2,30 +2,58 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createStepHandlers = void 0;
4
4
  const logger_1 = require("./logger");
5
- const guards_1 = require("./guards");
6
5
  const call_step_file_1 = require("./call-step-file");
7
- const createStepHandlers = (steps, eventManager, state) => {
8
- logger_1.globalLogger.debug(`[step handler] creating step handlers for ${steps.length} steps`);
9
- steps.filter(guards_1.isEventStep).forEach((step) => {
6
+ const createStepHandlers = (lockedData, eventManager, state) => {
7
+ const eventSteps = lockedData.eventSteps();
8
+ const printer = lockedData.printer;
9
+ logger_1.globalLogger.debug(`[step handler] creating step handlers for ${eventSteps.length} steps`);
10
+ const removeLogger = (event) => {
11
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
12
+ const { logger, ...rest } = event;
13
+ return rest;
14
+ };
15
+ const createHandler = (step) => {
10
16
  const { config, filePath } = step;
11
- const { subscribes } = config;
17
+ const { subscribes, name } = config;
12
18
  logger_1.globalLogger.debug('[step handler] establishing step subscriptions', { filePath, step: step.config.name });
13
19
  subscribes.forEach((subscribe) => {
14
- eventManager.subscribe(subscribe, step.config.name, async (event) => {
15
- const { logger, ...rest } = event;
16
- logger_1.globalLogger.debug('[step handler] received event', { event: rest, step: step.config.name });
17
- try {
18
- await (0, call_step_file_1.callStepFile)(filePath, step.config.name, event, eventManager, state);
19
- }
20
- catch (error) {
21
- logger_1.globalLogger.error(`[step handler] error calling step`, {
22
- error: error.message,
23
- filePath,
24
- step: step.config.name,
25
- });
26
- }
20
+ eventManager.subscribe({
21
+ filePath,
22
+ event: subscribe,
23
+ handlerName: step.config.name,
24
+ handler: async (event) => {
25
+ const { logger, data, traceId } = event;
26
+ logger_1.globalLogger.debug('[step handler] received event', { event: removeLogger(event), step: name });
27
+ try {
28
+ await (0, call_step_file_1.callStepFile)({
29
+ contextInFirstArg: false,
30
+ step,
31
+ printer,
32
+ eventManager,
33
+ state,
34
+ lockedData,
35
+ data,
36
+ traceId,
37
+ logger,
38
+ });
39
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
40
+ }
41
+ catch (error) {
42
+ const message = typeof error === 'string' ? error : error.message;
43
+ logger.error(message);
44
+ }
45
+ },
27
46
  });
28
47
  });
29
- });
48
+ };
49
+ const removeHandler = (step) => {
50
+ const { config, filePath } = step;
51
+ const { subscribes } = config;
52
+ subscribes.forEach((subscribe) => {
53
+ eventManager.unsubscribe({ filePath, event: subscribe });
54
+ });
55
+ };
56
+ eventSteps.forEach(createHandler);
57
+ return { removeHandler, createHandler };
30
58
  };
31
59
  exports.createStepHandlers = createStepHandlers;
@@ -0,0 +1,14 @@
1
+ import { Step } from './types';
2
+ export type ValidationSuccess = {
3
+ success: true;
4
+ };
5
+ export type ValidationError = {
6
+ success: false;
7
+ error: string;
8
+ errors?: Array<{
9
+ path: string;
10
+ message: string;
11
+ }>;
12
+ };
13
+ export type ValidationResult = ValidationSuccess | ValidationError;
14
+ export declare const validateStep: (step: Step) => ValidationResult;
@@ -0,0 +1,138 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateStep = void 0;
4
+ const zod_1 = require("zod");
5
+ const jsonSchema = zod_1.z.object({
6
+ type: zod_1.z.string(),
7
+ properties: zod_1.z.record(zod_1.z.any()),
8
+ required: zod_1.z.array(zod_1.z.string()).optional(),
9
+ additionalProperties: zod_1.z.boolean().optional(),
10
+ description: zod_1.z.string().optional(),
11
+ title: zod_1.z.string().optional(),
12
+ definitions: zod_1.z.record(zod_1.z.any()).optional(),
13
+ $ref: zod_1.z.string().optional(),
14
+ items: zod_1.z.any().optional(),
15
+ enum: zod_1.z.array(zod_1.z.any()).optional(),
16
+ allOf: zod_1.z.array(zod_1.z.any()).optional(),
17
+ anyOf: zod_1.z.array(zod_1.z.any()).optional(),
18
+ oneOf: zod_1.z.array(zod_1.z.any()).optional(),
19
+ not: zod_1.z.any().optional(),
20
+ format: zod_1.z.string().optional(),
21
+ default: zod_1.z.any().optional(),
22
+ examples: zod_1.z.array(zod_1.z.any()).optional(),
23
+ multipleOf: zod_1.z.number().optional(),
24
+ maximum: zod_1.z.number().optional(),
25
+ exclusiveMaximum: zod_1.z.union([zod_1.z.boolean(), zod_1.z.number()]).optional(),
26
+ minimum: zod_1.z.number().optional(),
27
+ exclusiveMinimum: zod_1.z.union([zod_1.z.boolean(), zod_1.z.number()]).optional(),
28
+ maxLength: zod_1.z.number().optional(),
29
+ minLength: zod_1.z.number().optional(),
30
+ pattern: zod_1.z.string().optional(),
31
+ maxItems: zod_1.z.number().optional(),
32
+ minItems: zod_1.z.number().optional(),
33
+ uniqueItems: zod_1.z.boolean().optional(),
34
+ maxProperties: zod_1.z.number().optional(),
35
+ minProperties: zod_1.z.number().optional(),
36
+ const: zod_1.z.any().optional(),
37
+ });
38
+ const emits = zod_1.z.array(zod_1.z.union([
39
+ zod_1.z.string(),
40
+ zod_1.z
41
+ .object({
42
+ topic: zod_1.z.string(),
43
+ label: zod_1.z.string().optional(),
44
+ conditional: zod_1.z.boolean().optional(),
45
+ })
46
+ .strict(),
47
+ ]));
48
+ const noopSchema = zod_1.z
49
+ .object({
50
+ type: zod_1.z.literal('noop'),
51
+ name: zod_1.z.string(),
52
+ description: zod_1.z.string().optional(),
53
+ virtualEmits: emits,
54
+ virtualSubscribes: zod_1.z.array(zod_1.z.string()),
55
+ flows: zod_1.z.array(zod_1.z.string()).optional(),
56
+ })
57
+ .strict();
58
+ const eventSchema = zod_1.z
59
+ .object({
60
+ type: zod_1.z.literal('event'),
61
+ name: zod_1.z.string(),
62
+ description: zod_1.z.string().optional(),
63
+ subscribes: zod_1.z.array(zod_1.z.string()),
64
+ emits: emits,
65
+ virtualEmits: emits.optional(),
66
+ input: zod_1.z.union([jsonSchema, zod_1.z.object({}), zod_1.z.null()]).optional(),
67
+ flows: zod_1.z.array(zod_1.z.string()).optional(),
68
+ includeFiles: zod_1.z.array(zod_1.z.string()).optional(),
69
+ })
70
+ .strict();
71
+ const apiSchema = zod_1.z
72
+ .object({
73
+ type: zod_1.z.literal('api'),
74
+ name: zod_1.z.string(),
75
+ description: zod_1.z.string().optional(),
76
+ path: zod_1.z.string(),
77
+ method: zod_1.z.string(),
78
+ emits: emits,
79
+ virtualEmits: emits.optional(),
80
+ virtualSubscribes: zod_1.z.array(zod_1.z.string()).optional(),
81
+ flows: zod_1.z.array(zod_1.z.string()).optional(),
82
+ includeFiles: zod_1.z.array(zod_1.z.string()).optional(),
83
+ middleware: zod_1.z.array(zod_1.z.any()).optional(),
84
+ queryParams: zod_1.z.array(zod_1.z.object({ name: zod_1.z.string(), description: zod_1.z.string().optional() })).optional(),
85
+ bodySchema: zod_1.z.union([jsonSchema, zod_1.z.object({}), zod_1.z.null()]).optional(),
86
+ responseSchema: zod_1.z.record(zod_1.z.string(), jsonSchema).optional(),
87
+ })
88
+ .strict();
89
+ const cronSchema = zod_1.z
90
+ .object({
91
+ type: zod_1.z.literal('cron'),
92
+ name: zod_1.z.string(),
93
+ description: zod_1.z.string().optional(),
94
+ cron: zod_1.z.string(),
95
+ virtualEmits: emits.optional(),
96
+ emits: emits,
97
+ flows: zod_1.z.array(zod_1.z.string()).optional(),
98
+ includeFiles: zod_1.z.array(zod_1.z.string()).optional(),
99
+ })
100
+ .strict();
101
+ const validateStep = (step) => {
102
+ try {
103
+ if (step.config.type === 'noop') {
104
+ noopSchema.parse(step.config);
105
+ }
106
+ else if (step.config.type === 'event') {
107
+ eventSchema.parse(step.config);
108
+ }
109
+ else if (step.config.type === 'api') {
110
+ apiSchema.parse(step.config);
111
+ }
112
+ else if (step.config.type === 'cron') {
113
+ cronSchema.parse(step.config);
114
+ }
115
+ else {
116
+ return {
117
+ success: false,
118
+ error: 'Invalid step type',
119
+ };
120
+ }
121
+ return { success: true };
122
+ }
123
+ catch (error) {
124
+ if (error instanceof zod_1.z.ZodError) {
125
+ return {
126
+ success: false,
127
+ error: error.errors.map((err) => err.message).join(', '),
128
+ errors: error.errors.map((err) => ({ path: err.path.join('.'), message: err.message })),
129
+ };
130
+ }
131
+ // Handle unexpected errors
132
+ return {
133
+ success: false,
134
+ error: 'Unexpected validation error occurred',
135
+ };
136
+ }
137
+ };
138
+ exports.validateStep = validateStep;
@@ -0,0 +1,11 @@
1
+ import { ApiResponse, ApiRouteConfig, ApiRouteHandler } from '../types';
2
+ export declare const config: ApiRouteConfig;
3
+ type EmitData = {
4
+ topic: string;
5
+ data: Record<string, unknown>;
6
+ };
7
+ export declare const handler: ApiRouteHandler<EmitData, ApiResponse<200, {
8
+ success: true;
9
+ emitted: EmitData;
10
+ }>, EmitData>;
11
+ export {};
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.handler = exports.config = void 0;
4
+ const zod_1 = require("zod");
5
+ exports.config = {
6
+ type: 'api',
7
+ name: 'Event Emitter',
8
+ description: 'System endpoint for emitting events',
9
+ path: '/emit',
10
+ method: 'POST',
11
+ emits: [], // Dynamic emissions
12
+ flows: ['_system'],
13
+ bodySchema: zod_1.z.object({
14
+ topic: zod_1.z.string(),
15
+ data: zod_1.z.record(zod_1.z.unknown()),
16
+ }),
17
+ };
18
+ const handler = async (req, { emit, logger }) => {
19
+ const { topic, data } = req.body;
20
+ logger.info('[Event Emitter] Emitting event', { topic, data });
21
+ await emit({ topic, data });
22
+ return {
23
+ status: 200,
24
+ body: { success: true, emitted: { topic, data } },
25
+ };
26
+ };
27
+ exports.handler = handler;
@@ -0,0 +1,34 @@
1
+ import { ApiResponse, ApiRouteConfig, ApiRouteHandler } from '../types'
2
+ import { z } from 'zod'
3
+
4
+ export const config: ApiRouteConfig = {
5
+ type: 'api',
6
+ name: 'Event Emitter',
7
+ description: 'System endpoint for emitting events',
8
+ path: '/emit',
9
+ method: 'POST',
10
+ emits: [], // Dynamic emissions
11
+ flows: ['_system'],
12
+ bodySchema: z.object({
13
+ topic: z.string(),
14
+ data: z.record(z.unknown()),
15
+ }),
16
+ }
17
+
18
+ type EmitData = { topic: string; data: Record<string, unknown> }
19
+
20
+ export const handler: ApiRouteHandler<
21
+ EmitData,
22
+ ApiResponse<200, { success: true; emitted: EmitData }>,
23
+ EmitData
24
+ > = async (req, { emit, logger }) => {
25
+ const { topic, data } = req.body
26
+
27
+ logger.info('[Event Emitter] Emitting event', { topic, data })
28
+ await emit({ topic, data })
29
+
30
+ return {
31
+ status: 200,
32
+ body: { success: true, emitted: { topic, data } },
33
+ }
34
+ }
@@ -0,0 +1,2 @@
1
+ import { Step } from '../types';
2
+ export declare const systemSteps: Step[];
@@ -0,0 +1,16 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.systemSteps = void 0;
7
+ const path_1 = __importDefault(require("path"));
8
+ const emit_step_1 = require("./emit.step");
9
+ exports.systemSteps = [
10
+ {
11
+ // NOTE: this is the path of the file inside the dist folder
12
+ filePath: path_1.default.join(__dirname, 'emit.step.js'),
13
+ version: '1',
14
+ config: emit_step_1.config,
15
+ },
16
+ ];
@@ -0,0 +1,2 @@
1
+ import { LockedData } from '../locked-data';
2
+ export declare const apiEndpoints: (lockedData: LockedData) => void;
@@ -0,0 +1,71 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.apiEndpoints = void 0;
4
+ const guards_1 = require("../guards");
5
+ const state_stream_1 = require("../state-stream");
6
+ const mapEndpoint = (step) => {
7
+ return {
8
+ id: step.filePath,
9
+ method: step.config.method,
10
+ path: step.config.path,
11
+ description: step.config.description,
12
+ queryParams: step.config.queryParams,
13
+ responseSchema: step.config.responseSchema,
14
+ bodySchema: step.config.bodySchema,
15
+ };
16
+ };
17
+ class ApiEndpointsStream extends state_stream_1.StateStream {
18
+ constructor(lockedData) {
19
+ super();
20
+ this.lockedData = lockedData;
21
+ }
22
+ async get(id) {
23
+ const endpoint = this.lockedData.apiSteps().find((step) => step.config.path === id);
24
+ return endpoint ? mapEndpoint(endpoint) : null;
25
+ }
26
+ async delete(id) {
27
+ return { id };
28
+ }
29
+ async set(_, __, data) {
30
+ return data;
31
+ }
32
+ async getGroup() {
33
+ return this.lockedData.apiSteps().map(mapEndpoint);
34
+ }
35
+ }
36
+ const apiEndpoints = (lockedData) => {
37
+ const stream = lockedData.createStream({
38
+ filePath: '__motia.api-endpoints.ts',
39
+ hidden: true,
40
+ config: {
41
+ name: '__motia.api-endpoints',
42
+ baseConfig: { storageType: 'custom', factory: () => new ApiEndpointsStream(lockedData) },
43
+ schema: null,
44
+ },
45
+ })();
46
+ const apiStepCreated = (step) => {
47
+ if ((0, guards_1.isApiStep)(step)) {
48
+ stream.set('default', step.filePath, {
49
+ id: step.filePath,
50
+ method: step.config.method,
51
+ path: step.config.path,
52
+ description: step.config.description,
53
+ queryParams: step.config.queryParams,
54
+ });
55
+ }
56
+ };
57
+ const apiStepUpdated = (step) => {
58
+ if ((0, guards_1.isApiStep)(step)) {
59
+ stream.set('default', step.filePath, mapEndpoint(step));
60
+ }
61
+ };
62
+ const apiStepRemoved = (step) => {
63
+ if ((0, guards_1.isApiStep)(step)) {
64
+ stream.delete('default', step.filePath);
65
+ }
66
+ };
67
+ lockedData.onStep('step-created', apiStepCreated);
68
+ lockedData.onStep('step-updated', apiStepUpdated);
69
+ lockedData.onStep('step-removed', apiStepRemoved);
70
+ };
71
+ exports.apiEndpoints = apiEndpoints;
@@ -0,0 +1,14 @@
1
+ import { LockedData } from '../locked-data';
2
+ import { StateStream } from '../state-stream';
3
+ export type Flow = {
4
+ id: string;
5
+ name: string;
6
+ };
7
+ export declare class FlowsStream extends StateStream<Flow> {
8
+ private readonly lockedData;
9
+ constructor(lockedData: LockedData);
10
+ get(id: string): Promise<Flow | null>;
11
+ delete(id: string): Promise<Flow | null>;
12
+ set(_: string, __: string, data: Flow): Promise<Flow>;
13
+ getGroup(): Promise<Flow[]>;
14
+ }
@@ -0,0 +1,29 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.FlowsStream = void 0;
4
+ const state_stream_1 = require("../state-stream");
5
+ class FlowsStream extends state_stream_1.StateStream {
6
+ constructor(lockedData) {
7
+ super();
8
+ this.lockedData = lockedData;
9
+ }
10
+ async get(id) {
11
+ return (Object.entries(this.lockedData.flows)
12
+ .map(([id, flow]) => ({ id, name: flow.name }))
13
+ .find((flow) => flow.id === id) ?? null);
14
+ }
15
+ async delete(id) {
16
+ return { id, name: id };
17
+ }
18
+ async set(_, __, data) {
19
+ return data;
20
+ }
21
+ async getGroup() {
22
+ /**
23
+ * Get list should receive a groupId argument but that's irrelevant for this stream
24
+ * since we only have one group of flows.
25
+ */
26
+ return Object.entries(this.lockedData.flows).map(([id, flow]) => ({ id, name: flow.name }));
27
+ }
28
+ }
29
+ exports.FlowsStream = FlowsStream;
@@ -0,0 +1,16 @@
1
+ import { StateStream } from '../state-stream';
2
+ export type Log = {
3
+ id: string;
4
+ level: string;
5
+ time: number;
6
+ msg: string;
7
+ traceId: string;
8
+ flows: string[];
9
+ [key: string]: any;
10
+ };
11
+ export declare class LogsStream extends StateStream<Log> {
12
+ get: () => Promise<null>;
13
+ delete: () => Promise<null>;
14
+ getGroup: () => Promise<never[]>;
15
+ set(_: string, __: string, data: Log): Promise<Log>;
16
+ }
@@ -0,0 +1,22 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LogsStream = void 0;
4
+ const state_stream_1 = require("../state-stream");
5
+ /*
6
+ * We're not storing logs in the state because of size of data
7
+ * if process stays for to long it would consume too much memory
8
+ * in this case, we're just streaming through events.
9
+ */
10
+ class LogsStream extends state_stream_1.StateStream {
11
+ constructor() {
12
+ super(...arguments);
13
+ this.get = async () => null;
14
+ this.delete = async () => null;
15
+ this.getGroup = async () => [];
16
+ }
17
+ async set(_, __, data) {
18
+ await this.send({ groupId: 'default' }, { type: 'log', data });
19
+ return data;
20
+ }
21
+ }
22
+ exports.LogsStream = LogsStream;