meridianjs 0.2.3 → 0.2.5

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 (94) hide show
  1. package/CHANGELOG.md +97 -150
  2. package/README.md +214 -122
  3. package/dist/analytics/collector.d.ts +44 -0
  4. package/dist/analytics/collector.d.ts.map +1 -0
  5. package/dist/analytics/collector.js +82 -0
  6. package/dist/analytics/collector.js.map +1 -0
  7. package/dist/analytics/index.d.ts +3 -0
  8. package/dist/analytics/index.d.ts.map +1 -0
  9. package/dist/analytics/index.js +2 -0
  10. package/dist/analytics/index.js.map +1 -0
  11. package/dist/capabilities/index.d.ts +3 -0
  12. package/dist/capabilities/index.d.ts.map +1 -0
  13. package/dist/capabilities/index.js +2 -0
  14. package/dist/capabilities/index.js.map +1 -0
  15. package/dist/capabilities/registry.d.ts +6 -0
  16. package/dist/capabilities/registry.d.ts.map +1 -0
  17. package/dist/capabilities/registry.js +61 -0
  18. package/dist/capabilities/registry.js.map +1 -0
  19. package/dist/core/pipeline.d.ts +3 -1
  20. package/dist/core/pipeline.d.ts.map +1 -1
  21. package/dist/core/pipeline.js +42 -0
  22. package/dist/core/pipeline.js.map +1 -1
  23. package/dist/core/types.d.ts +42 -1
  24. package/dist/core/types.d.ts.map +1 -1
  25. package/dist/core/types.js +1 -1
  26. package/dist/core/types.js.map +1 -1
  27. package/dist/debug/index.d.ts +3 -0
  28. package/dist/debug/index.d.ts.map +1 -0
  29. package/dist/debug/index.js +2 -0
  30. package/dist/debug/index.js.map +1 -0
  31. package/dist/debug/recorder.d.ts +32 -0
  32. package/dist/debug/recorder.d.ts.map +1 -0
  33. package/dist/debug/recorder.js +76 -0
  34. package/dist/debug/recorder.js.map +1 -0
  35. package/dist/generator/cli.d.ts +20 -0
  36. package/dist/generator/cli.d.ts.map +1 -0
  37. package/dist/generator/cli.js +56 -0
  38. package/dist/generator/cli.js.map +1 -0
  39. package/dist/generator/index.d.ts +9 -0
  40. package/dist/generator/index.d.ts.map +1 -0
  41. package/dist/generator/index.js +49 -0
  42. package/dist/generator/index.js.map +1 -0
  43. package/dist/generator/openapi.d.ts +13 -0
  44. package/dist/generator/openapi.d.ts.map +1 -0
  45. package/dist/generator/openapi.js +49 -0
  46. package/dist/generator/openapi.js.map +1 -0
  47. package/dist/generator/templates.d.ts +16 -0
  48. package/dist/generator/templates.d.ts.map +1 -0
  49. package/dist/generator/templates.js +292 -0
  50. package/dist/generator/templates.js.map +1 -0
  51. package/dist/index.d.ts +33 -0
  52. package/dist/index.d.ts.map +1 -1
  53. package/dist/index.js +101 -0
  54. package/dist/index.js.map +1 -1
  55. package/dist/policies/builtin.d.ts +40 -0
  56. package/dist/policies/builtin.d.ts.map +1 -0
  57. package/dist/policies/builtin.js +186 -0
  58. package/dist/policies/builtin.js.map +1 -0
  59. package/dist/policies/index.d.ts +2 -0
  60. package/dist/policies/index.d.ts.map +1 -0
  61. package/dist/policies/index.js +2 -0
  62. package/dist/policies/index.js.map +1 -0
  63. package/dist/public.d.ts +17 -0
  64. package/dist/public.d.ts.map +1 -1
  65. package/dist/public.js +15 -0
  66. package/dist/public.js.map +1 -1
  67. package/dist/schema/index.d.ts +2 -0
  68. package/dist/schema/index.d.ts.map +1 -0
  69. package/dist/schema/index.js +2 -0
  70. package/dist/schema/index.js.map +1 -0
  71. package/dist/schema/monitor.d.ts +23 -0
  72. package/dist/schema/monitor.d.ts.map +1 -0
  73. package/dist/schema/monitor.js +70 -0
  74. package/dist/schema/monitor.js.map +1 -0
  75. package/dist/services/index.d.ts +2 -0
  76. package/dist/services/index.d.ts.map +1 -0
  77. package/dist/services/index.js +2 -0
  78. package/dist/services/index.js.map +1 -0
  79. package/dist/services/service-client.d.ts +41 -0
  80. package/dist/services/service-client.d.ts.map +1 -0
  81. package/dist/services/service-client.js +243 -0
  82. package/dist/services/service-client.js.map +1 -0
  83. package/dist/transactions/index.d.ts +3 -0
  84. package/dist/transactions/index.d.ts.map +1 -0
  85. package/dist/transactions/index.js +2 -0
  86. package/dist/transactions/index.js.map +1 -0
  87. package/dist/transactions/saga.d.ts +22 -0
  88. package/dist/transactions/saga.d.ts.map +1 -0
  89. package/dist/transactions/saga.js +58 -0
  90. package/dist/transactions/saga.js.map +1 -0
  91. package/dist/validation/drift-detector.d.ts.map +1 -1
  92. package/dist/validation/drift-detector.js +17 -8
  93. package/dist/validation/drift-detector.js.map +1 -1
  94. package/package.json +7 -3
