@cimplify/sdk 0.7.2 → 0.7.4

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.mjs CHANGED
@@ -236,74 +236,6 @@ function combineObject(results) {
236
236
  return ok(values);
237
237
  }
238
238
 
239
- // src/query/builder.ts
240
- function escapeQueryValue(value) {
241
- return value.replace(/'/g, "\\'");
242
- }
243
- var QueryBuilder = class {
244
- constructor(entity) {
245
- this.filters = [];
246
- this.modifiers = [];
247
- this.pathSegments = [];
248
- this.entity = entity;
249
- }
250
- path(segment) {
251
- this.pathSegments.push(segment);
252
- return this;
253
- }
254
- where(field, op, value) {
255
- const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
256
- if (op === "contains" || op === "startsWith") {
257
- this.filters.push(`@.${field} ${op} ${v}`);
258
- } else {
259
- this.filters.push(`@.${field}${op}${v}`);
260
- }
261
- return this;
262
- }
263
- and(field, op, value) {
264
- return this.where(field, op, value);
265
- }
266
- sort(field, order = "asc") {
267
- this.modifiers.push(`sort(${field},${order})`);
268
- return this;
269
- }
270
- limit(n) {
271
- this.modifiers.push(`limit(${n})`);
272
- return this;
273
- }
274
- offset(n) {
275
- this.modifiers.push(`offset(${n})`);
276
- return this;
277
- }
278
- count() {
279
- this.modifiers.push("count");
280
- return this;
281
- }
282
- enriched() {
283
- this.modifiers.push("enriched");
284
- return this;
285
- }
286
- build() {
287
- let query2 = this.entity;
288
- if (this.pathSegments.length > 0) {
289
- query2 += "." + this.pathSegments.join(".");
290
- }
291
- if (this.filters.length > 0) {
292
- query2 += `[?(${this.filters.join(" && ")})]`;
293
- }
294
- for (const mod of this.modifiers) {
295
- query2 += `#${mod}`;
296
- }
297
- return query2;
298
- }
299
- toString() {
300
- return this.build();
301
- }
302
- };
303
- function query(entity) {
304
- return new QueryBuilder(entity);
305
- }
306
-
307
239
  // src/catalogue.ts
308
240
  function toCimplifyError(error) {
309
241
  if (error instanceof CimplifyError) return enrichError(error);
@@ -319,14 +251,6 @@ async function safe(promise) {
319
251
  return err(toCimplifyError(error));
320
252
  }
321
253
  }
322
- async function safeWithFallback(primary, fallback) {
323
- const primaryResult = await safe(primary());
324
- if (primaryResult.ok) return primaryResult;
325
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
326
- return primaryResult;
327
- }
328
- return safe(fallback());
329
- }
330
254
  function withQuery(path, params) {
331
255
  const query2 = new URLSearchParams();
332
256
  for (const [key, value] of Object.entries(params)) {
@@ -388,22 +312,6 @@ function normalizeCatalogueProductPayload(product) {
388
312
  }
389
313
  return normalized;
390
314
  }
391
- function findProductBySlug(products, slug) {
392
- return products.find((product) => {
393
- const value = product["slug"];
394
- return typeof value === "string" && value === slug;
395
- });
396
- }
397
- function findCategoryBySlug(categories, slug) {
398
- return categories.find((category) => {
399
- const value = category["slug"];
400
- return typeof value === "string" && value === slug;
401
- });
402
- }
403
- function hasCategorySlug(category) {
404
- const value = category["slug"];
405
- return typeof value === "string" && value.trim().length > 0;
406
- }
407
315
  function toFiniteNumber(value) {
408
316
  if (typeof value === "number" && Number.isFinite(value)) {
409
317
  return value;
@@ -491,53 +399,11 @@ var CatalogueQueries = class {
491
399
  this.client = client;
492
400
  }
493
401
  async getCatalogue() {
494
- const result = await safeWithFallback(
495
- () => this.client.get("/api/v1/catalogue"),
496
- () => this.client.query("catalogue")
497
- );
402
+ const result = await safe(this.client.get("/api/v1/catalogue"));
498
403
  if (!result.ok) return result;
499
404
  return ok(normalizeCatalogueSnapshot(result.value));
500
405
  }
501
406
  async getProducts(options) {
502
- let query2 = "products";
503
- const filters = [];
504
- if (options?.category) {
505
- filters.push(`@.category_id=='${escapeQueryValue(options.category)}'`);
506
- }
507
- if (options?.featured !== void 0) {
508
- filters.push(`@.featured==${options.featured}`);
509
- }
510
- if (options?.in_stock !== void 0) {
511
- filters.push(`@.in_stock==${options.in_stock}`);
512
- }
513
- if (options?.search) {
514
- filters.push(`@.name contains '${escapeQueryValue(options.search)}'`);
515
- }
516
- if (options?.tags?.length) {
517
- for (const tag of options.tags) {
518
- if (tag.trim().length > 0) {
519
- filters.push(`@.tags contains '${escapeQueryValue(tag)}'`);
520
- }
521
- }
522
- }
523
- if (options?.min_price !== void 0) {
524
- filters.push(`@.price>=${options.min_price}`);
525
- }
526
- if (options?.max_price !== void 0) {
527
- filters.push(`@.price<=${options.max_price}`);
528
- }
529
- if (filters.length > 0) {
530
- query2 += `[?(${filters.join(" && ")})]`;
531
- }
532
- if (options?.sort_by) {
533
- query2 += `#sort(${options.sort_by},${options.sort_order || "asc"})`;
534
- }
535
- if (options?.limit !== void 0) {
536
- query2 += `#limit(${options.limit})`;
537
- }
538
- if (options?.offset !== void 0) {
539
- query2 += `#offset(${options.offset})`;
540
- }
541
407
  const path = withQuery("/api/v1/catalogue/products", {
542
408
  category_id: options?.category,
543
409
  search: options?.search,
@@ -553,325 +419,145 @@ var CatalogueQueries = class {
553
419
  offset: options?.offset,
554
420
  cursor: options?.cursor
555
421
  });
556
- const result = await safeWithFallback(
557
- () => this.client.get(path),
558
- () => this.client.query(query2)
559
- );
422
+ const result = await safe(this.client.get(path));
560
423
  if (!result.ok) return result;
561
424
  return ok(normalizeCatalogueResult(result.value));
562
425
  }
563
426
  async getProduct(id) {
564
427
  const encodedId = encodeURIComponent(id);
565
- const result = await safeWithFallback(
566
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}`),
567
- () => this.client.query(`products.${id}`)
568
- );
428
+ const result = await safe(this.client.get(`/api/v1/catalogue/products/${encodedId}`));
569
429
  if (!result.ok) return result;
570
430
  return ok(normalizeCatalogueProductPayload(result.value));
571
431
  }
572
432
  async getProductBySlug(slug) {
573
433
  const encodedSlug = encodeURIComponent(slug);
574
- const restResult = await safe(
575
- this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`)
576
- );
577
- if (restResult.ok) {
578
- return ok(normalizeCatalogueProductPayload(restResult.value));
579
- }
580
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
581
- return restResult;
582
- }
583
- const filteredResult = await safe(
584
- this.client.query(
585
- `products[?(@.slug=='${escapeQueryValue(slug)}')]#limit(50)`
586
- )
587
- );
588
- if (!filteredResult.ok) return filteredResult;
589
- const exactMatch = findProductBySlug(filteredResult.value, slug);
590
- if (exactMatch) {
591
- return ok(normalizeCatalogueProductPayload(exactMatch));
592
- }
593
- if (filteredResult.value.length === 1) {
594
- return ok(normalizeCatalogueProductPayload(filteredResult.value[0]));
595
- }
596
- const unfilteredResult = await safe(
597
- this.client.query("products#limit(200)")
598
- );
599
- if (!unfilteredResult.ok) return unfilteredResult;
600
- const fallbackMatch = findProductBySlug(unfilteredResult.value, slug);
601
- if (!fallbackMatch) {
602
- return err(new CimplifyError("NOT_FOUND", `Product not found: ${slug}`, false));
603
- }
604
- return ok(normalizeCatalogueProductPayload(fallbackMatch));
434
+ const result = await safe(this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`));
435
+ if (!result.ok) return result;
436
+ return ok(normalizeCatalogueProductPayload(result.value));
605
437
  }
606
438
  async getVariants(productId) {
607
439
  const encodedId = encodeURIComponent(productId);
608
- return safeWithFallback(
609
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`),
610
- () => this.client.query(`products.${productId}.variants`)
611
- );
440
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`));
612
441
  }
613
442
  async getVariantAxes(productId) {
614
443
  const encodedId = encodeURIComponent(productId);
615
- return safeWithFallback(
616
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`),
617
- () => this.client.query(`products.${productId}.variant_axes`)
618
- );
444
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`));
619
445
  }
620
- /**
621
- * Find a variant by axis selections (e.g., { "Size": "Large", "Color": "Red" })
622
- * Returns the matching variant or null if no match found.
623
- */
624
446
  async getVariantByAxisSelections(productId, selections) {
625
447
  const encodedId = encodeURIComponent(productId);
626
- return safeWithFallback(
627
- () => this.client.post(
448
+ return safe(
449
+ this.client.post(
628
450
  `/api/v1/catalogue/products/${encodedId}/variants/find`,
629
451
  {
630
452
  axis_selections: selections
631
453
  }
632
- ),
633
- () => this.client.query(`products.${productId}.variant`, {
634
- axis_selections: selections
635
- })
454
+ )
636
455
  );
637
456
  }
638
- /**
639
- * Get a specific variant by its ID
640
- */
641
457
  async getVariantById(productId, variantId) {
642
458
  const encodedProductId = encodeURIComponent(productId);
643
459
  const encodedVariantId = encodeURIComponent(variantId);
644
- return safeWithFallback(
645
- () => this.client.get(
460
+ return safe(
461
+ this.client.get(
646
462
  `/api/v1/catalogue/products/${encodedProductId}/variants/${encodedVariantId}`
647
- ),
648
- () => this.client.query(`products.${productId}.variant.${variantId}`)
463
+ )
649
464
  );
650
465
  }
651
466
  async getAddOns(productId) {
652
467
  const encodedId = encodeURIComponent(productId);
653
- return safeWithFallback(
654
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`),
655
- () => this.client.query(`products.${productId}.add_ons`)
656
- );
468
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`));
657
469
  }
658
470
  async getCategories() {
659
- const result = await safeWithFallback(
660
- () => this.client.get("/api/v1/catalogue/categories"),
661
- () => this.client.query("categories")
662
- );
663
- if (!result.ok) return result;
664
- if (result.value.some(hasCategorySlug)) {
665
- return result;
666
- }
667
- const catalogueResult = await safe(
668
- this.client.query("catalogue#limit(1)")
669
- );
670
- if (!catalogueResult.ok) {
671
- return result;
672
- }
673
- const fallbackCategories = Array.isArray(catalogueResult.value.categories) ? catalogueResult.value.categories : [];
674
- return fallbackCategories.length > 0 ? ok(fallbackCategories) : result;
471
+ return safe(this.client.get("/api/v1/catalogue/categories"));
675
472
  }
676
473
  async getCategory(id) {
677
474
  const encodedId = encodeURIComponent(id);
678
- return safeWithFallback(
679
- () => this.client.get(`/api/v1/catalogue/categories/${encodedId}`),
680
- () => this.client.query(`categories.${id}`)
681
- );
475
+ return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}`));
682
476
  }
