@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,1187 @@
1
+ ---
2
+ title: "React SDK"
3
+ slug: "frontend-integration/react-sdk"
4
+ section: "frontend-integration"
5
+ description: "Documentation for the Kelviq React SDK"
6
+ ---
7
+ The `@kelviq/react-sdk` provides a seamless way to integrate kelviq entitlement management into your React applications.
8
+
9
+ ## Overview
10
+
11
+ - A **React Context Provider** (`KelviqProvider`) to initialize and configure the SDK.
12
+ - **Hooks** to easily access entitlement status, pricing, and data within your components.
13
+ - **Conditional rendering components** to show or hide UI elements based on feature access.
14
+ - **Pricing components** (`KQPrice`, `KQFeatureList`) for displaying localized plan pricing and features.
15
+ - Automatic and manual **data fetching** and caching mechanisms.
16
+
17
+ The SDK fetches all entitlements for a given organization and customer, caches them, and makes them available throughout your application via React Context and custom hooks.
18
+
19
+ ## **2. Installation**
20
+
21
+ Install the SDK using npm or yarn:
22
+
23
+ ``` bash
24
+ npm install @kelviq/react-sdk
25
+ # or
26
+ yarn add @kelviq/react-sdk
27
+
28
+ ```
29
+
30
+ You will also need `react` as a peer dependency.
31
+
32
+ ## **3. Setup & Configuration**
33
+
34
+ ### `KelviqProvider`
35
+
36
+ The core of the SDK is the `KelviqProvider`. You need to wrap your application (or the relevant part of it) with this provider. It initializes the SDK and makes entitlement data available to its children components via context.
37
+
38
+ ``` tsx
39
+ // In your App.tsx or main application entry point
40
+ import React from 'react';
41
+ import { KelviqProvider } from '@kelviq/react-sdk';
42
+
43
+ const App = () => {
44
+ return (
45
+ <KelviqProvider
46
+ customerId="your-customer-id"
47
+ accessToken="your-access-token"
48
+ productId="your-product-id"
49
+ plansEnabled="pro,enterprise" // optional: filter to specific plans
50
+ config={{
51
+ fetchPricingOnMount: true, // fetch pricing data on mount
52
+ }}
53
+ >
54
+
55
+ </KelviqProvider>
56
+ );
57
+ };
58
+
59
+ const MyAppContent = () => {
60
+
61
+ return (
62
+ <div>
63
+ <h1>My Application</h1>
64
+ </div>
65
+ );
66
+
67
+ };
68
+
69
+ export default App;
70
+
71
+ ```
72
+
73
+ ### Required Props for `KelviqProvider`
74
+
75
+ - `accessToken: string | null`
76
+ - Your **Client API Key** for authenticating requests to the Kelviq API. This key is safe to expose in client-side code. You can find it in the [API keys](https://app.kelviq.com/settings/api-keys) section of your Kelviq dashboard. Never use your Server API Key in client-side code.
77
+
78
+ ### Optional Props for `KelviqProvider`
79
+
80
+ - `customerId?: string`
81
+ - The ID of the customer for whom entitlements are being fetched. This will be sent as a query parameter (`customer_id`). Required for entitlements, subscriptions, and customer data. Optional when only using pricing.
82
+ - `productId?: string`
83
+ - The product identifier for fetching pricing/offering data. Required when `fetchPricingOnMount` is `true`.
84
+ - `plansEnabled?: string`
85
+ - Comma-separated list of plan identifiers to include in the pricing response. When omitted, all active plans for the product are returned. Example: `"pro,enterprise"`.
86
+ - `apiUrl: string`
87
+ - The base URL for your kelviq API. For example, `https://edge.api.kelviq.com/api/v1`.
88
+ - `environment: 'sandbox' | 'production'`
89
+ - The environment to use. If you want to use the sandbox, you must provide this.
90
+ - `entitlementsPath: string`
91
+ - The specific path for the endpoint that returns all entitlements for a customer. This path will be appended to `apiUrl`. For example, `entitlement-check` or `user-entitlements`.
92
+ - `config?: KelviqApiBehaviorOptions`
93
+ - An optional object to configure more advanced behaviors of the SDK.
94
+
95
+ ### **Configuration Object (**`config: KelviqApiBehaviorOptions`**)**
96
+
97
+ This optional object can contain the following properties:
98
+
99
+ - `onError?: (error: Error) => void`
100
+ - A callback function that will be invoked if an error occurs during the API request for entitlements.
101
+ - `maxRetries?: number`
102
+ - The maximum number of times to retry a failed API request. Defaults to the value set in your `apiRequest` service (typically 3).
103
+ - `timeout?: number`
104
+ - Timeout for API requests in milliseconds. Defaults to the value set in your `apiRequest` service (typically 5000ms).
105
+ - `backoffBaseDelay?: number`
106
+ - Base delay (in milliseconds) for the exponential backoff strategy used in retries. Defaults to the value set in your `apiRequest` service (typically 1000ms).
107
+ - `fetchEntitlementsOnMount?: boolean`
108
+ - Defaults to `true`. If true, entitlements are fetched automatically when the `KelviqProvider` mounts.
109
+ - Set to `false` if you want to control the initial fetch manually using the `refreshAllEntitlements` function from the `useKelviq` hook.
110
+ - `fetchSubscriptionsOnMount?: boolean`
111
+ - Defaults to `false`. If true, the customer's subscription data is fetched automatically when the `KelviqProvider` mounts.
112
+ - When enabled, data is available via the `useSubscriptions()` hook or `subscriptions` from `useKelviq()`.
113
+ - `fetchCustomerOnMount?: boolean`
114
+ - Defaults to `false`. If true, customer data is fetched automatically when the `KelviqProvider` mounts.
115
+ - When enabled, data is available via the `useCustomer()` hook or `customer` from `useKelviq()`.
116
+ - `fetchPricingOnMount?: boolean`
117
+ - Defaults to `false`. If true, pricing/offering data is fetched automatically when the `KelviqProvider` mounts. Requires `productId` to be set on the provider.
118
+ - When enabled, data is available via the `usePricing()` hook or `pricing` from `useKelviq()`.
119
+
120
+ ## **4. Fetching Entitlements**
121
+
122
+ ### **Automatic Fetching on Mount**
123
+
124
+ By default (`fetchEntitlementsOnMount: true` in the `config` prop, or if `config` or this specific option is omitted), the SDK will attempt to fetch all entitlements for the specified `customerId` as soon as the `KelviqProvider` is mounted.
125
+
126
+ The `isLoading` state from `useKelviq()` will be `true` during this initial fetch.
127
+
128
+ ### **Manual Fetching**
129
+
130
+ If `fetchEntitlementsOnMount` is set to `false`, or if you need to re-fetch entitlements at any point (e.g., after a user action that might change their entitlements), you can use the `refreshAllEntitlements` function.
131
+
132
+ ``` tsx
133
+ import { useKelviq } from '@kelviq/react-sdk';
134
+
135
+ function MyComponent() {
136
+ const { refreshAllEntitlements, isLoading, error } = useKelviq();
137
+
138
+ const handleRefresh = async () => {
139
+ try {
140
+ await refreshAllEntitlements();
141
+ console.log("Entitlements refreshed!");
142
+ } catch (e) {
143
+ console.error("Failed to refresh entitlements:", e);
144
+ }
145
+ };
146
+
147
+ return (
148
+ <div>
149
+ <button onClick={handleRefresh} disabled={isLoading}>
150
+ {isLoading ? 'Refreshing...' : 'Refresh Entitlements'}
151
+ </button>
152
+ {error && <p style={{ color: 'red' }}>Error: {error.message}</p>}
153
+
154
+ </div>
155
+ );
156
+ }
157
+
158
+ ```
159
+
160
+ ## **5. Accessing Entitlement Data (Hooks)**
161
+
162
+ The SDK provides several hooks to access entitlement data and SDK state.
163
+
164
+ ### `useKelviq()`
165
+
166
+ This is the primary hook to access the SDK's context.
167
+
168
+ - **Returns:** `KelviqContextValue` object containing:
169
+ - `allEntitlements: AsyncState<EntitlementMap | null>`: The state object for all fetched entitlements.
170
+ - `data`: An `EntitlementMap` (a `Record<string, Entitlement>`) where keys are `featureId`s, or `null` if not loaded or error.
171
+ - `isLoading`: Boolean indicating if the `allEntitlements` data is currently being fetched/refreshed.
172
+ - `error`: An `Error` object if the last fetch failed, otherwise `null`.
173
+ - `refreshAllEntitlements: () => Promise<void>`: Function to manually trigger a re-fetch of all entitlements.
174
+ - `getEntitlements: () => EntitlementMap`: Returns all aggregated entitlements as a `Record<string, Entitlement>` keyed by `featureId`. Returns an empty object if data has not been fetched yet.
175
+ - `getEntitlement: (featureId: string) => Entitlement | null`: Returns the aggregated entitlement for a given `featureId`, or `null` if not found or not yet loaded.
176
+ - `getRawEntitlements: () => EntitlementsResponse | null`: Returns the raw API response with `customerId` and the un-aggregated `entitlements` array (duplicate `featureId` entries are preserved). Returns `null` if data has not been fetched yet.
177
+ - `getRawEntitlement: (featureId: string) => EntitlementsResponse | null`: Returns the raw API response filtered to a specific `featureId`, with `customerId` and only the matching entries.
178
+ - `hasAccess: (featureId: string) => boolean`: A utility function to quickly check access for a feature. Returns `true` if access is granted, `false` if denied, feature not found, or data is not yet loaded.
179
+ - `updateEntitlement: (featureId: string, data: Partial<...>) => void`: Updates a cached entitlement in-place. Accepts partial data (excluding `featureId`, `featureType`, and `items`). Automatically recalculates `remaining` when `usageLimit` or `currentUsage` are updated.
180
+ - `subscriptions: AsyncState<RawSubscriptionData[] | null>`: The state object for the customer's subscriptions. Only populated when `fetchSubscriptionsOnMount` is `true` or after calling `refreshSubscriptions()`.
181
+ - `refreshSubscriptions: () => Promise<void>`: Function to manually trigger a re-fetch of the customer's subscriptions.
182
+ - `customer: AsyncState<RawCustomerApiResponse | null>`: The state object for customer data. Only populated when `fetchCustomerOnMount` is `true` or after calling `refreshCustomer()`.
183
+ - `refreshCustomer: () => Promise<void>`: Function to manually trigger a re-fetch of the customer data.
184
+ - `pricing: AsyncState<RawPricingApiResponse | null>`: The state object for pricing/offering data with localized currency. Only populated when `fetchPricingOnMount` is `true` or after calling `refreshPricing()`.
185
+ - `refreshPricing: () => Promise<void>`: Function to manually trigger a re-fetch of the pricing data.
186
+ - `isLoading: boolean`: A global loading state indicating if the SDK is performing its initial configured fetch or a refresh operation.
187
+ - `error: Error | null`: A global error state reflecting any error from the last fetch operation initiated by the provider.
188
+ - `customerId: string`: The customer ID passed to the provider.
189
+ - `environment: string`: The environment (`'production'` or `'sandbox'`) passed to the provider.
190
+ - `apiUrl: string`: The resolved API URL used by the provider.
191
+ - `entitlementsPath: string`: The entitlements path passed to the provider.
192
+
193
+ ---
194
+
195
+ #### `hasAccess(featureId)`
196
+
197
+ Quickly check if a customer has access to a feature.
198
+
199
+ ```tsx
200
+ const { hasAccess } = useKelviq();
201
+ const canUse = hasAccess("premium-reporting");
202
+ ```
203
+
204
+ ```json
205
+ true
206
+ ```
207
+
208
+ ---
209
+
210
+ #### `getEntitlement(featureId)`
211
+
212
+ Returns the aggregated entitlement for a given feature. When the API returns multiple entries for the same `featureId` (e.g. from different subscriptions), the SDK groups them and exposes aggregated totals at the top level.
213
+
214
+ ```tsx
215
+ const { getEntitlement } = useKelviq();
216
+ const entitlement = getEntitlement("api-calls-quota");
217
+ ```
218
+
219
+ ```json
220
+ {
221
+ "featureId": "api-calls-quota",
222
+ "featureType": "METER",
223
+ "hasAccess": true,
224
+ "currentUsage": 150,
225
+ "usageLimit": 1000,
226
+ "remaining": 850,
227
+ "hardLimit": true,
228
+ "items": [
229
+ {
230
+ "featureId": "api-calls-quota",
231
+ "featureType": "METER",
232
+ "hasAccess": true,
233
+ "resetAt": "2025-06-01T00:00:00Z",
234
+ "hardLimit": false,
235
+ "usageLimit": 500,
236
+ "currentUsage": 100,
237
+ "remaining": 400
238
+ },
239
+ {
240
+ "featureId": "api-calls-quota",
241
+ "featureType": "METER",
242
+ "hasAccess": true,
243
+ "resetAt": "2025-07-01T00:00:00Z",
244
+ "hardLimit": true,
245
+ "usageLimit": 500,
246
+ "currentUsage": 50,
247
+ "remaining": 450
248
+ }
249
+ ]
250
+ }
251
+ ```
252
+
253
+ ```json
254
+ {
255
+ "featureId": "enable-dark-mode",
256
+ "featureType": "BOOLEAN",
257
+ "hasAccess": true,
258
+ "currentUsage": 0,
259
+ "usageLimit": null,
260
+ "remaining": null,
261
+ "hardLimit": false,
262
+ "items": [
263
+ {
264
+ "featureId": "enable-dark-mode",
265
+ "featureType": "BOOLEAN",
266
+ "hasAccess": true
267
+ }
268
+ ]
269
+ }
270
+ ```
271
+
272
+ ```json
273
+ {
274
+ "featureId": "max-items-per-page",
275
+ "featureType": "CUSTOMIZABLE",
276
+ "hasAccess": true,
277
+ "currentUsage": 0,
278
+ "usageLimit": 50,
279
+ "remaining": 50,
280
+ "hardLimit": false,
281
+ "items": [
282
+ {
283
+ "featureId": "max-items-per-page",
284
+ "featureType": "CUSTOMIZABLE",
285
+ "hasAccess": true,
286
+ "usageLimit": 50,
287
+ "currentUsage": 0,
288
+ "remaining": 50
289
+ }
290
+ ]
291
+ }
292
+ ```
293
+
294
+ ---
295
+
296
+ #### `getEntitlements()`
297
+
298
+ Returns all aggregated entitlements as a `Record<string, Entitlement>` keyed by `featureId`.
299
+
300
+ ```tsx
301
+ const { getEntitlements } = useKelviq();
302
+ const entitlements = getEntitlements();
303
+ ```
304
+
305
+ ```json
306
+ {
307
+ "api-calls-quota": {
308
+ "featureId": "api-calls-quota",
309
+ "featureType": "METER",
310
+ "hasAccess": true,
311
+ "currentUsage": 150,
312
+ "usageLimit": 1000,
313
+ "remaining": 850,
314
+ "hardLimit": true,
315
+ "items": [
316
+ {
317
+ "featureId": "api-calls-quota",
318
+ "featureType": "METER",
319
+ "hasAccess": true,
320
+ "resetAt": "2025-06-01T00:00:00Z",
321
+ "hardLimit": false,
322
+ "usageLimit": 500,
323
+ "currentUsage": 100,
324
+ "remaining": 400
325
+ },
326
+ {
327
+ "featureId": "api-calls-quota",
328
+ "featureType": "METER",
329
+ "hasAccess": true,
330
+ "resetAt": "2025-07-01T00:00:00Z",
331
+ "hardLimit": true,
332
+ "usageLimit": 500,
333
+ "currentUsage": 50,
334
+ "remaining": 450
335
+ }
336
+ ]
337
+ },
338
+ "enable-dark-mode": {
339
+ "featureId": "enable-dark-mode",
340
+ "featureType": "BOOLEAN",
341
+ "hasAccess": true,
342
+ "currentUsage": 0,
343
+ "usageLimit": null,
344
+ "remaining": null,
345
+ "hardLimit": false,
346
+ "items": [
347
+ {
348
+ "featureId": "enable-dark-mode",
349
+ "featureType": "BOOLEAN",
350
+ "hasAccess": true
351
+ }
352
+ ]
353
+ }
354
+ }
355
+ ```
356
+
357
+ ---
358
+
359
+ #### `getRawEntitlements()`
360
+
361
+ Returns the raw, un-aggregated API response with `customerId`. Duplicate `featureId` entries from multiple subscriptions are preserved as-is.
362
+
363
+ ```tsx
364
+ const { getRawEntitlements } = useKelviq();
365
+ const raw = getRawEntitlements();
366
+ ```
367
+
368
+ ```json
369
+ {
370
+ "customerId": "cust_456",
371
+ "entitlements": [
372
+ {
373
+ "featureId": "api-calls-quota",
374
+ "featureType": "METER",
375
+ "hasAccess": true,
376
+ "resetAt": "2025-06-01T00:00:00Z",
377
+ "hardLimit": false,
378
+ "usageLimit": 500,
379
+ "currentUsage": 100,
380
+ "remaining": 400
381
+ },
382
+ {
383
+ "featureId": "api-calls-quota",
384
+ "featureType": "METER",
385
+ "hasAccess": true,
386
+ "resetAt": "2025-07-01T00:00:00Z",
387
+ "hardLimit": true,
388
+ "usageLimit": 500,
389
+ "currentUsage": 50,
390
+ "remaining": 450
391
+ },
392
+ {
393
+ "featureId": "enable-dark-mode",
394
+ "featureType": "BOOLEAN",
395
+ "hasAccess": true
396
+ }
397
+ ]
398
+ }
399
+ ```
400
+
401
+ ---
402
+
403
+ #### `getRawEntitlement(featureId)`
404
+
405
+ Returns the raw API response filtered to a specific `featureId`. Useful for accessing per-subscription data for a single feature.
406
+
407
+ ```tsx
408
+ const { getRawEntitlement } = useKelviq();
409
+ const raw = getRawEntitlement("api-calls-quota");
410
+ ```
411
+
412
+ ```json
413
+ {
414
+ "customerId": "cust_456",
415
+ "entitlements": [
416
+ {
417
+ "featureId": "api-calls-quota",
418
+ "featureType": "METER",
419
+ "hasAccess": true,
420
+ "resetAt": "2025-06-01T00:00:00Z",
421
+ "hardLimit": false,
422
+ "usageLimit": 500,
423
+ "currentUsage": 100,
424
+ "remaining": 400
425
+ },
426
+ {
427
+ "featureId": "api-calls-quota",
428
+ "featureType": "METER",
429
+ "hasAccess": true,
430
+ "resetAt": "2025-07-01T00:00:00Z",
431
+ "hardLimit": true,
432
+ "usageLimit": 500,
433
+ "currentUsage": 50,
434
+ "remaining": 450
435
+ }
436
+ ]
437
+ }
438
+ ```
439
+
440
+ ---
441
+
442
+ #### `updateEntitlement(featureId, data)`
443
+
444
+ Updates a cached entitlement in-place. Useful for optimistically updating the UI after a usage increment without waiting for a full refresh. The `remaining` field is automatically recalculated when `usageLimit` or `currentUsage` are updated.
445
+
446
+ ```tsx
447
+ const { updateEntitlement } = useKelviq();
448
+
449
+ // After the user performs an action that consumes usage
450
+ updateEntitlement("api-calls-quota", { currentUsage: 151 });
451
+ ```
452
+
453
+ ```json
454
+ {
455
+ "featureId": "api-calls-quota",
456
+ "featureType": "METER",
457
+ "hasAccess": true,
458
+ "currentUsage": 151,
459
+ "usageLimit": 1000,
460
+ "remaining": 849,
461
+ "hardLimit": true,
462
+ "items": [...]
463
+ }
464
+ ```
465
+
466
+ Accepts `Partial<Omit<Entitlement, 'featureId' | 'featureType' | 'items'>>`. You can update any combination of `hasAccess`, `currentUsage`, `usageLimit`, and `remaining`.
467
+
468
+ ### `useAllEntitlements()`
469
+
470
+ A convenience hook that directly returns the `allEntitlements` state object.
471
+
472
+ - **Returns:** `AsyncState<EntitlementMap | null>`
473
+
474
+ ``` tsx
475
+ import { useAllEntitlements } from '@kelviq/react-sdk';
476
+
477
+ function EntitlementsList() {
478
+ const { data: entitlementsMap, isLoading, error } = useAllEntitlements();
479
+
480
+ if (isLoading) return <p>Loading all entitlements...</p>;
481
+ if (error) return <p>Error loading entitlements: {error.message}</p>;
482
+ if (!entitlementsMap) return <p>No entitlements data.</p>;
483
+
484
+ return (
485
+ <ul>
486
+ {Object.values(entitlementsMap).map(ent => (
487
+ <li key={ent.featureId}>
488
+ {ent.featureId}: {ent.hasAccess ? 'Enabled' : 'Disabled'} ({ent.featureType})
489
+ </li>
490
+ ))}
491
+ </ul>
492
+ );
493
+ }
494
+
495
+ ```
496
+
497
+ ```json
498
+ {
499
+ "api-calls-quota": {
500
+ "featureId": "api-calls-quota",
501
+ "featureType": "METER",
502
+ "hasAccess": true,
503
+ "currentUsage": 150,
504
+ "usageLimit": 1000,
505
+ "remaining": 850,
506
+ "hardLimit": true,
507
+ "items": [...]
508
+ },
509
+ "enable-dark-mode": {
510
+ "featureId": "enable-dark-mode",
511
+ "featureType": "BOOLEAN",
512
+ "hasAccess": true,
513
+ "currentUsage": 0,
514
+ "usageLimit": null,
515
+ "remaining": null,
516
+ "hardLimit": false,
517
+ "items": [...]
518
+ },
519
+ "max-items-per-page": {
520
+ "featureId": "max-items-per-page",
521
+ "featureType": "CUSTOMIZABLE",
522
+ "hasAccess": true,
523
+ "currentUsage": 0,
524
+ "usageLimit": 50,
525
+ "remaining": 50,
526
+ "hardLimit": false,
527
+ "items": [...]
528
+ }
529
+ }
530
+ ```
531
+
532
+ ### `useBooleanEntitlement(featureId: string)`
533
+
534
+ Returns the aggregated entitlement for a specific boolean feature from the cache.
535
+
536
+ - **Arguments:**
537
+ - `featureId: string`: The identifier of the boolean feature.
538
+ - **Returns:** `Entitlement | null`
539
+
540
+ ```tsx
541
+ import { useBooleanEntitlement } from '@kelviq/react-sdk';
542
+
543
+ const entitlement = useBooleanEntitlement("enable-dark-mode");
544
+ ```
545
+
546
+ ```json
547
+ {
548
+ "featureId": "enable-dark-mode",
549
+ "featureType": "BOOLEAN",
550
+ "hasAccess": true,
551
+ "currentUsage": 0,
552
+ "usageLimit": null,
553
+ "remaining": null,
554
+ "hardLimit": false,
555
+ "items": [
556
+ {
557
+ "featureId": "enable-dark-mode",
558
+ "featureType": "BOOLEAN",
559
+ "hasAccess": true
560
+ }
561
+ ]
562
+ }
563
+ ```
564
+
565
+ ### `useCustomizableEntitlement(featureId: string)`
566
+
567
+ Returns the aggregated entitlement for a specific customizable feature from the cache.
568
+
569
+ - **Arguments:**
570
+ - `featureId: string`: The identifier of the customizable feature.
571
+ - **Returns:** `Entitlement | null`
572
+
573
+ ```tsx
574
+ import { useCustomizableEntitlement } from '@kelviq/react-sdk';
575
+
576
+ const entitlement = useCustomizableEntitlement("max-items-per-page");
577
+ ```
578
+
579
+ ```json
580
+ {
581
+ "featureId": "max-items-per-page",
582
+ "featureType": "CUSTOMIZABLE",
583
+ "hasAccess": true,
584
+ "currentUsage": 0,
585
+ "usageLimit": 50,
586
+ "remaining": 50,
587
+ "hardLimit": false,
588
+ "items": [
589
+ {
590
+ "featureId": "max-items-per-page",
591
+ "featureType": "CUSTOMIZABLE",
592
+ "hasAccess": true,
593
+ "usageLimit": 50,
594
+ "currentUsage": 0,
595
+ "remaining": 50
596
+ }
597
+ ]
598
+ }
599
+ ```
600
+
601
+ ### `useMeteredEntitlement(featureId: string)`
602
+
603
+ Returns the aggregated entitlement for a specific metered feature from the cache.
604
+
605
+ - **Arguments:**
606
+ - `featureId: string`: The identifier of the metered feature.
607
+ - **Returns:** `Entitlement | null`
608
+
609
+ ```tsx
610
+ import { useMeteredEntitlement } from '@kelviq/react-sdk';
611
+
612
+ const entitlement = useMeteredEntitlement("api-calls-quota");
613
+ ```
614
+
615
+ ```json
616
+ {
617
+ "featureId": "api-calls-quota",
618
+ "featureType": "METER",
619
+ "hasAccess": true,
620
+ "currentUsage": 150,
621
+ "usageLimit": 1000,
622
+ "remaining": 850,
623
+ "hardLimit": true,
624
+ "items": [
625
+ {
626
+ "featureId": "api-calls-quota",
627
+ "featureType": "METER",
628
+ "hasAccess": true,
629
+ "resetAt": "2025-06-01T00:00:00Z",
630
+ "hardLimit": false,
631
+ "usageLimit": 500,
632
+ "currentUsage": 100,
633
+ "remaining": 400
634
+ },
635
+ {
636
+ "featureId": "api-calls-quota",
637
+ "featureType": "METER",
638
+ "hasAccess": true,
639
+ "resetAt": "2025-07-01T00:00:00Z",
640
+ "hardLimit": true,
641
+ "usageLimit": 500,
642
+ "currentUsage": 50,
643
+ "remaining": 450
644
+ }
645
+ ]
646
+ }
647
+ ```
648
+
649
+ ### `useSubscriptions()`
650
+
651
+ Returns the customer's subscription data. Only populated when `fetchSubscriptionsOnMount` is enabled in the provider config, or after calling `refreshSubscriptions()` from `useKelviq()`.
652
+
653
+ - **Returns:** `AsyncState<RawSubscriptionData[] | null>`
654
+
655
+ ```tsx
656
+ import { useSubscriptions } from '@kelviq/react-sdk';
657
+
658
+ function SubscriptionInfo() {
659
+ const { data: subscriptions, isLoading, error } = useSubscriptions();
660
+
661
+ if (isLoading) return <p>Loading subscriptions...</p>;
662
+ if (error) return <p>Error: {error.message}</p>;
663
+ if (!subscriptions) return <p>No subscriptions found.</p>;
664
+
665
+ return (
666
+ <ul>
667
+ {subscriptions.map(sub => (
668
+ <li key={sub.id}>
669
+ {sub.plan.name} — {sub.status} ({sub.recurrence})
670
+ </li>
671
+ ))}
672
+ </ul>
673
+ );
674
+ }
675
+ ```
676
+
677
+ ```json
678
+ [
679
+ {
680
+ "id": "sub-uuid-1",
681
+ "externalSubscriptionId": "ext-sub-123",
682
+ "startDate": "2025-01-01T00:00:00Z",
683
+ "endDate": null,
684
+ "billingPeriodStartTime": "2025-06-01T00:00:00Z",
685
+ "billingPeriodEndTime": "2025-07-01T00:00:00Z",
686
+ "amount": "49.99",
687
+ "recurrence": "monthly",
688
+ "currency": "USD",
689
+ "status": "active",
690
+ "product": {
691
+ "name": "Pro Plan",
692
+ "identifier": "pro-plan"
693
+ },
694
+ "plan": {
695
+ "name": "Pro Monthly",
696
+ "identifier": "pro-monthly"
697
+ },
698
+ "features": [
699
+ {
700
+ "featureId": "api-calls-quota",
701
+ "featureType": "METER",
702
+ "hasAccess": true,
703
+ "usageLimit": 1000,
704
+ "currentUsage": 150,
705
+ "remaining": 850
706
+ }
707
+ ],
708
+ "trialDaysRemaining": null,
709
+ "customerId": "cust_456"
710
+ }
711
+ ]
712
+ ```
713
+
714
+ You must enable `fetchSubscriptionsOnMount: true` in the provider's `config` prop, or call `refreshSubscriptions()` manually, for this hook to return data.
715
+
716
+ ### `useCustomer()`
717
+
718
+ Returns the customer data. Only populated when `fetchCustomerOnMount` is enabled in the provider config, or after calling `refreshCustomer()` from `useKelviq()`.
719
+
720
+ - **Returns:** `AsyncState<RawCustomerApiResponse | null>`
721
+
722
+ ```tsx
723
+ import { useCustomer } from '@kelviq/react-sdk';
724
+
725
+ function CustomerProfile() {
726
+ const { data: customer, isLoading, error } = useCustomer();
727
+
728
+ if (isLoading) return <p>Loading customer...</p>;
729
+ if (error) return <p>Error: {error.message}</p>;
730
+ if (!customer) return <p>No customer data.</p>;
731
+
732
+ return (
733
+ <div>
734
+ <h2>{customer.name}</h2>
735
+ <p>{customer.email}</p>
736
+ {customer.billingAddress && (
737
+ <p>{customer.billingAddress.city}, {customer.billingAddress.state}</p>
738
+ )}
739
+ </div>
740
+ );
741
+ }
742
+ ```
743
+
744
+ ```json
745
+ {
746
+ "id": "a1b2c3d4-e5f6-7890-1234-567890abcdef",
747
+ "customerId": "unique-customer-id-123",
748
+ "name": "John Doe",
749
+ "email": "customer@example.com",
750
+ "details": {},
751
+ "metadata": {
752
+ "source": "sdk_import",
753
+ "priority": "high"
754
+ },
755
+ "billingAddress": {
756
+ "country": "IN",
757
+ "line1": "123 Main Street",
758
+ "line2": "Apt 4B",
759
+ "postalCode": "560001",
760
+ "city": "Bangalore",
761
+ "state": "Karnataka"
762
+ },
763
+ "createdOn": "2025-06-04T06:03:30.195790Z",
764
+ "modifiedOn": "2025-06-04T06:03:30.195831Z"
765
+ }
766
+ ```
767
+
768
+ You must enable `fetchCustomerOnMount: true` in the provider's `config` prop, or call `refreshCustomer()` manually, for this hook to return data.
769
+
770
+ ### `usePricing()`
771
+
772
+ Returns the pricing/offering data for the configured product. Includes localized currency information, plans, features, and billing periods. Only populated when `fetchPricingOnMount` is enabled in the provider config, or after calling `refreshPricing()` from `useKelviq()`.
773
+
774
+ - **Returns:** `AsyncState<RawPricingApiResponse | null>`
775
+
776
+ ```tsx
777
+ import { usePricing } from '@kelviq/react-sdk';
778
+
779
+ function PricingDisplay() {
780
+ const { data: pricing, isLoading, error } = usePricing();
781
+
782
+ if (isLoading) return <p>Loading pricing...</p>;
783
+ if (error) return <p>Error: {error.message}</p>;
784
+ if (!pricing) return <p>No pricing data.</p>;
785
+
786
+ return (
787
+ <div>
788
+ <p>Currency: {pricing.currencySymbol} ({pricing.currencyCode})</p>
789
+ <ul>
790
+ {pricing.plans.map(plan => (
791
+ <li key={plan.id}>
792
+ {plan.displayName} — {plan.price.priceType}
793
+ </li>
794
+ ))}
795
+ </ul>
796
+ </div>
797
+ );
798
+ }
799
+ ```
800
+
801
+ You must set `productId` on the provider and enable `fetchPricingOnMount: true` in the provider's `config` prop, or call `refreshPricing()` manually, for this hook to return data.
802
+
803
+ When `customerId` is provided, the pricing response includes the customer's active subscription details and the `isCustomerExists` flag. Use `plansEnabled` to filter the response to specific plans (e.g., `"pro,enterprise"`).
804
+
805
+ **Example using a specific entitlement hook:**
806
+
807
+ ``` tsx
808
+ import { useBooleanEntitlement, useKelviq } from '@kelviq/react-sdk';
809
+
810
+ function FeatureSpecificComponent({ featureId }: { featureId: string }) {
811
+ const { isLoading, error } = useKelviq();
812
+ const entitlement = useBooleanEntitlement(featureId);
813
+
814
+ if (isLoading) return <p>Loading feature {featureId}...</p>;
815
+ if (error) return <p>Error loading feature {featureId}: {error.message}</p>;
816
+
817
+ if (entitlement && entitlement.hasAccess) {
818
+ return <p>You have access to {featureId}!</p>;
819
+ } else {
820
+ return <p>You do not have access to {featureId}.</p>;
821
+ }
822
+ }
823
+
824
+ ```
825
+
826
+ ## **6. Conditional Rendering Components**
827
+
828
+ These components provide a declarative way to render UI based on entitlement status. They internally use the respective hooks.
829
+
830
+ **Common Props:**
831
+
832
+ - `featureId: string`: The unique identifier of the feature to check.
833
+ - `children: ReactNode | ((data: Entitlement) => ReactNode)`:
834
+ - If a `ReactNode`, it's rendered when the user is entitled and conditions are met.
835
+ - If a function (render prop), it's called with the aggregated `Entitlement` data and its return value is rendered.
836
+ - `fallback?: ReactNode`: Content to render if the user is not entitled, or if data is loading (and no `loadingComponent` is provided), or if an error occurs. Defaults to `null`.
837
+ - `loadingComponent?: ReactNode`: Specific content to render while the entitlement data is loading. Overrides `fallback` during loading.
838
+
839
+ ### `ShowWhenBooleanEntitled`
840
+
841
+ Renders children if the boolean feature is enabled (`hasAccess: true`).
842
+
843
+ ``` tsx
844
+ import { ShowWhenBooleanEntitled } from '@kelviq/react-sdk';
845
+
846
+ <ShowWhenBooleanEntitled
847
+ featureId="enable-dark-mode"
848
+ loadingComponent={<p>Checking theme settings...</p>}
849
+ fallback={<p>Dark mode is not available.</p>}
850
+ >
851
+ <button>Toggle Dark Mode</button>
852
+ </ShowWhenBooleanEntitled>
853
+
854
+ <ShowWhenBooleanEntitled featureId="show-advanced-settings">
855
+ {(entitlementData) => (
856
+ <div>Advanced settings for {entitlementData.featureId} are visible!</div>
857
+ )}
858
+ </ShowWhenBooleanEntitled>
859
+
860
+ ```
861
+
862
+ ```json
863
+ {
864
+ "featureId": "show-advanced-settings",
865
+ "featureType": "BOOLEAN",
866
+ "hasAccess": true,
867
+ "currentUsage": 0,
868
+ "usageLimit": null,
869
+ "remaining": null,
870
+ "hardLimit": false,
871
+ "items": [
872
+ {
873
+ "featureId": "show-advanced-settings",
874
+ "featureType": "BOOLEAN",
875
+ "hasAccess": true
876
+ }
877
+ ]
878
+ }
879
+ ```
880
+
881
+ ### `ShowWhenCustomizableEntitled`
882
+
883
+ Renders children if the customizable feature is enabled (`hasAccess: true`).
884
+
885
+ ``` tsx
886
+ import { ShowWhenCustomizableEntitled } from '@kelviq/react-sdk';
887
+
888
+ <ShowWhenCustomizableEntitled
889
+ featureId="max-items-per-page"
890
+ loadingComponent={<p>Loading display settings...</p>}
891
+ fallback={<p>Default item limit applies.</p>}
892
+ >
893
+ {(entitlementData) => (
894
+ <p>You have access to {entitlementData.featureId}.</p>
895
+ )}
896
+ </ShowWhenCustomizableEntitled>
897
+
898
+ ```
899
+
900
+ ```json
901
+ {
902
+ "featureId": "max-items-per-page",
903
+ "featureType": "CUSTOMIZABLE",
904
+ "hasAccess": true,
905
+ "currentUsage": 0,
906
+ "usageLimit": 50,
907
+ "remaining": 50,
908
+ "hardLimit": false,
909
+ "items": [
910
+ {
911
+ "featureId": "max-items-per-page",
912
+ "featureType": "CUSTOMIZABLE",
913
+ "hasAccess": true,
914
+ "usageLimit": 50,
915
+ "currentUsage": 0,
916
+ "remaining": 50
917
+ }
918
+ ]
919
+ }
920
+ ```
921
+
922
+ ### `ShowWhenMeteredEntitled`
923
+
924
+ Renders children if the metered feature is enabled and, by default, if `remaining` usage is greater than 0 or unlimited (`usageLimit` is `null`).
925
+
926
+ - **Optional Prop:**
927
+ - `condition?: (data: Entitlement) => boolean`: A custom function to further determine if children should render based on the entitlement data.
928
+ - **Children Prop:** Can be `ReactNode` or `(data: Entitlement) => ReactNode`.
929
+
930
+ ``` tsx
931
+ import { ShowWhenMeteredEntitled } from '@kelviq/react-sdk';
932
+
933
+ <ShowWhenMeteredEntitled
934
+ featureId="api-calls-quota"
935
+ loadingComponent={<p>Loading API quota...</p>}
936
+ fallback={<p>API call limit reached or feature not available.</p>}
937
+ >
938
+ {(meterData) => (
939
+ <div>
940
+ <p>API Calls Used: {meterData.currentUsage} / {meterData.usageLimit === null ? 'Unlimited' : meterData.usageLimit}</p>
941
+ <p>Remaining: {meterData.remaining === null ? 'Unlimited' : meterData.remaining}</p>
942
+ </div>
943
+ )}
944
+ </ShowWhenMeteredEntitled>
945
+
946
+ ```
947
+
948
+ ```json
949
+ {
950
+ "featureId": "api-calls-quota",
951
+ "featureType": "METER",
952
+ "hasAccess": true,
953
+ "currentUsage": 150,
954
+ "usageLimit": 1000,
955
+ "remaining": 850,
956
+ "hardLimit": true,
957
+ "items": [
958
+ {
959
+ "featureId": "api-calls-quota",
960
+ "featureType": "METER",
961
+ "hasAccess": true,
962
+ "resetAt": "2025-06-01T00:00:00Z",
963
+ "hardLimit": false,
964
+ "usageLimit": 500,
965
+ "currentUsage": 100,
966
+ "remaining": 400
967
+ },
968
+ {
969
+ "featureId": "api-calls-quota",
970
+ "featureType": "METER",
971
+ "hasAccess": true,
972
+ "resetAt": "2025-07-01T00:00:00Z",
973
+ "hardLimit": true,
974
+ "usageLimit": 500,
975
+ "currentUsage": 50,
976
+ "remaining": 450
977
+ }
978
+ ]
979
+ }
980
+ ```
981
+
982
+ ## **7. Pricing Components**
983
+
984
+ The SDK provides render-prop components for displaying pricing data. These require `productId` on the provider and `fetchPricingOnMount: true` (or a manual `refreshPricing()` call).
985
+
986
+ ### `KQPrice`
987
+
988
+ Renders pricing information for a specific plan and billing period. Provides a `formattedPrice` string with locale-aware number formatting and currency symbol.
989
+
990
+ **Props:**
991
+ - `planIdentifier: string`: The plan identifier to display pricing for.
992
+ - `billingPeriod: string`: The billing period to show (e.g. `"MONTHLY"`, `"YEARLY"`, `"ONE_TIME"`).
993
+ - `children: (data) => ReactNode`: Render function receiving price data.
994
+ - `formatOptions?: KQFormatPriceOptions`: Options for the `formattedPrice` string.
995
+ - `loadingComponent?: ReactNode`: Shown while pricing data is loading.
996
+ - `fallback?: ReactNode`: Shown when the plan is not found or pricing data is unavailable.
997
+
998
+ ```tsx
999
+ import { KQPrice } from '@kelviq/react-sdk';
1000
+
1001
+ <KQPrice
1002
+ planIdentifier="pro-plan"
1003
+ billingPeriod="MONTHLY"
1004
+ fallback={<p>Price not available</p>}
1005
+ >
1006
+ {({ formattedPrice, isFree, hasFreeTrial, trialPeriod }) => (
1007
+ <div>
1008
+ <h3>{formattedPrice}</h3>
1009
+ {hasFreeTrial && <p>{trialPeriod}-day free trial</p>}
1010
+ </div>
1011
+ )}
1012
+ </KQPrice>
1013
+ ```
1014
+
1015
+ The `children` render function receives an object with:
1016
+ - `plan`: The full plan object (`RawPricingPlan`).
1017
+ - `charge`: The matching charge for the billing period (`RawPricingCharge | null`).
1018
+ - `amount: number`: The raw price amount.
1019
+ - `formattedPrice: string`: Locale-formatted price string (e.g. `"$49.99"`, `"Free"`).
1020
+ - `currencySymbol: string`: The currency symbol (e.g. `"$"`, `"€"`).
1021
+ - `currencyCode: string`: The currency code (e.g. `"USD"`, `"EUR"`).
1022
+ - `pricingLocale: string`: The locale used for pricing (e.g. `"en-US"`).
1023
+ - `isFree: boolean`: Whether the plan is free.
1024
+ - `hasFreeTrial: boolean`: Whether the plan has a free trial.
1025
+ - `trialPeriod: number`: Trial period in days.
1026
+
1027
+ #### `KQFormatPriceOptions`
1028
+
1029
+ Options for customizing the `formattedPrice` string:
1030
+
1031
+ - `compact?: boolean`: Use compact notation (e.g. `"1.2K"` instead of `"1,200"`). Defaults to `false`.
1032
+ - `locale?: string`: Locale for number formatting. Defaults to the `pricingLocale` from the API.
1033
+ - `includeCurrencySymbol?: boolean`: Whether to include the currency symbol. Defaults to `true`.
1034
+
1035
+ ### `KQFeatureList`
1036
+
1037
+ Iterates over features for a specific plan, calling the render function for each feature.
1038
+
1039
+ **Props:**
1040
+ - `planIdentifier: string`: The plan identifier to display features for.
1041
+ - `children: (data) => ReactNode`: Render function called for each feature.
1042
+ - `featureType?: 'BOOLEAN' | 'METER'`: Optional filter to show only specific feature types.
1043
+ - `loadingComponent?: ReactNode`: Shown while pricing data is loading.
1044
+ - `fallback?: ReactNode`: Shown when the plan is not found or has no features.
1045
+
1046
+ ```tsx
1047
+ import { KQFeatureList } from '@kelviq/react-sdk';
1048
+
1049
+ <KQFeatureList
1050
+ planIdentifier="pro-plan"
1051
+ fallback={<p>No features</p>}
1052
+ >
1053
+ {({ feature }) => (
1054
+ <div key={feature.id}>
1055
+ <span>{feature.displayName}</span>
1056
+ <span>
1057
+ {feature.featureType === 'BOOLEAN'
1058
+ ? feature.value ? '✓' : '✗'
1059
+ : feature.value}
1060
+ </span>
1061
+ </div>
1062
+ )}
1063
+ </KQFeatureList>
1064
+ ```
1065
+
1066
+ The `children` render function receives an object with:
1067
+ - `feature`: The feature object (`RawPricingFeature`) with `id`, `displayName`, `featureType`, `value`, `enabled`.
1068
+ - `plan`: The full plan object (`RawPricingPlan`).
1069
+ - `index: number`: The index of the feature in the list.
1070
+
1071
+ ### `kqFormatPrice(amount, currencySymbol, options?)`
1072
+
1073
+ A standalone utility function for formatting prices. Exported from the SDK for use outside of components.
1074
+
1075
+ ```tsx
1076
+ import { kqFormatPrice } from '@kelviq/react-sdk';
1077
+
1078
+ kqFormatPrice(1299.99, '$'); // "$1,299.99"
1079
+ kqFormatPrice(1299.99, '$', { compact: true }); // "$1.3K"
1080
+ kqFormatPrice(49.99, '€', { locale: 'de-DE' }); // "€49,99"
1081
+ kqFormatPrice(49.99, '$', { includeCurrencySymbol: false }); // "49.99"
1082
+ ```
1083
+
1084
+ ## **8. Key Types**
1085
+
1086
+ The SDK exports several types for better integration with TypeScript. Some key ones include:
1087
+
1088
+ - `KelviqContextValue`: The shape of the object returned by `useKelviq()`.
1089
+ - `KelviqApiBehaviorOptions`: Configuration options for the `config` prop.
1090
+ - `AsyncState<T>`: Generic type for asynchronous data states (`{ data, isLoading, error }`).
1091
+ - `Entitlement`: The unified entitlement type with aggregated data and an `items` array containing the raw API objects.
1092
+ - `EntitlementMap`: The structure of the cached entitlements (`Record<string, Entitlement>`), keyed by `featureId`.
1093
+ - `EntitlementsResponse`: The raw API response shape (`{ customerId, entitlements }`) returned by `getRawEntitlements()` and `getRawEntitlement()`.
1094
+ - `RawEntitlementsApiResponse` and related `Raw...` types: Represent the structure of the direct API response.
1095
+ - `RawSubscriptionData`: A single subscription object as returned by the subscriptions API, including `plan`, `product`, `features`, `status`, `amount`, `recurrence`, etc.
1096
+ - `RawCustomerApiResponse`: Customer data as returned by the customer API, including `id`, `customerId`, `name`, `email`, `billingAddress`, `details`, `metadata`, `createdOn`, and `modifiedOn`.
1097
+ - `RawBillingAddress`: The billing address object (`country`, `line1`, `line2`, `postalCode`, `city`, `state`).
1098
+ - `RawPricingApiResponse`: The full pricing/offering API response including `plans`, `currencySymbol`, `currencyCode`, `pricingLocale`, and `billingPeriods`.
1099
+ - `RawPricingPlan`: A single plan with `identifier`, `displayName`, `displayDescription`, `price`, `features`, and `enabled`.
1100
+ - `RawPricingFeature`: A plan feature with `id`, `displayName`, `featureType`, `value`, and `enabled`.
1101
+ - `RawPricingCharge`: A charge entry with `chargePeriod` and `priceData` (containing `amount`).
1102
+ - `KQFormatPriceOptions`: Options for the `kqFormatPrice` utility (`compact`, `locale`, `includeCurrencySymbol`).
1103
+
1104
+ You can import these types directly from the main SDK entry:
1105
+
1106
+ ``` ts
1107
+ import type {
1108
+ Entitlement,
1109
+ EntitlementMap,
1110
+ EntitlementsResponse,
1111
+ RawSubscriptionData,
1112
+ RawCustomerApiResponse,
1113
+ RawBillingAddress,
1114
+ RawPricingApiResponse,
1115
+ RawPricingPlan,
1116
+ RawPricingFeature,
1117
+ RawPricingCharge,
1118
+ KQFormatPriceOptions,
1119
+ } from '@kelviq/react-sdk';
1120
+ ```
1121
+
1122
+ ## **9. Error Handling**
1123
+
1124
+ - **Provider Level:** The `onError` callback in `config` (`KelviqApiBehaviorOptions`) can be used to globally handle errors that occur during the entitlement fetching process initiated by the provider.
1125
+ - **Context Level:** `useKelviq()` returns a global `isLoading: boolean` and `error: Error | null` state, reflecting the provider's most recent fetch operation. Use these for loading/error UI in your components.
1126
+ - **`allEntitlements` Level:** The `allEntitlements` object from `useKelviq()` or `useAllEntitlements()` also carries its own `isLoading` and `error` fields within the `AsyncState` wrapper.
1127
+
1128
+ ## **10. Example Usage**
1129
+
1130
+ A comprehensive example is provided within the comments of the SDK code, demonstrating provider setup and component usage. The core setup involves:
1131
+
1132
+ 1. Wrapping your application with `KelviqProvider` and providing the required props (`customerId`, `accessToken`)
1133
+ 2. Using hooks like `useBooleanEntitlement` or conditional components like `ShowWhenBooleanEntitled` in your components to control UI and behavior based on entitlements.
1134
+
1135
+ ## **11. API Request Service**
1136
+
1137
+ The SDK relies on an `apiRequest` function for making HTTP requests. The SDK's `KelviqProvider` passes configuration like `timeout`, `maxRetries`, `backoffBaseDelay`, and `accessToken` to this function.
1138
+
1139
+ - **Your Responsibility:** You need to ensure that your project includes an implementation of this `apiRequest` service (e.g., in `src/services/makeRequest.service.ts`) that matches the `ApiRequestConfig` and `ApiResponse` interfaces used by the SDK. This service should handle actual HTTP communication, including appending query parameters passed via `ApiRequestConfig.queryParams` and using the `accessToken` to set the `Authorization` header.
1140
+ - The placeholder `apiRequest` function included in the SDK's source code is for demonstration and type-checking purposes only and will not make real API calls.
1141
+
1142
+ ## **12. Project Structure (for contributors/reference)**
1143
+
1144
+ The SDK source code (`lib/`) is organized as follows:
1145
+
1146
+ - `components/`: Contains conditional rendering and pricing React components.
1147
+ - `ShowWhenBooleanEntitled.tsx`
1148
+ - `ShowWhenCustomizableEntitled.tsx`
1149
+ - `ShowWhenMeteredEntitled.tsx`
1150
+ - `ShowWhenEntitledInternal.tsx` (Internal helper, not typically exported)
1151
+ - `KQPrice.tsx`
1152
+ - `KQFeatureList.tsx`
1153
+ - `contexts/`: Defines the React Context and Provider.
1154
+ - `KelviqContext.ts`
1155
+ - `KelviqProvider.tsx`
1156
+ - `hooks/`: Contains all custom React Hooks.
1157
+ - `useKelviq.ts`
1158
+ - `useAllEntitlements.ts`
1159
+ - `useBooleanEntitlement.ts`
1160
+ - `useCustomizableEntitlement.ts`
1161
+ - `useMeteredEntitlement.ts`
1162
+ - `useSubscriptions.ts`
1163
+ - `useCustomer.ts`
1164
+ - `usePricing.ts`
1165
+ - `index.ts` (Exports all hooks)
1166
+ - `types/`: Contains all TypeScript definitions.
1167
+ - `api.types.ts` (Raw types from API, including pricing types)
1168
+ - `sdk.types.ts` (Processed types for SDK and public use)
1169
+ - `index.ts` (Re-exports all types)
1170
+ - `utils/`: Contains utility functions.
1171
+ - `transformations.ts` (For `transformApiEntitlements`)
1172
+ - `formatPrice.ts` (For `kqFormatPrice`)
1173
+ - `index.ts` (Exports utilities)
1174
+ - `index.ts`: The main entry point of the SDK, re-exporting all public APIs (provider, hooks, components, types).
1175
+
1176
+ ## Using the Sandbox
1177
+
1178
+ If you want to use the sandbox, you need to set the `environment` option to `sandbox` in the `KelviqProvider`.
1179
+
1180
+ ```tsx
1181
+ <KelviqProvider
1182
+ customerId="YOUR_CUSTOMER_ID"
1183
+ accessToken="YOUR_ACCESS_TOKEN"
1184
+ environment="sandbox">
1185
+
1186
+ </KelviqProvider>
1187
+ ```