react-shopwave-connect 0.4.4 → 0.4.6

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
@@ -638,6 +638,35 @@ async function readImageSize(file) {
638
638
  bitmap.close?.();
639
639
  }
640
640
  }
641
+ /** Draws `crop` of the bitmap at `width × height` and encodes it (one resample). */
642
+ async function drawCrop(bitmap, crop, width, height, type, quality, fn) {
643
+ const { sx, sy, sw, sh } = crop;
644
+ if (typeof OffscreenCanvas === "function") {
645
+ const canvas$1 = new OffscreenCanvas(width, height);
646
+ const ctx$1 = canvas$1.getContext("2d");
647
+ if (!ctx$1) throw new Error(`${fn}: no 2D canvas context`);
648
+ ctx$1.imageSmoothingQuality = "high";
649
+ ctx$1.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
650
+ return canvas$1.convertToBlob({
651
+ type,
652
+ quality
653
+ });
654
+ }
655
+ const canvas = document.createElement("canvas");
656
+ canvas.width = width;
657
+ canvas.height = height;
658
+ const ctx = canvas.getContext("2d");
659
+ if (!ctx) throw new Error(`${fn}: no 2D canvas context`);
660
+ ctx.imageSmoothingQuality = "high";
661
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
662
+ return new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error(`${fn}: encoding failed`)), type, quality));
663
+ }
664
+ /** The input's name with the output type's extension. */
665
+ function outputName(file, type) {
666
+ const name = file.name || "image";
667
+ const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
668
+ return `${name.replace(/\.[^.]+$/, "")}.${ext}`;
669
+ }
641
670
  /**
642
671
  * Returns the image at exactly `width × height`: scaled and centre-cropped
643
672
  * (never stretched). Browser only. The result is a `File` named like the
@@ -646,39 +675,194 @@ async function readImageSize(file) {
646
675
  async function fitImageToSize(file, width, height, options = {}) {
647
676
  requireBrowserImages("fitImageToSize");
648
677
  const { type = "image/png", quality, keepIfExact = true } = options;
649
- const name = file.name || "image";
650
- const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
651
- const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
678
+ const outName = outputName(file, type);
652
679
  const bitmap = await createImageBitmap(file);
653
680
  try {
654
681
  if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
655
- const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
656
- let blob;
657
- if (typeof OffscreenCanvas === "function") {
658
- const canvas = new OffscreenCanvas(width, height);
659
- const ctx = canvas.getContext("2d");
660
- if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
661
- ctx.imageSmoothingQuality = "high";
662
- ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
663
- blob = await canvas.convertToBlob({
664
- type,
665
- quality
666
- });
667
- } else {
668
- const canvas = document.createElement("canvas");
669
- canvas.width = width;
670
- canvas.height = height;
671
- const ctx = canvas.getContext("2d");
672
- if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
673
- ctx.imageSmoothingQuality = "high";
674
- ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
675
- blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
676
- }
682
+ const blob = await drawCrop(bitmap, coverCrop(bitmap.width, bitmap.height, width, height), width, height, type, quality, "fitImageToSize");
677
683
  return new File([blob], outName, { type });
678
684
  } finally {
679
685
  bitmap.close?.();
680
686
  }
681
687
  }
688
+ /** A rule that can't be met by any image (a mistake in the rule, not the image). */
689
+ var ImageRuleError = class extends Error {
690
+ constructor(message) {
691
+ super(message);
692
+ this.name = "ImageRuleError";
693
+ }
694
+ };
695
+ /** The image is smaller than the rule's minimum (and `allowUpscale` is off). */
696
+ var ImageTooSmallError = class extends Error {
697
+ /** The smallest size the rule accepts. */
698
+ required;
699
+ /** The largest area of the right shape the image could give. */
700
+ actual;
701
+ constructor(required, actual) {
702
+ super(`The image is too small: it needs to be at least ${required.width} × ${required.height}, and it's ${actual.width} × ${actual.height}`);
703
+ this.name = "ImageTooSmallError";
704
+ this.required = required;
705
+ this.actual = actual;
706
+ }
707
+ };
708
+ const isPositive = (n) => typeof n === "number" && Number.isFinite(n) && n > 0;
709
+ /**
710
+ * An aspect ratio as width ÷ height: `"100:77"`, `"100/77"`, `[100, 77]` →
711
+ * 1.2987…; `1.3` → 1.3. Throws {@link ImageRuleError} for anything else.
712
+ */
713
+ function parseAspectRatio(value) {
714
+ let parts = null;
715
+ if (typeof value === "number") return isPositive(value) ? value : badRatio(value);
716
+ if (Array.isArray(value)) parts = [value[0], value[1]];
717
+ else if (typeof value === "string") {
718
+ const text$1 = value.trim();
719
+ const match = /^(\d+(?:\.\d+)?)\s*[:/x×]\s*(\d+(?:\.\d+)?)$/i.exec(text$1);
720
+ if (match) parts = [Number(match[1]), Number(match[2])];
721
+ else if (/^\d+(?:\.\d+)?$/.test(text$1)) return isPositive(Number(text$1)) ? Number(text$1) : badRatio(value);
722
+ }
723
+ if (parts && isPositive(parts[0]) && isPositive(parts[1])) return parts[0] / parts[1];
724
+ return badRatio(value);
725
+ }
726
+ function badRatio(value) {
727
+ throw new ImageRuleError(`Not an aspect ratio: ${JSON.stringify(value)} (use e.g. "100:77", [100, 77] or 1.3)`);
728
+ }
729
+ /** Throws {@link ImageRuleError} when the rule contradicts itself. */
730
+ function checkImageRule(rule) {
731
+ if (!rule || typeof rule !== "object") throw new ImageRuleError("An image rule must be an object");
732
+ for (const key of [
733
+ "width",
734
+ "height",
735
+ "minWidth",
736
+ "minHeight",
737
+ "maxWidth",
738
+ "maxHeight",
739
+ "maxLongSide"
740
+ ]) if (rule[key] != null && !isPositive(rule[key])) throw new ImageRuleError(`${key} must be a positive number`);
741
+ if (rule.width != null || rule.height != null) {
742
+ if (rule.width == null || rule.height == null) throw new ImageRuleError("An exact size needs both width and height");
743
+ if (rule.aspectRatio != null) throw new ImageRuleError("Give an exact size or an aspectRatio, not both (the size sets the ratio)");
744
+ const extra = [
745
+ "minWidth",
746
+ "minHeight",
747
+ "maxWidth",
748
+ "maxHeight",
749
+ "maxLongSide"
750
+ ].filter((key) => rule[key] != null);
751
+ if (extra.length > 0) throw new ImageRuleError(`An exact size is already the minimum and the maximum; remove ${extra.join(", ")}`);
752
+ return;
753
+ }
754
+ if (rule.aspectRatio != null) parseAspectRatio(rule.aspectRatio);
755
+ if (rule.minWidth != null && rule.maxWidth != null && rule.minWidth > rule.maxWidth) throw new ImageRuleError("minWidth is larger than maxWidth");
756
+ if (rule.minHeight != null && rule.maxHeight != null && rule.minHeight > rule.maxHeight) throw new ImageRuleError("minHeight is larger than maxHeight");
757
+ if (rule.maxLongSide != null && Math.max(rule.minWidth ?? 0, rule.minHeight ?? 0) > rule.maxLongSide) throw new ImageRuleError("The minimum size is larger than maxLongSide");
758
+ }
759
+ /**
760
+ * Works out what to do to a `source`-sized image to meet `rule`: the centred
761
+ * crop of the right shape (the largest one), then the output size (scaled
762
+ * down to the maximum, never below the minimum). Pure: no browser needed.
763
+ *
764
+ * Throws {@link ImageTooSmallError} when the crop is below the minimum (or
765
+ * the exact size) and `allowUpscale` is off, and {@link ImageRuleError} for a
766
+ * contradictory rule.
767
+ *
768
+ * @example
769
+ * planImageFit({ width: 6000, height: 4000 }, { aspectRatio: "100:77", minWidth: 600, minHeight: 462, maxLongSide: 2000 })
770
+ * // → crop { sx: 403, sy: 0, sw: 5194, sh: 4000 }, 2000 × 1540
771
+ */
772
+ function planImageFit(source, rule) {
773
+ checkImageRule(rule);
774
+ const { width: W, height: H } = source ?? {};
775
+ if (!isPositive(W) || !isPositive(H)) throw new Error("planImageFit: the image has no size");
776
+ const exact = rule.width != null && rule.height != null;
777
+ const ratio = exact ? rule.width / rule.height : rule.aspectRatio != null ? parseAspectRatio(rule.aspectRatio) : null;
778
+ const crop = ratio == null ? {
779
+ sx: 0,
780
+ sy: 0,
781
+ sw: W,
782
+ sh: H
783
+ } : coverCrop(W, H, ratio, 1);
784
+ const { sw, sh } = crop;
785
+ const kept = {
786
+ width: sw,
787
+ height: sh
788
+ };
789
+ let width;
790
+ let height;
791
+ if (exact) {
792
+ width = rule.width;
793
+ height = rule.height;
794
+ if ((sw < width || sh < height) && !rule.allowUpscale) throw new ImageTooSmallError({
795
+ width,
796
+ height
797
+ }, kept);
798
+ } else {
799
+ const minW = rule.minWidth ?? 0;
800
+ const minH = rule.minHeight ?? 0;
801
+ if ((sw < minW || sh < minH) && !rule.allowUpscale) throw new ImageTooSmallError(requiredSize(minW, minH, ratio), kept);
802
+ let scale = 1;
803
+ if (rule.maxWidth != null) scale = Math.min(scale, rule.maxWidth / sw);
804
+ if (rule.maxHeight != null) scale = Math.min(scale, rule.maxHeight / sh);
805
+ if (rule.maxLongSide != null) scale = Math.min(scale, rule.maxLongSide / Math.max(sw, sh));
806
+ scale = Math.max(scale, minW / sw, minH / sh);
807
+ width = Math.max(1, Math.round(sw * scale));
808
+ height = Math.max(1, Math.round(sh * scale));
809
+ }
810
+ const unchanged = crop.sx === 0 && crop.sy === 0 && sw === W && sh === H && width === W && height === H;
811
+ return {
812
+ crop,
813
+ width,
814
+ height,
815
+ unchanged
816
+ };
817
+ }
818
+ /** The minimum as a full size: a ratio rule with only one minimum implies the other. */
819
+ function requiredSize(minW, minH, ratio) {
820
+ if (ratio == null) return {
821
+ width: minW,
822
+ height: minH
823
+ };
824
+ return {
825
+ width: Math.max(minW, Math.ceil(minH * ratio)),
826
+ height: Math.max(minH, Math.ceil(minW / ratio))
827
+ };
828
+ }
829
+ const OUTPUT_TYPES = [
830
+ "image/png",
831
+ "image/jpeg",
832
+ "image/webp"
833
+ ];
834
+ /**
835
+ * Returns the image meeting `rule` ({@link planImageFit}): centre-cropped to
836
+ * the right shape and scaled in a single draw. An image that already fits is
837
+ * returned untouched (same bytes). Browser only.
838
+ *
839
+ * Throws {@link ImageTooSmallError} (show `required` and `actual` to the
840
+ * person) or {@link ImageRuleError}; an unreadable file rejects with the
841
+ * browser's decoding error.
842
+ *
843
+ * @example
844
+ * const ready = await prepareImage(file, { aspectRatio: "100:77", minWidth: 600, minHeight: 462, maxLongSide: 2000 });
845
+ * await uploadImage(ready, { kind: "product", prefix: "product" });
846
+ */
847
+ async function prepareImage(file, rule, options = {}) {
848
+ checkImageRule(rule);
849
+ requireBrowserImages("prepareImage");
850
+ const sourceType = file.type && OUTPUT_TYPES.includes(file.type) ? file.type : "image/png";
851
+ const type = options.type ?? sourceType;
852
+ const quality = options.quality ?? (type === "image/png" ? void 0 : .9);
853
+ const bitmap = await createImageBitmap(file);
854
+ try {
855
+ const plan = planImageFit({
856
+ width: bitmap.width,
857
+ height: bitmap.height
858
+ }, rule);
859
+ if (plan.unchanged && type === file.type) return file instanceof File ? file : new File([file], outputName(file, type), { type });
860
+ const blob = await drawCrop(bitmap, plan.crop, plan.width, plan.height, type, quality, "prepareImage");
861
+ return new File([blob], outputName(file, type), { type });
862
+ } finally {
863
+ bitmap.close?.();
864
+ }
865
+ }
682
866
 
