awsibnj
v18.0.2
Published
HTTP client and Axios replacement with intelligent API field-name transformation (camelCase/snake_case/PascalCase/kebab-case), auto-retry, response caching, request deduplication, token refresh, lifecycle hooks, pluggable adapters, circuit breaker, securi
Downloads
386
Maintainers
Readme
awsibnj v18
Created by awsibnj
Enterprise-grade Axios replacement with elite security and production power tools — a complete, zero-dependency HTTP client with zero-trust engine, threat intelligence, mTLS, request integrity chains, adaptive rate limiting, OWASP security headers, encrypted config vault, SSRF protection, input sanitization, RBAC permissions, auto-retry, response caching, request dedup, token refresh, lifecycle hooks, intelligent API mismatch detection, and 80+ modules.
awsibnj is a true drop-in replacement for Axios that also bridges the gap between backend and frontend naming conventions. It detects snake_case, PascalCase, kebab-case, SCREAMING_SNAKE keys from your API and transforms them into your preferred convention — with AI-powered semantic matching, persistent learning, and zero manual mapping.
v18 Highlights: Zero-trust engine, threat intelligence, secure sessions, request integrity chain, adaptive rate limiting, OWASP security headers, encrypted config vault, mutual TLS — plus CSP, certificate pinning, HMAC signing, input sanitization, RBAC, payload encryption, idempotency, SSRF protection, replay detection, journey tracking, auto-retry, caching, dedup, token refresh, 1178 tests.
Table of Contents
- Features
- Why Replace Axios?
- Installation
- Quick Start
- Axios Migration Guide
- API Reference
- V14 Features
- V15 Features
- V16 Features
- V17 Features
- V18 Features
- V8 Features
- V7 Features
- V6 Features
- V5 Features
- V4 Features
- V3 Features
- V2 Features
- Type Coercion
- Learning Engine
- Schema Definitions
- Export Reports
- Error Handling
- Architecture
- Running Tests
- Migration from Previous Versions
- License
Features
Axios Compatibility (v9–v18)
| Axios Feature | v9 | v10 | v11 | v12 | v13 | v14 | v15 | v16 | v17 | v18 |
|---|---|---|---|---|---|---|---|---|---|---|
| HTTP methods (GET/POST/PUT/PATCH/DELETE/HEAD/OPTIONS) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| createClient() / create() factory | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Request/response interceptors | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Base URL, headers, query params | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Timeout + AbortController | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Retries with exponential backoff | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Smart Proxy mode (dynamic field resolution) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Expectation schema (expect) | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| auth, validateStatus, responseType | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| CancelToken, Cancel, isCancel | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| toFormData, formToJSON, isFormData | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| all(), spread(), mergeConfig() | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| transformRequest / transformResponse | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxContentLength / maxBodyLength | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| AxiosHeaders class | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| HttpStatusCode enum | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Pluggable adapters (fetch/xhr/custom) | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| postForm(), putForm(), patchForm() | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| isAbsoluteURL, combineURLs, URL utils | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Callable default export: apiBridge(config) | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Axios / AxiosError class aliases | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Error code constants (ERR_NETWORK, etc.) | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| isAxiosError() function | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| transitional config option | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Delete with data body | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| AxiosHeaders in all responses | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Default transformRequest/Response chains | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| .isAxiosError property on errors | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| response.request property | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| maxRate throttling | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| lookup DNS option | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Auto-retry engine (retryConfig) | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Response caching (TTL, stale-while-revalidate) | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Request deduplication (dedupe) | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Auto token refresh (tokenRefresh) | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Request timing (timing) | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Lifecycle hooks (hooks) | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ |
| Interceptor runWhen + synchronous | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Auto Content-Type serialization | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
| beforeRedirect callback | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
| Request correlation IDs (requestId) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ |
| SSRF protection (SSRFGuard) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
| Header injection prevention | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
| Client-side rate limiting | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
| Request fingerprinting (replay detection) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
| Journey tracking | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ |
| Content Security Policy (CSP) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| Certificate pinning | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| HMAC request signing | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| Input sanitization (XSS/SQL injection) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| RBAC permission policy | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| AES-256-GCM payload encryption | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| Idempotency manager | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ |
| Zero-trust engine | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| Threat intelligence (IP reputation) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| Secure session manager | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| Request integrity chain | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| Adaptive rate limiter (anomaly detection) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| OWASP security headers | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| Encrypted config vault | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
| Mutual TLS (mTLS) | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
Core Features (v1–v8)
| Feature | v1 | v2 | v3 | v4 | v5 | v6 | v7 | v8 | |---------|----|----|-----|-----|-----|-----|-----|-----| | snake_case → camelCase | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | All 5 naming conventions | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Axios interceptors | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Native fetch wrapper | GET/POST | All HTTP methods | All HTTP methods | All HTTP methods | All HTTP methods | All HTTP methods | All HTTP methods | All HTTP methods | | Semantic synonym matching | ✅ | ✅ (expanded) | ✅ (expanded + healthcare, analytics, DevOps) | ✅ | ✅ | ✅ | ✅ (+ financial, IoT, education, social) | ✅ | | Fuzzy Levenshtein matching | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ (enhanced multi-strategy) | ✅ (weighted ensemble 7-strategy) | ✅ | | Learning engine | ✅ | ✅ (confidence decay) | ✅ (v3 persistence format) | ✅ | ✅ | ✅ | ✅ | ✅ | | Type coercion | ✅ | ✅ (+ integer, float) | ✅ | ✅ | ✅ | ✅ (schema-based auto-coercion) | ✅ (case-insensitive, %, comma) | ✅ | | CSV export | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | JSON export | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Schema validation | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Response normalization | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Middleware pipeline | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Response caching (LRU + TTL) | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Retry with backoff | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Custom error classes | ❌ | ✅ | ✅ (9 types) | ✅ (13 types) | ✅ (19 types) | ✅ (22 types) | ✅ (22 types) | ✅ (27 types) | | Plugin system | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | ✅ | | Circuit breaker | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | | GraphQL bridge | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | ✅ | | Mock server | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | | Health check monitor | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | | Event bus | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | ✅ | ✅ | | Weighted ensemble matching | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | ✅ | | Multi-alias field resolution | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Schema migration engine | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Deep merge engine | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ | | Conditional transforms | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ❌ | ✅ |
Installation
npm install awsibnjOr clone the repo:
git clone https://github.com/biswaranjantudu064-netizen/Api_bridge.git
cd Api_bridge
npm installWhy Replace Axios?
awsibnj is not just an Axios wrapper — it's a complete replacement that gives you everything Axios does plus intelligent API transformation:
| | Axios | awsibnj v18 |
|---|---|---|
| HTTP client (GET/POST/PUT/PATCH/DELETE) | ✅ | ✅ |
| Request/response interceptors | ✅ | ✅ |
| CancelToken + AbortController | ✅ | ✅ |
| FormData, toFormData, formToJSON | ✅ | ✅ |
| AxiosHeaders class | ✅ | ✅ |
| HttpStatusCode enum | ✅ | ✅ |
| transformRequest/transformResponse | ✅ | ✅ (with defaults) |
| Pluggable adapters (fetch/xhr) | ✅ | ✅ |
| error.isAxiosError property | ✅ | ✅ |
| response.request property | ✅ | ✅ |
| Zero dependencies | ❌ (follow-redirects) | ✅ |
| Intelligent field mapping | ❌ | ✅ |
| Fuzzy matching (7 strategies) | ❌ | ✅ |
| Learning engine | ❌ | ✅ |
| Schema migration | ❌ | ✅ |
| Smart Proxy mode | ❌ | ✅ |
| 80+ utility modules | ❌ | ✅ |
Quick Migration from Axios
// Before (Axios)
const axios = require('axios');
const api = axios.create({ baseURL: '/api' });
// After (awsibnj — drop-in replacement)
const apiBridge = require('awsibnj');
const api = apiBridge.create({ baseURL: '/api' });
// Everything works the same:
const res = await api.get('/users', { params: { page: 1 } });
console.log(res.data); // ✅ Same response shape
console.log(res.status); // ✅ Same status
console.log(res.headers.get('content-type')); // ✅ AxiosHeaders
console.log(res.request); // ✅ Request object
console.log(res.config.data); // ✅ Request data
// Error handling — identical to Axios
try {
await api.get('/missing');
} catch (err) {
if (err.isAxiosError) { // ✅ Property check works
console.log(err.response.status);
console.log(err.response.headers.get('content-type')); // ✅ AxiosHeaders
}
}Project Structure
awsibnj/
├── src/
│ ├── index.js # Main entry point (exports everything)
│ ├── core/ # Core transformation engine
│ │ ├── index.js # Barrel export for core module
│ │ ├── errors.js # 27 structured error classes
│ │ ├── client.js # HTTP client engine (Axios replacement)
│ │ ├── interceptors.js # Request/response interceptor system
│ │ ├── cancel.js # CancelToken, Cancel, isCancel
│ │ ├── form-data.js # FormData utilities
│ │ ├── headers.js # AxiosHeaders class
│ │ ├── http-status.js # HttpStatusCode enum
│ │ ├── adapters.js # Pluggable adapters (fetch/xhr)
│ │ ├── url-utils.js # URL utilities
│ │ ├── helpers.js # Type & utility helpers
│ │ ├── expectation.js # Expectation schema system
│ │ ├── proxy.js # Smart Proxy mode
│ │ ├── transformer.js # 7-level mismatch detection & correction
│ │ ├── learning.js # Persistent learning engine
│ │ ├── normalizer.js # Response normalization
│ │ ├── synonyms.js # Synonym dictionary (financial, IoT, etc.)
│ │ ├── fuzzy-matcher.js # Weighted ensemble fuzzy matching
│ │ ├── cryptic-resolver.js # Cryptic/arbitrary name resolution
│ │ ├── type-coercer.js # Schema-based type coercion
│ │ ├── field-aliaser.js # Multi-alias field resolution
│ │ ├── validator.js # Schema validation
│ │ ├── inference.js # Auto schema inference
│ │ ├── conditional-transform.js # Conditional rules
│ │ └── schema-migrator.js # Version migration engine
│ ├── utils/ # Utility modules
│ │ ├── index.js # Barrel export for utils module
│ │ ├── cache.js # LRU response cache with TTL
│ │ ├── dedup.js # Request deduplication
│ │ ├── diff.js # Schema diff engine
│ │ ├── exporter.js # CSV/JSON export
│ │ ├── masking.js # PII data masking
│ │ ├── metrics.js # Performance metrics
│ │ ├── patch.js # JSON Patch (RFC 6902)
│ │ ├── typegen.js # TypeScript type generator
│ │ ├── deep-merge.js # Intelligent deep merge
│ │ ├── output-formatter.js # Multi-format output
│ │ ├── field-stats.js # Field analytics
│ │ ├── projection.js # Field projection
│ │ └── request-logger.js # Structured request logging
│ └── adapters/ # Protocol adapters & middleware
│ ├── index.js # Barrel export for adapters module
│ ├── graphql.js # GraphQL bridge
│ ├── webhook.js # Webhook handler
│ ├── openapi.js # OpenAPI importer
│ ├── mock-server.js # Mock server
│ ├── circuit-breaker.js # Circuit breaker
│ ├── retry-strategy.js # Advanced retry strategies
│ ├── rate-limiter.js # Rate limiter
│ ├── health-check.js # Health check monitor
│ ├── event-bus.js # Event bus (pub/sub)
│ ├── middleware.js # Middleware pipeline
│ ├── pipeline.js # Composable pipeline
│ ├── plugins.js # Plugin system
│ ├── request-interceptor.js # Request interceptor chain
│ ├── batch-orchestrator.js # Batch execution
│ ├── dependency-graph.js # DAG orchestration
│ ├── schema-registry.js # Versioned schema registry
│ ├── response-streamer.js # Response streaming
│ └── versioning.js # API versioning
├── types/
│ └── index.d.ts # TypeScript type declarations
├── examples/
│ ├── basic-usage.js # Basic usage examples
│ ├── advanced-usage.js # Advanced SDK patterns
│ └── plugin-example.js # Custom plugin development
├── test.js # 1178 tests
├── package.json
├── CHANGELOG.md
└── README.mdImporting Modules
Full Import (default)
const { bridge, transform, CircuitBreaker, EventBus } = require('awsibnj');Subpath Imports (tree-shakeable)
Import only the modules you need for smaller bundle sizes:
// Core transformation & matching
const { awsibnjTransformer, FuzzyMatcher, SchemaValidator } = require('awsibnj/core');
// Utilities
const { ResponseCache, DeepMerge, OutputFormatter } = require('awsibnj/utils');
// Adapters & middleware
const { CircuitBreaker, EventBus, PluginManager } = require('awsibnj/adapters');
// Error classes only
const { ValidationError, TransformError } = require('awsibnj/errors');TypeScript Support
TypeScript type declarations are included out of the box:
import { transform, SchemaValidator, CircuitBreaker } from 'awsibnj';
const result = transform({ first_name: 'John' });
// result is Record<string, any>
const validator = new SchemaValidator({ strict: true });
const { valid, errors } = validator.validate(data, schema);Plugin & Extension System
awsibnj has a built-in plugin system for extending functionality:
Creating a Plugin
const { PluginManager } = require('awsibnj');
const myPlugin = {
name: 'my-plugin',
version: '1.0.0',
hooks: {
beforeTransform: (data, ctx) => {
// Modify data before transformation
console.log('Transforming:', Object.keys(data));
return data;
},
afterTransform: (data, ctx) => {
// Modify data after transformation
return { ...data, _transformed: true };
},
onMismatch: (record) => {
// React to field mismatches
console.log('Mismatch detected:', record);
},
onError: (error) => {
// Handle errors
console.error('Error:', error.message);
},
},
init: () => console.log('Plugin loaded'),
destroy: () => console.log('Plugin unloaded'),
};
const plugins = new PluginManager();
plugins.register(myPlugin);Available Hook Points
| Hook | Phase | Description |
|------|-------|-------------|
| beforeTransform | Pre-transform | Modify data before field mapping |
| afterTransform | Post-transform | Modify data after field mapping |
| beforeValidate | Pre-validation | Modify data before schema validation |
| afterValidate | Post-validation | Modify validation results |
| onMismatch | Detection | React to field name mismatches |
| onError | Error | Handle errors in the pipeline |
| beforeRequest | Pre-request | Modify outgoing HTTP requests |
| afterRequest | Post-request | Modify incoming HTTP responses |
Plugin Factory Pattern
function createMetricsPlugin(options = {}) {
const metrics = {};
return {
name: 'metrics-plugin',
hooks: {
beforeTransform: (data) => {
metrics.startTime = Date.now();
return data;
},
afterTransform: (data) => {
metrics.duration = Date.now() - metrics.startTime;
if (options.onMetric) options.onMetric(metrics);
return data;
},
},
};
}Quick Start
1. As Axios Replacement (v18 — Recommended)
const apiBridge = require('awsibnj');
// Works exactly like axios:
const api = apiBridge.create({ baseURL: 'https://api.example.com' });
const { data } = await api.get('/users/1');
console.log(data);
// Or use the callable default:
const res = await apiBridge.get('https://api.example.com/users/1');
console.log(res.data);
console.log(res.status); // 200
console.log(res.headers.get('content-type')); // AxiosHeaders
console.log(res.request); // Request object
// Error handling with .isAxiosError property:
try {
await api.get('/missing');
} catch (err) {
if (err.isAxiosError) { // ✅ Property check
console.log(err.response.status); // 404
console.log(err.code); // ERR_BAD_REQUEST
}
}2. With Axios (Legacy Bridge)
const axios = require('axios');
const { bridge } = require('awsibnj');
const api = bridge(axios.create({ baseURL: 'https://api.example.com' }), {
schema: {
isActive: { column: 'is_active', type: 'boolean' },
createdAt: { column: 'created_at', type: 'date' },
},
});
// All responses automatically transformed to camelCase
const { data } = await api.get('/users/1');
console.log(data.firstName); // from "first_name"
console.log(data.isActive); // true (from integer 1)3. With Native Fetch
const { bridgeFetch } = require('awsibnj');
const api = bridgeFetch({
retries: 3,
retryDelay: 1000,
cache: { ttl: 60000 },
});
const user = await api.get('https://api.example.com/users/1');
console.log(user.firstName); // from "first_name"4. Direct Transform (No HTTP)
const { transform } = require('awsibnj');
const result = transform({
user_id: 1,
first_name: 'John',
last_name: 'Doe',
is_active: 1,
created_at: '2024-01-15',
});
// Result:
// {
// userId: 1,
// firstName: 'John',
// lastName: 'Doe',
// isActive: 1,
// createdAt: '2024-01-15',
// }5. Schema Inference (v3)
const { SchemaInference } = require('awsibnj');
const inference = new SchemaInference();
const schema = inference.infer([
{ id: 1, name: 'John', email: '[email protected]', is_active: true },
{ id: 2, name: 'Jane', email: '[email protected]', is_active: false },
]);
// Automatically detects types, required fields, and patterns5. Data Masking (v3)
const { DataMasker } = require('awsibnj');
const masker = new DataMasker();
const masked = masker.mask({
name: 'John',
password: 'secret123',
api_key: 'sk-abc123',
email: '[email protected]',
});
// { name: 'John', password: '[REDACTED]', api_key: '[REDACTED]', email: '[email protected]' }6. Circuit Breaker (v4)
const { CircuitBreaker } = require('awsibnj');
const breaker = new CircuitBreaker({
failureThreshold: 5, // Open after 5 consecutive failures
resetTimeout: 30000, // Try half-open after 30s
});
// All API calls go through the breaker
const data = await breaker.execute(async () => {
const res = await fetch('https://api.example.com/users');
return res.json();
});
// If the API keeps failing, the breaker opens and rejects instantly
// After 30s, it allows a probe request to test recovery
console.log(breaker.getState()); // 'CLOSED', 'OPEN', or 'HALF_OPEN'7. GraphQL Bridge (v4)
const { GraphQLBridge } = require('awsibnj');
const gql = new GraphQLBridge({
convention: 'camelCase',
stripTypename: true,
});
// Transform GraphQL response
const result = gql.transformResponse({
data: { user_name: 'John', email_address: '[email protected]' },
errors: [],
});
// { data: { userName: 'John', emailAddress: '[email protected]' }, errors: [] }
// Transform variables for server
const vars = gql.transformVariables({ userName: 'John' }, 'snake_case');
// { user_name: 'John' }
// Extract nested data
const posts = gql.extractData(response, 'user.posts');8. Composable Pipeline (v4)
const { ComposablePipeline } = require('awsibnj');
const pipe = new ComposablePipeline({ name: 'userPipeline' });
pipe
.pipe('validate', (data) => { if (!data.name) throw new Error('Name required'); return data; })
.pipe('transform', (data) => ({ ...data, name: data.name.toUpperCase() }))
.tap('log', (data) => console.log('Processed:', data.name))
.pipe('enrich', (data) => ({ ...data, processedAt: new Date().toISOString() }));
const { result, stages, duration } = await pipe.execute({ name: 'John', age: 30 });
// result: { name: 'JOHN', age: 30, processedAt: '2024-...' }9. Enhanced Fuzzy Matcher (v6)
const { FuzzyMatcher } = require('awsibnj');
const fuzzy = new FuzzyMatcher();
// Multi-strategy fuzzy matching: Levenshtein, phonetic, vowel-drop, abbreviation
const result = fuzzy.findBestMatch('usr_email', ['user_email', 'user_name', 'phone']);
// { match: 'user_email', confidence: 0.92, method: 'fuzzy_abbreviation' }
// Works with typos
const typo = fuzzy.findBestMatch('frist_name', ['first_name', 'last_name']);
// { match: 'first_name', confidence: 0.88, method: 'fuzzy_levenshtein' }
// Vowel-dropped abbreviations
const abbr = fuzzy.findBestMatch('usr_nm', ['user_name', 'email']);
// { match: 'user_name', confidence: 0.85, method: 'fuzzy_vowel_drop' }10. Cryptic Name Resolver (v6)
const { CrypticResolver } = require('awsibnj');
const resolver = new CrypticResolver();
// Resolve cryptic field names with prefixes
const result = resolver.resolve('z9_ref_id', ['reference_id', 'user_id']);
// { match: 'reference_id', confidence: 0.65, method: 'prefix_strip', stripped: 'ref_id' }
// Detect if a field name is cryptic
resolver.isCryptic('z9_ref_id'); // true
resolver.isCryptic('user_name'); // false
// Suffix-based matching
const suffix = resolver.resolve('x_user_flag', ['is_active', 'user_flag']);
// { match: 'user_flag', confidence: 0.65, method: 'suffix_match', stripped: '_flag' }11. Schema-Based Type Coercer (v6)
const { TypeCoercer } = require('awsibnj');
const coercer = new TypeCoercer();
// Coerce individual values
const result = coercer.coerceValue('true', 'boolean', 'isActive');
// { value: true, coerced: true, conflict: { field: 'isActive', sourceType: 'boolean_string', targetType: 'boolean', ... } }
// Coerce an entire object based on a schema
const { data, coerced, conflicts } = coercer.coerceObject(
{ isActive: '1', count: '42', createdAt: '2024-01-15' },
{ isActive: { type: 'boolean' }, count: { type: 'integer' }, createdAt: { type: 'date' } }
);
// data: { isActive: true, count: 42, createdAt: Date('2024-01-15') }
// coerced: ['isActive', 'count', 'createdAt']
// Detect type conflicts without coercing
const conflicts = coercer.detectConflicts(data, schema);
// Statistics
coercer.getStats();
// { totalConflicts: 3, coerced: 3, failed: 0, byType: { boolean_string_to_boolean: 1, ... } }V14 Features
Auto-Retry Engine
Advanced retry configuration with custom strategies, conditions, and callbacks:
const { createClient } = require('awsibnj');
const api = createClient({
baseURL: 'https://api.example.com',
retryConfig: {
retries: 3,
retryCondition: (error) => error.status >= 500, // only retry server errors
retryDelay: (retryCount) => retryCount * 1000, // linear backoff
shouldResetTimeout: false,
onRetry: (count, error, config) => {
console.log(`Retry #${count} for ${config.url}: ${error.message}`);
},
},
});
// Per-request override:
await api.get('/flaky-endpoint', {
retryConfig: { retries: 5, retryDelay: (n) => n * 500 },
});Response Caching (v14)
Built-in TTL-based response cache with stale-while-revalidate support:
const api = createClient({
baseURL: 'https://api.example.com',
cache: {
ttl: 60000, // 60 seconds
maxSize: 100, // max 100 entries
methods: ['GET'], // only cache GET requests
exclude: ['/auth', '/live'], // exclude these URL patterns
staleWhileRevalidate: true, // serve stale data while refreshing
keyGenerator: (config) => `${config.method}:${config.url}`,
},
});
const res1 = await api.get('/users'); // network request
const res2 = await api.get('/users'); // instant cache hit
api.clearResponseCache(); // clear all cached responsesRequest Deduplication (Client-Level)
Coalesce identical in-flight requests to avoid redundant network calls:
const api = createClient({
baseURL: 'https://api.example.com',
dedupe: {
enabled: true,
methods: ['GET'], // only deduplicate GET requests
keyGenerator: (config) => `${config.method}:${config.url}`,
},
});
// These fire simultaneously — only 1 network request is made:
const [res1, res2] = await Promise.all([
api.get('/users'),
api.get('/users'),
]);
// res1 and res2 are the same responseAuto Token Refresh
Automatically handle 401 responses with token refresh and request queuing:
const api = createClient({
baseURL: 'https://api.example.com',
headers: { Authorization: 'Bearer initial-token' },
tokenRefresh: {
onRefresh: async () => {
const res = await fetch('/auth/refresh', { method: 'POST' });
const { accessToken } = await res.json();
return accessToken; // returned token replaces the header
},
statusCodes: [401], // trigger on 401 (default)
maxRetries: 1, // max refresh attempts
headerName: 'Authorization', // header to update
tokenPrefix: 'Bearer ', // prefix for the new token
},
});
// If the request gets a 401, the token is automatically refreshed and retried:
const data = await api.get('/protected-resource');Request Timing
Built-in performance monitoring on every response:
const api = createClient({
baseURL: 'https://api.example.com',
timing: true,
});
const res = await api.get('/users');
console.log(res.duration); // 142 (milliseconds)
console.log(res.timing); // { start: 1713614400000, end: 1713614400142, duration: 142 }Lifecycle Hooks
Fire-and-forget event observers for logging, analytics, and monitoring:
const api = createClient({
baseURL: 'https://api.example.com',
hooks: {
onRequest: [
(config) => console.log(`→ ${config.method} ${config.url}`),
(config) => analytics.track('api_request', { url: config.url }),
],
onResponse: [
(res) => console.log(`← ${res.status} (${res.duration}ms)`),
],
onError: [
(err) => errorTracker.capture(err),
],
onRetry: [
(count, err, config) => console.warn(`Retry #${count}: ${err.message}`),
],
},
timing: true,
retryConfig: { retries: 2, retryDelay: () => 1000 },
});V15 Features
Interceptor runWhen / synchronous
Conditional and synchronous interceptor execution:
const { createClient } = require('awsibnj');
const api = createClient({ baseURL: 'https://api.example.com' });
// Only run interceptor for POST requests
api.interceptors.request.use(
(config) => { config.headers['X-CSRF'] = 'token'; return config; },
null,
{ runWhen: (config) => config.method === 'POST' }
);
// Synchronous interceptor (skips await overhead)
api.interceptors.request.use(
(config) => { config.headers['X-Req-Time'] = Date.now(); return config; },
null,
{ synchronous: true }
);Auto Content-Type Serialization
Automatic body conversion based on Content-Type:
const api = createClient({ baseURL: 'https://api.example.com' });
// Plain object + application/x-www-form-urlencoded → auto-converts to URLSearchParams
await api.post('/form', { username: 'john', password: 'secret' }, {
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
// Plain object + multipart/form-data → auto-converts to FormData
await api.post('/upload', { file: blob, name: 'avatar' }, {
headers: { 'Content-Type': 'multipart/form-data' },
});Enhanced paramsSerializer
Axios 1.x-compatible object form for parameter serialization:
const api = createClient({
baseURL: 'https://api.example.com',
paramsSerializer: {
encode: (value) => encodeURIComponent(value),
serialize: (params) => Object.entries(params).map(([k, v]) => `${k}=${v}`).join('&'),
},
});beforeRedirect Callback
Intercept and modify redirect requests:
const api = createClient({
baseURL: 'https://api.example.com',
beforeRedirect: (options, { headers, status, location }) => {
console.log(`Redirecting to ${location} (${status})`);
options.headers['X-Forwarded-From'] = 'original-host';
},
});Request Correlation IDs
Automatic unique ID generation for every request:
const api = createClient({
baseURL: 'https://api.example.com',
requestId: true, // auto-generate x-request-id
// or: requestId: 'X-Correlation-ID' // custom header name
});
const res = await api.get('/users');
// Request sent with header: x-request-id: <16-char-unique-id>V16 Features
SSRF Protection
Server-Side Request Forgery prevention — enabled by default:
const { createClient } = require('awsibnj');
const api = createClient({ baseURL: 'https://api.example.com' });
// These are automatically blocked:
// await api.get('http://169.254.169.254/metadata') → ERR_SSRF_BLOCKED
// await api.get('http://127.0.0.1:8080/admin') → ERR_SSRF_BLOCKED
// await api.get('file:///etc/passwd') → ERR_SSRF_BLOCKED
// Allowlist trusted internal hosts:
const internalApi = createClient({
baseURL: 'https://api.example.com',
ssrf: { allowlist: ['internal-service.local'] },
});
// Disable for testing:
const testApi = createClient({ ssrf: { enabled: false } });Header Injection Prevention
CRLF attack prevention with RFC 7230 validation:
const api = createClient({
baseURL: 'https://api.example.com',
maxHeadersCount: 50, // max number of headers (default 100)
maxHeaderSize: 4096, // max header value size (default 8192)
});
// Headers with CR/LF characters are automatically rejected → ERR_HEADER_VALIDATIONClient-Side Rate Limiting
Token bucket rate limiter to prevent overwhelming APIs:
const api = createClient({
baseURL: 'https://api.example.com',
rateLimiter: {
maxRequests: 50, // max 50 requests
windowMs: 10000, // per 10 seconds
},
});
// Exceeding the limit → ERR_RATE_LIMITEDResponse Size Guard
Prevent memory exhaustion from oversized responses:
const api = createClient({
baseURL: 'https://api.example.com',
maxResponseSize: 5 * 1024 * 1024, // 5MB max response size
});
// Responses exceeding limit → ERR_RESPONSE_TOO_LARGESensitive Data Redaction
Automatic credential stripping from error objects for safe logging:
const api = createClient({ baseURL: 'https://api.example.com' });
try {
await api.get('/endpoint', { headers: { Authorization: 'Bearer secret' } });
} catch (err) {
// err.config.headers.Authorization is '[REDACTED]' — safe to log
console.log(JSON.stringify(err));
}Request Fingerprinting
SHA-256 based replay detection:
const api = createClient({
baseURL: 'https://api.example.com',
replayDetection: 5000, // block duplicate requests within 5 seconds
});
// Duplicate requests within window → ERR_DUPLICATE_REQUESTRequest Journey Tracking
Per-request observability with attempt history:
const api = createClient({
baseURL: 'https://api.example.com',
journeyTracking: true,
timing: true,
});
const res = await api.get('/users');
console.log(res.journey);
// { attempts: [{ status: 200, duration: 142 }], totalDuration: 142, cacheHit: false }V17 Features
Content Security Policy
Build and validate CSP headers:
const { createClient } = require('awsibnj');
const api = createClient({
baseURL: 'https://api.example.com',
csp: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'https://cdn.example.com'],
styleSrc: ["'self'", "'unsafe-inline'"],
reportOnly: true,
reportUri: '/csp-report',
},
});Certificate Pinning
SHA-256 certificate hash verification per host:
const api = createClient({
baseURL: 'https://api.example.com',
certPinning: {
pins: [
{ host: 'api.example.com', sha256: ['base64hash1', 'base64hash2'] },
],
enforceMode: 'enforce', // or 'report' to log without blocking
includeSubdomains: true,
},
});
// Certificate mismatch → ERR_CERT_PIN_FAILEDRequest Signing
HMAC-SHA256 request integrity verification:
const api = createClient({
baseURL: 'https://api.example.com',
requestSigning: {
secret: 'your-hmac-secret',
algorithm: 'sha256',
signedHeaders: ['content-type', 'x-request-id'],
},
});
// Every request includes: x-signature, x-timestamp, x-signed-headersInput Sanitizer
XSS, SQL injection, and path traversal prevention:
const api = createClient({
baseURL: 'https://api.example.com',
inputSanitizer: {
mode: 'escape', // 'escape' | 'strip' | 'reject'
maxDepth: 10,
maxStringLength: 10000,
},
});
// Request bodies are automatically sanitized before sending
// Dangerous content in 'reject' mode → ERR_INPUT_REJECTEDSecurity Audit Logger
Tamper-proof event logging with SHA-256 hash chain:
const api = createClient({
baseURL: 'https://api.example.com',
auditLog: {
maxEntries: 5000,
onAlert: (entry) => {
console.error(`Security alert: ${entry.event} — ${entry.severity}`);
},
},
});
// All security events are automatically logged with integrity verificationPermission Policy (RBAC)
Role-based access control for API endpoints:
const api = createClient({
baseURL: 'https://api.example.com',
permissions: {
policies: [
{ role: 'admin', methods: ['*'], endpoints: ['*'] },
{ role: 'user', methods: ['GET'], endpoints: ['/api/users/*'] },
{ role: 'user', methods: ['GET', 'PUT'], endpoints: ['/api/profile'] },
],
defaultAllow: false,
},
});
// Per-request role:
await api.get('/api/users', { role: 'user' }); // ✅ allowed
await api.delete('/api/users/1', { role: 'user' }); // ❌ ERR_PERMISSION_DENIEDPayload Encryptor
AES-256-GCM authenticated encryption for request/response payloads:
const api = createClient({
baseURL: 'https://api.example.com',
encryption: {
key: 'hex-encoded-32-byte-key', // or auto-generated
},
});
// Payloads are encrypted before sending and decrypted on receiptIdempotency Manager
Automatic idempotency key generation for safe retries:
const api = createClient({
baseURL: 'https://api.example.com',
idempotency: {
ttl: 86400000, // 24 hours
methods: ['POST', 'PUT', 'PATCH'],
headerName: 'idempotency-key',
},
});
// POST/PUT/PATCH requests automatically include unique idempotency keys
// Duplicate idempotent requests return cached responsesV18 Features
Zero Trust Engine
Continuous verification with dynamic trust scoring — never implicitly trust any request:
const { createClient } = require('awsibnj');
const api = createClient({
baseURL: 'https://api.example.com',
zeroTrust: {
trustThreshold: 50, // minimum trust score to allow requests
maxTrustScore: 100,
decayRate: 5, // trust decays over time
decayIntervalMs: 60000, // decay every 60 seconds
},
});
// Low trust score → ERR_ZERO_TRUST_DENIEDThreat Intelligence
Real-time threat feed with IP reputation and attack pattern detection:
const api = createClient({
baseURL: 'https://api.example.com',
threatIntel: {
blockedIPs: ['1.2.3.4'],
suspiciousThreshold: 5, // auto-block after 5 suspicious events
autoBlock: true,
},
});
// Blocked IPs or detected threats → ERR_THREAT_DETECTEDSecure Session Manager
Cryptographic session tokens with IP/User-Agent binding:
const api = createClient({
baseURL: 'https://api.example.com',
sessionManager: {
tokenLength: 32,
maxAge: 3600000, // 1 hour
bindToIP: true, // prevent session hijacking
bindToUserAgent: true,
rotationInterval: 900000, // rotate every 15 minutes
},
});
// Invalid/expired/hijacked sessions → ERR_SESSION_INVALIDRequest Integrity Chain
Blockchain-inspired immutable request lineage with SHA-256 hashing:
const api = createClient({
baseURL: 'https://api.example.com',
integrityChain: {
algorithm: 'sha256',
maxChainLength: 10000,
},
});
// Every request is hashed into a chain: hash = SHA-256(prevHash + method + url + timestamp + bodyHash)
// Tampered chain → ERR_INTEGRITY_VIOLATIONAdaptive Rate Limiter
ML-inspired anomaly detection with dynamic rate adaptation:
const api = createClient({
baseURL: 'https://api.example.com',
adaptiveRateLimiter: {
baseRate: 100,
windowMs: 60000,
burstMultiplier: 1.5,
anomalyThreshold: 2.0, // standard deviations
minRate: 10,
maxRate: 500,
},
});
// Anomalous traffic patterns → ERR_ADAPTIVE_RATE_LIMITEDSecurity Headers Manager
Automatic OWASP-recommended security headers:
const api = createClient({
baseURL: 'https://api.example.com',
securityHeaders: {
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
frameOptions: 'DENY',
contentTypeOptions: 'nosniff',
referrerPolicy: 'strict-origin-when-cross-origin',
permissionsPolicy: { camera: 'none', microphone: 'none' },
},
});
// Generates: Strict-Transport-Security, X-Frame-Options, X-Content-Type-Options, etc.Encrypted Config Vault
AES-256-GCM encrypted storage for API keys and secrets:
const api = createClient({
baseURL: 'https://api.example.com',
configVault: {
masterKey: 'hex-encoded-32-byte-key',
},
});
// Store and retrieve encrypted config values
// Supports master key rotation and backup/restore
// Invalid access → ERR_VAULT_ACCESS_DENIEDMutual TLS Manager
mTLS certificate management with revocation and expiry validation:
const api = createClient({
baseURL: 'https://api.example.com',
mtls: {
trustedCerts: ['sha256-fingerprint-1', 'sha256-fingerprint-2'],
requireClientCert: true,
maxCertAge: 365 * 24 * 60 * 60 * 1000, // 1 year
},
});
// Certificate validation failure → ERR_MTLS_FAILEDV8 Features
Multi-Alias Field Resolution
const { FieldAliaser } = require('awsibnj');
const aliaser = new FieldAliaser();
// Register aliases for a canonical field
aliaser.register('userId', ['user_id', 'uid', 'member_id']);
aliaser.register('email', ['email_address', 'mail', 'e_mail']);
// Resolve any alias to canonical
aliaser.resolve('uid'); // { canonical: 'userId', matched: true, source: 'alias' }
aliaser.resolve('email_address'); // { canonical: 'email', matched: true }
// API-specific aliases (different APIs use different names)
aliaser.register('userId', ['usr_id'], { api: 'legacyService' });
aliaser.register('userId', ['memberId'], { api: 'memberService' });
aliaser.resolve('usr_id', 'legacyService'); // { canonical: 'userId', source: 'api:legacyService' }
// Get preferred alias for a specific API
aliaser.getAliasFor('userId', 'legacyService'); // 'usr_id'
// Bulk import/export
aliaser.bulkImport({ userId: ['uid', 'user_id'], name: ['full_name'] });
const definitions = aliaser.bulkExport();
// Conflict detection
const conflicts = aliaser.detectConflicts();
// Statistics
aliaser.getStats(); // { totalGroups, totalAliases, lookups, hits, misses, hitRate }Schema Migration Engine
const { SchemaMigrator } = require('awsibnj');
const migrator = new SchemaMigrator();
// Define migrations between versions
migrator.define('1.0', '2.0', {
rename: { user_name: 'username', phone_number: 'phone' },
add: { version: '2.0', updatedAt: () => new Date().toISOString() },
remove: ['legacy_field', 'deprecated_flag'],
transform: { price: (v) => v * 100 }, // dollars to cents
});
migrator.define('2.0', '3.0', {
rename: { username: 'displayName' },
add: { apiVersion: '3.0' },
});
// Migrate forward (auto-chains through intermediate versions)
const result = migrator.migrate(data, '1.0', '3.0');
// { data: { displayName: 'John', ... }, steps: ['1.0 → 2.0', '2.0 → 3.0'], success: true }
// Migrate backward (auto-reverses)
migrator.migrate(data, '3.0', '1.0');
// Dry-run to preview changes
const preview = migrator.dryRun(data, '1.0', '2.0');
// { changes: [{ type: 'renamed', field: 'user_name', ... }], path: [...], possible: true }
// Rollback last migration
migrator.rollback(data);
// Version detection
migrator.registerDetector((data) => data._version || null);
migrator.detectVersion({ _version: '2.0' }); // '2.0'
// History and stats
migrator.getHistory();
migrator.getStats(); // { totalMigrations, historyLength, versions }Batch Request Orchestrator
const { BatchOrchestrator } = require('awsibnj');
const batch = new BatchOrchestrator({
concurrency: 5,
failureStrategy: 'continue', // 'continue', 'abort', or 'retry'
maxRetries: 2,
});
// Parallel execution with concurrency control
const result = await batch.executeParallel([
{ id: 'users', execute: () => fetch('/api/users').then(r => r.json()) },
{ id: 'orders', execute: () => fetch('/api/orders').then(r => r.json()) },
{ id: 'products', execute: () => fetch('/api/products').then(r => r.json()) },
]);
// { results: [...], successful: 3, failed: 0, duration: 150 }
// Sequential execution (each request receives previous results)
const sequential = await batch.executeSequential([
{ id: 'user', execute: () => fetch('/api/user/1').then(r => r.json()) },
{ id: 'orders', execute: (prev) => fetch(`/api/orders?userId=${prev.user.id}`).then(r => r.json()) },
]);
// Aggregate results
const merged = batch.aggregate(result.results, 'merge'); // Merge all into one object
const collected = batch.aggregate(result.results, 'collect'); // Array of results
// Progress tracking
const batchWithProgress = new BatchOrchestrator({
onProgress: (completed, total, result) => console.log(`${completed}/${total}`),
});
// Statistics
batch.getStats(); // { totalBatches, totalRequests, successRate, avgDuration }Field Analytics Collector
const { FieldStats } = require('awsibnj');
const stats = new FieldStats();
// Record field transformations
stats.record('user_name', { targetKey: 'userName', confidence: 0.97, method: 'pattern_conversion' });
stats.record('usr_eml', { targetKey: 'userEmail', confidence: 0.72, method: 'fuzzy_abbreviation' });
// Per-field analytics
stats.getFieldStats('user_name');
// { count: 1, methods: { pattern_conversion: 1 }, avgConfidence: 0.97, ... }
// Top transformed fields
stats.getTopFields(10);
// [{ field: 'user_name', count: 100, primaryMethod: 'pattern_conversion', avgConfidence: 0.97 }, ...]
// Find fields that need schema definitions
stats.getLowConfidenceFields(0.75);
// [{ field: 'usr_eml', avgConfidence: 0.72, suggestedAction: 'add_synonym' }, ...]
// Coverage report
stats.getCoverageReport();
// { totalTransformations, uniqueFields, confidenceDistribution: { high, medium, low }, autoResolvedRate }
// Export all analytics
const analytics = stats.export();Conditional Transformation
const { ConditionalTransform } = require('awsibnj');
const ct = new ConditionalTransform();
// Value-based rules
ct.when('nullToNA', (v) => v === null, () => 'N/A');
ct.when('trimStrings', (v) => typeof v === 'string' && v !== v.trim(), (v) => v.trim());
ct.when('roundNumbers', (v) => typeof v === 'number' && !Number.isInteger(v), (v) => Math.round(v * 100) / 100);
// Context-aware rules (access sibling fields)
ct.when('vipDiscount',
(value, field, context) => context.isVip === true,
(value) => value * 0.8,
{ fields: ['price'] }
);
// Priority ordering
ct.when('lowPriority', condition, transform, { priority: 1 });
ct.when('highPriority', condition, transform, { priority: 10 }); // Evaluated first
// Default fallbacks
ct.otherwise('status', (v) => String(v).toUpperCase());
// Apply to a single field
const result = ct.apply(null, 'status');
// { value: 'N/A', rule: 'nullToNA', applied: true }
// Apply to all fields in an object
const { data, applied } = ct.applyAll({ name: ' John ', status: null, price: 100 });
// data: { name: 'John', status: 'N/A', price: 100 }
// Statistics
ct.getStats(); // { totalRules, totalEvaluations, ruleHits, topRules }Deep Merge Engine
const { DeepMerge } = require('awsibnj');
const merger = new DeepMerge({
arrayStrategy: 'union', // 'concat', 'union', 'replace', 'interleave'
conflictStrategy: 'latest', // 'first', 'latest', 'custom'
});
// Basic deep merge
const result = merger.merge(
{ user: { name: 'John', age: 30 }, tags: ['admin'] },
{ user: { age: 31, email: '[email protected]' }, tags: ['editor'] }
);
// { user: { name: 'John', age: 31, email: '[email protected]' }, tags: ['admin', 'editor'] }
// Custom conflict resolution
const custom = new DeepMerge({
conflictStrategy: 'custom',
conflictResolver: (key, a, b) => key === 'priority' ? Math.max(a, b) : b,
});
// Labeled merge with source tracking
const { result: merged, sources } = merger.mergeLabeled([
{ label: 'userApi', data: { name: 'John' } },
{ label: 'orderApi', data: { lastOrder: '2024-01-15' } },
]);
// sources: { name: 'userApi', lastOrder: 'orderApi' }
// Multiple sources
merger.merge(source1, source2, source3, source4);
// Prototype pollution protection built-in
// Statistics
merger.getStats(); // { totalMerges, conflicts, fieldsProcessed }Output Formatter
const { OutputFormatter } = require('awsibnj');
const fmt = new OutputFormatter();
// JSON pretty-print
fmt.toJSON({ name: 'John', age: 30 });
// XML serialization
fmt.toXML({ name: 'John', age: 30 });
// <?xml version="1.0" encoding="UTF-8"?><root><name>John</name><age>30</age></root>
// XML with custom root/item names
fmt.toXML(dataArray, { root: 'users', item: 'user' });
// CSV output
fmt.toCSV([{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]);
// name,age\nJohn,30\nJane,25
// Key-value pairs (great for logging)
fmt.toKeyValue({ user: { name: 'John' } });
// user.name: John
// Table format (great for console)
fmt.toTable([{ name: 'John', age: 30 }, { name: 'Jane', age: 25 }]);
// Template formatting
fmt.fromTemplate({ name: 'John', age: 30 }, 'Hello {{name}}, you are {{age}} years old');
// 'Hello John, you are 30 years old'
// Statistics
fmt.getStats(); // { json: 1, xml: 2, csv: 1, keyvalue: 0, table: 0, template: 1 }Request Interceptor Chain
const { RequestInterceptor } = require('awsibnj');
const interceptor = new RequestInterceptor();
// Add request interceptors (priority-ordered)
interceptor.useRequest('addAuth', (ctx) => ({
...ctx,
headers: { ...ctx.headers, Authorization: 'Bearer ' + getToken() },
}), { priority: 100, group: 'auth' });
interceptor.useRequest('addCorrelationId', (ctx) => ({
...ctx,
headers: { ...ctx.headers, 'X-Correlation-ID': generateId() },
}), { priority: 50, group: 'logging' });
// Add response interceptors
interceptor.useResponse('transformBody', (ctx) => ({
...ctx,
data: transformFields(ctx.data),
}));
// Run interceptor chains
const { context: req } = await interceptor.interceptRequest({ url: '/api/users', headers: {} });
const { context: res } = await interceptor.interceptResponse({ status: 200, data: rawData });
// Short-circuit (stop chain and return immediately)
interceptor.useRequest('rateLimit', (ctx) => {
if (isRateLimited()) return { ...ctx, _shortCircuit: true, error: 'Rate limited' };
return ctx;
}, { priority: 200 });
// Enable/disable groups
interceptor.setGroupEnabled('auth', false); // Disable all auth interceptors
// Per-interceptor error handling
interceptor.useRequest('risky', handler, {
onError: (err, ctx) => ({ ...ctx, fallback: true }),
});
// List, remove, stats
interceptor.list(); // { request: [...], response: [...] }
interceptor.remove('addAuth');
interceptor.getStats(); // { requestInterceptions, responseInterceptions, shortCircuits, errors }API Reference
bridge() — Axios Integration
const api = bridge(axiosInstance, options);Options:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| targetConvention | string | 'camelCase' | Output naming convention |
| sourceConvention | string | 'auto' | Input naming convention (auto-detected) |
| autoApplyThreshold | number | 0.85 | Minimum confidence to auto-apply a mapping |
| logMismatches | boolean | true | Log mismatches to console |
| schema | object | null | Field mapping and type coercion schema |
| transformRequests | boolean | true | Transform outgoing request bodies |
| cache | object | {} | Cache options: { maxSize, ttl, enabled } |
| validator | object | {} | Validator options: { strict, coerce, throwOnError } |
| normalizer | object | {} | Normalizer options |
| maxDepth | number | 50 | Max nesting depth |
| cloneInput | boolean | false | Deep-clone input before transforming |
Attached methods:
api.approve('src_key', 'targetKey') // Teach a mapping
api.reject('src_key', 'wrong', 'correct') // Reject a wrong mapping
api.exportCSV('/path/to/file.csv') // Export mismatch report (CSV)
api.exportJSON('/path/to/file.json') // Export mismatch report (JSON)
api.getStats() // Get session statistics
api.getPending() // Get unresolved mismatches
api.validate(data, schema) // Validate data against schema
api.normalize(body, statusCode) // Normalize response
api.use('name', middlewareFn, 'before') // Register middleware
api.clearCache() // Clear response cache
api.resetSession() // Reset stats and mismatches
api.bulkImport({ src: 'target', ... }) // Import learned mappings
api.bulkExport() // Export all learned mappingsbridgeFetch() — Native Fetch Integration
const api = bridgeFetch(options);Supports all options from bridge() plus:
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| retries | number | 0 | Max retry attempts on failure |
| retryDelay | number | 1000 | Base delay in ms (doubles each retry) |
HTTP Methods:
await api.get(url, config)
await api.post(url, body, config)
await api.put(url, body, config)
await api.patch(url, body, config)
await api.delete(url, body, config)
await api.head(url, config)
await api.options(url, config)
await api.request(method, url, body, config) // Generictransform() — Direct Transform
const { transform } = require('awsibnj');
// Simple
const result = transform({ snake_key: 'value' });
// With options
const result = transform(data, {
targetConvention: 'PascalCase',
schema: mySchema,
direction: 'toBackend',
});createTransformer() — Reusable Instance
const { createTransformer } = require('awsibnj');
const t = createTransformer({ logMismatches: false });
const r1 = t.transform({ first_name: 'John' });
const r2 = t.transform({ last_name: 'Doe' });
console.log(t.getStats()); // Stats accumulate across callsV7 Features
Weighted Ensemble Fuzzy Matcher
v7 replaces the max-based scoring of v6 with a weighted ensemble that combines all 7 matching strategies with tuned weights for 99%+ accuracy:
const { FuzzyMatcher } = require('awsibnj');
const fuzzy = new FuzzyMatcher();
// Strategies: Levenshtein, token match, vowel-drop, phonetic,
// abbreviation, n-gram, substring — all combined
const result = fuzzy.findBestMatch('usr_email', ['user_email', 'user_name']);
console.log(result);
// { match: 'user_email', confidence: 0.92, method: 'fuzzy_ensemble' }
// Get/set strategy weights
console.log(fuzzy.getWeights());
// { levenshtein: 0.30, tokenMatch: 0.25, vowelDrop: 0.10, ... }
fuzzy.setWeights({ levenshtein: 0.5, tokenMatch: 0.3 }); // Custom tuningN-Gram Similarity Matching
New bigram-based similarity scoring that catches matches missed by Levenshtein distance — especially effective for short/garbled field names:
const { ngramSimilarity, ngrams } = require('awsibnj/src/fuzzy-matcher');
// Generate bigrams
ngrams('hello'); // ['he', 'el', 'll', 'lo']
// Dice coefficient similarity
ngramSimilarity('username', 'usrname'); // ~0.67
ngramSimilarity('email', 'emial'); // ~0.50Context-Aware Field Resolution
v7's transformer uses abbreviation expansion in semantic similarity, meaning fields like txn_id, inv_num, or cert_id are automatically matched to transaction_id, invoice_number, or certificate_id even without a schema.
Enhanced Type Coercion
v7 adds case-insensitive boolean parsing, percentage strings, comma-separated numbers, and more date formats:
const { TypeCoercer } = require('awsibnj');
const coercer = new TypeCoercer();
// Case-insensitive booleans
coercer.coerceValue('TRUE', 'boolean', 'flag'); // { value: true, coerced: true }
coercer.coerceValue('Yes', 'boolean', 'active'); // { value: true, coerced: true }
coercer.coerceValue('OFF', 'boolean', 'enabled'); // { value: false, coerced: true }
// Percentage strings
coercer.coerceValue('50%', 'float', 'rate'); // { value: 0.5, coerced: true }
coercer.coerceValue('75%', 'number', 'completion');// { value: 0.75, coerced: true }
// Comma-separated numbers
coercer.coerceValue('1,000', 'integer', 'count'); // { value: 1000, coerced: true }
coercer.coerceValue('1,234.56', 'float', 'amt'); // { value: 1234.56, coerced: true }
// More date formats (DD/MM/YYYY, MM-DD-YYYY)
coercer.coerceValue('15/01/2024', 'date', 'created_at'); // Date object
// Comma-separated strings as arrays
coercer.coerceValue('red,green,blue', 'array', 'colors'); // ['red', 'green', 'blue']Expanded Synonym Dictionary
v7 adds 4 new domain dictionaries with 60+ new synonym groups:
| Domain | Example Groups | |--------|---------------| | Financial | balance/account_balance, credit/debit, routing_number/sort_code, transfer/wire/remittance | | IoT/Hardware | device/gadget/endpoint, sensor/probe/detector, temperature/celsius, battery/charge | | Education | student/pupil/learner, teacher/instructor/professor, course/class/module, grade/score/mark | | Social | follower/subscriber/fan, post/article/entry, like/upvote/reaction, notification/alert/push |
Database Prefix Stripping
The cryptic resolver now automatically strips common database prefixes (tbl_, fk_, pk_, vw_, sp_, idx_, fn_) before matching:
const { CrypticResolver } = require('awsibnj');
const resolver = new CrypticResolver();
resolver.resolve('tbl_user_name', ['user_name', 'account_name']);
// { match: 'user_name', confidence: 0.70, method: 'db_prefix_strip' }
resolver.resolve('fk_order_id', ['order_id', 'product_id']);
// { match: 'order_id', confidence: 0.70, method: 'db_prefix_strip' }V6 Features
Enhanced Fuzzy Matcher
Multi-strategy fuzzy matching engine for resolving typos, abbreviations, and near-matches with 97%+ accuracy:
const { FuzzyMatcher } = require('awsibnj');
const fuzzy = new FuzzyMatcher({
levenshteinThreshold: 0.35, // Max normalized distance to consider
minConfidence: 0.55, // Minimum confidence to report
expandAbbreviations: true, // Expand common abbreviations (usr→user, eml→email)
usePhonetic: true, // Use phonetic similarity (ph/f confusion, etc.)
useVowelDrop: true, // Detect vowel-dropped abbreviations (usr→user)
});
// Find best match using 5 strategies: Levenshtein, token matching,
// vowel-drop detection, phonetic similarity, abbreviation expansion
const result = fuzzy.findBestMatch('usr_email', ['user_email', 'user_name', 'phone']);
// { match: 'user_email', confidence: 0.92, method: 'fuzzy_abbreviation' }
// Works with common typos
const typo = fuzzy.findBestMatch('frist_name', ['first_name', 'last_name']);
// { match: 'first_name', confidence: 0.88, method: 'fuzzy_levenshtein' }
// Vowel-dropped abbreviations
const abbr = fuzzy.findBestMatch('usr_nm', ['user_name', 'email']);
// { match: 'user_name', confidence: 0.85, method: 'fuzzy_vowel_drop' }
// Confidence boosting when multiple strategies agree
// If 2+ strategies score > 0.5, the best score gets a boost
// Check available strategies
fuzzy.getStrategies();
// { levenshtein: true, tokenMatch: true, vowelDrop: true, phonetic: true, abbreviation: true }Built-in abbreviation map includes 80+ common developer abbreviations:
usr→user, eml→email, addr→address, desc→description, cfg→config, pwd→password, tok→token, perm→permission, loc→location, etc.
Matching strategies:
| Strategy | What it detects | Example |
|----------|----------------|---------|
| Levenshtein | Character-level similarity | frist_name → first_name |
| Token match | Token-level similarity | user_full_name → full_user_name |
| Vowel drop | Missing vowels | usr → user, eml → email |
| Phonetic | Sound-alike words | fone → phone |
| Abbreviation | Known abbreviations | addr → address, msg → message |
Cryptic Name Resolver
Best-effort resolution of cryptic and arbitrary field names commonly found in legacy systems:
const { CrypticResolver } = require('awsibnj');
const resolver = new CrypticResolver({
minConfidence: 0.45, // Minimum confidence to report
stripCrypticPrefix: true, // Strip prefixes like x_, z9_, etc.
useSuffixMatching: true, // Match by shared suffixes (_id, _flag, _date, etc.)
useVocabulary: true, // Match 