react-shopwave-connect 0.4.3 → 0.4.5

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.
@@ -381,17 +381,29 @@ const UPLOAD_KINDS = Object.freeze({
381
381
  applicationLogo: "applicaionLogo",
382
382
  applicationImages: "applicaionImages"
383
383
  });
384
+ /** Every `UploadPrefix`, longest first so a name check never takes `product` for `product_thumbnail`. */
385
+ const UPLOAD_PREFIXES = Object.freeze([
386
+ "product_thumbnail",
387
+ "variant_thumbnail",
388
+ "product",
389
+ "variant"
390
+ ]);
384
391
  /** How uploads are addressed (app route and Shopwave uploader). */
385
392
  const SHOPWAVE_UPLOAD = Object.freeze({
386
393
  route: "upload",
387
394
  upstream: "uploader",
388
395
  kindHeader: "contentType",
396
+ prefixHeader: "prefix",
389
397
  fileField: "file",
390
- kindField: "kind"
398
+ kindField: "kind",
399
+ prefixField: "prefix"
391
400
  });
392
401
  function isUploadKind(value) {
393
402
  return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
394
403
  }
404
+ function isUploadPrefix(value) {
405
+ return typeof value === "string" && UPLOAD_PREFIXES.includes(value);
406
+ }
395
407
  const SHOPWAVE_LOOKUPS = Object.freeze({
396
408
  productTags: {
397
409
  route: "products/tags",
@@ -558,22 +570,503 @@ async function logout(options = {}) {
558
570
  * function yet (e.g. `/api/merchant`).
559
571
  */
560
572
  /**
561
- * Deletes `/api/{resourcePath}/{entityId}`.
573
+ * Deletes `/api/{resourcePath}/{entityId}`.
574
+ */
575
+ async function deleteEntity(resourcePath, entityId, options = {}) {
576
+ if (entityId == null || entityId === "") throw new Error("entityId is missing");
577
+ await apiDelete(`/api/${resourcePath}/${entityId}`, options);
578
+ }
579
+ /**
580
+ * Sends a create/update mutation. Returns the response's `result` field when it
581
+ * has one (older app routes wrapped their answer that way), otherwise the whole
582
+ * parsed response body. Throws `ShopwaveApiError` on HTTP or API errors.
583
+ */
584
+ async function submitEntity({ endpoint, method = "POST", payload }, options = {}) {
585
+ const json = await apiSend(endpoint, method, payload, options);
586
+ assertNoApiErrors(json, 200);
587
+ if (json && typeof json === "object" && "result" in json) return json.result;
588
+ return json ?? void 0;
589
+ }
590
+
591
+ //#endregion
592
+ //#region src/core/imageFit.ts
593
+ /**
594
+ * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
595
+ * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
596
+ */
597
+ function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
598
+ if (![
599
+ srcWidth,
600
+ srcHeight,
601
+ dstWidth,
602
+ dstHeight
603
+ ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
604
+ const srcRatio = srcWidth / srcHeight;
605
+ const dstRatio = dstWidth / dstHeight;
606
+ if (srcRatio > dstRatio) {
607
+ const sw = Math.round(srcHeight * dstRatio);
608
+ return {
609
+ sx: Math.round((srcWidth - sw) / 2),
610
+ sy: 0,
611
+ sw,
612
+ sh: srcHeight
613
+ };
614
+ }
615
+ const sh = Math.round(srcWidth / dstRatio);
616
+ return {
617
+ sx: 0,
618
+ sy: Math.round((srcHeight - sh) / 2),
619
+ sw: srcWidth,
620
+ sh
621
+ };
622
+ }
623
+ function requireBrowserImages(fn) {
624
+ if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
625
+ }
626
+ /** Reads an image file's pixel size (browser only). */
627
+ async function readImageSize(file) {
628
+ requireBrowserImages("readImageSize");
629
+ const bitmap = await createImageBitmap(file);
630
+ try {
631
+ return {
632
+ width: bitmap.width,
633
+ height: bitmap.height
634
+ };
635
+ } finally {
636
+ bitmap.close?.();
637
+ }
638
+ }
639
+ /** Draws `crop` of the bitmap at `width × height` and encodes it (one resample). */
640
+ async function drawCrop(bitmap, crop, width, height, type, quality, fn) {
641
+ const { sx, sy, sw, sh } = crop;
642
+ if (typeof OffscreenCanvas === "function") {
643
+ const canvas$1 = new OffscreenCanvas(width, height);
644
+ const ctx$1 = canvas$1.getContext("2d");
645
+ if (!ctx$1) throw new Error(`${fn}: no 2D canvas context`);
646
+ ctx$1.imageSmoothingQuality = "high";
647
+ ctx$1.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
648
+ return canvas$1.convertToBlob({
649
+ type,
650
+ quality
651
+ });
652
+ }
653
+ const canvas = document.createElement("canvas");
654
+ canvas.width = width;
655
+ canvas.height = height;
656
+ const ctx = canvas.getContext("2d");
657
+ if (!ctx) throw new Error(`${fn}: no 2D canvas context`);
658
+ ctx.imageSmoothingQuality = "high";
659
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
660
+ return new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error(`${fn}: encoding failed`)), type, quality));
661
+ }
662
+ /** The input's name with the output type's extension. */
663
+ function outputName(file, type) {
664
+ const name = file.name || "image";
665
+ const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
666
+ return `${name.replace(/\.[^.]+$/, "")}.${ext}`;
667
+ }
668
+ /**
669
+ * Returns the image at exactly `width × height`: scaled and centre-cropped
670
+ * (never stretched). Browser only. The result is a `File` named like the
671
+ * input, with the output type's extension.
672
+ */
673
+ async function fitImageToSize(file, width, height, options = {}) {
674
+ requireBrowserImages("fitImageToSize");
675
+ const { type = "image/png", quality, keepIfExact = true } = options;
676
+ const outName = outputName(file, type);
677
+ const bitmap = await createImageBitmap(file);
678
+ try {
679
+ if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
680
+ const blob = await drawCrop(bitmap, coverCrop(bitmap.width, bitmap.height, width, height), width, height, type, quality, "fitImageToSize");
681
+ return new File([blob], outName, { type });
682
+ } finally {
683
+ bitmap.close?.();
684
+ }
685
+ }
686
+ /** A rule that can't be met by any image (a mistake in the rule, not the image). */
687
+ var ImageRuleError = class extends Error {
688
+ constructor(message) {
689
+ super(message);
690
+ this.name = "ImageRuleError";
691
+ }
692
+ };
693
+ /** The image is smaller than the rule's minimum (and `allowUpscale` is off). */
694
+ var ImageTooSmallError = class extends Error {
695
+ /** The smallest size the rule accepts. */
696
+ required;
697
+ /** The largest area of the right shape the image could give. */
698
+ actual;
699
+ constructor(required, actual) {
700
+ super(`The image is too small: it needs to be at least ${required.width} × ${required.height}, and it's ${actual.width} × ${actual.height}`);
701
+ this.name = "ImageTooSmallError";
702
+ this.required = required;
703
+ this.actual = actual;
704
+ }
705
+ };
706
+ const isPositive = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
707
+ /**
708
+ * An aspect ratio as width ÷ height: `"100:77"`, `"100/77"`, `[100, 77]` →
709
+ * 1.2987…; `1.3` → 1.3. Throws {@link ImageRuleError} for anything else.
710
+ */
711
+ function parseAspectRatio(value) {
712
+ let parts = null;
713
+ if (typeof value === "number") return isPositive(value) ? value : badRatio(value);
714
+ if (Array.isArray(value)) parts = [value[0], value[1]];
715
+ else if (typeof value === "string") {
716
+ const text$1 = value.trim();
717
+ const match = /^(\d+(?:\.\d+)?)\s*[:/x×]\s*(\d+(?:\.\d+)?)$/i.exec(text$1);
718
+ if (match) parts = [Number(match[1]), Number(match[2])];
719
+ else if (/^\d+(?:\.\d+)?$/.test(text$1)) return isPositive(Number(text$1)) ? Number(text$1) : badRatio(value);
720
+ }
721
+ if (parts && isPositive(parts[0]) && isPositive(parts[1])) return parts[0] / parts[1];
722
+ return badRatio(value);
723
+ }
724
+ function badRatio(value) {
725
+ throw new ImageRuleError(`Not an aspect ratio: ${JSON.stringify(value)} (use e.g. "100:77", [100, 77] or 1.3)`);
726
+ }
727
+ /** Throws {@link ImageRuleError} when the rule contradicts itself. */
728
+ function checkImageRule(rule) {
729
+ if (!rule || typeof rule !== "object") throw new ImageRuleError("An image rule must be an object");
730
+ for (const key of [
731
+ "width",
732
+ "height",
733
+ "minWidth",
734
+ "minHeight",
735
+ "maxWidth",
736
+ "maxHeight",
737
+ "maxLongSide"
738
+ ]) if (rule[key] != null && !isPositive(rule[key])) throw new ImageRuleError(`${key} must be a positive number`);
739
+ if (rule.width != null || rule.height != null) {
740
+ if (rule.width == null || rule.height == null) throw new ImageRuleError("An exact size needs both width and height");
741
+ if (rule.aspectRatio != null) throw new ImageRuleError("Give an exact size or an aspectRatio, not both (the size sets the ratio)");
742
+ const extra = [
743
+ "minWidth",
744
+ "minHeight",
745
+ "maxWidth",
746
+ "maxHeight",
747
+ "maxLongSide"
748
+ ].filter((key) => rule[key] != null);
749
+ if (extra.length > 0) throw new ImageRuleError(`An exact size is already the minimum and the maximum; remove ${extra.join(", ")}`);
750
+ return;
751
+ }
752
+ if (rule.aspectRatio != null) parseAspectRatio(rule.aspectRatio);
753
+ if (rule.minWidth != null && rule.maxWidth != null && rule.minWidth > rule.maxWidth) throw new ImageRuleError("minWidth is larger than maxWidth");
754
+ if (rule.minHeight != null && rule.maxHeight != null && rule.minHeight > rule.maxHeight) throw new ImageRuleError("minHeight is larger than maxHeight");
755
+ if (rule.maxLongSide != null && Math.max(rule.minWidth ?? 0, rule.minHeight ?? 0) > rule.maxLongSide) throw new ImageRuleError("The minimum size is larger than maxLongSide");
756
+ }
757
+ /**
758
+ * Works out what to do to a `source`-sized image to meet `rule`: the centred
759
+ * crop of the right shape (the largest one), then the output size (scaled
760
+ * down to the maximum, never below the minimum). Pure: no browser needed.
761
+ *
762
+ * Throws {@link ImageTooSmallError} when the crop is below the minimum (or
763
+ * the exact size) and `allowUpscale` is off, and {@link ImageRuleError} for a
764
+ * contradictory rule.
765
+ *
766
+ * @example
767
+ * planImageFit({ width: 6000, height: 4000 }, { aspectRatio: "100:77", minWidth: 600, minHeight: 462, maxLongSide: 2000 })
768
+ * // → crop { sx: 403, sy: 0, sw: 5194, sh: 4000 }, 2000 × 1540
769
+ */
770
+ function planImageFit(source, rule) {
771
+ checkImageRule(rule);
772
+ const { width: W, height: H } = source ?? {};
773
+ if (!isPositive(W) || !isPositive(H)) throw new Error("planImageFit: the image has no size");
774
+ const exact = rule.width != null && rule.height != null;
775
+ const ratio = exact ? rule.width / rule.height : rule.aspectRatio != null ? parseAspectRatio(rule.aspectRatio) : null;
776
+ const crop = ratio == null ? {
777
+ sx: 0,
778
+ sy: 0,
779
+ sw: W,
780
+ sh: H
781
+ } : coverCrop(W, H, ratio, 1);
782
+ const { sw, sh } = crop;
783
+ const kept = {
784
+ width: sw,
785
+ height: sh
786
+ };
787
+ let width;
788
+ let height;
789
+ if (exact) {
790
+ width = rule.width;
791
+ height = rule.height;
792
+ if ((sw < width || sh < height) && !rule.allowUpscale) throw new ImageTooSmallError({
793
+ width,
794
+ height
795
+ }, kept);
796
+ } else {
797
+ const minW = rule.minWidth ?? 0;
798
+ const minH = rule.minHeight ?? 0;
799
+ if ((sw < minW || sh < minH) && !rule.allowUpscale) throw new ImageTooSmallError(requiredSize(minW, minH, ratio), kept);
800
+ let scale = 1;
801
+ if (rule.maxWidth != null) scale = Math.min(scale, rule.maxWidth / sw);
802
+ if (rule.maxHeight != null) scale = Math.min(scale, rule.maxHeight / sh);
803
+ if (rule.maxLongSide != null) scale = Math.min(scale, rule.maxLongSide / Math.max(sw, sh));
804
+ scale = Math.max(scale, minW / sw, minH / sh);
805
+ width = Math.max(1, Math.round(sw * scale));
806
+ height = Math.max(1, Math.round(sh * scale));
807
+ }
808
+ const unchanged = crop.sx === 0 && crop.sy === 0 && sw === W && sh === H && width === W && height === H;
809
+ return {
810
+ crop,
811
+ width,
812
+ height,
813
+ unchanged
814
+ };
815
+ }
816
+ /** The minimum as a full size: a ratio rule with only one minimum implies the other. */
817
+ function requiredSize(minW, minH, ratio) {
818
+ if (ratio == null) return {
819
+ width: minW,
820
+ height: minH
821
+ };
822
+ return {
823
+ width: Math.max(minW, Math.ceil(minH * ratio)),
824
+ height: Math.max(minH, Math.ceil(minW / ratio))
825
+ };
826
+ }
827
+ const OUTPUT_TYPES = [
828
+ "image/png",
829
+ "image/jpeg",
830
+ "image/webp"
831
+ ];
832
+ /**
833
+ * Returns the image meeting `rule` ({@link planImageFit}): centre-cropped to
834
+ * the right shape and scaled in a single draw. An image that already fits is
835
+ * returned untouched (same bytes). Browser only.
836
+ *
837
+ * Throws {@link ImageTooSmallError} (show `required` and `actual` to the
838
+ * person) or {@link ImageRuleError}; an unreadable file rejects with the
839
+ * browser's decoding error.
840
+ *
841
+ * @example
842
+ * const ready = await prepareImage(file, { aspectRatio: "100:77", minWidth: 600, minHeight: 462, maxLongSide: 2000 });
843
+ * await uploadImage(ready, { kind: "product", prefix: "product" });
844
+ */
845
+ async function prepareImage(file, rule, options = {}) {
846
+ checkImageRule(rule);
847
+ requireBrowserImages("prepareImage");
848
+ const sourceType = file.type && OUTPUT_TYPES.includes(file.type) ? file.type : "image/png";
849
+ const type = options.type ?? sourceType;
850
+ const quality = options.quality ?? (type === "image/png" ? void 0 : .9);
851
+ const bitmap = await createImageBitmap(file);
852
+ try {
853
+ const plan = planImageFit({
854
+ width: bitmap.width,
855
+ height: bitmap.height
856
+ }, rule);
857
+ if (plan.unchanged && type === file.type) return file instanceof File ? file : new File([file], outputName(file, type), { type });
858
+ const blob = await drawCrop(bitmap, plan.crop, plan.width, plan.height, type, quality, "prepareImage");
859
+ return new File([blob], outputName(file, type), { type });
860
+ } finally {
861
+ bitmap.close?.();
862
+ }
863
+ }
864
+
865
+ //#endregion
866
+ //#region src/core/upload.ts
867
+ /**
868
+ * HTTPS host that serves the Shopwave CDN's images. The API returns
869
+ * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
870
+ * (checked Sep 2026), so pages served over HTTPS can't show it.
871
+ */
872
+ const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
873
+ const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
874
+ /**
875
+ * Turns an image path from the API into a URL a page can load over HTTPS:
876
+ * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
877
+ * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
878
+ * Other absolute URLs are returned unchanged; empty input gives `""`.
879
+ */
880
+ function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
881
+ if (!path) return "";
882
+ const root = base.replace(/\/+$/, "");
883
+ if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
884
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
885
+ return `${root}/${path.replace(/^\/+/, "")}`;
886
+ }
887
+ /**
888
+ * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
889
+ * (`createShopwaveApi(...).upload()`), and returns its id and URL.
890
+ *
891
+ * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
892
+ * record has to point at it to use it. Live API (Sep 2026): the upload answers
893
+ * 201 `{ fileName, path }`.
894
+ */
895
+ async function uploadImage(file, params, options = {}) {
896
+ if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
897
+ if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
898
+ if (params.prefix != null && !isUploadPrefix(params.prefix)) throw new Error(`uploadImage: unknown prefix "${params.prefix}"`);
899
+ const name = params.fileName ?? file.name ?? "upload";
900
+ const form = new FormData();
901
+ form.append(SHOPWAVE_UPLOAD.fileField, file, name);
902
+ form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
903
+ if (params.prefix != null) form.append(SHOPWAVE_UPLOAD.prefixField, params.prefix);
904
+ const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
905
+ method: "POST",
906
+ body: form
907
+ }, options);
908
+ const body = raw;
909
+ assertNoApiErrors(body, status);
910
+ const id = typeof body?.fileName === "string" ? body.fileName : "";
911
+ const path = typeof body?.path === "string" ? body.path : "";
912
+ if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
913
+ return {
914
+ id,
915
+ url: getImageUrl(path),
916
+ path
917
+ };
918
+ }
919
+
920
+ //#endregion
921
+ //#region src/core/merchantImages.ts
922
+ /** The three image slots on the merchant settings page. */
923
+ const MERCHANT_IMAGE_SLOT_KEYS = [
924
+ "receipt",
925
+ "square",
926
+ "featured"
927
+ ];
928
+ /**
929
+ * Where each slot lives, its upload kind and its exact size (from adminV1's
930
+ * merchant settings page).
931
+ */
932
+ const MERCHANT_IMAGE_SLOTS = Object.freeze({
933
+ receipt: {
934
+ field: "logo.receipt",
935
+ uploadKind: "merchant",
936
+ width: 576,
937
+ height: 325
938
+ },
939
+ square: {
940
+ field: "logo.square",
941
+ uploadKind: "merchant",
942
+ width: 1e3,
943
+ height: 1e3
944
+ },
945
+ featured: {
946
+ field: "feature[0]",
947
+ uploadKind: "merchantFeature",
948
+ width: 1200,
949
+ height: 600
950
+ }
951
+ });
952
+ /**
953
+ * The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
954
+ * `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
955
+ * Returns `null` for empty or non-string values.
956
+ */
957
+ function imageFileName(value) {
958
+ if (typeof value !== "string") return null;
959
+ const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
960
+ return last ? decodeURIComponent(last) : null;
961
+ }
962
+ /** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
963
+ function getMerchantImage(imageIds, slot) {
964
+ if (!imageIds || typeof imageIds !== "object") return null;
965
+ let value;
966
+ if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
967
+ else {
968
+ const logo = imageIds.logo;
969
+ value = logo && typeof logo === "object" ? logo[slot] : void 0;
970
+ }
971
+ return typeof value === "string" && value.trim() ? value.trim() : null;
972
+ }
973
+ /**
974
+ * An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
975
+ * holds only a file name (a fresh upload not yet saved; use the upload's `url`).
976
+ */
977
+ function getMerchantImageUrl(imageIds, slot, base) {
978
+ const value = getMerchantImage(imageIds, slot);
979
+ if (!value || !value.includes("/")) return "";
980
+ return getImageUrl(value, base);
981
+ }
982
+ /**
983
+ * Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
984
+ * with `null`). Other slots and unknown keys are kept; an empty `logo` or
985
+ * `feature` is removed.
986
+ */
987
+ function setMerchantImage(imageIds, slot, fileName) {
988
+ const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
989
+ if (slot === "featured") {
990
+ const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
991
+ const feature = fileName ? [fileName, ...rest] : rest;
992
+ if (feature.length > 0) next.feature = feature;
993
+ else delete next.feature;
994
+ } else {
995
+ const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
996
+ if (fileName) logo[slot] = fileName;
997
+ else delete logo[slot];
998
+ if (Object.keys(logo).length > 0) next.logo = logo;
999
+ else delete next.logo;
1000
+ }
1001
+ return next;
1002
+ }
1003
+ function toStored(value) {
1004
+ if (typeof value === "string") return imageFileName(value) ?? void 0;
1005
+ if (Array.isArray(value)) {
1006
+ const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
1007
+ return items.length > 0 ? items : void 0;
1008
+ }
1009
+ if (value && typeof value === "object") {
1010
+ const out = {};
1011
+ for (const [k, v] of Object.entries(value)) {
1012
+ const stored = toStored(v);
1013
+ if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
1014
+ }
1015
+ return Object.keys(out).length > 0 ? out : void 0;
1016
+ }
1017
+ }
1018
+ /**
1019
+ * The `imageIds` to send on a save: every URL is turned back into its file
1020
+ * name (what adminV1 does with images you didn't change) and empty values
1021
+ * are dropped. No images gives `{}`.
1022
+ */
1023
+ function toStoredImageIds(imageIds) {
1024
+ return toStored(imageIds) ?? {};
1025
+ }
1026
+ /**
1027
+ * Uploads an image for a merchant slot: fits it to the slot's size, uploads
1028
+ * it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
1029
+ * `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
1030
+ */
1031
+ async function uploadMerchantImage(file, slot, options = {}) {
1032
+ const def = MERCHANT_IMAGE_SLOTS[slot];
1033
+ if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
1034
+ const { fit = true, fitOptions,...requestOptions } = options;
1035
+ return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1036
+ }
1037
+
1038
+ //#endregion
1039
+ //#region src/core/productImages.ts
1040
+ /**
1041
+ * Product images, as the live API stores them (merchant 5644, 4 Nov 2026):
1042
+ * - A product's `images` is a list. **Reads return full URLs**
1043
+ * (`http://static.merchantstack.com/images/merchant/<id>/product/<file>`);
1044
+ * **writes take the uploader's file names** ({@link toStoredProductImages};
1045
+ * `saveProduct` does this for you).
1046
+ * - The uploader takes one file per request. With a `prefix` (see
1047
+ * `UploadPrefix`) it names the file `<prefix>_<hash>.<ext>`
1048
+ * (`product_thumbnail_1bdd…41090b.png`); without one, `<hash>.<ext>`. So an
1049
+ * image's role can be read back from its name ({@link productImageRole}).
1050
+ */
1051
+ /**
1052
+ * The role in an image's file name or URL, from the uploader's `prefix`:
1053
+ * `"…/product_thumbnail_1bdd.png"` → `"product_thumbnail"`. `null` for a name
1054
+ * without one (images uploaded without a prefix, e.g. before prefixes existed).
562
1055
  */