package/CHANGELOG.md CHANGED
@@ -1,174 +1,121 @@
1
1
  # Changelog
2
2
 
3
- All notable changes to this project will be documented in this file.
3
+ All notable changes to Meridian are documented here.
4
4
 
5
- The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
- and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+ ---
7
6
 
8
- ## [0.2.3] - 2026-06-01
7
+ ## [0.2.5] Adoption Sprint
9
8
 
10
9
  ### Added
11
- - **Core stabilization**: Integrated 741 contract tests (19 invariants × 39 adapters) verifying error handling, rate limiting, retries, timeouts, pagination, and request/response normalization across every provider adapter via the shared `runProviderContract` harness.
12
- - **Contract test suite & CLI runner**: Run tests with `npm run test:contracts` or per-provider via `npm run test:contracts stripe`.
13
- - **CI pipeline integration**: Added contract validation to the GitHub Actions test runner.
14
- - **Provider status matrix**: Published a complete compatibility checklist in the README.
15
- - **Comprehensive developer documentation**: Added 8 core manuals under the `docs/` folder.
16
10
 
17
- ## [2.0.2] - 2025-01-XX
11
+ **Service Routing Weighted & Geo**
12
+ - `strategy: "weighted"` — probabilistic load distribution across providers using a `weights` map (e.g. `{ stripe: 70, razorpay: 30 }`)
13
+ - `strategy: "geo"` — region-aware routing via `MERIDIAN_REGION` env var or `defaultRegion`; `regions` maps region names to ordered provider lists
14
+ - Both strategies select a primary provider via `selectIndex()` and failover through remaining providers on retryable errors
18
15
 
19
- ### Changed
20
- - **Public API lockdown**: Package now exports from `src/public.ts` as the single public entry point. This restricts consumer access to only documented, stable APIs.
21
- - **Error contract enhancement**: `MeridianError` now exposes a `code` getter returning a frozen public `MeridianErrorCode` (e.g. `AUTH_FAILED`, `RATE_LIMITED`, `UPSTREAM_5XX`), derived from `category` and HTTP status. This provides a stable, documented error contract independent of the internal category.
22
-
23
- ### Internal
24
- - Fixed incomplete code from prior refactoring in error message formatting
25
- - Corrected timeout error construction to use proper `MeridianError` class instantiation
26
- - Improved code consistency across error handling paths
27
-
28
- ## [2.0.1] - 2025-01-14
29
-
30
- ### Fixed
31
- - Fix incorrect internal package version. SDK_VERSION now correctly reads from package.json as single source of truth, eliminating version mismatches.
16
+ **Policy Engine — Three New Built-ins**
17
+ - `redact(fields, providers?)` redacts dot-notation field paths (e.g. `"user.ssn"`) from the request body before it reaches the provider; does not block the request
18
+ - `requireFields(fields, providers?)` blocks requests missing required body fields; returns `MeridianError` with `category: "validation"`
19
+ - `denyCountries(codes, field?)` — blocks requests where `body.country`, `body.country_code`, or `body.countryCode` matches a denied ISO 3166-1 alpha-2 code
32
20
 
33
- ## [2.0.0] - 2025-01-09
21
+ **Schema Monitor Three New Methods**
22
+ - `meridian.schema.diff(provider, endpoint, data)` — returns drift between current data and stored schema baseline
23
+ - `meridian.schema.report(provider)` — returns structured `SchemaReport` with all snapshotted endpoints, field counts, and schemas
24
+ - `meridian.schema.alert(provider, endpoint, data, callback)` — runs drift check and invokes callback with drifts if any are detected; returns the drifts array
34
25
 
