@ondc/automation-mock-runner 0.0.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 (43) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +372 -0
  3. package/dist/index.d.ts +18 -0
  4. package/dist/index.js +43 -0
  5. package/dist/lib/MockRunner.d.ts +18 -0
  6. package/dist/lib/MockRunner.js +335 -0
  7. package/dist/lib/configHelper.d.ts +2 -0
  8. package/dist/lib/configHelper.js +101 -0
  9. package/dist/lib/constants/function-registry.d.ts +26 -0
  10. package/dist/lib/constants/function-registry.js +132 -0
  11. package/dist/lib/runners/base-runner.d.ts +6 -0
  12. package/dist/lib/runners/base-runner.js +6 -0
  13. package/dist/lib/runners/browser-runner.d.ts +12 -0
  14. package/dist/lib/runners/browser-runner.js +91 -0
  15. package/dist/lib/runners/node-runner.d.ts +16 -0
  16. package/dist/lib/runners/node-runner.js +189 -0
  17. package/dist/lib/runners/runner-factory.d.ts +25 -0
  18. package/dist/lib/runners/runner-factory.js +113 -0
  19. package/dist/lib/types/execution-results.d.ts +30 -0
  20. package/dist/lib/types/execution-results.js +2 -0
  21. package/dist/lib/types/mock-config.d.ts +107 -0
  22. package/dist/lib/types/mock-config.js +52 -0
  23. package/dist/lib/utils/errors.d.ts +47 -0
  24. package/dist/lib/utils/errors.js +84 -0
  25. package/dist/lib/utils/input-validator.d.ts +18 -0
  26. package/dist/lib/utils/input-validator.js +146 -0
  27. package/dist/lib/utils/logger.d.ts +36 -0
  28. package/dist/lib/utils/logger.js +86 -0
  29. package/dist/lib/utils/performance-monitor.d.ts +34 -0
  30. package/dist/lib/utils/performance-monitor.js +98 -0
  31. package/dist/lib/utils/validateConfig.d.ts +6 -0
  32. package/dist/lib/utils/validateConfig.js +16 -0
  33. package/dist/lib/validators/code-validator.d.ts +30 -0
  34. package/dist/lib/validators/code-validator.js +327 -0
  35. package/dist/lib/worker/worker-factory.d.ts +3 -0
  36. package/dist/lib/worker/worker-factory.js +81 -0
  37. package/dist/test/MockRunner.test.d.ts +4 -0
  38. package/dist/test/MockRunner.test.js +144 -0
  39. package/dist/test/__mocks__/uuid.d.ts +5 -0
  40. package/dist/test/__mocks__/uuid.js +8 -0
  41. package/dist/test/setup.d.ts +3 -0
  42. package/dist/test/setup.js +43 -0
  43. package/package.json +84 -0
