@cimplify/sdk 0.7.1 → 0.7.3

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,
@@ -2250,57 +1763,51 @@ var CheckoutService = class {
2250
1763
  constructor(client) {
2251
1764
  this.client = client;
2252
1765
  }
1766
+ orderTokenParam(orderId) {
1767
+ const token = this.client.getOrderToken(orderId);
1768
+ return token ? `?token=${encodeURIComponent(token)}` : "";
1769
+ }
2253
1770
  async process(data) {
2254
1771
  const checkoutData = {
2255
1772
  ...data,
2256
1773
  idempotency_key: data.idempotency_key || generateIdempotencyKey()
2257
1774
  };
2258
- return safeWithFallback3(
2259
- () => this.client.post("/api/v1/checkout", {
2260
- checkout_data: checkoutData
2261
- }),
2262
- () => this.client.call(CHECKOUT_MUTATION.PROCESS, {
1775
+ const result = await safe3(
1776
+ this.client.post("/api/v1/checkout", {
2263
1777
  checkout_data: checkoutData
2264
1778
  })
2265
1779
  );
1780
+ if (result.ok && result.value.bill_token) {
1781
+ this.client.setOrderToken(result.value.order_id, result.value.bill_token);
1782
+ }
1783
+ return result;
2266
1784
  }
2267
- async initializePayment(orderId, method) {
2268
- return safe3(
2269
- this.client.call("order.initializePayment", {
2270
- order_id: orderId,
2271
- payment_method: method
2272
- })
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
+ )
2273
1792
  );
2274
1793
  }
2275
1794
  async submitAuthorization(input) {
2276
- return safeWithFallback3(
2277
- () => this.client.post("/api/v1/payments/authorization", input),
2278
- () => this.client.call(PAYMENT_MUTATION.SUBMIT_AUTHORIZATION, input)
2279
- );
1795
+ return safe3(this.client.post("/api/v1/payments/authorization", input));
2280
1796
  }
2281
1797
  async pollPaymentStatus(orderId) {
2282
1798
  const encodedId = encodeURIComponent(orderId);
2283
- return safeWithFallback3(
2284
- () => this.client.get(`/api/v1/orders/${encodedId}/payment-status`),
2285
- () => this.client.call(PAYMENT_MUTATION.CHECK_STATUS, orderId)
2286
- );
1799
+ const tokenParam = this.orderTokenParam(orderId);
1800
+ return safe3(this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`));
2287
1801
  }
2288
1802
  async updateOrderCustomer(orderId, customer) {
2289
1803
  const encodedId = encodeURIComponent(orderId);
2290
- return safeWithFallback3(
2291
- () => this.client.post(`/api/v1/orders/${encodedId}/customer`, customer),
2292
- () => this.client.call(ORDER_MUTATION.UPDATE_CUSTOMER, {
2293
- order_id: orderId,
2294
- ...customer
2295
- })
2296
- );
1804
+ const tokenParam = this.orderTokenParam(orderId);
1805
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer));
2297
1806
  }
2298
1807
  async verifyPayment(orderId) {
2299
- return safe3(
2300
- this.client.call("order.verifyPayment", {
2301
- order_id: orderId
2302
- })
2303
- );
1808
+ const encodedId = encodeURIComponent(orderId);
1809
+ const tokenParam = this.orderTokenParam(orderId);
1810
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/verify-payment${tokenParam}`));
2304
1811
  }
2305
1812
  async processAndResolve(data) {
2306
1813
  data.on_status_change?.("preparing", {});
@@ -2419,61 +1926,38 @@ async function safe4(promise) {
2419
1926
  return err(toCimplifyError4(error));
2420
1927
  }
2421
1928
  }
2422
- async function safeWithFallback4(primary, fallback) {
2423
- const primaryResult = await safe4(primary());
2424
- if (primaryResult.ok) return primaryResult;
2425
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2426
- return primaryResult;
2427
- }
2428
- return safe4(fallback());
2429
- }
2430
1929
  var OrderQueries = class {
2431
1930
  constructor(client) {
2432
1931
  this.client = client;
2433
1932
  }
1933
+ orderTokenParam(orderId) {
1934
+ const token = this.client.getOrderToken(orderId);
1935
+ return token ? `?token=${encodeURIComponent(token)}` : "";
1936
+ }
2434
1937
  async list(options) {
2435
- let query2 = "orders";
2436
- if (options?.status) {
2437
- query2 += `[?(@.status=='${options.status}')]`;
2438
- }
2439
- query2 += "#sort(created_at,desc)";
2440
- if (options?.limit) {
2441
- query2 += `#limit(${options.limit})`;
2442
- }
2443
- if (options?.offset) {
2444
- query2 += `#offset(${options.offset})`;
2445
- }
2446
1938
  const params = new URLSearchParams();
2447
1939
  if (options?.status) params.set("status", options.status);
2448
1940
  if (options?.limit) params.set("limit", String(options.limit));
2449
1941
  if (options?.offset) params.set("offset", String(options.offset));
2450
1942
  const path = params.toString() ? `/api/v1/orders?${params.toString()}` : "/api/v1/orders";
2451
- return safeWithFallback4(
2452
- () => this.client.get(path),
2453
- () => this.client.query(query2)
2454
- );
1943
+ return safe4(this.client.get(path));
2455
1944
  }
2456
1945
  async get(orderId) {
2457
1946
  const encodedId = encodeURIComponent(orderId);
2458
- return safeWithFallback4(
2459
- () => this.client.get(`/api/v1/orders/${encodedId}`),
2460
- () => this.client.query(`orders.${orderId}`)
2461
- );
1947
+ const tokenParam = this.orderTokenParam(orderId);
1948
+ return safe4(this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`));
2462
1949
  }
2463
1950
  async getRecent(limit = 5) {
2464
- return safe4(this.client.query(`orders#sort(created_at,desc)#limit(${limit})`));
1951
+ return this.list({ limit });
2465
1952
  }
2466
1953
  async getByStatus(status) {
2467
1954
  return this.list({ status });
2468
1955
  }
2469
1956
  async cancel(orderId, reason) {
2470
1957
  const encodedId = encodeURIComponent(orderId);
2471
- return safeWithFallback4(
2472
- () => this.client.post(`/api/v1/orders/${encodedId}/cancel`, {
2473
- reason
2474
- }),
2475
- () => this.client.call("order.cancelOrder", {
2476
- order_id: orderId,
1958
+ const tokenParam = this.orderTokenParam(orderId);
1959
+ return safe4(
1960
+ this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
2477
1961
  reason
2478
1962
  })
2479
1963
  );
@@ -2495,6 +1979,38 @@ async function safe5(promise) {
2495
1979
  return err(toCimplifyError5(error));
2496
1980
  }
2497
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
+ }
2498
2014
  var LinkService = class {
2499
2015
  constructor(client) {
2500
2016
  this.client = client;
@@ -2522,11 +2038,7 @@ var LinkService = class {
2522
2038
  return result;
2523
2039
  }
2524
2040
  async checkStatus(contact) {
2525
- return safe5(
2526
- this.client.call(LINK_MUTATION.CHECK_STATUS, {
2527
- contact
2528
- })
2529
- );
2041
+ return safe5(this.client.linkPost("/v1/link/check-status", { contact }));
2530
2042
  }
2531
2043
  async getLinkData() {
2532
2044
  return safe5(this.client.linkGet("/v1/link/data"));
@@ -2538,61 +2050,85 @@ var LinkService = class {
2538
2050
  return safe5(this.client.linkGet("/v1/link/mobile-money"));
2539
2051
  }
2540
2052
  async getPreferences() {
2541
- return safe5(this.client.query(LINK_QUERY.PREFERENCES));
2053
+ return safe5(this.client.linkGet("/v1/link/preferences"));
2542
2054
  }
2543
2055
  async enroll(data) {
2544
- return safe5(this.client.call(LINK_MUTATION.ENROLL, data));
2056
+ return safe5(this.client.linkPost("/v1/link/enroll", data));
2545
2057
  }
2546
2058
  async enrollAndLinkOrder(data) {
2547
2059
  return safe5(
2548
- this.client.call(LINK_MUTATION.ENROLL_AND_LINK_ORDER, data)
2060
+ this.client.linkPost("/v1/link/enroll-and-link-order", data)
2549
2061
  );
2550
2062
  }
2551
2063
  async updatePreferences(preferences) {
2552
- return safe5(this.client.call(LINK_MUTATION.UPDATE_PREFERENCES, preferences));
2064
+ return safe5(this.client.linkPost("/v1/link/preferences", preferences));
2553
2065
  }
2554
2066
  async createAddress(input) {
2555
- return safe5(this.client.call(LINK_MUTATION.CREATE_ADDRESS, input));
2067
+ return safe5(
2068
+ this.client.linkPost("/v1/link/addresses", toCreateAddressPayload(input))
2069
+ );
2556
2070
  }
2557
2071
  async updateAddress(input) {
2558
- 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
+ );
2559
2078
  }
2560
2079
  async deleteAddress(addressId) {
2561
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2080
+ return safe5(
2081
+ this.client.linkDelete(`/v1/link/addresses/${encodePathSegment(addressId)}`)
2082
+ );
2562
2083
  }
2563
2084
  async setDefaultAddress(addressId) {
2564
- 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
+ );
2565
2090
  }
2566
2091
  async trackAddressUsage(addressId) {
2567
2092
  return safe5(
2568
- this.client.call(LINK_MUTATION.TRACK_ADDRESS_USAGE, {
2569
- address_id: addressId
2570
- })
2093
+ this.client.linkPost(
2094
+ `/v1/link/addresses/${encodePathSegment(addressId)}/track-usage`
2095
+ )
2571
2096
  );
2572
2097
  }
2573
2098
  async createMobileMoney(input) {
2574
- 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
+ );
2575
2105
  }
2576
2106
  async deleteMobileMoney(mobileMoneyId) {
2577
2107
  return safe5(
2578
- this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`)
2108
+ this.client.linkDelete(
2109
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}`
2110
+ )
2579
2111
  );
2580
2112
  }
2581
2113
  async setDefaultMobileMoney(mobileMoneyId) {
2582
2114
  return safe5(
2583
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2115
+ this.client.linkPost(
2116
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/default`
2117
+ )
2584
2118
  );
2585
2119
  }
2586
2120
  async trackMobileMoneyUsage(mobileMoneyId) {
2587
2121
  return safe5(
2588
- this.client.call(LINK_MUTATION.TRACK_MOBILE_MONEY_USAGE, {
2589
- mobile_money_id: mobileMoneyId
2590
- })
2122
+ this.client.linkPost(
2123
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/track-usage`
2124
+ )
2591
2125
  );
2592
2126
  }
2593
2127
  async verifyMobileMoney(mobileMoneyId) {
2594
2128
  return safe5(
2595
- this.client.call(LINK_MUTATION.VERIFY_MOBILE_MONEY, mobileMoneyId)
2129
+ this.client.linkPost(
2130
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/verify`
2131
+ )
2596
2132
  );
2597
2133
  }
2598
2134
  async getSessions() {
@@ -2605,30 +2141,28 @@ var LinkService = class {
2605
2141
  return safe5(this.client.linkDelete("/v1/link/sessions"));
2606
2142
  }
2607
2143
  async getAddressesRest() {
2608
- return safe5(this.client.linkGet("/v1/link/addresses"));
2144
+ return this.getAddresses();
2609
2145
  }
2610
2146
  async createAddressRest(input) {
2611
- return safe5(this.client.linkPost("/v1/link/addresses", input));
2147
+ return this.createAddress(input);
2612
2148
  }
2613
2149
  async deleteAddressRest(addressId) {
2614
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2150
+ return this.deleteAddress(addressId);
2615
2151
  }
2616
2152
  async setDefaultAddressRest(addressId) {
2617
- return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
2153
+ return this.setDefaultAddress(addressId);
2618
2154
  }
2619
2155
  async getMobileMoneyRest() {
2620
- return safe5(this.client.linkGet("/v1/link/mobile-money"));
2156
+ return this.getMobileMoney();
2621
2157
  }
2622
2158
  async createMobileMoneyRest(input) {
2623
- return safe5(this.client.linkPost("/v1/link/mobile-money", input));
2159
+ return this.createMobileMoney(input);
2624
2160
  }
2625
2161
  async deleteMobileMoneyRest(mobileMoneyId) {
2626
- return safe5(this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`));
2162
+ return this.deleteMobileMoney(mobileMoneyId);
2627
2163
  }
2628
2164
  async setDefaultMobileMoneyRest(mobileMoneyId) {
2629
- return safe5(
2630
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2631
- );
2165
+ return this.setDefaultMobileMoney(mobileMoneyId);
2632
2166
  }
2633
2167
  };
2634
2168
 
@@ -2647,23 +2181,12 @@ async function safe6(promise) {
2647
2181
  return err(toCimplifyError6(error));
2648
2182
  }
2649
2183
  }
2650
- async function safeWithFallback5(primary, fallback) {
2651
- const primaryResult = await safe6(primary());
2652
- if (primaryResult.ok) return primaryResult;
2653
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2654
- return primaryResult;
2655
- }
2656
- return safe6(fallback());
2657
- }
2658
2184
  var AuthService = class {
2659
2185
  constructor(client) {
2660
2186
  this.client = client;
2661
2187
  }
2662
2188
  async getStatus() {
2663
- return safeWithFallback5(
2664
- () => this.client.get("/api/v1/auth/status"),
2665
- () => this.client.query("auth")
2666
- );
2189
+ return safe6(this.client.get("/api/v1/auth/status"));
2667
2190
  }
2668
2191
  async getCurrentUser() {
2669
2192
  const result = await this.getStatus();
@@ -2676,43 +2199,26 @@ var AuthService = class {
2676
2199
  return ok(result.value.is_authenticated);
2677
2200
  }
2678
2201
  async requestOtp(contact, contactType) {
2679
- return safeWithFallback5(
2680
- () => this.client.post("/api/v1/auth/request-otp", {
2681
- contact,
2682
- contact_type: contactType
2683
- }),
2684
- () => this.client.call(AUTH_MUTATION.REQUEST_OTP, {
2202
+ return safe6(
2203
+ this.client.post("/api/v1/auth/request-otp", {
2685
2204
  contact,
2686
2205
  contact_type: contactType
2687
2206
  })
2688
2207
  );
2689
2208
  }
2690
2209
  async verifyOtp(code, contact) {
2691
- return safeWithFallback5(
2692
- () => this.client.post("/api/v1/auth/verify-otp", {
2693
- otp_code: code,
2694
- contact
2695
- }),
2696
- () => this.client.call(AUTH_MUTATION.VERIFY_OTP, {
2210
+ return safe6(
2211
+ this.client.post("/api/v1/auth/verify-otp", {
2697
2212
  otp_code: code,
2698
2213
  contact
2699
2214
  })
2700
2215
  );
2701
2216
  }
2702
2217
  async logout() {
2703
- return safeWithFallback5(
2704
- () => this.client.post("/api/v1/auth/logout"),
2705
- () => this.client.call("auth.logout")
2706
- );
2218
+ return safe6(this.client.post("/api/v1/auth/logout"));
2707
2219
  }
2708
2220
  async updateProfile(input) {
2709
- return safe6(this.client.call("auth.update_profile", input));
2710
- }
2711
- async changePassword(input) {
2712
- return safe6(this.client.call("auth.change_password", input));
2713
- }
2714
- async resetPassword(email) {
2715
- return safe6(this.client.call("auth.reset_password", { email }));
2221
+ return safe6(this.client.post("/api/v1/auth/profile", input));
2716
2222
  }
2717
2223
  };
2718
2224
 
@@ -2731,47 +2237,29 @@ async function safe7(promise) {
2731
2237
  return err(toCimplifyError7(error));
2732
2238
  }
2733
2239
  }
2734
- async function safeWithFallback6(primary, fallback) {
2735
- const primaryResult = await safe7(primary());
2736
- if (primaryResult.ok) return primaryResult;
2737
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2738
- return primaryResult;
2739
- }
2740
- return safe7(fallback());
2741
- }
2742
2240
  var BusinessService = class {
2743
2241
  constructor(client) {
2744
2242
  this.client = client;
2745
2243
  }
2746
2244
  async getInfo() {
2747
- return safeWithFallback6(
2748
- () => this.client.get("/api/v1/business"),
2749
- () => this.client.query("business.info")
2750
- );
2245
+ return safe7(this.client.get("/api/v1/business"));
2751
2246
  }
2752
2247
  async getByHandle(handle) {
2753
- 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}`));
2754
2250
  }
2755
2251
  async getByDomain(domain) {
2756
- 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}`));
2757
2254
  }
2758
2255
  async getSettings() {
2759
- return safeWithFallback6(
2760
- () => this.client.get("/api/v1/business/settings"),
2761
- () => this.client.query("business.settings")
2762
- );
2256
+ return safe7(this.client.get("/api/v1/business/settings"));
2763
2257
  }
2764
2258
  async getTheme() {
2765
- return safeWithFallback6(
2766
- () => this.client.get("/api/v1/business/theme"),
2767
- () => this.client.query("business.theme")
2768
- );
2259
+ return safe7(this.client.get("/api/v1/business/theme"));
2769
2260
  }
2770
2261
  async getLocations() {
2771
- return safeWithFallback6(
2772
- () => this.client.get("/api/v1/business/locations"),
2773
- () => this.client.query("business.locations")
2774
- );
2262
+ return safe7(this.client.get("/api/v1/business/locations"));
2775
2263
  }
2776
2264
  async getLocation(locationId) {
2777
2265
  const result = await this.getLocations();
@@ -2783,10 +2271,7 @@ var BusinessService = class {
2783
2271
  return ok(location);
2784
2272
  }
2785
2273
  async getHours() {
2786
- return safeWithFallback6(
2787
- () => this.client.get("/api/v1/business/hours"),
2788
- () => this.client.query("business.hours")
2789
- );
2274
+ return safe7(this.client.get("/api/v1/business/hours"));
2790
2275
  }
2791
2276
  async getLocationHours(locationId) {
2792
2277
  const result = await this.getHours();
@@ -2794,31 +2279,7 @@ var BusinessService = class {
2794
2279
  return ok(result.value.filter((hour) => hour.location_id === locationId));
2795
2280
  }
2796
2281
  async getBootstrap() {
2797
- const restBootstrap = await safe7(this.client.get("/api/v1/bootstrap"));
2798
- if (restBootstrap.ok) {
2799
- return restBootstrap;
2800
- }
2801
- const [businessResult, locationsResult, categoriesResult] = await Promise.all([
2802
- this.getInfo(),
2803
- this.getLocations(),
2804
- safe7(this.client.query("categories#select(id,name,slug)"))
2805
- ]);
2806
- if (!businessResult.ok) return businessResult;
2807
- if (!locationsResult.ok) return locationsResult;
2808
- if (!categoriesResult.ok) return categoriesResult;
2809
- const business = businessResult.value;
2810
- const locations = locationsResult.value;
2811
- const categories = categoriesResult.value;
2812
- const defaultLocation = locations[0];
2813
- return ok({
2814
- business,
2815
- location: defaultLocation,
2816
- locations,
2817
- categories,
2818
- currency: business.default_currency,
2819
- is_open: defaultLocation?.accepts_online_orders ?? false,
2820
- accepts_orders: defaultLocation?.accepts_online_orders ?? false
2821
- });
2282
+ return safe7(this.client.get("/api/v1/bootstrap"));
2822
2283
  }
2823
2284
  };
2824
2285
 
@@ -2841,49 +2302,47 @@ var InventoryService = class {
2841
2302
  constructor(client) {
2842
2303
  this.client = client;
2843
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
+ }
2844
2314
  async getStockLevels() {
2845
- return safe8(this.client.query("inventory.stock_levels"));
2315
+ return safe8(this.client.get("/api/v1/inventory/stock-levels"));
2846
2316
  }
2847
2317
  async getProductStock(productId, locationId) {
2848
- if (locationId) {
2849
- return safe8(
2850
- this.client.query("inventory.product", {
2851
- product_id: productId,
2852
- location_id: locationId
2853
- })
2854
- );
2855
- }
2856
- return safe8(
2857
- this.client.query("inventory.product", {
2858
- product_id: productId
2859
- })
2860
- );
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));
2861
2323
  }
2862
2324
  async getVariantStock(variantId, locationId) {
2863
- return safe8(
2864
- this.client.query("inventory.variant", {
2865
- variant_id: variantId,
2866
- location_id: locationId
2867
- })
2868
- );
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));
2869
2330
  }
2870
2331
  async checkProductAvailability(productId, quantity, locationId) {
2871
- return safe8(
2872
- this.client.query("inventory.check_availability", {
2873
- product_id: productId,
2874
- quantity,
2875
- location_id: locationId
2876
- })
2877
- );
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));
2878
2338
  }