35
- **This release establishes the long-term safety contract of the SDK.** All breaking changes are intentional and enforce safety by default.
26
+ **Documentation**
27
+ - `docs/payments/` — Stripe/Razorpay/Cashfree unified interface, failover, analytics
28
+ - `docs/llms/` — OpenAI→Anthropic→Gemini failover, production chat endpoints
29
+ - `docs/communications/` — Twilio→MSG91 SMS fallback, email fallback patterns
30
+ - `docs/failover/` — all 7 routing strategies with runnable examples
31
+ - `docs/policies/` — all policy built-ins with fintech compliance example
32
+ - `docs/schema-drift/` — full snapshot→diff→report→alert workflow
33
+ - `docs/transactions/` — saga pattern with multi-step rollback example
36
34
 
37
- **⚠️ BREAKING: This is a major version release with breaking changes. See migration guide below.**
35
+ **Cost Intelligence**
36
+ - `MeridianConfig.providerCosts` — declare per-request cost for each provider (e.g. `{ openai: 0.03, anthropic: 0.01 }`)
37
+ - `meridian.cost(currency?)` — returns `CostReport` with per-provider request counts, cost-per-request, estimated spend, and a total; resets with `analytics.reset()`
38
+ - `CostReport`, `CostEntry` exported from `meridianjs`
38
39
 
39
- ### Breaking Changes
40
+ **Examples**
41
+ - `examples/nextjs-openai-failover/` — Next.js 14 App Router LLM endpoint with failover
42
+ - `examples/express-stripe/` — Express server with pagination, idempotency, health endpoint
43
+ - `examples/nestjs-payments/` — NestJS module with DI, weighted routing, saga transaction
44
+ - `examples/fastify-webhooks/` — Fastify webhook verification with raw body parsing
45
+ - `examples/multi-provider-llm/` — Node.js script demonstrating failover, cheapest routing, drift detection, analytics
40
46
 
41
- - **Constructor removed**: `new Meridian(config)` no longer works. Use `await Meridian.create(config)` instead. This enforces async initialization and prevents use before initialization.
47
+ ---
42
48
 
43
- - **Mandatory initialization**: All SDK methods throw if called before `Meridian.create()` completes. This prevents undefined behavior from uninitialized state.
49
+ ## [0.2.4] Operational Intelligence
44
50
 
45
- - **StateStorage enforcement**:
46
- - `mode: "distributed"` **requires** a `StateStorage` implementation. Startup fails without it.
47
- - Configurations without `stateStorage` require explicit `localUnsafe: true` to acknowledge the limitation.
48
- - This prevents accidental use of in-memory state in production deployments.
49
-
50
- - **Node.js version requirement**: SDK now explicitly requires Node.js ≥18.0.0 (was implicit before). This is enforced via `engines` field in `package.json`.
51
-
52
- - **Typed request options**: `ProviderClient` methods now use strict `RequestOptions` types instead of `any`. Invalid options are caught at compile time.
51
+ This release transforms Meridian from an API normalisation SDK into an operational layer for third-party integrations. Every feature below works with zero configuration beyond what you already have.
53
52
 
54
53
  ### Added
55
54
 
