@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.js CHANGED
@@ -238,74 +238,6 @@ function combineObject(results) {
238
238
  return ok(values);
239
239
  }
240
240
 
241
- // src/query/builder.ts
242
- function escapeQueryValue(value) {
243
- return value.replace(/'/g, "\\'");
244
- }
245
- var QueryBuilder = class {
246
- constructor(entity) {
247
- this.filters = [];
248
- this.modifiers = [];
249
- this.pathSegments = [];
250
- this.entity = entity;
251
- }
252
- path(segment) {
253
- this.pathSegments.push(segment);
254
- return this;
255
- }
256
- where(field, op, value) {
257
- const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
258
- if (op === "contains" || op === "startsWith") {
259
- this.filters.push(`@.${field} ${op} ${v}`);
260
- } else {
261
- this.filters.push(`@.${field}${op}${v}`);
262
- }
263
- return this;
264
- }
265
- and(field, op, value) {
266
- return this.where(field, op, value);
267
- }
268
- sort(field, order = "asc") {
269
- this.modifiers.push(`sort(${field},${order})`);
270
- return this;
271
- }
272
- limit(n) {
273
- this.modifiers.push(`limit(${n})`);
274
- return this;
275
- }
276
- offset(n) {
277
- this.modifiers.push(`offset(${n})`);
278
- return this;
279
- }
280
- count() {
281
- this.modifiers.push("count");
282
- return this;
283
- }
284
- enriched() {
285
- this.modifiers.push("enriched");
286
- return this;
287
- }
288
- build() {
289
- let query2 = this.entity;
290
- if (this.pathSegments.length > 0) {
291
- query2 += "." + this.pathSegments.join(".");
292
- }
293
- if (this.filters.length > 0) {
294
- query2 += `[?(${this.filters.join(" && ")})]`;
295
- }
296
- for (const mod of this.modifiers) {
297
- query2 += `#${mod}`;
298
- }
299
- return query2;
300
- }
301
- toString() {
302
- return this.build();
303
- }
304
- };
305
- function query(entity) {
306
- return new QueryBuilder(entity);
307
- }
308
-
309
241
  // src/catalogue.ts
310
242
  function toCimplifyError(error) {
311
243
  if (error instanceof CimplifyError) return enrichError(error);
@@ -321,14 +253,6 @@ async function safe(promise) {
321
253
  return err(toCimplifyError(error));
322
254
  }
323
255
  }
324
- async function safeWithFallback(primary, fallback) {
325
- const primaryResult = await safe(primary());
326
- if (primaryResult.ok) return primaryResult;
327
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
328
- return primaryResult;
329
- }
330
- return safe(fallback());
331
- }
332
256
  function withQuery(path, params) {
333
257
  const query2 = new URLSearchParams();
334
258
  for (const [key, value] of Object.entries(params)) {
@@ -390,22 +314,6 @@ function normalizeCatalogueProductPayload(product) {
390
314
  }
391
315
  return normalized;
392
316
  }
393
- function findProductBySlug(products, slug) {
394
- return products.find((product) => {
395
- const value = product["slug"];
396
- return typeof value === "string" && value === slug;
397
- });
398
- }
399
- function findCategoryBySlug(categories, slug) {
400
- return categories.find((category) => {
401
- const value = category["slug"];
402
- return typeof value === "string" && value === slug;
403
- });
404
- }
405
- function hasCategorySlug(category) {
406
- const value = category["slug"];
407
- return typeof value === "string" && value.trim().length > 0;
408
- }
409
317
  function toFiniteNumber(value) {
410
318
  if (typeof value === "number" && Number.isFinite(value)) {
411
319
  return value;
@@ -493,53 +401,11 @@ var CatalogueQueries = class {
493
401
  this.client = client;
494
402
  }
495
403
  async getCatalogue() {
496
- const result = await safeWithFallback(
497
- () => this.client.get("/api/v1/catalogue"),
498
- () => this.client.query("catalogue")
499
- );
404
+ const result = await safe(this.client.get("/api/v1/catalogue"));
500
405
  if (!result.ok) return result;
501
406
  return ok(normalizeCatalogueSnapshot(result.value));
502
407
  }
503
408
  async getProducts(options) {
504
- let query2 = "products";
505
- const filters = [];
506
- if (options?.category) {
507
- filters.push(`@.category_id=='${escapeQueryValue(options.category)}'`);
508
- }
509
- if (options?.featured !== void 0) {
510
- filters.push(`@.featured==${options.featured}`);
511
- }
512
- if (options?.in_stock !== void 0) {
513
- filters.push(`@.in_stock==${options.in_stock}`);
514
- }
515
- if (options?.search) {
516
- filters.push(`@.name contains '${escapeQueryValue(options.search)}'`);
517
- }
518
- if (options?.tags?.length) {
519
- for (const tag of options.tags) {
520
- if (tag.trim().length > 0) {
521
- filters.push(`@.tags contains '${escapeQueryValue(tag)}'`);
522
- }
523
- }
524
- }
525
- if (options?.min_price !== void 0) {
526
- filters.push(`@.price>=${options.min_price}`);
527
- }
528
- if (options?.max_price !== void 0) {
529
- filters.push(`@.price<=${options.max_price}`);
530
- }
531
- if (filters.length > 0) {
532
- query2 += `[?(${filters.join(" && ")})]`;
533
- }
534
- if (options?.sort_by) {
535
- query2 += `#sort(${options.sort_by},${options.sort_order || "asc"})`;
536
- }
537
- if (options?.limit !== void 0) {
538
- query2 += `#limit(${options.limit})`;
539
- }
540
- if (options?.offset !== void 0) {
541
- query2 += `#offset(${options.offset})`;
542
- }
543
409
  const path = withQuery("/api/v1/catalogue/products", {
544
410
  category_id: options?.category,
545
411
  search: options?.search,
@@ -555,325 +421,145 @@ var CatalogueQueries = class {
555
421
  offset: options?.offset,
556
422
  cursor: options?.cursor
557
423
  });
558
- const result = await safeWithFallback(
559
- () => this.client.get(path),
560
- () => this.client.query(query2)
561
- );
424
+ const result = await safe(this.client.get(path));
562
425
  if (!result.ok) return result;
563
426
  return ok(normalizeCatalogueResult(result.value));
564
427
  }
565
428
  async getProduct(id) {
566
429
  const encodedId = encodeURIComponent(id);
567
- const result = await safeWithFallback(
568
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}`),
569
- () => this.client.query(`products.${id}`)
570
- );
430
+ const result = await safe(this.client.get(`/api/v1/catalogue/products/${encodedId}`));
571
431
  if (!result.ok) return result;
572
432
  return ok(normalizeCatalogueProductPayload(result.value));
573
433
  }
574
434
  async getProductBySlug(slug) {
575
435
  const encodedSlug = encodeURIComponent(slug);
576
- const restResult = await safe(
577
- this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`)
578
- );
579
- if (restResult.ok) {
580
- return ok(normalizeCatalogueProductPayload(restResult.value));
581
- }
582
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
583
- return restResult;
584
- }
585
- const filteredResult = await safe(
586
- this.client.query(
587
- `products[?(@.slug=='${escapeQueryValue(slug)}')]#limit(50)`
588
- )
589
- );
590
- if (!filteredResult.ok) return filteredResult;
591
- const exactMatch = findProductBySlug(filteredResult.value, slug);
592
- if (exactMatch) {
593
- return ok(normalizeCatalogueProductPayload(exactMatch));
594
- }
595
- if (filteredResult.value.length === 1) {
596
- return ok(normalizeCatalogueProductPayload(filteredResult.value[0]));
597
- }
598
- const unfilteredResult = await safe(
599
- this.client.query("products#limit(200)")
600
- );
601
- if (!unfilteredResult.ok) return unfilteredResult;
602
- const fallbackMatch = findProductBySlug(unfilteredResult.value, slug);
603
- if (!fallbackMatch) {
604
- return err(new CimplifyError("NOT_FOUND", `Product not found: ${slug}`, false));
605
- }
606
- return ok(normalizeCatalogueProductPayload(fallbackMatch));
436
+ const result = await safe(this.client.get(`/api/v1/catalogue/products/slug/${encodedSlug}`));
437
+ if (!result.ok) return result;
438
+ return ok(normalizeCatalogueProductPayload(result.value));
607
439
  }
608
440
  async getVariants(productId) {
609
441
  const encodedId = encodeURIComponent(productId);
610
- return safeWithFallback(
611
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`),
612
- () => this.client.query(`products.${productId}.variants`)
613
- );
442
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variants`));
614
443
  }
615
444
  async getVariantAxes(productId) {
616
445
  const encodedId = encodeURIComponent(productId);
617
- return safeWithFallback(
618
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`),
619
- () => this.client.query(`products.${productId}.variant_axes`)
620
- );
446
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/variant-axes`));
621
447
  }