2879
2339
  async checkVariantAvailability(variantId, quantity, locationId) {
2880
- return safe8(
2881
- this.client.query("inventory.check_availability", {
2882
- variant_id: variantId,
2883
- quantity,
2884
- location_id: locationId
2885
- })
2886
- );
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));
2887
2346
  }
2888
2347
  async checkMultipleAvailability(items, locationId) {
2889
2348
  const results = await Promise.all(
@@ -2897,7 +2356,7 @@ var InventoryService = class {
2897
2356
  return ok(results.map((r) => r.value));
2898
2357
  }
2899
2358
  async getSummary() {
2900
- return safe8(this.client.query("inventory.summary"));
2359
+ return safe8(this.client.get("/api/v1/inventory/summary"));
2901
2360
  }
2902
2361
  async isInStock(productId, locationId) {
2903
2362
  const result = await this.checkProductAvailability(productId, 1, locationId);
@@ -2912,9 +2371,6 @@ var InventoryService = class {
2912
2371
  };
2913
2372
 
2914
2373
  // src/scheduling.ts
2915
- function toVariables(input) {
2916
- return Object.fromEntries(Object.entries(input));
2917
- }
2918
2374
  function toCimplifyError9(error) {
2919
2375
  if (error instanceof CimplifyError) return error;
2920
2376
  if (error instanceof Error) {
@@ -2929,68 +2385,110 @@ async function safe9(promise) {
2929
2385
  return err(toCimplifyError9(error));
2930
2386
  }
2931
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
+ }
2932
2410
  var SchedulingService = class {
2933
2411
  constructor(client) {
2934
2412
  this.client = client;
2935
2413
  }
2936
2414
  async getServices() {
2937
- return safe9(this.client.query("scheduling.services"));
2415
+ return safe9(this.client.get("/api/v1/scheduling/services"));
2938
2416
  }
2939
2417
  /**
2940
- * Get a specific service by ID
2941
- * Note: Filters from all services client-side (no single-service endpoint)
2418
+ * Get a specific service by ID.
2942
2419
  */
2943
2420
  async getService(serviceId) {
2944
2421
  const result = await this.getServices();
2945
2422
  if (!result.ok) return result;
2946
- return ok(result.value.find((s) => s.id === serviceId) || null);
2423
+ return ok(result.value.find((service) => service.id === serviceId) || null);
2947
2424
  }
2948
2425
  async getAvailableSlots(input) {
2949
- return safe9(
2950
- this.client.query("scheduling.slots", toVariables(input))
2951
- );
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));
2952
2433
  }
2953
2434
  async checkSlotAvailability(input) {
2954
- return safe9(
2955
- this.client.query(
2956
- "scheduling.check_availability",
2957
- toVariables(input)
2958
- )
2959
- );
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));
2960
2442
  }
2961
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
+ });
2962
2451
  return safe9(
2963
- this.client.query(
2964
- "scheduling.availability",
2965
- toVariables(params)
2966
- )
2452
+ this.client.get(path).then((result) => normalizeServiceAvailability(result))
2967
2453
  );
