@tallyui/connector-medusa 2.0.0 → 3.0.0-next.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/README.md ADDED
@@ -0,0 +1,7 @@
1
+ # TallyUI Medusa connector
2
+
3
+ ## Errors
4
+
5
+ Requests with expired or rejected credentials reject with `ConnectorUnauthorizedError` (`code: 'unauthorized'`), defined in `@tallyui/core` and re-exported by this connector. The app should sign in again.
6
+
7
+ Sign-in itself rejects with `SignInError`.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
- import { ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, ConnectorAuth, TallyConnector, ServerCapabilities } from '@tallyui/core';
1
+ import * as _tallyui_core from '@tallyui/core';
2
+ import { ProductTraits, CollectionSync, ReplicationAdapter, StockReconcileAdapter, SyncContext, StoreSettingsChoice, StoreSettings, CustomerInput, Customer, TallyConnector, ConnectorAuth, ServerCapabilities } from '@tallyui/core';
3
+ export { ConnectorUnauthorizedError } from '@tallyui/core';
2
4
  import { RxJsonSchema } from 'rxdb';
3
5
 
4
6
  /** A store API variant's `calculated_price`: the fields the connector reads. Amounts are major units. */
@@ -128,6 +130,21 @@ declare const medusaStockReconcile: StockReconcileAdapter;
128
130
  */
129
131
  declare const medusaStoreSettings: (context: SyncContext, choice?: StoreSettingsChoice) => Promise<StoreSettings>;
130
132
 
133
+ type MedusaCustomer = {
134
+ id: string;
135
+ deleted_at?: string | null;
136
+ } & Record<string, unknown>;
137
+ type CustomerInit = {
138
+ signal?: AbortSignal;
139
+ fetch?: typeof fetch;
140
+ };
141
+ declare function toCustomer(raw: MedusaCustomer): Customer;
142
+ declare function searchMedusaCustomers(baseUrl: string, headers: Record<string, string>, query: string, init?: CustomerInit & {
143
+ limit?: number;
144
+ }): Promise<Customer[]>;
145
+ declare function createMedusaCustomer(baseUrl: string, headers: Record<string, string>, input: CustomerInput, init?: CustomerInit): Promise<Customer>;
146
+ declare function getMedusaCustomer(baseUrl: string, headers: Record<string, string>, id: string, init?: CustomerInit): Promise<Customer | null>;
147
+
131
148
  /**
132
149
  * Fills each variant's `calculated_price` from the store API, priced with
133
150
  * `context.pricingContext` (`region_id`, `publishable_key`): what Medusa
@@ -148,24 +165,41 @@ declare const medusaSecretKeyAuth: ConnectorAuth;
148
165
  declare const medusaSignIn: NonNullable<ConnectorAuth['signIn']>;
149
166
  /** Re-reads the store's `order.create` capability (ADR-062) for a restored session, with the connector's own headers. */
150
167
  declare const medusaCapabilities: (context: SyncContext) => Promise<ServerCapabilities | undefined>;
168
+ declare const medusaSearchCustomers: (context: SyncContext, query: string, options?: {
169
+ limit?: number;
170
+ }) => Promise<_tallyui_core.Customer[]>;
171
+ declare const medusaCreateCustomer: (context: SyncContext, input: CustomerInput) => Promise<_tallyui_core.Customer>;
172
+ declare const medusaGetCustomer: (context: SyncContext, id: string) => Promise<_tallyui_core.Customer | null>;
151
173
  declare const medusaAdminUserAuth: ConnectorAuth;
152
174
  /**
153
- * MedusaJS v2 connector for Tally UI.
175
+ * MedusaJS v2 connector for Tally UI, with a secret API key. Build one per store session, anew on each
176
+ * sign-in or store change: it owns the reconcile feed, whose queued work must never reach another store's database (#307).
154
177
  *
155
178
  * Connects to Medusa backends via the Admin API.
156
179
  * Products are stored in RxDB using a schema that mirrors the Medusa API shape.
157
180
  *
158
181
  * ```ts
159
- * import { medusaConnector } from '@tallyui/connector-medusa';
182
+ * import { createMedusaConnector } from '@tallyui/connector-medusa';
160
183
  * import { ConnectorProvider } from '@tallyui/core';
161
184
  *
162
- * <ConnectorProvider connector={medusaConnector}>
185
+ * const connector = useMemo(() => createMedusaConnector(), [backendUrl]);
186
+ * <ConnectorProvider connector={connector}>
163
187
  * <App />
164
188
  * </ConnectorProvider>
165
189
  * ```
166
190
  */
191
+ declare function createMedusaConnector(): TallyConnector;
192
+ /** Medusa connector using an admin user's Bearer JWT; like createMedusaConnector(), one per store session with its own feed. */
193
+ declare const createMedusaAdminUserConnector: () => TallyConnector;
194
+ /**
195
+ * @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
196
+ * Use createMedusaConnector() per store session. Removed in 4.0.
197
+ */
167
198
  declare const medusaConnector: TallyConnector;
168
- /** Medusa connector using an admin user's Bearer JWT. */
199
+ /**
200
+ * @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
201
+ * Use createMedusaAdminUserConnector() per store session. Removed in 4.0.
202
+ */
169
203
  declare const medusaAdminUserConnector: TallyConnector;
170
204
 