package/LICENSE ADDED
@@ -0,0 +1,15 @@
1
+ ISC License
2
+
3
+ Copyright (c) 2024, ONDC Automation Team
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10
+ WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11
+ MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
12
+ ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13
+ WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14
+ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
15
+ OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,372 @@
1
+ # ONDC Automation Mock Runner
2
+
3
+ A robust TypeScript library designed for testing and validating ONDC (Open Network for Digital Commerce) transaction flows. This tool helps developers build reliable ONDC integrations by providing a comprehensive framework for generating, validating, and testing API payloads across different transaction scenarios.
4
+
5
+ ## What is this?
6
+
7
+ When building applications that integrate with the ONDC network, you need to handle complex multi-step transaction flows where each API call depends on data from previous steps. This library provides a structured way to:
8
+
9
+ - **Generate realistic test payloads** for ONDC APIs (search, select, init, confirm, etc.)
10
+ - **Validate incoming requests** against your business logic
11
+ - **Check prerequisites** before proceeding with each transaction step
12
+ - **Maintain session state** across the entire transaction flow
13
+
14
+ The core concept is simple: define your transaction flow once, then let the runner handle payload generation, validation, and state management automatically.
15
+
16
+ ## Key Features
17
+
18
+ ### ๐Ÿ”„ Transaction Flow Management
19
+
20
+ - Define multi-step ONDC transaction flows with dependencies between steps
21
+ - Automatic context generation with proper ONDC headers and metadata
22
+ - Session data persistence across transaction steps
23
+
24
+ ### ๐Ÿงช Secure Code Execution
25
+
26
+ - Safe execution of custom JavaScript functions for payload generation and validation
27
+ - Multiple execution environments: Node.js worker threads, VM sandboxes, or browser workers
28
+ - Built-in timeout protection and error isolation
29
+
30
+ ### โœ… Schema Validation
31
+
32
+ - Zod-based configuration validation
33
+ - Runtime type checking for all inputs and outputs
34
+ - Detailed error reporting with line-by-line feedback
35
+
36
+ ### ๐ŸŽฏ ONDC-Specific Features
37
+
38
+ - Built-in support for BAP (Buyer App) and BPP (Seller App) roles
39
+ - Automatic message ID correlation for request-response pairs
40
+ - Version-aware context generation (supports ONDC v1.x and v2.x)
41
+
42
+ ## Installation
43
+
44
+ ```bash
45
+ npm install @ondc/automation-mock-runner
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ Here's how to set up a basic ONDC search-to-confirm flow:
51
+
52
+ ```typescript
53
+ import { MockRunner } from "@ondc/automation-mock-runner";
54
+
55
+ // Define your transaction configuration
56
+ const config = {
57
+ meta: {
58
+ domain: "retail",
59
+ version: "1.2.0",
60
+ flowId: "search-select-init-confirm",
61
+ },
62
+ transaction_data: {
63
+ transaction_id: "uuid-here",
64
+ latest_timestamp: new Date().toISOString(),
65
+ bap_id: "buyer-app.example.com",
66
+ bap_uri: "https://buyer-app.example.com",
67
+ bpp_id: "seller-app.example.com",
68
+ bpp_uri: "https://seller-app.example.com",
69
+ },
70
+ steps: [
71
+ {
72
+ api: "search",
73
+ action_id: "search_001",
74
+ owner: "BAP",
75
+ responseFor: null,
76
+ unsolicited: false,
77
+ description: "Search for products in electronics category",
78
+ mock: {
79
+ generate: `
80
+ // Add search intent to the payload
81
+ defaultPayload.message = {
82
+ intent: {
83
+ category: { descriptor: { name: "Electronics" } },
84
+ location: { country: { code: "IND" }, city: { code: "std:080" } }
85
+ }
86
+ };
87
+ return defaultPayload;
88
+ `,
89
+ validate: `
90
+ if (!targetPayload.message?.catalog?.providers?.length) {
91
+ return { valid: false, code: 400, description: "No providers found" };
92
+ }
93
+ return { valid: true, code: 200, description: "Valid catalog response" };
94
+ `,
95
+ requirements: `return { valid: true, code: 200, description: "Ready to search" };`,
96
+ defaultPayload: { context: {}, message: {} },
97
+ saveData: {
98
+ providers: "$.message.catalog.providers",
99
+ },
100
+ inputs: {},
101
+ },
102
+ },
103
+ ],
104
+ transaction_history: [],
105
+ validationLib: "",
106
+ helperLib: "",
107
+ };
108
+
109
+ // Initialize the runner
110
+ const runner = new MockRunner(config);
111
+
112
+ // Generate a search payload
113
+ const searchResult = await runner.runGeneratePayload("search_001", {});
114
+ console.log("Generated search payload:", searchResult.result);
115
+
116
+ // Validate a response
117
+ const validationResult = await runner.runValidatePayload(
118
+ "search_001",
119
+ responsePayload
120
+ );
121
+ console.log("Validation passed:", validationResult.success);
122
+ ```
123
+
124
+ ## Configuration Structure
125
+
126
+ ### Transaction Metadata
127
+
128
+ ```typescript
129
+ meta: {
130
+ domain: string, // ONDC domain (retail, mobility, etc.)
131
+ version: string, // ONDC version (1.2.0, 2.0.0, etc.)
132
+ flowId: string // Unique identifier for this flow
133
+ }
134
+ ```
135
+
136
+ ### Transaction Data
137
+
138
+ ```typescript
139
+ transaction_data: {
140
+ transaction_id: string, // UUID for this transaction
141
+ latest_timestamp: string, // ISO timestamp
142
+ bap_id?: string, // Buyer app ID
143
+ bap_uri?: string, // Buyer app URI
144
+ bpp_id?: string, // Seller app ID
145
+ bpp_uri?: string // Seller app URI
146
+ }
147
+ ```
148
+
149
+ ### Action Steps
150
+
151
+ Each step represents one API call in your transaction flow:
152
+
153
+ ```typescript
154
+ {
155
+ api: "search" | "select" | "init" | "confirm" | "on_search" | "on_select" | ...,
156
+ action_id: string, // Unique ID for this step
157
+ owner: "BAP" | "BPP", // Who initiates this call
158
+ responseFor: string | null, // If this responds to another action
159
+ unsolicited: boolean, // Whether this is an unsolicited call
160
+ description: string, // Human-readable description
161
+ mock: {
162
+ generate: string, // JavaScript code to generate payload
163
+ validate: string, // JavaScript code to validate response
164
+ requirements: string, // JavaScript code to check prerequisites
165
+ defaultPayload: object, // Base payload structure
166
+ saveData: object, // JSONPath expressions to save data
167
+ inputs: object // Input schema for user data
168
+ }
169
+ }
170
+ ```
171
+
172
+ ## Advanced Usage
173
+
174
+ ### Chaining Transaction Steps
175
+
176
+ ```typescript
177
+ const steps = [
178
+ {
179
+ api: "search",
180
+ action_id: "search_001",
181
+ // ... search configuration
182
+ mock: {
183
+ saveData: {
184
+ selectedProvider: "$.message.catalog.providers[0]",
185
+ },
186
+ // ...
187
+ },
188
+ },
189
+ {
190
+ api: "select",
191
+ action_id: "select_001",
192
+ // ... select configuration
193
+ mock: {
194
+ generate: `
195
+ // Use data from previous search step
196
+ const provider = sessionData.selectedProvider;
197
+ defaultPayload.message = {
198
+ order: {
199
+ provider: { id: provider.id },
200
+ items: [{ id: provider.items[0].id, quantity: { count: 1 } }]
201
+ }
202
+ };
203
+ return defaultPayload;
204
+ `,
205
+ // ...
206
+ },
207
+ },
208
+ ];
209
+ ```
210
+
211
+ ### Custom Validation Logic
212
+
213
+ ```typescript
214
+ const validatePayload = `
215
+ // Check if order total matches expected amount
216
+ const expectedTotal = sessionData.calculatedTotal;
217
+ const actualTotal = targetPayload.message.order.quote.total;
218
+
219
+ if (Math.abs(expectedTotal - actualTotal) > 0.01) {
220
+ return {
221
+ valid: false,
222
+ code: 400,
223
+ description: \`Total mismatch: expected \${expectedTotal}, got \${actualTotal}\`
224
+ };
225
+ }
226
+
227
+ return { valid: true, code: 200, description: "Order total validated" };
228
+ `;
229
+ ```
230
+
231
+ ### User Input Handling
232
+
233
+ ```typescript
234
+ const stepWithInputs = {
235
+ // ... other config
236
+ mock: {
237
+ generate: `
238
+ // Access user inputs
239
+ const { email, deliveryAddress } = sessionData.user_inputs;
240
+
241
+ defaultPayload.message.order.billing = {
242
+ email: email,
243
+ address: deliveryAddress
244
+ };
245
+
246
+ return defaultPayload;
247
+ `,
248
+ inputs: {
249
+ id: "user_details",
250
+ jsonSchema: {
251
+ type: "object",
252
+ properties: {
253
+ email: { type: "string", format: "email" },
254
+ deliveryAddress: { type: "string", minLength: 10 },
255
+ },
256
+ required: ["email", "deliveryAddress"],
257
+ },
258
+ },
259
+ },
260
+ };
261
+ ```
262
+
263
+ ## API Reference
264
+
265
+ ### MockRunner
266
+
267
+ #### Constructor
268
+
269
+ ```typescript
270
+ new MockRunner(config: MockPlaygroundConfigType)
271
+ ```
272
+
273
+ #### Methods
274
+
275
+ **`validateConfig()`**
276
+ Validates the entire configuration against the schema.
277
+
278
+ ```typescript
279
+ const validation = runner.validateConfig();
280
+ if (!validation.success) {
281
+ console.log("Config errors:", validation.errors);
282
+ }
283
+ ```
284
+
285
+ **`runGeneratePayload(actionId: string, inputs: any)`**
286
+ Generates a payload for the specified action step.
287
+
288
+ ```typescript
289
+ const result = await runner.runGeneratePayload("search_001", {
290
+ category: "books",
291
+ });
292
+ ```
293
+
294
+ **`runValidatePayload(actionId: string, targetPayload: any)`**
295
+ Validates an incoming payload against the specified action step.
296
+
297
+ ```typescript
298
+ const result = await runner.runValidatePayload(
299
+ "on_search_001",
300
+ responsePayload
301
+ );
302
+ ```
303
+
304
+ **`runMeetRequirements(actionId: string, targetPayload: any)`**
305
+ Checks if prerequisites are met before proceeding with an action.
306
+
307
+ ```typescript
308
+ const result = await runner.runMeetRequirements("select_001", {});
309
+ ```
310
+
311
+ **`getDefaultStep(api: string, actionId: string)`**
312
+ Creates a new step configuration with sensible defaults.
313
+
314
+ ```typescript
315
+ const newStep = runner.getDefaultStep("search", "search_002");
316
+ ```
317
+
318
+ ## Error Handling
319
+
320
+ The library provides detailed error information for debugging:
321
+
322
+ ```typescript
323
+ const result = await runner.runGeneratePayload("invalid_step", {});
324
+
325
+ if (!result.success) {
326
+ console.log("Error:", result.error.message);
327
+ console.log("Logs:", result.logs);
328
+ console.log("Execution time:", result.executionTime);
329
+ }
330
+ ```
331
+
332
+ Common error types:
333
+
334
+ - **ValidationError**: Configuration or input validation failed
335
+ - **PayloadGenerationError**: Error in payload generation code
336
+ - **PayloadValidationError**: Error in validation code
337
+ - **MeetRequirementsError**: Error in requirements check code
338
+ - **TimeoutError**: Code execution exceeded timeout limit
339
+
340
+ ## Testing
341
+
342
+ The library includes comprehensive tests. Run them with:
343
+
344
+ ```bash
345
+ npm test # Run all tests
346
+ npm run test:watch # Run tests in watch mode
347
+ npm run test:coverage # Generate coverage report
348
+ ```
349
+
350
+ ## Security Considerations
351
+
352
+ - All user code runs in isolated environments (worker threads or VM sandboxes)
353
+ - Dangerous functions like `eval`, `require`, and file system access are blocked
354
+ - Execution timeouts prevent infinite loops
355
+ - Memory limits prevent resource exhaustion
356
+
357
+ ## Contributing
358
+
359
+ This library is built for the ONDC ecosystem. When contributing:
360
+
361
+ 1. Ensure all tests pass: `npm test`
362
+ 2. Follow the existing code style: `npm run lint`
363
+ 3. Add tests for new features
364
+ 4. Update documentation for API changes
365
+
366
+ ## License
367
+
368
+ ISC License - see LICENSE file for details.
369
+
370
+ ## Support
371
+
372
+ For ONDC-specific questions, refer to the [ONDC documentation](https://ondc.org/). For issues with this library, please file an issue on the repository.
@@ -0,0 +1,18 @@
1
+ /**
2
+ * @ondc/automation-mock-runner
3
+ * A TypeScript library for ONDC automation mock runner
4
+ */
5
+ export * from "./lib/MockRunner";
6
+ export * from "./lib/types/mock-config";
7
+ export * from "./lib/types/execution-results";
8
+ export * from "./lib/utils/validateConfig";
9
+ export * from "./lib/utils/logger";
10
+ export * from "./lib/utils/errors";
11
+ export { InputValidator, ValidationResult as InputValidationResult } from "./lib/utils/input-validator";
12
+ export * from "./lib/utils/performance-monitor";
13
+ export * from "./lib/constants/function-registry";
14
+ export * from "./lib/runners/base-runner";
15
+ export * from "./lib/runners/runner-factory";
16
+ export { MockRunner as default } from "./lib/MockRunner";
17
+ export * from "./lib/constants/function-registry";
18
+ export * from "./lib/configHelper";
package/dist/index.js ADDED
@@ -0,0 +1,43 @@
1
+ "use strict";
2
+ /**
3
+ * @ondc/automation-mock-runner
4
+ * A TypeScript library for ONDC automation mock runner
5
+ */
6
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
7
+ if (k2 === undefined) k2 = k;
8
+ var desc = Object.getOwnPropertyDescriptor(m, k);
9
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
10
+ desc = { enumerable: true, get: function() { return m[k]; } };
11
+ }
12
+ Object.defineProperty(o, k2, desc);
13
+ }) : (function(o, m, k, k2) {
14
+ if (k2 === undefined) k2 = k;
15
+ o[k2] = m[k];
16
+ }));
17
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
18
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
19
+ };
20
+ Object.defineProperty(exports, "__esModule", { value: true });
21
+ exports.default = exports.InputValidator = void 0;
22
+ // Core exports
23
+ __exportStar(require("./lib/MockRunner"), exports);
24
+ // Type definitions
25
+ __exportStar(require("./lib/types/mock-config"), exports);
26
+ __exportStar(require("./lib/types/execution-results"), exports);
27
+ // Utilities
28
+ __exportStar(require("./lib/utils/validateConfig"), exports);
29
+ __exportStar(require("./lib/utils/logger"), exports);
30
+ __exportStar(require("./lib/utils/errors"), exports);
31
+ var input_validator_1 = require("./lib/utils/input-validator");
32
+ Object.defineProperty(exports, "InputValidator", { enumerable: true, get: function () { return input_validator_1.InputValidator; } });
33
+ __exportStar(require("./lib/utils/performance-monitor"), exports);
34
+ // Constants
35
+ __exportStar(require("./lib/constants/function-registry"), exports);
36
+ // Runners (for advanced usage)
37
+ __exportStar(require("./lib/runners/base-runner"), exports);
38
+ __exportStar(require("./lib/runners/runner-factory"), exports);
39
+ // Default export
40
+ var MockRunner_1 = require("./lib/MockRunner");
41
+ Object.defineProperty(exports, "default", { enumerable: true, get: function () { return MockRunner_1.MockRunner; } });
42
+ __exportStar(require("./lib/constants/function-registry"), exports);
43
+ __exportStar(require("./lib/configHelper"), exports);
@@ -0,0 +1,18 @@
1
+ import { MockPlaygroundConfigType } from "./types/mock-config";
2
+ import { ExecutionResult } from "./types/execution-results";
3
+ export declare class MockRunner {
4
+ private config;
5
+ private runner;
6
+ private logger;
7
+ constructor(config: MockPlaygroundConfigType);
8
+ validateConfig(): {
9
+ success: boolean;
10
+ errors?: import("zod/v4/core").$ZodIssue[];
11
+ };
12
+ runGeneratePayload(actionId: string, inputs?: any): Promise<ExecutionResult>;
13
+ runValidatePayload(actionId: string, targetPayload: any): Promise<ExecutionResult>;
14
+ runMeetRequirements(actionId: string, targetPayload: any): Promise<ExecutionResult>;
15
+ getDefaultStep(api: string, actionId: string): MockPlaygroundConfigType["steps"][0];
16
+ generateContext(actionId: string, action: string): any;
17
+ getSessionDataUpToStep(index: number, config: MockPlaygroundConfigType): Record<string, any>;
18
+ }