2968
2454
  }
2969
2455
  async getBooking(bookingId) {
2970
- return safe9(this.client.query(`scheduling.${bookingId}`));
2456
+ const encodedId = encodeURIComponent(bookingId);
2457
+ return safe9(this.client.get(`/api/v1/scheduling/bookings/${encodedId}`));
2971
2458
  }
2972
- async getCustomerBookings() {
2973
- 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));
2974
2464
  }
2975
2465
  async getUpcomingBookings() {
2976
- return safe9(
2977
- this.client.query(
2978
- "scheduling[?(@.status!='completed' && @.status!='cancelled')]#sort(start_time,asc)"
2979
- )
2980
- );
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);
2981
2473
  }
2982
2474
  async getPastBookings(limit = 10) {
2983
- return safe9(
2984
- this.client.query(
2985
- `scheduling[?(@.status=='completed')]#sort(start_time,desc)#limit(${limit})`
2986
- )
2987
- );
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);
2988
2479
  }
2989
2480
  async cancelBooking(input) {
2990
- 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
+ );
2991
2487
  }
2992
2488
  async rescheduleBooking(input) {
2993
- return safe9(this.client.call("scheduling.reschedule_booking", input));
2489
+ return safe9(
2490
+ this.client.post("/api/v1/scheduling/bookings/reschedule", input)
2491
+ );
2994
2492
  }