171
- export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS, type MedusaCalculatedPrice, type MedusaProductDocument, type MedusaVariantDocument, createMedusaVariantFeedReplication, medusaAdminUserAuth, medusaAdminUserConnector, medusaCapabilities, medusaConnector, medusaProductReplication, medusaProductSchema, medusaProductSync, medusaProductTraits, medusaSecretKeyAuth, medusaSignIn, medusaStockReconcile, medusaStoreSettings, withCalculatedPrices };
205
+ export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS, type MedusaCalculatedPrice, type MedusaProductDocument, type MedusaVariantDocument, createMedusaAdminUserConnector, createMedusaConnector, createMedusaCustomer, createMedusaVariantFeedReplication, getMedusaCustomer, medusaAdminUserAuth, medusaAdminUserConnector, medusaCapabilities, medusaConnector, medusaCreateCustomer, medusaGetCustomer, medusaProductReplication, medusaProductSchema, medusaProductSync, medusaProductTraits, medusaSearchCustomers, medusaSecretKeyAuth, medusaSignIn, medusaStockReconcile, medusaStoreSettings, searchMedusaCustomers, toCustomer, withCalculatedPrices };
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { combinePullAdapters, createReconcileFeed, SignInError as SignInError2 } from "@tallyui/core";
3
3
 
4
4
  // src/capabilities.ts
5
- import { SignInError } from "@tallyui/core";
5
+ import { parseInfoCapabilities, SignInError } from "@tallyui/core";
6
6
  var CAPABILITIES_PATH = "/tally/v1/info";
7
7
  async function readCapabilities(baseUrl, headers, init = {}) {
8
8
  const doFetch = init.fetch ?? fetch;
@@ -21,9 +21,72 @@ async function readCapabilities(baseUrl, headers, init = {}) {
21
21
  } catch {
22
22
  return { orderCreate: 1 };
23
23
  }
24
- const contracts = body?.contracts?.["order.create"];
25
- const valid = Array.isArray(contracts) ? contracts.filter((v) => typeof v === "number" && Number.isSafeInteger(v) && v > 0) : [];
26
- return { orderCreate: valid.length > 0 ? Math.max(...valid) : 1 };
24
+ return parseInfoCapabilities(body, (reason) => console.warn(`@tallyui/connector-medusa: ${reason}`));
25
+ }
26
+
27
+ // src/customers.ts
28
+ import { ConnectorUnauthorizedError, CustomerServiceError } from "@tallyui/core";
29
+ function toCustomer(raw) {
30
+ const customer = { id: raw.id, name: raw.id };
31
+ for (const [key, value] of [
32
+ ["firstName", raw.first_name],
33
+ ["lastName", raw.last_name],
34
+ ["email", raw.email],
35
+ ["phone", raw.phone],
36
+ ["company", raw.company_name]
37
+ ]) {
38
+ if (typeof value === "string" && value.length > 0) customer[key] = value;
39
+ }
40
+ customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(" ") || customer.company || customer.email || customer.id;
41
+ return customer;
42
+ }
43
+ function errorMessage(error) {
44
+ if (typeof error === "object" && error !== null && "message" in error && typeof error.message === "string") {
45
+ return error.message;
46
+ }
47
+ return String(error);
48
+ }
49
+ async function customerRequest(url, key, init) {
50
+ const { fetch: doFetch = fetch, ...requestInit } = init;
51
+ let res;
52
+ try {
53
+ res = await doFetch(url, requestInit);
54
+ } catch (error) {
55
+ throw new CustomerServiceError("network", errorMessage(error));
56
+ }
57
+ if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorizedError(`Medusa rejected the credentials (HTTP ${res.status})`, res.status);
58
+ if (res.status === 404 && key === "customer" && init.method === "GET") return null;
59
+ if (!res.ok && res.status !== 400) throw new CustomerServiceError("server", `HTTP ${res.status}`);
60
+ let body;
61
+ try {
62
+ body = await res.json();
63
+ } catch {
64
+ throw new CustomerServiceError(res.status === 400 ? "invalid" : "server", res.status === 400 ? "HTTP 400" : "unexpected response");
65
+ }
66
+ if (res.status === 400) throw new CustomerServiceError("invalid", body?.message ?? "HTTP 400");
67
+ if (key === "customers" ? !Array.isArray(body?.[key]) : !body?.[key]) throw new CustomerServiceError("server", "unexpected response");
68
+ return body[key];
69
+ }
70
+ async function searchMedusaCustomers(baseUrl, headers, query, init = {}) {
71
+ if (!query.trim()) return [];
72
+ const limit = Math.max(1, Math.min(50, init.limit ?? 20));
73
+ const customers = await customerRequest(`${baseUrl}/admin/customers?q=${encodeURIComponent(query.trim())}&limit=${limit}`, "customers", { method: "GET", headers, signal: init.signal, fetch: init.fetch });
74
+ return customers.filter((raw) => raw.deleted_at == null).map(toCustomer);
75
+ }
76
+ async function createMedusaCustomer(baseUrl, headers, input, init = {}) {
77
+ const body = {
78
+ email: input.email,
79
+ ...input.firstName ? { first_name: input.firstName } : {},
80
+ ...input.lastName ? { last_name: input.lastName } : {},
81
+ ...input.phone ? { phone: input.phone } : {},
82
+ ...input.company ? { company_name: input.company } : {}
83
+ };
84
+ const customer = await customerRequest(`${baseUrl}/admin/customers`, "customer", { ...init, method: "POST", headers: { ...headers, "Content-Type": "application/json" }, body: JSON.stringify(body) });
85
+ return toCustomer(customer);
86
+ }
87
+ async function getMedusaCustomer(baseUrl, headers, id, init = {}) {
88
+ const customer = await customerRequest(`${baseUrl}/admin/customers/${encodeURIComponent(id)}`, "customer", { ...init, method: "GET", headers });
89
+ return customer === null || customer.deleted_at != null ? null : toCustomer(customer);
27
90
  }
28
91
 
29
92
  // src/schemas/products.ts
@@ -454,7 +517,7 @@ var medusaProductSync = {
454
517
  };
455
518
 
456
519
  // src/replication/products.ts
457
- import { compareIds } from "@tallyui/core";
520
+ import { compareIds, ConnectorUnauthorizedError as ConnectorUnauthorizedError2 } from "@tallyui/core";
458
521
 