56
- - **Safety guarantees**:
57
- - Fail-fast initialization enforcement
58
- - Fail-closed state management
59
- - Guaranteed secret redaction in all observability paths
60
- - No silent degradation - all failures are explicit
61
-
62
- - **Pagination safety**: Cycle detection and max page limit (1000 pages) prevent infinite loops from malformed adapters.
63
-
64
- - **Adapter validation safety**: Validation uses fake test tokens to prevent side effects during adapter checks.
65
-
66
- - **Instance-scoped adapter cache**: Prevents config sharing across Meridian instances.
55
+ **Service Abstraction & Failover**
56
+ - `meridian.service("name")` logical service client that routes across multiple providers
57
+ - `MeridianConfig.services` configure provider groups with a routing strategy
58
+ - Routing strategies: `"failover"`, `"round-robin"`, `"lowest-latency"`, `"cheapest"`, `"highest-success-rate"`
59
+ - `"lowest-latency"` self-calibrates via EWMA over `meta.trace.latency`
60
+ - `"highest-success-rate"` routes dynamically using live analytics data
61
+ - `"cheapest"` accepts a `costs` map and fails over in ascending cost order
62
+
63
+ **Request Trace**
64
+ - `result.meta.trace` — always present: `retries`, `latency`, `circuitBreaker`, `rateLimitRemaining`
65
+ - `ResponseContext.trace` trace data now visible to all observability adapters
66
+
67
+ **Analytics & Health**
68
+ - `meridian.analytics()` — per-provider: `requests`, `errors`, `errorRate`, `successRate`, `avgLatency`, `p95Latency`
69
+ - `meridian.health()` — per-provider status (`healthy`/`degraded`/`down`) combining analytics + circuit breaker
70
+ - `AnalyticsCollector` always active, zero configuration required
71
+
72
+ **Debug Recording & Replay**
73
+ - `meridian.debug.enable()` / `.disable()` / `.clear()`
74
+ - `meridian.debug.recordings()` — full log with trace data and original request options
75
+ - `meridian.replay(requestId)` — re-execute any recorded request with identical options
76
+
77
+ **Policy Engine**
78
+ - `MeridianConfig.policies` — evaluate before every request, block or allow
79
+ - Built-ins: `blockPII()`, `allowedProviders()`, `blockedProviders()`, `readOnly()`, `customPolicy()`
80
+ - PII detection covers: credit cards, SSNs, emails, phone numbers, Aadhaar, PAN
81
+ - Blocked requests throw `MeridianError` with `category: "validation"` — no network round-trip wasted
82
+
83
+ **Multi-Provider Transactions**
84
+ - `meridian.transaction(steps)` — saga pattern across multiple providers
85
+ - Per-step `rollback` function; executed in reverse order on failure
86
+ - `TransactionError` carries `failed`, `succeeded`, `rolledBack`, `rollbackErrors`, `results`
87
+
88
+ **Schema Drift Detection (enhanced)**
89
+ - `meridian.schema.snapshot(provider, endpoint, data)` — baseline any live response
90
+ - `meridian.schema.check(provider, endpoint, data)` — detect field removals, type changes, required changes
91
+ - `DriftDetector` now recurses into nested object and array schemas
92
+
93
+ **Provider Capability Registry**
94
+ - `meridian.providers()` — all configured providers with capability arrays
95
+ - `meridian.findProviders({ capability })` — filter by capability string
96
+ - 39 providers mapped: chat, embeddings, streaming, payments, kyc, upi, shipping, maps, and more
97
+
98
+ **Adapter Generator**
99
+ - `npx meridian generate --provider <name> [--openapi spec.json]`
100
+ - Parses OpenAPI 3.x JSON: extracts base URL, auth type, endpoint list
101
+ - Generates `adapter.ts`, `adapter.test.ts` (8 passing tests out of the box), `pagination.ts`, `index.ts`
67
102
 
68
103
  ### Changed
69
104
 
70
- - All examples and documentation updated to use `Meridian.create()` pattern.
71
- - Enhanced header sanitization to handle variations (e.g., "X-API-Key" matches "apikey").
72
- - Improved error messages for state management failures.
73
-
74
- ### Fixed
75
-
76
- - Secrets no longer leak through observability (logs, errors, metrics).
77
- - Adapter cache properly scoped per instance.
78
- - Pagination cannot infinite-loop.
79
-
80
- ### Migration from 1.x
81
-
82
- **Required changes:**
83
-
84
- 1. **Replace constructor with factory method:**
85
- ```typescript
86
- // ❌ OLD (1.x)
87
- const meridian = new Meridian({ ... });
88
-
89
- // ✅ NEW (2.0.0)
90
- const meridian = await Meridian.create({ ... });
91
- ```
92
-
93
- 2. **Add state management configuration:**
94
- ```typescript
95
- // For local development
96
- const meridian = await Meridian.create({
97
- ...config,
98
- localUnsafe: true, // Required for local dev
99
- });
100
-
101
- // For production/distributed
102
- const meridian = await Meridian.create({
103
- ...config,
104
- mode: "distributed",
105
- stateStorage: new YourStateStorage(), // Required
106
- });
107
- ```
108
-
109
- 3. **Ensure Node.js ≥18.0.0** (now enforced via `engines` field)
105
+ - `DriftDetector.detect()` now recursively compares nested schemas (previously top-level only)
106
+ - `ResponseContext` gains optional `trace?: RequestTrace` for observability adapter use
110
107
 