2995
2493
  async getNextAvailableSlot(serviceId, fromDate) {
2996
2494
  const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -3009,6 +2507,12 @@ var SchedulingService = class {
3009
2507
  if (!result.ok) return result;
3010
2508
  return ok(result.value.some((slot) => slot.is_available));
3011
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
+ }
3012
2516
  };
3013
2517
 
3014
2518
  // src/lite.ts
@@ -3031,47 +2535,18 @@ var LiteService = class {
3031
2535
  this.client = client;
3032
2536
  }
3033
2537
  async getBootstrap() {
3034
- return safe10(this.client.query("lite.bootstrap"));
2538
+ return safe10(this.client.get("/api/v1/lite/bootstrap"));
3035
2539
  }
3036
2540
  async getTable(tableId) {
3037
- return safe10(this.client.query(`lite.table.${tableId}`));
3038
- }
3039
- async getTableByNumber(tableNumber, locationId) {
3040
- return safe10(
3041
- this.client.query("lite.table_by_number", {
3042
- table_number: tableNumber,
3043
- location_id: locationId
3044
- })
3045
- );
3046
- }
3047
- async sendToKitchen(tableId, items) {
3048
- return safe10(
3049
- this.client.call("lite.send_to_kitchen", {
3050
- table_id: tableId,
3051
- items
3052
- })
3053
- );
3054
- }
3055
- async callWaiter(tableId, reason) {
3056
- return safe10(
3057
- this.client.call("lite.call_waiter", {
3058
- table_id: tableId,
3059
- reason
3060
- })
3061
- );
3062
- }
3063
- async requestBill(tableId) {
3064
- return safe10(
3065
- this.client.call("lite.request_bill", {
3066
- table_id: tableId
3067
- })
3068
- );
2541
+ const encodedId = encodeURIComponent(tableId);
2542
+ return safe10(this.client.get(`/api/v1/lite/tables/${encodedId}`));
3069
2543
  }
