react-shopwave-connect 0.3.0 → 0.4.0

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
@@ -710,6 +710,486 @@ function buildConsumerMap(consumers) {
710
710
  return map;
711
711
  }
712
712
 
713
+ //#endregion
714
+ //#region src/core/resources.ts
715
+ /**
716
+ * - merchant: `GET /merchant`; `POST /merchant` with `{ merchant: { id, … } }`
717
+ * updates it (without an `id` the API would create a second merchant, so the
718
+ * route requires one).
719
+ * - user: `GET /user` (read-only here; the API's `POST /user` invites users and
720
+ * needs the admin scope).
721
+ */
722
+ const SHOPWAVE_RESOURCES = Object.freeze({
723
+ merchant: {
724
+ route: "merchant",
725
+ key: "merchant",
726
+ upstream: "merchant",
727
+ writable: true
728
+ },
729
+ user: {
730
+ route: "user",
731
+ key: "user",
732
+ upstream: "user",
733
+ writable: false
734
+ }
735
+ });
736
+ /** `UploadKind` → the API's `contentType` value. */
737
+ const UPLOAD_KINDS = Object.freeze({
738
+ merchant: "merchant",
739
+ merchantFeature: "merchantFeature",
740
+ product: "product",
741
+ user: "user",
742
+ applicationLogo: "applicaionLogo",
743
+ applicationImages: "applicaionImages"
744
+ });
745
+ /** How uploads are addressed (app route and Shopwave uploader). */
746
+ const SHOPWAVE_UPLOAD = Object.freeze({
747
+ route: "upload",
748
+ upstream: "uploader",
749
+ kindHeader: "contentType",
750
+ fileField: "file",
751
+ kindField: "kind"
752
+ });
753
+ function isUploadKind(value) {
754
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(UPLOAD_KINDS, value);
755
+ }
756
+
757
+ //#endregion
758
+ //#region src/core/imageFit.ts
759
+ /**
760
+ * The centred part of a `srcWidth × srcHeight` image with the aspect ratio of
761
+ * `dstWidth × dstHeight` (like CSS `object-fit: cover`).
762
+ */
763
+ function coverCrop(srcWidth, srcHeight, dstWidth, dstHeight) {
764
+ if (![
765
+ srcWidth,
766
+ srcHeight,
767
+ dstWidth,
768
+ dstHeight
769
+ ].every((n) => Number.isFinite(n) && n > 0)) throw new Error("coverCrop: sizes must be positive numbers");
770
+ const srcRatio = srcWidth / srcHeight;
771
+ const dstRatio = dstWidth / dstHeight;
772
+ if (srcRatio > dstRatio) {
773
+ const sw = Math.round(srcHeight * dstRatio);
774
+ return {
775
+ sx: Math.round((srcWidth - sw) / 2),
776
+ sy: 0,
777
+ sw,
778
+ sh: srcHeight
779
+ };
780
+ }
781
+ const sh = Math.round(srcWidth / dstRatio);
782
+ return {
783
+ sx: 0,
784
+ sy: Math.round((srcHeight - sh) / 2),
785
+ sw: srcWidth,
786
+ sh
787
+ };
788
+ }
789
+ function requireBrowserImages(fn) {
790
+ if (typeof createImageBitmap !== "function") throw new Error(`${fn} needs a browser (createImageBitmap is not available)`);
791
+ }
792
+ /** Reads an image file's pixel size (browser only). */
793
+ async function readImageSize(file) {
794
+ requireBrowserImages("readImageSize");
795
+ const bitmap = await createImageBitmap(file);
796
+ try {
797
+ return {
798
+ width: bitmap.width,
799
+ height: bitmap.height
800
+ };
801
+ } finally {
802
+ bitmap.close?.();
803
+ }
804
+ }
805
+ /**
806
+ * Returns the image at exactly `width × height`: scaled and centre-cropped
807
+ * (never stretched). Browser only. The result is a `File` named like the
808
+ * input, with the output type's extension.
809
+ */
810
+ async function fitImageToSize(file, width, height, options = {}) {
811
+ requireBrowserImages("fitImageToSize");
812
+ const { type = "image/png", quality, keepIfExact = true } = options;
813
+ const name = file.name || "image";
814
+ const ext = type === "image/jpeg" ? "jpg" : type.split("/")[1];
815
+ const outName = `${name.replace(/\.[^.]+$/, "")}.${ext}`;
816
+ const bitmap = await createImageBitmap(file);
817
+ try {
818
+ if (keepIfExact && bitmap.width === width && bitmap.height === height && file.type === type) return file instanceof File ? file : new File([file], outName, { type });
819
+ const { sx, sy, sw, sh } = coverCrop(bitmap.width, bitmap.height, width, height);
820
+ let blob;
821
+ if (typeof OffscreenCanvas === "function") {
822
+ const canvas = new OffscreenCanvas(width, height);
823
+ const ctx = canvas.getContext("2d");
824
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
825
+ ctx.imageSmoothingQuality = "high";
826
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
827
+ blob = await canvas.convertToBlob({
828
+ type,
829
+ quality
830
+ });
831
+ } else {
832
+ const canvas = document.createElement("canvas");
833
+ canvas.width = width;
834
+ canvas.height = height;
835
+ const ctx = canvas.getContext("2d");
836
+ if (!ctx) throw new Error("fitImageToSize: no 2D canvas context");
837
+ ctx.imageSmoothingQuality = "high";
838
+ ctx.drawImage(bitmap, sx, sy, sw, sh, 0, 0, width, height);
839
+ blob = await new Promise((resolve, reject) => canvas.toBlob((b) => b ? resolve(b) : reject(/* @__PURE__ */ new Error("fitImageToSize: encoding failed")), type, quality));
840
+ }
841
+ return new File([blob], outName, { type });
842
+ } finally {
843
+ bitmap.close?.();
844
+ }
845
+ }
846
+
847
+ //#endregion
848
+ //#region src/core/upload.ts
849
+ /**
850
+ * HTTPS host that serves the Shopwave CDN's images. The API returns
851
+ * `http://static.merchantstack.com/images/…`, which has no HTTPS endpoint
852
+ * (checked Sep 2026), so pages served over HTTPS can't show it.
853
+ */
854
+ const SHOPWAVE_IMAGE_BASE_URL = "https://s3-eu-west-1.amazonaws.com/static.merchantstack.com/images";
855
+ const STATIC_HOST = /^https?:\/\/static\.merchantstack\.com\/images\//i;
856
+ /**
857
+ * Turns an image path from the API into a URL a page can load over HTTPS:
858
+ * `http://static.merchantstack.com/images/x.png` → `<base>/x.png`, and a
859
+ * relative path (`merchant/5644/logo/x.png`) → `<base>/merchant/5644/logo/x.png`.
860
+ * Other absolute URLs are returned unchanged; empty input gives `""`.
861
+ */
862
+ function getImageUrl(path, base = SHOPWAVE_IMAGE_BASE_URL) {
863
+ if (!path) return "";
864
+ const root = base.replace(/\/+$/, "");
865
+ if (STATIC_HOST.test(path)) return `${root}/${path.replace(STATIC_HOST, "")}`;
866
+ if (/^[a-z][a-z0-9+.-]*:/i.test(path) || path.startsWith("//")) return path;
867
+ return `${root}/${path.replace(/^\/+/, "")}`;
868
+ }
869
+ /**
870
+ * Uploads one image to the Shopwave CDN through the app's `/api/upload` route
871
+ * (`createShopwaveApi(...).upload()`), and returns its id and URL.
872
+ *
873
+ * The file only lands on the CDN (under `…/images/<kind>/<merchantId>/…`); a
874
+ * record has to point at it to use it. Live API (Sep 2026): the upload answers
875
+ * 201 `{ fileName, path }`.
876
+ */
877
+ async function uploadImage(file, params, options = {}) {
878
+ if (!file || typeof file.size !== "number") throw new Error("uploadImage: file must be a File or Blob");
879
+ if (!isUploadKind(params?.kind)) throw new Error(`uploadImage: unknown kind "${params?.kind}"`);
880
+ const name = params.fileName ?? file.name ?? "upload";
881
+ const form = new FormData();
882
+ form.append(SHOPWAVE_UPLOAD.fileField, file, name);
883
+ form.append(SHOPWAVE_UPLOAD.kindField, params.kind);
884
+ const { status, body: raw } = await apiRequest(`/api/${SHOPWAVE_UPLOAD.route}`, {
885
+ method: "POST",
886
+ body: form
887
+ }, options);
888
+ const body = raw;
889
+ assertNoApiErrors(body, status);
890
+ const id = typeof body?.fileName === "string" ? body.fileName : "";
891
+ const path = typeof body?.path === "string" ? body.path : "";
892
+ if (!id) throw new ShopwaveApiError(status, `Shopwave API error (${status}): the upload response has no fileName`, { body });
893
+ return {
894
+ id,
895
+ url: getImageUrl(path),
896
+ path
897
+ };
898
+ }
899
+
900
+ //#endregion
901
+ //#region src/core/merchantImages.ts
902
+ /** The three image slots on the merchant settings page. */
903
+ const MERCHANT_IMAGE_SLOT_KEYS = [
904
+ "receipt",
905
+ "square",
906
+ "featured"
907
+ ];
908
+ /**
909
+ * Where each slot lives, its upload kind and its exact size (from adminV1's
910
+ * merchant settings page).
911
+ */
912
+ const MERCHANT_IMAGE_SLOTS = Object.freeze({
913
+ receipt: {
914
+ field: "logo.receipt",
915
+ uploadKind: "merchant",
916
+ width: 576,
917
+ height: 325
918
+ },
919
+ square: {
920
+ field: "logo.square",
921
+ uploadKind: "merchant",
922
+ width: 1e3,
923
+ height: 1e3
924
+ },
925
+ featured: {
926
+ field: "feature[0]",
927
+ uploadKind: "merchantFeature",
928
+ width: 1200,
929
+ height: 600
930
+ }
931
+ });
932
+ /**
933
+ * The file name in an image value: `"http://…/logo/abc.png"` → `"abc.png"`,
934
+ * `"abc.png"` → `"abc.png"`. Query strings and fragments are ignored.
935
+ * Returns `null` for empty or non-string values.
936
+ */
937
+ function imageFileName(value) {
938
+ if (typeof value !== "string") return null;
939
+ const last = value.trim().replace(/[?#].*$/, "").split("/").pop() ?? "";
940
+ return last ? decodeURIComponent(last) : null;
941
+ }
942
+ /** The stored value for a slot (a URL when read from the API; a file name right after an upload). */
943
+ function getMerchantImage(imageIds, slot) {
944
+ if (!imageIds || typeof imageIds !== "object") return null;
945
+ let value;
946
+ if (slot === "featured") value = Array.isArray(imageIds.feature) ? imageIds.feature[0] : void 0;
947
+ else {
948
+ const logo = imageIds.logo;
949
+ value = logo && typeof logo === "object" ? logo[slot] : void 0;
950
+ }
951
+ return typeof value === "string" && value.trim() ? value.trim() : null;
952
+ }
953
+ /**
954
+ * An HTTPS URL for a slot's stored image, or `""` when the slot is empty or
955
+ * holds only a file name (a fresh upload not yet saved; use the upload's `url`).
956
+ */
957
+ function getMerchantImageUrl(imageIds, slot, base) {
958
+ const value = getMerchantImage(imageIds, slot);
959
+ if (!value || !value.includes("/")) return "";
960
+ return getImageUrl(value, base);
961
+ }
962
+ /**
963
+ * Returns a copy of `imageIds` with one slot set to `fileName` (or cleared
964
+ * with `null`). Other slots and unknown keys are kept; an empty `logo` or
965
+ * `feature` is removed.
966
+ */
967
+ function setMerchantImage(imageIds, slot, fileName) {
968
+ const next = { ...imageIds && typeof imageIds === "object" ? imageIds : {} };
969
+ if (slot === "featured") {
970
+ const rest = Array.isArray(next.feature) ? next.feature.slice(1) : [];
971
+ const feature = fileName ? [fileName, ...rest] : rest;
972
+ if (feature.length > 0) next.feature = feature;
973
+ else delete next.feature;
974
+ } else {
975
+ const logo = { ...next.logo && typeof next.logo === "object" ? next.logo : {} };
976
+ if (fileName) logo[slot] = fileName;
977
+ else delete logo[slot];
978
+ if (Object.keys(logo).length > 0) next.logo = logo;
979
+ else delete next.logo;
980
+ }
981
+ return next;
982
+ }
983
+ function toStored(value) {
984
+ if (typeof value === "string") return imageFileName(value) ?? void 0;
985
+ if (Array.isArray(value)) {
986
+ const items = value.map(toStored).filter((v) => v !== void 0 && v !== null && v !== "");
987
+ return items.length > 0 ? items : void 0;
988
+ }
989
+ if (value && typeof value === "object") {
990
+ const out = {};
991
+ for (const [k, v] of Object.entries(value)) {
992
+ const stored = toStored(v);
993
+ if (stored !== void 0 && stored !== null && stored !== "") out[k] = stored;
994
+ }
995
+ return Object.keys(out).length > 0 ? out : void 0;
996
+ }
997
+ }
998
+ /**
999
+ * The `imageIds` to send on a save: every URL is turned back into its file
1000
+ * name (what adminV1 does with images you didn't change) and empty values
1001
+ * are dropped. No images gives `{}`.
1002
+ */
1003
+ function toStoredImageIds(imageIds) {
1004
+ return toStored(imageIds) ?? {};
1005
+ }
1006
+ /**
1007
+ * Uploads an image for a merchant slot: fits it to the slot's size, uploads
1008
+ * it with the slot's kind, and returns `{ id, url, path }`. Put `id` into
1009
+ * `imageIds` with {@link setMerchantImage} and save with `updateMerchant`.
1010
+ */
1011
+ async function uploadMerchantImage(file, slot, options = {}) {
1012
+ const def = MERCHANT_IMAGE_SLOTS[slot];
1013
+ if (!def) throw new Error(`uploadMerchantImage: unknown slot "${slot}"`);
1014
+ const { fit = true, fitOptions,...requestOptions } = options;
1015
+ return uploadImage(fit ? await fitImageToSize(file, def.width, def.height, fitOptions) : file, { kind: def.uploadKind }, requestOptions);
1016
+ }
1017
+
1018
+ //#endregion
1019
+ //#region src/core/merchant.ts
1020
+ const MERCHANT_PATH = `/api/${SHOPWAVE_RESOURCES.merchant.route}`;
1021
+ /** Colour keys inside `colours.primary`, in display order. */
1022
+ const MERCHANT_COLOUR_KEYS = [
1023
+ "main",
1024
+ "highlight",
1025
+ "contrast"
1026
+ ];
1027
+ /** Flat link fields a form edits, in display order. */
1028
+ const MERCHANT_LINK_KEYS = [
1029
+ "website",
1030
+ "twitter",
1031
+ "facebook",
1032
+ "instagram"
1033
+ ];
1034
+ /** Where each flat link field lives in `merchant.links`. */
1035
+ const MERCHANT_LINK_PATHS = Object.freeze({
1036
+ website: ["website", "home"],
1037
+ twitter: ["social", "twitter"],
1038
+ facebook: ["social", "facebook"],
1039
+ instagram: ["social", "instagram"]
1040
+ });
1041
+ function trimmed(value) {
1042
+ return typeof value === "string" && value.trim() ? value.trim() : void 0;
1043
+ }
1044
+ /**
1045
+ * Reads `merchant.links` as flat fields (`{ website, twitter, facebook,
1046
+ * instagram }`), whatever shape it was saved in:
1047
+ * - the nested shape adminV1 saves (`{ website: { home }, social: { … } }`);
1048
+ * - flat keys (`{ website: "…" }`, what SDK 0.4.0 pre-releases sent);
1049
+ * - an array in {@link MERCHANT_LINK_KEYS} order (older AdminUI versions).
1050
+ * Empty values are dropped.
1051
+ */
1052
+ function merchantLinksToForm(links) {
1053
+ const out = {};
1054
+ if (Array.isArray(links)) {
1055
+ links.forEach((value, i) => {
1056
+ const key = MERCHANT_LINK_KEYS[i];
1057
+ const v = trimmed(value);
1058
+ if (key && v) out[key] = v;
1059
+ });
1060
+ return out;
1061
+ }
1062
+ if (!links || typeof links !== "object") return out;
1063
+ const obj = links;
1064
+ for (const key of MERCHANT_LINK_KEYS) {
1065
+ const [group, field] = MERCHANT_LINK_PATHS[key];
1066
+ const nested = obj[group];
1067
+ const v = nested && typeof nested === "object" && !Array.isArray(nested) ? trimmed(nested[field]) : trimmed(obj[key]);
1068
+ if (v) out[key] = v;
1069
+ }
1070
+ return out;
1071
+ }
1072
+ /**
1073
+ * Builds the stored `links` object from flat fields. Empty values are left
1074
+ * out, and so is a group with nothing in it; no links gives `{}`.
1075
+ */
1076
+ function merchantLinksFromForm(form) {
1077
+ const out = {};
1078
+ for (const key of MERCHANT_LINK_KEYS) {
1079
+ const v = trimmed(form[key]);
1080
+ if (!v) continue;
1081
+ const [group, field] = MERCHANT_LINK_PATHS[key];
1082
+ (out[group] ??= {})[field] = v;
1083
+ }
1084
+ return out;
1085
+ }
1086
+ /** Reads any stored or older `links` value into the nested shape adminV1 saves. */
1087
+ function normalizeMerchantLinks(links) {
1088
+ return merchantLinksFromForm(merchantLinksToForm(links));
1089
+ }
1090
+ /**
1091
+ * Object fields of the merchant. The API keeps one you leave out, and
1092
+ * replaces it as a whole when you send it.
1093
+ */
1094
+ const MERCHANT_OBJECT_FIELDS = [
1095
+ "colours",
1096
+ "links",
1097
+ "imageIds"
1098
+ ];
1099
+ /** Fields the API sets itself; `updateMerchant` never sends them back. */
1100
+ const MERCHANT_READ_ONLY_FIELDS = ["createdDate", "modifiedDate"];
1101
+ /**
1102
+ * Longest values the API stores. Longer values are cut off silently
1103
+ * (live API, Sep 2026), so `updateMerchant` rejects them instead.
1104
+ * `vatNumber` fits a UK VAT number without the `GB` prefix.
1105
+ */
1106
+ const MERCHANT_FIELD_MAX_LENGTH = Object.freeze({
1107
+ companyNumber: 11,
1108
+ vatNumber: 9
1109
+ });
1110
+ /** Returns `"<field> is longer than <n> characters"` messages for over-long fields. */
1111
+ function validateMerchant(merchant) {
1112
+ const problems = [];
1113
+ for (const [field, max] of Object.entries(MERCHANT_FIELD_MAX_LENGTH)) {
1114
+ const value = merchant[field];
1115
+ if (typeof value === "string" && value.length > max) problems.push(`${field} is longer than ${max} characters`);
1116
+ }
1117
+ return problems;
1118
+ }
1119
+ /**
1120
+ * Reads the logged-in user's merchant (a user has exactly one), or `null`
1121
+ * when the API returns none.
1122
+ */
1123
+ async function fetchMerchant(options = {}) {
1124
+ const json = await apiGet(MERCHANT_PATH, {}, options);
1125
+ assertNoApiErrors(json, 200);
1126
+ return json?.merchant ?? null;
1127
+ }
1128
+ /**
1129
+ * Updates the merchant and returns it as stored.
1130
+ *
1131
+ * Shopwave's `POST /merchant` replaces the whole record: a scalar field you
1132
+ * leave out (`companyNumber`, `vatNumber`, `note`, …) is set to null, while
1133
+ * an object field you leave out (`colours`, `links`, `imageIds`) is kept and
1134
+ * one you send replaces the stored one; sending `{}` clears it (live API,
1135
+ * Sep 2026). So by default the
1136
+ * current merchant is read first and the patch is merged over it.
1137
+ *
1138
+ * `imageIds` is always sent as file names ({@link toStoredImageIds}), so you
1139
+ * can pass back what you read. See `MerchantImageIds` for the shape.
1140
+ *
1141
+ * The API answers 205 with an empty body, so the merchant is read again after
1142
+ * the save and that is what's returned (it shows exactly what was kept).
1143
+ * Throws before sending when a value is longer than the API stores
1144
+ * ({@link MERCHANT_FIELD_MAX_LENGTH}).
1145
+ */
1146
+ async function updateMerchant(patch, options = {}) {
1147
+ const { merge = true,...requestOptions } = options;
1148
+ let merchant = { ...patch };
1149
+ if (merge) {
1150
+ const current = await fetchMerchant(requestOptions);
1151
+ if (!current) throw new ShopwaveApiError(404, "Shopwave API error (404): no merchant to update");
1152
+ if (patch.id != null && String(patch.id) !== String(current.id)) throw new Error(`Merchant id ${patch.id} is not the logged-in merchant (${current.id})`);
1153
+ merchant = {
1154
+ ...current,
1155
+ ...patch,
1156
+ id: current.id
1157
+ };
1158
+ for (const field of MERCHANT_OBJECT_FIELDS) if (!(field in patch)) delete merchant[field];
1159
+ }
1160
+ if (merchant.imageIds && typeof merchant.imageIds === "object") merchant.imageIds = toStoredImageIds(merchant.imageIds);
1161
+ if (merchant.id == null || merchant.id === "") throw new Error("merchant id is missing");
1162
+ for (const field of MERCHANT_READ_ONLY_FIELDS) delete merchant[field];
1163
+ const problems = validateMerchant(merchant);
1164
+ if (problems.length > 0) throw new Error(`Invalid merchant: ${problems.join("; ")}`);
1165
+ const { status, body: raw } = await apiRequest(MERCHANT_PATH, {
1166
+ method: "PUT",
1167
+ headers: { "Content-Type": "application/json" },
1168
+ body: JSON.stringify({ merchant })
1169
+ }, requestOptions);
1170
+ const body = raw;
1171
+ assertNoApiErrors(body, status);
1172
+ const echoed = body?.merchant && typeof body.merchant === "object" ? body.merchant : null;
1173
+ if (echoed) return {
1174
+ ...merchant,
1175
+ ...echoed,
1176
+ id: Number(echoed.id ?? merchant.id)
1177
+ };
1178
+ return await fetchMerchant(requestOptions) ?? {
1179
+ ...merchant,
1180
+ id: Number(merchant.id)
1181
+ };
1182
+ }
1183
+
1184
+ //#endregion
1185
+ //#region src/core/user.ts
1186
+ /** Reads the logged-in user, or `null` when the API returns none. */
1187
+ async function fetchUser(options = {}) {
1188
+ const json = await apiGet(`/api/${SHOPWAVE_RESOURCES.user.route}`, {}, options);
1189
+ assertNoApiErrors(json, 200);
1190
+ return json?.user ?? null;
1191
+ }
1192
+
713
1193
  //#endregion
714
1194
  //#region src/hooks/shared.ts
715
1195
  function toMessage(e) {
@@ -1067,6 +1547,85 @@ function useSession(options) {
1067
1547
  }), [options?.baseUrl]);
1068
1548
  }