459
522
  // src/pricing/calculated.ts
460
523
  var STORE_PAGE_SIZE = 100;
@@ -511,6 +574,7 @@ var MEDUSA_PRODUCT_FIELDS = [
511
574
  "*options",
512
575
  "*options.values"
513
576
  ].join(",");
577
+ var MEDUSA_PULL_BATCH_SIZE = 500;
514
578
  var medusaProductReplication = {
515
579
  pull: {
516
580
  async handler(lastCheckpoint, batchSize, context) {
@@ -523,6 +587,7 @@ var medusaProductReplication = {
523
587
  );
524
588
  if (!markResponse.ok) {
525
589
  const error = await markResponse.json().catch(() => ({}));
590
+ if (markResponse.status === 401 || markResponse.status === 403) throw new ConnectorUnauthorizedError2(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ""}`, markResponse.status);
526
591
  throw new Error(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ""}`);
527
592
  }
528
593
  const markData = await markResponse.json();
@@ -555,6 +620,7 @@ var medusaProductReplication = {
555
620
  );
556
621
  if (!response.ok) {
557
622
  const error = await response.json().catch(() => ({}));
623
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError2(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
558
624
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
559
625
  }
560
626
  const data = await response.json();
@@ -579,7 +645,11 @@ var medusaProductReplication = {
579
645
  }
580
646
  };
581
647
 
648
+ // src/replication/variant-feed.ts
649
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError4 } from "@tallyui/core";
650
+
582
651
  // src/reconcile/ids.ts
652
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError3 } from "@tallyui/core";
583
653
  var PAGE_SIZE = 1e3;
584
654
  var MAX_IDS_PER_REQUEST = 100;
585
655
  async function get(path, context) {
@@ -589,6 +659,7 @@ async function get(path, context) {
589
659
  });
590
660
  if (!response.ok) {
591
661
  const error = await response.json().catch(() => ({}));
662
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError3(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
592
663
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
593
664
  }
594
665
  return response.json();
@@ -628,6 +699,7 @@ async function get2(path, context) {
628
699
  });
629
700
  if (!response.ok) {
630
701
  const error = await response.json().catch(() => ({}));
702
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError4(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
631
703
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
632
704
  }
633
705
  return response.json();
@@ -688,6 +760,7 @@ var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
688
760
  });
689
761
 
690
762
  // src/reconcile/stock.ts
763
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError5 } from "@tallyui/core";
691
764
  var PAGE_SIZE2 = 1e3;
692
765
  var FIELDS = "id,location_levels.stocked_quantity,location_levels.reserved_quantity,location_levels.location_id";
693
766
  var pairsKey = (levels = []) => levels.map((l) => JSON.stringify([l.stocked_quantity, l.reserved_quantity])).sort().join();
@@ -701,6 +774,7 @@ var medusaStockReconcile = {
701
774
  });
702
775
  if (!response.ok) {
703
776
  const error = await response.json().catch(() => ({}));
777
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError5(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
704
778
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
705
779
  }
706
780
  const data = await response.json();
@@ -727,6 +801,7 @@ var medusaStockReconcile = {
727
801
  };
728
802
 
729
803
  // src/reconcile/prices.ts
804
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError6 } from "@tallyui/core";
730
805
  var PAGE_SIZE3 = 1e3;
731
806
  var MEDUSA_PRICE_RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1e3;
732
807
  async function get3(path, context) {
@@ -736,6 +811,7 @@ async function get3(path, context) {
736
811
  });