3070
2544
  async getMenu() {
3071
- return safe10(this.client.query("lite.menu"));
2545
+ return safe10(this.client.get("/api/v1/lite/menu"));
3072
2546
  }
3073
2547
  async getMenuByCategory(categoryId) {
3074
- 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}`));
3075
2550
  }
3076
2551
  };
3077
2552
 
@@ -3090,30 +2565,16 @@ async function safe11(promise) {
3090
2565
  return err(toCimplifyError11(error));
3091
2566
  }
3092
2567
  }
3093
- async function safeWithFallback7(primary, fallback) {
3094
- const primaryResult = await safe11(primary());
3095
- if (primaryResult.ok) return primaryResult;
3096
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
3097
- return primaryResult;
3098
- }
3099
- return safe11(fallback());
3100
- }
3101
2568
  var FxService = class {
3102
2569
  constructor(client) {
3103
2570
  this.client = client;
3104
2571
  }
3105
2572
  async getRate(from, to) {
3106
2573
  const path = `/api/v1/fx/rate?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
3107
- return safeWithFallback7(
3108
- () => this.client.get(path),
3109
- () => this.client.call("fx.getRate", { from, to })
3110
- );
2574
+ return safe11(this.client.get(path));
3111
2575
  }
3112
2576
  async lockQuote(request) {
3113
- return safeWithFallback7(
3114
- () => this.client.post("/api/v1/fx/quotes", request),
3115
- () => this.client.call("fx.lockQuote", request)
3116
- );
2577
+ return safe11(this.client.post("/api/v1/fx/quotes", request));
3117
2578
  }
