@kelviq/mcp-server 0.2.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.
Files changed (149) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +322 -0
  3. package/dist/config.d.ts +16 -0
  4. package/dist/config.js +45 -0
  5. package/dist/config.js.map +1 -0
  6. package/dist/docs/README.md +128 -0
  7. package/dist/docs/api-reference/authentication.md +41 -0
  8. package/dist/docs/backend-integration/node-sdk.md +1040 -0
  9. package/dist/docs/backend-integration/python-sdk.md +1198 -0
  10. package/dist/docs/changelog/app.md +80 -0
  11. package/dist/docs/changelog/checkout-api.md +59 -0
  12. package/dist/docs/changelog/js-promotions-ui.md +14 -0
  13. package/dist/docs/changelog/js-sdk.md +281 -0
  14. package/dist/docs/changelog/node-sdk.md +378 -0
  15. package/dist/docs/changelog/python-sdk.md +456 -0
  16. package/dist/docs/changelog/react-sdk.md +580 -0
  17. package/dist/docs/checkout/checkout-configuration.md +434 -0
  18. package/dist/docs/coustomers-management/overview.md +111 -0
  19. package/dist/docs/customer-portal/overview.md +81 -0
  20. package/dist/docs/frontend-integration/js-sdk.md +676 -0
  21. package/dist/docs/frontend-integration/promotions-ui-js.md +265 -0
  22. package/dist/docs/frontend-integration/react-promotions-ui.md +361 -0
  23. package/dist/docs/frontend-integration/react-sdk.md +1187 -0
  24. package/dist/docs/frontend-integration/react-ui.md +771 -0
  25. package/dist/docs/getstarted/fees.md +160 -0
  26. package/dist/docs/getstarted/introduction-to-kelviq.md +80 -0
  27. package/dist/docs/getstarted/merchant-of-record.md +64 -0
  28. package/dist/docs/getstarted/review-process.md +190 -0
  29. package/dist/docs/guides/subscription-integration-for-nextjs.md +512 -0
  30. package/dist/docs/guides/subscription-integration.md +291 -0
  31. package/dist/docs/guides/webhooks.md +963 -0
  32. package/dist/docs/legal/approved-prohibited-policy.md +252 -0
  33. package/dist/docs/legal/buyer-terms.md +177 -0
  34. package/dist/docs/legal/compliant-user-flow.md +216 -0
  35. package/dist/docs/legal/master-service-agreement.md +404 -0
  36. package/dist/docs/legal/payment-flow-diagram.md +188 -0
  37. package/dist/docs/legal/seller-terms.md +169 -0
  38. package/dist/docs/manifest.json +415 -0
  39. package/dist/docs/monetization/offerings.md +156 -0
  40. package/dist/docs/monetization/pricing-tables.md +226 -0
  41. package/dist/docs/monetization/targeting-rules.md +278 -0
  42. package/dist/docs/openapi.json +5479 -0
  43. package/dist/docs/payouts/overview.md +43 -0
  44. package/dist/docs/payouts/payout-account.md +12 -0
  45. package/dist/docs/payouts/transactions.md +23 -0
  46. package/dist/docs/product-catalog/digital-downloads.md +117 -0
  47. package/dist/docs/product-catalog/discounts.md +69 -0
  48. package/dist/docs/product-catalog/entitlements.md +428 -0
  49. package/dist/docs/product-catalog/free-and-trials.md +36 -0
  50. package/dist/docs/product-catalog/license-keys.md +324 -0
  51. package/dist/docs/product-catalog/links.md +92 -0
  52. package/dist/docs/product-catalog/location-based-pricing.md +41 -0
  53. package/dist/docs/product-catalog/one-time-payments.md +24 -0
  54. package/dist/docs/product-catalog/plans.md +199 -0
  55. package/dist/docs/product-catalog/products.md +60 -0
  56. package/dist/docs/product-catalog/subscriptions.md +29 -0
  57. package/dist/docs/product-catalog/tax-settings.md +37 -0
  58. package/dist/docs/product-catalog/usage-based-billing.md +119 -0
  59. package/dist/docs/promotions/create-a-promotion.md +75 -0
  60. package/dist/docs/promotions/customize-banner.md +41 -0
  61. package/dist/docs/promotions/integrate.md +38 -0
  62. package/dist/docs/promotions/overview.md +51 -0
  63. package/dist/docs/quickstart/core-concepts.md +146 -0
  64. package/dist/docs/quickstart/dashboard-setup.md +129 -0
  65. package/dist/docs/quickstart/integrate-with-your-app.md +149 -0
  66. package/dist/docs/sales/checkout-sessions.md +58 -0
  67. package/dist/docs/sales/orders.md +76 -0
  68. package/dist/http/client.d.ts +28 -0
  69. package/dist/http/client.js +76 -0
  70. package/dist/http/client.js.map +1 -0
  71. package/dist/http/errors.d.ts +20 -0
  72. package/dist/http/errors.js +58 -0
  73. package/dist/http/errors.js.map +1 -0
  74. package/dist/resources/docs-index.d.ts +25 -0
  75. package/dist/resources/docs-index.js +109 -0
  76. package/dist/resources/docs-index.js.map +1 -0
  77. package/dist/resources/index.d.ts +2 -0
  78. package/dist/resources/index.js +73 -0
  79. package/dist/resources/index.js.map +1 -0
  80. package/dist/schemas/kelviq.d.ts +1304 -0
  81. package/dist/schemas/kelviq.js +468 -0
  82. package/dist/schemas/kelviq.js.map +1 -0
  83. package/dist/server.d.ts +2 -0
  84. package/dist/server.js +41 -0
  85. package/dist/server.js.map +1 -0
  86. package/dist/tools/_util.d.ts +15 -0
  87. package/dist/tools/_util.js +15 -0
  88. package/dist/tools/_util.js.map +1 -0
  89. package/dist/tools/checkout.d.ts +3 -0
  90. package/dist/tools/checkout.js +18 -0
  91. package/dist/tools/checkout.js.map +1 -0
  92. package/dist/tools/customers.d.ts +3 -0
  93. package/dist/tools/customers.js +32 -0
  94. package/dist/tools/customers.js.map +1 -0
  95. package/dist/tools/docs.d.ts +2 -0
  96. package/dist/tools/docs.js +43 -0
  97. package/dist/tools/docs.js.map +1 -0
  98. package/dist/tools/entitlements.d.ts +3 -0
  99. package/dist/tools/entitlements.js +22 -0
  100. package/dist/tools/entitlements.js.map +1 -0
  101. package/dist/tools/features.d.ts +3 -0
  102. package/dist/tools/features.js +55 -0
  103. package/dist/tools/features.js.map +1 -0
  104. package/dist/tools/index.d.ts +3 -0
  105. package/dist/tools/index.js +44 -0
  106. package/dist/tools/index.js.map +1 -0
  107. package/dist/tools/licenses.d.ts +3 -0
  108. package/dist/tools/licenses.js +44 -0
  109. package/dist/tools/licenses.js.map +1 -0
  110. package/dist/tools/media.d.ts +3 -0
  111. package/dist/tools/media.js +18 -0
  112. package/dist/tools/media.js.map +1 -0
  113. package/dist/tools/offerings.d.ts +3 -0
  114. package/dist/tools/offerings.js +21 -0
  115. package/dist/tools/offerings.js.map +1 -0
  116. package/dist/tools/partner.d.ts +3 -0
  117. package/dist/tools/partner.js +55 -0
  118. package/dist/tools/partner.js.map +1 -0
  119. package/dist/tools/plan-entitlements.d.ts +3 -0
  120. package/dist/tools/plan-entitlements.js +56 -0
  121. package/dist/tools/plan-entitlements.js.map +1 -0
  122. package/dist/tools/plan-files.d.ts +3 -0
  123. package/dist/tools/plan-files.js +43 -0
  124. package/dist/tools/plan-files.js.map +1 -0
  125. package/dist/tools/plans.d.ts +3 -0
  126. package/dist/tools/plans.js +120 -0
  127. package/dist/tools/plans.js.map +1 -0
  128. package/dist/tools/portal.d.ts +3 -0
  129. package/dist/tools/portal.js +18 -0
  130. package/dist/tools/portal.js.map +1 -0
  131. package/dist/tools/product-files.d.ts +3 -0
  132. package/dist/tools/product-files.js +31 -0
  133. package/dist/tools/product-files.js.map +1 -0
  134. package/dist/tools/product-settings.d.ts +3 -0
  135. package/dist/tools/product-settings.js +31 -0
  136. package/dist/tools/product-settings.js.map +1 -0
  137. package/dist/tools/products.d.ts +3 -0
  138. package/dist/tools/products.js +69 -0
  139. package/dist/tools/products.js.map +1 -0
  140. package/dist/tools/promotions.d.ts +3 -0
  141. package/dist/tools/promotions.js +19 -0
  142. package/dist/tools/promotions.js.map +1 -0
  143. package/dist/tools/subscriptions.d.ts +3 -0
  144. package/dist/tools/subscriptions.js +63 -0
  145. package/dist/tools/subscriptions.js.map +1 -0
  146. package/dist/tools/usage.d.ts +3 -0
  147. package/dist/tools/usage.js +18 -0
  148. package/dist/tools/usage.js.map +1 -0
  149. package/package.json +88 -0