622
- /**
623
- * Find a variant by axis selections (e.g., { "Size": "Large", "Color": "Red" })
624
- * Returns the matching variant or null if no match found.
625
- */
626
448
  async getVariantByAxisSelections(productId, selections) {
627
449
  const encodedId = encodeURIComponent(productId);
628
- return safeWithFallback(
629
- () => this.client.post(
450
+ return safe(
451
+ this.client.post(
630
452
  `/api/v1/catalogue/products/${encodedId}/variants/find`,
631
453
  {
632
454
  axis_selections: selections
633
455
  }
634
- ),
635
- () => this.client.query(`products.${productId}.variant`, {
636
- axis_selections: selections
637
- })
456
+ )
638
457
  );
639
458
  }
640
- /**
641
- * Get a specific variant by its ID
642
- */
643
459
  async getVariantById(productId, variantId) {
644
460
  const encodedProductId = encodeURIComponent(productId);
645
461
  const encodedVariantId = encodeURIComponent(variantId);
646
- return safeWithFallback(
647
- () => this.client.get(
462
+ return safe(
463
+ this.client.get(
648
464
  `/api/v1/catalogue/products/${encodedProductId}/variants/${encodedVariantId}`
649
- ),
650
- () => this.client.query(`products.${productId}.variant.${variantId}`)
465
+ )
651
466
  );
652
467
  }
653
468
  async getAddOns(productId) {
654
469
  const encodedId = encodeURIComponent(productId);
655
- return safeWithFallback(
656
- () => this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`),
657
- () => this.client.query(`products.${productId}.add_ons`)
658
- );
470
+ return safe(this.client.get(`/api/v1/catalogue/products/${encodedId}/add-ons`));
659
471
  }
660
472
  async getCategories() {
661
- const result = await safeWithFallback(
662
- () => this.client.get("/api/v1/catalogue/categories"),
663
- () => this.client.query("categories")
664
- );
665
- if (!result.ok) return result;
666
- if (result.value.some(hasCategorySlug)) {
667
- return result;
668
- }
669
- const catalogueResult = await safe(
670
- this.client.query("catalogue#limit(1)")
671
- );
672
- if (!catalogueResult.ok) {
673
- return result;
674
- }
675
- const fallbackCategories = Array.isArray(catalogueResult.value.categories) ? catalogueResult.value.categories : [];
676
- return fallbackCategories.length > 0 ? ok(fallbackCategories) : result;
473
+ return safe(this.client.get("/api/v1/catalogue/categories"));
677
474
  }
678
475
  async getCategory(id) {
679
476
  const encodedId = encodeURIComponent(id);
680
- return safeWithFallback(
681
- () => this.client.get(`/api/v1/catalogue/categories/${encodedId}`),
682
- () => this.client.query(`categories.${id}`)
683
- );
477
+ return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}`));
684
478
  }
685
479
  async getCategoryBySlug(slug) {
686
480
  const encodedSlug = encodeURIComponent(slug);
687
- const restResult = await safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
688
- if (restResult.ok) {
689
- return restResult;
690
- }
691
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
692
- return restResult;
693
- }
694
- const result = await safe(
695
- this.client.query(`categories[?(@.slug=='${escapeQueryValue(slug)}')]`)
696
- );
697
- if (!result.ok) return result;
698
- const exactMatch = findCategoryBySlug(result.value, slug);
699
- if (exactMatch) {
700
- return ok(exactMatch);
701
- }
702
- const categoriesResult = await this.getCategories();
703
- if (!categoriesResult.ok) {
704
- return categoriesResult;
705
- }
706
- const fallbackMatch = findCategoryBySlug(categoriesResult.value, slug);
707
- if (!fallbackMatch) {
708
- return err(new CimplifyError("NOT_FOUND", `Category not found: ${slug}`, false));
709
- }
710
- return ok(fallbackMatch);
481
+ return safe(this.client.get(`/api/v1/catalogue/categories/slug/${encodedSlug}`));
711
482
  }
712
483
  async getCategoryProducts(categoryId) {
713
484
  const encodedId = encodeURIComponent(categoryId);
714
- return safeWithFallback(
715
- () => this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`),
716
- () => this.client.query(
717
- `products[?(@.category_id=='${escapeQueryValue(categoryId)}')]`
718
- )
719
- );
485
+ return safe(this.client.get(`/api/v1/catalogue/categories/${encodedId}/products`));
720
486
  }
721
487
  async getCollections() {
722
- return safeWithFallback(
723
- () => this.client.get("/api/v1/catalogue/collections"),
724
- () => this.client.query("collections")
725
- );
488
+ return safe(this.client.get("/api/v1/catalogue/collections"));
726
489
  }
727
490
  async getCollection(id) {
728
491
  const encodedId = encodeURIComponent(id);
729
- return safeWithFallback(
730
- () => this.client.get(`/api/v1/catalogue/collections/${encodedId}`),
731
- () => this.client.query(`collections.${id}`)
732
- );
492
+ return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}`));
733
493
  }
734
494
  async getCollectionBySlug(slug) {
735
495
  const encodedSlug = encodeURIComponent(slug);
736
- const restResult = await safe(
737
- this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`)
738
- );
739
- if (restResult.ok) return restResult;
740
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
741
- return restResult;
742
- }
743
- const result = await safe(
744
- this.client.query(`collections[?(@.slug=='${escapeQueryValue(slug)}')]`)
745
- );
746
- if (!result.ok) return result;
747
- if (!result.value.length) {
748
- return err(new CimplifyError("NOT_FOUND", `Collection not found: ${slug}`, false));
749
- }
750
- return ok(result.value[0]);
496
+ return safe(this.client.get(`/api/v1/catalogue/collections/slug/${encodedSlug}`));
751
497
  }
752
498
  async getCollectionProducts(collectionId) {
753
499
  const encodedId = encodeURIComponent(collectionId);
754
- return safeWithFallback(
755
- () => this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`),
756
- () => this.client.query(`collections.${collectionId}.products`)
757
- );
500
+ return safe(this.client.get(`/api/v1/catalogue/collections/${encodedId}/products`));
758
501
  }
759
502
  async searchCollections(query2, limit = 20) {
760
503
  const path = withQuery("/api/v1/catalogue/collections", { search: query2, limit });
761
- return safeWithFallback(
762
- () => this.client.get(path),
763
- () => this.client.query(
764
- `collections[?(@.name contains '${escapeQueryValue(query2)}')]#limit(${limit})`
765
- )
766
- );
504
+ return safe(this.client.get(path));
767
505
  }
768
506
  async getBundles() {
769
- return safeWithFallback(
770
- () => this.client.get("/api/v1/catalogue/bundles"),
771
- () => this.client.query("bundles")
772
- );
507
+ return safe(this.client.get("/api/v1/catalogue/bundles"));
773
508
  }
774
509
  async getBundle(id) {
775
510
  const encodedId = encodeURIComponent(id);
776
- return safeWithFallback(
777
- () => this.client.get(`/api/v1/catalogue/bundles/${encodedId}`),
778
- () => this.client.query(`bundles.${id}`)
779
- );
511
+ return safe(this.client.get(`/api/v1/catalogue/bundles/${encodedId}`));
780
512
  }
781
513
  async getBundleBySlug(slug) {
782
514
  const encodedSlug = encodeURIComponent(slug);
783
- const restResult = await safe(
784
- this.client.get(`/api/v1/catalogue/bundles/slug/${encodedSlug}`)
785
- );
786
- if (restResult.ok) return restResult;
787
- if (restResult.error.code !== "HTTP_404" && restResult.error.code !== "API_ERROR") {
788
- return restResult;
789
- }
790
- const result = await safe(
791
- this.client.query(
792
- `bundles[?(@.slug=='${escapeQueryValue(slug)}')]`
793
- )
794
- );
795
- if (!result.ok) return result;
796
- if (!result.value.length) {
797
- return err(new CimplifyError("NOT_FOUND", `Bundle not found: ${slug}`, false));
798
- }
799
- return ok(result.value[0]);
515
+ return safe(this.client.get(`/api/v1/catalogue/bundles/slug/${encodedSlug}`));
800
516
  }
801
517
  async searchBundles(query2, limit = 20) {
802
518
  const path = withQuery("/api/v1/catalogue/bundles", { search: query2, limit });
803
- return safeWithFallback(
804
- () => this.client.get(path),
805
- () => this.client.query(
806
- `bundles[?(@.name contains '${escapeQueryValue(query2)}')]#limit(${limit})`
807
- )
808
- );
519
+ return safe(this.client.get(path));
809
520
  }
810
521
  async getComposites(options) {
811
- let query2 = "composites";
812
- if (options?.limit) {
813
- query2 += `#limit(${options.limit})`;
814
- }
815
522
  const path = withQuery("/api/v1/catalogue/composites", { limit: options?.limit });
816
- return safeWithFallback(
817
- () => this.client.get(path),
818
- () => this.client.query(query2)
819
- );
523
+ return safe(this.client.get(path));
820
524
  }
821
525
  async getComposite(id) {
822
526
  const encodedId = encodeURIComponent(id);
823
- return safeWithFallback(
824
- () => this.client.get(`/api/v1/catalogue/composites/${encodedId}`),
825
- () => this.client.query(`composites.${id}`)
826
- );
527
+ return safe(this.client.get(`/api/v1/catalogue/composites/${encodedId}`));
827
528
  }
828
529
  async getCompositeByProductId(productId) {
829
530
  const encodedId = encodeURIComponent(productId);
830
- return safeWithFallback(
831
- () => this.client.get(
531
+ return safe(
532
+ this.client.get(
832
533
  `/api/v1/catalogue/composites/by-product/${encodedId}`
833
- ),
834
- () => this.client.query(`composites.by_product.${productId}`)
534
+ )
835
535
  );
836
536
  }
837
537
  async calculateCompositePrice(compositeId, selections, locationId) {
838
538
  const encodedId = encodeURIComponent(compositeId);
839
- return safeWithFallback(
840
- () => this.client.post(
539
+ return safe(
540
+ this.client.post(
841
541
  `/api/v1/catalogue/composites/${encodedId}/calculate-price`,
842
542
  {
843
543
  selections,
844
544
  location_id: locationId
845
545
  }
846
- ),
847
- () => this.client.call("composite.calculatePrice", {
848
- composite_id: compositeId,
849
- selections,
850
- location_id: locationId
851
- })
546
+ )
852
547
  );
853
548
  }
854
549
  async fetchQuote(input) {
855
- return safeWithFallback(
856
- () => this.client.post("/api/v1/catalogue/quotes", input),
857
- () => this.client.call("catalogue.createQuote", input)
858
- );
550
+ return safe(this.client.post("/api/v1/catalogue/quotes", input));
859
551
  }
860
552
  async getQuote(quoteId) {
861
553
  const encodedQuoteId = encodeURIComponent(quoteId);
862
- return safeWithFallback(
863
- () => this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`),
864
- () => this.client.call("catalogue.getQuote", {
865
- quote_id: quoteId
866
- })
867
- );
554
+ return safe(this.client.get(`/api/v1/catalogue/quotes/${encodedQuoteId}`));
868
555
  }
869
556
  async refreshQuote(input) {
870
557
  const encodedQuoteId = encodeURIComponent(input.quote_id);
871
- return safeWithFallback(
872
- () => this.client.post(
558
+ return safe(
559
+ this.client.post(
873
560
  `/api/v1/catalogue/quotes/${encodedQuoteId}/refresh`,
874
561
  input
875
- ),
876
- () => this.client.call("catalogue.refreshQuote", input)
562
+ )
877
563
  );
878
564
  }
879
565
  async search(query2, options) {
@@ -889,35 +575,19 @@ var CatalogueQueries = class {
889
575
  return this.search(query2, options);
890
576
  }
891
577
  async getMenu(options) {
892
- let query2 = "menu";
893
- if (options?.category) {
894
- query2 = `menu[?(@.category=='${escapeQueryValue(options.category)}')]`;
895
- }
896
- if (options?.limit) {
897
- query2 += `#limit(${options.limit})`;
898
- }
899
578
  const path = withQuery("/api/v1/catalogue/menu", {
900
579
  category_id: options?.category,
901
580
  limit: options?.limit
902
581
  });
903
- return safeWithFallback(
904
- () => this.client.get(path),
905
- () => this.client.query(query2)
906
- );
582
+ return safe(this.client.get(path));
907
583
  }
908
584
  async getMenuCategory(categoryId) {
909
585
  const encodedId = encodeURIComponent(categoryId);
910
- return safeWithFallback(
911
- () => this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`),
912
- () => this.client.query(`menu.category.${categoryId}`)
913
- );
586
+ return safe(this.client.get(`/api/v1/catalogue/menu/categories/${encodedId}`));
914
587
  }
915
588
  async getMenuItem(itemId) {
916
589
  const encodedId = encodeURIComponent(itemId);
917
- return safeWithFallback(
918
- () => this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`),
919
- () => this.client.query(`menu.${itemId}`)
920
- );
590
+ return safe(this.client.get(`/api/v1/catalogue/menu/items/${encodedId}`));
921
591
  }
922
592
  };