683
477
  async getCategoryBySlug(slug) {
684
478
  const encodedSlug = encodeURIComponent(slug);
685
- const restResult = await safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
686
- if (restResult.ok) {
687
- return restResult;
688
- }
689
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
690
- return restResult;
691
- }
692
- const result = await safe(
693
- this.client.query(`categories[?(@.slug=='${escapeQueryValue(slug)}')]`)
694
- );
695
- if (!result.ok) return result;
696
- const exactMatch = findCategoryBySlug(result.value, slug);
697
- if (exactMatch) {
698
- return ok(exactMatch);
699
- }
700
- const categoriesResult = await this.getCategories();
701
- if (!categoriesResult.ok) {
702
- return categoriesResult;
703
- }
704
- const fallbackMatch = findCategoryBySlug(categoriesResult.value, slug);
705
- if (!fallbackMatch) {
706
- return err(new CimplifyError("NOT_FOUND", `Category not found: ${slug}`, false));
707
- }
708
- return ok(fallbackMatch);
479
+ return safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
709
480
  }
710
481
  async getCategoryProducts(categoryId) {
711
482
  const encodedId = encodeURIComponent(categoryId);
712
- return safeWithFallback(
713
- () => this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`),
714
- () => this.client.query(
715
- `products[?(@.category_id=='${escapeQueryValue(categoryId)}')]`
716
- )
717
- );
483
+ return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`));
718
484
  }
719
485
  async getCollections() {
720
- return safeWithFallback(
721
- () => this.client.get("/api/v1/catalogue/collections"),
722
- () => this.client.query("collections")
723
- );
486
+ return safe(this.client.get("/api/v1/catalogue/collections"));
724
487
  }
725
488
  async getCollection(id) {
726
489
  const encodedId = encodeURIComponent(id);
727
- return safeWithFallback(
728
- () => this.client.get(`/api/v1/catalogue/collections/${encodedId}`),
729
- () => this.client.query(`collections.${id}`)
730
- );
490
+ return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}`));
731
491
  }
732
492
  async getCollectionBySlug(slug) {
733
493
  const encodedSlug = encodeURIComponent(slug);
734
- const restResult = await safe(
735
- this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`)
736
- );
737
- if (restResult.ok) return restResult;
738
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
739
- return restResult;
740
- }
741
- const result = await safe(
742
- this.client.query(`collections[?(@.slug=='${escapeQueryValue(slug)}')]`)
743
- );
744
- if (!result.ok) return result;
745
- if (!result.value.length) {
746
- return err(new CimplifyError("NOT_FOUND", `Collection not found: ${slug}`, false));
747
- }
748
- return ok(result.value[0]);
494
+ return safe(this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`));
749
495
  }
750
496
  async getCollectionProducts(collectionId) {
751
497
  const encodedId = encodeURIComponent(collectionId);
752
- return safeWithFallback(
753
- () => this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`),
754
- () => this.client.query(`collections.${collectionId}.products`)
755
- );
498
+ return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`));
756
499
  }
757
500
  async searchCollections(query2, limit = 20) {
758
501
  const path = withQuery("/api/v1/catalogue/collections", { search: query2, limit });
759
- return safeWithFallback(
760
- () => this.client.get(path),
761
- () => this.client.query(
762
- `collections[?(@.name contains '${escapeQueryValue(query2)}')]#limit(${limit})`
763
- )
764
- );
502
+ return safe(this.client.get(path));
765
503
  }
766
504
  async getBundles() {
767
- return safeWithFallback(
768
- () => this.client.get("/api/v1/catalogue/bundles"),
769
- () => this.client.query("bundles")
770
- );
505
+ return safe(this.client.get("/api/v1/catalogue/bundles"));
771
506
  }
772
507
  async getBundle(id) {
773
508
  const encodedId = encodeURIComponent(id);
774
- return safeWithFallback(
775
- () => this.client.get(`/api/v1/catalogue/bundles/${encodedId}`),
776
- () => this.client.query(`bundles.${id}`)
777
- );
509
+ return safe(this.client.get(`/api/v1/catalogue/bundles/${encodedId}`));
778
510
  }
779
511
  async getBundleBySlug(slug) {
780
512
  const encodedSlug = encodeURIComponent(slug);
781
- const restResult = await safe(
782
- this.client.get(`/api/v1/catalogue/bundles/slug/${encodedSlug}`)
783
- );
784
- if (restResult.ok) return restResult;
785
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
786
- return restResult;
787
- }
788
- const result = await safe(
789
- this.client.query(
790
- `bundles[?(@.slug=='${escapeQueryValue(slug)}')]`
791
- )
792
- );
793
- if (!result.ok) return result;
794
- if (!result.value.length) {
795
- return err(new CimplifyError("NOT_FOUND", `Bundle not found: ${slug}`, false));
796
- }
797
- return ok(result.value[0]);
513
+ return safe(this.client.get(`/api/v1/catalogue/bundles/slug/${encodedSlug}`));
798
514
  }
799
515
  async searchBundles(query2, limit = 20) {
800
516
  const path = withQuery("/api/v1/catalogue/bundles", { search: query2, limit });
801
- return safeWithFallback(
802
- () => this.client.get(path),
803
- () => this.client.query(
804
- `bundles[?(@.name contains '${escapeQueryValue(query2)}')]#limit(${limit})`
805
- )
806
- );
517
+ return safe(this.client.get(path));
807
518
  }
808
519
  async getComposites(options) {
809
- let query2 = "composites";
810
- if (options?.limit) {
811
- query2 += `#limit(${options.limit})`;
812
- }
813
520
  const path = withQuery("/api/v1/catalogue/composites", { limit: options?.limit });
814
- return safeWithFallback(
815
- () => this.client.get(path),
816
- () => this.client.query(query2)
817
- );
521
+ return safe(this.client.get(path));
818
522
  }
819
523
  async getComposite(id) {
820
524
  const encodedId = encodeURIComponent(id);
821
- return safeWithFallback(
822
- () => this.client.get(`/api/v1/catalogue/composites/${encodedId}`),
823
- () => this.client.query(`composites.${id}`)
824
- );
525
+ return safe(this.client.get(`/api/v1/catalogue/composites/${encodedId}`));
825
526
  }
826
527
  async getCompositeByProductId(productId) {
827
528
  const encodedId = encodeURIComponent(productId);
828
- return safeWithFallback(
829
- () => this.client.get(
529
+ return safe(
530
+ this.client.get(
830
531
  `/api/v1/catalogue/composites/by-product/${encodedId}`
831
- ),
832
- () => this.client.query(`composites.by_product.${productId}`)
532
+ )
833
533
  );
834
534
  }
835
535
  async calculateCompositePrice(compositeId, selections, locationId) {
836
536
  const encodedId = encodeURIComponent(compositeId);
837
- return safeWithFallback(
838
- () => this.client.post(
537
+ return safe(
538
+ this.client.post(
839
539
  `/api/v1/catalogue/composites/${encodedId}/calculate-price`,
840
540
  {
841
541
  selections,
842
542
  location_id: locationId
843
543
  }
844
- ),
845
- () => this.client.call("composite.calculatePrice", {
846
- composite_id: compositeId,
847
- selections,
848
- location_id: locationId
849
- })
544
+ )
850
545
  );
851
546
  }
852
547
  async fetchQuote(input) {
853
- return safeWithFallback(
854
- () => this.client.post("/api/v1/catalogue/quotes", input),
855
- () => this.client.call("catalogue.createQuote", input)
856
- );
548
+ return safe(this.client.post("/api/v1/catalogue/quotes", input));
857
549
  }
858
550
  async getQuote(quoteId) {
859
551
  const encodedQuoteId = encodeURIComponent(quoteId);
860
- return safeWithFallback(
861
- () => this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`),
862
- () => this.client.call("catalogue.getQuote", {
863
- quote_id: quoteId
864
- })
865
- );
552
+ return safe(this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`));
866
553
  }
867
554
  async refreshQuote(input) {
868
555
  const encodedQuoteId = encodeURIComponent(input.quote_id);
869
- return safeWithFallback(
870
- () => this.client.post(
556
+ return safe(
557
+ this.client.post(
871
558
  `/api/v1/catalogue/quotes/${encodedQuoteId}/refresh`,
872
559
  input
873
- ),
874
- () => this.client.call("catalogue.refreshQuote", input)
560
+ )
875
561
  );
876
562
  }
877
563
  async search(query2, options) {
@@ -887,35 +573,19 @@ var CatalogueQueries = class {
887
573
  return this.search(query2, options);
888
574
  }
889
575
  async getMenu(options) {
890
- let query2 = "menu";
891
- if (options?.category) {
892
- query2 = `menu[?(@.category=='${escapeQueryValue(options.category)}')]`;
893
- }
894
- if (options?.limit) {
895
- query2 += `#limit(${options.limit})`;
896
- }
897
576
  const path = withQuery("/api/v1/catalogue/menu", {
898
577
  category_id: options?.category,
899
578
  limit: options?.limit
900
579
  });
901
- return safeWithFallback(
902
- () => this.client.get(path),
903
- () => this.client.query(query2)
904
- );
580
+ return safe(this.client.get(path));
905
581
  }
906
582
  async getMenuCategory(categoryId) {
907
583
  const encodedId = encodeURIComponent(categoryId);
908
- return safeWithFallback(
909
- () => this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`),
910
- () => this.client.query(`menu.category.${categoryId}`)
911
- );
584
+ return safe(this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`));
912
585
  }
913
586
  async getMenuItem(itemId) {
914
587
  const encodedId = encodeURIComponent(itemId);
915
- return safeWithFallback(
916
- () => this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`),
917
- () => this.client.query(`menu.${itemId}`)
918
- );
588
+ return safe(this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`));
919
589
  }
920
590
  };
