@tallyui/connector-medusa 1.0.0 → 2.0.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
@@ -1,7 +1,36 @@
1
+ // src/index.ts
2
+ import { combinePullAdapters, createReconcileFeed, SignInError as SignInError2 } from "@tallyui/core";
3
+
4
+ // src/capabilities.ts
5
+ import { SignInError } from "@tallyui/core";
6
+ var CAPABILITIES_PATH = "/tally/v1/info";
7
+ async function readCapabilities(baseUrl, headers, init = {}) {
8
+ const doFetch = init.fetch ?? fetch;
9
+ let res;
10
+ try {
11
+ res = await doFetch(`${baseUrl}${CAPABILITIES_PATH}`, { method: "GET", headers, signal: init.signal });
12
+ } catch {
13
+ return void 0;
14
+ }
15
+ if (res.status === 401) throw new SignInError("invalid_credentials", `Medusa rejected the credentials reading capabilities (HTTP 401)`);
16
+ if (res.status === 404) return { orderCreate: 1 };
17
+ if (!res.ok) return void 0;
18
+ let body;
19
+ try {
20
+ body = await res.json();
21
+ } catch {
22
+ return { orderCreate: 1 };
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 };
27
+ }
28
+
1
29
  // src/schemas/products.ts
2
30
  var medusaProductSchema = {
3
31
  title: "Medusa Product",
4
- version: 0,
32
+ // 1: declares `variants[].calculated_price` (backlog 44). A bump drops and resyncs (ConnectorSchemas).
33
+ version: 1,
5
34
  type: "object",
6
35
  primaryKey: "id",
7
36
  properties: {
@@ -12,8 +41,10 @@ var medusaProductSchema = {
12
41
  title: {
13
42
  type: "string"
14
43
  },
44
+ // Indexed fields must be required strings with a maxLength (RxDB SC34).
15
45
  handle: {
16
- type: "string"
46
+ type: "string",
47
+ maxLength: 255
17
48
  },
18
49
  subtitle: {
19
50
  type: ["string", "null"]
@@ -24,7 +55,8 @@ var medusaProductSchema = {
24
55
  status: {
25
56
  type: "string",
26
57
  enum: ["draft", "proposed", "published", "rejected"],
27
- default: "draft"
58
+ default: "draft",
59
+ maxLength: 20
28
60
  },
29
61
  thumbnail: {
30
62
  type: ["string", "null"]
@@ -154,6 +186,7 @@ var medusaProductSchema = {
154
186
  }
155
187
  }
156
188
  },
189
+ // Admin base prices.
157
190
  prices: {
158
191
  type: "array",
159
192
  items: {
@@ -166,6 +199,27 @@ var medusaProductSchema = {
166
199
  max_quantity: { type: ["number", "null"] }
167
200
  }
168
201
  }
202
+ },
203
+ // The store API's price (D2b), as `MedusaCalculatedPrice`: an object in priced mode,
204
+ // `null` when the sales channel or region does not sell the variant, and absent in
205
+ // base-only mode, with no pricing context. No `additionalProperties: false`: the store
206
+ // API sends more fields (`id`, `original_price`) and can add others.
207
+ calculated_price: {
208
+ type: ["object", "null"],
209
+ properties: {
210
+ calculated_amount: { type: ["number", "null"] },
211
+ original_amount: { type: ["number", "null"] },
212
+ currency_code: { type: "string" },
213
+ is_calculated_price_tax_inclusive: { type: ["boolean", "null"] },
214
+ is_original_price_tax_inclusive: { type: ["boolean", "null"] },
215
+ calculated_price: {
216
+ type: "object",
217
+ properties: {
218
+ price_list_id: { type: ["string", "null"] },
219
+ price_list_type: { type: ["string", "null"] }
220
+ }
221
+ }
222
+ }
169
223
  }
170
224
  }
171
225
  }
@@ -178,25 +232,104 @@ var medusaProductSchema = {
178
232
  }
179
233
  },
180
234
  indexes: ["handle", "status"],
181
- required: ["id"]
235
+ required: ["id", "handle", "status"]
182
236
  };
183
237
 
184
238
  // src/traits/product.ts