923
593
 
@@ -936,14 +606,6 @@ async function safe2(promise) {
936
606
  return err(toCimplifyError2(error));
937
607
  }
938
608
  }
939
- async function safeWithFallback2(primary, fallback) {
940
- const primaryResult = await safe2(primary());
941
- if (primaryResult.ok) return primaryResult;
942
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
943
- return primaryResult;
944
- }
945
- return safe2(fallback());
946
- }
947
609
  function isUICartResponse(value) {
948
610
  return "cart" in value;
949
611
  }
@@ -955,36 +617,21 @@ var CartOperations = class {
955
617
  this.client = client;
956
618
  }
957
619
  async get() {
958
- const result = await safeWithFallback2(
959
- () => this.client.get("/api/v1/cart"),
960
- () => this.client.query("cart#enriched")
961
- );
620
+ const result = await safe2(this.client.get("/api/v1/cart"));
962
621
  if (!result.ok) return result;
963
622
  return ok(unwrapEnrichedCart(result.value));
964
623
  }
965
624
  async getRaw() {
966
- return safeWithFallback2(
967
- () => this.client.get("/api/v1/cart"),
968
- () => this.client.query("cart")
969
- );
625
+ return safe2(this.client.get("/api/v1/cart"));
970
626
  }
971
627
  async getItems() {
972
- return safeWithFallback2(
973
- () => this.client.get("/api/v1/cart/items"),
974
- () => this.client.query("cart_items")
975
- );
628
+ return safe2(this.client.get("/api/v1/cart/items"));
976
629
  }
977
630
  async getCount() {
978
- return safeWithFallback2(
979
- () => this.client.get("/api/v1/cart/count"),
980
- () => this.client.query("cart#count")
981
- );
631
+ return safe2(this.client.get("/api/v1/cart/count"));
982
632
  }
983
633
  async getTotal() {
984
- return safeWithFallback2(
985
- () => this.client.get("/api/v1/cart/total"),
986
- () => this.client.query("cart#total")
987
- );
634
+ return safe2(this.client.get("/api/v1/cart/total"));
988
635
  }
989
636
  async getSummary() {
990
637
  const cartResult = await this.get();
@@ -1001,66 +648,39 @@ var CartOperations = class {
1001
648
  });
1002
649
  }
1003
650
  async addItem(input) {
1004
- return safeWithFallback2(
1005
- () => this.client.post("/api/v1/cart/items", input),
1006
- () => this.client.call("cart.addItem", input)
1007
- );
651
+ return safe2(this.client.post("/api/v1/cart/items", input));
1008
652
  }
1009
653
  async updateItem(cartItemId, updates) {
1010
654
  if (typeof updates.quantity === "number") {
1011
655
  return this.updateQuantity(cartItemId, updates.quantity);
1012
656
  }
1013
657
  const encodedId = encodeURIComponent(cartItemId);
1014
- return safeWithFallback2(
1015
- () => this.client.patch(`/api/v1/cart/items/${encodedId}`, updates),
1016
- () => this.client.call("cart.updateItem", {
1017
- cart_item_id: cartItemId,
1018
- ...updates
1019
- })
1020
- );
658
+ return safe2(this.client.patch(`/api/v1/cart/items/${encodedId}`, updates));
1021
659
  }