@@ -0,0 +1,676 @@
1
+ ---
2
+ title: "JavaScript SDK"
3
+ slug: "frontend-integration/js-sdk"
4
+ section: "frontend-integration"
5
+ description: "Documentation for the Kelviq JavaScript SDK"
6
+ ---
7
+ The `@kelviq/js-sdk` is a lightweight, plain TypeScript library designed for interacting with Kelviq entitlement and pricing services. It allows you to:
8
+
9
+ * Fetch all feature entitlements for a specific organization and customer.
10
+ * Cache these entitlements client-side for efficient and repeated access.
11
+ * Check if a user has access to a particular feature.
12
+ * Retrieve specific entitlement details, including boolean flags, numeric configurations, and metered usage data.
13
+ * Fetch product offering and pricing data for display on pricing pages.
14
+ * Format prices with locale-aware currency formatting.
15
+ * Automatically populate pricing into DOM elements via data attributes.
16
+ * Manually refresh entitlement and pricing data from the server.
17
+
18
+ If you are using React, you can use the <a href="/frontend-integration/react-sdk">React SDK</a> instead.
19
+
20
+ ### Installation
21
+
22
+ Install the SDK using your preferred package manager or include it directly via CDN.
23
+
24
+ ```bash
25
+ npm install @kelviq/js-sdk
26
+ # or
27
+ yarn add @kelviq/js-sdk
28
+ # or
29
+ pnpm add @kelviq/js-sdk
30
+ ```
31
+
32
+ **CDN Installation:**
33
+ ```html
34
+ <script src="https://unpkg.com/@kelviq/js-sdk@2.1.0/dist/kelviq-js-sdk.umd.js"></script>
35
+ ```
36
+
37
+ ### Basic Usage
38
+
39
+ Get started with the SDK in just a few lines of code.
40
+
41
+ ```typescript
42
+ import kelviqSDK from '@kelviq/js-sdk';
43
+
44
+ // Initialize the SDK (fetches entitlements automatically)
45
+ const kq = kelviqSDK({
46
+ customerId: "your-customer-id",
47
+ accessToken: "your-access-token",
48
+ });
49
+
50
+ // Wait for the initial fetch to complete
51
+ await kq.ready();
52
+
53
+ // Check if user has access to a feature
54
+ if (kq.hasAccess('premium-features')) {
55
+ console.log("User has access to premium features!");
56
+ }
57
+
58
+ // Get specific entitlement details
59
+ const emailQuota = kq.getEntitlement('email-sends');
60
+ if (emailQuota && emailQuota.hasAccess) {
61
+ console.log(`Emails remaining: ${emailQuota.remaining}`);
62
+ }
63
+ ```
64
+
65
+ ## API Reference
66
+
67
+ Complete documentation of all SDK methods and configuration options.
68
+
69
+ ### Initialization
70
+
71
+ Create and configure your SDK instance with the required parameters.
72
+
73
+ **Security Warning:** Never use your Server API Key in the browser. Use the **Client API Key** which is safe to expose in client-side code. You can find both keys in the [API keys](https://app.kelviq.com/settings/api-keys) section of your Kelviq dashboard.
74
+
75
+ ```typescript
76
+ // Initialize the SDK
77
+ const kq = kelviqSDK({
78
+ customerId: "your-customer-id",
79
+ accessToken: "your-access-token",
80
+ });
81
+ ```
82
+
83
+ You can also initialize the SDK with just a `productId` to fetch pricing data only (without entitlements):
84
+
85
+ ```typescript
86
+ // Initialize for pricing only
87
+ const kq = kelviqSDK({
88
+ productId: "your-product-id",
89
+ accessToken: "your-access-token",
90
+ });
91
+
92
+ await kq.ready();
93
+ const pricing = kq.getPricing();
94
+ ```
95
+
96
+ Or use both `customerId` and `productId` together:
97
+
98
+ ```typescript
99
+ // Initialize for both entitlements and pricing
100
+ const kq = kelviqSDK({
101
+ customerId: "your-customer-id",
102
+ productId: "your-product-id",
103
+ accessToken: "your-access-token",
104
+ });
105
+
106
+ await kq.ready();
107
+ // Both entitlements and pricing are now available
108
+ ```
109
+
110
+ #### Options
111
+
112
+ | Option | Type | Description |
113
+ |--------|------|-------------|
114
+ | `customerId` | `string` | Unique identifier for the customer (required for entitlements) |
115
+ | `productId` | `string` | Product identifier for fetching pricing data (required for pricing) |
116
+ | `accessToken` | `string` | Authentication token for API requests |
117
+ | `environment` | `sandbox\|production` | 'production' | The environment to use. If you want to use the sandbox, you must provide this. |
118
+ | `initializeAndFetch` | `boolean` | `true` | Automatically fetch data on initialization |
119
+ | `onError` | `(error: Error) => void` | Error callback function |
120
+ | `mainApiUrl` | `string` | Optional override for the main API base URL (used by pricing) |
121
+
122
+ At least one of `customerId` or `productId` must be provided.
123
+
124
+ ### Core Methods
125
+
126
+ #### `hasAccess(featureId: string): boolean`
127
+
128
+ Check if the user has access to a specific feature. Returns `false` if the feature doesn't exist or data hasn't been fetched.
129
+
130
+ ```typescript
131
+ if (kq.hasAccess('premium-features')) {
132
+ // Show premium features
133
+ showPremiumUI();
134
+ }
135
+ ```
136
+
137
+ #### `getEntitlement(featureId: string): Entitlement | null`
138
+
139
+ Get the aggregated entitlement for a specific feature. Returns the unified `Entitlement` object which includes the `.items` array of raw API objects.
140
+
141
+ ```typescript
142
+ // Boolean entitlement
143
+ const canUseAnalytics = kq.getEntitlement('analytics');
144
+ if (canUseAnalytics?.hasAccess) {
145
+ enableAnalytics();
146
+ }
147
+
148
+ // Metered entitlement
149
+ const emailQuota = kq.getEntitlement('email-sends');
150
+ if (emailQuota?.hasAccess && emailQuota.remaining !== null && emailQuota.remaining > 0) {
151
+ console.log(`Usage: ${emailQuota.currentUsage} / ${emailQuota.usageLimit}`);
152
+ console.log(`Emails remaining: ${emailQuota.remaining}`);
153
+ }
154
+ ```
155
+
156
+ #### `getEntitlements(): Record<string, Entitlement> | null`
157
+
158
+ Get all aggregated entitlements as a map keyed by `featureId`.
159
+
160
+ ```typescript
161
+ const allEntitlements = kq.getEntitlements();
162
+ if (allEntitlements) {
163
+ Object.entries(allEntitlements).forEach(([featureId, entitlement]) => {
164
+ console.log(`${featureId}: ${entitlement.hasAccess ? 'Access granted' : 'Access denied'}`);
165
+ });
166
+ }
167
+ ```
168
+
169
+ #### `getRawEntitlement(featureId: string): RawEntitlement[] | null`
170
+
171
+ Get the raw, un-aggregated API items for a specific feature. Useful when you need per-item details like `resetAt` or `hardLimit`.
172
+
173
+ ```typescript
174
+ const rawItems = kq.getRawEntitlement('email-sends');
175
+ if (rawItems) {
176
+ rawItems.forEach(item => {
177
+ console.log(`Reset at: ${item.resetAt}, Limit: ${item.usageLimit}`);
178
+ });
179
+ }
180
+ ```
181
+
182
+ #### `getRawEntitlements(): RawEntitlementsApiResponse | null`
183
+
184
+ Get the full raw API response including the `customerId` wrapper, exactly as received from the server.
185
+
186
+ ```typescript
187
+ const raw = kq.getRawEntitlements();
188
+ if (raw) {
189
+ console.log(`Customer: ${raw.customerId}`);
190
+ console.log(`Total items: ${raw.entitlements.length}`);
191
+ }
192
+ ```
193
+
194
+ #### `ready(): Promise<void>`
195
+
196
+ Wait for the initial fetch (triggered by `initializeAndFetch: true`) to complete. Resolves immediately if no initial fetch was triggered or if the data is already available.
197
+
198
+ ```typescript
199
+ const kq = kelviqSDK({
200
+ customerId: "your-customer-id",
201
+ accessToken: "your-access-token",
202
+ });
203
+
204
+ await kq.ready();
205
+ // Entitlements are now available
206
+ if (kq.hasAccess('premium-features')) {
207
+ showPremiumUI();
208
+ }
209
+ ```
210
+
211
+ #### `fetchAllEntitlements(forceRefresh?: boolean): Promise<Record<string, Entitlement>>`
212
+
213
+ Manually trigger a network request to refresh the entitlements. If a fetch is already in progress, the same promise is returned (calls are deduplicated).
214
+
215
+ ```typescript
216
+ // Fetch fresh data
217
+ try {
218
+ const entitlements = await kq.fetchAllEntitlements(true);
219
+ console.log('Entitlements refreshed:', entitlements);
220
+ } catch (error) {
221
+ console.error('Failed to refresh entitlements:', error);
222
+ }
223
+ ```
224
+
225
+ #### `isLoading(): boolean`
226
+
227
+ Check if entitlements are currently being fetched.
228
+
229
+ ```typescript
230
+ if (kq.isLoading()) {
231
+ showLoadingSpinner();
232
+ } else {
233
+ hideLoadingSpinner();
234
+ }
235
+ ```
236
+
237
+ #### `getLastError(): Error | null`
238
+
239
+ Get the last error that occurred during entitlement fetching.
240
+
241
+ ```typescript
242
+ const lastError = kq.getLastError();
243
+ if (lastError) {
244
+ console.error('Last SDK error:', lastError.message);
245
+ }
246
+ ```
247
+
248
+ #### `clearCache(): void`
249
+
250
+ Clear the cached entitlements.
251
+
252
+ ```typescript
253
+ kq.clearCache();
254
+ // Next call to hasAccess or getEntitlement will need a new fetch
255
+ ```
256
+
257
+ ### Pricing Methods
258
+
259
+ #### `fetchPricing(forceRefresh?: boolean): Promise<RawPricingApiResponse>`
260
+
261
+ Fetch product offering and pricing data. Requires `productId` to be set. Results are cached; use `forceRefresh` to bypass the cache.
262
+
263
+ ```typescript
264
+ const pricing = await kq.fetchPricing();
265
+ console.log(`Plans: ${pricing.plans.length}`);
266
+ console.log(`Currency: ${pricing.currencySymbol}`);
267
+ ```
268
+
269
+ #### `getPricing(): RawPricingApiResponse | null`
270
+
271
+ Get cached pricing data. Returns `null` if not yet fetched.
272
+
273
+ ```typescript
274
+ const pricing = kq.getPricing();
275
+ if (pricing) {
276
+ pricing.plans.forEach(plan => {
277
+ console.log(`${plan.displayName}: ${plan.price.priceType}`);
278
+ });
279
+ }
280
+ ```
281
+
282
+ #### `getPlan(identifier: string): RawPricingPlan | null`
283
+
284
+ Find an enabled plan by its identifier from cached pricing data.
285
+
286
+ ```typescript
287
+ const starterPlan = kq.getPlan('starter');
288
+ if (starterPlan) {
289
+ const monthlyCharge = starterPlan.price.charges.find(c => c.chargePeriod === 'MONTHLY');
290
+ console.log(`Monthly price: ${monthlyCharge?.priceData.amount}`);
291
+ }
292
+ ```
293
+
294
+ #### `isPricingLoading(): boolean`
295
+
296
+ Check if pricing data is currently being fetched.
297
+
298
+ #### `getLastPricingError(): Error | null`
299
+
300
+ Get the last error from a pricing fetch.
301
+
302
+ #### `clearPricingCache(): void`
303
+
304
+ Clear cached pricing data and reset pricing state.
305
+
306
+ ```typescript
307
+ kq.clearPricingCache();
308
+ // Next call to getPricing will need a new fetch
309
+ ```
310
+
311
+ ### `renderPricing()` — DOM Binding
312
+
313
+ Automatically populate pricing into HTML elements using `data-kq-price` attributes. The SDK scans the DOM for elements with these attributes and fills in formatted prices.
314
+
315
+ ```html
316
+ <span data-kq-price="starter" data-kq-period="MONTHLY">Loading...</span>
317
+ <span data-kq-price="starter" data-kq-period="ANNUALLY">Loading...</span>
318
+ <span data-kq-price="free" data-kq-period="MONTHLY">Loading...</span>
319
+ ```
320
+
321
+ ```typescript
322
+ const kq = kelviqSDK({
323
+ productId: "your-product-id",
324
+ accessToken: "your-access-token",
325
+ });
326
+
327
+ await kq.ready();
328
+ kq.renderPricing(); // Scans DOM and populates data-kq-price elements
329
+ ```
330
+
331
+ - `data-kq-price` — the plan identifier (e.g., `"starter"`, `"pro"`)
332
+ - `data-kq-period` — the charge period (e.g., `"MONTHLY"`, `"ANNUALLY"`)
333
+ - Free plans display `"Free"` instead of a price
334
+ - Disabled or missing plans result in empty text
335
+
336
+ You can scope the scan to a container and pass formatting options:
337
+
338
+ ```typescript
339
+ kq.renderPricing({
340
+ container: document.getElementById('pricing-section'),
341
+ formatOptions: { compact: true },
342
+ });
343
+ ```
344
+
345
+ ### `kqFormatPrice` Utility
346
+
347
+ A standalone utility for formatting prices with locale-aware currency formatting.
348
+
349
+ ```typescript
350
+ import { kqFormatPrice } from '@kelviq/js-sdk';
351
+
352
+ kqFormatPrice(49.99, '$'); // "$49.99"
353
+ kqFormatPrice(1299, '$', { compact: true }); // "$1.3K"
354
+ kqFormatPrice(100, '€', { locale: 'de-DE' }); // "€100"
355
+ kqFormatPrice(29, '$', { includeCurrencySymbol: false }); // "29"
356
+ ```
357
+
358
+ | Option | Type | Default | Description |
359
+ |--------|------|---------|-------------|
360
+ | `compact` | `boolean` | `false` | Use compact notation (e.g., "1.2K") |
361
+ | `locale` | `string` | `'en-US'` | Locale for number formatting |
362
+ | `includeCurrencySymbol` | `boolean` | `true` | Include the currency symbol |
363
+ | `pricingLocale` | `string` | — | Fallback locale (from pricing API response) |
364
+
365
+ ## Entitlement Types
366
+
367
+ The SDK uses a single, unified `Entitlement` interface. When the API returns duplicate `featureId`s (e.g., from Subscriptions + Top-ups), they are aggregated automatically.
368
+
369
+ ```typescript
370
+ interface Entitlement {
371
+ featureId: string;
372
+ featureType: "METER" | "BOOLEAN" | "CUSTOMIZABLE";
373
+ hasAccess: boolean; // METER: remaining === null || remaining > 0; others: true if any item grants access
374
+ hardLimit: boolean; // true if any item has a hard limit
375
+ currentUsage: number; // METER: summed across items; CUSTOMIZABLE: from first item; BOOLEAN: 0
376
+ usageLimit: number | null; // METER: summed across items; CUSTOMIZABLE: from first item; BOOLEAN: null
377
+ remaining: number | null; // METER: usageLimit - currentUsage; CUSTOMIZABLE: from first item; BOOLEAN: null
378
+ items: RawEntitlement[]; // The raw array of original API objects for this featureId
379
+ }
380
+ ```
381
+
382
+ Per-item details such as `resetAt` and `hardLimit` are available on each item in the `items` array.
383
+
384
+ ## Pricing Types
385
+
386
+ The pricing API returns a rich data structure with plans, charges, features, and billing periods.
387
+
388
+ ```typescript
389
+ interface RawPricingApiResponse {
390
+ organizationId: number;
391
+ countryCode: string;
392
+ pricingLocale: string;
393
+ currencyCode: string;
394
+ currencySymbol: string;
395
+ currencyConversionRate: number;
396
+ baseCurrencyCode: string;
397
+ baseCurrencySymbol: string;
398
+ plans: RawPricingPlan[];
399
+ subscription: { hasPreviousSubscription: boolean };
400
+ isCustomerExists: boolean;
401
+ billingPeriods: RawPricingBillingPeriod[];
402
+ }
403
+
404
+ interface RawPricingPlan {
405
+ name: string;
406
+ identifier: string;
407
+ displayName: string;
408
+ displayDescription: string;
409
+ price: RawPricingPrice;
410
+ features: RawPricingFeature[];
411
+ enabled: boolean;
412
+ shouldHighlight: boolean;
413
+ // ... additional fields
414
+ }
415
+
416
+ interface RawPricingPrice {
417
+ priceType: 'FREE' | 'PAID';
418
+ charges: RawPricingCharge[];
419
+ freeTrial: boolean;
420
+ trialPeriod: number;
421
+ currency: string;
422
+ }
423
+
424
+ interface RawPricingCharge {
425
+ chargePeriod: string; // e.g., "MONTHLY", "ANNUALLY"
426
+ priceData: { amount: number };
427
+ }
428
+ ```
429
+
430
+ All pricing types are exported from the SDK: `RawPricingApiResponse`, `RawPricingPlan`, `RawPricingPrice`, `RawPricingCharge`, `RawPricingFeature`, `RawPricingBillingPeriod`.
431
+
432
+ ## Examples
433
+
434
+ Real-world usage patterns and common implementation scenarios.
435
+
436
+ ### Feature Gating
437
+
438
+ Control access to features based on user entitlements.
439
+
440
+ ```typescript
441
+ // Simple feature gate
442
+ if (kq.hasAccess('beta-features')) {
443
+ showBetaFeatures();
444
+ }
445
+
446
+ // Conditional rendering
447
+ const canUseAdvancedSearch = kq.hasAccess('advanced-search');
448
+ return (
449
+ <div>
450
+
451
+ {canUseAdvancedSearch && }
452
+ </div>
453
+ );
454
+ ```
455
+
456
+ ### Usage-Based Features
457
+
458
+ Implement usage limits and quota management.
459
+
460
+ ```typescript
461
+ const apiCalls = kq.getEntitlement('api-calls');
462
+ if (apiCalls?.hasAccess) {
463
+ if (apiCalls.remaining === null || apiCalls.remaining > 0) {
464
+ // Allow API call
465
+ makeApiCall();
466
+ console.log(`Usage: ${apiCalls.currentUsage} / ${apiCalls.usageLimit}`);
467
+ } else {
468
+ // Show upgrade message
469
+ showUpgradeMessage();
470
+ }
471
+ }
472
+ ```
473
+
474
+ ### Configuration-Based Features
475
+
476
+ Apply dynamic configuration based on user entitlements.
477
+
478
+ ```typescript
479
+ const teamSizeEntitlement = kq.getEntitlement('max-team-size');
480
+
481
+ if (teamSizeEntitlement?.hasAccess) {
482
+ if (currentTeam.length >= (teamSizeEntitlement.usageLimit ?? Infinity)) {
483
+ showUpgradePrompt(); // or disable the "Add Member" button
484
+ } else {
485
+ enableTeamInvite();
486
+ }
487
+ }
488
+ ```
489
+
490
+ ### Accessing Per-Item Details
491
+
492
+ When you need item-level details like `resetAt` or `hardLimit`, use the `items` array or the `getRawEntitlement` method.
493
+
494
+ ```typescript
495
+ // Via the aggregated entitlement's items array
496
+ const emailQuota = kq.getEntitlement('email-sends');
497
+ if (emailQuota) {
498
+ emailQuota.items.forEach(item => {
499
+ console.log(`Reset at: ${item.resetAt}, Hard limit: ${item.hardLimit}`);
500
+ });
501
+ }
502
+
503
+ // Or via getRawEntitlement
504
+ const rawItems = kq.getRawEntitlement('email-sends');
505
+ if (rawItems) {
506
+ rawItems.forEach(item => {
507
+ console.log(`Reset at: ${item.resetAt}, Hard limit: ${item.hardLimit}`);
508
+ });
509
+ }
510
+ ```
511
+
512
+ ### Error Handling
513
+
514
+ Robust error handling for production applications.
515
+
516
+ ```typescript
517
+ const kq = kelviqSDK({
518
+ customerId: "user123",
519
+ accessToken: "token456",
520
+ onError: (error) => {
521
+ // Log to monitoring service
522
+ logError('kelviq SDK Error', error);
523
+
524
+ // Show user-friendly message
525
+ showNotification('Unable to load feature settings', 'error');
526
+ }
527
+ });
528
+
529
+ // Handle fetch errors
530
+ try {
531
+ await kq.fetchAllEntitlements();
532
+ } catch (error) {
533
+ console.error('Failed to load entitlements:', error);
534
+ // Fallback to default behavior
535
+ showDefaultFeatures();
536
+ }
537
+ ```
538
+
539
+ ### Custom API Request Service
540
+
541
+ Integrate with your existing HTTP client or add custom logic.
542
+
543
+ ```typescript
544
+ // Custom API request function
545
+ async function customApiRequest<T>(config: ApiRequestConfig): Promise<ApiResponse<T>> {
546
+ const response = await fetch(config.url, {
547
+ method: config.method || 'GET',
548
+ headers: {
549
+ 'Authorization': `Bearer ${config.accessToken}`,
550
+ 'Content-Type': 'application/json',
551
+ ...config.headers
552
+ },
553
+ body: config.body ? JSON.stringify(config.body) : undefined
554
+ });
555
+
556
+ if (!response.ok) {
557
+ throw new Error(`HTTP ${response.status}: ${response.statusText}`);
558
+ }
559
+
560
+ return {
561
+ status: response.status,
562
+ statusText: response.statusText,
563
+ data: await response.json()
564
+ };
565
+ }
566
+
567
+ // Use custom API request
568
+ const kq = kelviqSDK({
569
+ customerId: "user123",
570
+ accessToken: "token456"
571
+ }, customApiRequest);
572
+ ```
573
+
574
+ ## TypeScript Support
575
+
576
+ Full TypeScript support with comprehensive type definitions.
577
+
578
+ The SDK is written in TypeScript and provides full type safety:
579
+
580
+ ```typescript
581
+ import kelviqSDK, {
582
+ KelviqClientOptions,
583
+ Entitlement,
584
+ RawEntitlement,
585
+ RawEntitlementsApiResponse
586
+ } from '@kelviq/js-sdk';
587
+
588
+ const options: KelviqClientOptions = {
589
+ customerId: "user123",
590
+ accessToken: "token456"
591
+ };
592
+
593
+ const kq = kelviqSDK(options);
594
+
595
+ // Type-safe entitlement access
596
+ const emailQuota: Entitlement | null = kq.getEntitlement('emails');
597
+ ```
598
+
599
+ ## Advanced Configuration
600
+
601
+ Advanced options for customizing SDK behavior and API integration.
602
+
603
+ ### API Configuration
604
+
605
+ Configure API request behavior and retry logic.
606
+
607
+ ```typescript
608
+ const kq = kelviqSDK({
609
+ customerId: "user123",
610
+ accessToken: "token456",
611
+ apiConfig: {
612
+ maxRetries: 5,
613
+ timeout: 10000,
614
+ backoffBaseDelay: 2000
615
+ }
616
+ });
617
+ ```
618
+
619
+ ### Custom Error Handling
620
+
621
+ Implement sophisticated error handling and recovery strategies.
622
+
623
+ ```typescript
624
+ const kq = kelviqSDK({
625
+ customerId: "user123",
626
+ accessToken: "token456",
627
+ onError: (error) => {
628
+ // Send to error tracking service
629
+ Sentry.captureException(error);
630
+
631
+ // Retry logic
632
+ if (error.message.includes('network')) {
633
+ setTimeout(() => kq.fetchAllEntitlements(), 5000);
634
+ }
635
+ }
636
+ });
637
+ ```
638
+
639
+ ### Advanced Options
640
+
641
+ Additional configuration options for specialized use cases.
642
+
643
+ Default values are:
644
+ ```typescript
645
+ const kq = kelviqSDK({
646
+ customerId: "",
647
+ accessToken: "",
648
+ apiUrl: "https://edge.api.kelviq.com/api/v1",
649
+ entitlementsPath: "entitlements/",
650
+ apiConfig: {
651
+ maxRetries: 3,
652
+ timeout: 5000,
653
+ backoffBaseDelay: 1000
654
+ }
655
+ });
656
+ ```
657
+
658
+ | Option | Type | Description |
659
+ |--------|------|---------|
660
+ | `apiUrl` | `string` | Base URL for the API |
661
+ | `entitlementsPath` | `string` | Path for fetching entitlements |
662
+ | `apiConfig.maxRetries` | `number` | Maximum number of retries for API requests |
663
+ | `apiConfig.timeout` | `number` | Timeout for API requests in milliseconds |
664
+ | `apiConfig.backoffBaseDelay` | `number` | Base delay for exponential backoff strategy |
665
+
666
+ ## Using the Sandbox
667
+
668
+ If you want to use the sandbox, you need to set the `environment` option to `sandbox` in the `init` function.
669
+
670
+ ```typescript
671
+ const kq = kelviqSDK({
672
+ customerId: "your-customer-id",
673
+ accessToken: "your-access-token",
674
+ environment: "sandbox"
675
+ });
676
+ ```