1069
1549
 
1550
+ //#endregion
1551
+ //#region src/hooks/useMerchant.ts
1552
+ /**
1553
+ * The logged-in user's merchant, fetched on mount. `data` is `null` while
1554
+ * loading or when the API has no merchant.
1555
+ *
1556
+ * @example
1557
+ * const { data: merchant, loading, refetch } = useMerchant();
1558
+ */
1559
+ function useMerchant(options) {
1560
+ return useQuery((signal) => fetchMerchant({
1561
+ ...options,
1562
+ signal
1563
+ }), [options?.baseUrl, options?.token]);
1564
+ }
1565
+ /**
1566
+ * Manually-triggered merchant update (see `updateMerchant`: the patch is merged
1567
+ * over the current merchant by default). Resolves to the saved merchant, or
1568
+ * `null` on error (then `error` / `errorStatus` are set).
1569
+ *
1570
+ * @example
1571
+ * const { mutate: saveMerchant, loading: saving } = useUpdateMerchant();
1572
+ * const saved = await saveMerchant({ vatNumber: "GB123" });
1573
+ */
1574
+ function useUpdateMerchant(options) {
1575
+ return useMutation((patch) => updateMerchant(patch, options), [
1576
+ options?.baseUrl,
1577
+ options?.token,
1578
+ options?.merge
1579
+ ]);
1580
+ }
1581
+
1582
+ //#endregion
1583
+ //#region src/hooks/useUser.ts
1584
+ /**
1585
+ * The logged-in user, fetched on mount. `errorStatus` is 401 when logged out.
1586
+ *
1587
+ * @example
1588
+ * const { data: user } = useUser();
1589
+ */
1590
+ function useUser(options) {
1591
+ const enabled = options?.enabled ?? true;
1592
+ return useQuery((signal) => fetchUser({
1593
+ ...options,
1594
+ signal
1595
+ }), [options?.baseUrl, options?.token], enabled);
1596
+ }
1597
+
1598
+ //#endregion
1599
+ //#region src/hooks/useUploadImage.ts
1600
+ /**
1601
+ * Manually-triggered image upload. Resolves to `{ id, url }`, or `null` on
1602
+ * error (then `error` / `errorStatus` are set).
1603
+ *
1604
+ * @example
1605
+ * const { mutate: upload, loading: uploading } = useUploadImage();
1606
+ * const image = await upload(file, { kind: "merchant" });
1607
+ */
1608
+ function useUploadImage(options) {
1609
+ return useMutation((file, params) => uploadImage(file, params, options), [options?.baseUrl, options?.token]);
1610
+ }
1611
+ /**
1612
+ * Manually-triggered upload for a merchant image slot (`receipt`, `square`,
1613
+ * `featured`): fits the image to the slot's exact size, uploads it with the
1614
+ * slot's kind, and resolves to `{ id, url }`. Put `id` into `imageIds` with
1615
+ * `setMerchantImage`.
1616
+ *
1617
+ * @example
1618
+ * const { mutate: upload } = useUploadMerchantImage();
1619
+ * const image = await upload(file, "square");
1620
+ */
1621
+ function useUploadMerchantImage(options) {
1622
+ return useMutation((file, slot) => uploadMerchantImage(file, slot, options), [
1623
+ options?.baseUrl,
1624
+ options?.token,
1625
+ options?.fit
1626
+ ]);
1627
+ }
1628
+
1070
1629
  //#endregion