239
+ import { minorUnitDigits, moneyToMajor, resolvePrice } from "@tallyui/core";
240
+ function productStock(variants) {
241
+ if (!variants.length) return { status: "unknown" };
242
+ const status = variants.some((stock) => stock.status === "in_stock") ? "in_stock" : variants.some((stock) => stock.status === "backorder") ? "backorder" : variants.every((stock) => stock.status === "out_of_stock") ? "out_of_stock" : "unknown";
243
+ const quantity = variants.every((stock) => stock.quantity != null) ? variants.reduce((sum, stock) => sum + stock.quantity, 0) : void 0;
244
+ return quantity === void 0 ? { status } : { status, quantity };
245
+ }
246
+ function variantQuantity(variant) {
247
+ if (variant?.inventory_quantity != null) return variant.inventory_quantity;
248
+ const items = variant?.inventory_items ?? [];
249
+ const known = items.filter((item) => item?.inventory?.location_levels);
250
+ if (!known.length) return null;
251
+ return Math.min(
252
+ ...known.map((item) => {
253
+ const available = item.inventory.location_levels.reduce(
254
+ (sum, level) => sum + Number(level?.stocked_quantity ?? 0) - Number(level?.reserved_quantity ?? 0),
255
+ 0
256
+ );
257
+ return Math.floor(available / Number(item.required_quantity || 1));
258
+ })
259
+ );
260
+ }
261
+ var toMinor = (amount, currency) => Math.round(Number(amount) * 10 ** minorUnitDigits(currency));
262
+ var taxFlag = (flag) => typeof flag === "boolean" ? { taxInclusive: flag } : {};
263
+ function calculatedPrices(calc) {
264
+ if (!calc?.currency_code || calc.original_amount == null || calc.calculated_amount == null) return [];
265
+ const currency = calc.currency_code.toUpperCase();
266
+ const type = calc.calculated_price?.price_list_type;
267
+ if (type === "override") {
268
+ return [{ amount: toMinor(calc.calculated_amount, currency), currency, kind: "base", ...taxFlag(calc.is_calculated_price_tax_inclusive) }];
269
+ }
270
+ const prices = [{ amount: toMinor(calc.original_amount, currency), currency, kind: "base", ...taxFlag(calc.is_original_price_tax_inclusive) }];
271
+ if (type === "sale" && calc.calculated_amount < calc.original_amount) {
272
+ prices.push({ amount: toMinor(calc.calculated_amount, currency), currency, kind: "sale", ...taxFlag(calc.is_calculated_price_tax_inclusive) });
273
+ }
274
+ return prices;
275
+ }
276
+ function variantPrices(variant) {
277
+ if (!variant) return [];
278
+ if (variant.calculated_price !== void 0) return calculatedPrices(variant.calculated_price);
279
+ const prices = [];
280
+ const seen = /* @__PURE__ */ new Set();
281
+ for (const price of variant.prices ?? []) {
282
+ if (price?.price_list_id || price?.amount == null || !price.currency_code) continue;
283
+ const currency = String(price.currency_code).toUpperCase();
284
+ if (seen.has(currency)) continue;
285
+ seen.add(currency);
286
+ prices.push({ amount: toMinor(price.amount, currency), currency, kind: "base" });
287
+ }
288
+ return prices;
289
+ }
290
+ var isPriced = (doc) => (doc.variants ?? []).some((v) => v.calculated_price !== void 0);
291
+ function pricedMajor(doc, which) {
292
+ const resolved = resolvePrice(variantPrices(doc.variants?.[0]));
293
+ const money = which === "base" ? resolved?.was ?? resolved?.current : resolved?.current;
294
+ return money ? moneyToMajor(money).toFixed(2) : void 0;
295
+ }
296
+ function variantStock(variant) {
297
+ if (!variant) return { status: "unknown" };
298
+ if (variant.manage_inventory === false) return { status: "in_stock" };
299
+ const quantity = variantQuantity(variant);
300
+ if (quantity == null) return { status: "unknown" };
301
+ if (quantity > 0) return { status: "in_stock", quantity };
302
+ return { status: variant.allow_backorder ? "backorder" : "out_of_stock", quantity };
303
+ }
185
304
  var medusaProductTraits = {
186
305
  getId: (doc) => doc.id,
187
306
  getName: (doc) => doc.title ?? "",
188
307
  getSku: (doc) => {
189
308
  return doc.variants?.[0]?.sku || void 0;
190
309
  },
310
+ getPrices: (doc) => variantPrices(doc.variants?.[0]),
311
+ getStock: (doc) => productStock((doc.variants ?? []).map(variantStock)),
312
+ getVariants: (doc) => (doc.variants ?? []).map((v) => ({
313
+ id: v.id,
314
+ title: v.title ?? void 0,
315
+ sku: v.sku || void 0,
316
+ barcode: v.barcode || v.ean || v.upc || void 0,
317
+ prices: variantPrices(v),
318
+ stock: variantStock(v)
319
+ })),
320
+ // getPrice, getRegularPrice and getSalePrice: deprecated; use `getPrices`. In priced mode the
321
+ // first two give what `getPrices` resolves to, never the admin prices.
191
322
  getPrice: (doc) => {
323
+ if (isPriced(doc)) return pricedMajor(doc, "current");
192
324
  const amount = doc.variants?.[0]?.prices?.[0]?.amount;
193
325
  if (amount == null) return void 0;
194
- return (amount / 100).toFixed(2);
326
+ return Number(amount).toFixed(2);
195
327
  },
196
328
  getRegularPrice: (doc) => {
329
+ if (isPriced(doc)) return pricedMajor(doc, "base");
197
330
  const amount = doc.variants?.[0]?.prices?.[0]?.amount;
198
331
  if (amount == null) return void 0;
199
- return (amount / 100).toFixed(2);
332
+ return Number(amount).toFixed(2);
200
333
  },
201
334
  getSalePrice: () => {
202
335
  return void 0;
@@ -221,16 +354,20 @@ var medusaProductTraits = {
221
354
  if (!variant) return "unknown";
222
355
  if (variant.manage_inventory === false) return "instock";
223
356
  if (variant.allow_backorder) return "onbackorder";
224
- const qty = variant.inventory_quantity;
357
+ const qty = variantQuantity(variant);
225
358
  if (qty == null) return "unknown";
226
359
  return qty > 0 ? "instock" : "outofstock";
227
360
  },
228
361
  getStockQuantity: (doc) => {
229
- return doc.variants?.[0]?.inventory_quantity ?? null;
362
+ return variantQuantity(doc.variants?.[0]);
230
363
  },
231
364
  hasVariants: (doc) => {
232
365
  return (doc.variants?.length ?? 0) > 1;
233
366
  },
367
+ // In priced mode, a product with no variant that yields a price (a null calculated price, or null
368
+ // amounts) is not sold in this channel or region.
369
+ isSellable: (doc) => (doc.status === void 0 || doc.status === "published") && (!isPriced(doc) || doc.variants.some((v) => variantPrices(v).length > 0)),
370
+ getVariantCount: (doc) => doc.variants?.length ?? 1,
234
371
  getType: (doc) => {
235
372
  if (doc.is_giftcard) return "giftcard";
236
373
  if ((doc.variants?.length ?? 0) > 1) return "variable";
@@ -298,7 +435,8 @@ var medusaProductSync = {
298
435
  },
299
436
  async fetchModifiedAfter(date, context) {
300
437
  const response = await fetch(
301
- `${context.baseUrl}/admin/products?updated_at[gte]=${date}&limit=100&fields=*variants,*variants.prices,*images,*categories,*tags,*options,*options.values`,
438
+ // Medusa 2.21 honours only the operator form; `updated_at[gte]` is silently dropped.
439
+ `${context.baseUrl}/admin/products?updated_at[$gte]=${date}&limit=100&fields=*variants,*variants.prices,*images,*categories,*tags,*options,*options.values`,
302
440
  {
303
441
  headers: {
304
442
  ...context.headers,
@@ -316,17 +454,94 @@ var medusaProductSync = {
316
454
  };
317
455
 
318
456
  // src/replication/products.ts
319
- var MEDUSA_PRODUCT_FIELDS = "*variants,*variants.prices,*images,*categories,*tags,*options,*options.values";
457
+ import { compareIds } from "@tallyui/core";
458
+
459
+ // src/pricing/calculated.ts
460
+ var STORE_PAGE_SIZE = 100;
461
+ var STORE_PRICE_FIELDS = "id,*variants.calculated_price";
462
+ async function storeGet(path, context) {
463
+ const key = context.pricingContext?.publishable_key ?? "";
464
+ const response = await fetch(`${context.baseUrl}${path}`, {
465
+ headers: { "x-publishable-api-key": key, "Content-Type": "application/json" },
466
+ signal: context.signal
467
+ });
468
+ if (!response.ok) {
469
+ const error = await response.json().catch(() => ({}));
470
+ const message = typeof error?.message === "string" && key ? error.message.split(key).join("[key]") : error?.message;
471
+ throw new Error(`Medusa store API error: ${response.status}${message ? `: ${message}` : ""}`);
472
+ }
473
+ return response.json();
474
+ }
475
+ async function withCalculatedPrices(docs, context) {
476
+ const pricing = context.pricingContext;
477
+ if (!pricing) return docs;
478
+ const byVariant = /* @__PURE__ */ new Map();
479
+ for (let i = 0; i < docs.length; i += STORE_PAGE_SIZE) {
480
+ const params = new URLSearchParams({ region_id: pricing.region_id ?? "", limit: String(STORE_PAGE_SIZE), fields: STORE_PRICE_FIELDS });
481
+ for (const doc of docs.slice(i, i + STORE_PAGE_SIZE)) params.append("id[]", doc.id);
482
+ const data = await storeGet(`/store/products?${params}`, context);
483
+ for (const product of data.products ?? []) {
484
+ for (const variant of product.variants ?? []) byVariant.set(variant.id, variant.calculated_price ?? null);
485
+ }
486
+ }
487
+ return docs.map((doc) => Array.isArray(doc.variants) ? { ...doc, variants: doc.variants.map((v) => ({ ...v, calculated_price: byVariant.get(v.id) ?? null })) } : doc);
488
+ }
489
+
490
+ // src/replication/products.ts
491
+ var SCHEMA_FIELDS = Object.keys(medusaProductSchema.properties);
492
+ function toDocument(product) {
493
+ const doc = {};
494
+ for (const field of SCHEMA_FIELDS) {
495
+ if (product[field] !== void 0) doc[field] = product[field];
496
+ }
497
+ if (Array.isArray(doc.variants)) {
498
+ doc.variants = [...doc.variants].sort((a, b) => compareIds(a.id, b.id));
499
+ }
500
+ return doc;
501
+ }
502
+ var MEDUSA_PRODUCT_FIELDS = [
503
+ "*variants",
504
+ "*variants.prices",
505
+ "+variants.inventory_items.required_quantity",
506
+ "+variants.inventory_items.inventory.location_levels.stocked_quantity",
507
+ "+variants.inventory_items.inventory.location_levels.reserved_quantity",
508
+ "*images",
509
+ "*categories",
510
+ "*tags",
511
+ "*options",
512
+ "*options.values"
513
+ ].join(",");
320
514
  var medusaProductReplication = {
321
515
  pull: {
322
516
  async handler(lastCheckpoint, batchSize, context) {
517
+ const offset = lastCheckpoint?.offset ?? 0;
518
+ let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? "";
519
+ if (offset === 0 && lastCheckpoint?.pass_mark === void 0) {
520
+ const markResponse = await fetch(
521
+ `${context.baseUrl}/admin/products?limit=1&order=-updated_at&fields=id,updated_at`,
522
+ { headers: { ...context.headers, "Content-Type": "application/json" }, signal: context.signal }
523
+ );
524
+ if (!markResponse.ok) {
525
+ const error = await markResponse.json().catch(() => ({}));
526
+ throw new Error(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ""}`);
527
+ }
528
+ const markData = await markResponse.json();
529
+ passMark = markData.products?.[0]?.updated_at ?? passMark;
530
+ if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
531
+ return { documents: [], checkpoint: lastCheckpoint };
532
+ }
533
+ }
323
534
  const params = new URLSearchParams({
324
535
  limit: String(batchSize),
325
536
  offset: String(lastCheckpoint?.offset ?? 0),
326
- fields: MEDUSA_PRODUCT_FIELDS
537
+ fields: MEDUSA_PRODUCT_FIELDS,
538
+ // Offsets need a total order. Many products share an updated_at
539
+ // (bulk writes), and Medusa sorts by one field only, so page by the
540
+ // unique id within the fixed updated_at window.
541
+ order: "id"
327
542
  });
328
543
  if (lastCheckpoint?.updated_at) {
329
- params.set("updated_at[gte]", lastCheckpoint.updated_at);
544
+ params.set("updated_at[$gte]", lastCheckpoint.updated_at);
330
545
  }
331
546
  const response = await fetch(
332
547
  `${context.baseUrl}/admin/products?${params}`,
@@ -339,82 +554,397 @@ var medusaProductReplication = {
339
554
  }
340
555
  );
341
556
  if (!response.ok) {
342
- throw new Error(`Medusa API error: ${response.status}`);
557
+ const error = await response.json().catch(() => ({}));
558
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
343
559
  }
344
560
  const data = await response.json();
345
561
  const products = data.products ?? [];
346
- const documents = products.map((p) => ({ ...p, _deleted: false }));
347
- const nextOffset = products.length < batchSize ? 0 : (lastCheckpoint?.offset ?? 0) + products.length;
348
- const checkpoint = products.length > 0 ? {
349
- offset: nextOffset,
350
- updated_at: products[products.length - 1].updated_at
351
- } : lastCheckpoint ?? { offset: 0, updated_at: "" };
562
+ if (offset > 0 && (products.length === 0 || data.count < (lastCheckpoint?.pass_count ?? data.count))) {
563
+ return medusaProductReplication.pull.handler({
564
+ offset: 0,
565
+ updated_at: lastCheckpoint?.updated_at ?? "",
566
+ pass_mark: passMark
567
+ }, batchSize, context);
568
+ }
569
+ const priced = await withCalculatedPrices(products.map(toDocument), context);
570
+ const documents = priced.map((doc) => ({ ...doc, _deleted: false }));
571
+ const checkpoint = offset + products.length >= data.count ? { offset: 0, updated_at: passMark, pass_mark: void 0, pass_count: void 0 } : {
572
+ offset: offset + products.length,
573
+ updated_at: lastCheckpoint?.updated_at ?? "",
574
+ pass_mark: passMark,
575
+ pass_count: offset === 0 ? data.count : lastCheckpoint?.pass_count ?? data.count
576
+ };
352
577
  return { documents, checkpoint };
353
578
  }
354
- },
355
- push: {
356
- async handler(changeRows, context) {
357
- const conflicts = [];
358
- for (const row of changeRows) {
359
- const doc = row.newDocumentState;
360
- try {
361
- const response = await fetch(
362
- `${context.baseUrl}/admin/products/${doc.id}`,
363
- {
364
- method: "POST",
365
- headers: {
366
- ...context.headers,
367
- "Content-Type": "application/json"
368
- },
369
- body: JSON.stringify(doc),
370
- signal: context.signal
371
- }
372
- );
373
- if (!response.ok) {
374
- if (row.assumedMasterState) {
375
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
376
- }
377
- }
378
- } catch {
379
- if (row.assumedMasterState) {
380
- conflicts.push({ ...row.assumedMasterState, _deleted: false });
381
- }
579
+ }
580
+ };
581
+
582
+ // src/reconcile/ids.ts
583
+ var PAGE_SIZE = 1e3;
584
+ var MAX_IDS_PER_REQUEST = 100;
585
+ async function get(path, context) {
586
+ const response = await fetch(`${context.baseUrl}${path}`, {
587
+ headers: { ...context.headers, "Content-Type": "application/json" },
588
+ signal: context.signal
589
+ });
590
+ if (!response.ok) {
591
+ const error = await response.json().catch(() => ({}));
592
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
593
+ }
594
+ return response.json();
595
+ }
596
+ async function* fetchPages(context) {
597
+ for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
598
+ const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), order: "id", fields: "id,variants.id" });
599
+ const data = await get(`/admin/products?${params}`, context);
600
+ const products = data.products ?? [];
601
+ count = data.count;
602
+ yield products.map((p) => ({ id: String(p.id), variantIds: (p.variants ?? []).map((v) => String(v.id)) }));
603
+ }
604
+ }
605
+ function variantIds(doc) {
606
+ return (doc.variants ?? []).map((v) => String(v.id));
607
+ }
608
+ async function fetchByIds(ids, context) {
609
+ const results = [];
610
+ for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
611
+ const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
612
+ const params = new URLSearchParams({ fields: MEDUSA_PRODUCT_FIELDS, limit: String(chunk.length) });
613
+ for (const id of chunk) params.append("id[]", id);
614
+ const data = await get(`/admin/products?${params}`, context);
615
+ const products = data.products ?? [];
616
+ results.push(...products.map(toDocument));
617
+ }
618
+ return withCalculatedPrices(results, context);
619
+ }
620
+
621
+ // src/replication/variant-feed.ts
622
+ var MAX_LIMIT = 1e3;
623
+ var MARK_PATH = "/admin/product-variants?limit=1&order=-updated_at&fields=id,updated_at";
624
+ async function get2(path, context) {
625
+ const response = await fetch(`${context.baseUrl}${path}`, {
626
+ headers: { ...context.headers, "Content-Type": "application/json" },
627
+ signal: context.signal
628
+ });
629
+ if (!response.ok) {
630
+ const error = await response.json().catch(() => ({}));
631
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
632
+ }
633
+ return response.json();
634
+ }
635
+ var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
636
+ pull: {
637
+ // The next call's unchanged-mark check then ends at one mark read, unless
638
+ // a variant changed since.
639
+ async seedCheckpoint(context) {
640
+ const markData = await get2(MARK_PATH, context);
641
+ return { offset: 0, updated_at: markData.variants?.[0]?.updated_at ?? "", pass_mark: void 0, pass_count: void 0 };
642
+ },
643
+ async handler(lastCheckpoint, batchSize, context) {
644
+ let offset = lastCheckpoint?.offset ?? 0;
645
+ let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? "";
646
+ let passCount = lastCheckpoint?.pass_count;
647
+ if (offset === 0 && lastCheckpoint?.pass_mark === void 0) {
648
+ const markData = await get2(MARK_PATH, context);
649
+ passMark = markData.variants?.[0]?.updated_at ?? passMark;
650
+ if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
651
+ return { documents: [], checkpoint: lastCheckpoint };
382
652
  }
383
653
  }
384
- return conflicts;
654
+ const page = (from) => {
655
+ const params = new URLSearchParams({ limit: String(variantPageSize), offset: String(from), order: "id", fields: "id,product_id" });
656
+ if (lastCheckpoint?.updated_at) params.set("updated_at[$gte]", lastCheckpoint.updated_at);
657
+ return get2(`/admin/product-variants?${params}`, context);
658
+ };
659
+ const seen = /* @__PURE__ */ new Set();
660
+ const documents = [];
661
+ let complete = false;
662
+ while (!complete && documents.length < batchSize) {
663
+ let data = await page(offset);
664
+ if (offset > 0 && (!data.variants?.length || data.count < (passCount ?? data.count))) {
665
+ offset = 0;
666
+ data = await page(0);
667
+ }
668
+ const variants = data.variants ?? [];
669
+ if (offset === 0) passCount = data.count;
670
+ const parentIds = [...new Set(variants.map((v) => String(v.product_id)))].filter((id) => !seen.has(id));
671
+ parentIds.forEach((id) => seen.add(id));
672
+ if (parentIds.length) {
673
+ documents.push(...(await fetchByIds(parentIds, context)).map((doc) => ({ ...doc, _deleted: false })));
674
+ }
675
+ offset += variants.length;
676
+ complete = offset >= data.count || !variants.length;
677
+ }
678
+ const checkpoint = complete ? { offset: 0, updated_at: passMark, pass_mark: void 0, pass_count: void 0 } : { offset, updated_at: lastCheckpoint?.updated_at ?? "", pass_mark: passMark, pass_count: passCount };
679
+ const moved = ["offset", "updated_at", "pass_mark", "pass_count"].some((key) => checkpoint[key] !== lastCheckpoint?.[key]);
680
+ if (!documents.length && moved) {
681
+ const carrier = await get2(`/admin/products?${new URLSearchParams({ limit: "1", fields: MEDUSA_PRODUCT_FIELDS })}`, context);
682
+ const priced = await withCalculatedPrices((carrier.products ?? []).map(toDocument), context);
683
+ documents.push(...priced.map((doc) => ({ ...doc, _deleted: false })));
684
+ }
685
+ return { documents, checkpoint };
385
686
  }
386
687
  }
688
+ });
689
+
690
+ // src/reconcile/stock.ts
691
+ var PAGE_SIZE2 = 1e3;
692
+ var FIELDS = "id,location_levels.stocked_quantity,location_levels.reserved_quantity,location_levels.location_id";
693
+ var pairsKey = (levels = []) => levels.map((l) => JSON.stringify([l.stocked_quantity, l.reserved_quantity])).sort().join();
694
+ var medusaStockReconcile = {
695
+ async *fetchPages(context) {
696
+ for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE2) {
697
+ const params = new URLSearchParams({ limit: String(PAGE_SIZE2), offset: String(offset), fields: FIELDS, order: "id" });
698
+ const response = await fetch(`${context.baseUrl}/admin/inventory-items?${params}`, {
699
+ headers: { ...context.headers, "Content-Type": "application/json" },
700
+ signal: context.signal
701
+ });
702
+ if (!response.ok) {
703
+ const error = await response.json().catch(() => ({}));
704
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
705
+ }
706
+ const data = await response.json();
707
+ count = data.count;
708
+ yield new Map(data.inventory_items.map((item) => [item.id, (item.location_levels ?? []).map(({ stocked_quantity, reserved_quantity }) => ({ stocked_quantity, reserved_quantity }))]));
709
+ }
710
+ },
711
+ overlay(doc, stock) {
712
+ let changed = false;
713
+ const variants = (doc.variants ?? []).map((variant) => {
714
+ let variantChanged = false;
715
+ const inventory_items = (variant.inventory_items ?? []).map((item) => {
716
+ const levels = stock.get(item.inventory_item_id);
717
+ if (!levels || pairsKey(levels) === pairsKey(item.inventory?.location_levels)) return item;
718
+ variantChanged = true;
719
+ return { ...item, inventory: { ...item.inventory, location_levels: levels } };
720
+ });
721
+ if (!variantChanged) return variant;
722
+ changed = true;
723
+ return { ...variant, inventory_items };
724
+ });
725
+ return changed ? { variants } : void 0;
726
+ }
727
+ };
728
+
729
+ // src/reconcile/prices.ts
730
+ var PAGE_SIZE3 = 1e3;
731
+ var MEDUSA_PRICE_RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1e3;
732
+ async function get3(path, context) {
733
+ const response = await fetch(`${context.baseUrl}${path}`, {
734
+ headers: { ...context.headers, "Content-Type": "application/json" },
735
+ signal: context.signal
736
+ });
737
+ if (!response.ok) {
738
+ const error = await response.json().catch(() => ({}));
739
+ throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
740
+ }
741
+ return response.json();
742
+ }
743
+ var fingerprintOf = (entries) => [...entries].sort().join("|");
744
+ async function* fetchPages2(context) {
745
+ const byProduct = /* @__PURE__ */ new Map();
746
+ for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE3) {
747
+ const params = new URLSearchParams({
748
+ limit: String(PAGE_SIZE3),
749
+ offset: String(offset),
750
+ order: "id",
751
+ fields: "id,product_id,prices.amount,prices.currency_code,prices.price_list_id"
752
+ });
753
+ const data = await get3(`/admin/product-variants?${params}`, context);
754
+ const variants = data.variants ?? [];
755
+ count = data.count;
756
+ const touched = /* @__PURE__ */ new Set();
757
+ for (const variant of variants) {
758
+ const productId = String(variant.product_id);
759
+ touched.add(productId);
760
+ const entries = byProduct.get(productId) ?? [];
761
+ byProduct.set(productId, entries);
762
+ for (const price of variant.prices ?? []) {
763
+ if (price.price_list_id) continue;
764
+ entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
765
+ }
766
+ }
767
+ yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
768
+ }
769
+ }
770
+ function fingerprint(doc) {
771
+ const entries = [];
772
+ for (const variant of doc.variants ?? []) {
773
+ for (const price of variant.prices ?? []) {
774
+ if (price.price_list_id) continue;
775
+ entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
776
+ }
777
+ }
778
+ return fingerprintOf(entries);
779
+ }
780
+
781
+ // src/reconcile/calculated-prices.ts
782
+ var MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS = 30 * 60 * 1e3;
783
+ function fingerprintOf2(variants) {
784
+ return variants.map(({ id, calculated_price: c }) => c ? `${id}:${c.currency_code}:${c.calculated_amount}:${c.original_amount}:${c.is_calculated_price_tax_inclusive}:${c.is_original_price_tax_inclusive}:${c.calculated_price?.price_list_type ?? ""}` : `${id}:-`).sort().join("|");
785
+ }
786
+ async function* fetchPages3(context) {
787
+ const pricing = context.pricingContext;
788
+ if (!pricing) return;
789
+ for (let offset = 0, count = 1; offset < count; offset += STORE_PAGE_SIZE) {
790
+ const params = new URLSearchParams({
791
+ region_id: pricing.region_id ?? "",
792
+ limit: String(STORE_PAGE_SIZE),
793
+ offset: String(offset),
794
+ order: "id",
795
+ fields: STORE_PRICE_FIELDS
796
+ });
797
+ const data = await storeGet(`/store/products?${params}`, context);
798
+ count = data.count;
799
+ yield new Map((data.products ?? []).map((p) => [String(p.id), fingerprintOf2(p.variants ?? [])]));
800
+ }
801
+ }
802
+ function fingerprint2(doc) {
803
+ return fingerprintOf2(doc.variants ?? []);
804
+ }
805
+
806
+ // src/store-settings.ts
807
+ import { StoreSettingsError } from "@tallyui/core";
808
+ async function get4(context, path) {
809
+ const response = await fetch(`${context.baseUrl}${path}`, {
810
+ headers: { ...context.headers, "Content-Type": "application/json" },
811
+ signal: context.signal
812
+ });
813
+ if (!response.ok) {
814
+ const body = await response.json().catch(() => ({}));
815
+ throw new StoreSettingsError("failed", `Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ""}`);
816
+ }
817
+ return response.json();
818
+ }
819
+ function resolveRegion(regions, store, choice) {
820
+ const region = choice?.region && regions.find((r) => r.id === choice.region) || store?.default_region_id && regions.find((r) => r.id === store.default_region_id) || (regions.length === 1 ? regions[0] : void 0);
821
+ if (!region) throw new StoreSettingsError("choice_required", "Medusa has more than one region; choose one", { regions: regions.map((r) => ({ id: r.id, name: r.name })) });
822
+ return region;
823
+ }
824
+ function channelName(key) {
825
+ const names = (key.sales_channels ?? []).map((c) => c.name).filter((name) => name?.trim());
826
+ return names.length > 0 ? names.join(", ") : key.title;
827
+ }
828
+ var medusaStoreSettings = async (context, choice) => {
829
+ const [storeRes, regionsRes, pricePrefRes, apiKeysRes] = await Promise.all([
830
+ get4(context, "/admin/stores?fields=id,default_region_id"),
831
+ get4(context, "/admin/regions?limit=1000&fields=id,name,currency_code,*countries"),
832
+ get4(context, "/admin/price-preferences?limit=1000"),
833
+ get4(context, "/admin/api-keys?type=publishable&limit=1000&fields=id,title,token,revoked_at,sales_channels.id,sales_channels.name")
834
+ ]);
835
+ const region = resolveRegion(regionsRes.regions ?? [], storeRes.stores?.[0], choice);
836
+ const pricePreferences = pricePrefRes.price_preferences ?? [];
837
+ const pref = pricePreferences.find((p) => p.attribute === "region_id" && p.value === region.id) ?? pricePreferences.find((p) => p.attribute === "currency_code" && p.value === region.currency_code);
838
+ const pricesIncludeTax = pref?.is_tax_inclusive ?? false;
839
+ const countries = region.countries ?? [];
840
+ const chosenCountry = choice?.country?.toLowerCase();
841
+ const countryCode = chosenCountry ? countries.find((c) => c.iso_2.toLowerCase() === chosenCountry)?.iso_2 : countries.length === 1 ? countries[0].iso_2 : void 0;
842
+ let taxRegions = [];
843
+ if (countryCode !== void 0) {
844
+ const taxRegionsRes = await get4(context, `/admin/tax-regions?country_code=${encodeURIComponent(countryCode)}&limit=1000&fields=id,country_code,province_code,*tax_rates`);
845
+ taxRegions = taxRegionsRes.tax_regions ?? [];
846
+ }
847
+ const apiKeys = apiKeysRes.api_keys ?? [];
848
+ const availableKeys = apiKeys.filter((k) => !k.revoked_at);
849
+ if (availableKeys.length === 0) throw new StoreSettingsError("failed", "Medusa has no publishable API key; create one in the admin");
850
+ const channelKey = choice?.channel && availableKeys.find((k) => k.id === choice.channel) || (availableKeys.length === 1 ? availableKeys[0] : void 0);
851
+ if (countryCode === void 0 || !channelKey) {
852
+ const message = chosenCountry && countryCode === void 0 ? "the chosen country isn't in this region; choose a country" : "Medusa needs a country and/or sales channel choice";
853
+ throw new StoreSettingsError("choice_required", message, {
854
+ countries: countries.map((c) => c.iso_2.toLowerCase()),
855
+ channels: availableKeys.map((k) => ({ id: k.id, name: channelName(k) }))
856
+ });
857
+ }
858
+ const countryTaxRegion = taxRegions.find((tr) => tr.province_code === null);
859
+ const eligibleRates = (countryTaxRegion?.tax_rates ?? []).filter((r) => !r.rules || r.rules.length === 0);
860
+ const defaultRate = eligibleRates.find((r) => r.is_default);
861
+ const taxRatesPpm = { default: defaultRate?.rate != null ? Math.round(defaultRate.rate * 1e4) : 0 };
862
+ return {
863
+ currency: region.currency_code.toUpperCase(),
864
+ pricesIncludeTax,
865
+ taxRatesPpm,
866
+ // The publishable key is a public credential, as storefronts embed it, so it may sit here.
867
+ // It never appears in an error message, `choices`, or console output — only in this context.
868
+ pricingContext: {
869
+ region_id: region.id,
870
+ currency_code: region.currency_code.toLowerCase(),
871
+ publishable_key: channelKey.token
872
+ }
873
+ };
387
874
  };
388
875
 
389
876
  // src/index.ts
877
+ var idFeed = createReconcileFeed({ fetchByIds });
878
+ var medusaSecretKeyAuth = {
879
+ type: "Medusa Admin API",
880
+ fields: [
881
+ { key: "url", label: "Backend URL", type: "url", placeholder: "https://my-medusa-backend.com", required: true },
882
+ { key: "api_token", label: "Secret API Key", type: "password", placeholder: "sk_...", required: true }
883
+ ],
884
+ // Medusa v2 only accepts secret API keys over HTTP Basic auth, with the
885
+ // key as the username and an empty password. Bearer is for user JWTs.
886
+ getHeaders: (credentials) => ({ Authorization: `Basic ${btoa(`${credentials.api_token}:`)}` })
887
+ };
888
+ var jwtExpiresAt = (token) => {
889
+ try {
890
+ const part = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
891
+ const { exp } = JSON.parse(atob(part.padEnd(Math.ceil(part.length / 4) * 4, "=")));
892
+ return typeof exp === "number" ? new Date(exp * 1e3).toISOString() : void 0;
893
+ } catch {
894
+ return void 0;
895
+ }
896
+ };
897
+ var medusaSignIn = async (baseUrl, { email, password }, init = {}) => {
898
+ const doFetch = init.fetch ?? fetch;
899
+ let res;
900
+ try {
901
+ res = await doFetch(`${baseUrl}/auth/user/emailpass`, {
902
+ method: "POST",
903
+ headers: { "Content-Type": "application/json" },
904
+ signal: init.signal,
905
+ body: JSON.stringify({ email, password })
906
+ });
907
+ } catch (error) {
908
+ if (error?.name === "AbortError" || init.signal?.aborted) throw error;
909
+ throw new SignInError2("failed", `Could not reach Medusa at ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
910
+ }
911
+ let body = {};
912
+ let bodyUnparseable = false;
913
+ try {
914
+ const parsed = await res.json();
915
+ if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) body = parsed;
916
+ else bodyUnparseable = true;
917
+ } catch {
918
+ bodyUnparseable = true;
919
+ }
920
+ if (res.status === 401) throw new SignInError2("invalid_credentials", body.message ?? "Invalid email or password");
921
+ if (bodyUnparseable) throw new SignInError2("server_error", `Medusa sent an unreadable response (HTTP ${res.status})`, res.status);
922
+ if (body.location) throw new SignInError2("unsupported", `Medusa wants to continue sign-in at ${body.location}; only email and password are supported`);
923
+ if (body.mfa_required === true) throw new SignInError2("unsupported", "Medusa requires multi-factor authentication, which this connector does not support");
924
+ if (body.verification_required === true) throw new SignInError2("unsupported", "Medusa requires email verification, which this connector does not support");
925
+ if (!res.ok) throw new SignInError2("server_error", body.message ?? `Medusa sign-in failed (HTTP ${res.status})`, res.status);
926
+ if (typeof body.token !== "string") throw new SignInError2("server_error", `Medusa sign-in response had no token (HTTP ${res.status})`, res.status);
927
+ const capabilities = await readCapabilities(baseUrl, { Authorization: `Bearer ${body.token}` }, { fetch: doFetch, signal: init.signal });
928
+ return { token: body.token, expiresAt: jwtExpiresAt(body.token), capabilities };
929
+ };
930
+ var medusaCapabilities = (context) => readCapabilities(context.baseUrl, context.headers, { signal: context.signal });
931
+ var medusaAdminUserAuth = {
932
+ type: "Medusa admin user (Bearer JWT)",
933
+ fields: [
934
+ { key: "url", label: "Backend URL", type: "url", placeholder: "https://my-medusa-backend.com", required: true },
935
+ { key: "email", label: "Email", type: "text", required: true },
936
+ { key: "password", label: "Password", type: "password", required: true }
937
+ ],
938
+ getHeaders: (credentials) => typeof credentials.token === "string" && credentials.token.length > 0 ? { Authorization: `Bearer ${credentials.token}` } : {},
939
+ signIn: medusaSignIn
940
+ };
390
941
  var medusaConnector = {
391
942
  id: "medusa",
392
943
  name: "MedusaJS",
393
944
  description: "Connect to MedusaJS v2 backends via the Admin API",
394
945
  icon: void 0,
395
946
  // TODO: Medusa logo
396
- auth: {
397
- type: "Medusa Admin API",
398
- fields: [
399
- {
400
- key: "url",
401
- label: "Backend URL",
402
- type: "url",
403
- placeholder: "https://my-medusa-backend.com",
404
- required: true
405
- },
406
- {
407
- key: "api_token",
408
- label: "API Token",
409
- type: "password",
410
- placeholder: "Your admin API token",
411
- required: true
412
- }
413
- ],
414
- getHeaders: (credentials) => ({
415
- Authorization: `Bearer ${credentials.api_token}`
416
- })
417
- },
947
+ auth: medusaSecretKeyAuth,
418
948
  schemas: {
419
949
  products: medusaProductSchema
420
950
  },
@@ -425,13 +955,40 @@ var medusaConnector = {
425
955
  products: medusaProductSync
426
956
  },
427
957
  replication: {
428
- products: medusaProductReplication
429
- }
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
+ storeSettings: medusaStoreSettings
975
+ // No capabilities read here: the plugin's routes authenticate users only, so this connector can't send orders through the plugin either.
430
976
  };
977
+ var medusaAdminUserConnector = { ...medusaConnector, auth: medusaAdminUserAuth, capabilities: medusaCapabilities };
431
978
  export {
979
+ MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS,
980
+ createMedusaVariantFeedReplication,
981
+ medusaAdminUserAuth,
982
+ medusaAdminUserConnector,
983
+ medusaCapabilities,
432
984
  medusaConnector,
433
985
  medusaProductReplication,
434
986
  medusaProductSchema,
435
987
  medusaProductSync,
436
- medusaProductTraits
988
+ medusaProductTraits,
989
+ medusaSecretKeyAuth,
990
+ medusaSignIn,
991
+ medusaStockReconcile,
992
+ medusaStoreSettings,
993
+ withCalculatedPrices
437
994
  };