563
- async function deleteEntity(resourcePath, entityId, options = {}) {
564
- if (entityId == null || entityId === "") throw new Error("entityId is missing");
565
- await apiDelete(`/api/${resourcePath}/${entityId}`, options);
1056
+ function productImageRole(value) {
1057
+ const name = imageFileName(value);
1058
+ if (!name) return null;
1059
+ return UPLOAD_PREFIXES.find((prefix) => name.startsWith(`${prefix}_`)) ?? null;
566
1060
  }
567
1061
  /**
568
- * Sends a create/update mutation. Returns the response's `result` field when it
569
- * has one (older app routes wrapped their answer that way), otherwise the whole
570
- * parsed response body. Throws `ShopwaveApiError` on HTTP or API errors.
1062
+ * A product's `images` as the API takes them on a save: file names, not the
1063
+ * URLs a read returns. Non-strings, blanks and duplicates are dropped; the
1064
+ * order is kept.
571
1065
  */
572
- async function submitEntity({ endpoint, method = "POST", payload }, options = {}) {
573
- const json = await apiSend(endpoint, method, payload, options);
574
- assertNoApiErrors(json, 200);
575
- if (json && typeof json === "object" && "result" in json) return json.result;
576
- return json ?? void 0;
1066
+ function toStoredProductImages(images) {
1067
+ if (!Array.isArray(images)) return [];
1068
+ const names = images.map(imageFileName).filter((name) => Boolean(name));
1069
+ return Array.from(new Set(names));
577
1070
  }
578
1071
 
579
1072
  //#endregion
@@ -730,12 +1223,20 @@ async function fetchEntityById(kind, id, params = {}, options = {}) {
730
1223
  * read) so an edited price is sent as a new instance. As a safeguard, a new
731
1224
  * product (no `id`, e.g. a duplicate) never sends instance ids: an id copied from
732
1225
  * another product would otherwise point the save at that product's instances.
1226
+ *
1227
+ * `images` is sent as file names ({@link toStoredProductImages}), so the URLs a
1228
+ * read returns can be passed straight back; leaving `images` out keeps them.
733
1229
  */
734
1230
  const saveProduct = (product, options) => {
735
- return saveEntity("product", (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
1231
+ let toSave = (product.id == null || String(product.id).trim() === "") && product.instances != null ? {
736
1232
  ...product,
737
1233
  instances: toProductInstancesForSave(product.instances)
738
- } : product, options);
1234
+ } : product;
1235
+ if (Array.isArray(toSave.images)) toSave = {
1236
+ ...toSave,
1237
+ images: toStoredProductImages(toSave.images)
1238
+ };
1239
+ return saveEntity("product", toSave, options);
739
1240
  };
740
1241
  const deleteProduct = (id, options) => deleteEntityById("product", id, options);
741
1242
  const fetchProduct = (id, params, options) => fetchEntityById("product", id, params, options);
@@ -910,267 +1411,6 @@ function buildConsumerMap(consumers) {
910
1411
  return map;
911
1412
  }
912
1413
 
913
- //#endregion
914
- //#region src/core/imageFit.ts
915
- /**
916
- * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
917
- * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
918
- */
919
- function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
920
- if (![
921
- srcWidth,
922
- srcHeight,
923
- dstWidth,
924
- dstHeight
925
- ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
926
- const srcRatio = srcWidth / srcHeight;
927
- const dstRatio = dstWidth / dstHeight;
928
- if (srcRatio > dstRatio) {
929
- const sw = Math.round(srcHeight * dstRatio);
930
- return {
931
- sx: Math.round((srcWidth - sw) / 2),
932
- sy: 0,
933
- sw,
934
- sh: srcHeight
935
- };
936
- }
937
- const sh = Math.round(srcWidth / dstRatio);
938
- return {
939
- sx: 0,
940
- sy: Math.round((srcHeight - sh) / 2),
941
- sw: srcWidth,
942
- sh
943
- };
944
- }
945
- function requireBrowserImages(fn) {
946
- if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
947
- }
948
- /** Reads an image file's pixel size (browser only). */
949
- async function readImageSize(file) {
950
- requireBrowserImages("readImageSize");
951
- const bitmap = await createImageBitmap(file);
952
- try {
953
- return {
954
- width: bitmap.width,
955
- height: bitmap.height
956
- };
957
- } finally {
958
- bitmap.close?.();
959
- }
960
- }
961
- /**
962
- * Returns the image at exactly `width × height`: scaled and centre-cropped
963
- * (never stretched). Browser only. The result is a `File` named like the
964
- * input, with the output type's extension.
965
- */
966
- async function fitImageToSize(file, width, height, options = {}) {
967
- requireBrowserImages("fitImageToSize");
968
- const { type = "image/png", quality, keepIfExact = true } = options;
969
- const name = file.name || "image";
970
- const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
971
- const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
972
- const bitmap = await createImageBitmap(file);
973
- try {
974
- if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
975
- const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
976
- let blob;
977
- if (typeof OffscreenCanvas === "function") {
978
- const canvas = new OffscreenCanvas(width, height);
979
- const ctx = canvas.getContext("2d");
980
- if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
981
- ctx.imageSmoothingQuality = "high";
982
- ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
983
- blob = await canvas.convertToBlob({
984
- type,
985
- quality
986
- });
987
- } else {
988
- const canvas = document.createElement("canvas");
989
- canvas.width = width;
990
- canvas.height = height;
991
- const ctx = canvas.getContext("2d");
992
- if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
993
- ctx.imageSmoothingQuality = "high";
994
- ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
995
- blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
996
- }
997
- return new File([blob], outName, { type });
998
- } finally {
999
- bitmap.close?.();
1000
- }
1001
- }
1002
-
1003
- //#endregion
1004
- //#region src/core/upload.ts
1005
- /**
1006
- * HTTPS host that serves the Shopwave CDN's images. The API returns
1007
- * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
1008
- * (checked Sep 2026), so pages served over HTTPS can't show it.
1009
- */
1010
- const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
1011
- const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
1012
- /**
1013
- * Turns an image path from the API into a URL a page can load over HTTPS:
1014
- * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
1015
- * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
1016
- * Other absolute URLs are returned unchanged; empty input gives `""`.
1017
- */
1018
- function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
1019
- if (!path) return "";
1020
- const root = base.replace(/\/+$/, "");
1021
- if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
1022
- if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
1023
- return `${root}/${path.replace(/^\/+/, "")}`;
1024
- }
1025
- /**
1026
- * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
1027
- * (`createShopwaveApi(...).upload()`), and returns its id and URL.
1028
- *
1029
- * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
1030
- * record has to point at it to use it. Live API (Sep 2026): the upload answers
1031
- * 201 `{ fileName, path }`.
1032
- */
1033
- async function uploadImage(file, params, options = {}) {
1034
- if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
1035
- if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
1036
- const name = params.fileName ?? file.name ?? "upload";
1037
- const form = new FormData();
1038
- form.append(SHOPWAVE_UPLOAD.fileField, file, name);
1039
- form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
1040
- const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
1041
- method: "POST",
1042
- body: form
1043
- }, options);
1044
- const body = raw;
1045
- assertNoApiErrors(body, status);
1046
- const id = typeof body?.fileName === "string" ? body.fileName : "";
1047
- const path = typeof body?.path === "string" ? body.path : "";
1048
- if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
1049
- return {
1050
- id,
1051
- url: getImageUrl(path),
1052
- path
1053
- };
1054
- }
1055
-
1056
- //#endregion
1057
- //#region src/core/merchantImages.ts
1058
- /** The three image slots on the merchant settings page. */
1059
- const MERCHANT_IMAGE_SLOT_KEYS = [
1060
- "receipt",
1061
- "square",
1062
- "featured"
1063
- ];
1064
- /**
1065
- * Where each slot lives, its upload kind and its exact size (from adminV1's
1066
- * merchant settings page).
1067
- */
1068
- const MERCHANT_IMAGE_SLOTS = Object.freeze({
1069
- receipt: {
1070
- field: "logo.receipt",
1071
- uploadKind: "merchant",
1072
- width: 576,
1073
- height: 325
1074
- },
1075
- square: {
1076
- field: "logo.square",
1077
- uploadKind: "merchant",
1078
- width: 1e3,
1079
- height: 1e3
1080
- },
1081
- featured: {
1082
- field: "feature[0]",
1083
- uploadKind: "merchantFeature",
1084
- width: 1200,
1085
- height: 600
1086
- }
1087
- });
1088
- /**
1089
- * The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
1090
- * `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
1091
- * Returns `null` for empty or non-string values.
1092
- */
1093
- function imageFileName(value) {
1094
- if (typeof value !== "string") return null;
1095
- const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
1096
- return last ? decodeURIComponent(last) : null;
1097
- }
1098
- /** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
1099
- function getMerchantImage(imageIds, slot) {
1100
- if (!imageIds || typeof imageIds !== "object") return null;
1101
- let value;
1102
- if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
1103
- else {
1104
- const logo = imageIds.logo;
1105
- value = logo && typeof logo === "object" ? logo[slot] : void 0;
1106
- }
1107
- return typeof value === "string" && value.trim() ? value.trim() : null;
1108
- }
1109
- /**
1110
- * An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
1111
- * holds only a file name (a fresh upload not yet saved; use the upload's `url`).
1112
- */
1113
- function getMerchantImageUrl(imageIds, slot, base) {
1114
- const value = getMerchantImage(imageIds, slot);
1115
- if (!value || !value.includes("/")) return "";
1116
- return getImageUrl(value, base);
1117
- }
1118
- /**
1119
- * Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
1120
- * with `null`). Other slots and unknown keys are kept; an empty `logo` or
1121
- * `feature` is removed.
1122
- */
1123
- function setMerchantImage(imageIds, slot, fileName) {
1124
- const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
1125
- if (slot === "featured") {
1126
- const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
1127
- const feature = fileName ? [fileName, ...rest] : rest;
1128
- if (feature.length > 0) next.feature = feature;
1129
- else delete next.feature;
1130
- } else {
1131
- const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
1132
- if (fileName) logo[slot] = fileName;
1133
- else delete logo[slot];
1134
- if (Object.keys(logo).length > 0) next.logo = logo;
1135
- else delete next.logo;
1136
- }
1137
- return next;
1138
- }
1139
- function toStored(value) {
1140
- if (typeof value === "string") return imageFileName(value) ?? void 0;
1141
- if (Array.isArray(value)) {
1142
- const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
1143
- return items.length > 0 ? items : void 0;
1144
- }
1145
- if (value && typeof value === "object") {
1146
- const out = {};
1147
- for (const [k, v] of Object.entries(value)) {
1148
- const stored = toStored(v);
1149
- if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
1150
- }
1151
- return Object.keys(out).length > 0 ? out : void 0;
1152
- }
1153
- }
1154
- /**
1155
- * The `imageIds` to send on a save: every URL is turned back into its file
1156
- * name (what adminV1 does with images you didn't change) and empty values
1157
- * are dropped. No images gives `{}`.
1158
- */
1159
- function toStoredImageIds(imageIds) {
1160
- return toStored(imageIds) ?? {};
1161
- }
1162
- /**
1163
- * Uploads an image for a merchant slot: fits it to the slot's size, uploads
1164
- * it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
1165
- * `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
1166
- */
1167
- async function uploadMerchantImage(file, slot, options = {}) {
1168
- const def = MERCHANT_IMAGE_SLOTS[slot];
1169
- if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
1170
- const { fit = true, fitOptions,...requestOptions } = options;
1171
- return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1172
- }
1173
-
1174
1414
  //#endregion