683
867
  //#endregion
684
868
  //#region src/core/upload.ts
@@ -692,7 +876,7 @@ const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
692
876
  /**
693
877
  * Turns an image path from the API into a URL a page can load over HTTPS:
694
878
  * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
695
- * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
879
+ * relative path (`merchant/123/logo/x.png`) → `<base>/merchant/123/logo/x.png`.
696
880
  * Other absolute URLs are returned unchanged; empty input gives `""`.
697
881
  */
698
882
  function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
@@ -744,7 +928,7 @@ const MERCHANT_IMAGE_SLOT_KEYS = [
744
928
  "featured"
745
929
  ];
746
930
  /**
747
- * Where each slot lives, its upload kind and its exact size (from adminV1's
931
+ * Where each slot lives, its upload kind and its exact size (from the existing admin's
748
932
  * merchant settings page).
749
933
  */
750
934
  const MERCHANT_IMAGE_SLOTS = Object.freeze({
@@ -835,7 +1019,7 @@ function toStored(value) {
835
1019
  }
836
1020
  /**
837
1021
  * The `imageIds` to send on a save: every URL is turned back into its file
838
- * name (what adminV1 does with images you didn't change) and empty values
1022
+ * name (what the existing admin does with images you didn't change) and empty values
839
1023
  * are dropped. No images gives `{}`.
840
1024
  */
841
1025
  function toStoredImageIds(imageIds) {
@@ -856,7 +1040,7 @@ async function uploadMerchantImage(file, slot, options = {}) {
856
1040
  //#endregion
857
1041
  //#region src/core/productImages.ts
858
1042
  /**
859
- * Product images, as the live API stores them (merchant 5644, 4 Nov 2026):
1043
+ * Product images, as the live API stores them (4 Nov 2026):
860
1044
  * - A product's `images` is a list. **Reads return full URLs**
861
1045
  * (`http://static.merchantstack.com/images/merchant/<id>/product/<file>`);
862
1046
  * **writes take the uploader's file names** ({@link toStoredProductImages};
@@ -1258,9 +1442,9 @@ function trimmed(value) {
1258
1442
  /**
1259
1443
  * Reads `merchant.links` as flat fields (`{ website, twitter, facebook,
1260
1444
  * instagram }`), whatever shape it was saved in:
1261
- * - the nested shape adminV1 saves (`{ website: { home }, social: { … } }`);
1445
+ * - the nested shape the existing admin saves (`{ website: { home }, social: { … } }`);
1262
1446
  * - flat keys (`{ website: "…" }`, what SDK 0.4.0 pre-releases sent);
1263
- * - an array in {@link MERCHANT_LINK_KEYS} order (older AdminUI versions).
1447
+ * - an array in {@link MERCHANT_LINK_KEYS} order (older app versions).
1264
1448
  * Empty values are dropped.
1265
1449
  */
1266
1450
  function merchantLinksToForm(links) {
@@ -1297,7 +1481,7 @@ function merchantLinksFromForm(form) {
1297
1481
  }
1298
1482
  return out;
1299
1483
  }
1300
- /** Reads any stored or older `links` value into the nested shape adminV1 saves. */
1484
+ /** Reads any stored or older `links` value into the nested shape the existing admin saves. */
1301
1485
  function normalizeMerchantLinks(links) {
1302
1486
  return merchantLinksFromForm(merchantLinksToForm(links));
1303
1487
  }
@@ -1971,5 +2155,5 @@ function useBasketReport(options) {
1971
2155
  }
1972
2156
 
1973
2157
  //#endregion
1974
- 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, UPLOAD_PREFIXES, 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, isUploadPrefix, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, normalizeTagList, parseBasketReportData, productImageRole, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toProductInstancesForSave, toShopwaveApiError, toStoredImageIds, toStoredProductImages, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, useProductInstanceTags, useProductTags, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
2158
+ 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, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, useProductInstanceTags, useProductTags, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1975
2159
  //# sourceMappingURL=index.js.map