111
- 4. **Update TypeScript types:** `ProviderClient` methods now use strict `RequestOptions` instead of `any`
112
-
113
- ## [0.1.3] - 2026-05-31
114
-
115
- ### Added
116
- - **Razorpay adapter** (`src/providers/razorpay/`) — full `ProviderAdapter` implementation for India's largest payment gateway
117
- - Basic auth with `key_id:key_secret` (supports `username`/`password` or `apiKey`/`custom.keySecret`)
118
- - `X-Idempotency-Key` header support on write operations
119
- - Error mapping: 400/422→validation, 401/403→auth, 404→validation, 429→rate_limit, 5xx→provider (retryable)
120
- - Offset-based pagination via Razorpay's `items[]`/`count`/`skip` list format
121
- - Idempotency config for orders, payments, refunds, transfers, payouts, subscriptions, invoices
122
- - 31 contract tests covering all adapter methods
123
- - Registered 17 additional Indian provider adapters in the built-in registry (Cashfree, PayU, Juspay, MSG91, Exotel, Gupshup, Setu, Decentro, Shiprocket, Delhivery, HyperVerge, Digio, Karza, IDfy, Cleartax, MapMyIndia, Perfios) — implementations pending
124
- - `ROADMAP.md` — comprehensive future plan covering Indian and international provider coverage, SDK capabilities (webhook verification, streaming, mock adapter, batch operations, India compliance mode, UPI helpers), and version targets through v1.0
125
-
126
- ## [Unreleased]
127
-
128
- ### Added
129
- - Auto-registration of built-in provider adapters
130
- - Configuration validation for rate limit, retry, circuit breaker, and timeout settings
131
- - Fallback error handling when adapter `parseError()` throws unexpectedly
132
-
133
- ### Fixed
134
- - Removed circular self-dependency in package.json that caused installation failures
135
- - Fetch timeout now properly cancels requests using `AbortController` (prevents resource leaks)
136
- - GitHub 403 errors now correctly distinguished between rate limit and permission denied
137
- - Adapter validation now runs in production (logs warning instead of throwing)
138
-
139
- ### Changed
140
- - Improved type safety: `authToken` parameter now uses `AuthToken` type instead of `any`
141
-
142
- ## [1.0.2] - 2024-01-XX
143
-
144
- ### Fixed
145
- - Constructor now supports both nested and flat provider config structures
146
- - GitHub adapter auto-registers when provider is configured
147
-
148
- ## [1.0.1] - 2024-01-XX
149
-
150
- ### Fixed
151
- - TypeScript strict mode compatibility issues
152
- - Optional property handling in exactOptionalPropertyTypes mode
153
-
154
- ## [1.0.0] - 2024-01-XX
155
-
156
- ### Added
157
- - Core request pipeline with unified response normalization
158
- - Circuit breaker implementation with state machine
159
- - Rate limiting with token bucket and adaptive backoff
160
- - Retry strategy with exponential backoff and idempotency awareness
161
- - Idempotency resolver with SAFE/IDEMPOTENT/CONDITIONAL/UNSAFE levels
162
- - Schema validation with pluggable storage and drift detection
163
- - Observability adapter pattern with console and no-op implementations
164
- - GitHub provider adapter with OAuth support
165
- - Pagination normalization for cursor and offset-based strategies
166
- - Error normalization with unified error contract
167
- - TypeScript strict mode with full type safety
168
-
169
- [Unreleased]: https://github.com/Raghaverma/Meridian/compare/v1.0.2...HEAD
170
- [1.0.2]: https://github.com/Raghaverma/Meridian/compare/v1.0.1...v1.0.2
171
- [1.0.1]: https://github.com/Raghaverma/Meridian/compare/v1.0.0...v1.0.1
172
- [1.0.0]: https://github.com/Raghaverma/Meridian/releases/tag/v1.0.0
108
+ ---
173
109
 
110
+ ## [0.2.3] — SDK Prototype
174
111
 
112
+ - 39 provider adapters with unified contract
113
+ - Normalized responses, errors, pagination, rate limits
114
+ - Circuit breaker, retry, rate limiting
115
+ - Webhook verification
116
+ - Contract testing suite (19 invariants per adapter)
117
+ - Streaming (SSE) for OpenAI, Anthropic, Gemini, Mistral, Cohere
118
+ - Batch requests with concurrency control
119
+ - India compliance mode (DPDPA PII redaction)
120
+ - Proxy server (`boundary-proxy`)
121
+ - Observability adapters: Console, NoOp, OpenTelemetry, Prometheus