jsfe 0.1.0

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.
package/README.md ADDED
@@ -0,0 +1,783 @@
1
+ # JSFE — JavaScript Flow Engine
2
+
3
+ ESM TypeScript library for workflow + tool orchestration.
4
+
5
+ ## Install
6
+ \`\`\`bash
7
+ npm i jsfe
8
+ \`\`\`
9
+
10
+ ## 📖 Documentation
11
+
12
+ - **[JavaScript Flow Engine User Guide](JavaScript%20Flow%20Engine.md)** - Comprehensive tutorials, examples, and best practices
13
+ - **[README.md](README.md)** - Technical API reference (this document)
14
+
15
+ *For detailed tutorials, step-by-step examples, and comprehensive workflow patterns, see the **[User Guide](JavaScript%20Flow%20Engine.md)**.*
16
+
17
+ ## Usage
18
+ \`\`\`ts
19
+ import { WorkflowEngine } from "jsfe";
20
+ const engine = new WorkflowEngine(
21
+ hostLogger: Logger, // logger instance like winston - supporting .info/.debug/.warn/.error methods
22
+ aiCallback: AiCallbackFunction, // host provided access to AI fetch function aiFetcher(systemInstructions, userMessage) -> response string
23
+ flowsMenu: FlowDefinition[], // host defined available flows
24
+ toolsRegistry: ToolDefinition[], // host defined tools registry
25
+ APPROVED_FUNCTIONS: ApprovedFunctions, // Optional host provided safe functions map
26
+ globalVariables?: Record<string, unknown> // Optional global variables shared across all new flows
27
+ validateOnInit: boolean = true, // Optional validate all flows an enggine initialization
28
+ language?: string, // Optional language code
29
+ messageRegistry?: MessageRegistry, // Optional override all engine internationalized messages
30
+ guidanceConfig?: GuidanceConfig, // Optional overide default internationalized guidance prompts
31
+ );
32
+
33
+ \`\`\`
34
+
35
+ /*
36
+ ==========================================
37
+ ENHANCED FLOW ENGINE ARCHITECTURE OVERVIEW
38
+ ==========================================
39
+
40
+ MAJOR DESIGN ENHANCEMENT: Stack-of-Stacks Architecture for Flow Interruption/Resumption
41
+
42
+ This Flow Engine implements a sophisticated "stack-of-stacks" architecture that allows flows to be
43
+ suspended and resumed, enabling users to naturally interrupt one workflow to handle another task,
44
+ then return to their original workflow seamlessly.
45
+
46
+ ==========================================
47
+ CORE ARCHITECTURE COMPONENTS
48
+ ==========================================
49
+
50
+ 1. STACK-OF-STACKS DESIGN:
51
+ - Multiple independent flow execution stacks
52
+ - Active stack index tracks current execution context
53
+ - Automatic stack switching for flow interruption/resumption
54
+ - Proper isolation between different workflow contexts
55
+
56
+ 2. FLOW FRAME STRUCTURE:
57
+ Each flow execution maintains a complete context frame:
58
+ - flowName, flowId, flowVersion: Flow identity and versioning
59
+ - flowStepsStack: Remaining steps (reversed for efficient pop operations)
60
+ - contextStack: Complete history of inputs and responses
61
+ - inputStack: Current input context for step execution
62
+ - variables: Unified flat variable storage (shared across sub-flows)
63
+ - transaction: Comprehensive transaction management and audit trail
64
+ - userId, startTime: User context and timing metadata
65
+
66
+ 3. HELPER FUNCTION ARCHITECTURE:
67
+ All stack operations go through centralized helper functions:
68
+ - initializeFlowStacks(engine): Ensures proper structure
69
+ - getCurrentStack(engine): Gets currently active stack
70
+ - getCurrentStackLength(engine): Safe length checking
71
+ - pushToCurrentStack(engine, frame): Adds flow to active stack
72
+ - popFromCurrentStack(engine): Removes flow from active stack
73
+ - createNewStack(engine): Creates new stack for interruptions
74
+ - switchToPreviousStack(engine): Returns to previous context
75
+
76
+ ==========================================
77
+ DATA STRUCTURES & PROPERTIES
78
+ ==========================================
79
+
80
+ FLOW FRAME PROPERTIES:
81
+ {
82
+ flowName: string, // Human-readable flow name
83
+ flowId: string, // Unique flow identifier
84
+ flowVersion: string, // Flow version for compatibility
85
+ flowStepsStack: [...], // Remaining steps (reversed)
86
+ contextStack: [...], // Complete interaction history
87
+ inputStack: [...], // Current input context
88
+ variables: {}, // Unified variable storage
89
+ transaction: TransactionObj, // Audit and transaction tracking
90
+ userId: string, // User identifier
91
+ startTime: number, // Flow start timestamp
92
+ pendingVariable: string, // Variable awaiting user input
93
+ lastSayMessage: string, // Last SAY step output
94
+ pendingInterruption: {} // Interruption state management
95
+ }
96
+
97
+ ========================================
98
+ SUPPORTED FEATURES & CAPABILITIES
99
+ ========================================
100
+
101
+ FLOW EXECUTION MODES:
102
+ ✅ Linear Flow Execution - Sequential step processing
103
+ ✅ Sub-Flow Calls - Nested workflow execution
104
+ ✅ Flow Interruption - Suspend current flow for new task
105
+ ✅ Flow Resumption - Return to previously suspended flows
106
+ ✅ Flow Replacement - Replace current flow with new flow
107
+ ✅ Flow Reboot - Nuclear option: clear all flows and restart
108
+
109
+ CALL TYPE BEHAVIORS:
110
+ ✅ "call" (default) - Normal sub-flow, preserves parent on stack
111
+ ✅ "replace" - Replace current flow with new flow
112
+ ✅ "reboot" - Clear entire stack and start fresh (emergency recovery)
113
+
114
+ STEP TYPE SUPPORT:
115
+ ✅ SAY - Non-blocking output messages (accumulated)
116
+ ✅ SAY-GET - Blocking output with user input request
117
+ ✅ SET - Variable assignment with interpolation support
118
+ ✅ CALL-TOOL - External tool execution with error handling
119
+ ✅ FLOW - Sub-flow execution with multiple call types
120
+ ✅ SWITCH - Enhanced conditional branching with expressions
121
+
122
+ ADVANCED SWITCH CONDITIONS:
123
+ ✅ Exact Value Matching - Traditional switch behavior
124
+ ✅ Expression Evaluation - Dynamic condition evaluation using safe JavaScript expressions
125
+ ✅ Mixed Branches - Combine exact matches with conditions
126
+ ✅ Secure Evaluation - No eval(), no code injection, safe expression parsing
127
+ ✅ Expression Templates - {{variable + otherVar}} and {{complex.expression > threshold}} support
128
+
129
+ EXPRESSION TEMPLATE SYSTEM:
130
+ The engine supports safe JavaScript expressions within {{}} templates:
131
+ - Simple variables: {{userName}}, {{account.balance}}
132
+ - Arithmetic: {{amount + fee}}, {{price * quantity}}
133
+ - Comparisons: {{age >= 18}}, {{status === 'active'}}
134
+ - Logical: {{isAdmin && hasAccess}}, {{retryCount < maxRetries}}
135
+ - Complex: {{user.permissions.includes('admin') && creditScore > 700}}
136
+
137
+ SAFE METHOD CALLS:
138
+ The engine includes comprehensive security controls that allow only pre-approved methods:
139
+
140
+ **String Methods:**
141
+ ✅ Case conversion: toLowerCase(), toUpperCase()
142
+ ✅ Whitespace: trim(), padStart(), padEnd()
143
+ ✅ Access: charAt(), charCodeAt(), indexOf(), lastIndexOf()
144
+ ✅ Extraction: substring(), substr(), slice(), split()
145
+ ✅ Search: includes(), startsWith(), endsWith(), match(), search()
146
+ ✅ Manipulation: replace(), repeat(), concat()
147
+ ✅ Utility: toString(), valueOf(), length, localeCompare(), normalize()
148
+
149
+ **Array Methods:**
150
+ ✅ Inspection: length, includes(), indexOf(), lastIndexOf()
151
+ ✅ Extraction: slice(), join()
152
+ ✅ Conversion: toString(), valueOf()
153
+
154
+ **Math Methods:**
155
+ ✅ Basic: abs(), ceil(), floor(), round()
156
+ ✅ Comparison: max(), min()
157
+ ✅ Advanced: pow(), sqrt(), random()
158
+
159
+ **Examples:**
160
+ ```javascript
161
+ // String processing
162
+ {{userInput.toLowerCase().trim()}}
163
+ {{email.includes('@') && email.length > 5}}
164
+ {{text.substring(0, 10).padEnd(15, '...')}}
165
+
166
+ // Array operations
167
+ {{items.length > 0 && items.includes('premium')}}
168
+ {{categories.slice(0, 3).join(', ')}}
169
+
170
+ // Mathematical operations
171
+ {{Math.round(price * 1.08)}} // Tax calculation
172
+ {{Math.max(balance, 0)}} // Ensure non-negative
173
+ ```
174
+
175
+ SAFE FUNCTIONS:
176
+ ✅ **Built-in Functions:** parseInt(), parseFloat(), isNaN(), isFinite()
177
+ ✅ **Type Conversion:** String(), Number(), Boolean() (non-constructor forms)
178
+ ✅ **URI Encoding:** encodeURIComponent(), decodeURIComponent(), encodeURI(), decodeURI()
179
+ ✅ **User-Defined Functions:** Any functions registered in the APPROVED_FUNCTIONS registry
180
+
181
+ **Examples:**
182
+ ```javascript
183
+ // Type conversion and validation
184
+ {{Number(input) > 0 && !isNaN(Number(input))}}
185
+ {{Boolean(user.isActive && user.hasAccess)}}
186
+
187
+ // URI encoding for API calls
188
+ {{encodeURIComponent(searchTerm)}}
189
+
190
+ // User-defined approved functions
191
+ {{currentTime()}} // If registered as approved function
192
+ {{extractCryptoFromInput(userMessage)}} // If registered as approved function to provide Custom business logic
193
+ ```
194
+
195
+ INTELLIGENT ERROR HANDLING:
196
+ ✅ Smart Default OnFail - Context-aware error recovery
197
+ ✅ Financial Operation Protection - Special handling for sensitive flows
198
+ ✅ Network Error Recovery - Intelligent retry and messaging
199
+ ✅ Graceful Degradation - Maintain user experience during failures
200
+ ✅ Transaction Rollback - Proper cleanup on critical failures
201
+
202
+ FLOW CONTROL COMMANDS:
203
+ ✅ Universal Commands - Work in any flow context
204
+ ✅ "cancel"/"abort" - Exit current flow
205
+ ✅ "help" - Context-sensitive help messages
206
+ ✅ "status" - Current flow state information
207
+
208
+
209
+ INTENT INTERRUPTION SYSTEM:
210
+ ✅ AI-Powered Intent Detection - Recognize new workflow requests (when `aiCallback` is provided)
211
+ ✅ Fallback Flow Matching - If `aiCallback` is `null`, the engine will match the user input to a flow by id or name (case-insensitive), and if no exact match is found, will attempt a partial match. This allows demos and tests to run without requiring a real AI function.
212
+ ✅ Three-Tier Intent Strength - Weak/Medium/Strong intent classification
213
+ ✅ Financial Flow Protection - Require explicit confirmation
214
+ ✅ Graceful Interruption - Preserve context while switching
215
+ ✅ Smart Resume Logic - Automatic return to suspended flows
216
+
217
+ ---
218
+
219
+ ## ⚡️ Demo/Test Mode: Flow Matching Without AI
220
+
221
+ For demos, tests, or developer convenience, you can now set `aiCallback` to `null` when constructing the engine. In this mode, intent detection will:
222
+
223
+ 1. **Match by Flow Name or ID (case-insensitive):**
224
+ - If the user input exactly matches a flow's `name` or `id`, that flow is activated.
225
+ 2. **Partial Match Fallback:**
226
+ - If no exact match is found, the engine will look for a flow whose `name` or `id` contains the input (case-insensitive).
227
+ 3. **No Match:**
228
+ - If no match is found, no flow is activated.
229
+
230
+ This makes it easy to run demos and tests without requiring a real AI intent detection function. In production, always provide a real `aiCallback` for robust intent detection.
231
+
232
+ ========================================
233
+ SECURITY & COMPLIANCE FEATURES
234
+ ========================================
235
+
236
+ EXPRESSION SECURITY:
237
+ ✅ Safe Expression Evaluation - No eval(), no code injection, allowlist-based safe method calls
238
+ ✅ Safe Method Allowlist - Only pre-approved string, array, and math methods allowed
239
+ ✅ Safe Function Registry - Built-in safe functions + user-defined approved functions
240
+ ✅ Pattern-Based Security - Block dangerous operations (constructors, eval, etc.)
241
+ ✅ Variable Path Validation - Secure nested property access
242
+ ✅ Input Sanitization - Clean and validate all user inputs
243
+
244
+ TRANSACTION MANAGEMENT:
245
+ ✅ Comprehensive Audit Trail - Every action logged
246
+ ✅ Transaction State Tracking - Success/failure/pending states
247
+ ✅ Error Recovery Logging - Detailed failure analysis
248
+ ✅ User Context Isolation - Prevent cross-user data leaks
249
+
250
+ RATE LIMITING & VALIDATION:
251
+ ✅ Per-User Rate Limiting - Prevent abuse
252
+ ✅ JSON Schema Validation - Type-safe parameter handling
253
+ ✅ Input Size Limits - Prevent memory exhaustion
254
+ ✅ Timeout Management - Prevent hanging operations
255
+
256
+ ========================================
257
+ INTEGRATION CAPABILITIES
258
+ ========================================
259
+
260
+ REST API SUPPORT:
261
+ ✅ HTTP Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
262
+ ✅ Content Types: JSON, Form-data, URL-encoded, XML/SOAP, Plain text, Multipart
263
+ ✅ Authentication: Bearer tokens, Basic auth, API keys, HMAC signatures
264
+ ✅ Parameter Handling: Path params, Query params, Request body, Headers
265
+ ✅ Advanced Features: Retries with exponential backoff, Timeouts, Rate limiting
266
+ ✅ Response Handling: JSON, XML, Text with automatic content-type detection
267
+ ✅ DECLARATIVE RESPONSE MAPPING: Secure, generic transformation without code injection
268
+ ✅ Error Handling: Status-based retry logic, Detailed error messages
269
+ ✅ Security: Input sanitization, Credential management, Audit logging
270
+
271
+ DECLARATIVE RESPONSE MAPPING SYSTEM:
272
+ The engine supports completely generic response transformation through declarative
273
+ JSON configuration, eliminating the need for users to inject code. This maintains
274
+ complete engine security while supporting complex API response handling.
275
+
276
+ MAPPING TYPES SUPPORTED:
277
+
278
+ 1. JSONPATH MAPPING - Extract and transform specific fields:
279
+ {
280
+ responseMapping: {
281
+ type: "jsonPath",
282
+ mappings: {
283
+ "output_field": {
284
+ path: "api.response.field[0].value",
285
+ transform: { type: "parseInt", fallback: 0 },
286
+ fallback: "$args.inputField"
287
+ }
288
+ }
289
+ }
290
+ }
291
+
292
+ 2. OBJECT MAPPING - Restructure response objects:
293
+ {
294
+ responseMapping: {
295
+ type: "object",
296
+ mappings: {
297
+ "user_name": "name",
298
+ "contact": {
299
+ "email": "email",
300
+ "phone": "phone"
301
+ },
302
+ "metadata": {
303
+ "processed": true,
304
+ "timestamp": "{{new Date().toISOString()}}"
305
+ }
306
+ }
307
+ }
308
+ }
309
+
310
+ 3. ARRAY MAPPING - Filter and transform arrays:
311
+ {
312
+ responseMapping: {
313
+ type: "array",
314
+ source: "results",
315
+ limit: 10,
316
+ filter: { field: "status", operator: "equals", value: "active" },
317
+ itemMapping: {
318
+ type: "object",
319
+ mappings: { "id": "id", "name": "name" }
320
+ }
321
+ }
322
+ }
323
+
324
+ 4. TEMPLATE MAPPING - String interpolation:
325
+ {
326
+ responseMapping: {
327
+ type: "template",
328
+ template: "User {{name}} ({{email}}) from {$args.source}"
329
+ }
330
+ }
331
+
332
+ 5. CONDITIONAL MAPPING - Different mapping based on response structure:
333
+ {
334
+ responseMapping: {
335
+ type: "conditional",
336
+ conditions: [
337
+ {
338
+ if: { field: "status", operator: "equals", value: "success" },
339
+ then: { type: "object", mappings: { "result": "data" } }
340
+ }
341
+ ],
342
+ else: { type: "object", mappings: { "error": "message" } }
343
+ }
344
+ }
345
+
346
+ VALUE TRANSFORMATIONS SUPPORTED:
347
+ - parseInt, parseFloat: Number conversion
348
+ - toLowerCase, toUpperCase, trim: String manipulation
349
+ - replace: Regex replacement
350
+ - concat: Add prefix/suffix
351
+ - regex: Extract with regex groups
352
+ - date: Convert to ISO date string
353
+ - default: Fallback values
354
+
355
+ SECURITY & BEST PRACTICES:
356
+ - No code injection possible - all transformations are declarative
357
+ - Secure path traversal with validation
358
+ - Fallback handling for missing data
359
+ - Type coercion with validation
360
+ - Error handling with graceful degradation
361
+
362
+ ========================================
363
+ IMPLEMENTATION NOTES & BEST PRACTICES
364
+ ========================================
365
+
366
+ PROPER USAGE PATTERNS:
367
+ 1. Always use helper functions for stack operations
368
+ 2. Never directly access flowStacks arrays
369
+ 3. Maintain transaction state consistency
370
+ 4. Use proper error handling with smart defaults
371
+ 5. Implement comprehensive logging for debugging
372
+
373
+ ========================================
374
+ 🚀 ENHANCED TRANSFORMATION CAPABILITIES
375
+ ========================================
376
+
377
+ The JavaScript Flow Engine now includes a comprehensive suite of mathematical, temporal,
378
+ and template processing enhancements that enable sophisticated data transformations
379
+ without code injection risks.
380
+
381
+ MATHEMATICAL OPERATIONS:
382
+ ✅ `add` - Addition with precision control: `{ type: "add", addend: 10, precision: 2 }`
383
+ ✅ `subtract` - Subtraction with precision control: `{ type: "subtract", subtrahend: 5, precision: 2 }`
384
+ ✅ `multiply` - Multiplication: `{ type: "multiply", multiplier: 1.08, precision: 2 }`
385
+ ✅ `divide` - Division with zero protection: `{ type: "divide", divisor: 100, precision: 2 }`
386
+ ✅ `percentage` - Percentage calculation: `{ type: "percentage", divisor: 1000, precision: 1 }`
387
+ ✅ `abs`, `round`, `floor`, `ceil` - Mathematical functions
388
+
389
+ DATE-BASED CALCULATIONS:
390
+ ✅ `currentYear` - Get current year: `{ type: "currentYear" }`
391
+ ✅ `yearDifference` - Calculate age/duration: `{ type: "yearDifference" }` (current year - value)
392
+ ✅ Dynamic age calculations, time-based transformations
393
+
394
+ ARRAY AGGREGATIONS:
395
+ ✅ `sum` - Sum array values: `{ type: "sum", field: "budget" }` (for object arrays)
396
+ ✅ `average` - Calculate mean: `{ type: "average", field: "employees", precision: 1 }`
397
+ ✅ `count` - Count non-null values: `{ type: "count", field: "active" }`
398
+ ✅ `min` - Find minimum: `{ type: "min", field: "price" }`
399
+ ✅ `max` - Find maximum: `{ type: "max", field: "score" }`
400
+
401
+ ENHANCED TEMPLATE SYSTEM:
402
+ ✅ **Array Length Access**: `{{array.length}}` automatically supported
403
+ ✅ **Handlebars-Style Iteration**: `{{#each items}}...{{/each}}` with full nesting
404
+ ✅ **Context Variables**: `{{@index}}` (current index), `{{@last}}` (is last item)
405
+ ✅ **Conditional Rendering**: `{{#unless @last}}separator{{/unless}}`
406
+ ✅ **Nested Property Access**: `{{item.nested.property}}`
407
+
408
+ REAL-WORLD EXAMPLES:
409
+
410
+ **Age Calculation:**
411
+ ```json
412
+ {
413
+ "path": "user.birthYear",
414
+ "transform": { "type": "yearDifference" }
415
+ }
416
+ ```
417
+ Input: `2015` → Output: `10` (automatically calculated as 2025 - 2015)
418
+
419
+ **Financial Aggregations:**
420
+ ```json
421
+ {
422
+ "path": "departments",
423
+ "transform": {
424
+ "type": "sum",
425
+ "field": "budget",
426
+ "precision": 0
427
+ }
428
+ }
429
+ ```
430
+ Input: `[{budget: 8500000}, {budget: 3200000}]` → Output: `11700000`
431
+
432
+ **Complex Template with Arrays:**
433
+ ```json
434
+ {
435
+ "type": "template",
436
+ "template": "Operating in {{locations.length}} locations: {{#each locations}}{{city}}, {{country}} ({{employees}} employees){{#unless @last}}; {{/unless}}{{/each}}"
437
+ }
438
+ ```
439
+ Input: Array of locations → Output: `"Operating in 3 locations: San Francisco, USA (150 employees); London, UK (60 employees); Toronto, Canada (40 employees)"`
440
+
441
+ **Percentage Calculations:**
442
+ ```json
443
+ {
444
+ "path": "completedProjects",
445
+ "transform": {
446
+ "type": "percentage",
447
+ "divisor": "{{totalProjects}}",
448
+ "precision": 1
449
+ }
450
+ }
451
+ ```
452
+ Input: `19` completed, `30` total → Output: `63.3` (percentage)
453
+
454
+ CONTRIBUTORS: Areas for Future Enhancement
455
+ ✅ **Current Coverage**: Mathematical, temporal, aggregation, template processing
456
+ ⚠️ **Missing Operations**: Trigonometric functions (sin, cos, tan)
457
+ ⚠️ **Missing Date Functions**: Date formatting, timezone conversions, date arithmetic
458
+ ⚠️ **Missing String Functions**: Advanced regex operations, locale-specific formatting
459
+ ⚠️ **Missing Array Functions**: Complex filtering, sorting, grouping operations
460
+ ⚠️ **Missing Template Features**: Nested loops, advanced conditionals, custom helpers
461
+
462
+ ========================================
463
+ 📋 COMPREHENSIVE FEATURE MATRIX FOR CONTRIBUTORS
464
+ ========================================
465
+
466
+ This section provides a complete overview of implemented features and identifies
467
+ areas where contributors can add value. All features maintain the engine's security
468
+ model (no code injection, declarative-only transformations).
469
+
470
+ FLOW EXECUTION ENGINE:
471
+ ✅ **Stack-of-stacks architecture** - Complete with interruption/resumption
472
+ ✅ **Flow frame management** - Variables, context, transaction tracking
473
+ ✅ **Step types** - SAY, SAY-GET, SET, CALL-TOOL, FLOW, SWITCH
474
+ ✅ **Expression evaluation** - Safe JavaScript expressions with allowlist
475
+ ✅ **Error handling** - Smart defaults, financial protection, graceful degradation
476
+ ✅ **Intent detection** - AI-powered + fallback flow matching
477
+ ✅ **Universal commands** - help, status, cancel, exit
478
+
479
+ TRANSFORMATION SYSTEM:
480
+ ✅ **Basic types** - parseInt, parseFloat, toLowerCase, toUpperCase, trim
481
+ ✅ **String operations** - replace, concat, regex, substring, split, join
482
+ ✅ **Mathematical** - add, subtract, multiply, divide, percentage, abs, round, floor, ceil
483
+ ✅ **Date/Time** - currentYear, yearDifference, ISO date conversion
484
+ ✅ **Array aggregations** - sum, average, count, min, max (with field targeting)
485
+ ✅ **Conditional logic** - Multi-branch conditions with operators
486
+ ✅ **Template processing** - Simple placeholders + Handlebars-style iteration
487
+ ✅ **Default/fallback** - Robust null handling
488
+
489
+ RESPONSE MAPPING SYSTEM:
490
+ ✅ **JSONPath mapping** - Deep object extraction with transformations
491
+ ✅ **Object mapping** - Restructuring and field remapping
492
+ ✅ **Array mapping** - Filtering, limiting, item transformation
493
+ ✅ **Template mapping** - String interpolation with complex iteration
494
+ ✅ **Conditional mapping** - Response-structure-based branching
495
+
496
+ REST API INTEGRATION:
497
+ ✅ **HTTP methods** - GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
498
+ ✅ **Content types** - JSON, form-data, URL-encoded, XML/SOAP, text, multipart
499
+ ✅ **Authentication** - Bearer, Basic, API keys, HMAC signatures
500
+ ✅ **Parameters** - Path params, query params, body, headers
501
+ ✅ **Advanced features** - Retries, timeouts, rate limiting
502
+ ✅ **Response handling** - Auto content-type detection, declarative mapping
503
+
504
+ SECURITY & COMPLIANCE:
505
+ ✅ **Expression security** - Safe evaluation, method allowlist, no eval()
506
+ ✅ **Transaction management** - Audit trails, state tracking, recovery
507
+ ✅ **Rate limiting** - Per-user controls, abuse prevention
508
+ ✅ **Input validation** - JSON Schema, size limits, sanitization
509
+ ✅ **Credential management** - Secure token handling, audit logging
510
+
511
+ AREAS FOR CONTRIBUTOR ENHANCEMENT (very liberal AI based 🫣 ):
512
+
513
+ 🔢 **MATHEMATICAL EXTENSIONS:**
514
+ ⚠️ Trigonometric functions (sin, cos, tan, asin, acos, atan)
515
+ ⚠️ Logarithmic functions (log, log10, ln)
516
+ ⚠️ Statistical functions (median, mode, standard deviation)
517
+ ⚠️ Financial functions (compound interest, NPV, IRR)
518
+
519
+ 📅 **DATE/TIME ENHANCEMENTS:**
520
+ ⚠️ Date formatting with locale support (MM/DD/YYYY, DD-MM-YYYY)
521
+ ⚠️ Timezone conversions and handling
522
+ ⚠️ Date arithmetic (add days, subtract months, etc.)
523
+ ⚠️ Relative date calculations (next Monday, last quarter)
524
+ ⚠️ Duration calculations (time between dates)
525
+
526
+ 🔤 **STRING PROCESSING EXPANSIONS:**
527
+ ⚠️ Advanced regex operations (lookahead, lookbehind)
528
+ ⚠️ Locale-specific formatting (currency, numbers)
529
+ ⚠️ String similarity and distance algorithms
530
+ ⚠️ Text normalization and cleaning utilities
531
+ ⚠️ Encoding/decoding beyond URI (Base64, hex)
532
+
533
+ 🔗 **ARRAY OPERATION ENHANCEMENTS:**
534
+ ⚠️ Complex filtering with multiple conditions
535
+ ⚠️ Sorting with custom comparators
536
+ ⚠️ Grouping and partitioning operations
537
+ ⚠️ Set operations (union, intersection, difference)
538
+ ⚠️ Array flattening and nested operations
539
+
540
+ 🎨 **TEMPLATE SYSTEM EXTENSIONS:**
541
+ ⚠️ Nested loop support (each within each)
542
+ ⚠️ Advanced conditionals (if/else if/else blocks)
543
+ ⚠️ Custom helper functions (user-defined template functions)
544
+ ⚠️ Template caching and optimization
545
+ ⚠️ Internationalization and localization support
546
+
547
+ 🔧 **INTEGRATION CAPABILITIES:**
548
+ ⚠️ Database connectivity (with secure query building)
549
+ ⚠️ File system operations (secure read/write)
550
+ ⚠️ Message queue integration (Kafka, RabbitMQ, SQS)
551
+ ⚠️ Real-time capabilities (WebSocket, Server-Sent Events)
552
+ ⚠️ Monitoring and metrics collection
553
+
554
+ ⚡ **PERFORMANCE OPTIMIZATIONS:**
555
+ ⚠️ Expression caching and compilation
556
+ ⚠️ Lazy evaluation for expensive operations
557
+ ⚠️ Memory usage optimization for large datasets
558
+ ⚠️ Parallel processing for independent operations
559
+ ⚠️ Streaming processing for large arrays
560
+
561
+ IMPLEMENTATION GUIDELINES FOR CONTRIBUTORS:
562
+ 1. **Security First**: All new features must maintain no-code-injection principle
563
+ 2. **Declarative Design**: Use JSON configuration, not executable code
564
+ 3. **Error Handling**: Implement comprehensive fallbacks and validation
565
+ 4. **Testing**: Add to the 40+ test comprehensive test suite
566
+ 5. **Documentation**: Update both README.md and User Guide
567
+ 6. **Type Safety**: Maintain TypeScript compliance with proper interfaces
568
+ 7. **Performance**: Consider memory and computational impact
569
+
570
+ CURRENT TEST COVERAGE:
571
+ ✅ **40 Comprehensive Test Scenarios** - 100% pass rate validated
572
+ ✅ **Flow execution patterns** - Linear, nested, interrupted, resumed
573
+ ✅ **Mathematical transformations** - All operations with edge cases
574
+ ✅ **Template processing** - Simple and complex Handlebars-style
575
+ ✅ **API integrations** - HTTP methods, auth, error handling
576
+ ✅ **Error scenarios** - Network failures, invalid data, timeouts
577
+ ✅ **Security validation** - Expression safety, input sanitization
578
+
579
+ ========================================
580
+
581
+ - OpenAI Function Calling Standard schemas
582
+ - JSON Schema validation with ajv
583
+ - Secure function registry
584
+ - Comprehensive error handling & transaction management
585
+ - Audit logging for compliance
586
+ - Rate limiting and input validation
587
+ - COMPREHENSIVE REST API SUPPORT with all common conventions:
588
+
589
+ REST API FEATURES SUPPORTED:
590
+ ✅ HTTP Methods: GET, POST, PUT, PATCH, DELETE, HEAD, OPTIONS
591
+ ✅ Content Types: JSON, Form-data, URL-encoded, XML/SOAP, Plain text, Multipart
592
+ ✅ Authentication: Bearer tokens, Basic auth, API keys, HMAC signatures
593
+ ✅ Parameter Handling: Path params, Query params, Request body, Headers
594
+ ✅ Advanced Features: Retries with exponential backoff, Timeouts, Rate limiting
595
+ ✅ Response Handling: JSON, XML, Text with automatic content-type detection
596
+ ✅ DECLARATIVE RESPONSE MAPPING: Secure, generic transformation without code injection
597
+ ✅ Error Handling: Status-based retry logic, Detailed error messages
598
+ ✅ Security: Input sanitization, Credential management, Audit logging
599
+
600
+ DECLARATIVE RESPONSE MAPPING SYSTEM:
601
+ The engine now supports completely generic response transformation through declarative
602
+ JSON configuration, eliminating the need for users to inject code. This maintains
603
+ complete engine security while supporting complex API response handling.
604
+
605
+ MAPPING TYPES SUPPORTED:
606
+
607
+ 1. JSONPATH MAPPING - Extract and transform specific fields:
608
+ {
609
+ responseMapping: {
610
+ type: "jsonPath",
611
+ mappings: {
612
+ "output_field": {
613
+ path: "api.response.field[0].value",
614
+ transform: { type: "parseInt", fallback: 0 },
615
+ fallback: "$args.inputField"
616
+ }
617
+ }
618
+ }
619
+ }
620
+
621
+ 2. OBJECT MAPPING - Restructure response objects:
622
+ {
623
+ responseMapping: {
624
+ type: "object",
625
+ mappings: {
626
+ "user_name": "name",
627
+ "contact": {
628
+ "email": "email",
629
+ "phone": "phone"
630
+ },
631
+ "metadata": {
632
+ "processed": true,
633
+ "timestamp": "{{new Date().toISOString()}}"
634
+ }
635
+ }
636
+ }
637
+ }
638
+
639
+ 3. ARRAY MAPPING - Filter and transform arrays:
640
+ {
641
+ responseMapping: {
642
+ type: "array",
643
+ source: "results",
644
+ limit: 10,
645
+ filter: { field: "status", operator: "equals", value: "active" },
646
+ itemMapping: {
647
+ type: "object",
648
+ mappings: { "id": "id", "name": "name" }
649
+ }
650
+ }
651
+ }
652
+
653
+ 4. TEMPLATE MAPPING - String interpolation:
654
+ {
655
+ responseMapping: {
656
+ type: "template",
657
+ template: "User {{name}} ({{email}}) from {$args.source}"
658
+ }
659
+ }
660
+
661
+ 5. CONDITIONAL MAPPING - Different mapping based on response structure:
662
+ {
663
+ responseMapping: {
664
+ type: "conditional",
665
+ conditions: [
666
+ {
667
+ if: { field: "status", operator: "equals", value: "success" },
668
+ then: { type: "object", mappings: { "result": "data" } }
669
+ }
670
+ ],
671
+ else: { type: "object", mappings: { "error": "message" } }
672
+ }
673
+ }
674
+
675
+ VALUE TRANSFORMATIONS SUPPORTED:
676
+ - parseInt, parseFloat: Number conversion
677
+ - toLowerCase, toUpperCase, trim: String manipulation
678
+ - replace: Regex replacement
679
+ - concat: Add prefix/suffix
680
+ - regex: Extract with regex groups
681
+ - date: Convert to ISO date string
682
+ - default: Fallback values
683
+
684
+ SECURITY & BEST PRACTICES:
685
+ - No code injection possible - all transformations are declarative
686
+ - Secure path traversal with validation
687
+ - Fallback handling for missing data
688
+ - Type coercion with validation
689
+ - Error handling with graceful degradation
690
+
691
+ EXAMPLE TOOL CONFIGURATIONS:
692
+
693
+ 1. SIMPLE GET REQUEST:
694
+ {
695
+ implementation: {
696
+ type: "http",
697
+ url: "https://api.example.com/users",
698
+ method: "GET"
699
+ }
700
+ }
701
+
702
+ 2. AUTHENTICATED POST WITH JSON:
703
+ {
704
+ implementation: {
705
+ type: "http",
706
+ url: "https://api.example.com/users",
707
+ method: "POST",
708
+ contentType: "application/json"
709
+ },
710
+ apiKey: "your-bearer-token"
711
+ }
712
+
713
+ 3. PATH PARAMETERS WITH RESPONSE MAPPING:
714
+ {
715
+ implementation: {
716
+ type: "http",
717
+ url: "https://api.example.com/users/{userId}",
718
+ method: "GET",
719
+ pathParams: ["userId"],
720
+ responseMapping: {
721
+ type: "object",
722
+ mappings: {
723
+ "user_id": "id",
724
+ "full_name": "name",
725
+ "contact_email": "email"
726
+ }
727
+ }
728
+ }
729
+ }
730
+
731
+ 4. COMPLEX API WITH ARRAY PROCESSING:
732
+ {
733
+ implementation: {
734
+ type: "http",
735
+ url: "https://api.example.com/search",
736
+ method: "GET",
737
+ responseMapping: {
738
+ type: "array",
739
+ source: "results",
740
+ limit: 5,
741
+ filter: { field: "active", operator: "equals", value: true },
742
+ itemMapping: {
743
+ type: "object",
744
+ mappings: {
745
+ "id": "id",
746
+ "title": "name",
747
+ "snippet": {
748
+ path: "description",
749
+ transform: { type: "regex", pattern: "^(.{100})", group: 1 }
750
+ }
751
+ }
752
+ }
753
+ }
754
+ }
755
+ }
756
+
757
+ 5. WEATHER API WITH DECLARATIVE MAPPING:
758
+ {
759
+ implementation: {
760
+ type: "http",
761
+ url: "https://wttr.in/{city}",
762
+ pathParams: ["city"],
763
+ customQuery: "format=j1",
764
+ responseMapping: {
765
+ type: "jsonPath",
766
+ mappings: {
767
+ "location.name": {
768
+ path: "nearest_area[0].areaName[0].value",
769
+ fallback: "$args.city"
770
+ },
771
+ "current.temp_c": {
772
+ path: "current_condition[0].temp_C",
773
+ transform: { type: "parseInt", fallback: 0 }
774
+ },
775
+ "current.condition": {
776
+ path: "current_condition[0].weatherDesc[0].value",
777
+ fallback: "Unknown"
778
+ }
779
+ }
780
+ }
781
+ }
782
+ }
783
+ */