1022
660
  async updateQuantity(cartItemId, quantity) {
1023
661
  const encodedId = encodeURIComponent(cartItemId);
1024
- return safeWithFallback2(
1025
- () => this.client.patch(`/api/v1/cart/items/${encodedId}`, {
1026
- quantity
1027
- }),
1028
- () => this.client.call("cart.updateItemQuantity", {
1029
- cart_item_id: cartItemId,
662
+ return safe2(
663
+ this.client.patch(`/api/v1/cart/items/${encodedId}`, {
1030
664
  quantity
1031
665
  })
1032
666
  );
1033
667
  }
1034
668
  async removeItem(cartItemId) {
1035
669
  const encodedId = encodeURIComponent(cartItemId);
1036
- return safeWithFallback2(
1037
- () => this.client.delete(`/api/v1/cart/items/${encodedId}`),
1038
- () => this.client.call("cart.removeItem", {
1039
- cart_item_id: cartItemId
1040
- })
1041
- );
670
+ return safe2(this.client.delete(`/api/v1/cart/items/${encodedId}`));
1042
671
  }
1043
672
  async clear() {
1044
- return safeWithFallback2(
1045
- () => this.client.delete("/api/v1/cart"),
1046
- () => this.client.call("cart.clearCart")
1047
- );
673
+ return safe2(this.client.delete("/api/v1/cart"));
1048
674
  }
1049
675
  async applyCoupon(code) {
1050
- return safeWithFallback2(
1051
- () => this.client.post("/api/v1/cart/coupons", {
1052
- coupon_code: code
1053
- }),
1054
- () => this.client.call("cart.applyCoupon", {
676
+ return safe2(
677
+ this.client.post("/api/v1/cart/coupons", {
1055
678
  coupon_code: code
1056
679
  })
1057
680
  );
1058
681
  }
1059
682
  async removeCoupon() {
1060
- return safeWithFallback2(
1061
- () => this.client.delete("/api/v1/cart/coupons/current"),
1062
- () => this.client.call("cart.removeCoupon")
1063
- );
683
+ return safe2(this.client.delete("/api/v1/cart/coupons/current"));
1064
684
  }
1065
685
  async isEmpty() {
1066
686
  const countResult = await this.getCount();
@@ -1097,105 +717,6 @@ var CartOperations = class {
1097
717
  }
1098
718
  };
1099
719
 
1100
- // src/constants.ts
1101
- var CHECKOUT_MODE = {
1102
- LINK: "link",
1103
- GUEST: "guest"
1104
- };
1105
- var ORDER_TYPE = {
1106
- DELIVERY: "delivery",
1107
- PICKUP: "pickup",
1108
- DINE_IN: "dine-in",
1109
- WALK_IN: "walk-in"
1110
- };
1111
- var PAYMENT_METHOD = {
1112
- MOBILE_MONEY: "mobile_money",
1113
- CARD: "card"
1114
- };
1115
- var CHECKOUT_STEP = {
1116
- AUTHENTICATION: "authentication",
1117
- ORDER_DETAILS: "order_details",
1118
- PAYMENT_METHOD: "payment_method",
1119
- PAYMENT: "payment",
1120
- CONFIRMATION: "confirmation"
1121
- };
1122
- var PAYMENT_STATE = {
1123
- INITIAL: "initial",
1124
- PREPARING: "preparing",
1125
- PROCESSING: "processing",
1126
- VERIFYING: "verifying",
1127
- AWAITING_AUTHORIZATION: "awaiting_authorization",
1128
- SUCCESS: "success",
1129
- ERROR: "error",
1130
- TIMEOUT: "timeout"
1131
- };
1132
- var PICKUP_TIME_TYPE = {
1133
- ASAP: "asap",
1134
- SCHEDULED: "scheduled"
1135
- };
1136
- var MOBILE_MONEY_PROVIDER = {
1137
- MTN: "mtn",
1138
- VODAFONE: "vodafone",
1139
- AIRTEL: "airtel"
1140
- };
1141
- var AUTHORIZATION_TYPE = {
1142
- OTP: "otp",
1143
- PIN: "pin",
1144
- PHONE: "phone",
1145
- BIRTHDAY: "birthday",
1146
- ADDRESS: "address"
1147
- };
1148
- var DEVICE_TYPE = {
1149
- MOBILE: "mobile",
1150
- DESKTOP: "desktop",
1151
- TABLET: "tablet"
1152
- };
1153
- var CONTACT_TYPE = {
1154
- PHONE: "phone",
1155
- EMAIL: "email"
1156
- };
1157
- var LINK_QUERY = {
1158
- DATA: "link.data",
1159
- ADDRESSES: "link.addresses",
1160
- MOBILE_MONEY: "link.mobile_money",
1161
- PREFERENCES: "link.preferences",
1162
- SESSIONS: "link.sessions"
1163
- };
1164
- var LINK_MUTATION = {
1165
- CHECK_STATUS: "link.check_status",
1166
- ENROLL: "link.enroll",
1167
- ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
1168
- UPDATE_PREFERENCES: "link.update_preferences",
1169
- CREATE_ADDRESS: "link.create_address",
1170
- UPDATE_ADDRESS: "link.update_address",
1171
- DELETE_ADDRESS: "link.delete_address",
1172
- SET_DEFAULT_ADDRESS: "link.set_default_address",
1173
- TRACK_ADDRESS_USAGE: "link.track_address_usage",
1174
- CREATE_MOBILE_MONEY: "link.create_mobile_money",
1175
- DELETE_MOBILE_MONEY: "link.delete_mobile_money",
1176
- SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
1177
- TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
1178
- VERIFY_MOBILE_MONEY: "link.verify_mobile_money",
1179
- REVOKE_SESSION: "link.revoke_session",
1180
- REVOKE_ALL_SESSIONS: "link.revoke_all_sessions"
1181
- };
1182
- var AUTH_MUTATION = {
1183
- REQUEST_OTP: "auth.request_otp",
1184
- VERIFY_OTP: "auth.verify_otp"
1185
- };
1186
- var CHECKOUT_MUTATION = {
1187
- PROCESS: "checkout.process"
1188
- };
1189
- var PAYMENT_MUTATION = {
1190
- SUBMIT_AUTHORIZATION: "payment.submit_authorization",
1191
- CHECK_STATUS: "order.poll_payment_status"
1192
- };
1193
- var ORDER_MUTATION = {
1194
- UPDATE_CUSTOMER: "order.update_order_customer"
1195
- };
1196
- var DEFAULT_CURRENCY = "GHS";
1197
- var DEFAULT_COUNTRY = "GHA";
1198
-
1199
720
  // src/utils/price.ts
1200
721
  var CURRENCY_SYMBOLS = {
1201
722
  // Major world currencies
@@ -2222,14 +1743,6 @@ async function safe3(promise) {
2222
1743
  return err(toCimplifyError3(error));
2223
1744
  }
2224
1745
  }
2225
- async function safeWithFallback3(primary, fallback) {
2226
- const primaryResult = await safe3(primary());
2227
- if (primaryResult.ok) return primaryResult;
2228
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2229
- return primaryResult;
2230
- }
2231
- return safe3(fallback());
2232
- }
2233
1746
  function toTerminalFailure(code, message, recoverable) {
2234
1747
  return {
2235
1748
  success: false,
@@ -2252,57 +1765,51 @@ var CheckoutService = class {
2252
1765
  constructor(client) {
2253
1766
  this.client = client;
2254
1767
  }
1768
+ orderTokenParam(orderId) {
1769
+ const token = this.client.getOrderToken(orderId);
1770
+ return token ? `?token=${encodeURIComponent(token)}` : "";
1771
+ }
2255
1772
  async process(data) {
2256
1773
  const checkoutData = {
2257
1774
  ...data,
2258
1775
  idempotency_key: data.idempotency_key || generateIdempotencyKey()
2259
1776
  };
2260
- return safeWithFallback3(
2261
- () => this.client.post("/api/v1/checkout", {
2262
- checkout_data: checkoutData
2263
- }),
2264
- () => this.client.call(CHECKOUT_MUTATION.PROCESS, {
1777
+ const result = await safe3(
1778
+ this.client.post("/api/v1/checkout", {
2265
1779
  checkout_data: checkoutData
2266
1780
  })
2267
1781
  );
1782
+ if (result.ok && result.value.bill_token) {
1783
+ this.client.setOrderToken(result.value.order_id, result.value.bill_token);
1784
+ }
1785
+ return result;
2268
1786
  }
2269
- async initializePayment(orderId, method) {
2270
- return safe3(
2271
- this.client.call("order.initializePayment", {
2272
- order_id: orderId,
2273
- payment_method: method
2274
- })
1787
+ async initializePayment(_orderId, _method) {
1788
+ return err(
1789
+ new CimplifyError(
1790
+ "NOT_IMPLEMENTED",
1791
+ "initializePayment is not available in REST mode.",
1792
+ false
1793
+ )
2275
1794
  );
2276
1795
  }
2277
1796
  async submitAuthorization(input) {
2278
- return safeWithFallback3(
2279
- () => this.client.post("/api/v1/payments/authorization", input),
2280
- () => this.client.call(PAYMENT_MUTATION.SUBMIT_AUTHORIZATION, input)
2281
- );
1797
+ return safe3(this.client.post("/api/v1/payments/authorization", input));
2282
1798
  }
2283
1799
  async pollPaymentStatus(orderId) {
2284
1800
  const encodedId = encodeURIComponent(orderId);
2285
- return safeWithFallback3(
2286
- () => this.client.get(`/api/v1/orders/${encodedId}/payment-status`),
2287
- () => this.client.call(PAYMENT_MUTATION.CHECK_STATUS, orderId)
2288
- );
1801
+ const tokenParam = this.orderTokenParam(orderId);
1802
+ return safe3(this.client.get(`/api/v1/orders/${encodedId}/payment-status${tokenParam}`));
2289
1803
  }
2290
1804
  async updateOrderCustomer(orderId, customer) {
2291
1805
  const encodedId = encodeURIComponent(orderId);
2292
- return safeWithFallback3(
2293
- () => this.client.post(`/api/v1/orders/${encodedId}/customer`, customer),
2294
- () => this.client.call(ORDER_MUTATION.UPDATE_CUSTOMER, {
2295
- order_id: orderId,
2296
- ...customer
2297
- })
2298
- );
1806
+ const tokenParam = this.orderTokenParam(orderId);
1807
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/customer${tokenParam}`, customer));
2299
1808
  }
2300
1809
  async verifyPayment(orderId) {
2301
- return safe3(
2302
- this.client.call("order.verifyPayment", {
2303
- order_id: orderId
2304
- })
2305
- );
1810
+ const encodedId = encodeURIComponent(orderId);
1811
+ const tokenParam = this.orderTokenParam(orderId);
1812
+ return safe3(this.client.post(`/api/v1/orders/${encodedId}/verify-payment${tokenParam}`));
2306
1813
  }
2307
1814
  async processAndResolve(data) {
2308
1815
  data.on_status_change?.("preparing", {});
@@ -2421,61 +1928,38 @@ async function safe4(promise) {
2421
1928
  return err(toCimplifyError4(error));
2422
1929
  }
2423
1930
  }
2424
- async function safeWithFallback4(primary, fallback) {
2425
- const primaryResult = await safe4(primary());
2426
- if (primaryResult.ok) return primaryResult;
2427
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2428
- return primaryResult;
2429
- }
2430
- return safe4(fallback());
2431
- }
2432
1931
  var OrderQueries = class {
2433
1932
  constructor(client) {
2434
1933
  this.client = client;
2435
1934
  }
1935
+ orderTokenParam(orderId) {
1936
+ const token = this.client.getOrderToken(orderId);
1937
+ return token ? `?token=${encodeURIComponent(token)}` : "";
1938
+ }
2436
1939
  async list(options) {
2437
- let query2 = "orders";
2438
- if (options?.status) {
2439
- query2 += `[?(@.status=='${options.status}')]`;
2440
- }
2441
- query2 += "#sort(created_at,desc)";
2442
- if (options?.limit) {
2443
- query2 += `#limit(${options.limit})`;
2444
- }
2445
- if (options?.offset) {
2446
- query2 += `#offset(${options.offset})`;
2447
- }
2448
1940
  const params = new URLSearchParams();
2449
1941
  if (options?.status) params.set("status", options.status);
2450
1942
  if (options?.limit) params.set("limit", String(options.limit));
2451
1943
  if (options?.offset) params.set("offset", String(options.offset));
2452
1944
  const path = params.toString() ? `/api/v1/orders?${params.toString()}` : "/api/v1/orders";
2453
- return safeWithFallback4(
2454
- () => this.client.get(path),
2455
- () => this.client.query(query2)
2456
- );
1945
+ return safe4(this.client.get(path));
2457
1946
  }
2458
1947
  async get(orderId) {
2459
1948
  const encodedId = encodeURIComponent(orderId);
2460
- return safeWithFallback4(
2461
- () => this.client.get(`/api/v1/orders/${encodedId}`),
2462
- () => this.client.query(`orders.${orderId}`)
2463
- );
1949
+ const tokenParam = this.orderTokenParam(orderId);
1950
+ return safe4(this.client.get(`/api/v1/orders/${encodedId}${tokenParam}`));
2464
1951
  }
2465
1952
  async getRecent(limit = 5) {
2466
- return safe4(this.client.query(`orders#sort(created_at,desc)#limit(${limit})`));
1953
+ return this.list({ limit });
2467
1954
  }
2468
1955
  async getByStatus(status) {
2469
1956
  return this.list({ status });
2470
1957
  }
2471
1958
  async cancel(orderId, reason) {
2472
1959
  const encodedId = encodeURIComponent(orderId);
2473
- return safeWithFallback4(
2474
- () => this.client.post(`/api/v1/orders/${encodedId}/cancel`, {
2475
- reason
2476
- }),
2477
- () => this.client.call("order.cancelOrder", {
2478
- order_id: orderId,
1960
+ const tokenParam = this.orderTokenParam(orderId);
1961
+ return safe4(
1962
+ this.client.post(`/api/v1/orders/${encodedId}/cancel${tokenParam}`, {
2479
1963
  reason
2480
1964
  })
2481
1965
  );
@@ -2497,6 +1981,38 @@ async function safe5(promise) {
2497
1981
  return err(toCimplifyError5(error));
2498
1982
  }
2499
1983
  }
1984
+ function encodePathSegment(value) {
1985
+ return encodeURIComponent(value);
1986
+ }
1987
+ function toCreateAddressPayload(input) {
1988
+ return {
1989
+ label: input.label,
1990
+ street_address: input.address_line1,
1991
+ apartment: input.address_line2,
1992
+ city: input.city,
1993
+ region: input.state ?? "",
1994
+ postal_code: input.postal_code,
1995
+ country: input.country
1996
+ };
1997
+ }
1998
+ function toUpdateAddressPayload(input) {
1999
+ return {
2000
+ label: input.label,
2001
+ street_address: input.address_line1,
2002
+ apartment: input.address_line2,
2003
+ city: input.city,
2004
+ region: input.state,
2005
+ postal_code: input.postal_code,
2006
+ country: input.country
2007
+ };
2008
+ }
2009
+ function toCreateMobileMoneyPayload(input) {
2010
+ return {
2011
+ phone_number: input.phone_number,
2012
+ provider: input.provider,
2013
+ label: input.account_name
2014
+ };
2015
+ }
2500
2016
  var LinkService = class {
2501
2017
  constructor(client) {
2502
2018
  this.client = client;
@@ -2524,11 +2040,7 @@ var LinkService = class {
2524
2040
  return result;
2525
2041
  }
2526
2042
  async checkStatus(contact) {
2527
- return safe5(
2528
- this.client.call(LINK_MUTATION.CHECK_STATUS, {
2529
- contact
2530
- })
2531
- );
2043
+ return safe5(this.client.linkPost("/v1/link/check-status", { contact }));
2532
2044
  }
2533
2045
  async getLinkData() {
2534
2046
  return safe5(this.client.linkGet("/v1/link/data"));
@@ -2540,61 +2052,85 @@ var LinkService = class {
2540
2052
  return safe5(this.client.linkGet("/v1/link/mobile-money"));
2541
2053
  }
2542
2054
  async getPreferences() {
2543
- return safe5(this.client.query(LINK_QUERY.PREFERENCES));
2055
+ return safe5(this.client.linkGet("/v1/link/preferences"));
2544
2056
  }
2545
2057
  async enroll(data) {
2546
- return safe5(this.client.call(LINK_MUTATION.ENROLL, data));
2058
+ return safe5(this.client.linkPost("/v1/link/enroll", data));
2547
2059
  }
2548
2060
  async enrollAndLinkOrder(data) {
2549
2061
  return safe5(
2550
- this.client.call(LINK_MUTATION.ENROLL_AND_LINK_ORDER, data)
2062
+ this.client.linkPost("/v1/link/enroll-and-link-order", data)
2551
2063
  );
2552
2064
  }
2553
2065
  async updatePreferences(preferences) {
2554
- return safe5(this.client.call(LINK_MUTATION.UPDATE_PREFERENCES, preferences));
2066
+ return safe5(this.client.linkPost("/v1/link/preferences", preferences));
2555
2067
  }
2556
2068
  async createAddress(input) {
2557
- return safe5(this.client.call(LINK_MUTATION.CREATE_ADDRESS, input));
2069
+ return safe5(
2070
+ this.client.linkPost("/v1/link/addresses", toCreateAddressPayload(input))
2071
+ );
2558
2072
  }
2559
2073
  async updateAddress(input) {
2560
- return safe5(this.client.call(LINK_MUTATION.UPDATE_ADDRESS, input));
2074
+ return safe5(
2075
+ this.client.linkPost(
2076
+ `/v1/link/addresses/${encodePathSegment(input.address_id)}`,
2077
+ toUpdateAddressPayload(input)
2078
+ )
2079
+ );
2561
2080
  }
2562
2081
  async deleteAddress(addressId) {
2563
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2082
+ return safe5(
2083
+ this.client.linkDelete(`/v1/link/addresses/${encodePathSegment(addressId)}`)
2084
+ );
2564
2085
  }
2565
2086
  async setDefaultAddress(addressId) {
2566
- return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
2087
+ return safe5(
2088
+ this.client.linkPost(
2089
+ `/v1/link/addresses/${encodePathSegment(addressId)}/default`
2090
+ )
2091
+ );
2567
2092
  }
2568
2093
  async trackAddressUsage(addressId) {
2569
2094
  return safe5(
2570
- this.client.call(LINK_MUTATION.TRACK_ADDRESS_USAGE, {
2571
- address_id: addressId
2572
- })
2095
+ this.client.linkPost(
2096
+ `/v1/link/addresses/${encodePathSegment(addressId)}/track-usage`
2097
+ )
2573
2098
  );
2574
2099
  }
2575
2100
  async createMobileMoney(input) {
2576
- return safe5(this.client.call(LINK_MUTATION.CREATE_MOBILE_MONEY, input));
2101
+ return safe5(
2102
+ this.client.linkPost(
2103
+ "/v1/link/mobile-money",
2104
+ toCreateMobileMoneyPayload(input)
2105
+ )
2106
+ );
2577
2107
  }
2578
2108
  async deleteMobileMoney(mobileMoneyId) {
2579
2109
  return safe5(
2580
- this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`)
2110
+ this.client.linkDelete(
2111
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}`
2112
+ )
2581
2113
  );
2582
2114
  }
2583
2115
  async setDefaultMobileMoney(mobileMoneyId) {
2584
2116
  return safe5(
2585
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2117
+ this.client.linkPost(
2118
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/default`
2119
+ )
2586
2120
  );
2587
2121
  }
2588
2122
  async trackMobileMoneyUsage(mobileMoneyId) {
2589
2123
  return safe5(
2590
- this.client.call(LINK_MUTATION.TRACK_MOBILE_MONEY_USAGE, {
2591
- mobile_money_id: mobileMoneyId
2592
- })
2124
+ this.client.linkPost(
2125
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/track-usage`
2126
+ )
2593
2127
  );
2594
2128
  }
2595
2129
  async verifyMobileMoney(mobileMoneyId) {
2596
2130
  return safe5(
2597
- this.client.call(LINK_MUTATION.VERIFY_MOBILE_MONEY, mobileMoneyId)
2131
+ this.client.linkPost(
2132
+ `/v1/link/mobile-money/${encodePathSegment(mobileMoneyId)}/verify`
2133
+ )
2598
2134
  );
2599
2135
  }
2600
2136
  async getSessions() {
@@ -2607,30 +2143,28 @@ var LinkService = class {
2607
2143
  return safe5(this.client.linkDelete("/v1/link/sessions"));
2608
2144
  }
2609
2145
  async getAddressesRest() {
2610
- return safe5(this.client.linkGet("/v1/link/addresses"));
2146
+ return this.getAddresses();
2611
2147
  }
2612
2148
  async createAddressRest(input) {
2613
- return safe5(this.client.linkPost("/v1/link/addresses", input));
2149
+ return this.createAddress(input);
2614
2150
  }
2615
2151
  async deleteAddressRest(addressId) {
2616
- return safe5(this.client.linkDelete(`/v1/link/addresses/${addressId}`));
2152
+ return this.deleteAddress(addressId);
2617
2153
  }
2618
2154
  async setDefaultAddressRest(addressId) {
2619
- return safe5(this.client.linkPost(`/v1/link/addresses/${addressId}/default`));
2155
+ return this.setDefaultAddress(addressId);
2620
2156
  }
2621
2157
  async getMobileMoneyRest() {
2622
- return safe5(this.client.linkGet("/v1/link/mobile-money"));
2158
+ return this.getMobileMoney();
2623
2159
  }
2624
2160
  async createMobileMoneyRest(input) {
2625
- return safe5(this.client.linkPost("/v1/link/mobile-money", input));
2161
+ return this.createMobileMoney(input);
2626
2162
  }
2627
2163
  async deleteMobileMoneyRest(mobileMoneyId) {
2628
- return safe5(this.client.linkDelete(`/v1/link/mobile-money/${mobileMoneyId}`));
2164
+ return this.deleteMobileMoney(mobileMoneyId);
2629
2165
  }
2630
2166
  async setDefaultMobileMoneyRest(mobileMoneyId) {
2631
- return safe5(
2632
- this.client.linkPost(`/v1/link/mobile-money/${mobileMoneyId}/default`)
2633
- );
2167
+ return this.setDefaultMobileMoney(mobileMoneyId);
2634
2168
  }
2635
2169
  };
2636
2170
 
@@ -2649,23 +2183,12 @@ async function safe6(promise) {
2649
2183
  return err(toCimplifyError6(error));
2650
2184
  }
2651
2185
  }
2652
- async function safeWithFallback5(primary, fallback) {
2653
- const primaryResult = await safe6(primary());
2654
- if (primaryResult.ok) return primaryResult;
2655
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2656
- return primaryResult;
2657
- }
2658
- return safe6(fallback());
2659
- }
2660
2186
  var AuthService = class {
2661
2187
  constructor(client) {
2662
2188
  this.client = client;
2663
2189
  }
2664
2190
  async getStatus() {
2665
- return safeWithFallback5(
2666
- () => this.client.get("/api/v1/auth/status"),
2667
- () => this.client.query("auth")
2668
- );
2191
+ return safe6(this.client.get("/api/v1/auth/status"));
2669
2192
  }
2670
2193
  async getCurrentUser() {
2671
2194
  const result = await this.getStatus();
@@ -2678,43 +2201,26 @@ var AuthService = class {
2678
2201
  return ok(result.value.is_authenticated);
2679
2202
  }
2680
2203
  async requestOtp(contact, contactType) {
2681
- return safeWithFallback5(
2682
- () => this.client.post("/api/v1/auth/request-otp", {
2683
- contact,
2684
- contact_type: contactType
2685
- }),
2686
- () => this.client.call(AUTH_MUTATION.REQUEST_OTP, {
2204
+ return safe6(
2205
+ this.client.post("/api/v1/auth/request-otp", {
2687
2206
  contact,
2688
2207
  contact_type: contactType
2689
2208
  })
2690
2209
  );
2691
2210
  }
2692
2211
  async verifyOtp(code, contact) {
2693
- return safeWithFallback5(
2694
- () => this.client.post("/api/v1/auth/verify-otp", {
2695
- otp_code: code,
2696
- contact
2697
- }),
2698
- () => this.client.call(AUTH_MUTATION.VERIFY_OTP, {
2212
+ return safe6(
2213
+ this.client.post("/api/v1/auth/verify-otp", {
2699
2214
  otp_code: code,
2700
2215
  contact
2701
2216
  })
2702
2217
  );
2703
2218
  }
2704
2219
  async logout() {
2705
- return safeWithFallback5(
2706
- () => this.client.post("/api/v1/auth/logout"),
2707
- () => this.client.call("auth.logout")
2708
- );
2220
+ return safe6(this.client.post("/api/v1/auth/logout"));
2709
2221
  }
2710
2222
  async updateProfile(input) {
2711
- return safe6(this.client.call("auth.update_profile", input));
2712
- }
2713
- async changePassword(input) {
2714
- return safe6(this.client.call("auth.change_password", input));
2715
- }
2716
- async resetPassword(email) {
2717
- return safe6(this.client.call("auth.reset_password", { email }));
2223
+ return safe6(this.client.post("/api/v1/auth/profile", input));
2718
2224
  }
2719
2225
  };
2720
2226
 
@@ -2733,47 +2239,29 @@ async function safe7(promise) {
2733
2239
  return err(toCimplifyError7(error));
2734
2240
  }
2735
2241
  }
2736
- async function safeWithFallback6(primary, fallback) {
2737
- const primaryResult = await safe7(primary());
2738
- if (primaryResult.ok) return primaryResult;
2739
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
2740
- return primaryResult;
2741
- }
2742
- return safe7(fallback());
2743
- }
2744
2242
  var BusinessService = class {
2745
2243
  constructor(client) {
2746
2244
  this.client = client;
2747
2245
  }
2748
2246
  async getInfo() {
2749
- return safeWithFallback6(
2750
- () => this.client.get("/api/v1/business"),
2751
- () => this.client.query("business.info")
2752
- );
2247
+ return safe7(this.client.get("/api/v1/business"));
2753
2248
  }
2754
2249
  async getByHandle(handle) {
2755
- return safe7(this.client.query(`business.handle.${handle}`));
2250
+ const encodedHandle = encodeURIComponent(handle);
2251
+ return safe7(this.client.get(`/api/v1/business/by-handle/${encodedHandle}`));
2756
2252
  }
2757
2253
  async getByDomain(domain) {
2758
- return safe7(this.client.query("business.domain", { domain }));
2254
+ const encodedDomain = encodeURIComponent(domain);
2255
+ return safe7(this.client.get(`/api/v1/business/by-domain?domain=${encodedDomain}`));
2759
2256
  }
2760
2257
  async getSettings() {
2761
- return safeWithFallback6(
2762
- () => this.client.get("/api/v1/business/settings"),
2763
- () => this.client.query("business.settings")
2764
- );
2258
+ return safe7(this.client.get("/api/v1/business/settings"));
2765
2259
  }
2766
2260
  async getTheme() {
2767
- return safeWithFallback6(
2768
- () => this.client.get("/api/v1/business/theme"),
2769
- () => this.client.query("business.theme")
2770
- );
2261
+ return safe7(this.client.get("/api/v1/business/theme"));
2771
2262
  }
2772
2263
  async getLocations() {
2773
- return safeWithFallback6(
2774
- () => this.client.get("/api/v1/business/locations"),
2775
- () => this.client.query("business.locations")
2776
- );
2264
+ return safe7(this.client.get("/api/v1/business/locations"));
2777
2265
  }
2778
2266
  async getLocation(locationId) {
2779
2267
  const result = await this.getLocations();
@@ -2785,10 +2273,7 @@ var BusinessService = class {
2785
2273
  return ok(location);
2786
2274
  }
2787
2275
  async getHours() {
2788
- return safeWithFallback6(
2789
- () => this.client.get("/api/v1/business/hours"),
2790
- () => this.client.query("business.hours")
2791
- );
2276
+ return safe7(this.client.get("/api/v1/business/hours"));
2792
2277
  }
2793
2278
  async getLocationHours(locationId) {
2794
2279
  const result = await this.getHours();
@@ -2796,31 +2281,7 @@ var BusinessService = class {
2796
2281
  return ok(result.value.filter((hour) => hour.location_id === locationId));
2797
2282
  }
2798
2283
  async getBootstrap() {
2799
- const restBootstrap = await safe7(this.client.get("/api/v1/bootstrap"));
2800
- if (restBootstrap.ok) {
2801
- return restBootstrap;
2802
- }
2803
- const [businessResult, locationsResult, categoriesResult] = await Promise.all([
2804
- this.getInfo(),
2805
- this.getLocations(),
2806
- safe7(this.client.query("categories#select(id,name,slug)"))
2807
- ]);
2808
- if (!businessResult.ok) return businessResult;
2809
- if (!locationsResult.ok) return locationsResult;
2810
- if (!categoriesResult.ok) return categoriesResult;
2811
- const business = businessResult.value;
2812
- const locations = locationsResult.value;
2813
- const categories = categoriesResult.value;
2814
- const defaultLocation = locations[0];
2815
- return ok({
2816
- business,
2817
- location: defaultLocation,
2818
- locations,
2819
- categories,
2820
- currency: business.default_currency,
2821
- is_open: defaultLocation?.accepts_online_orders ?? false,
2822
- accepts_orders: defaultLocation?.accepts_online_orders ?? false
2823
- });
2284
+ return safe7(this.client.get("/api/v1/bootstrap"));
2824
2285
  }
2825
2286
  };
2826
2287
 
@@ -2843,49 +2304,47 @@ var InventoryService = class {
2843
2304
  constructor(client) {
2844
2305
  this.client = client;
2845
2306
  }
2307
+ withQuery(path, params) {
2308
+ const searchParams = new URLSearchParams();
2309
+ for (const [key, value] of Object.entries(params)) {
2310
+ if (value === void 0) continue;
2311
+ searchParams.set(key, String(value));
2312
+ }
2313
+ const query2 = searchParams.toString();
2314
+ return query2 ? `${path}?${query2}` : path;
2315
+ }
2846
2316
  async getStockLevels() {
2847
- return safe8(this.client.query("inventory.stock_levels"));
2317
+ return safe8(this.client.get("/api/v1/inventory/stock-levels"));
2848
2318
  }
2849
2319
  async getProductStock(productId, locationId) {
2850
- if (locationId) {
2851
- return safe8(
2852
- this.client.query("inventory.product", {
2853
- product_id: productId,
2854
- location_id: locationId
2855
- })
2856
- );
2857
- }
2858
- return safe8(
2859
- this.client.query("inventory.product", {
2860
- product_id: productId
2861
- })
2862
- );
2320
+ const encodedId = encodeURIComponent(productId);
2321
+ const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/stock`, {
2322
+ location_id: locationId
2323
+ });
2324
+ return safe8(this.client.get(path));
2863
2325
  }
2864
2326
  async getVariantStock(variantId, locationId) {
2865
- return safe8(
2866
- this.client.query("inventory.variant", {
2867
- variant_id: variantId,
2868
- location_id: locationId
2869
- })
2870
- );
2327
+ const encodedId = encodeURIComponent(variantId);
2328
+ const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/stock`, {
2329
+ location_id: locationId
2330
+ });
2331
+ return safe8(this.client.get(path));
2871
2332
  }
2872
2333
  async checkProductAvailability(productId, quantity, locationId) {
2873
- return safe8(
2874
- this.client.query("inventory.check_availability", {
2875
- product_id: productId,
2876
- quantity,
2877
- location_id: locationId
2878
- })
2879
- );
2334
+ const encodedId = encodeURIComponent(productId);
2335
+ const path = this.withQuery(`/api/v1/inventory/products/${encodedId}/availability`, {
2336
+ quantity,
2337
+ location_id: locationId
2338
+ });
2339
+ return safe8(this.client.get(path));
2880
2340
  }
2881
2341
  async checkVariantAvailability(variantId, quantity, locationId) {
2882
- return safe8(
2883
- this.client.query("inventory.check_availability", {
2884
- variant_id: variantId,
2885
- quantity,
2886
- location_id: locationId
2887
- })
2888
- );
2342
+ const encodedId = encodeURIComponent(variantId);
2343
+ const path = this.withQuery(`/api/v1/inventory/variants/${encodedId}/availability`, {
2344
+ quantity,
2345
+ location_id: locationId
2346
+ });
2347
+ return safe8(this.client.get(path));
2889
2348
  }
2890
2349
  async checkMultipleAvailability(items, locationId) {
2891
2350
  const results = await Promise.all(
@@ -2899,7 +2358,7 @@ var InventoryService = class {
2899
2358
  return ok(results.map((r) => r.value));
2900
2359
  }
2901
2360
  async getSummary() {
2902
- return safe8(this.client.query("inventory.summary"));
2361
+ return safe8(this.client.get("/api/v1/inventory/summary"));
2903
2362
  }
2904
2363
  async isInStock(productId, locationId) {
2905
2364
  const result = await this.checkProductAvailability(productId, 1, locationId);
@@ -2914,9 +2373,6 @@ var InventoryService = class {
2914
2373
  };
2915
2374
 
2916
2375
  // src/scheduling.ts
2917
- function toVariables(input) {
2918
- return Object.fromEntries(Object.entries(input));
2919
- }
2920
2376
  function toCimplifyError9(error) {
2921
2377
  if (error instanceof CimplifyError) return error;
2922
2378
  if (error instanceof Error) {
@@ -2931,68 +2387,110 @@ async function safe9(promise) {
2931
2387
  return err(toCimplifyError9(error));
2932
2388
  }
2933
2389
  }
2390
+ function withQuery2(path, params) {
2391
+ const searchParams = new URLSearchParams();
2392
+ for (const [key, value] of Object.entries(params)) {
2393
+ if (value === void 0) continue;
2394
+ searchParams.set(key, String(value));
2395
+ }
2396
+ const query2 = searchParams.toString();
2397
+ return query2 ? `${path}?${query2}` : path;
2398
+ }
2399
+ function normalizeServiceAvailability(result) {
2400
+ if (Array.isArray(result.days) && result.days.length > 0) {
2401
+ return result;
2402
+ }
2403
+ const days = Array.isArray(result.availability) ? result.availability.map((day) => ({
2404
+ ...day,
2405
+ is_fully_booked: day.is_fully_booked ?? (typeof day.has_availability === "boolean" ? !day.has_availability : void 0)
2406
+ })) : [];
2407
+ return { ...result, days };
2408
+ }
2409
+ function firstScheduledTime(booking) {
2410
+ return booking.service_items.find((item) => typeof item.scheduled_start === "string")?.scheduled_start || booking.created_at;
2411
+ }
2934
2412
  var SchedulingService = class {
2935
2413
  constructor(client) {
2936
2414
  this.client = client;
2937
2415
  }
2938
2416
  async getServices() {
2939
- return safe9(this.client.query("scheduling.services"));
2417
+ return safe9(this.client.get("/api/v1/scheduling/services"));
2940
2418
  }
2941
2419
  /**
2942
- * Get a specific service by ID
2943
- * Note: Filters from all services client-side (no single-service endpoint)
2420
+ * Get a specific service by ID.
2944
2421
  */
2945
2422
  async getService(serviceId) {
2946
2423
  const result = await this.getServices();
2947
2424
  if (!result.ok) return result;
2948
- return ok(result.value.find((s) => s.id === serviceId) || null);
2425
+ return ok(result.value.find((service) => service.id === serviceId) || null);
2949
2426
  }
2950
2427
  async getAvailableSlots(input) {
2951
- return safe9(
2952
- this.client.query("scheduling.slots", toVariables(input))
2953
- );
2428
+ const path = withQuery2("/api/v1/scheduling/slots", {
2429
+ service_id: input.service_id,
2430
+ date: input.date,
2431
+ participant_count: input.participant_count,
2432
+ duration_minutes: input.duration_minutes
2433
+ });
2434
+ return safe9(this.client.get(path));
2954
2435
  }
2955
2436
  async checkSlotAvailability(input) {
2956
- return safe9(
2957
- this.client.query(
2958
- "scheduling.check_availability",
2959
- toVariables(input)
2960
- )
2961
- );
2437
+ const path = withQuery2("/api/v1/scheduling/slots/check", {
2438
+ service_id: input.service_id,
2439
+ slot_time: input.slot_time,
2440
+ duration_minutes: input.duration_minutes,
2441
+ participant_count: input.participant_count
2442
+ });
2443
+ return safe9(this.client.get(path));
2962
2444
  }
2963
2445
  async getServiceAvailability(params) {
2446
+ const path = withQuery2("/api/v1/scheduling/availability", {
2447
+ service_id: params.service_id,
2448
+ start_date: params.start_date,
2449
+ end_date: params.end_date,
2450
+ location_id: params.location_id,
2451
+ participant_count: params.participant_count
2452
+ });
2964
2453
  return safe9(
2965
- this.client.query(
2966
- "scheduling.availability",
2967
- toVariables(params)
2968
- )
2454
+ this.client.get(path).then((result) => normalizeServiceAvailability(result))
2969
2455
  );
2970
2456
  }
2971
2457
  async getBooking(bookingId) {
2972
- return safe9(this.client.query(`scheduling.${bookingId}`));
2458
+ const encodedId = encodeURIComponent(bookingId);
2459
+ return safe9(this.client.get(`/api/v1/scheduling/bookings/${encodedId}`));
2973
2460
  }
2974
- async getCustomerBookings() {
2975
- return safe9(this.client.query("scheduling"));
2461
+ async getCustomerBookings(customerId) {
2462
+ const path = withQuery2("/api/v1/scheduling/bookings", {
2463
+ customer_id: customerId
2464
+ });
2465
+ return safe9(this.client.get(path));
2976
2466
  }
2977
2467
  async getUpcomingBookings() {
2978
- return safe9(
2979
- this.client.query(
2980
- "scheduling[?(@.status!='completed' && @.status!='cancelled')]#sort(start_time,asc)"
2981
- )
2982
- );
2468
+ const result = await this.getCustomerBookings();
2469
+ if (!result.ok) return result;
2470
+ const upcoming = result.value.filter((booking) => {
2471
+ const status = String(booking.status).toLowerCase();
2472
+ return status !== "completed" && status !== "cancelled";
2473
+ }).sort((a, b) => firstScheduledTime(a).localeCompare(firstScheduledTime(b)));
2474
+ return ok(upcoming);
2983
2475
  }
2984
2476
  async getPastBookings(limit = 10) {
2985
- return safe9(
2986
- this.client.query(
2987
- `scheduling[?(@.status=='completed')]#sort(start_time,desc)#limit(${limit})`
2988
- )
2989
- );
2477
+ const result = await this.getCustomerBookings();
2478
+ if (!result.ok) return result;
2479
+ 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));
2480
+ return ok(past);
2990
2481
  }
2991
2482
  async cancelBooking(input) {
2992
- return safe9(this.client.call("scheduling.cancel_booking", input));
2483
+ const encodedId = encodeURIComponent(input.booking_id);
2484
+ return safe9(
2485
+ this.client.post(`/api/v1/scheduling/bookings/${encodedId}/cancel`, {
2486
+ reason: input.reason
2487
+ })
2488
+ );
2993
2489
  }
2994
2490
  async rescheduleBooking(input) {
2995
- return safe9(this.client.call("scheduling.reschedule_booking", input));
2491
+ return safe9(
2492
+ this.client.post("/api/v1/scheduling/bookings/reschedule", input)
2493
+ );
2996
2494
  }
2997
2495
  async getNextAvailableSlot(serviceId, fromDate) {
2998
2496
  const date = fromDate || (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
@@ -3011,6 +2509,12 @@ var SchedulingService = class {
3011
2509
  if (!result.ok) return result;
3012
2510
  return ok(result.value.some((slot) => slot.is_available));
3013
2511
  }
2512
+ // Compatibility alias for callers typed against the older Booking shape.
2513
+ async getBookingLegacy(bookingId) {
2514
+ const result = await this.getBooking(bookingId);
2515
+ if (!result.ok) return result;
2516
+ return ok(result.value);
2517
+ }
3014
2518
  };
3015
2519
 
3016
2520
  // src/lite.ts
@@ -3033,47 +2537,18 @@ var LiteService = class {
3033
2537
  this.client = client;
3034
2538
  }
3035
2539
  async getBootstrap() {
3036
- return safe10(this.client.query("lite.bootstrap"));
2540
+ return safe10(this.client.get("/api/v1/lite/bootstrap"));
3037
2541
  }
3038
2542
  async getTable(tableId) {
3039
- return safe10(this.client.query(`lite.table.${tableId}`));
3040
- }
3041
- async getTableByNumber(tableNumber, locationId) {
3042
- return safe10(
3043
- this.client.query("lite.table_by_number", {
3044
- table_number: tableNumber,
3045
- location_id: locationId
3046
- })
3047
- );
3048
- }
3049
- async sendToKitchen(tableId, items) {
3050
- return safe10(
3051
- this.client.call("lite.send_to_kitchen", {
3052
- table_id: tableId,
3053
- items
3054
- })
3055
- );
3056
- }
3057
- async callWaiter(tableId, reason) {
3058
- return safe10(
3059
- this.client.call("lite.call_waiter", {
3060
- table_id: tableId,
3061
- reason
3062
- })
3063
- );
3064
- }
3065
- async requestBill(tableId) {
3066
- return safe10(
3067
- this.client.call("lite.request_bill", {
3068
- table_id: tableId
3069
- })
3070
- );
2543
+ const encodedId = encodeURIComponent(tableId);
2544
+ return safe10(this.client.get(`/api/v1/lite/tables/${encodedId}`));
3071
2545
  }
3072
2546
  async getMenu() {
3073
- return safe10(this.client.query("lite.menu"));
2547
+ return safe10(this.client.get("/api/v1/lite/menu"));
3074
2548
  }
3075
2549
  async getMenuByCategory(categoryId) {
3076
- return safe10(this.client.query(`lite.menu.category.${categoryId}`));
2550
+ const encodedId = encodeURIComponent(categoryId);
2551
+ return safe10(this.client.get(`/api/v1/lite/menu/categories/${encodedId}`));
3077
2552
  }
3078
2553
  };
3079
2554
 
@@ -3092,30 +2567,16 @@ async function safe11(promise) {
3092
2567
  return err(toCimplifyError11(error));
3093
2568
  }
3094
2569
  }
3095
- async function safeWithFallback7(primary, fallback) {
3096
- const primaryResult = await safe11(primary());
3097
- if (primaryResult.ok) return primaryResult;
3098
- if (primaryResult.error.code !== "HTTP_404" && primaryResult.error.code !== "API_ERROR") {
3099
- return primaryResult;
3100
- }
3101
- return safe11(fallback());
3102
- }
3103
2570
  var FxService = class {
3104
2571
  constructor(client) {
3105
2572
  this.client = client;
3106
2573
  }
3107
2574
  async getRate(from, to) {
3108
2575
  const path = `/api/v1/fx/rate?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}`;
3109
- return safeWithFallback7(
3110
- () => this.client.get(path),
3111
- () => this.client.call("fx.getRate", { from, to })
3112
- );
2576
+ return safe11(this.client.get(path));
3113
2577
  }
3114
2578
  async lockQuote(request) {
3115
- return safeWithFallback7(
3116
- () => this.client.post("/api/v1/fx/quotes", request),
3117
- () => this.client.call("fx.lockQuote", request)
3118
- );
2579
+ return safe11(this.client.post("/api/v1/fx/quotes", request));
3119
2580
  }
3120
2581
  };
3121
2582
 
@@ -3726,6 +3187,7 @@ function createElements(client, businessId, options) {
3726
3187
 
3727
3188
  // src/client.ts
3728
3189
  var ACCESS_TOKEN_STORAGE_KEY = "cimplify_access_token";
3190
+ var ORDER_TOKEN_PREFIX = "cimplify_ot_";
3729
3191
  var DEFAULT_TIMEOUT_MS = 3e4;
3730
3192
  var DEFAULT_MAX_RETRIES = 3;
3731
3193
  var DEFAULT_RETRY_DELAY_MS = 1e3;
@@ -3867,7 +3329,29 @@ var CimplifyClient = class {
3867
3329
  source: "clear"
3868
3330
  });
3869
3331
  }
3870
- /** Set the active location/branch for all subsequent requests */
3332
+ setOrderToken(orderId, token) {
3333
+ if (typeof window !== "undefined" && window.localStorage) {
3334
+ localStorage.setItem(`${ORDER_TOKEN_PREFIX}${orderId}`, token);
3335
+ }
3336
+ }
3337
+ getOrderToken(orderId) {
3338
+ if (typeof window !== "undefined" && window.localStorage) {
3339
+ return localStorage.getItem(`${ORDER_TOKEN_PREFIX}${orderId}`);
3340
+ }
3341
+ return null;
3342
+ }
3343
+ clearOrderTokens() {
3344
+ if (typeof window !== "undefined" && window.localStorage) {
3345
+ const keysToRemove = [];
3346
+ for (let i = 0; i < localStorage.length; i++) {
3347
+ const key = localStorage.key(i);
3348
+ if (key?.startsWith(ORDER_TOKEN_PREFIX)) {
3349
+ keysToRemove.push(key);
3350
+ }
3351
+ }
3352
+ keysToRemove.forEach((k) => localStorage.removeItem(k));
3353
+ }
3354
+ }
3871
3355
  setLocationId(locationId) {
3872
3356
  if (locationId) {
3873
3357
  this.context.location_id = locationId;
@@ -4068,41 +3552,6 @@ var CimplifyClient = class {
4068
3552
  this.inflightRequests.set(key, request);
4069
3553
  return request;
4070
3554
  }
4071
- async query(query2, variables) {
4072
- const body = { query: query2 };
4073
- if (variables) {
4074
- body.variables = variables;
4075
- }
4076
- if (Object.keys(this.context).length > 0) {
4077
- body.context = this.context;
4078
- }
4079
- const key = this.getDedupeKey("query", body);
4080
- return this.deduplicatedRequest(key, async () => {
4081
- const response = await this.resilientFetch(`${this.baseUrl}/api/q`, {
4082
- method: "POST",
4083
- credentials: this.credentials,
4084
- headers: this.getHeaders(),
4085
- body: JSON.stringify(body)
4086
- });
4087
- return this.handleResponse(response);
4088
- });
4089
- }
4090
- async call(method, args) {
4091
- const body = {
4092
- method,
4093
- args: args !== void 0 ? [args] : []
4094
- };
4095
- if (Object.keys(this.context).length > 0) {
4096
- body.context = this.context;
4097
- }
4098
- const response = await this.resilientFetch(`${this.baseUrl}/api/m`, {
4099
- method: "POST",
4100
- credentials: this.credentials,
4101
- headers: this.getHeaders(),
4102
- body: JSON.stringify(body)
4103
- });
4104
- return this.handleResponse(response);
4105
- }
4106
3555
  async get(path) {
4107
3556
  const key = this.getDedupeKey("get", path);
4108
3557
  return this.deduplicatedRequest(key, async () => {
@@ -4205,26 +3654,6 @@ var CimplifyClient = class {
4205
3654
  }
4206
3655
  return json;
4207
3656
  }
4208
- async handleResponse(response) {
4209
- const json = await response.json();
4210
- if (!json.success || json.error) {
4211
- const error = enrichError(
4212
- new CimplifyError(
4213
- json.error?.code || "UNKNOWN_ERROR",
4214
- json.error?.message || "An unknown error occurred",
4215
- json.error?.retryable || false
4216
- ),
4217
- { isTestMode: this.isTestMode() }
4218
- );
4219
- if (response.status === 401 || error.code === ErrorCode.UNAUTHORIZED) {
4220
- console.warn(
4221
- "[Cimplify] Received 401 Unauthorized. Access token may be missing/expired. Refresh authentication and retry the request."
4222
- );
4223
- }
4224
- throw error;
4225
- }
4226
- return json.data;
4227
- }
4228
3657
  get catalogue() {
4229
3658
  if (!this._catalogue) {
4230
3659
  this._catalogue = new CatalogueQueries(this);
@@ -4316,6 +3745,173 @@ function createCimplifyClient(config = {}) {
4316
3745
  return new CimplifyClient(config);
4317
3746
  }
4318
3747
 
3748
+ // src/query/builder.ts
3749
+ function escapeQueryValue(value) {
3750
+ return value.replace(/'/g, "\\'");
3751
+ }
3752
+ var QueryBuilder = class {
3753
+ constructor(entity) {
3754
+ this.filters = [];
3755
+ this.modifiers = [];
3756
+ this.pathSegments = [];
3757
+ this.entity = entity;
3758
+ }
3759
+ path(segment) {
3760
+ this.pathSegments.push(segment);
3761
+ return this;
3762
+ }
3763
+ where(field, op, value) {
3764
+ const v = typeof value === "string" ? `'${escapeQueryValue(value)}'` : value;
3765
+ if (op === "contains" || op === "startsWith") {
3766
+ this.filters.push(`@.${field} ${op} ${v}`);
3767
+ } else {
3768
+ this.filters.push(`@.${field}${op}${v}`);
3769
+ }
3770
+ return this;
3771
+ }
3772
+ and(field, op, value) {
3773
+ return this.where(field, op, value);
3774
+ }
3775
+ sort(field, order = "asc") {
3776
+ this.modifiers.push(`sort(${field},${order})`);
3777
+ return this;
3778
+ }
3779
+ limit(n) {
3780
+ this.modifiers.push(`limit(${n})`);
3781
+ return this;
3782
+ }
3783
+ offset(n) {
3784
+ this.modifiers.push(`offset(${n})`);
3785
+ return this;
3786
+ }
3787
+ count() {
3788
+ this.modifiers.push("count");
3789
+ return this;
3790
+ }
3791
+ enriched() {
3792
+ this.modifiers.push("enriched");
3793
+ return this;
3794
+ }
3795
+ build() {
3796
+ let query2 = this.entity;
3797
+ if (this.pathSegments.length > 0) {
3798
+ query2 += "." + this.pathSegments.join(".");
3799
+ }
3800
+ if (this.filters.length > 0) {
3801
+ query2 += `[?(${this.filters.join(" && ")})]`;
3802
+ }
3803
+ for (const mod of this.modifiers) {
3804
+ query2 += `#${mod}`;
3805
+ }
3806
+ return query2;
3807
+ }
3808
+ toString() {
3809
+ return this.build();
3810
+ }
3811
+ };
3812
+ function query(entity) {
3813
+ return new QueryBuilder(entity);
3814
+ }
3815
+
3816
+ // src/constants.ts
3817
+ var CHECKOUT_MODE = {
3818
+ LINK: "link",
3819
+ GUEST: "guest"
3820
+ };
3821
+ var ORDER_TYPE = {
3822
+ DELIVERY: "delivery",
3823
+ PICKUP: "pickup",
3824
+ DINE_IN: "dine-in",
3825
+ WALK_IN: "walk-in"
3826
+ };
3827
+ var PAYMENT_METHOD = {
3828
+ MOBILE_MONEY: "mobile_money",
3829
+ CARD: "card"
3830
+ };
3831
+ var CHECKOUT_STEP = {
3832
+ AUTHENTICATION: "authentication",
3833
+ ORDER_DETAILS: "order_details",
3834
+ PAYMENT_METHOD: "payment_method",
3835
+ PAYMENT: "payment",
3836
+ CONFIRMATION: "confirmation"
3837
+ };
3838
+ var PAYMENT_STATE = {
3839
+ INITIAL: "initial",
3840
+ PREPARING: "preparing",
3841
+ PROCESSING: "processing",
3842
+ VERIFYING: "verifying",
3843
+ AWAITING_AUTHORIZATION: "awaiting_authorization",
3844
+ SUCCESS: "success",
3845
+ ERROR: "error",
3846
+ TIMEOUT: "timeout"
3847
+ };
3848
+ var PICKUP_TIME_TYPE = {
3849
+ ASAP: "asap",
3850
+ SCHEDULED: "scheduled"
3851
+ };
3852
+ var MOBILE_MONEY_PROVIDER = {
3853
+ MTN: "mtn",
3854
+ VODAFONE: "vodafone",
3855
+ AIRTEL: "airtel"
3856
+ };
3857
+ var AUTHORIZATION_TYPE = {
3858
+ OTP: "otp",
3859
+ PIN: "pin",
3860
+ PHONE: "phone",
3861
+ BIRTHDAY: "birthday",
3862
+ ADDRESS: "address"
3863
+ };
3864
+ var DEVICE_TYPE = {
3865
+ MOBILE: "mobile",
3866
+ DESKTOP: "desktop",
3867
+ TABLET: "tablet"
3868
+ };
3869
+ var CONTACT_TYPE = {
3870
+ PHONE: "phone",
3871
+ EMAIL: "email"
3872
+ };
3873
+ var LINK_QUERY = {
3874
+ DATA: "link.data",
3875
+ ADDRESSES: "link.addresses",
3876
+ MOBILE_MONEY: "link.mobile_money",
3877
+ PREFERENCES: "link.preferences",
3878
+ SESSIONS: "link.sessions"
3879
+ };
3880
+ var LINK_MUTATION = {
3881
+ CHECK_STATUS: "link.check_status",
3882
+ ENROLL: "link.enroll",
3883
+ ENROLL_AND_LINK_ORDER: "link.enroll_and_link_order",
3884
+ UPDATE_PREFERENCES: "link.update_preferences",
3885
+ CREATE_ADDRESS: "link.create_address",
3886
+ UPDATE_ADDRESS: "link.update_address",
3887
+ DELETE_ADDRESS: "link.delete_address",
3888
+ SET_DEFAULT_ADDRESS: "link.set_default_address",
3889
+ TRACK_ADDRESS_USAGE: "link.track_address_usage",
3890
+ CREATE_MOBILE_MONEY: "link.create_mobile_money",
3891
+ DELETE_MOBILE_MONEY: "link.delete_mobile_money",
3892
+ SET_DEFAULT_MOBILE_MONEY: "link.set_default_mobile_money",
3893
+ TRACK_MOBILE_MONEY_USAGE: "link.track_mobile_money_usage",
3894
+ VERIFY_MOBILE_MONEY: "link.verify_mobile_money",
3895
+ REVOKE_SESSION: "link.revoke_session",
3896
+ REVOKE_ALL_SESSIONS: "link.revoke_all_sessions"
3897
+ };
3898
+ var AUTH_MUTATION = {
3899
+ REQUEST_OTP: "auth.request_otp",
3900
+ VERIFY_OTP: "auth.verify_otp"
3901
+ };
3902
+ var CHECKOUT_MUTATION = {
3903
+ PROCESS: "checkout.process"
3904
+ };
3905
+ var PAYMENT_MUTATION = {
3906
+ SUBMIT_AUTHORIZATION: "payment.submit_authorization",
3907
+ CHECK_STATUS: "order.poll_payment_status"
3908
+ };
3909
+ var ORDER_MUTATION = {
3910
+ UPDATE_CUSTOMER: "order.update_order_customer"
3911
+ };
3912
+ var DEFAULT_CURRENCY = "GHS";
3913
+ var DEFAULT_COUNTRY = "GHA";
3914
+
4319
3915
  exports.AUTHORIZATION_TYPE = AUTHORIZATION_TYPE;
4320
3916
  exports.AUTH_MUTATION = AUTH_MUTATION;
4321
3917
  exports.AuthService = AuthService;