737
812
  if (!response.ok) {
738
813
  const error = await response.json().catch(() => ({}));
814
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError6(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`, response.status);
739
815
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
740
816
  }
741
817
  return response.json();
@@ -804,7 +880,7 @@ function fingerprint2(doc) {
804
880
  }
805
881
 
806
882
  // src/store-settings.ts
807
- import { StoreSettingsError } from "@tallyui/core";
883
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError7, StoreSettingsError } from "@tallyui/core";
808
884
  async function get4(context, path) {
809
885
  const response = await fetch(`${context.baseUrl}${path}`, {
810
886
  headers: { ...context.headers, "Content-Type": "application/json" },
@@ -812,6 +888,7 @@ async function get4(context, path) {
812
888
  });
813
889
  if (!response.ok) {
814
890
  const body = await response.json().catch(() => ({}));
891
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError7(`Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ""}`, response.status);
815
892
  throw new StoreSettingsError("failed", `Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ""}`);
816
893
  }
817
894
  return response.json();
@@ -874,7 +951,7 @@ var medusaStoreSettings = async (context, choice) => {
874
951
  };
875
952
 
876
953
  // src/index.ts
877
- var idFeed = createReconcileFeed({ fetchByIds });
954
+ import { ConnectorUnauthorizedError as ConnectorUnauthorizedError8 } from "@tallyui/core";
878
955
  var medusaSecretKeyAuth = {
879
956
  type: "Medusa Admin API",
880
957
  fields: [
@@ -928,6 +1005,9 @@ var medusaSignIn = async (baseUrl, { email, password }, init = {}) => {
928
1005
  return { token: body.token, expiresAt: jwtExpiresAt(body.token), capabilities };
929
1006
  };
930
1007
  var medusaCapabilities = (context) => readCapabilities(context.baseUrl, context.headers, { signal: context.signal });
1008
+ var medusaSearchCustomers = (context, query, options) => searchMedusaCustomers(context.baseUrl, context.headers, query, { ...options, signal: context.signal });
1009
+ var medusaCreateCustomer = (context, input) => createMedusaCustomer(context.baseUrl, context.headers, input, { signal: context.signal });
1010
+ var medusaGetCustomer = (context, id) => getMedusaCustomer(context.baseUrl, context.headers, id, { signal: context.signal });
931
1011
  var medusaAdminUserAuth = {
932
1012
  type: "Medusa admin user (Bearer JWT)",
933
1013
  fields: [
@@ -938,7 +1018,31 @@ var medusaAdminUserAuth = {
938
1018
  getHeaders: (credentials) => typeof credentials.token === "string" && credentials.token.length > 0 ? { Authorization: `Bearer ${credentials.token}` } : {},
939
1019
  signIn: medusaSignIn
940
1020
  };
941
- var medusaConnector = {
1021
+ function createMedusaConnector() {
1022
+ const idFeed = createReconcileFeed({ fetchByIds });
1023
+ const refetchBatchSize = MAX_IDS_PER_REQUEST;
1024
+ return {
1025
+ ...medusaConnectorParts,
1026
+ replication: {
1027
+ // One replication per collection: the product, variant and id-reconcile
1028
+ // feeds share it (ADR-060). The variant feed catches price-only edits,
1029
+ // which bump only the variant. reconcile is last so its fetch wins duplicates.
1030
+ products: combinePullAdapters({
1031
+ products: medusaProductReplication,
1032
+ variants: createMedusaVariantFeedReplication(),
1033
+ reconcile: idFeed.adapter
1034
+ }, { legacyKey: "products", batchSize: MEDUSA_PULL_BATCH_SIZE })
1035
+ },
1036
+ reconcile: {
1037
+ stock: medusaStockReconcile,
1038
+ ids: { fetchPages, variantIds, enqueue: idFeed.enqueue, refetchBatchSize },
1039
+ prices: { fetchPages: fetchPages2, fingerprint, enqueue: idFeed.enqueue, refetchBatchSize },
1040
+ // Re-fetched through the enriched fetchByIds, so the corrected document carries the new calculated prices (D2b).
1041
+ calculatedPrices: { fetchPages: fetchPages3, fingerprint: fingerprint2, enqueue: idFeed.enqueue, refetchBatchSize }
1042
+ }
1043
+ };
1044
+ }
1045
+ var medusaConnectorParts = {
942
1046
  id: "medusa",
943
1047
  name: "MedusaJS",
944
1048
  description: "Connect to MedusaJS v2 backends via the Admin API",
@@ -954,41 +1058,43 @@ var medusaConnector = {
954
1058
  sync: {
955
1059
  products: medusaProductSync
956
1060
  },
957
- replication: {
958
- // One replication per collection: the product, variant and id-reconcile
959
- // feeds share it (ADR-060). The variant feed catches price-only edits,
960
- // which bump only the variant. reconcile is last so its fetch wins duplicates.
961
- products: combinePullAdapters({
962
- products: medusaProductReplication,
963
- variants: createMedusaVariantFeedReplication(),
964
- reconcile: idFeed.adapter
965
- }, { legacyKey: "products" })
966
- },
967
- reconcile: {
968
- stock: medusaStockReconcile,
969
- ids: { fetchPages, variantIds, enqueue: idFeed.enqueue },
970
- prices: { fetchPages: fetchPages2, fingerprint, enqueue: idFeed.enqueue },
971
- // Re-fetched through the enriched fetchByIds, so the corrected document carries the new calculated prices (D2b).
972
- calculatedPrices: { fetchPages: fetchPages3, fingerprint: fingerprint2, enqueue: idFeed.enqueue }
973
- },
974
1061
  storeSettings: medusaStoreSettings
975
1062
  // No capabilities read here: the plugin's routes authenticate users only, so this connector can't send orders through the plugin either.
976
1063
  };
977
- var medusaAdminUserConnector = { ...medusaConnector, auth: medusaAdminUserAuth, capabilities: medusaCapabilities };
1064
+ var createMedusaAdminUserConnector = () => ({
1065
+ ...createMedusaConnector(),
1066
+ auth: medusaAdminUserAuth,
1067
+ capabilities: medusaCapabilities,
1068
+ searchCustomers: medusaSearchCustomers,
1069
+ createCustomer: medusaCreateCustomer,
1070
+ getCustomer: medusaGetCustomer
1071
+ });
1072
+ var medusaConnector = createMedusaConnector();
1073
+ var medusaAdminUserConnector = createMedusaAdminUserConnector();
978
1074
  export {
1075
+ ConnectorUnauthorizedError8 as ConnectorUnauthorizedError,
979
1076
  MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS,
1077
+ createMedusaAdminUserConnector,
1078
+ createMedusaConnector,
1079
+ createMedusaCustomer,
980
1080
  createMedusaVariantFeedReplication,
1081
+ getMedusaCustomer,
981
1082
  medusaAdminUserAuth,
982
1083
  medusaAdminUserConnector,
983
1084
  medusaCapabilities,
984
1085
  medusaConnector,
1086
+ medusaCreateCustomer,
1087
+ medusaGetCustomer,
985
1088
  medusaProductReplication,
986
1089
  medusaProductSchema,
987
1090
  medusaProductSync,
988
1091
  medusaProductTraits,
1092
+ medusaSearchCustomers,
989
1093
  medusaSecretKeyAuth,
990
1094
  medusaSignIn,
991
1095
  medusaStockReconcile,
992
1096
  medusaStoreSettings,
1097
+ searchMedusaCustomers,
1098
+ toCustomer,
993
1099
  withCalculatedPrices
994
1100
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tallyui/connector-medusa",
3
- "version": "2.0.0",
3
+ "version": "3.0.0-next.0",
4
4
  "type": "module",
5
5
  "description": "MedusaJS v2 connector for Tally UI",
6
6
  "main": "./dist/index.js",
@@ -27,11 +27,11 @@
27
27
  "directory": "connectors/medusa"
28
28
  },
29
29
  "peerDependencies": {
30
- "@tallyui/core": "2.0.0"
30
+ "@tallyui/core": "^3.0.0-next.0"
31
31
  },
32
32
  "devDependencies": {
33
- "@tallyui/database": "2.0.0",
34
- "rxdb": "16.21.1"
33
+ "@tallyui/database": "3.0.0-next.0",
34
+ "rxdb": "17.5.0"
35
35
  },
36
36
  "scripts": {
37
37
  "build": "tsup",
@@ -1,12 +1,11 @@
1
- import { SignInError, type ServerCapabilities } from '@tallyui/core';
1
+ import { parseInfoCapabilities, SignInError, type ServerCapabilities } from '@tallyui/core';
2
2
 
3
3
  /** Path of Medusa's own contract-capability endpoint (ADR-062), relative to the backend's base URL. */
4
4
  export const CAPABILITIES_PATH = '/tally/v1/info';
5
5
 
6
6
  /**
7
- * Reads the store's `order.create` contract capability (ADR-062), with the
8
- * connector's usual injectable `fetch`. A 2xx with a valid list gives its
9
- * max; a 2xx with the field missing/malformed, a non-JSON body, or a 404
7
+ * Reads the store's contract capabilities (ADR-062) and `taxRounding` (#287), with the
8
+ * connector's usual injectable `fetch`. A 2xx gives `parseInfoCapabilities`; a 2xx with the field missing/malformed, a non-JSON body, or a 404
10
9
  * both mean an old plugin and give `{ orderCreate: 1 }`. A network failure,
11
10
  * a 5xx or any other non-2xx that isn't 404/401 is unknown and gives
12
11
  * `undefined`, never 1. A 401 means rejected/expired credentials and throws.
@@ -32,9 +31,5 @@ export async function readCapabilities(
32
31
  } catch {
33
32
  return { orderCreate: 1 };
34
33
  }
35
- const contracts = (body as { contracts?: Record<string, unknown> } | null)?.contracts?.['order.create'];
36
- const valid = Array.isArray(contracts)
37
- ? contracts.filter((v): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v > 0)
38
- : [];
39
- return { orderCreate: valid.length > 0 ? Math.max(...valid) : 1 };
34
+ return parseInfoCapabilities(body, (reason) => console.warn(`@tallyui/connector-medusa: ${reason}`));
40
35
  }
@@ -0,0 +1,69 @@
1
+ import { ConnectorUnauthorizedError, CustomerServiceError, type Customer, type CustomerInput } from '@tallyui/core';
2
+
3
+ type MedusaCustomer = { id: string; deleted_at?: string | null } & Record<string, unknown>;
4
+ type CustomerInit = { signal?: AbortSignal; fetch?: typeof fetch };
5
+
6
+ export function toCustomer(raw: MedusaCustomer): Customer {
7
+ const customer: Customer = { id: raw.id, name: raw.id };
8
+ for (const [key, value] of [
9
+ ['firstName', raw.first_name], ['lastName', raw.last_name], ['email', raw.email],
10
+ ['phone', raw.phone], ['company', raw.company_name],
11
+ ] as const) {
12
+ if (typeof value === 'string' && value.length > 0) customer[key] = value;
13
+ }
14
+ customer.name = [customer.firstName, customer.lastName].filter(Boolean).join(' ') || customer.company || customer.email || customer.id;
15
+ return customer;
16
+ }
17
+
18
+ function errorMessage(error: unknown): string {
19
+ if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {
20
+ return error.message;
21
+ }
22
+ return String(error);
23
+ }
24
+
25
+ async function customerRequest(url: string, key: 'customers' | 'customer', init: RequestInit & CustomerInit) {
26
+ const { fetch: doFetch = fetch, ...requestInit } = init;
27
+ let res: Response;
28
+ try {
29
+ res = await doFetch(url, requestInit);
30
+ } catch (error) {
31
+ throw new CustomerServiceError('network', errorMessage(error));
32
+ }
33
+ if (res.status === 401 || res.status === 403) throw new ConnectorUnauthorizedError(`Medusa rejected the credentials (HTTP ${res.status})`, res.status);
34
+ if (res.status === 404 && key === 'customer' && init.method === 'GET') return null;
35
+ if (!res.ok && res.status !== 400) throw new CustomerServiceError('server', `HTTP ${res.status}`);
36
+ let body;
37
+ try {
38
+ body = await res.json();
39
+ } catch {
40
+ throw new CustomerServiceError(res.status === 400 ? 'invalid' : 'server', res.status === 400 ? 'HTTP 400' : 'unexpected response');
41
+ }
42
+ if (res.status === 400) throw new CustomerServiceError('invalid', body?.message ?? 'HTTP 400');
43
+ if (key === 'customers' ? !Array.isArray(body?.[key]) : !body?.[key]) throw new CustomerServiceError('server', 'unexpected response');
44
+ return body[key];
45
+ }
46
+
47
+ export async function searchMedusaCustomers(baseUrl: string, headers: Record<string, string>, query: string, init: CustomerInit & { limit?: number } = {}): Promise<Customer[]> {
48
+ if (!query.trim()) return [];
49
+ const limit = Math.max(1, Math.min(50, init.limit ?? 20));
50
+ const customers: MedusaCustomer[] = await customerRequest(`${baseUrl}/admin/customers?q=${encodeURIComponent(query.trim())}&limit=${limit}`, 'customers', { method: 'GET', headers, signal: init.signal, fetch: init.fetch });
51
+ return customers.filter((raw) => raw.deleted_at == null).map(toCustomer);
52
+ }
53
+
54
+ export async function createMedusaCustomer(baseUrl: string, headers: Record<string, string>, input: CustomerInput, init: CustomerInit = {}): Promise<Customer> {
55
+ const body = {
56
+ email: input.email,
57
+ ...(input.firstName ? { first_name: input.firstName } : {}),
58
+ ...(input.lastName ? { last_name: input.lastName } : {}),
59
+ ...(input.phone ? { phone: input.phone } : {}),
60
+ ...(input.company ? { company_name: input.company } : {}),
61
+ };
62
+ const customer = await customerRequest(`${baseUrl}/admin/customers`, 'customer', { ...init, method: 'POST', headers: { ...headers, 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
63
+ return toCustomer(customer);
64
+ }
65
+
66
+ export async function getMedusaCustomer(baseUrl: string, headers: Record<string, string>, id: string, init: CustomerInit = {}): Promise<Customer | null> {
67
+ const customer: MedusaCustomer | null = await customerRequest(`${baseUrl}/admin/customers/${encodeURIComponent(id)}`, 'customer', { ...init, method: 'GET', headers });
68
+ return customer === null || customer.deleted_at != null ? null : toCustomer(customer);
69
+ }
package/src/index.ts CHANGED
@@ -1,20 +1,18 @@
1
- import { combinePullAdapters, createReconcileFeed, SignInError, type ConnectorAuth, type ServerCapabilities, type SyncContext, type TallyConnector } from '@tallyui/core';
1
+ import { combinePullAdapters, createReconcileFeed, SignInError, type ConnectorAuth, type CustomerInput, type ServerCapabilities, type SyncContext, type TallyConnector } from '@tallyui/core';
2
2
 
3
3
  import { readCapabilities } from './capabilities';
4
+ import { searchMedusaCustomers, createMedusaCustomer, getMedusaCustomer } from './customers';
4
5
  import { medusaProductSchema } from './schemas/products';
5
6
  import { medusaProductTraits } from './traits/product';
6
7
  import { medusaProductSync } from './sync/products';
7
- import { medusaProductReplication } from './replication/products';
8
+ import { MEDUSA_PULL_BATCH_SIZE, medusaProductReplication } from './replication/products';
8
9
  import { createMedusaVariantFeedReplication } from './replication/variant-feed';
9
10
  import { medusaStockReconcile } from './reconcile/stock';
10
- import { fetchByIds, fetchPages, variantIds } from './reconcile/ids';
11
+ import { fetchByIds, fetchPages, MAX_IDS_PER_REQUEST, variantIds } from './reconcile/ids';
11
12
  import { fetchPages as fetchPricePages, fingerprint as priceFingerprint } from './reconcile/prices';
12
13
  import { fetchPages as fetchCalculatedPricePages, fingerprint as calculatedPriceFingerprint } from './reconcile/calculated-prices';
13
14
  import { medusaStoreSettings } from './store-settings';
14
15
 
15
- // The id reconcile's corrections reach `products` only through this pull adapter (ADR-060).
16
- const idFeed = createReconcileFeed({ fetchByIds });
17
-
18
16
  export const medusaSecretKeyAuth: ConnectorAuth = {
19
17
  type: 'Medusa Admin API',
20
18
  fields: [
@@ -72,6 +70,12 @@ export const medusaSignIn: NonNullable<ConnectorAuth['signIn']> = async (baseUrl
72
70
  /** Re-reads the store's `order.create` capability (ADR-062) for a restored session, with the connector's own headers. */
73
71
  export const medusaCapabilities = (context: SyncContext): Promise<ServerCapabilities | undefined> =>
74
72
  readCapabilities(context.baseUrl, context.headers, { signal: context.signal });
73
+ export const medusaSearchCustomers = (context: SyncContext, query: string, options?: { limit?: number }) =>
74
+ searchMedusaCustomers(context.baseUrl, context.headers, query, { ...options, signal: context.signal });
75
+ export const medusaCreateCustomer = (context: SyncContext, input: CustomerInput) =>
76
+ createMedusaCustomer(context.baseUrl, context.headers, input, { signal: context.signal });
77
+ export const medusaGetCustomer = (context: SyncContext, id: string) =>
78
+ getMedusaCustomer(context.baseUrl, context.headers, id, { signal: context.signal });
75
79
 
76
80
  // The JWT from Medusa's emailpass sign-in (POST /auth/user/emailpass) is stored as token.
77
81
  // email and password are only sign-in form fields and are never sent as headers.
@@ -88,21 +92,51 @@ export const medusaAdminUserAuth: ConnectorAuth = {
88
92
  };
89
93
 
90
94
  /**
91
- * MedusaJS v2 connector for Tally UI.
95
+ * MedusaJS v2 connector for Tally UI, with a secret API key. Build one per store session, anew on each
96
+ * sign-in or store change: it owns the reconcile feed, whose queued work must never reach another store's database (#307).
92
97
  *
93
98
  * Connects to Medusa backends via the Admin API.
94
99
  * Products are stored in RxDB using a schema that mirrors the Medusa API shape.
95
100
  *
96
101
  * ```ts