1175
1415
  //#region src/core/merchant.ts
1176
1416
  const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
@@ -1347,5 +1587,5 @@ async function fetchUser(options = {}) {
1347
1587
  }
1348
1588
 
1349
1589
  //#endregion
1350
- export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, PromotionRuleSet, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_LOOKUPS, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, ShopwaveApiError, UPLOAD_KINDS, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProductInstanceTags, fetchProductTags, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, normalizeTagList, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, validateMerchant, withToken };
1590
+ export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, ImageRuleError, ImageTooSmallError, MERCHANT_COLOUR_KEYS, MERCHANT_FIELD_MAX_LENGTH, MERCHANT_IMAGE_SLOTS, MERCHANT_IMAGE_SLOT_KEYS, MERCHANT_LINK_KEYS, MERCHANT_LINK_PATHS, MERCHANT_OBJECT_FIELDS, MERCHANT_READ_ONLY_FIELDS, PromotionRuleSet, SHOPWAVE_ENTITIES, SHOPWAVE_IMAGE_BASE_URL, SHOPWAVE_LOOKUPS, SHOPWAVE_RESOURCES, SHOPWAVE_UPLOAD, ShopwaveApiError, UPLOAD_KINDS, UPLOAD_PREFIXES, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, checkImageRule, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, coverCrop, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchMerchant, fetchProduct, fetchProductInstanceTags, fetchProductTags, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, findRepricedInstances, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isSameInstancePrice, isUploadKind, isUploadPrefix, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, normalizeTagList, parseAspectRatio, parseBasketReportData, planImageFit, prepareImage, productImageRole, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, toStoredProductImages, updateMerchant, uploadImage, uploadMerchantImage, validateMerchant, withToken };
1351
1591
  //# sourceMappingURL=index.js.map