1071
1630
  //#region src/hooks/useBasketReport.ts
1072
1631
  /**
@@ -1171,5 +1730,5 @@ function useBasketReport(options) {
1171
1730
  }
1172
1731
 
1173
1732
  //#endregion
1174
- export { DEFAULT_BASKET_FILTERS, DEFAULT_PAGINATION, PromotionRuleSet, SHOPWAVE_ENTITIES, ShopwaveApiError, apiDelete, apiGet, apiRequest, apiSend, assertNoApiErrors, authorizationFor, buildBasketReportQuery, buildConsumerMap, collectConsumerIds, collectProductIds, combineBasketRows, computeBasketSummary, deleteCategory, deleteEmployee, deleteEntity, deleteEntityById, deleteProduct, deletePromotion, deleteStore, fetchCategories, fetchCategory, fetchConsumer, fetchConsumers, fetchEmployee, fetchEmployees, fetchEntityById, fetchProduct, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, formatDateForQuery, getApiErrorMap, getApiErrors, loginPath, logout, logoutPath, parseBasketReportData, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, submitEntity, toShopwaveApiError, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, withToken };
1733
+ 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_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, fetchProducts, fetchProductsMap, fetchPromotion, fetchPromotions, fetchReport, fetchSession, fetchStore, fetchStores, fetchUser, fitImageToSize, formatDateForQuery, getApiErrorMap, getApiErrors, getImageUrl, getMerchantImage, getMerchantImageUrl, imageFileName, isUploadKind, loginPath, logout, logoutPath, merchantLinksFromForm, merchantLinksToForm, normalizeMerchantLinks, parseBasketReportData, readImageSize, rolesById, saveCategory, saveEmployee, saveEntities, saveEntity, saveProduct, savePromotion, saveStore, setMerchantImage, submitEntity, toShopwaveApiError, toStoredImageIds, updateMerchant, uploadImage, uploadMerchantImage, useBasketReport, useCategory, useConsumer, useDelete, useEmployee, useLogout, useMerchant, useProduct, usePromotion, useReport, useSession, useStore, useSubmit, useUpdateMerchant, useUploadImage, useUploadMerchantImage, useUser, validateMerchant, withToken };
1175
1734
  //# sourceMappingURL=index.js.map