@kelviq/react-sdk 0.0.1-beta → 2.0.1-beta

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.
@@ -1,165 +1,164 @@
1
- import { jsx as q, Fragment as b } from "react/jsx-runtime";
2
- import { createContext as C, useState as U, useCallback as R, useEffect as _, useMemo as F, useContext as O } from "react";
3
- const B = "GET", j = 5e3, N = 3, z = 1e3;
4
- function G(e) {
1
+ import { jsx as S, Fragment as M } from "react/jsx-runtime";
2
+ import { createContext as Z, useState as T, useCallback as y, useEffect as Q, useMemo as ee, useContext as te } from "react";
3
+ const re = "GET", ne = 5e3, se = 3, oe = 1e3;
4
+ function O(n) {
5
5
  const {
6
- method: i = B,
7
- headers: t = {},
6
+ method: o = re,
7
+ headers: i = {},
8
8
  // Renamed to avoid conflict with internal 'headers' variable
9
- body: n,
10
- timeout: v = j,
11
- maxRetries: o = N,
12
- backoffBaseDelay: y = z,
13
- queryParams: p,
14
- accessToken: w
9
+ body: t,
10
+ timeout: g = ne,
11
+ maxRetries: m = se,
12
+ backoffBaseDelay: L = oe,
13
+ queryParams: v,
14
+ accessToken: l
15
15
  // Use the direct accessToken
16
- } = e;
17
- let { url: f } = e, c = 0;
18
- return new Promise((T, m) => {
19
- if (p) {
16
+ } = n;
17
+ let { url: f } = n, p = 0;
18
+ return new Promise((U, b) => {
19
+ if (v) {
20
20
  const s = new URLSearchParams();
21
- for (const h in p)
22
- p[h] !== void 0 && s.append(h, String(p[h]));
21
+ for (const u in v)
22
+ v[u] !== void 0 && s.append(u, String(v[u]));
23
23
  s.toString() && (f += (f.includes("?") ? "&" : "?") + s.toString());
24
24
  }
25
- function a() {
25
+ function C() {
26
26
  const s = new XMLHttpRequest();
27
- s.open(i, f, !0), s.timeout = v;
28
- const h = {
27
+ s.open(o, f, !0), s.timeout = g;
28
+ const u = {
29
29
  Accept: "application/json",
30
30
  "X-Requested-With": "XMLHttpRequest",
31
- ...t
31
+ ...i
32
32
  // Apply custom headers, allowing them to override defaults
33
33
  };
34
- i !== "GET" && n && typeof n == "object" && !(n instanceof FormData) && (h["Content-Type"] || (h["Content-Type"] = "application/json")), w && (h.Authorization = `Bearer ${w}`);
35
- for (const [l, E] of Object.entries(h))
36
- s.setRequestHeader(l, E);
34
+ o !== "GET" && t && typeof t == "object" && !(t instanceof FormData) && (u["Content-Type"] || (u["Content-Type"] = "application/json")), l && (u.Authorization = `Bearer ${l}`);
35
+ for (const [a, w] of Object.entries(u))
36
+ s.setRequestHeader(a, w);
37
37
  s.onload = function() {
38
- const { status: l, statusText: E, responseText: A } = s;
39
- if (l >= 200 && l < 300)
38
+ const { status: a, statusText: w, responseText: P } = s;
39
+ if (a >= 200 && a < 300)
40
40
  try {
41
- const S = A ? JSON.parse(A) : {};
42
- T({ status: l, statusText: E, data: S });
43
- } catch (S) {
44
- const $ = S instanceof Error ? S : new Error(String(S));
41
+ const A = P ? JSON.parse(P) : {};
42
+ U({ status: a, statusText: w, data: A });
43
+ } catch (A) {
44
+ const I = A instanceof Error ? A : new Error(String(A));
45
45
  console.error(
46
- `Kelviq SDK (apiRequest): Invalid JSON response for URL ${f}. Error: ${$.message}. Response: ${A}`
47
- ), m(
46
+ `Kelviq SDK (apiRequest): Invalid JSON response for URL ${f}. Error: ${I.message}. Response: ${P}`
47
+ ), b(
48
48
  new Error(
49
- `Invalid JSON response: ${$.message}`
49
+ `Invalid JSON response: ${I.message}`
50
50
  )
51
51
  );
52
52
  }
53
53
  else
54
- L(
55
- `Request to ${f} failed with status ${l} ${E}. Response: ${A}`
54
+ h(
55
+ `Request to ${f} failed with status ${a} ${w}. Response: ${P}`
56
56
  );
57
- }, s.onerror = () => L(
57
+ }, s.onerror = () => h(
58
58
  `Network error for URL ${f}. The request could not be completed.`
59
- ), s.ontimeout = () => L(`Request to ${f} timed out.`);
60
- function L(l) {
61
- if (c < o) {
62
- c++;
63
- const E = Math.min(
64
- y * Math.pow(2, c - 1),
59
+ ), s.ontimeout = () => h(`Request to ${f} timed out.`);
60
+ function h(a) {
61
+ if (p < m) {
62
+ p++;
63
+ const w = Math.min(
64
+ L * Math.pow(2, p - 1),
65
65
  3e4
66
66
  // Cap retry delay at 30 seconds
67
67
  );
68
68
  console.warn(
69
- `Kelviq SDK (apiRequest): Retrying request to ${f}. Attempt ${c}/${o}. Error: ${l}. Retrying in ${E}ms.`
70
- ), setTimeout(a, E);
69
+ `Kelviq SDK (apiRequest): Retrying request to ${f}. Attempt ${p}/${m}. Error: ${a}. Retrying in ${w}ms.`
70
+ ), setTimeout(C, w);
71
71
  } else
72
- m(
72
+ b(
73
73
  new Error(
74
- `${l} (Max retries ${o} reached)`
74
+ `${a} (Max retries ${m} reached)`
75
75
  )
76
76
  );
77
77
  }
78
78
  try {
79
- let l = n;
80
- n && typeof n == "object" && !(n instanceof FormData) && h["Content-Type"] === "application/json" && (l = JSON.stringify(n)), s.send(l);
81
- } catch (l) {
82
- const E = l instanceof Error ? l : new Error(String(l));
79
+ let a = t;
80
+ t && typeof t == "object" && !(t instanceof FormData) && u["Content-Type"] === "application/json" && (a = JSON.stringify(t)), s.send(a);
81
+ } catch (a) {
82
+ const w = a instanceof Error ? a : new Error(String(a));
83
83
  console.error(
84
84
  `Kelviq SDK (apiRequest): Error sending request to ${f}.`,
85
- E
86
- ), m(new Error(`Failed to send request: ${E.message}`));
85
+ w
86
+ ), b(new Error(`Failed to send request: ${w.message}`));
87
87
  }
88
88
  }
89
- a();
89
+ C();
90
90
  });
91
91
  }
92
- function H(e) {
92
+ function ie(n, o) {
93
+ const i = o[0].featureType;
94
+ if (i === "METER") {
95
+ let t = 0, g = 0, m = !1;
96
+ for (const v of o) {
97
+ const l = v, f = typeof l.usageLimit == "number" ? l.usageLimit : null, p = typeof l.currentUsage == "number" ? l.currentUsage : 0;
98
+ f === null && (t = null), t !== null && (t += f), g += p, l.hardLimit && (m = !0);
99
+ }
100
+ const L = t !== null ? t - g : null;
101
+ return {
102
+ featureId: n,
103
+ featureType: i,
104
+ hasAccess: L === null || L > 0,
105
+ currentUsage: g,
106
+ usageLimit: t,
107
+ remaining: L,
108
+ hardLimit: m,
109
+ items: o
110
+ };
111
+ }
112
+ if (i === "CUSTOMIZABLE") {
113
+ const t = o[0];
114
+ return {
115
+ featureId: n,
116
+ featureType: i,
117
+ hasAccess: o.some((g) => g.hasAccess),
118
+ currentUsage: typeof t.currentUsage == "number" ? t.currentUsage : 0,
119
+ usageLimit: typeof t.usageLimit == "number" ? t.usageLimit : null,
120
+ remaining: typeof t.remaining == "number" ? t.remaining : null,
121
+ hardLimit: t.hardLimit === !0,
122
+ items: o
123
+ };
124
+ }
125
+ return {
126
+ featureId: n,
127
+ featureType: i,
128
+ hasAccess: o.some((t) => t.hasAccess),
129
+ currentUsage: 0,
130
+ usageLimit: null,
131
+ remaining: null,
132
+ hardLimit: !1,
133
+ items: o
134
+ };
135
+ }
136
+ function ae(n) {
137
+ const o = {};
138
+ if (!n || !Array.isArray(n.entitlements))
139
+ return console.warn(
140
+ "Kelviq SDK: Invalid or empty entitlements array in API response.",
141
+ n
142
+ ), o;
93
143
  const i = {};
94
- return !e || !Array.isArray(e.entitlements) ? (console.warn(
95
- "Kelviq SDK: Invalid or empty entitlements array in API response.",
96
- e
97
- ), i) : (e.entitlements.forEach((t) => {
144
+ for (const t of n.entitlements) {
98
145
  if (!t || typeof t.featureId != "string" || typeof t.featureType != "string") {
99
146
  console.warn(
100
147
  "Kelviq SDK: Skipping invalid raw entitlement object:",
101
148
  t
102
149
  );
103
- return;
104
- }
105
- let n = null;
106
- const v = {
107
- // Omit type as it's added in switch
108
- featureKey: t.featureId,
109
- hasAccess: t.hasAccess
110
- };
111
- switch (t.featureType) {
112
- case "BOOLEAN":
113
- n = {
114
- ...v,
115
- type: "boolean"
116
- };
117
- break;
118
- case "CUSTOMIZABLE": {
119
- const o = t;
120
- n = {
121
- ...v,
122
- type: "customizable",
123
- configuration: typeof o.value == "number" ? o.value : null
124
- };
125
- break;
126
- }
127
- case "METER": {
128
- const o = t, y = typeof o.usageLimit == "number" ? o.usageLimit : null, p = typeof o.currentUsage == "number" ? o.currentUsage : 0;
129
- n = {
130
- ...v,
131
- type: "metered",
132
- limit: y,
133
- used: p,
134
- remaining: y !== null ? y - p : null,
135
- // If limit is null (unlimited), remaining is also null
136
- resetAt: o.resetAt,
137
- hardLimit: o.hardLimit
138
- };
139
- break;
140
- }
141
- default: {
142
- const o = t;
143
- console.warn(
144
- `Kelviq SDK: Encountered unknown or unhandled entitlement featureType: '${String(
145
- o.featureType
146
- )}' for feature '${String(
147
- o.featureId
148
- )}'. This entitlement will be ignored.`
149
- );
150
- break;
151
- }
150
+ continue;
152
151
  }
153
- n && (i[n.featureKey] = n);
154
- }), i);
152
+ i[t.featureId] || (i[t.featureId] = []), i[t.featureId].push(t);
153
+ }
154
+ for (const t in i)
155
+ o[t] = ie(
156
+ t,
157
+ i[t]
158
+ );
159
+ return o;
155
160
  }
156
- const W = () => ({
157
- data: null,
158
- isLoading: !1,
159
- error: new Error(
160
- "KelviqContext not fully initialized or entitlements not fetched."
161
- )
162
- }), I = {
161
+ const J = {
163
162
  allEntitlements: {
164
163
  data: null,
165
164
  isLoading: !0,
@@ -168,294 +167,482 @@ const W = () => ({
168
167
  refreshAllEntitlements: () => (console.warn(
169
168
  "refreshAllEntitlements called on default KelviqContext. Ensure KelviqProvider is properly set up."
170
169
  ), Promise.resolve()),
171
- getEntitlement: W,
172
- hasAccess: () => {
170
+ getEntitlements: () => ({}),
171
+ getEntitlement: () => null,
172
+ getRawEntitlements: () => null,
173
+ getRawEntitlement: () => null,
174
+ hasAccess: () => !1,
175
+ updateEntitlement: () => {
176
+ console.warn(
177
+ "updateEntitlement called on default KelviqContext. Ensure KelviqProvider is properly set up."
178
+ );
179
+ },
180
+ subscriptions: {
181
+ data: null,
182
+ isLoading: !1,
183
+ error: null
184
+ },
185
+ refreshSubscriptions: () => (console.warn(
186
+ "refreshSubscriptions called on default KelviqContext. Ensure KelviqProvider is properly set up."
187
+ ), Promise.resolve()),
188
+ customer: {
189
+ data: null,
190
+ isLoading: !1,
191
+ error: null
173
192
  },
193
+ refreshCustomer: () => (console.warn(
194
+ "refreshCustomer called on default KelviqContext. Ensure KelviqProvider is properly set up."
195
+ ), Promise.resolve()),
174
196
  isLoading: !0,
175
197
  error: null,
176
198
  apiUrl: "",
177
199
  environment: "production",
178
200
  entitlementsPath: "",
179
201
  customerId: ""
180
- }, M = C(
181
- I
182
- ), X = "https://edge.api.kelviq.com/api/v1/", J = "https://edge.sandboxapi.kelviq.com/api/v1/", V = "entitlements/", Q = ({
183
- children: e,
184
- apiUrl: i,
185
- // Direct prop
186
- entitlementsPath: t = V,
187
- // Direct prop
188
- customerId: n,
189
- // Direct prop
190
- environment: v = "production",
191
- accessToken: o,
192
- // Direct prop
193
- config: y = {}
194
- // Optional config object with defaults
202
+ }, V = Z(
203
+ J
204
+ ), le = "https://edge.api.kelviq.com/api/v1/", ue = "https://edge.sandboxapi.kelviq.com/api/v1/", ce = "entitlements/", me = ({
205
+ children: n,
206
+ apiUrl: o,
207
+ entitlementsPath: i = ce,
208
+ customerId: t,
209
+ environment: g = "production",
210
+ accessToken: m,
211
+ config: L = {}
195
212
  }) => {
196
213
  const {
197
- onError: p,
198
- maxRetries: w,
214
+ onError: v,
215
+ maxRetries: l,
199
216
  timeout: f,
200
- backoffBaseDelay: c,
201
- fetchEntitlementsOnMount: T = !0
202
- // Default within config
203
- } = y, m = i || (v === "sandbox" ? J : X), [a, s] = U({
217
+ backoffBaseDelay: p,
218
+ fetchEntitlementsOnMount: U = !0,
219
+ fetchSubscriptionsOnMount: b = !1,
220
+ fetchCustomerOnMount: C = !1
221
+ } = L, s = o || (g === "sandbox" ? ue : le), [u, h] = T({
222
+ data: null,
223
+ isLoading: !!s && U,
224
+ error: null
225
+ }), [a, w] = T(null), [P, A] = T({
204
226
  data: null,
205
- isLoading: !!m && T,
206
- // Only loading if apiBaseUrl is present and fetchOnMount is true
227
+ isLoading: !!s && b,
207
228
  error: null
208
- }), [h, L] = U(
209
- !!m && T
210
- ), [l, E] = U(null), A = R(
211
- (g, d, r) => {
212
- const u = new Error(
213
- `Kelviq SDK (${d}): ${g}`
229
+ }), [I, $] = T({
230
+ data: null,
231
+ isLoading: !!s && C,
232
+ error: null
233
+ }), [D, K] = T(
234
+ !!s && U
235
+ ), [k, x] = T(null), E = y(
236
+ (c, e, r) => {
237
+ const d = new Error(
238
+ `Kelviq SDK (${e}): ${c}`
214
239
  );
215
- console.error(u.message, r || ""), E((P) => P || u), p && p(u);
240
+ console.error(d.message, r || ""), x((q) => q || d), v && v(d);
216
241
  },
217
- [p]
218
- ), S = R(() => {
219
- if (!m) {
242
+ [v]
243
+ ), _ = y(() => {
244
+ if (!s) {
220
245
  const r = "API URL not configured. Cannot fetch entitlements.";
221
- return s({
246
+ return h({
222
247
  data: null,
223
248
  isLoading: !1,
224
249
  error: new Error(r)
225
- }), A(r, "fetchAllEntitlements"), L(!1), Promise.reject(new Error(r));
250
+ }), E(r, "fetchAllEntitlements"), K(!1), Promise.reject(new Error(r));
226
251
  }
227
- if (!n) {
252
+ if (!t) {
228
253
  const r = "CustomerId must be provided as props to KelviqProvider.";
229
- return s(() => ({
254
+ return h(() => ({
230
255
  data: null,
231
256
  isLoading: !1,
232
257
  error: new Error(r)
233
- })), A(r, "fetchAllEntitlements"), L(!1), Promise.reject(new Error(r));
258
+ })), E(r, "fetchAllEntitlements"), K(!1), Promise.reject(new Error(r));
234
259
  }
235
- s((r) => ({
260
+ h((r) => ({
236
261
  ...r,
237
262
  isLoading: !0,
238
263
  error: null
239
- })), L(!0), E(null);
240
- const g = `${m.replace(/\/$/, "")}/${t.replace(/^\//, "")}`;
241
- return G({
242
- url: g,
264
+ })), K(!0), x(null);
265
+ const c = `${s.replace(/\/$/, "")}/${i.replace(/^\//, "")}`;
266
+ return O({
267
+ url: c,
243
268
  method: "GET",
244
269
  timeout: f,
245
- maxRetries: w,
246
- backoffBaseDelay: c,
247
- // Pass this to apiRequest
248
- accessToken: o,
270
+ maxRetries: l,
271
+ backoffBaseDelay: p,
272
+ accessToken: m,
249
273
  queryParams: {
250
- customer_id: n
274
+ customer_id: t
251
275
  }
252
276
  }).then((r) => {
253
277
  if (r && r.data && Array.isArray(r.data.entitlements)) {
254
- const u = H(
278
+ w(r.data);
279
+ const d = ae(
255
280
  r.data
256
281
  );
257
- s({
258
- data: u,
282
+ h({
283
+ data: d,
259
284
  isLoading: !1,
260
285
  error: null
261
286
  });
262
287
  } else {
263
- const u = new Error(
288
+ const d = new Error(
264
289
  "Received empty, malformed, or invalid data structure from entitlements API."
265
290
  );
266
- throw s({
291
+ throw h({
267
292
  data: null,
268
293
  isLoading: !1,
269
- error: u
270
- }), A(
271
- u.message,
294
+ error: d
295
+ }), E(
296
+ d.message,
272
297
  "fetchAllEntitlements",
273
298
  r
274
- ), u;
299
+ ), d;
275
300
  }
276
301
  }).catch((r) => {
277
- const u = r instanceof Error ? r : new Error(String(r));
278
- return s((P) => ({
279
- ...P,
302
+ const d = r instanceof Error ? r : new Error(String(r));
303
+ return h((q) => ({
304
+ ...q,
280
305
  isLoading: !1,
281
- error: u
282
- })), A(u.message, "fetchAllEntitlements", r), Promise.reject(u);
306
+ error: d
307
+ })), E(d.message, "fetchAllEntitlements", r), Promise.reject(d);
283
308
  }).finally(() => {
284
- L(!1);
309
+ K(!1);
285
310
  });
286
311
  }, [
312
+ s,
313
+ t,
314
+ i,
315
+ f,
316
+ l,
317
+ p,
287
318
  m,
288
- n,
319
+ E
320
+ ]), j = y(() => {
321
+ if (!s) {
322
+ const e = "API URL not configured. Cannot fetch subscriptions.";
323
+ return A({
324
+ data: null,
325
+ isLoading: !1,
326
+ error: new Error(e)
327
+ }), E(e, "fetchSubscriptions"), Promise.reject(new Error(e));
328
+ }
329
+ if (!t) {
330
+ const e = "CustomerId must be provided as props to KelviqProvider.";
331
+ return A({
332
+ data: null,
333
+ isLoading: !1,
334
+ error: new Error(e)
335
+ }), E(e, "fetchSubscriptions"), Promise.reject(new Error(e));
336
+ }
337
+ A((e) => ({
338
+ ...e,
339
+ isLoading: !0,
340
+ error: null
341
+ }));
342
+ const c = `${s.replace(/\/$/, "")}/subscriptions/`;
343
+ return O({
344
+ url: c,
345
+ method: "GET",
346
+ timeout: f,
347
+ maxRetries: l,
348
+ backoffBaseDelay: p,
349
+ accessToken: m,
350
+ queryParams: { customer_id: t }
351
+ }).then((e) => {
352
+ if (e && e.data && Array.isArray(e.data.results))
353
+ A({
354
+ data: e.data.results,
355
+ isLoading: !1,
356
+ error: null
357
+ });
358
+ else {
359
+ const r = new Error(
360
+ "Received empty, malformed, or invalid data structure from subscriptions API."
361
+ );
362
+ throw A({
363
+ data: null,
364
+ isLoading: !1,
365
+ error: r
366
+ }), E(
367
+ r.message,
368
+ "fetchSubscriptions",
369
+ e
370
+ ), r;
371
+ }
372
+ }).catch((e) => {
373
+ const r = e instanceof Error ? e : new Error(String(e));
374
+ return A((d) => ({
375
+ ...d,
376
+ isLoading: !1,
377
+ error: r
378
+ })), E(
379
+ r.message,
380
+ "fetchSubscriptions",
381
+ e
382
+ ), Promise.reject(r);
383
+ });
384
+ }, [
385
+ s,
386
+ t,
387
+ f,
388
+ l,
389
+ p,
390
+ m,
391
+ E
392
+ ]), F = y(() => {
393
+ if (!s) {
394
+ const e = "API URL not configured. Cannot fetch customer.";
395
+ return $({
396
+ data: null,
397
+ isLoading: !1,
398
+ error: new Error(e)
399
+ }), E(e, "fetchCustomer"), Promise.reject(new Error(e));
400
+ }
401
+ if (!t) {
402
+ const e = "CustomerId must be provided as props to KelviqProvider.";
403
+ return $({
404
+ data: null,
405
+ isLoading: !1,
406
+ error: new Error(e)
407
+ }), E(e, "fetchCustomer"), Promise.reject(new Error(e));
408
+ }
409
+ $((e) => ({
410
+ ...e,
411
+ isLoading: !0,
412
+ error: null
413
+ }));
414
+ const c = `${s.replace(/\/$/, "")}/customers/${t}/`;
415
+ return O({
416
+ url: c,
417
+ method: "GET",
418
+ timeout: f,
419
+ maxRetries: l,
420
+ backoffBaseDelay: p,
421
+ accessToken: m
422
+ }).then((e) => {
423
+ if (e && e.data)
424
+ $({
425
+ data: e.data,
426
+ isLoading: !1,
427
+ error: null
428
+ });
429
+ else {
430
+ const r = new Error(
431
+ "Received empty or invalid data from customer API."
432
+ );
433
+ throw $({
434
+ data: null,
435
+ isLoading: !1,
436
+ error: r
437
+ }), E(
438
+ r.message,
439
+ "fetchCustomer",
440
+ e
441
+ ), r;
442
+ }
443
+ }).catch((e) => {
444
+ const r = e instanceof Error ? e : new Error(String(e));
445
+ return $((d) => ({
446
+ ...d,
447
+ isLoading: !1,
448
+ error: r
449
+ })), E(r.message, "fetchCustomer", e), Promise.reject(r);
450
+ });
451
+ }, [
452
+ s,
289
453
  t,
290
454
  f,
291
- w,
292
- c,
293
- o,
294
- A
455
+ l,
456
+ p,
457
+ m,
458
+ E
295
459
  ]);
296
- _(() => {
297
- let g = !0;
298
- if (!m) {
299
- if (g) {
300
- const d = new Error(
460
+ Q(() => {
461
+ let c = !0;
462
+ if (!s) {
463
+ if (c) {
464
+ const e = new Error(
301
465
  "KelviqProvider: `apiBaseUrl` must be provided in config."
302
466
  );
303
- E(d), L(!1), s((r) => ({
467
+ x(e), K(!1), h((r) => ({
304
468
  ...r,
305
469
  isLoading: !1,
306
- error: d
307
- })), y.onError && y.onError(d);
470
+ error: e
471
+ })), L.onError && L.onError(e);
308
472
  }
309
473
  return;
310
474
  }
311
- return T ? S().catch((d) => {
312
- g && h && L(!1), console.error(
475
+ return U ? _().catch((e) => {
476
+ c && D && K(!1), console.error(
313
477
  "Kelviq SDK: Initial entitlement fetch failed.",
314
- d
478
+ e
315
479
  );
316
- }) : g && (s((d) => ({
317
- ...d,
480
+ }) : c && (h((e) => ({
481
+ ...e,
318
482
  isLoading: !1,
319
483
  data: null,
320
484
  error: null
321
- })), L(!1)), () => {
322
- g = !1;
485
+ })), K(!1)), b && j().catch((e) => {
486
+ console.error(
487
+ "Kelviq SDK: Initial subscriptions fetch failed.",
488
+ e
489
+ );
490
+ }), C && F().catch((e) => {
491
+ console.error(
492
+ "Kelviq SDK: Initial customer fetch failed.",
493
+ e
494
+ );
495
+ }), () => {
496
+ c = !1;
323
497
  };
324
- }, [m, T, y.onError]);
325
- const $ = R(
326
- (g, d) => {
327
- if (a.isLoading)
328
- return { data: null, isLoading: !0, error: null };
329
- if (a.error && !a.data)
330
- return {
331
- data: null,
332
- isLoading: !1,
333
- error: a.error
498
+ }, [s, U, b, C, L.onError]);
499
+ const N = y(
500
+ () => u.data ? u.data : {},
501
+ [u.data]
502
+ ), G = y(
503
+ () => a ? {
504
+ customerId: a.customerId,
505
+ entitlements: a.entitlements
506
+ } : null,
507
+ [a]
508
+ ), H = y(
509
+ (c) => a ? {
510
+ customerId: a.customerId,
511
+ entitlements: a.entitlements.filter(
512
+ (e) => e.featureId === c
513
+ )
514
+ } : null,
515
+ [a]
516
+ ), W = y(
517
+ (c) => u.data ? u.data[c] ?? null : null,
518
+ [u.data]
519
+ ), X = y(
520
+ (c, e) => {
521
+ h((r) => {
522
+ if (!r.data) return r;
523
+ const d = r.data[c];
524
+ if (!d) return r;
525
+ const q = { ...d, ...e };
526
+ return ("usageLimit" in e || "currentUsage" in e) && (q.remaining = q.usageLimit !== null ? q.usageLimit - q.currentUsage : null), {
527
+ ...r,
528
+ data: {
529
+ ...r.data,
530
+ [c]: q
531
+ }
334
532
  };
335
- if (a.data) {
336
- const u = a.data[g];
337
- return u ? u.type === d ? {
338
- data: u,
339
- isLoading: !1,
340
- error: null
341
- } : {
342
- data: null,
343
- isLoading: !1,
344
- error: new Error(
345
- `Entitlement type mismatch for ${g}. Expected ${d}, got ${u.type}`
346
- )
347
- } : { data: null, isLoading: !1, error: null };
348
- }
349
- const r = m ? `Entitlements not yet fetched for ${g}. Call refreshAllEntitlements or ensure fetchEntitlementsOnMount is true.` : "API URL not configured. Check KelviqProvider configuration.";
350
- return {
351
- data: null,
352
- isLoading: !1,
353
- error: new Error(r)
354
- };
533
+ });
355
534
  },
356
- [a, m]
357
- ), D = R(
358
- (g) => {
359
- if (a.isLoading && !a.data || a.error && !a.data || !a.data) return;
360
- const d = a.data[g];
361
- return d ? d.hasAccess : !1;
535
+ []
536
+ ), z = y(
537
+ (c) => {
538
+ if (!u.data) return !1;
539
+ const e = u.data[c];
540
+ return e ? e.hasAccess : !1;
362
541
  },
363
- [a]
364
- ), x = F(
542
+ [u.data]
543
+ ), Y = ee(
365
544
  () => ({
366
- allEntitlements: a,
367
- refreshAllEntitlements: S,
368
- getEntitlement: $,
369
- hasAccess: D,
370
- isLoading: h,
371
- error: l,
372
- environment: v,
373
- apiUrl: m,
374
- entitlementsPath: t,
375
- customerId: n
545
+ allEntitlements: u,
546
+ refreshAllEntitlements: _,
547
+ getEntitlements: N,
548
+ getEntitlement: W,
549
+ getRawEntitlements: G,
550
+ getRawEntitlement: H,
551
+ hasAccess: z,
552
+ updateEntitlement: X,
553
+ subscriptions: P,
554
+ refreshSubscriptions: j,
555
+ customer: I,
556
+ refreshCustomer: F,
557
+ isLoading: D,
558
+ error: k,
559
+ environment: g,
560
+ apiUrl: s,
561
+ entitlementsPath: i,
562
+ customerId: t
376
563
  }),
377
564
  [
378
- a,
379
- S,
380
- $,
565
+ u,
566
+ _,
567
+ N,
568
+ W,
569
+ G,
570
+ H,
571
+ z,
572
+ X,
573
+ P,
574
+ j,
575
+ I,
576
+ F,
381
577
  D,
382
- h,
383
- l,
384
- v,
385
- m,
386
- t,
387
- n
578
+ k,
579
+ g,
580
+ s,
581
+ i,
582
+ t
388
583
  ]
389
584
  );
390
- return /* @__PURE__ */ q(M.Provider, { value: x, children: e });
391
- }, K = () => {
392
- const e = O(M);
393
- if (e === void 0 || e === I)
585
+ return /* @__PURE__ */ S(V.Provider, { value: Y, children: n });
586
+ }, R = () => {
587
+ const n = te(V);
588
+ if (n === void 0 || n === J)
394
589
  throw new Error(
395
590
  "useKelviq must be used within an initialized KelviqProvider."
396
591
  );
397
- return e;
398
- }, k = ({
399
- featureKey: e,
400
- type: i,
401
- children: t,
402
- fallback: n = null,
403
- loadingComponent: v,
404
- condition: o
592
+ return n;
593
+ }, B = ({
594
+ featureId: n,
595
+ children: o,
596
+ fallback: i = null,
597
+ loadingComponent: t,
598
+ condition: g
405
599
  }) => {
406
600
  const {
407
- getEntitlement: y,
408
- isLoading: p,
409
- error: w,
410
- allEntitlements: f
411
- } = K(), c = y(e, i);
412
- return c.isLoading || p && !c.data && !c.error && !f.data && !f.error ? /* @__PURE__ */ q(b, { children: v !== void 0 ? v : n }) : c.error || w && !c.data ? /* @__PURE__ */ q(b, { children: n }) : !c.data || !c.data.hasAccess || o && !o(c.data) ? /* @__PURE__ */ q(b, { children: n }) : typeof t == "function" ? /* @__PURE__ */ q(b, { children: t(c.data) }) : /* @__PURE__ */ q(b, { children: t });
413
- }, ee = ({ children: e, ...i }) => /* @__PURE__ */ q(
414
- k,
415
- {
416
- ...i,
417
- type: "customizable",
418
- children: (t) => t.hasAccess && t.configuration !== null && typeof t.configuration == "number" ? e(t.configuration) : /* @__PURE__ */ q(b, { children: i.fallback || null })
419
- }
420
- ), te = (e) => {
421
- const i = (t) => t.hasAccess && (t.remaining === null || t.remaining > 0);
422
- return /* @__PURE__ */ q(
423
- k,
601
+ getEntitlement: m,
602
+ isLoading: L,
603
+ error: v
604
+ } = R(), l = m(n);
605
+ return L && !l ? /* @__PURE__ */ S(M, { children: t !== void 0 ? t : i }) : v && !l ? /* @__PURE__ */ S(M, { children: i }) : !l || !l.hasAccess || g && !g(l) ? /* @__PURE__ */ S(M, { children: i }) : typeof o == "function" ? /* @__PURE__ */ S(M, { children: o(l) }) : /* @__PURE__ */ S(M, { children: o });
606
+ }, Ee = (n) => /* @__PURE__ */ S(B, { ...n }), ge = (n) => {
607
+ const o = (i) => i.hasAccess && (i.remaining === null || i.remaining > 0);
608
+ return /* @__PURE__ */ S(
609
+ B,
424
610
  {
425
- ...e,
426
- type: "metered",
427
- condition: e.condition || i
611
+ ...n,
612
+ condition: n.condition || o
428
613
  }
429
614
  );
430
- }, re = (e) => /* @__PURE__ */ q(
431
- k,
432
- {
433
- ...e,
434
- type: "boolean"
435
- }
436
- ), ne = () => {
437
- const { allEntitlements: e } = K();
438
- return e;
439
- }, oe = (e) => {
440
- const { getEntitlement: i } = K();
441
- return i(e, "boolean");
442
- }, ie = (e) => {
443
- const { getEntitlement: i } = K();
444
- return i(e, "customizable");
445
- }, se = (e) => {
446
- const { getEntitlement: i } = K();
447
- return i(e, "metered");
615
+ }, pe = (n) => /* @__PURE__ */ S(B, { ...n }), he = () => {
616
+ const { allEntitlements: n } = R();
617
+ return n;
618
+ }, Le = (n) => {
619
+ const { getEntitlement: o } = R();
620
+ return o(n);
621
+ }, ve = (n) => {
622
+ const { getEntitlement: o } = R();
623
+ return o(n);
624
+ }, we = (n) => {
625
+ const { getEntitlement: o } = R();
626
+ return o(n);
627
+ }, Ae = () => {
628
+ const { subscriptions: n } = R();
629
+ return n;
630
+ }, ye = () => {
631
+ const { customer: n } = R();
632
+ return n;
448
633
  };
449
634
  export {
450
- M as KelviqContext,
451
- Q as KelviqProvider,
452
- re as ShowWhenBooleanEntitled,
453
- ee as ShowWhenConfigEntitled,
454
- te as ShowWhenMeteredEntitled,
455
- I as defaultKelviqContextValue,
456
- ne as useAllEntitlements,
457
- oe as useBooleanEntitlement,
458
- ie as useConfigEntitlement,
459
- K as useKelviq,
460
- se as useMeteredEntitlement
635
+ V as KelviqContext,
636
+ me as KelviqProvider,
637
+ pe as ShowWhenBooleanEntitled,
638
+ Ee as ShowWhenCustomizableEntitled,
639
+ ge as ShowWhenMeteredEntitled,
640
+ J as defaultKelviqContextValue,
641
+ he as useAllEntitlements,
642
+ Le as useBooleanEntitlement,
643
+ ye as useCustomer,
644
+ ve as useCustomizableEntitlement,
645
+ R as useKelviq,
646
+ we as useMeteredEntitlement,
647
+ Ae as useSubscriptions
461
648
  };