3118
2579
  };
3119
2580
 
@@ -3724,6 +3185,7 @@ function createElements(client, businessId, options) {
3724
3185
 
3725
3186
  // src/client.ts
3726
3187
  var ACCESS_TOKEN_STORAGE_KEY = "cimplify_access_token";
3188
+ var ORDER_TOKEN_PREFIX = "cimplify_ot_";
3727
3189
  var DEFAULT_TIMEOUT_MS = 3e4;
3728
3190
  var DEFAULT_MAX_RETRIES = 3;
3729
3191
  var DEFAULT_RETRY_DELAY_MS = 1e3;
@@ -3865,7 +3327,29 @@ var CimplifyClient = class {
3865
3327
  source: "clear"
3866
3328
  });
3867
3329
  }
3868
- /** Set the active location/branch for all subsequent requests */
3330
+ setOrderToken(orderId, token) {
3331
+ if (typeof window !== "undefined" && window.localStorage) {
3332
+ localStorage.setItem(`${ORDER_TOKEN_PREFIX}${orderId}`, token);
3333
+ }
3334
+ }
3335
+ getOrderToken(orderId) {
3336
+ if (typeof window !== "undefined" && window.localStorage) {
3337
+ return localStorage.getItem(`${ORDER_TOKEN_PREFIX}${orderId}`);
3338
+ }
3339
+ return null;
3340
+ }
3341
+ clearOrderTokens() {
3342
+ if (typeof window !== "undefined" && window.localStorage) {
3343
+ const keysToRemove = [];
3344
+ for (let i = 0; i < localStorage.length; i++) {
3345
+ const key = localStorage.key(i);
3346
+ if (key?.startsWith(ORDER_TOKEN_PREFIX)) {
3347
+ keysToRemove.push(key);
3348
+ }
3349
+ }
3350
+ keysToRemove.forEach((k) => localStorage.removeItem(k));
3351
+ }
3352
+ }
3869
3353
  setLocationId(locationId) {
3870
3354
  if (locationId) {
3871
3355
  this.context.location_id = locationId;
@@ -4066,41 +3550,6 @@ var CimplifyClient = class {
4066
3550
  this.inflightRequests.set(key, request);
4067
3551
  return request;
4068
3552
  }
4069
- async query(query2, variables) {
4070
- const body = { query: query2 };
4071
- if (variables) {
4072
- body.variables = variables;
4073
- }
4074
- if (Object.keys(this.context).length > 0) {
4075
- body.context = this.context;
4076
- }
4077
- const key = this.getDedupeKey("query", body);
4078
- return this.deduplicatedRequest(key, async () => {
4079
- const response = await this.resilientFetch(`${this.baseUrl}/api/q`, {
4080
- method: "POST",
4081
- credentials: this.credentials,
4082
- headers: this.getHeaders(),
4083
- body: JSON.stringify(body)
4084
- });
4085
- return this.handleResponse(response);
4086
- });
4087
- }
4088
- async call(method, args) {
4089
- const body = {
4090
- method,
4091
- args: args !== void 0 ? [args] : []
4092
- };
4093
- if (Object.keys(this.context).length > 0) {
4094
- body.context = this.context;
4095
- }
4096
- const response = await this.resilientFetch(`${this.baseUrl}/api/m`, {
4097
- method: "POST",
4098
- credentials: this.credentials,
4099
- headers: this.getHeaders(),
4100
- body: JSON.stringify(body)
4101
- });
4102
- return this.handleResponse(response);
4103
- }
4104
3553
  async get(path) {
4105
3554
  const key = this.getDedupeKey("get", path);
4106
3555
  return this.deduplicatedRequest(key, async () => {
@@ -4203,26 +3652,6 @@ var CimplifyClient = class {
4203
3652
  }
4204
3653
  return json;
4205
3654
  }
4206
- async handleResponse(response) {
4207
- const json = await response.json();
4208
- if (!json.success || json.error) {
4209
- const error = enrichError(
4210
- new CimplifyError(
4211
- json.error?.code || "UNKNOWN_ERROR",
4212
- json.error?.message || "An unknown error occurred",
4213
- json.error?.retryable || false
4214
- ),
4215
- { isTestMode: this.isTestMode() }
4216
- );
4217
- if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
4218
- console.warn(
4219
- "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
4220
- );
4221
- }
4222
- throw error;
4223
- }
4224
- return json.data;
4225
- }
4226
3655
  get catalogue() {
4227
3656
  if (!this._catalogue) {
4228
3657
  this._catalogue = new CatalogueQueries(this);
@@ -4314,4 +3743,171 @@ function createCimplifyClient(config = {}) {
4314
3743
  return new CimplifyClient(config);
4315
3744
  }
4316
3745
 
3746
+ // src/query/builder.ts
3747
+ function escapeQueryValue(value) {
3748
+ return value.replace(/'/g, "\\'");
3749
+ }
3750
+ var QueryBuilder = class {
3751
+ constructor(entity) {
3752
+ this.filters = [];
3753
+ this.modifiers = [];
3754
+ this.pathSegments = [];
3755
+ this.entity = entity;
3756
+ }
3757
+ path(segment) {
3758
+ this.pathSegments.push(segment);
3759
+ return this;
3760
+ }
3761
+ where(field, op, value) {
3762
+ const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
3763
+ if (op === "contains" || op === "startsWith") {
3764
+ this.filters.push(`@.${field} ${op} ${v}`);
3765
+ } else {
3766
+ this.filters.push(`@.${field}${op}${v}`);
3767
+ }
3768
+ return this;
3769
+ }
3770
+ and(field, op, value) {
3771
+ return this.where(field, op, value);
3772
+ }
3773
+ sort(field, order = "asc") {
3774
+ this.modifiers.push(`sort(${field},${order})`);
3775
+ return this;
3776
+ }
3777
+ limit(n) {
3778
+ this.modifiers.push(`limit(${n})`);
3779
+ return this;
3780
+ }
3781
+ offset(n) {
3782
+ this.modifiers.push(`offset(${n})`);
3783
+ return this;
3784
+ }
3785
+ count() {
3786
+ this.modifiers.push("count");
3787
+ return this;
3788
+ }
3789
+ enriched() {
3790
+ this.modifiers.push("enriched");
3791
+ return this;
3792
+ }
3793
+ build() {
3794
+ let query2 = this.entity;
3795
+ if (this.pathSegments.length > 0) {
3796
+ query2 += "." + this.pathSegments.join(".");
3797
+ }
3798
+ if (this.filters.length > 0) {
3799
+ query2 += `[?(${this.filters.join(" && ")})]`;
3800
+ }
3801
+ for (const mod of this.modifiers) {
3802
+ query2 += `#${mod}`;
3803
+ }
3804
+ return query2;
3805
+ }
3806
+ toString() {
3807
+ return this.build();
3808
+ }
3809
+ };
3810
+ function query(entity) {
3811
+ return new QueryBuilder(entity);
3812
+ }
3813
+
3814
+ // src/constants.ts
3815
+ var CHECKOUT_MODE = {
3816
+ LINK: "link",
3817
+ GUEST: "guest"
3818
+ };
3819
+ var ORDER_TYPE = {
3820
+ DELIVERY: "delivery",
3821
+ PICKUP: "pickup",
3822
+ DINE_IN: "dine-in",
3823
+ WALK_IN: "walk-in"
3824
+ };
3825
+ var PAYMENT_METHOD = {
3826
+ MOBILE_MONEY: "mobile_money",
3827
+ CARD: "card"
3828
+ };
3829
+ var CHECKOUT_STEP = {
3830
+ AUTHENTICATION: "authentication",
3831
+ ORDER_DETAILS: "order_details",
3832
+ PAYMENT_METHOD: "payment_method",
3833
+ PAYMENT: "payment",
3834
+ CONFIRMATION: "confirmation"
3835
+ };
3836
+ var PAYMENT_STATE = {
3837
+ INITIAL: "initial",
3838
+ PREPARING: "preparing",
3839
+ PROCESSING: "processing",
3840
+ VERIFYING: "verifying",
3841
+ AWAITING_AUTHORIZATION: "awaiting_authorization",
3842
+ SUCCESS: "success",
3843
+ ERROR: "error",
3844
+ TIMEOUT: "timeout"
3845
+ };
3846
+ var PICKUP_TIME_TYPE = {
3847
+ ASAP: "asap",
3848
+ SCHEDULED: "scheduled"
3849
+ };
3850
+ var MOBILE_MONEY_PROVIDER = {
3851
+ MTN: "mtn",
3852
+ VODAFONE: "vodafone",
3853
+ AIRTEL: "airtel"
3854
+ };
3855
+ var AUTHORIZATION_TYPE = {
3856
+ OTP: "otp",
3857
+ PIN: "pin",
3858
+ PHONE: "phone",
3859
+ BIRTHDAY: "birthday",
3860
+ ADDRESS: "address"
3861
+ };
3862
+ var DEVICE_TYPE = {
3863
+ MOBILE: "mobile",
3864
+ DESKTOP: "desktop",
3865
+ TABLET: "tablet"
3866
+ };
3867
+ var CONTACT_TYPE = {
3868
+ PHONE: "phone",
3869
+ EMAIL: "email"
3870
+ };
3871
+ var LINK_QUERY = {
3872
+ DATA: "link.data",
3873
+ ADDRESSES: "link.addresses",
3874
+ MOBILE_MONEY: "link.mobile_money",
3875
+ PREFERENCES: "link.preferences",
3876
+ SESSIONS: "link.sessions"
3877
+ };
3878
+ var LINK_MUTATION = {
3879
+ CHECK_STATUS: "link.check_status",
3880
+ ENROLL: "link.enroll",
3881
+ ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
3882
+ UPDATE_PREFERENCES: "link.update_preferences",
3883
+ CREATE_ADDRESS: "link.create_address",
3884
+ UPDATE_ADDRESS: "link.update_address",
3885
+ DELETE_ADDRESS: "link.delete_address",
3886
+ SET_DEFAULT_ADDRESS: "link.set_default_address",
3887
+ TRACK_ADDRESS_USAGE: "link.track_address_usage",
3888
+ CREATE_MOBILE_MONEY: "link.create_mobile_money",
3889
+ DELETE_MOBILE_MONEY: "link.delete_mobile_money",
3890
+ SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
3891
+ TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
3892
+ VERIFY_MOBILE_MONEY: "link.verify_mobile_money",
3893
+ REVOKE_SESSION: "link.revoke_session",
3894
+ REVOKE_ALL_SESSIONS: "link.revoke_all_sessions"
3895
+ };
3896
+ var AUTH_MUTATION = {
3897
+ REQUEST_OTP: "auth.request_otp",
3898
+ VERIFY_OTP: "auth.verify_otp"
3899
+ };
3900
+ var CHECKOUT_MUTATION = {
3901
+ PROCESS: "checkout.process"
3902
+ };
3903
+ var PAYMENT_MUTATION = {
3904
+ SUBMIT_AUTHORIZATION: "payment.submit_authorization",
3905
+ CHECK_STATUS: "order.poll_payment_status"
3906
+ };
3907
+ var ORDER_MUTATION = {
3908
+ UPDATE_CUSTOMER: "order.update_order_customer"
3909
+ };
3910
+ var DEFAULT_CURRENCY = "GHS";
3911
+ var DEFAULT_COUNTRY = "GHA";
3912
+
4317
3913
  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 };