@eetech-commerce/cart-react 0.4.1

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.
package/dist/index.js ADDED
@@ -0,0 +1,1692 @@
1
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
2
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
3
+ }) : x)(function(x) {
4
+ if (typeof require !== "undefined") return require.apply(this, arguments);
5
+ throw Error('Dynamic require of "' + x + '" is not supported');
6
+ });
7
+
8
+ // src/adapters/localStorage.ts
9
+ var localStorageAdapter = {
10
+ get(key) {
11
+ if (typeof window === "undefined") return null;
12
+ return localStorage.getItem(key);
13
+ },
14
+ set(key, value) {
15
+ if (typeof window === "undefined") return;
16
+ localStorage.setItem(key, value);
17
+ },
18
+ remove(key) {
19
+ if (typeof window === "undefined") return;
20
+ localStorage.removeItem(key);
21
+ }
22
+ };
23
+
24
+ // src/context.ts
25
+ import { createContext, useContext } from "react";
26
+ var CartContext = createContext(null);
27
+ function useCartContext() {
28
+ const context = useContext(CartContext);
29
+ if (!context) {
30
+ throw new Error("useCartContext must be used within a CartProvider");
31
+ }
32
+ return context;
33
+ }
34
+
35
+ // src/hooks/cart.ts
36
+ import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
37
+ import { useCallback, useEffect, useRef } from "react";
38
+
39
+ // src/generated/@tanstack/react-query.gen.ts
40
+ import { queryOptions } from "@tanstack/react-query";
41
+
42
+ // src/generated/core/bodySerializer.gen.ts
43
+ var jsonBodySerializer = {
44
+ bodySerializer: (body) => JSON.stringify(body, (_key, value) => typeof value === "bigint" ? value.toString() : value)
45
+ };
46
+
47
+ // src/generated/core/params.gen.ts
48
+ var extraPrefixesMap = {
49
+ $body_: "body",
50
+ $headers_: "headers",
51
+ $path_: "path",
52
+ $query_: "query"
53
+ };
54
+ var extraPrefixes = Object.entries(extraPrefixesMap);
55
+
56
+ // src/generated/core/serverSentEvents.gen.ts
57
+ var createSseClient = ({
58
+ onRequest,
59
+ onSseError,
60
+ onSseEvent,
61
+ responseTransformer,
62
+ responseValidator,
63
+ sseDefaultRetryDelay,
64
+ sseMaxRetryAttempts,
65
+ sseMaxRetryDelay,
66
+ sseSleepFn,
67
+ url,
68
+ ...options
69
+ }) => {
70
+ let lastEventId;
71
+ const sleep = sseSleepFn ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
72
+ const createStream = async function* () {
73
+ let retryDelay = sseDefaultRetryDelay ?? 3e3;
74
+ let attempt = 0;
75
+ const signal = options.signal ?? new AbortController().signal;
76
+ while (true) {
77
+ if (signal.aborted) break;
78
+ attempt++;
79
+ const headers = options.headers instanceof Headers ? options.headers : new Headers(options.headers);
80
+ if (lastEventId !== void 0) {
81
+ headers.set("Last-Event-ID", lastEventId);
82
+ }
83
+ try {
84
+ const requestInit = {
85
+ redirect: "follow",
86
+ ...options,
87
+ body: options.serializedBody,
88
+ headers,
89
+ signal
90
+ };
91
+ let request = new Request(url, requestInit);
92
+ if (onRequest) {
93
+ request = await onRequest(url, requestInit);
94
+ }
95
+ const _fetch = options.fetch ?? globalThis.fetch;
96
+ const response = await _fetch(request);
97
+ if (!response.ok) throw new Error(`SSE failed: ${response.status} ${response.statusText}`);
98
+ if (!response.body) throw new Error("No body in SSE response");
99
+ const reader = response.body.pipeThrough(new TextDecoderStream()).getReader();
100
+ let buffer = "";
101
+ const abortHandler = () => {
102
+ try {
103
+ reader.cancel();
104
+ } catch {
105
+ }
106
+ };
107
+ signal.addEventListener("abort", abortHandler);
108
+ try {
109
+ while (true) {
110
+ const { done, value } = await reader.read();
111
+ if (done) break;
112
+ buffer += value;
113
+ const chunks = buffer.split("\n\n");
114
+ buffer = chunks.pop() ?? "";
115
+ for (const chunk of chunks) {
116
+ const lines = chunk.split("\n");
117
+ const dataLines = [];
118
+ let eventName;
119
+ for (const line of lines) {
120
+ if (line.startsWith("data:")) {
121
+ dataLines.push(line.replace(/^data:\s*/, ""));
122
+ } else if (line.startsWith("event:")) {
123
+ eventName = line.replace(/^event:\s*/, "");
124
+ } else if (line.startsWith("id:")) {
125
+ lastEventId = line.replace(/^id:\s*/, "");
126
+ } else if (line.startsWith("retry:")) {
127
+ const parsed = Number.parseInt(line.replace(/^retry:\s*/, ""), 10);
128
+ if (!Number.isNaN(parsed)) {
129
+ retryDelay = parsed;
130
+ }
131
+ }
132
+ }
133
+ let data;
134
+ let parsedJson = false;
135
+ if (dataLines.length) {
136
+ const rawData = dataLines.join("\n");
137
+ try {
138
+ data = JSON.parse(rawData);
139
+ parsedJson = true;
140
+ } catch {
141
+ data = rawData;
142
+ }
143
+ }
144
+ if (parsedJson) {
145
+ if (responseValidator) {
146
+ await responseValidator(data);
147
+ }
148
+ if (responseTransformer) {
149
+ data = await responseTransformer(data);
150
+ }
151
+ }
152
+ onSseEvent?.({
153
+ data,
154
+ event: eventName,
155
+ id: lastEventId,
156
+ retry: retryDelay
157
+ });
158
+ if (dataLines.length) {
159
+ yield data;
160
+ }
161
+ }
162
+ }
163
+ } finally {
164
+ signal.removeEventListener("abort", abortHandler);
165
+ reader.releaseLock();
166
+ }
167
+ break;
168
+ } catch (error) {
169
+ onSseError?.(error);
170
+ if (sseMaxRetryAttempts !== void 0 && attempt >= sseMaxRetryAttempts) {
171
+ break;
172
+ }
173
+ const backoff = Math.min(retryDelay * 2 ** (attempt - 1), sseMaxRetryDelay ?? 3e4);
174
+ await sleep(backoff);
175
+ }
176
+ }
177
+ };
178
+ const stream = createStream();
179
+ return { stream };
180
+ };
181
+
182
+ // src/generated/core/pathSerializer.gen.ts
183
+ var separatorArrayExplode = (style) => {
184
+ switch (style) {
185
+ case "label":
186
+ return ".";
187
+ case "matrix":
188
+ return ";";
189
+ case "simple":
190
+ return ",";
191
+ default:
192
+ return "&";
193
+ }
194
+ };
195
+ var separatorArrayNoExplode = (style) => {
196
+ switch (style) {
197
+ case "form":
198
+ return ",";
199
+ case "pipeDelimited":
200
+ return "|";
201
+ case "spaceDelimited":
202
+ return "%20";
203
+ default:
204
+ return ",";
205
+ }
206
+ };
207
+ var separatorObjectExplode = (style) => {
208
+ switch (style) {
209
+ case "label":
210
+ return ".";
211
+ case "matrix":
212
+ return ";";
213
+ case "simple":
214
+ return ",";
215
+ default:
216
+ return "&";
217
+ }
218
+ };
219
+ var serializeArrayParam = ({
220
+ allowReserved,
221
+ explode,
222
+ name,
223
+ style,
224
+ value
225
+ }) => {
226
+ if (!explode) {
227
+ const joinedValues2 = (allowReserved ? value : value.map((v) => encodeURIComponent(v))).join(separatorArrayNoExplode(style));
228
+ switch (style) {
229
+ case "label":
230
+ return `.${joinedValues2}`;
231
+ case "matrix":
232
+ return `;${name}=${joinedValues2}`;
233
+ case "simple":
234
+ return joinedValues2;
235
+ default:
236
+ return `${name}=${joinedValues2}`;
237
+ }
238
+ }
239
+ const separator = separatorArrayExplode(style);
240
+ const joinedValues = value.map((v) => {
241
+ if (style === "label" || style === "simple") {
242
+ return allowReserved ? v : encodeURIComponent(v);
243
+ }
244
+ return serializePrimitiveParam({
245
+ allowReserved,
246
+ name,
247
+ value: v
248
+ });
249
+ }).join(separator);
250
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
251
+ };
252
+ var serializePrimitiveParam = ({
253
+ allowReserved,
254
+ name,
255
+ value
256
+ }) => {
257
+ if (value === void 0 || value === null) {
258
+ return "";
259
+ }
260
+ if (typeof value === "object") {
261
+ throw new Error(
262
+ "Deeply-nested arrays/objects aren\u2019t supported. Provide your own `querySerializer()` to handle these."
263
+ );
264
+ }
265
+ return `${name}=${allowReserved ? value : encodeURIComponent(value)}`;
266
+ };
267
+ var serializeObjectParam = ({
268
+ allowReserved,
269
+ explode,
270
+ name,
271
+ style,
272
+ value,
273
+ valueOnly
274
+ }) => {
275
+ if (value instanceof Date) {
276
+ return valueOnly ? value.toISOString() : `${name}=${value.toISOString()}`;
277
+ }
278
+ if (style !== "deepObject" && !explode) {
279
+ let values = [];
280
+ Object.entries(value).forEach(([key, v]) => {
281
+ values = [...values, key, allowReserved ? v : encodeURIComponent(v)];
282
+ });
283
+ const joinedValues2 = values.join(",");
284
+ switch (style) {
285
+ case "form":
286
+ return `${name}=${joinedValues2}`;
287
+ case "label":
288
+ return `.${joinedValues2}`;
289
+ case "matrix":
290
+ return `;${name}=${joinedValues2}`;
291
+ default:
292
+ return joinedValues2;
293
+ }
294
+ }
295
+ const separator = separatorObjectExplode(style);
296
+ const joinedValues = Object.entries(value).map(
297
+ ([key, v]) => serializePrimitiveParam({
298
+ allowReserved,
299
+ name: style === "deepObject" ? `${name}[${key}]` : key,
300
+ value: v
301
+ })
302
+ ).join(separator);
303
+ return style === "label" || style === "matrix" ? separator + joinedValues : joinedValues;
304
+ };
305
+
306
+ // src/generated/core/utils.gen.ts
307
+ var PATH_PARAM_RE = /\{[^{}]+\}/g;
308
+ var defaultPathSerializer = ({ path, url: _url }) => {
309
+ let url = _url;
310
+ const matches = _url.match(PATH_PARAM_RE);
311
+ if (matches) {
312
+ for (const match of matches) {
313
+ let explode = false;
314
+ let name = match.substring(1, match.length - 1);
315
+ let style = "simple";
316
+ if (name.endsWith("*")) {
317
+ explode = true;
318
+ name = name.substring(0, name.length - 1);
319
+ }
320
+ if (name.startsWith(".")) {
321
+ name = name.substring(1);
322
+ style = "label";
323
+ } else if (name.startsWith(";")) {
324
+ name = name.substring(1);
325
+ style = "matrix";
326
+ }
327
+ const value = path[name];
328
+ if (value === void 0 || value === null) {
329
+ continue;
330
+ }
331
+ if (Array.isArray(value)) {
332
+ url = url.replace(match, serializeArrayParam({ explode, name, style, value }));
333
+ continue;
334
+ }
335
+ if (typeof value === "object") {
336
+ url = url.replace(
337
+ match,
338
+ serializeObjectParam({
339
+ explode,
340
+ name,
341
+ style,
342
+ value,
343
+ valueOnly: true
344
+ })
345
+ );
346
+ continue;
347
+ }
348
+ if (style === "matrix") {
349
+ url = url.replace(
350
+ match,
351
+ `;${serializePrimitiveParam({
352
+ name,
353
+ value
354
+ })}`
355
+ );
356
+ continue;
357
+ }
358
+ const replaceValue = encodeURIComponent(
359
+ style === "label" ? `.${value}` : value
360
+ );
361
+ url = url.replace(match, replaceValue);
362
+ }
363
+ }
364
+ return url;
365
+ };
366
+ var getUrl = ({
367
+ baseUrl,
368
+ path,
369
+ query,
370
+ querySerializer,
371
+ url: _url
372
+ }) => {
373
+ const pathUrl = _url.startsWith("/") ? _url : `/${_url}`;
374
+ let url = (baseUrl ?? "") + pathUrl;
375
+ if (path) {
376
+ url = defaultPathSerializer({ path, url });
377
+ }
378
+ let search = query ? querySerializer(query) : "";
379
+ if (search.startsWith("?")) {
380
+ search = search.substring(1);
381
+ }
382
+ if (search) {
383
+ url += `?${search}`;
384
+ }
385
+ return url;
386
+ };
387
+ function getValidRequestBody(options) {
388
+ const hasBody = options.body !== void 0;
389
+ const isSerializedBody = hasBody && options.bodySerializer;
390
+ if (isSerializedBody) {
391
+ if ("serializedBody" in options) {
392
+ const hasSerializedBody = options.serializedBody !== void 0 && options.serializedBody !== "";
393
+ return hasSerializedBody ? options.serializedBody : null;
394
+ }
395
+ return options.body !== "" ? options.body : null;
396
+ }
397
+ if (hasBody) {
398
+ return options.body;
399
+ }
400
+ return void 0;
401
+ }
402
+
403
+ // src/generated/core/auth.gen.ts
404
+ var getAuthToken = async (auth, callback) => {
405
+ const token = typeof callback === "function" ? await callback(auth) : callback;
406
+ if (!token) {
407
+ return;
408
+ }
409
+ if (auth.scheme === "bearer") {
410
+ return `Bearer ${token}`;
411
+ }
412
+ if (auth.scheme === "basic") {
413
+ return `Basic ${btoa(token)}`;
414
+ }
415
+ return token;
416
+ };
417
+
418
+ // src/generated/client/utils.gen.ts
419
+ var createQuerySerializer = ({
420
+ parameters = {},
421
+ ...args
422
+ } = {}) => {
423
+ const querySerializer = (queryParams) => {
424
+ const search = [];
425
+ if (queryParams && typeof queryParams === "object") {
426
+ for (const name in queryParams) {
427
+ const value = queryParams[name];
428
+ if (value === void 0 || value === null) {
429
+ continue;
430
+ }
431
+ const options = parameters[name] || args;
432
+ if (Array.isArray(value)) {
433
+ const serializedArray = serializeArrayParam({
434
+ allowReserved: options.allowReserved,
435
+ explode: true,
436
+ name,
437
+ style: "form",
438
+ value,
439
+ ...options.array
440
+ });
441
+ if (serializedArray) search.push(serializedArray);
442
+ } else if (typeof value === "object") {
443
+ const serializedObject = serializeObjectParam({
444
+ allowReserved: options.allowReserved,
445
+ explode: true,
446
+ name,
447
+ style: "deepObject",
448
+ value,
449
+ ...options.object
450
+ });
451
+ if (serializedObject) search.push(serializedObject);
452
+ } else {
453
+ const serializedPrimitive = serializePrimitiveParam({
454
+ allowReserved: options.allowReserved,
455
+ name,
456
+ value
457
+ });
458
+ if (serializedPrimitive) search.push(serializedPrimitive);
459
+ }
460
+ }
461
+ }
462
+ return search.join("&");
463
+ };
464
+ return querySerializer;
465
+ };
466
+ var getParseAs = (contentType) => {
467
+ if (!contentType) {
468
+ return "stream";
469
+ }
470
+ const cleanContent = contentType.split(";")[0]?.trim();
471
+ if (!cleanContent) {
472
+ return;
473
+ }
474
+ if (cleanContent.startsWith("application/json") || cleanContent.endsWith("+json")) {
475
+ return "json";
476
+ }
477
+ if (cleanContent === "multipart/form-data") {
478
+ return "formData";
479
+ }
480
+ if (["application/", "audio/", "image/", "video/"].some((type) => cleanContent.startsWith(type))) {
481
+ return "blob";
482
+ }
483
+ if (cleanContent.startsWith("text/")) {
484
+ return "text";
485
+ }
486
+ return;
487
+ };
488
+ var checkForExistence = (options, name) => {
489
+ if (!name) {
490
+ return false;
491
+ }
492
+ if (options.headers.has(name) || options.query?.[name] || options.headers.get("Cookie")?.includes(`${name}=`)) {
493
+ return true;
494
+ }
495
+ return false;
496
+ };
497
+ var setAuthParams = async ({
498
+ security,
499
+ ...options
500
+ }) => {
501
+ for (const auth of security) {
502
+ if (checkForExistence(options, auth.name)) {
503
+ continue;
504
+ }
505
+ const token = await getAuthToken(auth, options.auth);
506
+ if (!token) {
507
+ continue;
508
+ }
509
+ const name = auth.name ?? "Authorization";
510
+ switch (auth.in) {
511
+ case "query":
512
+ if (!options.query) {
513
+ options.query = {};
514
+ }
515
+ options.query[name] = token;
516
+ break;
517
+ case "cookie":
518
+ options.headers.append("Cookie", `${name}=${token}`);
519
+ break;
520
+ case "header":
521
+ default:
522
+ options.headers.set(name, token);
523
+ break;
524
+ }
525
+ }
526
+ };
527
+ var buildUrl = (options) => getUrl({
528
+ baseUrl: options.baseUrl,
529
+ path: options.path,
530
+ query: options.query,
531
+ querySerializer: typeof options.querySerializer === "function" ? options.querySerializer : createQuerySerializer(options.querySerializer),
532
+ url: options.url
533
+ });
534
+ var mergeConfigs = (a, b) => {
535
+ const config = { ...a, ...b };
536
+ if (config.baseUrl?.endsWith("/")) {
537
+ config.baseUrl = config.baseUrl.substring(0, config.baseUrl.length - 1);
538
+ }
539
+ config.headers = mergeHeaders(a.headers, b.headers);
540
+ return config;
541
+ };
542
+ var headersEntries = (headers) => {
543
+ const entries = [];
544
+ headers.forEach((value, key) => {
545
+ entries.push([key, value]);
546
+ });
547
+ return entries;
548
+ };
549
+ var mergeHeaders = (...headers) => {
550
+ const mergedHeaders = new Headers();
551
+ for (const header of headers) {
552
+ if (!header) {
553
+ continue;
554
+ }
555
+ const iterator = header instanceof Headers ? headersEntries(header) : Object.entries(header);
556
+ for (const [key, value] of iterator) {
557
+ if (value === null) {
558
+ mergedHeaders.delete(key);
559
+ } else if (Array.isArray(value)) {
560
+ for (const v of value) {
561
+ mergedHeaders.append(key, v);
562
+ }
563
+ } else if (value !== void 0) {
564
+ mergedHeaders.set(
565
+ key,
566
+ typeof value === "object" ? JSON.stringify(value) : value
567
+ );
568
+ }
569
+ }
570
+ }
571
+ return mergedHeaders;
572
+ };
573
+ var Interceptors = class {
574
+ constructor() {
575
+ this.fns = [];
576
+ }
577
+ clear() {
578
+ this.fns = [];
579
+ }
580
+ eject(id) {
581
+ const index = this.getInterceptorIndex(id);
582
+ if (this.fns[index]) {
583
+ this.fns[index] = null;
584
+ }
585
+ }
586
+ exists(id) {
587
+ const index = this.getInterceptorIndex(id);
588
+ return Boolean(this.fns[index]);
589
+ }
590
+ getInterceptorIndex(id) {
591
+ if (typeof id === "number") {
592
+ return this.fns[id] ? id : -1;
593
+ }
594
+ return this.fns.indexOf(id);
595
+ }
596
+ update(id, fn) {
597
+ const index = this.getInterceptorIndex(id);
598
+ if (this.fns[index]) {
599
+ this.fns[index] = fn;
600
+ return id;
601
+ }
602
+ return false;
603
+ }
604
+ use(fn) {
605
+ this.fns.push(fn);
606
+ return this.fns.length - 1;
607
+ }
608
+ };
609
+ var createInterceptors = () => ({
610
+ error: new Interceptors(),
611
+ request: new Interceptors(),
612
+ response: new Interceptors()
613
+ });
614
+ var defaultQuerySerializer = createQuerySerializer({
615
+ allowReserved: false,
616
+ array: {
617
+ explode: true,
618
+ style: "form"
619
+ },
620
+ object: {
621
+ explode: true,
622
+ style: "deepObject"
623
+ }
624
+ });
625
+ var defaultHeaders = {
626
+ "Content-Type": "application/json"
627
+ };
628
+ var createConfig = (override = {}) => ({
629
+ ...jsonBodySerializer,
630
+ headers: defaultHeaders,
631
+ parseAs: "auto",
632
+ querySerializer: defaultQuerySerializer,
633
+ ...override
634
+ });
635
+
636
+ // src/generated/client/client.gen.ts
637
+ var createClient = (config = {}) => {
638
+ let _config = mergeConfigs(createConfig(), config);
639
+ const getConfig = () => ({ ..._config });
640
+ const setConfig = (config2) => {
641
+ _config = mergeConfigs(_config, config2);
642
+ return getConfig();
643
+ };
644
+ const interceptors = createInterceptors();
645
+ const beforeRequest = async (options) => {
646
+ const opts = {
647
+ ..._config,
648
+ ...options,
649
+ fetch: options.fetch ?? _config.fetch ?? globalThis.fetch,
650
+ headers: mergeHeaders(_config.headers, options.headers),
651
+ serializedBody: void 0
652
+ };
653
+ if (opts.security) {
654
+ await setAuthParams({
655
+ ...opts,
656
+ security: opts.security
657
+ });
658
+ }
659
+ if (opts.requestValidator) {
660
+ await opts.requestValidator(opts);
661
+ }
662
+ if (opts.body !== void 0 && opts.bodySerializer) {
663
+ opts.serializedBody = opts.bodySerializer(opts.body);
664
+ }
665
+ if (opts.body === void 0 || opts.serializedBody === "") {
666
+ opts.headers.delete("Content-Type");
667
+ }
668
+ const url = buildUrl(opts);
669
+ return { opts, url };
670
+ };
671
+ const request = async (options) => {
672
+ const { opts, url } = await beforeRequest(options);
673
+ const requestInit = {
674
+ redirect: "follow",
675
+ ...opts,
676
+ body: getValidRequestBody(opts)
677
+ };
678
+ let request2 = new Request(url, requestInit);
679
+ for (const fn of interceptors.request.fns) {
680
+ if (fn) {
681
+ request2 = await fn(request2, opts);
682
+ }
683
+ }
684
+ const _fetch = opts.fetch;
685
+ let response;
686
+ try {
687
+ response = await _fetch(request2);
688
+ } catch (error2) {
689
+ let finalError2 = error2;
690
+ for (const fn of interceptors.error.fns) {
691
+ if (fn) {
692
+ finalError2 = await fn(error2, void 0, request2, opts);
693
+ }
694
+ }
695
+ finalError2 = finalError2 || {};
696
+ if (opts.throwOnError) {
697
+ throw finalError2;
698
+ }
699
+ return opts.responseStyle === "data" ? void 0 : {
700
+ error: finalError2,
701
+ request: request2,
702
+ response: void 0
703
+ };
704
+ }
705
+ for (const fn of interceptors.response.fns) {
706
+ if (fn) {
707
+ response = await fn(response, request2, opts);
708
+ }
709
+ }
710
+ const result = {
711
+ request: request2,
712
+ response
713
+ };
714
+ if (response.ok) {
715
+ const parseAs = (opts.parseAs === "auto" ? getParseAs(response.headers.get("Content-Type")) : opts.parseAs) ?? "json";
716
+ if (response.status === 204 || response.headers.get("Content-Length") === "0") {
717
+ let emptyData;
718
+ switch (parseAs) {
719
+ case "arrayBuffer":
720
+ case "blob":
721
+ case "text":
722
+ emptyData = await response[parseAs]();
723
+ break;
724
+ case "formData":
725
+ emptyData = new FormData();
726
+ break;
727
+ case "stream":
728
+ emptyData = response.body;
729
+ break;
730
+ case "json":
731
+ default:
732
+ emptyData = {};
733
+ break;
734
+ }
735
+ return opts.responseStyle === "data" ? emptyData : {
736
+ data: emptyData,
737
+ ...result
738
+ };
739
+ }
740
+ let data;
741
+ switch (parseAs) {
742
+ case "arrayBuffer":
743
+ case "blob":
744
+ case "formData":
745
+ case "json":
746
+ case "text":
747
+ data = await response[parseAs]();
748
+ break;
749
+ case "stream":
750
+ return opts.responseStyle === "data" ? response.body : {
751
+ data: response.body,
752
+ ...result
753
+ };
754
+ }
755
+ if (parseAs === "json") {
756
+ if (opts.responseValidator) {
757
+ await opts.responseValidator(data);
758
+ }
759
+ if (opts.responseTransformer) {
760
+ data = await opts.responseTransformer(data);
761
+ }
762
+ }
763
+ return opts.responseStyle === "data" ? data : {
764
+ data,
765
+ ...result
766
+ };
767
+ }
768
+ const textError = await response.text();
769
+ let jsonError;
770
+ try {
771
+ jsonError = JSON.parse(textError);
772
+ } catch {
773
+ }
774
+ const error = jsonError ?? textError;
775
+ let finalError = error;
776
+ for (const fn of interceptors.error.fns) {
777
+ if (fn) {
778
+ finalError = await fn(error, response, request2, opts);
779
+ }
780
+ }
781
+ finalError = finalError || {};
782
+ if (opts.throwOnError) {
783
+ throw finalError;
784
+ }
785
+ return opts.responseStyle === "data" ? void 0 : {
786
+ error: finalError,
787
+ ...result
788
+ };
789
+ };
790
+ const makeMethodFn = (method) => (options) => request({ ...options, method });
791
+ const makeSseFn = (method) => async (options) => {
792
+ const { opts, url } = await beforeRequest(options);
793
+ return createSseClient({
794
+ ...opts,
795
+ body: opts.body,
796
+ headers: opts.headers,
797
+ method,
798
+ onRequest: async (url2, init) => {
799
+ let request2 = new Request(url2, init);
800
+ for (const fn of interceptors.request.fns) {
801
+ if (fn) {
802
+ request2 = await fn(request2, opts);
803
+ }
804
+ }
805
+ return request2;
806
+ },
807
+ url
808
+ });
809
+ };
810
+ return {
811
+ buildUrl,
812
+ connect: makeMethodFn("CONNECT"),
813
+ delete: makeMethodFn("DELETE"),
814
+ get: makeMethodFn("GET"),
815
+ getConfig,
816
+ head: makeMethodFn("HEAD"),
817
+ interceptors,
818
+ options: makeMethodFn("OPTIONS"),
819
+ patch: makeMethodFn("PATCH"),
820
+ post: makeMethodFn("POST"),
821
+ put: makeMethodFn("PUT"),
822
+ request,
823
+ setConfig,
824
+ sse: {
825
+ connect: makeSseFn("CONNECT"),
826
+ delete: makeSseFn("DELETE"),
827
+ get: makeSseFn("GET"),
828
+ head: makeSseFn("HEAD"),
829
+ options: makeSseFn("OPTIONS"),
830
+ patch: makeSseFn("PATCH"),
831
+ post: makeSseFn("POST"),
832
+ put: makeSseFn("PUT"),
833
+ trace: makeSseFn("TRACE")
834
+ },
835
+ trace: makeMethodFn("TRACE")
836
+ };
837
+ };
838
+
839
+ // src/generated/client.gen.ts
840
+ var client = createClient(createConfig());
841
+
842
+ // src/generated/sdk.gen.ts
843
+ var cartControllerCreateCartV1 = (options) => {
844
+ return (options.client ?? client).post({
845
+ url: "/v1/t/{tenantSlug}/carts",
846
+ ...options,
847
+ headers: {
848
+ "Content-Type": "application/json",
849
+ ...options.headers
850
+ }
851
+ });
852
+ };
853
+ var cartControllerGetCartV1 = (options) => {
854
+ return (options.client ?? client).get({
855
+ url: "/v1/t/{tenantSlug}/carts/{cartSessionId}",
856
+ ...options
857
+ });
858
+ };
859
+ var cartControllerClearCartV1 = (options) => {
860
+ return (options.client ?? client).delete({
861
+ url: "/v1/t/{tenantSlug}/carts/{cartSessionId}/items",
862
+ ...options
863
+ });
864
+ };
865
+ var cartControllerAddItemV1 = (options) => {
866
+ return (options.client ?? client).post({
867
+ url: "/v1/t/{tenantSlug}/carts/{cartSessionId}/items",
868
+ ...options,
869
+ headers: {
870
+ "Content-Type": "application/json",
871
+ ...options.headers
872
+ }
873
+ });
874
+ };
875
+ var cartControllerRemoveItemV1 = (options) => {
876
+ return (options.client ?? client).delete({
877
+ url: "/v1/t/{tenantSlug}/carts/{cartSessionId}/items/{offerId}",
878
+ ...options
879
+ });
880
+ };
881
+ var cartControllerUpdateItemV1 = (options) => {
882
+ return (options.client ?? client).patch({
883
+ url: "/v1/t/{tenantSlug}/carts/{cartSessionId}/items/{offerId}",
884
+ ...options,
885
+ headers: {
886
+ "Content-Type": "application/json",
887
+ ...options.headers
888
+ }
889
+ });
890
+ };
891
+ var checkoutControllerVerifyCartV1 = (options) => {
892
+ return (options.client ?? client).post({
893
+ url: "/v1/t/{tenantSlug}/checkout/verify",
894
+ ...options,
895
+ headers: {
896
+ "Content-Type": "application/json",
897
+ ...options.headers
898
+ }
899
+ });
900
+ };
901
+ var checkoutControllerCreateCheckoutSessionV1 = (options) => {
902
+ return (options.client ?? client).post({
903
+ url: "/v1/t/{tenantSlug}/checkout/{cartSessionId}",
904
+ ...options,
905
+ headers: {
906
+ "Content-Type": "application/json",
907
+ ...options.headers
908
+ }
909
+ });
910
+ };
911
+ var checkoutControllerGetShippingOptionsV1 = (options) => {
912
+ return (options.client ?? client).get({
913
+ url: "/v1/t/{tenantSlug}/checkout/{cartSessionId}/shipping-options",
914
+ ...options
915
+ });
916
+ };
917
+ var checkoutControllerUpdateShippingSelectionsV1 = (options) => {
918
+ return (options.client ?? client).patch({
919
+ url: "/v1/t/{tenantSlug}/checkout/{cartSessionId}/shipping-selections",
920
+ ...options,
921
+ headers: {
922
+ "Content-Type": "application/json",
923
+ ...options.headers
924
+ }
925
+ });
926
+ };
927
+ var tenantPublicControllerGetPublicKeyV1 = (options) => {
928
+ return (options.client ?? client).get({
929
+ url: "/v1/tenants/{tenantSlug}/keys/{keyType}",
930
+ ...options
931
+ });
932
+ };
933
+ var paymentControllerCreateEmbeddedPaymentSessionV1 = (options) => {
934
+ return (options.client ?? client).post({
935
+ url: "/v1/t/{tenantSlug}/payments/sessions/embedded",
936
+ ...options,
937
+ headers: {
938
+ "Content-Type": "application/json",
939
+ ...options.headers
940
+ }
941
+ });
942
+ };
943
+ var paymentControllerGetPaymentSessionV1 = (options) => {
944
+ return (options.client ?? client).get({
945
+ url: "/v1/t/{tenantSlug}/payments/sessions/{id}",
946
+ ...options
947
+ });
948
+ };
949
+
950
+ // src/generated/@tanstack/react-query.gen.ts
951
+ var createQueryKey = (id, options, infinite, tags) => {
952
+ const params = {
953
+ _id: id,
954
+ baseUrl: options?.baseUrl || (options?.client ?? client).getConfig().baseUrl
955
+ };
956
+ if (infinite) {
957
+ params._infinite = infinite;
958
+ }
959
+ if (tags) {
960
+ params.tags = tags;
961
+ }
962
+ if (options?.body) {
963
+ params.body = options.body;
964
+ }
965
+ if (options?.headers) {
966
+ params.headers = options.headers;
967
+ }
968
+ if (options?.path) {
969
+ params.path = options.path;
970
+ }
971
+ if (options?.query) {
972
+ params.query = options.query;
973
+ }
974
+ return [params];
975
+ };
976
+ var cartControllerCreateCartV1Mutation = (options) => {
977
+ const mutationOptions = {
978
+ mutationFn: async (fnOptions) => {
979
+ const { data } = await cartControllerCreateCartV1({
980
+ ...options,
981
+ ...fnOptions,
982
+ throwOnError: true
983
+ });
984
+ return data;
985
+ }
986
+ };
987
+ return mutationOptions;
988
+ };
989
+ var cartControllerGetCartV1QueryKey = (options) => createQueryKey("cartControllerGetCartV1", options);
990
+ var cartControllerGetCartV1Options = (options) => queryOptions({
991
+ queryFn: async ({ queryKey, signal }) => {
992
+ const { data } = await cartControllerGetCartV1({
993
+ ...options,
994
+ ...queryKey[0],
995
+ signal,
996
+ throwOnError: true
997
+ });
998
+ return data;
999
+ },
1000
+ queryKey: cartControllerGetCartV1QueryKey(options)
1001
+ });
1002
+ var cartControllerClearCartV1Mutation = (options) => {
1003
+ const mutationOptions = {
1004
+ mutationFn: async (fnOptions) => {
1005
+ const { data } = await cartControllerClearCartV1({
1006
+ ...options,
1007
+ ...fnOptions,
1008
+ throwOnError: true
1009
+ });
1010
+ return data;
1011
+ }
1012
+ };
1013
+ return mutationOptions;
1014
+ };
1015
+ var cartControllerAddItemV1Mutation = (options) => {
1016
+ const mutationOptions = {
1017
+ mutationFn: async (fnOptions) => {
1018
+ const { data } = await cartControllerAddItemV1({
1019
+ ...options,
1020
+ ...fnOptions,
1021
+ throwOnError: true
1022
+ });
1023
+ return data;
1024
+ }
1025
+ };
1026
+ return mutationOptions;
1027
+ };
1028
+ var cartControllerRemoveItemV1Mutation = (options) => {
1029
+ const mutationOptions = {
1030
+ mutationFn: async (fnOptions) => {
1031
+ const { data } = await cartControllerRemoveItemV1({
1032
+ ...options,
1033
+ ...fnOptions,
1034
+ throwOnError: true
1035
+ });
1036
+ return data;
1037
+ }
1038
+ };
1039
+ return mutationOptions;
1040
+ };
1041
+ var cartControllerUpdateItemV1Mutation = (options) => {
1042
+ const mutationOptions = {
1043
+ mutationFn: async (fnOptions) => {
1044
+ const { data } = await cartControllerUpdateItemV1({
1045
+ ...options,
1046
+ ...fnOptions,
1047
+ throwOnError: true
1048
+ });
1049
+ return data;
1050
+ }
1051
+ };
1052
+ return mutationOptions;
1053
+ };
1054
+ var checkoutControllerVerifyCartV1Mutation = (options) => {
1055
+ const mutationOptions = {
1056
+ mutationFn: async (fnOptions) => {
1057
+ const { data } = await checkoutControllerVerifyCartV1({
1058
+ ...options,
1059
+ ...fnOptions,
1060
+ throwOnError: true
1061
+ });
1062
+ return data;
1063
+ }
1064
+ };
1065
+ return mutationOptions;
1066
+ };
1067
+ var checkoutControllerCreateCheckoutSessionV1Mutation = (options) => {
1068
+ const mutationOptions = {
1069
+ mutationFn: async (fnOptions) => {
1070
+ const { data } = await checkoutControllerCreateCheckoutSessionV1({
1071
+ ...options,
1072
+ ...fnOptions,
1073
+ throwOnError: true
1074
+ });
1075
+ return data;
1076
+ }
1077
+ };
1078
+ return mutationOptions;
1079
+ };
1080
+ var checkoutControllerGetShippingOptionsV1QueryKey = (options) => createQueryKey("checkoutControllerGetShippingOptionsV1", options);
1081
+ var checkoutControllerGetShippingOptionsV1Options = (options) => queryOptions({
1082
+ queryFn: async ({ queryKey, signal }) => {
1083
+ const { data } = await checkoutControllerGetShippingOptionsV1({
1084
+ ...options,
1085
+ ...queryKey[0],
1086
+ signal,
1087
+ throwOnError: true
1088
+ });
1089
+ return data;
1090
+ },
1091
+ queryKey: checkoutControllerGetShippingOptionsV1QueryKey(options)
1092
+ });
1093
+ var checkoutControllerUpdateShippingSelectionsV1Mutation = (options) => {
1094
+ const mutationOptions = {
1095
+ mutationFn: async (fnOptions) => {
1096
+ const { data } = await checkoutControllerUpdateShippingSelectionsV1({
1097
+ ...options,
1098
+ ...fnOptions,
1099
+ throwOnError: true
1100
+ });
1101
+ return data;
1102
+ }
1103
+ };
1104
+ return mutationOptions;
1105
+ };
1106
+ var tenantPublicControllerGetPublicKeyV1QueryKey = (options) => createQueryKey("tenantPublicControllerGetPublicKeyV1", options);
1107
+ var tenantPublicControllerGetPublicKeyV1Options = (options) => queryOptions({
1108
+ queryFn: async ({ queryKey, signal }) => {
1109
+ const { data } = await tenantPublicControllerGetPublicKeyV1({
1110
+ ...options,
1111
+ ...queryKey[0],
1112
+ signal,
1113
+ throwOnError: true
1114
+ });
1115
+ return data;
1116
+ },
1117
+ queryKey: tenantPublicControllerGetPublicKeyV1QueryKey(options)
1118
+ });
1119
+ var paymentControllerCreateEmbeddedPaymentSessionV1Mutation = (options) => {
1120
+ const mutationOptions = {
1121
+ mutationFn: async (fnOptions) => {
1122
+ const { data } = await paymentControllerCreateEmbeddedPaymentSessionV1({
1123
+ ...options,
1124
+ ...fnOptions,
1125
+ throwOnError: true
1126
+ });
1127
+ return data;
1128
+ }
1129
+ };
1130
+ return mutationOptions;
1131
+ };
1132
+ var paymentControllerGetPaymentSessionV1QueryKey = (options) => createQueryKey("paymentControllerGetPaymentSessionV1", options);
1133
+ var paymentControllerGetPaymentSessionV1Options = (options) => queryOptions({
1134
+ queryFn: async ({ queryKey, signal }) => {
1135
+ const { data } = await paymentControllerGetPaymentSessionV1({
1136
+ ...options,
1137
+ ...queryKey[0],
1138
+ signal,
1139
+ throwOnError: true
1140
+ });
1141
+ return data;
1142
+ },
1143
+ queryKey: paymentControllerGetPaymentSessionV1QueryKey(options)
1144
+ });
1145
+
1146
+ // src/keys.ts
1147
+ var cartKeys = {
1148
+ all: () => [{ _id: "cartControllerGetCartV1" }]
1149
+ };
1150
+ var shippingKeys = {
1151
+ all: () => [{ _id: "checkoutControllerGetShippingOptionsV1" }]
1152
+ };
1153
+ var paymentKeys = {
1154
+ all: () => [{ _id: "paymentControllerGetPaymentSessionV1" }]
1155
+ };
1156
+
1157
+ // src/hooks/cart.ts
1158
+ function useCart() {
1159
+ const { tenantSlug, cartSessionId, cartApiUrl } = useCartContext();
1160
+ return useQuery({
1161
+ ...cartControllerGetCartV1Options({
1162
+ baseUrl: cartApiUrl,
1163
+ path: {
1164
+ tenantSlug,
1165
+ cartSessionId
1166
+ }
1167
+ }),
1168
+ enabled: !!cartSessionId
1169
+ });
1170
+ }
1171
+ function useCreateCart() {
1172
+ const { tenantSlug, cartApiUrl, setCartSessionId } = useCartContext();
1173
+ const queryClient = useQueryClient();
1174
+ const mutation = useMutation({
1175
+ ...cartControllerCreateCartV1Mutation(),
1176
+ onSuccess: (data) => {
1177
+ setCartSessionId(data.sessionId);
1178
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1179
+ }
1180
+ });
1181
+ const createCart = useCallback(
1182
+ (params = {}, callbacks) => {
1183
+ const { currency = "USD", metadata = {} } = params;
1184
+ mutation.mutate(
1185
+ {
1186
+ path: { tenantSlug },
1187
+ body: { currency, metadata },
1188
+ baseUrl: cartApiUrl
1189
+ },
1190
+ callbacks
1191
+ );
1192
+ },
1193
+ [mutation, tenantSlug, cartApiUrl]
1194
+ );
1195
+ return {
1196
+ createCart,
1197
+ isPending: mutation.isPending,
1198
+ error: mutation.error
1199
+ };
1200
+ }
1201
+ function useAddToCart() {
1202
+ const { tenantSlug, cartApiUrl, cartSessionId } = useCartContext();
1203
+ const queryClient = useQueryClient();
1204
+ const mutation = useMutation({
1205
+ ...cartControllerAddItemV1Mutation(),
1206
+ onSuccess: () => {
1207
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1208
+ queryClient.invalidateQueries({ queryKey: shippingKeys.all() });
1209
+ }
1210
+ });
1211
+ const addToCart = useCallback(
1212
+ (params, callbacks) => {
1213
+ const { offerId, quantity = 1, metadata = {} } = params;
1214
+ mutation.mutate(
1215
+ {
1216
+ path: { tenantSlug, cartSessionId },
1217
+ body: { offerId, quantity, metadata },
1218
+ baseUrl: cartApiUrl
1219
+ },
1220
+ callbacks
1221
+ );
1222
+ },
1223
+ [mutation, tenantSlug, cartSessionId, cartApiUrl]
1224
+ );
1225
+ return {
1226
+ addToCart,
1227
+ isPending: mutation.isPending,
1228
+ error: mutation.error
1229
+ };
1230
+ }
1231
+ function useUpdateItemQty() {
1232
+ const { tenantSlug, cartApiUrl, cartSessionId } = useCartContext();
1233
+ const queryClient = useQueryClient();
1234
+ const mutation = useMutation({
1235
+ ...cartControllerUpdateItemV1Mutation(),
1236
+ onSuccess: () => {
1237
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1238
+ queryClient.invalidateQueries({ queryKey: shippingKeys.all() });
1239
+ }
1240
+ });
1241
+ const updateItemQty = useCallback(
1242
+ (params, callbacks) => {
1243
+ const { offerId, quantity } = params;
1244
+ mutation.mutate(
1245
+ {
1246
+ path: { tenantSlug, cartSessionId, offerId },
1247
+ body: { quantity },
1248
+ baseUrl: cartApiUrl
1249
+ },
1250
+ callbacks
1251
+ );
1252
+ },
1253
+ [mutation, tenantSlug, cartSessionId, cartApiUrl]
1254
+ );
1255
+ return {
1256
+ updateItemQty,
1257
+ isPending: mutation.isPending,
1258
+ error: mutation.error
1259
+ };
1260
+ }
1261
+ function useRemoveItem() {
1262
+ const { tenantSlug, cartApiUrl, cartSessionId } = useCartContext();
1263
+ const queryClient = useQueryClient();
1264
+ const mutation = useMutation({
1265
+ ...cartControllerRemoveItemV1Mutation(),
1266
+ onSuccess: () => {
1267
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1268
+ queryClient.invalidateQueries({ queryKey: shippingKeys.all() });
1269
+ }
1270
+ });
1271
+ const removeItem = useCallback(
1272
+ (params, callbacks) => {
1273
+ const { offerId } = params;
1274
+ mutation.mutate(
1275
+ {
1276
+ path: { tenantSlug, cartSessionId, offerId },
1277
+ baseUrl: cartApiUrl
1278
+ },
1279
+ callbacks
1280
+ );
1281
+ },
1282
+ [mutation, tenantSlug, cartSessionId, cartApiUrl]
1283
+ );
1284
+ return {
1285
+ removeItem,
1286
+ isPending: mutation.isPending,
1287
+ error: mutation.error
1288
+ };
1289
+ }
1290
+ function useClearCart() {
1291
+ const { tenantSlug, cartApiUrl, cartSessionId } = useCartContext();
1292
+ const queryClient = useQueryClient();
1293
+ const mutation = useMutation({
1294
+ ...cartControllerClearCartV1Mutation(),
1295
+ onSuccess: () => {
1296
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1297
+ queryClient.invalidateQueries({ queryKey: shippingKeys.all() });
1298
+ }
1299
+ });
1300
+ const clearCart = useCallback(
1301
+ (callbacks) => {
1302
+ mutation.mutate(
1303
+ {
1304
+ path: { tenantSlug, cartSessionId },
1305
+ baseUrl: cartApiUrl
1306
+ },
1307
+ callbacks
1308
+ );
1309
+ },
1310
+ [mutation, tenantSlug, cartSessionId, cartApiUrl]
1311
+ );
1312
+ return {
1313
+ clearCart,
1314
+ isPending: mutation.isPending,
1315
+ error: mutation.error
1316
+ };
1317
+ }
1318
+ function useInitializeCart() {
1319
+ const { tenantSlug, cartApiUrl, cartSessionId, setCartSessionId, setIsInitializing } = useCartContext();
1320
+ const queryClient = useQueryClient();
1321
+ const creatingCartRef = useRef(false);
1322
+ const cartQuery = useQuery({
1323
+ ...cartControllerGetCartV1Options({
1324
+ path: {
1325
+ tenantSlug,
1326
+ cartSessionId
1327
+ },
1328
+ baseUrl: cartApiUrl
1329
+ }),
1330
+ enabled: !!cartSessionId,
1331
+ retry: false
1332
+ });
1333
+ const createCartMutation = useMutation({
1334
+ ...cartControllerCreateCartV1Mutation(),
1335
+ onMutate: () => {
1336
+ creatingCartRef.current = true;
1337
+ },
1338
+ onSuccess: (data) => {
1339
+ setCartSessionId(data.sessionId);
1340
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1341
+ creatingCartRef.current = false;
1342
+ },
1343
+ onError: () => {
1344
+ creatingCartRef.current = false;
1345
+ }
1346
+ });
1347
+ useEffect(() => {
1348
+ if (creatingCartRef.current) return;
1349
+ if (cartSessionId) {
1350
+ if (cartQuery.isError) {
1351
+ setCartSessionId(null);
1352
+ createCartMutation.mutate({
1353
+ path: { tenantSlug },
1354
+ body: { currency: "USD", metadata: {} },
1355
+ baseUrl: cartApiUrl
1356
+ });
1357
+ return;
1358
+ }
1359
+ if (cartQuery.data?.completedAt) {
1360
+ setCartSessionId(null);
1361
+ createCartMutation.mutate({
1362
+ path: { tenantSlug },
1363
+ body: { currency: "USD", metadata: {} },
1364
+ baseUrl: cartApiUrl
1365
+ });
1366
+ return;
1367
+ }
1368
+ if (cartQuery.data) {
1369
+ setIsInitializing(false);
1370
+ }
1371
+ return;
1372
+ }
1373
+ createCartMutation.mutate({
1374
+ path: { tenantSlug },
1375
+ body: { currency: "USD", metadata: {} },
1376
+ baseUrl: cartApiUrl
1377
+ });
1378
+ }, [
1379
+ tenantSlug,
1380
+ cartApiUrl,
1381
+ cartSessionId,
1382
+ cartQuery.isError,
1383
+ cartQuery.data?.completedAt,
1384
+ cartQuery.data,
1385
+ setCartSessionId,
1386
+ setIsInitializing,
1387
+ createCartMutation
1388
+ ]);
1389
+ const isInitializing = cartQuery.isLoading || createCartMutation.isPending || !cartSessionId && !createCartMutation.isSuccess;
1390
+ return { isInitializing };
1391
+ }
1392
+
1393
+ // src/hooks/checkout.ts
1394
+ import { useMutation as useMutation2, useQuery as useQuery2, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
1395
+ import { useCallback as useCallback2 } from "react";
1396
+ function useVerifyCart() {
1397
+ const { tenantSlug, cartApiUrl } = useCartContext();
1398
+ const queryClient = useQueryClient2();
1399
+ const mutation = useMutation2({
1400
+ ...checkoutControllerVerifyCartV1Mutation(),
1401
+ onSuccess: () => {
1402
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1403
+ }
1404
+ });
1405
+ const verifyCart = useCallback2(
1406
+ (params, callbacks) => {
1407
+ mutation.mutate(
1408
+ {
1409
+ path: { tenantSlug },
1410
+ body: { cartSessionId: params.cartSessionId },
1411
+ baseUrl: cartApiUrl
1412
+ },
1413
+ callbacks
1414
+ );
1415
+ },
1416
+ [mutation, tenantSlug, cartApiUrl]
1417
+ );
1418
+ return {
1419
+ verifyCart,
1420
+ isPending: mutation.isPending,
1421
+ error: mutation.error
1422
+ };
1423
+ }
1424
+ function useCreateCheckoutSession() {
1425
+ const { tenantSlug, cartApiUrl, cartSessionId } = useCartContext();
1426
+ const queryClient = useQueryClient2();
1427
+ const mutation = useMutation2({
1428
+ ...checkoutControllerCreateCheckoutSessionV1Mutation(),
1429
+ onSuccess: () => {
1430
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1431
+ }
1432
+ });
1433
+ const createCheckoutSession = useCallback2(
1434
+ (params, callbacks) => {
1435
+ const { cartSessionId: paramSessionId, ...body } = params;
1436
+ mutation.mutate(
1437
+ {
1438
+ path: { tenantSlug, cartSessionId: paramSessionId ?? cartSessionId },
1439
+ body,
1440
+ baseUrl: cartApiUrl
1441
+ },
1442
+ callbacks
1443
+ );
1444
+ },
1445
+ [mutation, tenantSlug, cartSessionId, cartApiUrl]
1446
+ );
1447
+ return {
1448
+ createCheckoutSession,
1449
+ isPending: mutation.isPending,
1450
+ error: mutation.error
1451
+ };
1452
+ }
1453
+ function useShippingOptions(cartSessionId) {
1454
+ const { tenantSlug, cartApiUrl } = useCartContext();
1455
+ return useQuery2({
1456
+ ...checkoutControllerGetShippingOptionsV1Options({
1457
+ path: {
1458
+ tenantSlug,
1459
+ cartSessionId
1460
+ },
1461
+ baseUrl: cartApiUrl
1462
+ }),
1463
+ enabled: !!cartSessionId
1464
+ });
1465
+ }
1466
+ function useUpdateShippingSelections() {
1467
+ const { tenantSlug, cartApiUrl, cartSessionId } = useCartContext();
1468
+ const queryClient = useQueryClient2();
1469
+ const mutation = useMutation2({
1470
+ ...checkoutControllerUpdateShippingSelectionsV1Mutation(),
1471
+ onSuccess: () => {
1472
+ queryClient.invalidateQueries({ queryKey: cartKeys.all() });
1473
+ }
1474
+ });
1475
+ const updateShippingSelections = useCallback2(
1476
+ (params, callbacks) => {
1477
+ mutation.mutate(
1478
+ {
1479
+ path: { tenantSlug, cartSessionId },
1480
+ body: params,
1481
+ baseUrl: cartApiUrl
1482
+ },
1483
+ callbacks
1484
+ );
1485
+ },
1486
+ [mutation, tenantSlug, cartSessionId, cartApiUrl]
1487
+ );
1488
+ return {
1489
+ updateShippingSelections,
1490
+ isPending: mutation.isPending,
1491
+ error: mutation.error
1492
+ };
1493
+ }
1494
+
1495
+ // src/hooks/payment.ts
1496
+ import { useMutation as useMutation3, useQuery as useQuery3 } from "@tanstack/react-query";
1497
+ import { useCallback as useCallback3, useMemo } from "react";
1498
+ var _loadStripe = null;
1499
+ var _stripeLoadAttempted = false;
1500
+ function getStripeLoader() {
1501
+ if (_stripeLoadAttempted) {
1502
+ return _loadStripe;
1503
+ }
1504
+ _stripeLoadAttempted = true;
1505
+ try {
1506
+ const { loadStripe } = __require("@stripe/stripe-js");
1507
+ _loadStripe = loadStripe;
1508
+ return _loadStripe;
1509
+ } catch {
1510
+ _loadStripe = null;
1511
+ return null;
1512
+ }
1513
+ }
1514
+ function useStripePromise() {
1515
+ const { tenantSlug, cartApiUrl } = useCartContext();
1516
+ const { data: tenantPublicKey } = useQuery3({
1517
+ ...tenantPublicControllerGetPublicKeyV1Options({
1518
+ path: {
1519
+ keyType: "stripe_publishable_key",
1520
+ tenantSlug
1521
+ },
1522
+ baseUrl: cartApiUrl
1523
+ }),
1524
+ enabled: !!tenantSlug
1525
+ });
1526
+ const stripePromise = useMemo(() => {
1527
+ const publishableKey = tenantPublicKey?.value;
1528
+ if (!publishableKey) return null;
1529
+ const loadStripe = getStripeLoader();
1530
+ if (!loadStripe) {
1531
+ console.error(
1532
+ "useStripePromise: @stripe/stripe-js is not installed. Install it with: npm install @stripe/stripe-js"
1533
+ );
1534
+ return null;
1535
+ }
1536
+ return loadStripe(publishableKey);
1537
+ }, [tenantPublicKey?.value]);
1538
+ return stripePromise;
1539
+ }
1540
+ function useCreateEmbeddedCheckoutSession() {
1541
+ const { tenantSlug, cartApiUrl } = useCartContext();
1542
+ const mutation = useMutation3({
1543
+ ...paymentControllerCreateEmbeddedPaymentSessionV1Mutation()
1544
+ });
1545
+ const createEmbeddedCheckoutSession = useCallback3(
1546
+ (params, callbacks) => {
1547
+ mutation.mutate(
1548
+ {
1549
+ path: { tenantSlug },
1550
+ body: params,
1551
+ baseUrl: cartApiUrl
1552
+ },
1553
+ callbacks
1554
+ );
1555
+ },
1556
+ [mutation, tenantSlug, cartApiUrl]
1557
+ );
1558
+ return {
1559
+ createEmbeddedCheckoutSession,
1560
+ isPending: mutation.isPending,
1561
+ error: mutation.error,
1562
+ data: mutation.data
1563
+ };
1564
+ }
1565
+ function usePaymentSession(sessionId) {
1566
+ const { tenantSlug, cartApiUrl } = useCartContext();
1567
+ return useQuery3({
1568
+ ...paymentControllerGetPaymentSessionV1Options({
1569
+ path: {
1570
+ tenantSlug,
1571
+ id: sessionId
1572
+ },
1573
+ baseUrl: cartApiUrl
1574
+ }),
1575
+ enabled: !!sessionId
1576
+ });
1577
+ }
1578
+
1579
+ // src/providers/CartProvider.tsx
1580
+ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
1581
+ import { useCallback as useCallback4, useEffect as useEffect2, useMemo as useMemo2, useState } from "react";
1582
+ import { jsx, jsxs } from "react/jsx-runtime";
1583
+ var STORAGE_KEY = "cartSessionId";
1584
+ function CartProviderInner({
1585
+ children,
1586
+ tenantSlug,
1587
+ cartApiUrl,
1588
+ storage,
1589
+ autoInitialize
1590
+ }) {
1591
+ const [cartSessionId, setCartSessionIdState] = useState(
1592
+ () => storage.get(STORAGE_KEY)
1593
+ );
1594
+ const [isInitializing, setIsInitializing] = useState(autoInitialize ?? true);
1595
+ const setCartSessionId = useCallback4(
1596
+ (id) => {
1597
+ setCartSessionIdState(id);
1598
+ if (id) {
1599
+ storage.set(STORAGE_KEY, id);
1600
+ } else {
1601
+ storage.remove(STORAGE_KEY);
1602
+ }
1603
+ },
1604
+ [storage]
1605
+ );
1606
+ const contextValue = useMemo2(
1607
+ () => ({
1608
+ tenantSlug,
1609
+ cartApiUrl,
1610
+ storage,
1611
+ cartSessionId,
1612
+ setCartSessionId,
1613
+ isInitializing,
1614
+ setIsInitializing
1615
+ }),
1616
+ [tenantSlug, cartApiUrl, storage, cartSessionId, setCartSessionId, isInitializing]
1617
+ );
1618
+ return /* @__PURE__ */ jsxs(CartContext.Provider, { value: contextValue, children: [
1619
+ autoInitialize !== false && /* @__PURE__ */ jsx(AutoInitializer, {}),
1620
+ children
1621
+ ] });
1622
+ }
1623
+ function AutoInitializer() {
1624
+ const { isInitializing } = useInitializeCart();
1625
+ const { setIsInitializing } = useCartContext();
1626
+ useEffect2(() => {
1627
+ setIsInitializing(isInitializing);
1628
+ }, [isInitializing, setIsInitializing]);
1629
+ return null;
1630
+ }
1631
+ var internalQueryClient = null;
1632
+ function getOrCreateQueryClient() {
1633
+ if (!internalQueryClient) {
1634
+ internalQueryClient = new QueryClient({
1635
+ defaultOptions: {
1636
+ queries: { staleTime: 1e3 * 60, retry: false },
1637
+ mutations: { retry: false }
1638
+ }
1639
+ });
1640
+ }
1641
+ return internalQueryClient;
1642
+ }
1643
+ function CartProvider({
1644
+ children,
1645
+ tenantSlug,
1646
+ cartApiUrl,
1647
+ storageAdapter,
1648
+ autoInitialize = true,
1649
+ queryClient
1650
+ }) {
1651
+ const storage = storageAdapter ?? localStorageAdapter;
1652
+ useEffect2(() => {
1653
+ client.setConfig({ baseUrl: cartApiUrl });
1654
+ }, [cartApiUrl]);
1655
+ const [effectiveQueryClient] = useState(() => queryClient ?? getOrCreateQueryClient());
1656
+ const inner = /* @__PURE__ */ jsx(
1657
+ CartProviderInner,
1658
+ {
1659
+ tenantSlug,
1660
+ cartApiUrl,
1661
+ storage,
1662
+ autoInitialize,
1663
+ children
1664
+ }
1665
+ );
1666
+ if (queryClient) {
1667
+ return inner;
1668
+ }
1669
+ return /* @__PURE__ */ jsx(QueryClientProvider, { client: effectiveQueryClient, children: inner });
1670
+ }
1671
+ export {
1672
+ CartProvider,
1673
+ cartKeys,
1674
+ localStorageAdapter,
1675
+ paymentKeys,
1676
+ shippingKeys,
1677
+ useAddToCart,
1678
+ useCart,
1679
+ useCartContext,
1680
+ useClearCart,
1681
+ useCreateCart,
1682
+ useCreateCheckoutSession,
1683
+ useCreateEmbeddedCheckoutSession,
1684
+ useInitializeCart,
1685
+ usePaymentSession,
1686
+ useRemoveItem,
1687
+ useShippingOptions,
1688
+ useStripePromise,
1689
+ useUpdateItemQty,
1690
+ useUpdateShippingSelections,
1691
+ useVerifyCart
1692
+ };