97
- * import { medusaConnector } from '@tallyui/connector-medusa';
102
+ * import { createMedusaConnector } from '@tallyui/connector-medusa';
98
103
  * import { ConnectorProvider } from '@tallyui/core';
99
104
  *
100
- * <ConnectorProvider connector={medusaConnector}>
105
+ * const connector = useMemo(() => createMedusaConnector(), [backendUrl]);
106
+ * <ConnectorProvider connector={connector}>
101
107
  * <App />
102
108
  * </ConnectorProvider>
103
109
  * ```
104
110
  */
105
- export const medusaConnector: TallyConnector = {
111
+ export function createMedusaConnector(): TallyConnector {
112
+ // The id reconcile's corrections reach `products` only through this pull adapter (ADR-060).
113
+ const idFeed = createReconcileFeed({ fetchByIds });
114
+ // fetchByIds asks for at most this many ids per request; the runner budgets a page's refetch by requests.
115
+ const refetchBatchSize = MAX_IDS_PER_REQUEST;
116
+ return {
117
+ ...medusaConnectorParts,
118
+ replication: {
119
+ // One replication per collection: the product, variant and id-reconcile
120
+ // feeds share it (ADR-060). The variant feed catches price-only edits,
121
+ // which bump only the variant. reconcile is last so its fetch wins duplicates.
122
+ products: combinePullAdapters({
123
+ products: medusaProductReplication,
124
+ variants: createMedusaVariantFeedReplication(),
125
+ reconcile: idFeed.adapter,
126
+ }, { legacyKey: 'products', batchSize: MEDUSA_PULL_BATCH_SIZE }),
127
+ },
128
+ reconcile: {
129
+ stock: medusaStockReconcile,
130
+ ids: { fetchPages, variantIds, enqueue: idFeed.enqueue, refetchBatchSize },
131
+ prices: { fetchPages: fetchPricePages, fingerprint: priceFingerprint, enqueue: idFeed.enqueue, refetchBatchSize },
132
+ // Re-fetched through the enriched fetchByIds, so the corrected document carries the new calculated prices (D2b).
133
+ calculatedPrices: { fetchPages: fetchCalculatedPricePages, fingerprint: calculatedPriceFingerprint, enqueue: idFeed.enqueue, refetchBatchSize },
134
+ },
135
+ };
136
+ }
137
+
138
+ // Everything but the reconcile feed and what is wired to it: stateless, so every instance shares it.
139
+ const medusaConnectorParts = {
106
140
  id: 'medusa',
107
141
  name: 'MedusaJS',
108
142
  description: 'Connect to MedusaJS v2 backends via the Admin API',
@@ -122,32 +156,28 @@ export const medusaConnector: TallyConnector = {
122
156
  products: medusaProductSync,
123
157
  },
124
158
 
125
- replication: {
126
- // One replication per collection: the product, variant and id-reconcile
127
- // feeds share it (ADR-060). The variant feed catches price-only edits,
128
- // which bump only the variant. reconcile is last so its fetch wins duplicates.
129
- products: combinePullAdapters({
130
- products: medusaProductReplication,
131
- variants: createMedusaVariantFeedReplication(),
132
- reconcile: idFeed.adapter,
133
- }, { legacyKey: 'products' }),
134
- },
135
-
136
- reconcile: {
137
- stock: medusaStockReconcile,
138
- ids: { fetchPages, variantIds, enqueue: idFeed.enqueue },
139
- prices: { fetchPages: fetchPricePages, fingerprint: priceFingerprint, enqueue: idFeed.enqueue },
140
- // Re-fetched through the enriched fetchByIds, so the corrected document carries the new calculated prices (D2b).
141
- calculatedPrices: { fetchPages: fetchCalculatedPricePages, fingerprint: calculatedPriceFingerprint, enqueue: idFeed.enqueue },
142
- },
143
-
144
159
  storeSettings: medusaStoreSettings,
145
160
 
146
161
  // No capabilities read here: the plugin's routes authenticate users only, so this connector can't send orders through the plugin either.
147
- };
162
+ } satisfies Omit<TallyConnector, 'replication' | 'reconcile'>;
148
163
 
149
- /** Medusa connector using an admin user's Bearer JWT. */
150
- export const medusaAdminUserConnector: TallyConnector = { ...medusaConnector, auth: medusaAdminUserAuth, capabilities: medusaCapabilities };
164
+ /** Medusa connector using an admin user's Bearer JWT; like createMedusaConnector(), one per store session with its own feed. */
165
+ export const createMedusaAdminUserConnector = (): TallyConnector => ({
166
+ ...createMedusaConnector(), auth: medusaAdminUserAuth, capabilities: medusaCapabilities,
167
+ searchCustomers: medusaSearchCustomers, createCustomer: medusaCreateCustomer, getCustomer: medusaGetCustomer,
168
+ });
169
+
170
+ /**
171
+ * @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
172
+ * Use createMedusaConnector() per store session. Removed in 4.0.
173
+ */
174
+ export const medusaConnector: TallyConnector = createMedusaConnector();
175
+
176
+ /**
177
+ * @deprecated One instance for the whole app: a store switch can leak queued reconcile work across stores.
178
+ * Use createMedusaAdminUserConnector() per store session. Removed in 4.0.
179
+ */
180
+ export const medusaAdminUserConnector: TallyConnector = createMedusaAdminUserConnector();
151
181
 
152
182
  // Re-export pieces for advanced usage
153
183
  export { medusaProductSchema } from './schemas/products';
@@ -157,6 +187,9 @@ export { medusaProductReplication } from './replication/products';
157
187
  export { createMedusaVariantFeedReplication } from './replication/variant-feed';
158
188
  export { medusaStockReconcile } from './reconcile/stock';
159
189
  export { medusaStoreSettings } from './store-settings';
190
+ export { searchMedusaCustomers, createMedusaCustomer, getMedusaCustomer, toCustomer } from './customers';
160
191
  export { withCalculatedPrices } from './pricing/calculated';
161
192
  export { MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS } from './reconcile/calculated-prices';
162
193
  export type { MedusaCalculatedPrice, MedusaProductDocument, MedusaVariantDocument } from './schemas/products';
194
+
195
+ export { ConnectorUnauthorizedError } from '@tallyui/core';
@@ -1,3 +1,4 @@
1
+ import { ConnectorUnauthorizedError } from '@tallyui/core';
1
2
  import type { SyncContext } from '@tallyui/core';
2
3
  import { MEDUSA_PRODUCT_FIELDS, toDocument } from '../replication/products';
3
4
  import { withCalculatedPrices } from '../pricing/calculated';
@@ -10,7 +11,7 @@ const PAGE_SIZE = 1000;
10
11
  * At most this many ids per `fetchByIds` request. Medusa ids are about 31
11
12
  * characters; 1,000 of them would pass Node's 16 KB header/URL limit.
12
13
  */
13
- const MAX_IDS_PER_REQUEST = 100;
14
+ export const MAX_IDS_PER_REQUEST = 100;
14
15
 
15
16
  async function get(path: string, context: SyncContext) {
16
17
  const response = await fetch(`${context.baseUrl}${path}`, {
@@ -19,6 +20,7 @@ async function get(path: string, context: SyncContext) {
19
20
  });
20
21
  if (!response.ok) {
21
22
  const error = await response.json().catch(() => ({}));
23
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
22
24
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
23
25
  }
24
26
  return response.json();
@@ -1,3 +1,4 @@
1
+ import { ConnectorUnauthorizedError } from '@tallyui/core';
1
2
  import type { SyncContext } from '@tallyui/core';
2
3
 
3
4
  /** Admin API list limit; also the price-listing page size (ADR-060). */
@@ -16,6 +17,7 @@ async function get(path: string, context: SyncContext) {
16
17
  });
17
18
  if (!response.ok) {
18
19
  const error = await response.json().catch(() => ({}));
20
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
19
21
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
20
22
  }
21
23
  return response.json();
@@ -1,3 +1,4 @@
1
+ import { ConnectorUnauthorizedError } from '@tallyui/core';
1
2
  import type { StockReconcileAdapter } from '@tallyui/core';
2
3
 
3
4
  type Level = { stocked_quantity: number; reserved_quantity: number };
@@ -29,6 +30,7 @@ export const medusaStockReconcile: StockReconcileAdapter = {
29
30
  });
30
31
  if (!response.ok) {
31
32
  const error = await response.json().catch(() => ({}));
33
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
32
34
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
33
35
  }
34
36
  const data = await response.json() as { inventory_items: Array<{ id: string; location_levels?: Level[] }>; count: number };
@@ -1,4 +1,4 @@
1
- import { compareIds } from '@tallyui/core';
1
+ import { compareIds, ConnectorUnauthorizedError } from '@tallyui/core';
2
2
  import type { ReplicationAdapter } from '@tallyui/core';
3
3
 
4
4
  import { medusaProductSchema, type MedusaProductDocument } from '../schemas/products';
@@ -46,6 +46,11 @@ export const MEDUSA_PRODUCT_FIELDS = [
46
46
  '*options.values',
47
47
  ].join(',');
48
48
 
49
+ // A first sync of about 2,000 products took 21 sequential pages at RxDB's default 100
50
+ // (perf spike, 2026-09-28). 500 is within the 1,000 Admin API list limit;
51
+ // tune it against a real store.
52
+ export const MEDUSA_PULL_BATCH_SIZE = 500;
53
+
49
54
  /**
50
55
  * Replication adapter for Medusa v2 products.
51
56
  *
@@ -65,6 +70,7 @@ export const medusaProductReplication: ReplicationAdapter<any, MedusaProductChec
65
70
  );
66
71
  if (!markResponse.ok) {
67
72
  const error = await markResponse.json().catch(() => ({}));
73
+ if (markResponse.status === 401 || markResponse.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ''}`, markResponse.status);
68
74
  throw new Error(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ''}`);
69
75
  }
70
76
  const markData = await markResponse.json();
@@ -101,6 +107,7 @@ export const medusaProductReplication: ReplicationAdapter<any, MedusaProductChec
101
107
 
102
108
  if (!response.ok) {
103
109
  const error = await response.json().catch(() => ({}));
110
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
104
111
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
105
112
  }
106
113
 
@@ -1,3 +1,4 @@
1
+ import { ConnectorUnauthorizedError } from '@tallyui/core';
1
2
  import type { ReplicationAdapter, SyncContext } from '@tallyui/core';
2
3
  import { fetchByIds } from '../reconcile/ids';
3
4
  import { MEDUSA_PRODUCT_FIELDS, toDocument, type MedusaProductCheckpoint } from './products';
@@ -16,6 +17,7 @@ async function get(path: string, context: SyncContext) {
16
17
  });
17
18
  if (!response.ok) {
18
19
  const error = await response.json().catch(() => ({}));
20
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`, response.status);
19
21
  throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ''}`);
20
22
  }
21
23
  return response.json();
@@ -1,4 +1,4 @@
1
- import { StoreSettingsError } from '@tallyui/core';
1
+ import { ConnectorUnauthorizedError, StoreSettingsError } from '@tallyui/core';
2
2
  import type { StoreSettings, StoreSettingsChoice, SyncContext } from '@tallyui/core';
3
3
 
4
4
  type Store = { id: string; default_region_id: string | null };
@@ -10,7 +10,7 @@ type ApiKey = { id: string; title: string; token: string; revoked_at: string | n
10
10
  type TaxRate = { rate: number | null; is_default: boolean; rules?: unknown[] };
11
11
  type TaxRegion = { country_code: string; province_code: string | null; tax_rates?: TaxRate[] };
12
12
 
13
- /** A non-OK response becomes `StoreSettingsError('failed')`, carrying the HTTP status and Medusa's own `message`. */
13
+ /** Except for 401/403 (`ConnectorUnauthorizedError`), a non-OK response becomes `StoreSettingsError('failed')`, carrying the HTTP status and Medusa's own `message`. */
14
14
  async function get(context: SyncContext, path: string): Promise<any> {
15
15
  const response = await fetch(`${context.baseUrl}${path}`, {
16
16
  headers: { ...context.headers, 'Content-Type': 'application/json' },
@@ -18,6 +18,7 @@ async function get(context: SyncContext, path: string): Promise<any> {
18
18
  });
19
19
  if (!response.ok) {
20
20
  const body = await response.json().catch(() => ({}));
21
+ if (response.status === 401 || response.status === 403) throw new ConnectorUnauthorizedError(`Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ''}`, response.status);
21
22
  throw new StoreSettingsError('failed', `Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ''}`);
22
23
  }
23
24
  return response.json();