921
591
 
@@ -934,14 +604,6 @@ async function safe2(promise) {
934
604
  return err(toCimplifyError2(error));
935
605
  }
936
606
  }
937
- async function safeWithFallback2(primary, fallback) {
938
- const primaryResult = await safe2(primary());
939
- if (primaryResult.ok) return primaryResult;
940
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
941
- return primaryResult;
942
- }
943
- return safe2(fallback());
944
- }
945
607
  function isUICartResponse(value) {
946
608
  return "cart" in value;
947
609
  }
@@ -953,36 +615,21 @@ var CartOperations = class {
953
615
  this.client = client;
954
616
  }
955
617
  async get() {
956
- const result = await safeWithFallback2(
957
- () => this.client.get("/api/v1/cart"),
958
- () => this.client.query("cart#enriched")
959
- );
618
+ const result = await safe2(this.client.get("/api/v1/cart"));
960
619
  if (!result.ok) return result;
961
620
  return ok(unwrapEnrichedCart(result.value));
962
621
  }
963
622
  async getRaw() {
964
- return safeWithFallback2(
965
- () => this.client.get("/api/v1/cart"),
966
- () => this.client.query("cart")
967
- );
623
+ return safe2(this.client.get("/api/v1/cart"));
968
624
  }
969
625
  async getItems() {
970
- return safeWithFallback2(
971
- () => this.client.get("/api/v1/cart/items"),
972
- () => this.client.query("cart_items")
973
- );
626
+ return safe2(this.client.get("/api/v1/cart/items"));
974
627
  }
975
628
  async getCount() {
976
- return safeWithFallback2(
977
- () => this.client.get("/api/v1/cart/count"),
978
- () => this.client.query("cart#count")
979
- );
629
+ return safe2(this.client.get("/api/v1/cart/count"));
980
630
  }
981
631
  async getTotal() {
982
- return safeWithFallback2(
983
- () => this.client.get("/api/v1/cart/total"),
984
- () => this.client.query("cart#total")
985
- );
632
+ return safe2(this.client.get("/api/v1/cart/total"));
986
633
  }
987
634
  async getSummary() {
988
635
  const cartResult = await this.get();
@@ -999,66 +646,39 @@ var CartOperations = class {
999
646
  });
1000
647
  }
1001
648
  async addItem(input) {
1002
- return safeWithFallback2(
1003
- () => this.client.post("/api/v1/cart/items", input),
1004
- () => this.client.call("cart.addItem", input)
1005
- );
649
+ return safe2(this.client.post("/api/v1/cart/items", input));
1006
650
  }
1007
651
  async updateItem(cartItemId, updates) {
1008
652
  if (typeof updates.quantity === "number") {
1009
653
  return this.updateQuantity(cartItemId, updates.quantity);
1010
654
  }
1011
655
  const encodedId = encodeURIComponent(cartItemId);
1012
- return safeWithFallback2(
1013
- () => this.client.patch(`/api/v1/cart/items/${encodedId}`, updates),
1014
- () => this.client.call("cart.updateItem", {
1015
- cart_item_id: cartItemId,
1016
- ...updates
1017
- })
1018
- );
656
+ return safe2(this.client.patch(`/api/v1/cart/items/${encodedId}`, updates));
1019
657
  }
1020
658
  async updateQuantity(cartItemId, quantity) {
1021
659
  const encodedId = encodeURIComponent(cartItemId);
1022
- return safeWithFallback2(
1023
- () => this.client.patch(`/api/v1/cart/items/${encodedId}`, {
1024
- quantity
1025
- }),
1026
- () => this.client.call("cart.updateItemQuantity", {
1027
- cart_item_id: cartItemId,
660
+ return safe2(
661
+ this.client.patch(`/api/v1/cart/items/${encodedId}`, {
1028
662
  quantity
1029
663
  })
1030
664
  );
1031
665
  }
1032
666
  async removeItem(cartItemId) {
1033
667
  const encodedId = encodeURIComponent(cartItemId);
1034
- return safeWithFallback2(
1035
- () => this.client.delete(`/api/v1/cart/items/${encodedId}`),
1036
- () => this.client.call("cart.removeItem", {
1037
- cart_item_id: cartItemId
1038
- })
1039
- );
668
+ return safe2(this.client.delete(`/api/v1/cart/items/${encodedId}`));
1040
669
  }
1041
670
  async clear() {
1042
- return safeWithFallback2(
1043
- () => this.client.delete("/api/v1/cart"),
1044
- () => this.client.call("cart.clearCart")
1045
- );
671
+ return safe2(this.client.delete("/api/v1/cart"));
1046
672
  }
1047
673
  async applyCoupon(code) {
1048
- return safeWithFallback2(
1049
- () => this.client.post("/api/v1/cart/coupons", {
1050
- coupon_code: code
1051
- }),
1052
- () => this.client.call("cart.applyCoupon", {
674
+ return safe2(
675
+ this.client.post("/api/v1/cart/coupons", {
1053
676
  coupon_code: code
1054
677
  })
1055
678
  );
1056
679
  }
1057
680
  async removeCoupon() {
1058
- return safeWithFallback2(
1059
- () => this.client.delete("/api/v1/cart/coupons/current"),
1060
- () => this.client.call("cart.removeCoupon")
1061
- );
681
+ return safe2(this.client.delete("/api/v1/cart/coupons/current"));
1062
682
  }
1063
683
  async isEmpty() {
1064
684
  const countResult = await this.getCount();
@@ -1095,105 +715,6 @@ var CartOperations = class {
1095
715
  }
1096
716
  };
1097
717
 
1098
- // src/constants.ts
1099
- var CHECKOUT_MODE = {
1100
- LINK: "link",
1101
- GUEST: "guest"
1102
- };
1103
- var ORDER_TYPE = {
1104
- DELIVERY: "delivery",
1105
- PICKUP: "pickup",
1106
- DINE_IN: "dine-in",
1107
- WALK_IN: "walk-in"
1108
- };
1109
- var PAYMENT_METHOD = {
1110
- MOBILE_MONEY: "mobile_money",
1111
- CARD: "card"
1112
- };
1113
- var CHECKOUT_STEP = {
1114
- AUTHENTICATION: "authentication",
1115
- ORDER_DETAILS: "order_details",
1116
- PAYMENT_METHOD: "payment_method",
1117
- PAYMENT: "payment",
1118
- CONFIRMATION: "confirmation"
1119
- };
1120
- var PAYMENT_STATE = {
1121
- INITIAL: "initial",
1122
- PREPARING: "preparing",
1123
- PROCESSING: "processing",
1124
- VERIFYING: "verifying",
1125
- AWAITING_AUTHORIZATION: "awaiting_authorization",
1126
- SUCCESS: "success",
1127
- ERROR: "error",
1128
- TIMEOUT: "timeout"
1129
- };
1130
- var PICKUP_TIME_TYPE = {
1131
- ASAP: "asap",
1132
- SCHEDULED: "scheduled"
1133
- };
1134
- var MOBILE_MONEY_PROVIDER = {
1135
- MTN: "mtn",
1136
- VODAFONE: "vodafone",
1137
- AIRTEL: "airtel"
1138
- };
1139
- var AUTHORIZATION_TYPE = {
1140
- OTP: "otp",
1141
- PIN: "pin",
1142
- PHONE: "phone",
1143
- BIRTHDAY: "birthday",
1144
- ADDRESS: "address"
1145
- };
1146
- var DEVICE_TYPE = {
1147
- MOBILE: "mobile",
1148
- DESKTOP: "desktop",
1149
- TABLET: "tablet"
1150
- };
1151
- var CONTACT_TYPE = {
1152
- PHONE: "phone",
1153
- EMAIL: "email"
1154
- };
1155
- var LINK_QUERY = {
1156
- DATA: "link.data",
1157
- ADDRESSES: "link.addresses",
1158
- MOBILE_MONEY: "link.mobile_money",
1159
- PREFERENCES: "link.preferences",
1160
- SESSIONS: "link.sessions"
1161
- };
1162
- var LINK_MUTATION = {
1163
- CHECK_STATUS: "link.check_status",
1164
- ENROLL: "link.enroll",
1165
- ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
1166
- UPDATE_PREFERENCES: "link.update_preferences",
1167
- CREATE_ADDRESS: "link.create_address",
1168
- UPDATE_ADDRESS: "link.update_address",
1169
- DELETE_ADDRESS: "link.delete_address",
1170
- SET_DEFAULT_ADDRESS: "link.set_default_address",
1171
- TRACK_ADDRESS_USAGE: "link.track_address_usage",
1172
- CREATE_MOBILE_MONEY: "link.create_mobile_money",
1173
- DELETE_MOBILE_MONEY: "link.delete_mobile_money",
1174
- SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
1175
- TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
1176
- VERIFY_MOBILE_MONEY: "link.verify_mobile_money",
1177
- REVOKE_SESSION: "link.revoke_session",
1178
- REVOKE_ALL_SESSIONS: "link.revoke_all_sessions"
1179
- };
1180
- var AUTH_MUTATION = {
1181
- REQUEST_OTP: "auth.request_otp",
1182
- VERIFY_OTP: "auth.verify_otp"
1183
- };
1184
- var CHECKOUT_MUTATION = {
1185
- PROCESS: "checkout.process"
1186
- };
1187
- var PAYMENT_MUTATION = {
1188
- SUBMIT_AUTHORIZATION: "payment.submit_authorization",
1189
- CHECK_STATUS: "order.poll_payment_status"
1190
- };
1191
- var ORDER_MUTATION = {
1192
- UPDATE_CUSTOMER: "order.update_order_customer"
1193
- };
1194
- var DEFAULT_CURRENCY = "GHS";
1195
- var DEFAULT_COUNTRY = "GHA";
1196
-
1197
718
  // src/utils/price.ts
1198
719
  var CURRENCY_SYMBOLS = {
1199
720
  // Major world currencies
@@ -2220,14 +1741,6 @@ async function safe3(promise) {
2220
1741
  return err(toCimplifyError3(error));
2221
1742
  }
2222
1743
  }
2223
- async function safeWithFallback3(primary, fallback) {
2224
- const primaryResult = await safe3(primary());
2225
- if (primaryResult.ok) return primaryResult;
2226
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2227
- return primaryResult;
2228
- }
2229
- return safe3(fallback());
2230
- }
2231
1744
  function toTerminalFailure(code, message, recoverable) {
2232
1745
  return {
2233
1746
  success: false,
@@ -2259,11 +1772,8 @@ var CheckoutService = class {
2259
1772
  ...data,
2260
1773
  idempotency_key: data.idempotency_key || generateIdempotencyKey()
2261
1774
  };
2262
- const result = await safeWithFallback3(
2263
- () => this.client.post("/api/v1/checkout", {
2264
- checkout_data: checkoutData
2265
- }),
2266
- () => this.client.call(CHECKOUT_MUTATION.PROCESS, {
1775
+ const result = await safe3(
1776
+ this.client.post("/api/v1/checkout", {
2267
1777
  checkout_data: checkoutData
2268
1778
  })
2269
1779
  );
@@ -2272,45 +1782,32 @@ var CheckoutService = class {
2272
1782
  }
2273
1783
  return result;
2274
1784
  }
2275
- async initializePayment(orderId, method) {
2276
- return safe3(
2277
- this.client.call("order.initializePayment", {
2278
- order_id: orderId,
2279
- payment_method: method
2280
- })
1785
+ async initializePayment(_orderId, _method) {
1786
+ return err(
1787
+ new CimplifyError(
1788
+ "NOT_IMPLEMENTED",
1789
+ "initializePayment is not available in REST mode.",
1790
+ false
1791
+ )
2281
1792
  );
2282
1793
  }
2283
1794
  async submitAuthorization(input) {
2284
- return safeWithFallback3(
2285
- () => this.client.post("/api/v1/payments/authorization", input),
2286
- () => this.client.call(PAYMENT_MUTATION.SUBMIT_AUTHORIZATION, input)
2287
- );
1795
+ return safe3(this.client.post("/api/v1/payments/authorization", input));
2288
1796
  }
2289
1797
  async pollPaymentStatus(orderId) {
2290
1798
  const encodedId = encodeURIComponent(orderId);
2291
1799
  const tokenParam = this.orderTokenParam(orderId);
2292
- return safeWithFallback3(
2293
- () => this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`),
2294
- () => this.client.call(PAYMENT_MUTATION.CHECK_STATUS, orderId)
2295
- );
1800
+ return safe3(this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`));
2296
1801
  }
2297
1802
  async updateOrderCustomer(orderId, customer) {
2298
1803
  const encodedId = encodeURIComponent(orderId);
2299
1804
  const tokenParam = this.orderTokenParam(orderId);
2300
- return safeWithFallback3(
2301
- () => this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer),
2302
- () => this.client.call(ORDER_MUTATION.UPDATE_CUSTOMER, {
2303
- order_id: orderId,
2304
- ...customer
2305
- })
2306
- );
1805
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer));
2307
1806
  }
2308
1807
  async verifyPayment(orderId) {
2309
- return safe3(
2310
- this.client.call("order.verifyPayment", {
2311
- order_id: orderId
2312
- })
2313
- );
1808
+ const encodedId = encodeURIComponent(orderId);
1809
+ const tokenParam = this.orderTokenParam(orderId);
1810
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/verify-payment${tokenParam}`));
2314
1811
  }
2315
1812
  async processAndResolve(data) {
2316
1813
  data.on_status_change?.("preparing", {});
@@ -2429,14 +1926,6 @@ async function safe4(promise) {
2429
1926
  return err(toCimplifyError4(error));
2430
1927
  }
2431
1928
  }
2432
- async function safeWithFallback4(primary, fallback) {
2433
- const primaryResult = await safe4(primary());
2434
- if (primaryResult.ok) return primaryResult;
2435
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2436
- return primaryResult;
2437
- }
2438
- return safe4(fallback());
2439
- }
2440
1929
  var OrderQueries = class {
2441
1930
  constructor(client) {
2442
1931
  this.client = client;
@@ -2446,37 +1935,20 @@ var OrderQueries = class {
2446
1935
  return token ? `?token=${encodeURIComponent(token)}` : "";
2447
1936
  }
2448
1937
  async list(options) {
2449
- let query2 = "orders";
2450
- if (options?.status) {
2451
- query2 += `[?(@.status=='${options.status}')]`;
2452
- }
2453
- query2 += "#sort(created_at,desc)";
2454
- if (options?.limit) {
2455
- query2 += `#limit(${options.limit})`;
2456
- }
2457
- if (options?.offset) {
2458
- query2 += `#offset(${options.offset})`;
2459
- }
2460
1938
  const params = new URLSearchParams();
2461
1939
  if (options?.status) params.set("status", options.status);
2462
1940
  if (options?.limit) params.set("limit", String(options.limit));
2463
1941
  if (options?.offset) params.set("offset", String(options.offset));
2464
1942
  const path = params.toString() ? `/api/v1/orders?${params.toString()}` : "/api/v1/orders";
2465
- return safeWithFallback4(
2466
- () => this.client.get(path),
2467
- () => this.client.query(query2)
2468
- );
1943
+ return safe4(this.client.get(path));
2469
1944
  }
2470
1945
  async get(orderId) {
2471
1946
  const encodedId = encodeURIComponent(orderId);
2472
1947
  const tokenParam = this.orderTokenParam(orderId);
2473
- return safeWithFallback4(
2474
- () => this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`),
2475
- () => this.client.query(`orders.${orderId}`)
2476
- );
1948
+ return safe4(this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`));
2477
1949
  }
2478
1950
  async getRecent(limit = 5) {
2479
- return safe4(this.client.query(`orders#sort(created_at,desc)#limit(${limit})`));
1951
+ return this.list({ limit });
2480
1952
  }
2481
1953
  async getByStatus(status) {
2482
1954
  return this.list({ status });
@@ -2484,12 +1956,8 @@ var OrderQueries = class {
2484
1956
  async cancel(orderId, reason) {
2485
1957
  const encodedId = encodeURIComponent(orderId);
2486
1958
  const tokenParam = this.orderTokenParam(orderId);
2487
- return safeWithFallback4(
2488
- () => this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
2489
- reason
2490
- }),
2491
- () => this.client.call("order.cancelOrder", {
2492
- order_id: orderId,
1959
+ return safe4(
1960
+ this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
2493
1961
  reason
2494
1962
  })
2495
1963
  );
@@ -2511,6 +1979,38 @@ async function safe5(promise) {
2511
1979
  return err(toCimplifyError5(error));
2512
1980
  }
2513
1981
  }
1982
+ function encodePathSegment(value) {
1983
+ return encodeURIComponent(value);
1984
+ }
1985
+ function toCreateAddressPayload(input) {
1986
+ return {
1987
+ label: input.label,
1988
+ street_address: input.address_line1,
1989
+ apartment: input.address_line2,
1990
+ city: input.city,
1991
+ region: input.state ?? "",
1992
+ postal_code: input.postal_code,
1993
+ country: input.country
1994
+ };
1995
+ }
1996
+ function toUpdateAddressPayload(input) {
1997
+ return {
1998
+ label: input.label,
1999
+ street_address: input.address_line1,
2000
+ apartment: input.address_line2,
2001
+ city: input.city,
2002
+ region: input.state,
2003
+ postal_code: input.postal_code,
2004
+ country: input.country
2005
+ };
2006
+ }
2007
+ function toCreateMobileMoneyPayload(input) {
2008
+ return {
2009
+ phone_number: input.phone_number,
2010
+ provider: input.provider,
2011
+ label: input.account_name
2012
+ };
2013
+ }
2514
2014
  var LinkService = class {
2515
2015
  constructor(client) {
2516
2016
  this.client = client;
@@ -2538,11 +2038,7 @@ var LinkService = class {
2538
2038
  return result;
2539
2039
  }
2540
2040
  async checkStatus(contact) {
2541
- return safe5(
2542
- this.client.call(LINK_MUTATION.CHECK_STATUS, {
2543
- contact
2544
- })
2545
- );
2041
+ return safe5(this.client.linkPost("/v1/link/check-status", { contact }));
2546
2042
  }
2547
2043
  async getLinkData() {
2548
2044
  return safe5(this.client.linkGet("/v1/link/data"));
@@ -2554,61 +2050,85 @@ var LinkService = class {
2554
2050
  return safe5(this.client.linkGet("/v1/link/mobile-money"));
2555
2051
  }
2556
2052
  async getPreferences() {
2557
- return safe5(this.client.query(LINK_QUERY.PREFERENCES));
2053
+ return safe5(this.client.linkGet("/v1/link/preferences"));
2558
2054
  }
2559
2055
  async enroll(data) {
2560
- return safe5(this.client.call(LINK_MUTATION.ENROLL, data));
2056
+ return safe5(this.client.linkPost("/v1/link/enroll", data));
2561
2057
  }
2562
2058
  async enrollAndLinkOrder(data) {
2563
2059
  return safe5(
2564
- this.client.call(LINK_MUTATION.ENROLL_AND_LINK_ORDER, data)
2060
+ this.client.linkPost("/v1/link/enroll-and-link-order", data)
2565
2061
  );
2566
2062
  }
2567
2063
  async updatePreferences(preferences) {
2568
- return safe5(this.client.call(LINK_MUTATION.UPDATE_PREFERENCES, preferences));
2064
+ return safe5(this.client.linkPost("/v1/link/preferences", preferences));
2569
2065
  }
2570
2066
  async createAddress(input) {
2571
- return safe5(this.client.call(LINK_MUTATION.CREATE_ADDRESS, input));
2067
+ return safe5(
2068
+ this.client.linkPost("/v1/link/addresses", toCreateAddressPayload(input))
2069
+ );
2572
2070
  }
2573
2071
  async updateAddress(input) {
2574
- return safe5(this.client.call(LINK_MUTATION.UPDATE_ADDRESS, input));
2072
+ return safe5(
2073
+ this.client.linkPost(
2074
+ `/v1/link/addresses/${encodePathSegment(input.address_id)}`,
2075
+ toUpdateAddressPayload(input)
2076
+ )
2077
+ );
2575
2078
  }
2576
2079
  async deleteAddress(addressId) {
2577
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2080
+ return safe5(
2081
+ this.client.linkDelete(`/v1/link/addresses/${encodePathSegment(addressId)}`)
2082
+ );
2578
2083
  }
2579
2084
  async setDefaultAddress(addressId) {
2580
- return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
2085
+ return safe5(
2086
+ this.client.linkPost(
2087
+ `/v1/link/addresses/${encodePathSegment(addressId)}/default`
2088
+ )
2089
+ );
2581
2090
  }
2582
2091
  async trackAddressUsage(addressId) {
2583
2092
  return safe5(
2584
- this.client.call(LINK_MUTATION.TRACK_ADDRESS_USAGE, {
2585
- address_id: addressId
2586
- })
2093
+ this.client.linkPost(
2094
+ `/v1/link/addresses/${encodePathSegment(addressId)}/track-usage`
2095
+ )
2587
2096
  );
2588
2097
  }
2589
2098
  async createMobileMoney(input) {
2590
- return safe5(this.client.call(LINK_MUTATION.CREATE_MOBILE_MONEY, input));
2099
+ return safe5(
2100
+ this.client.linkPost(
2101
+ "/v1/link/mobile-money",
2102
+ toCreateMobileMoneyPayload(input)
2103
+ )
2104
+ );
2591
2105
  }
2592
2106
  async deleteMobileMoney(mobileMoneyId) {
2593
2107
  return safe5(
2594
- this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`)
2108
+ this.client.linkDelete(
2109
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}`
2110
+ )
2595
2111
  );
2596
2112
  }
2597
2113
  async setDefaultMobileMoney(mobileMoneyId) {
2598
2114
  return safe5(
2599
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2115
+ this.client.linkPost(
2116
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/default`
2117
+ )
2600
2118
  );
2601
2119
  }
2602
2120
  async trackMobileMoneyUsage(mobileMoneyId) {
2603
2121
  return safe5(
2604
- this.client.call(LINK_MUTATION.TRACK_MOBILE_MONEY_USAGE, {
2605
- mobile_money_id: mobileMoneyId
2606
- })
2122
+ this.client.linkPost(
2123
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/track-usage`
2124
+ )
2607
2125
  );
2608
2126
  }
2609
2127
  async verifyMobileMoney(mobileMoneyId) {
2610
2128
  return safe5(
2611
- this.client.call(LINK_MUTATION.VERIFY_MOBILE_MONEY, mobileMoneyId)
2129
+ this.client.linkPost(
2130
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/verify`
2131
+ )
2612
2132
  );
2613
2133
  }
2614
2134
  async getSessions() {
@@ -2621,30 +2141,28 @@ var LinkService = class {
2621
2141
  return safe5(this.client.linkDelete("/v1/link/sessions"));
2622
2142
  }
2623
2143
  async getAddressesRest() {
2624
- return safe5(this.client.linkGet("/v1/link/addresses"));
2144
+ return this.getAddresses();
2625
2145
  }
2626
2146
  async createAddressRest(input) {
2627
- return safe5(this.client.linkPost("/v1/link/addresses", input));
2147
+ return this.createAddress(input);
2628
2148
  }
2629
2149
  async deleteAddressRest(addressId) {
2630
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2150
+ return this.deleteAddress(addressId);
2631
2151
  }
2632
2152
  async setDefaultAddressRest(addressId) {
2633
- return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
2153
+ return this.setDefaultAddress(addressId);
2634
2154
  }
2635
2155
  async getMobileMoneyRest() {
2636
- return safe5(this.client.linkGet("/v1/link/mobile-money"));
2156
+ return this.getMobileMoney();
2637
2157
  }
2638
2158
  async createMobileMoneyRest(input) {
2639
- return safe5(this.client.linkPost("/v1/link/mobile-money", input));
2159
+ return this.createMobileMoney(input);
2640
2160
  }
2641
2161
  async deleteMobileMoneyRest(mobileMoneyId) {
2642
- return safe5(this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`));
2162
+ return this.deleteMobileMoney(mobileMoneyId);
2643
2163
  }
2644
2164
  async setDefaultMobileMoneyRest(mobileMoneyId) {
2645
- return safe5(
2646
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2647
- );
2165
+ return this.setDefaultMobileMoney(mobileMoneyId);
2648
2166
  }
2649
2167
  };
2650
2168
 
@@ -2663,23 +2181,12 @@ async function safe6(promise) {
2663
2181
  return err(toCimplifyError6(error));
2664
2182
  }
2665
2183
  }
2666
- async function safeWithFallback5(primary, fallback) {
2667
- const primaryResult = await safe6(primary());
2668
- if (primaryResult.ok) return primaryResult;
2669
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2670
- return primaryResult;
2671
- }
2672
- return safe6(fallback());
2673
- }
2674
2184
  var AuthService = class {
2675
2185
  constructor(client) {
2676
2186
  this.client = client;
2677
2187
  }
2678
2188
  async getStatus() {
2679
- return safeWithFallback5(
2680
- () => this.client.get("/api/v1/auth/status"),
2681
- () => this.client.query("auth")
2682
- );
2189
+ return safe6(this.client.get("/api/v1/auth/status"));
2683
2190
  }
2684
2191
  async getCurrentUser() {
2685
2192
  const result = await this.getStatus();
@@ -2692,43 +2199,26 @@ var AuthService = class {
2692
2199
  return ok(result.value.is_authenticated);
2693
2200
  }
2694
2201
  async requestOtp(contact, contactType) {
2695
- return safeWithFallback5(
2696
- () => this.client.post("/api/v1/auth/request-otp", {
2697
- contact,
2698
- contact_type: contactType
2699
- }),
2700
- () => this.client.call(AUTH_MUTATION.REQUEST_OTP, {
2202
+ return safe6(
2203
+ this.client.post("/api/v1/auth/request-otp", {
2701
2204
  contact,
2702
2205
  contact_type: contactType
2703
2206
  })
2704
2207
  );
2705
2208
  }
2706
2209
  async verifyOtp(code, contact) {
2707
- return safeWithFallback5(
2708
- () => this.client.post("/api/v1/auth/verify-otp", {
2709
- otp_code: code,
2710
- contact
2711
- }),
2712
- () => this.client.call(AUTH_MUTATION.VERIFY_OTP, {
2210
+ return safe6(
2211
+ this.client.post("/api/v1/auth/verify-otp", {
2713
2212
  otp_code: code,
2714
2213
  contact
2715
2214
  })
2716
2215
  );
2717
2216
  }
2718
2217
  async logout() {
2719
- return safeWithFallback5(
2720
- () => this.client.post("/api/v1/auth/logout"),
2721
- () => this.client.call("auth.logout")
2722
- );
2218
+ return safe6(this.client.post("/api/v1/auth/logout"));
2723
2219
  }
2724
2220
  async updateProfile(input) {
2725
- return safe6(this.client.call("auth.update_profile", input));
2726
- }
2727
- async changePassword(input) {
2728
- return safe6(this.client.call("auth.change_password", input));
2729
- }
2730
- async resetPassword(email) {
2731
- return safe6(this.client.call("auth.reset_password", { email }));
2221
+ return safe6(this.client.post("/api/v1/auth/profile", input));
2732
2222
  }
2733
2223
  };
2734
2224
 
@@ -2747,47 +2237,29 @@ async function safe7(promise) {
2747
2237
  return err(toCimplifyError7(error));
2748
2238
  }
2749
2239
  }
2750
- async function safeWithFallback6(primary, fallback) {
2751
- const primaryResult = await safe7(primary());
2752
- if (primaryResult.ok) return primaryResult;
2753
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2754
- return primaryResult;
2755
- }
2756
- return safe7(fallback());
2757
- }
2758
2240
  var BusinessService = class {
2759
2241
  constructor(client) {
2760
2242
  this.client = client;
2761
2243
  }
2762
2244
  async getInfo() {
2763
- return safeWithFallback6(
2764
- () => this.client.get("/api/v1/business"),
2765
- () => this.client.query("business.info")
2766
- );
2245
+ return safe7(this.client.get("/api/v1/business"));
2767
2246
  }
2768
2247
  async getByHandle(handle) {
2769
- return safe7(this.client.query(`business.handle.${handle}`));
2248
+ const encodedHandle = encodeURIComponent(handle);
2249
+ return safe7(this.client.get(`/api/v1/business/by-handle/${encodedHandle}`));
2770
2250
  }
2771
2251
  async getByDomain(domain) {
2772
- return safe7(this.client.query("business.domain", { domain }));
2252
+ const encodedDomain = encodeURIComponent(domain);
2253
+ return safe7(this.client.get(`/api/v1/business/by-domain?domain=${encodedDomain}`));
2773
2254
  }
2774
2255
  async getSettings() {
2775
- return safeWithFallback6(
2776
- () => this.client.get("/api/v1/business/settings"),
2777
- () => this.client.query("business.settings")
2778
- );
2256
+ return safe7(this.client.get("/api/v1/business/settings"));
2779
2257
  }
2780
2258
  async getTheme() {
2781
- return safeWithFallback6(
2782
- () => this.client.get("/api/v1/business/theme"),
2783
- () => this.client.query("business.theme")
2784
- );
2259
+ return safe7(this.client.get("/api/v1/business/theme"));
2785
2260
  }
2786
2261
  async getLocations() {
2787
- return safeWithFallback6(
2788
- () => this.client.get("/api/v1/business/locations"),
2789
- () => this.client.query("business.locations")
2790
- );
2262
+ return safe7(this.client.get("/api/v1/business/locations"));
2791
2263
  }
2792
2264
  async getLocation(locationId) {
2793
2265
  const result = await this.getLocations();
@@ -2799,10 +2271,7 @@ var BusinessService = class {
2799
2271
  return ok(location);
2800
2272
  }
2801
2273
  async getHours() {
2802
- return safeWithFallback6(
2803
- () => this.client.get("/api/v1/business/hours"),
2804
- () => this.client.query("business.hours")
2805
- );
2274
+ return safe7(this.client.get("/api/v1/business/hours"));
2806
2275
  }
2807
2276
  async getLocationHours(locationId) {
2808
2277
  const result = await this.getHours();
@@ -2810,31 +2279,7 @@ var BusinessService = class {
2810
2279
  return ok(result.value.filter((hour) => hour.location_id === locationId));
2811
2280
  }
2812
2281
  async getBootstrap() {
2813
- const restBootstrap = await safe7(this.client.get("/api/v1/bootstrap"));
2814
- if (restBootstrap.ok) {
2815
- return restBootstrap;
2816
- }
2817
- const [businessResult, locationsResult, categoriesResult] = await Promise.all([
2818
- this.getInfo(),
2819
- this.getLocations(),
2820
- safe7(this.client.query("categories#select(id,name,slug)"))
2821
- ]);
2822
- if (!businessResult.ok) return businessResult;
2823
- if (!locationsResult.ok) return locationsResult;
2824
- if (!categoriesResult.ok) return categoriesResult;
2825
- const business = businessResult.value;
2826
- const locations = locationsResult.value;
2827
- const categories = categoriesResult.value;
2828
- const defaultLocation = locations[0];
2829
- return ok({
2830
- business,
2831
- location: defaultLocation,
2832
- locations,
2833
- categories,
2834
- currency: business.default_currency,
2835
- is_open: defaultLocation?.accepts_online_orders ?? false,
2836
- accepts_orders: defaultLocation?.accepts_online_orders ?? false
2837
- });
2282
+ return safe7(this.client.get("/api/v1/bootstrap"));
2838
2283
  }
2839
2284
  };
2840
2285
 
@@ -2857,49 +2302,47 @@ var InventoryService = class {
2857
2302
  constructor(client) {
2858
2303
  this.client = client;
2859
2304
  }
2305
+ withQuery(path, params) {
2306
+ const searchParams = new URLSearchParams();
2307
+ for (const [key, value] of Object.entries(params)) {
2308
+ if (value === void 0) continue;
2309
+ searchParams.set(key, String(value));
2310
+ }
2311
+ const query2 = searchParams.toString();
2312
+ return query2 ? `${path}?${query2}` : path;
2313
+ }
2860
2314
  async getStockLevels() {
2861
- return safe8(this.client.query("inventory.stock_levels"));
2315
+ return safe8(this.client.get("/api/v1/inventory/stock-levels"));
2862
2316
  }
2863
2317
  async getProductStock(productId, locationId) {
2864
- if (locationId) {
2865
- return safe8(
2866
- this.client.query("inventory.product", {
2867
- product_id: productId,
2868
- location_id: locationId
2869
- })
2870
- );
2871
- }
2872
- return safe8(
2873
- this.client.query("inventory.product", {
2874
- product_id: productId
2875
- })
2876
- );
2318
+ const encodedId = encodeURIComponent(productId);
2319
+ const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/stock`, {
2320
+ location_id: locationId
2321
+ });
2322
+ return safe8(this.client.get(path));
2877
2323
  }
2878
2324
  async getVariantStock(variantId, locationId) {
2879
- return safe8(
2880
- this.client.query("inventory.variant", {
2881
- variant_id: variantId,
2882
- location_id: locationId
2883
- })
2884
- );
2325
+ const encodedId = encodeURIComponent(variantId);
2326
+ const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/stock`, {
2327
+ location_id: locationId
2328
+ });
2329
+ return safe8(this.client.get(path));
2885
2330
  }
2886
2331
  async checkProductAvailability(productId, quantity, locationId) {
2887
- return safe8(
2888
- this.client.query("inventory.check_availability", {
2889
- product_id: productId,
2890
- quantity,
2891
- location_id: locationId
2892
- })
2893
- );
2332
+ const encodedId = encodeURIComponent(productId);
2333
+ const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/availability`, {
2334
+ quantity,
2335
+ location_id: locationId
2336
+ });
2337
+ return safe8(this.client.get(path));
2894
2338
  }
2895
2339
  async checkVariantAvailability(variantId, quantity, locationId) {
2896
- return safe8(
2897
- this.client.query("inventory.check_availability", {
2898
- variant_id: variantId,
2899
- quantity,
2900
- location_id: locationId
2901
- })
2902
- );
2340
+ const encodedId = encodeURIComponent(variantId);
2341
+ const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/availability`, {
2342
+ quantity,
2343
+ location_id: locationId
2344
+ });
2345
+ return safe8(this.client.get(path));
2903
2346
  }
2904
2347
  async checkMultipleAvailability(items, locationId) {
2905
2348
  const results = await Promise.all(
@@ -2913,7 +2356,7 @@ var InventoryService = class {
2913
2356
  return ok(results.map((r) => r.value));
2914
2357
  }
2915
2358
  async getSummary() {
2916
- return safe8(this.client.query("inventory.summary"));
2359
+ return safe8(this.client.get("/api/v1/inventory/summary"));
2917
2360
  }
2918
2361
  async isInStock(productId, locationId) {
2919
2362
  const result = await this.checkProductAvailability(productId, 1, locationId);
@@ -2928,9 +2371,6 @@ var InventoryService = class {
2928
2371
  };
2929
2372
 
2930
2373
  // src/scheduling.ts
2931
- function toVariables(input) {
2932
- return Object.fromEntries(Object.entries(input));
2933
- }
2934
2374
  function toCimplifyError9(error) {
2935
2375
  if (error instanceof CimplifyError) return error;
2936
2376
  if (error instanceof Error) {
@@ -2945,68 +2385,110 @@ async function safe9(promise) {
2945
2385
  return err(toCimplifyError9(error));
2946
2386
  }
2947
2387
  }
2388
+ function withQuery2(path, params) {
2389
+ const searchParams = new URLSearchParams();
2390
+ for (const [key, value] of Object.entries(params)) {
2391
+ if (value === void 0) continue;
2392
+ searchParams.set(key, String(value));
2393
+ }
2394
+ const query2 = searchParams.toString();
2395
+ return query2 ? `${path}?${query2}` : path;
2396
+ }
2397
+ function normalizeServiceAvailability(result) {
2398
+ if (Array.isArray(result.days) && result.days.length > 0) {
2399
+ return result;
2400
+ }
2401
+ const days = Array.isArray(result.availability) ? result.availability.map((day) => ({
2402
+ ...day,
2403
+ is_fully_booked: day.is_fully_booked ?? (typeof day.has_availability === "boolean" ? !day.has_availability : void 0)
2404
+ })) : [];
2405
+ return { ...result, days };
2406
+ }
2407
+ function firstScheduledTime(booking) {
2408
+ return booking.service_items.find((item) => typeof item.scheduled_start === "string")?.scheduled_start || booking.created_at;
2409
+ }
2948
2410
  var SchedulingService = class {
2949
2411
  constructor(client) {
2950
2412
  this.client = client;
2951
2413
  }
2952
2414
  async getServices() {
2953
- return safe9(this.client.query("scheduling.services"));
2415
+ return safe9(this.client.get("/api/v1/scheduling/services"));
2954
2416
  }
2955
2417
  /**
2956
- * Get a specific service by ID
2957
- * Note: Filters from all services client-side (no single-service endpoint)
2418
+ * Get a specific service by ID.
2958
2419
  */
2959
2420
  async getService(serviceId) {
2960
2421
  const result = await this.getServices();
2961
2422
  if (!result.ok) return result;
2962
- return ok(result.value.find((s) => s.id === serviceId) || null);
2423
+ return ok(result.value.find((service) => service.id === serviceId) || null);
2963
2424
  }
2964
2425
  async getAvailableSlots(input) {
2965
- return safe9(
2966
- this.client.query("scheduling.slots", toVariables(input))
2967
- );
2426
+ const path = withQuery2("/api/v1/scheduling/slots", {
2427
+ service_id: input.service_id,
2428
+ date: input.date,
2429
+ participant_count: input.participant_count,
2430
+ duration_minutes: input.duration_minutes
2431
+ });
2432
+ return safe9(this.client.get(path));
2968
2433
  }
2969
2434
  async checkSlotAvailability(input) {
2970
- return safe9(
2971
- this.client.query(
2972
- "scheduling.check_availability",
2973
- toVariables(input)
2974
- )
2975
- );
2435
+ const path = withQuery2("/api/v1/scheduling/slots/check", {
2436
+ service_id: input.service_id,
2437
+ slot_time: input.slot_time,
2438
+ duration_minutes: input.duration_minutes,
2439
+ participant_count: input.participant_count
2440
+ });
2441
+ return safe9(this.client.get(path));
2976
2442
  }
2977
2443
  async getServiceAvailability(params) {
2444
+ const path = withQuery2("/api/v1/scheduling/availability", {
2445
+ service_id: params.service_id,
2446
+ start_date: params.start_date,
2447
+ end_date: params.end_date,
2448
+ location_id: params.location_id,
2449
+ participant_count: params.participant_count
2450
+ });
2978
2451
  return safe9(
2979
- this.client.query(
2980
- "scheduling.availability",
2981
- toVariables(params)
2982
- )
2452
+ this.client.get(path).then((result) => normalizeServiceAvailability(result))
2983
2453
  );
2984
2454
  }
2985
2455
  async getBooking(bookingId) {
2986
- return safe9(this.client.query(`scheduling.${bookingId}`));
2456
+ const encodedId = encodeURIComponent(bookingId);
2457
+ return safe9(this.client.get(`/api/v1/scheduling/bookings/${encodedId}`));
2987
2458
  }
2988
- async getCustomerBookings() {
2989
- return safe9(this.client.query("scheduling"));
2459
+ async getCustomerBookings(customerId) {
2460
+ const path = withQuery2("/api/v1/scheduling/bookings", {
2461
+ customer_id: customerId
2462
+ });
2463
+ return safe9(this.client.get(path));
2990
2464
  }
2991
2465
  async getUpcomingBookings() {
2992
- return safe9(
2993
- this.client.query(
2994
- "scheduling[?(@.status!='completed' && @.status!='cancelled')]#sort(start_time,asc)"
2995
- )
2996
- );
2466
+ const result = await this.getCustomerBookings();
2467
+ if (!result.ok) return result;
2468
+ const upcoming = result.value.filter((booking) => {
2469
+ const status = String(booking.status).toLowerCase();
2470
+ return status !== "completed" && status !== "cancelled";
2471
+ }).sort((a, b) => firstScheduledTime(a).localeCompare(firstScheduledTime(b)));
2472
+ return ok(upcoming);
2997
2473
  }
2998
2474
  async getPastBookings(limit = 10) {
2999
- return safe9(
3000
- this.client.query(
3001
- `scheduling[?(@.status=='completed')]#sort(start_time,desc)#limit(${limit})`
3002
- )
3003
- );
2475
+ const result = await this.getCustomerBookings();
2476
+ if (!result.ok) return result;
2477
+ const past = result.value.filter((booking) => String(booking.status).toLowerCase() === "completed").sort((a, b) => firstScheduledTime(b).localeCompare(firstScheduledTime(a))).slice(0, Math.max(0, limit));
2478
+ return ok(past);
3004
2479
  }
3005
2480
  async cancelBooking(input) {
3006
- return safe9(this.client.call("scheduling.cancel_booking", input));
2481
+ const encodedId = encodeURIComponent(input.booking_id);
2482
+ return safe9(
2483
+ this.client.post(`/api/v1/scheduling/bookings/${encodedId}/cancel`, {
2484
+ reason: input.reason
2485
+ })
2486
+ );
3007
2487
  }
3008
2488
  async rescheduleBooking(input) {
3009
- return safe9(this.client.call("scheduling.reschedule_booking", input));
2489
+ return safe9(
2490
+ this.client.post("/api/v1/scheduling/bookings/reschedule", input)
2491
+ );
3010
2492
  }
3011
2493
  async getNextAvailableSlot(serviceId, fromDate) {
3012
2494
  const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -3025,6 +2507,12 @@ var SchedulingService = class {
3025
2507
  if (!result.ok) return result;
3026
2508
  return ok(result.value.some((slot) => slot.is_available));
3027
2509
  }
2510
+ // Compatibility alias for callers typed against the older Booking shape.
2511
+ async getBookingLegacy(bookingId) {
2512
+ const result = await this.getBooking(bookingId);
2513
+ if (!result.ok) return result;
2514
+ return ok(result.value);
2515
+ }
3028
2516
  };
3029
2517
 
3030
2518
  // src/lite.ts
@@ -3047,47 +2535,18 @@ var LiteService = class {
3047
2535
  this.client = client;
3048
2536
  }
3049
2537
  async getBootstrap() {
3050
- return safe10(this.client.query("lite.bootstrap"));
2538
+ return safe10(this.client.get("/api/v1/lite/bootstrap"));
3051
2539
  }
3052
2540
  async getTable(tableId) {
3053
- return safe10(this.client.query(`lite.table.${tableId}`));
3054
- }
3055
- async getTableByNumber(tableNumber, locationId) {
3056
- return safe10(
3057
- this.client.query("lite.table_by_number", {
3058
- table_number: tableNumber,
3059
- location_id: locationId
3060
- })
3061
- );
3062
- }
3063
- async sendToKitchen(tableId, items) {
3064
- return safe10(
3065
- this.client.call("lite.send_to_kitchen", {
3066
- table_id: tableId,
3067
- items
3068
- })
3069
- );
3070
- }
3071
- async callWaiter(tableId, reason) {
3072
- return safe10(
3073
- this.client.call("lite.call_waiter", {
3074
- table_id: tableId,
3075
- reason
3076
- })
3077
- );
3078
- }
3079
- async requestBill(tableId) {
3080
- return safe10(
3081
- this.client.call("lite.request_bill", {
3082
- table_id: tableId
3083
- })
3084
- );
2541
+ const encodedId = encodeURIComponent(tableId);
2542
+ return safe10(this.client.get(`/api/v1/lite/tables/${encodedId}`));
3085
2543
  }
3086
2544
  async getMenu() {
3087
- return safe10(this.client.query("lite.menu"));
2545
+ return safe10(this.client.get("/api/v1/lite/menu"));
3088
2546
  }
3089
2547
  async getMenuByCategory(categoryId) {
3090
- return safe10(this.client.query(`lite.menu.category.${categoryId}`));
2548
+ const encodedId = encodeURIComponent(categoryId);
2549
+ return safe10(this.client.get(`/api/v1/lite/menu/categories/${encodedId}`));
3091
2550
  }
3092
2551
  };
3093
2552
 
@@ -3106,30 +2565,16 @@ async function safe11(promise) {
3106
2565
  return err(toCimplifyError11(error));
3107
2566
  }
3108
2567
  }
3109
- async function safeWithFallback7(primary, fallback) {
3110
- const primaryResult = await safe11(primary());
3111
- if (primaryResult.ok) return primaryResult;
3112
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
3113
- return primaryResult;
3114
- }
3115
- return safe11(fallback());
3116
- }
3117
2568
  var FxService = class {
3118
2569
  constructor(client) {
3119
2570
  this.client = client;
3120
2571
  }
3121
2572
  async getRate(from, to) {
3122
2573
  const path = `/api/v1/fx/rate?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
3123
- return safeWithFallback7(
3124
- () => this.client.get(path),
3125
- () => this.client.call("fx.getRate", { from, to })
3126
- );
2574
+ return safe11(this.client.get(path));
3127
2575
  }
3128
2576
  async lockQuote(request) {
3129
- return safeWithFallback7(
3130
- () => this.client.post("/api/v1/fx/quotes", request),
3131
- () => this.client.call("fx.lockQuote", request)
3132
- );
2577
+ return safe11(this.client.post("/api/v1/fx/quotes", request));
3133
2578
  }
3134
2579
  };
3135
2580
 
@@ -3740,7 +3185,9 @@ function createElements(client, businessId, options) {
3740
3185
 
3741
3186
  // src/client.ts
3742
3187
  var ACCESS_TOKEN_STORAGE_KEY = "cimplify_access_token";
3188
+ var SESSION_TOKEN_STORAGE_KEY = "cimplify_session_token";
3743
3189
  var ORDER_TOKEN_PREFIX = "cimplify_ot_";
3190
+ var SESSION_TOKEN_HEADER = "x-session-token";
3744
3191
  var DEFAULT_TIMEOUT_MS = 3e4;
3745
3192
  var DEFAULT_MAX_RETRIES = 3;
3746
3193
  var DEFAULT_RETRY_DELAY_MS = 1e3;
@@ -3825,6 +3272,7 @@ function getEnvPublicKey() {
3825
3272
  var CimplifyClient = class {
3826
3273
  constructor(config = {}) {
3827
3274
  this.accessToken = null;
3275
+ this.sessionToken = null;
3828
3276
  this.context = {};
3829
3277
  this.businessId = null;
3830
3278
  this.businessIdResolvePromise = null;
@@ -3839,6 +3287,7 @@ var CimplifyClient = class {
3839
3287
  this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
3840
3288
  this.hooks = config.hooks ?? {};
3841
3289
  this.accessToken = this.loadAccessToken();
3290
+ this.sessionToken = this.loadSessionToken();
3842
3291
  if (!this.publicKey && !config.suppressPublicKeyWarning) {
3843
3292
  console.warn(
3844
3293
  '[Cimplify] No public key found. Set NEXT_PUBLIC_CIMPLIFY_PUBLIC_KEY in your environment, or pass { publicKey: "pk_..." } to createCimplifyClient().'
@@ -3875,7 +3324,11 @@ var CimplifyClient = class {
3875
3324
  clearSession() {
3876
3325
  const previous = this.accessToken;
3877
3326
  this.accessToken = null;
3327
+ this.sessionToken = null;
3878
3328
  this.saveAccessToken(null);
3329
+ if (typeof window !== "undefined" && window.localStorage) {
3330
+ localStorage.removeItem(SESSION_TOKEN_STORAGE_KEY);
3331
+ }
3879
3332
  this.hooks.onSessionChange?.({
3880
3333
  previousToken: previous,
3881
3334
  newToken: null,
@@ -3972,6 +3425,27 @@ var CimplifyClient = class {
3972
3425
  }
3973
3426
  }
3974
3427
  }
3428
+ loadSessionToken() {
3429
+ if (typeof window !== "undefined" && window.localStorage) {
3430
+ return localStorage.getItem(SESSION_TOKEN_STORAGE_KEY);
3431
+ }
3432
+ return null;
3433
+ }
3434
+ saveSessionToken(token) {
3435
+ if (typeof window !== "undefined" && window.localStorage) {
3436
+ try {
3437
+ localStorage.setItem(SESSION_TOKEN_STORAGE_KEY, token);
3438
+ } catch {
3439
+ }
3440
+ }
3441
+ }
3442
+ captureSessionToken(response) {
3443
+ const token = response.headers.get(SESSION_TOKEN_HEADER);
3444
+ if (token && token !== this.sessionToken) {
3445
+ this.sessionToken = token;
3446
+ this.saveSessionToken(token);
3447
+ }
3448
+ }
3975
3449
  getHeaders() {
3976
3450
  const headers = {
3977
3451
  "Content-Type": "application/json"
@@ -3983,6 +3457,9 @@ var CimplifyClient = class {
3983
3457
  if (this.accessToken) {
3984
3458
  headers["Authorization"] = `Bearer ${this.accessToken}`;
3985
3459
  }
3460
+ if (this.sessionToken) {
3461
+ headers[SESSION_TOKEN_HEADER] = this.sessionToken;
3462
+ }
3986
3463
  return headers;
3987
3464
  }
3988
3465
  async resilientFetch(url, options) {
@@ -4008,6 +3485,7 @@ var CimplifyClient = class {
4008
3485
  signal: controller.signal
4009
3486
  });
4010
3487
  clearTimeout(timeoutId);
3488
+ this.captureSessionToken(response);
4011
3489
  if (response.ok) {
4012
3490
  this.hooks.onRequestSuccess?.({
4013
3491
  ...context,
@@ -4105,41 +3583,6 @@ var CimplifyClient = class {
4105
3583
  this.inflightRequests.set(key, request);
4106
3584
  return request;
4107
3585
  }
4108
- async query(query2, variables) {
4109
- const body = { query: query2 };
4110
- if (variables) {
4111
- body.variables = variables;
4112
- }
4113
- if (Object.keys(this.context).length > 0) {
4114
- body.context = this.context;
4115
- }
4116
- const key = this.getDedupeKey("query", body);
4117
- return this.deduplicatedRequest(key, async () => {
4118
- const response = await this.resilientFetch(`${this.baseUrl}/api/q`, {
4119
- method: "POST",
4120
- credentials: this.credentials,
4121
- headers: this.getHeaders(),
4122
- body: JSON.stringify(body)
4123
- });
4124
- return this.handleResponse(response);
4125
- });
4126
- }
4127
- async call(method, args) {
4128
- const body = {
4129
- method,
4130
- args: args !== void 0 ? [args] : []
4131
- };
4132
- if (Object.keys(this.context).length > 0) {
4133
- body.context = this.context;
4134
- }
4135
- const response = await this.resilientFetch(`${this.baseUrl}/api/m`, {
4136
- method: "POST",
4137
- credentials: this.credentials,
4138
- headers: this.getHeaders(),
4139
- body: JSON.stringify(body)
4140
- });
4141
- return this.handleResponse(response);
4142
- }
4143
3586
  async get(path) {
4144
3587
  const key = this.getDedupeKey("get", path);
4145
3588
  return this.deduplicatedRequest(key, async () => {
@@ -4242,26 +3685,6 @@ var CimplifyClient = class {
4242
3685
  }
4243
3686
  return json;
4244
3687
  }
4245
- async handleResponse(response) {
4246
- const json = await response.json();
4247
- if (!json.success || json.error) {
4248
- const error = enrichError(
4249
- new CimplifyError(
4250
- json.error?.code || "UNKNOWN_ERROR",
4251
- json.error?.message || "An unknown error occurred",
4252
- json.error?.retryable || false
4253
- ),
4254
- { isTestMode: this.isTestMode() }
4255
- );
4256
- if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
4257
- console.warn(
4258
- "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
4259
- );
4260
- }
4261
- throw error;
4262
- }
4263
- return json.data;
4264
- }
4265
3688
  get catalogue() {
4266
3689
  if (!this._catalogue) {
4267
3690
  this._catalogue = new CatalogueQueries(this);
@@ -4353,4 +3776,171 @@ function createCimplifyClient(config = {}) {
4353
3776
  return new CimplifyClient(config);
4354
3777
  }
4355
3778
 
3779
+ // src/query/builder.ts
3780
+ function escapeQueryValue(value) {
3781
+ return value.replace(/'/g, "\\'");
3782
+ }
3783
+ var QueryBuilder = class {
3784
+ constructor(entity) {
3785
+ this.filters = [];
3786
+ this.modifiers = [];
3787
+ this.pathSegments = [];
3788
+ this.entity = entity;
3789
+ }
3790
+ path(segment) {
3791
+ this.pathSegments.push(segment);
3792
+ return this;
3793
+ }
3794
+ where(field, op, value) {
3795
+ const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
3796
+ if (op === "contains" || op === "startsWith") {
3797
+ this.filters.push(`@.${field} ${op} ${v}`);
3798
+ } else {
3799
+ this.filters.push(`@.${field}${op}${v}`);
3800
+ }
3801
+ return this;
3802
+ }
3803
+ and(field, op, value) {
3804
+ return this.where(field, op, value);
3805
+ }
3806
+ sort(field, order = "asc") {
3807
+ this.modifiers.push(`sort(${field},${order})`);
3808
+ return this;
3809
+ }
3810
+ limit(n) {
3811
+ this.modifiers.push(`limit(${n})`);
3812
+ return this;
3813
+ }
3814
+ offset(n) {
3815
+ this.modifiers.push(`offset(${n})`);
3816
+ return this;
3817
+ }
3818
+ count() {
3819
+ this.modifiers.push("count");
3820
+ return this;
3821
+ }
3822
+ enriched() {
3823
+ this.modifiers.push("enriched");
3824
+ return this;
3825
+ }
3826
+ build() {
3827
+ let query2 = this.entity;
3828
+ if (this.pathSegments.length > 0) {
3829
+ query2 += "." + this.pathSegments.join(".");
3830
+ }
3831
+ if (this.filters.length > 0) {
3832
+ query2 += `[?(${this.filters.join(" && ")})]`;
3833
+ }
3834
+ for (const mod of this.modifiers) {
3835
+ query2 += `#${mod}`;
3836
+ }
3837
+ return query2;
3838
+ }
3839
+ toString() {
3840
+ return this.build();
3841
+ }
3842
+ };
3843
+ function query(entity) {
3844
+ return new QueryBuilder(entity);
3845
+ }
3846
+
3847
+ // src/constants.ts
3848
+ var CHECKOUT_MODE = {
3849
+ LINK: "link",
3850
+ GUEST: "guest"
3851
+ };
3852
+ var ORDER_TYPE = {
3853
+ DELIVERY: "delivery",
3854
+ PICKUP: "pickup",
3855
+ DINE_IN: "dine-in",
3856
+ WALK_IN: "walk-in"
3857
+ };
3858
+ var PAYMENT_METHOD = {
3859
+ MOBILE_MONEY: "mobile_money",
3860
+ CARD: "card"
3861
+ };
3862
+ var CHECKOUT_STEP = {
3863
+ AUTHENTICATION: "authentication",
3864
+ ORDER_DETAILS: "order_details",
3865
+ PAYMENT_METHOD: "payment_method",
3866
+ PAYMENT: "payment",
3867
+ CONFIRMATION: "confirmation"
3868
+ };
3869
+ var PAYMENT_STATE = {
3870
+ INITIAL: "initial",
3871
+ PREPARING: "preparing",
3872
+ PROCESSING: "processing",
3873
+ VERIFYING: "verifying",
3874
+ AWAITING_AUTHORIZATION: "awaiting_authorization",
3875
+ SUCCESS: "success",
3876
+ ERROR: "error",
3877
+ TIMEOUT: "timeout"
3878
+ };
3879
+ var PICKUP_TIME_TYPE = {
3880
+ ASAP: "asap",
3881
+ SCHEDULED: "scheduled"
3882
+ };
3883
+ var MOBILE_MONEY_PROVIDER = {
3884
+ MTN: "mtn",
3885
+ VODAFONE: "vodafone",
3886
+ AIRTEL: "airtel"
3887
+ };
3888
+ var AUTHORIZATION_TYPE = {
3889
+ OTP: "otp",
3890
+ PIN: "pin",
3891
+ PHONE: "phone",
3892
+ BIRTHDAY: "birthday",
3893
+ ADDRESS: "address"
3894
+ };
3895
+ var DEVICE_TYPE = {
3896
+ MOBILE: "mobile",
3897
+ DESKTOP: "desktop",
3898
+ TABLET: "tablet"
3899
+ };
3900
+ var CONTACT_TYPE = {
3901
+ PHONE: "phone",
3902
+ EMAIL: "email"
3903
+ };
3904
+ var LINK_QUERY = {
3905
+ DATA: "link.data",
3906
+ ADDRESSES: "link.addresses",
3907
+ MOBILE_MONEY: "link.mobile_money",
3908
+ PREFERENCES: "link.preferences",
3909
+ SESSIONS: "link.sessions"
3910
+ };
3911
+ var LINK_MUTATION = {
3912
+ CHECK_STATUS: "link.check_status",
3913
+ ENROLL: "link.enroll",
3914
+ ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
3915
+ UPDATE_PREFERENCES: "link.update_preferences",
3916
+ CREATE_ADDRESS: "link.create_address",
3917
+ UPDATE_ADDRESS: "link.update_address",
3918
+ DELETE_ADDRESS: "link.delete_address",
3919
+ SET_DEFAULT_ADDRESS: "link.set_default_address",
3920
+ TRACK_ADDRESS_USAGE: "link.track_address_usage",
3921
+ CREATE_MOBILE_MONEY: "link.create_mobile_money",
3922
+ DELETE_MOBILE_MONEY: "link.delete_mobile_money",
3923
+ SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
3924
+ TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
3925
+ VERIFY_MOBILE_MONEY: "link.verify_mobile_money",
3926
+ REVOKE_SESSION: "link.revoke_session",
3927
+ REVOKE_ALL_SESSIONS: "link.revoke_all_sessions"
3928
+ };
3929
+ var AUTH_MUTATION = {
3930
+ REQUEST_OTP: "auth.request_otp",
3931
+ VERIFY_OTP: "auth.verify_otp"
3932
+ };
3933
+ var CHECKOUT_MUTATION = {
3934
+ PROCESS: "checkout.process"
3935
+ };
3936
+ var PAYMENT_MUTATION = {
3937
+ SUBMIT_AUTHORIZATION: "payment.submit_authorization",
3938
+ CHECK_STATUS: "order.poll_payment_status"
3939
+ };
3940
+ var ORDER_MUTATION = {
3941
+ UPDATE_CUSTOMER: "order.update_order_customer"
3942
+ };
3943
+ var DEFAULT_CURRENCY = "GHS";
3944
+ var DEFAULT_COUNTRY = "GHA";
3945
+
4356
3946
  export { AUTHORIZATION_TYPE, AUTH_MUTATION, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CONTACT_TYPE, CURRENCY_SYMBOLS, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyClient, CimplifyElement, CimplifyElements, CimplifyError, DEFAULT_COUNTRY, DEFAULT_CURRENCY, DEVICE_TYPE, ELEMENT_TYPES, ERROR_HINTS, EVENT_TYPES, ErrorCode, FxService, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MESSAGE_TYPES, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, QueryBuilder, SchedulingService, ZERO, categorizePaymentError, combine, combineObject, createCimplifyClient, createElements, currencyCode, detectMobileMoneyProvider, enrichError, err, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatPriceWithTax, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getErrorHint, getMarkupPercentage, getOrElse, getProductCurrency, getTaxAmount, hasTaxInfo, isCimplifyError, isErr, isOk, isOnSale, isPaymentStatusFailure, isPaymentStatusRequiresAction, isPaymentStatusSuccess, isRetryableError, isTaxInclusive, mapError, mapResult, money, moneyFromNumber, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, query, toNullable, tryCatch, unwrap };