@tallyui/connector-medusa 1.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/LICENSE +21 -0
- package/README.md +7 -0
- package/dist/index.d.ts +144 -10
- package/dist/index.js +738 -75
- package/package.json +13 -4
- package/src/capabilities.ts +35 -0
- package/src/customers.ts +69 -0
- package/src/index.ts +154 -32
- package/src/pricing/calculated.ts +58 -0
- package/src/reconcile/calculated-prices.ts +44 -0
- package/src/reconcile/ids.ts +58 -0
- package/src/reconcile/prices.ts +73 -0
- package/src/reconcile/stock.ts +58 -0
- package/src/replication/products.ts +92 -56
- package/src/replication/variant-feed.ts +119 -0
- package/src/schemas/products.ts +54 -2
- package/src/store-settings.ts +115 -0
- package/src/sync/products.ts +2 -1
- package/src/traits/product.ts +133 -9
- package/src/__tests__/product-traits.test.ts +0 -260
- package/src/replication/products.test.ts +0 -169
package/dist/index.js
CHANGED
|
@@ -1,7 +1,99 @@
|
|
|
1
|
+
// src/index.ts
|
|
2
|
+
import { combinePullAdapters, createReconcileFeed, SignInError as SignInError2 } from "@tallyui/core";
|
|
3
|
+
|
|
4
|
+
// src/capabilities.ts
|
|
5
|
+
import { parseInfoCapabilities, 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
|
+
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);
|
|
90
|
+
}
|
|
91
|
+
|
|
1
92
|
// src/schemas/products.ts
|
|
2
93
|
var medusaProductSchema = {
|
|
3
94
|
title: "Medusa Product",
|
|
4
|
-
|
|
95
|
+
// 1: declares `variants[].calculated_price` (backlog 44). A bump drops and resyncs (ConnectorSchemas).
|
|
96
|
+
version: 1,
|
|
5
97
|
type: "object",
|
|
6
98
|
primaryKey: "id",
|
|
7
99
|
properties: {
|
|
@@ -12,8 +104,10 @@ var medusaProductSchema = {
|
|
|
12
104
|
title: {
|
|
13
105
|
type: "string"
|
|
14
106
|
},
|
|
107
|
+
// Indexed fields must be required strings with a maxLength (RxDB SC34).
|
|
15
108
|
handle: {
|
|
16
|
-
type: "string"
|
|
109
|
+
type: "string",
|
|
110
|
+
maxLength: 255
|
|
17
111
|
},
|
|
18
112
|
subtitle: {
|
|
19
113
|
type: ["string", "null"]
|
|
@@ -24,7 +118,8 @@ var medusaProductSchema = {
|
|
|
24
118
|
status: {
|
|
25
119
|
type: "string",
|
|
26
120
|
enum: ["draft", "proposed", "published", "rejected"],
|
|
27
|
-
default: "draft"
|
|
121
|
+
default: "draft",
|
|
122
|
+
maxLength: 20
|
|
28
123
|
},
|
|
29
124
|
thumbnail: {
|
|
30
125
|
type: ["string", "null"]
|
|
@@ -154,6 +249,7 @@ var medusaProductSchema = {
|
|
|
154
249
|
}
|
|
155
250
|
}
|
|
156
251
|
},
|
|
252
|
+
// Admin base prices.
|
|
157
253
|
prices: {
|
|
158
254
|
type: "array",
|
|
159
255
|
items: {
|
|
@@ -166,6 +262,27 @@ var medusaProductSchema = {
|
|
|
166
262
|
max_quantity: { type: ["number", "null"] }
|
|
167
263
|
}
|
|
168
264
|
}
|
|
265
|
+
},
|
|
266
|
+
// The store API's price (D2b), as `MedusaCalculatedPrice`: an object in priced mode,
|
|
267
|
+
// `null` when the sales channel or region does not sell the variant, and absent in
|
|
268
|
+
// base-only mode, with no pricing context. No `additionalProperties: false`: the store
|
|
269
|
+
// API sends more fields (`id`, `original_price`) and can add others.
|
|
270
|
+
calculated_price: {
|
|
271
|
+
type: ["object", "null"],
|
|
272
|
+
properties: {
|
|
273
|
+
calculated_amount: { type: ["number", "null"] },
|
|
274
|
+
original_amount: { type: ["number", "null"] },
|
|
275
|
+
currency_code: { type: "string" },
|
|
276
|
+
is_calculated_price_tax_inclusive: { type: ["boolean", "null"] },
|
|
277
|
+
is_original_price_tax_inclusive: { type: ["boolean", "null"] },
|
|
278
|
+
calculated_price: {
|
|
279
|
+
type: "object",
|
|
280
|
+
properties: {
|
|
281
|
+
price_list_id: { type: ["string", "null"] },
|
|
282
|
+
price_list_type: { type: ["string", "null"] }
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
169
286
|
}
|
|
170
287
|
}
|
|
171
288
|
}
|
|
@@ -178,25 +295,104 @@ var medusaProductSchema = {
|
|
|
178
295
|
}
|
|
179
296
|
},
|
|
180
297
|
indexes: ["handle", "status"],
|
|
181
|
-
required: ["id"]
|
|
298
|
+
required: ["id", "handle", "status"]
|
|
182
299
|
};
|
|
183
300
|
|
|
184
301
|
// src/traits/product.ts
|
|
302
|
+
import { minorUnitDigits, moneyToMajor, resolvePrice } from "@tallyui/core";
|
|
303
|
+
function productStock(variants) {
|
|
304
|
+
if (!variants.length) return { status: "unknown" };
|
|
305
|
+
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";
|
|
306
|
+
const quantity = variants.every((stock) => stock.quantity != null) ? variants.reduce((sum, stock) => sum + stock.quantity, 0) : void 0;
|
|
307
|
+
return quantity === void 0 ? { status } : { status, quantity };
|
|
308
|
+
}
|
|
309
|
+
function variantQuantity(variant) {
|
|
310
|
+
if (variant?.inventory_quantity != null) return variant.inventory_quantity;
|
|
311
|
+
const items = variant?.inventory_items ?? [];
|
|
312
|
+
const known = items.filter((item) => item?.inventory?.location_levels);
|
|
313
|
+
if (!known.length) return null;
|
|
314
|
+
return Math.min(
|
|
315
|
+
...known.map((item) => {
|
|
316
|
+
const available = item.inventory.location_levels.reduce(
|
|
317
|
+
(sum, level) => sum + Number(level?.stocked_quantity ?? 0) - Number(level?.reserved_quantity ?? 0),
|
|
318
|
+
0
|
|
319
|
+
);
|
|
320
|
+
return Math.floor(available / Number(item.required_quantity || 1));
|
|
321
|
+
})
|
|
322
|
+
);
|
|
323
|
+
}
|
|
324
|
+
var toMinor = (amount, currency) => Math.round(Number(amount) * 10 ** minorUnitDigits(currency));
|
|
325
|
+
var taxFlag = (flag) => typeof flag === "boolean" ? { taxInclusive: flag } : {};
|
|
326
|
+
function calculatedPrices(calc) {
|
|
327
|
+
if (!calc?.currency_code || calc.original_amount == null || calc.calculated_amount == null) return [];
|
|
328
|
+
const currency = calc.currency_code.toUpperCase();
|
|
329
|
+
const type = calc.calculated_price?.price_list_type;
|
|
330
|
+
if (type === "override") {
|
|
331
|
+
return [{ amount: toMinor(calc.calculated_amount, currency), currency, kind: "base", ...taxFlag(calc.is_calculated_price_tax_inclusive) }];
|
|
332
|
+
}
|
|
333
|
+
const prices = [{ amount: toMinor(calc.original_amount, currency), currency, kind: "base", ...taxFlag(calc.is_original_price_tax_inclusive) }];
|
|
334
|
+
if (type === "sale" && calc.calculated_amount < calc.original_amount) {
|
|
335
|
+
prices.push({ amount: toMinor(calc.calculated_amount, currency), currency, kind: "sale", ...taxFlag(calc.is_calculated_price_tax_inclusive) });
|
|
336
|
+
}
|
|
337
|
+
return prices;
|
|
338
|
+
}
|
|
339
|
+
function variantPrices(variant) {
|
|
340
|
+
if (!variant) return [];
|
|
341
|
+
if (variant.calculated_price !== void 0) return calculatedPrices(variant.calculated_price);
|
|
342
|
+
const prices = [];
|
|
343
|
+
const seen = /* @__PURE__ */ new Set();
|
|
344
|
+
for (const price of variant.prices ?? []) {
|
|
345
|
+
if (price?.price_list_id || price?.amount == null || !price.currency_code) continue;
|
|
346
|
+
const currency = String(price.currency_code).toUpperCase();
|
|
347
|
+
if (seen.has(currency)) continue;
|
|
348
|
+
seen.add(currency);
|
|
349
|
+
prices.push({ amount: toMinor(price.amount, currency), currency, kind: "base" });
|
|
350
|
+
}
|
|
351
|
+
return prices;
|
|
352
|
+
}
|
|
353
|
+
var isPriced = (doc) => (doc.variants ?? []).some((v) => v.calculated_price !== void 0);
|
|
354
|
+
function pricedMajor(doc, which) {
|
|
355
|
+
const resolved = resolvePrice(variantPrices(doc.variants?.[0]));
|
|
356
|
+
const money = which === "base" ? resolved?.was ?? resolved?.current : resolved?.current;
|
|
357
|
+
return money ? moneyToMajor(money).toFixed(2) : void 0;
|
|
358
|
+
}
|
|
359
|
+
function variantStock(variant) {
|
|
360
|
+
if (!variant) return { status: "unknown" };
|
|
361
|
+
if (variant.manage_inventory === false) return { status: "in_stock" };
|
|
362
|
+
const quantity = variantQuantity(variant);
|
|
363
|
+
if (quantity == null) return { status: "unknown" };
|
|
364
|
+
if (quantity > 0) return { status: "in_stock", quantity };
|
|
365
|
+
return { status: variant.allow_backorder ? "backorder" : "out_of_stock", quantity };
|
|
366
|
+
}
|
|
185
367
|
var medusaProductTraits = {
|
|
186
368
|
getId: (doc) => doc.id,
|
|
187
369
|
getName: (doc) => doc.title ?? "",
|
|
188
370
|
getSku: (doc) => {
|
|
189
371
|
return doc.variants?.[0]?.sku || void 0;
|
|
190
372
|
},
|
|
373
|
+
getPrices: (doc) => variantPrices(doc.variants?.[0]),
|
|
374
|
+
getStock: (doc) => productStock((doc.variants ?? []).map(variantStock)),
|
|
375
|
+
getVariants: (doc) => (doc.variants ?? []).map((v) => ({
|
|
376
|
+
id: v.id,
|
|
377
|
+
title: v.title ?? void 0,
|
|
378
|
+
sku: v.sku || void 0,
|
|
379
|
+
barcode: v.barcode || v.ean || v.upc || void 0,
|
|
380
|
+
prices: variantPrices(v),
|
|
381
|
+
stock: variantStock(v)
|
|
382
|
+
})),
|
|
383
|
+
// getPrice, getRegularPrice and getSalePrice: deprecated; use `getPrices`. In priced mode the
|
|
384
|
+
// first two give what `getPrices` resolves to, never the admin prices.
|
|
191
385
|
getPrice: (doc) => {
|
|
386
|
+
if (isPriced(doc)) return pricedMajor(doc, "current");
|
|
192
387
|
const amount = doc.variants?.[0]?.prices?.[0]?.amount;
|
|
193
388
|
if (amount == null) return void 0;
|
|
194
|
-
return (amount
|
|
389
|
+
return Number(amount).toFixed(2);
|
|
195
390
|
},
|
|
196
391
|
getRegularPrice: (doc) => {
|
|
392
|
+
if (isPriced(doc)) return pricedMajor(doc, "base");
|
|
197
393
|
const amount = doc.variants?.[0]?.prices?.[0]?.amount;
|
|
198
394
|
if (amount == null) return void 0;
|
|
199
|
-
return (amount
|
|
395
|
+
return Number(amount).toFixed(2);
|
|
200
396
|
},
|
|
201
397
|
getSalePrice: () => {
|
|
202
398
|
return void 0;
|
|
@@ -221,16 +417,20 @@ var medusaProductTraits = {
|
|
|
221
417
|
if (!variant) return "unknown";
|
|
222
418
|
if (variant.manage_inventory === false) return "instock";
|
|
223
419
|
if (variant.allow_backorder) return "onbackorder";
|
|
224
|
-
const qty = variant
|
|
420
|
+
const qty = variantQuantity(variant);
|
|
225
421
|
if (qty == null) return "unknown";
|
|
226
422
|
return qty > 0 ? "instock" : "outofstock";
|
|
227
423
|
},
|
|
228
424
|
getStockQuantity: (doc) => {
|
|
229
|
-
return doc.variants?.[0]
|
|
425
|
+
return variantQuantity(doc.variants?.[0]);
|
|
230
426
|
},
|
|
231
427
|
hasVariants: (doc) => {
|
|
232
428
|
return (doc.variants?.length ?? 0) > 1;
|
|
233
429
|
},
|
|
430
|
+
// In priced mode, a product with no variant that yields a price (a null calculated price, or null
|
|
431
|
+
// amounts) is not sold in this channel or region.
|
|
432
|
+
isSellable: (doc) => (doc.status === void 0 || doc.status === "published") && (!isPriced(doc) || doc.variants.some((v) => variantPrices(v).length > 0)),
|
|
433
|
+
getVariantCount: (doc) => doc.variants?.length ?? 1,
|
|
234
434
|
getType: (doc) => {
|
|
235
435
|
if (doc.is_giftcard) return "giftcard";
|
|
236
436
|
if ((doc.variants?.length ?? 0) > 1) return "variable";
|
|
@@ -298,7 +498,8 @@ var medusaProductSync = {
|
|
|
298
498
|
},
|
|
299
499
|
async fetchModifiedAfter(date, context) {
|
|
300
500
|
const response = await fetch(
|
|
301
|
-
|
|
501
|
+
// Medusa 2.21 honours only the operator form; `updated_at[gte]` is silently dropped.
|
|
502
|
+
`${context.baseUrl}/admin/products?updated_at[$gte]=${date}&limit=100&fields=*variants,*variants.prices,*images,*categories,*tags,*options,*options.values`,
|
|
302
503
|
{
|
|
303
504
|
headers: {
|
|
304
505
|
...context.headers,
|
|
@@ -316,17 +517,96 @@ var medusaProductSync = {
|
|
|
316
517
|
};
|
|
317
518
|
|
|
318
519
|
// src/replication/products.ts
|
|
319
|
-
|
|
520
|
+
import { compareIds, ConnectorUnauthorizedError as ConnectorUnauthorizedError2 } from "@tallyui/core";
|
|
521
|
+
|
|
522
|
+
// src/pricing/calculated.ts
|
|
523
|
+
var STORE_PAGE_SIZE = 100;
|
|
524
|
+
var STORE_PRICE_FIELDS = "id,*variants.calculated_price";
|
|
525
|
+
async function storeGet(path, context) {
|
|
526
|
+
const key = context.pricingContext?.publishable_key ?? "";
|
|
527
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
528
|
+
headers: { "x-publishable-api-key": key, "Content-Type": "application/json" },
|
|
529
|
+
signal: context.signal
|
|
530
|
+
});
|
|
531
|
+
if (!response.ok) {
|
|
532
|
+
const error = await response.json().catch(() => ({}));
|
|
533
|
+
const message = typeof error?.message === "string" && key ? error.message.split(key).join("[key]") : error?.message;
|
|
534
|
+
throw new Error(`Medusa store API error: ${response.status}${message ? `: ${message}` : ""}`);
|
|
535
|
+
}
|
|
536
|
+
return response.json();
|
|
537
|
+
}
|
|
538
|
+
async function withCalculatedPrices(docs, context) {
|
|
539
|
+
const pricing = context.pricingContext;
|
|
540
|
+
if (!pricing) return docs;
|
|
541
|
+
const byVariant = /* @__PURE__ */ new Map();
|
|
542
|
+
for (let i = 0; i < docs.length; i += STORE_PAGE_SIZE) {
|
|
543
|
+
const params = new URLSearchParams({ region_id: pricing.region_id ?? "", limit: String(STORE_PAGE_SIZE), fields: STORE_PRICE_FIELDS });
|
|
544
|
+
for (const doc of docs.slice(i, i + STORE_PAGE_SIZE)) params.append("id[]", doc.id);
|
|
545
|
+
const data = await storeGet(`/store/products?${params}`, context);
|
|
546
|
+
for (const product of data.products ?? []) {
|
|
547
|
+
for (const variant of product.variants ?? []) byVariant.set(variant.id, variant.calculated_price ?? null);
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
return docs.map((doc) => Array.isArray(doc.variants) ? { ...doc, variants: doc.variants.map((v) => ({ ...v, calculated_price: byVariant.get(v.id) ?? null })) } : doc);
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
// src/replication/products.ts
|
|
554
|
+
var SCHEMA_FIELDS = Object.keys(medusaProductSchema.properties);
|
|
555
|
+
function toDocument(product) {
|
|
556
|
+
const doc = {};
|
|
557
|
+
for (const field of SCHEMA_FIELDS) {
|
|
558
|
+
if (product[field] !== void 0) doc[field] = product[field];
|
|
559
|
+
}
|
|
560
|
+
if (Array.isArray(doc.variants)) {
|
|
561
|
+
doc.variants = [...doc.variants].sort((a, b) => compareIds(a.id, b.id));
|
|
562
|
+
}
|
|
563
|
+
return doc;
|
|
564
|
+
}
|
|
565
|
+
var MEDUSA_PRODUCT_FIELDS = [
|
|
566
|
+
"*variants",
|
|
567
|
+
"*variants.prices",
|
|
568
|
+
"+variants.inventory_items.required_quantity",
|
|
569
|
+
"+variants.inventory_items.inventory.location_levels.stocked_quantity",
|
|
570
|
+
"+variants.inventory_items.inventory.location_levels.reserved_quantity",
|
|
571
|
+
"*images",
|
|
572
|
+
"*categories",
|
|
573
|
+
"*tags",
|
|
574
|
+
"*options",
|
|
575
|
+
"*options.values"
|
|
576
|
+
].join(",");
|
|
577
|
+
var MEDUSA_PULL_BATCH_SIZE = 500;
|
|
320
578
|
var medusaProductReplication = {
|
|
321
579
|
pull: {
|
|
322
580
|
async handler(lastCheckpoint, batchSize, context) {
|
|
581
|
+
const offset = lastCheckpoint?.offset ?? 0;
|
|
582
|
+
let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? "";
|
|
583
|
+
if (offset === 0 && lastCheckpoint?.pass_mark === void 0) {
|
|
584
|
+
const markResponse = await fetch(
|
|
585
|
+
`${context.baseUrl}/admin/products?limit=1&order=-updated_at&fields=id,updated_at`,
|
|
586
|
+
{ headers: { ...context.headers, "Content-Type": "application/json" }, signal: context.signal }
|
|
587
|
+
);
|
|
588
|
+
if (!markResponse.ok) {
|
|
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);
|
|
591
|
+
throw new Error(`Medusa API error: ${markResponse.status}${error?.message ? `: ${error.message}` : ""}`);
|
|
592
|
+
}
|
|
593
|
+
const markData = await markResponse.json();
|
|
594
|
+
passMark = markData.products?.[0]?.updated_at ?? passMark;
|
|
595
|
+
if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
|
|
596
|
+
return { documents: [], checkpoint: lastCheckpoint };
|
|
597
|
+
}
|
|
598
|
+
}
|
|
323
599
|
const params = new URLSearchParams({
|
|
324
600
|
limit: String(batchSize),
|
|
325
601
|
offset: String(lastCheckpoint?.offset ?? 0),
|
|
326
|
-
fields: MEDUSA_PRODUCT_FIELDS
|
|
602
|
+
fields: MEDUSA_PRODUCT_FIELDS,
|
|
603
|
+
// Offsets need a total order. Many products share an updated_at
|
|
604
|
+
// (bulk writes), and Medusa sorts by one field only, so page by the
|
|
605
|
+
// unique id within the fixed updated_at window.
|
|
606
|
+
order: "id"
|
|
327
607
|
});
|
|
328
608
|
if (lastCheckpoint?.updated_at) {
|
|
329
|
-
params.set("updated_at[gte]", lastCheckpoint.updated_at);
|
|
609
|
+
params.set("updated_at[$gte]", lastCheckpoint.updated_at);
|
|
330
610
|
}
|
|
331
611
|
const response = await fetch(
|
|
332
612
|
`${context.baseUrl}/admin/products?${params}`,
|
|
@@ -339,82 +619,436 @@ var medusaProductReplication = {
|
|
|
339
619
|
}
|
|
340
620
|
);
|
|
341
621
|
if (!response.ok) {
|
|
342
|
-
|
|
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);
|
|
624
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
|
|
343
625
|
}
|
|
344
626
|
const data = await response.json();
|
|
345
627
|
const products = data.products ?? [];
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
628
|
+
if (offset > 0 && (products.length === 0 || data.count < (lastCheckpoint?.pass_count ?? data.count))) {
|
|
629
|
+
return medusaProductReplication.pull.handler({
|
|
630
|
+
offset: 0,
|
|
631
|
+
updated_at: lastCheckpoint?.updated_at ?? "",
|
|
632
|
+
pass_mark: passMark
|
|
633
|
+
}, batchSize, context);
|
|
634
|
+
}
|
|
635
|
+
const priced = await withCalculatedPrices(products.map(toDocument), context);
|
|
636
|
+
const documents = priced.map((doc) => ({ ...doc, _deleted: false }));
|
|
637
|
+
const checkpoint = offset + products.length >= data.count ? { offset: 0, updated_at: passMark, pass_mark: void 0, pass_count: void 0 } : {
|
|
638
|
+
offset: offset + products.length,
|
|
639
|
+
updated_at: lastCheckpoint?.updated_at ?? "",
|
|
640
|
+
pass_mark: passMark,
|
|
641
|
+
pass_count: offset === 0 ? data.count : lastCheckpoint?.pass_count ?? data.count
|
|
642
|
+
};
|
|
352
643
|
return { documents, checkpoint };
|
|
353
644
|
}
|
|
354
|
-
}
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
645
|
+
}
|
|
646
|
+
};
|
|
647
|
+
|
|
648
|
+
// src/replication/variant-feed.ts
|
|
649
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError4 } from "@tallyui/core";
|
|
650
|
+
|
|
651
|
+
// src/reconcile/ids.ts
|
|
652
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError3 } from "@tallyui/core";
|
|
653
|
+
var PAGE_SIZE = 1e3;
|
|
654
|
+
var MAX_IDS_PER_REQUEST = 100;
|
|
655
|
+
async function get(path, context) {
|
|
656
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
657
|
+
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
658
|
+
signal: context.signal
|
|
659
|
+
});
|
|
660
|
+
if (!response.ok) {
|
|
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);
|
|
663
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
|
|
664
|
+
}
|
|
665
|
+
return response.json();
|
|
666
|
+
}
|
|
667
|
+
async function* fetchPages(context) {
|
|
668
|
+
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE) {
|
|
669
|
+
const params = new URLSearchParams({ limit: String(PAGE_SIZE), offset: String(offset), order: "id", fields: "id,variants.id" });
|
|
670
|
+
const data = await get(`/admin/products?${params}`, context);
|
|
671
|
+
const products = data.products ?? [];
|
|
672
|
+
count = data.count;
|
|
673
|
+
yield products.map((p) => ({ id: String(p.id), variantIds: (p.variants ?? []).map((v) => String(v.id)) }));
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
function variantIds(doc) {
|
|
677
|
+
return (doc.variants ?? []).map((v) => String(v.id));
|
|
678
|
+
}
|
|
679
|
+
async function fetchByIds(ids, context) {
|
|
680
|
+
const results = [];
|
|
681
|
+
for (let i = 0; i < ids.length; i += MAX_IDS_PER_REQUEST) {
|
|
682
|
+
const chunk = ids.slice(i, i + MAX_IDS_PER_REQUEST);
|
|
683
|
+
const params = new URLSearchParams({ fields: MEDUSA_PRODUCT_FIELDS, limit: String(chunk.length) });
|
|
684
|
+
for (const id of chunk) params.append("id[]", id);
|
|
685
|
+
const data = await get(`/admin/products?${params}`, context);
|
|
686
|
+
const products = data.products ?? [];
|
|
687
|
+
results.push(...products.map(toDocument));
|
|
688
|
+
}
|
|
689
|
+
return withCalculatedPrices(results, context);
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
// src/replication/variant-feed.ts
|
|
693
|
+
var MAX_LIMIT = 1e3;
|
|
694
|
+
var MARK_PATH = "/admin/product-variants?limit=1&order=-updated_at&fields=id,updated_at";
|
|
695
|
+
async function get2(path, context) {
|
|
696
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
697
|
+
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
698
|
+
signal: context.signal
|
|
699
|
+
});
|
|
700
|
+
if (!response.ok) {
|
|
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);
|
|
703
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
|
|
704
|
+
}
|
|
705
|
+
return response.json();
|
|
706
|
+
}
|
|
707
|
+
var createMedusaVariantFeedReplication = (variantPageSize = MAX_LIMIT) => ({
|
|
708
|
+
pull: {
|
|
709
|
+
// The next call's unchanged-mark check then ends at one mark read, unless
|
|
710
|
+
// a variant changed since.
|
|
711
|
+
async seedCheckpoint(context) {
|
|
712
|
+
const markData = await get2(MARK_PATH, context);
|
|
713
|
+
return { offset: 0, updated_at: markData.variants?.[0]?.updated_at ?? "", pass_mark: void 0, pass_count: void 0 };
|
|
714
|
+
},
|
|
715
|
+
async handler(lastCheckpoint, batchSize, context) {
|
|
716
|
+
let offset = lastCheckpoint?.offset ?? 0;
|
|
717
|
+
let passMark = lastCheckpoint?.pass_mark ?? lastCheckpoint?.updated_at ?? "";
|
|
718
|
+
let passCount = lastCheckpoint?.pass_count;
|
|
719
|
+
if (offset === 0 && lastCheckpoint?.pass_mark === void 0) {
|
|
720
|
+
const markData = await get2(MARK_PATH, context);
|
|
721
|
+
passMark = markData.variants?.[0]?.updated_at ?? passMark;
|
|
722
|
+
if (lastCheckpoint?.updated_at && passMark === lastCheckpoint.updated_at) {
|
|
723
|
+
return { documents: [], checkpoint: lastCheckpoint };
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
const page = (from) => {
|
|
727
|
+
const params = new URLSearchParams({ limit: String(variantPageSize), offset: String(from), order: "id", fields: "id,product_id" });
|
|
728
|
+
if (lastCheckpoint?.updated_at) params.set("updated_at[$gte]", lastCheckpoint.updated_at);
|
|
729
|
+
return get2(`/admin/product-variants?${params}`, context);
|
|
730
|
+
};
|
|
731
|
+
const seen = /* @__PURE__ */ new Set();
|
|
732
|
+
const documents = [];
|
|
733
|
+
let complete = false;
|
|
734
|
+
while (!complete && documents.length < batchSize) {
|
|
735
|
+
let data = await page(offset);
|
|
736
|
+
if (offset > 0 && (!data.variants?.length || data.count < (passCount ?? data.count))) {
|
|
737
|
+
offset = 0;
|
|
738
|
+
data = await page(0);
|
|
739
|
+
}
|
|
740
|
+
const variants = data.variants ?? [];
|
|
741
|
+
if (offset === 0) passCount = data.count;
|
|
742
|
+
const parentIds = [...new Set(variants.map((v) => String(v.product_id)))].filter((id) => !seen.has(id));
|
|
743
|
+
parentIds.forEach((id) => seen.add(id));
|
|
744
|
+
if (parentIds.length) {
|
|
745
|
+
documents.push(...(await fetchByIds(parentIds, context)).map((doc) => ({ ...doc, _deleted: false })));
|
|
382
746
|
}
|
|
747
|
+
offset += variants.length;
|
|
748
|
+
complete = offset >= data.count || !variants.length;
|
|
749
|
+
}
|
|
750
|
+
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 };
|
|
751
|
+
const moved = ["offset", "updated_at", "pass_mark", "pass_count"].some((key) => checkpoint[key] !== lastCheckpoint?.[key]);
|
|
752
|
+
if (!documents.length && moved) {
|
|
753
|
+
const carrier = await get2(`/admin/products?${new URLSearchParams({ limit: "1", fields: MEDUSA_PRODUCT_FIELDS })}`, context);
|
|
754
|
+
const priced = await withCalculatedPrices((carrier.products ?? []).map(toDocument), context);
|
|
755
|
+
documents.push(...priced.map((doc) => ({ ...doc, _deleted: false })));
|
|
756
|
+
}
|
|
757
|
+
return { documents, checkpoint };
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
});
|
|
761
|
+
|
|
762
|
+
// src/reconcile/stock.ts
|
|
763
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError5 } from "@tallyui/core";
|
|
764
|
+
var PAGE_SIZE2 = 1e3;
|
|
765
|
+
var FIELDS = "id,location_levels.stocked_quantity,location_levels.reserved_quantity,location_levels.location_id";
|
|
766
|
+
var pairsKey = (levels = []) => levels.map((l) => JSON.stringify([l.stocked_quantity, l.reserved_quantity])).sort().join();
|
|
767
|
+
var medusaStockReconcile = {
|
|
768
|
+
async *fetchPages(context) {
|
|
769
|
+
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE2) {
|
|
770
|
+
const params = new URLSearchParams({ limit: String(PAGE_SIZE2), offset: String(offset), fields: FIELDS, order: "id" });
|
|
771
|
+
const response = await fetch(`${context.baseUrl}/admin/inventory-items?${params}`, {
|
|
772
|
+
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
773
|
+
signal: context.signal
|
|
774
|
+
});
|
|
775
|
+
if (!response.ok) {
|
|
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);
|
|
778
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
|
|
779
|
+
}
|
|
780
|
+
const data = await response.json();
|
|
781
|
+
count = data.count;
|
|
782
|
+
yield new Map(data.inventory_items.map((item) => [item.id, (item.location_levels ?? []).map(({ stocked_quantity, reserved_quantity }) => ({ stocked_quantity, reserved_quantity }))]));
|
|
783
|
+
}
|
|
784
|
+
},
|
|
785
|
+
overlay(doc, stock) {
|
|
786
|
+
let changed = false;
|
|
787
|
+
const variants = (doc.variants ?? []).map((variant) => {
|
|
788
|
+
let variantChanged = false;
|
|
789
|
+
const inventory_items = (variant.inventory_items ?? []).map((item) => {
|
|
790
|
+
const levels = stock.get(item.inventory_item_id);
|
|
791
|
+
if (!levels || pairsKey(levels) === pairsKey(item.inventory?.location_levels)) return item;
|
|
792
|
+
variantChanged = true;
|
|
793
|
+
return { ...item, inventory: { ...item.inventory, location_levels: levels } };
|
|
794
|
+
});
|
|
795
|
+
if (!variantChanged) return variant;
|
|
796
|
+
changed = true;
|
|
797
|
+
return { ...variant, inventory_items };
|
|
798
|
+
});
|
|
799
|
+
return changed ? { variants } : void 0;
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
|
|
803
|
+
// src/reconcile/prices.ts
|
|
804
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError6 } from "@tallyui/core";
|
|
805
|
+
var PAGE_SIZE3 = 1e3;
|
|
806
|
+
var MEDUSA_PRICE_RECONCILE_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
807
|
+
async function get3(path, context) {
|
|
808
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
809
|
+
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
810
|
+
signal: context.signal
|
|
811
|
+
});
|
|
812
|
+
if (!response.ok) {
|
|
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);
|
|
815
|
+
throw new Error(`Medusa API error: ${response.status}${error?.message ? `: ${error.message}` : ""}`);
|
|
816
|
+
}
|
|
817
|
+
return response.json();
|
|
818
|
+
}
|
|
819
|
+
var fingerprintOf = (entries) => [...entries].sort().join("|");
|
|
820
|
+
async function* fetchPages2(context) {
|
|
821
|
+
const byProduct = /* @__PURE__ */ new Map();
|
|
822
|
+
for (let offset = 0, count = 1; offset < count; offset += PAGE_SIZE3) {
|
|
823
|
+
const params = new URLSearchParams({
|
|
824
|
+
limit: String(PAGE_SIZE3),
|
|
825
|
+
offset: String(offset),
|
|
826
|
+
order: "id",
|
|
827
|
+
fields: "id,product_id,prices.amount,prices.currency_code,prices.price_list_id"
|
|
828
|
+
});
|
|
829
|
+
const data = await get3(`/admin/product-variants?${params}`, context);
|
|
830
|
+
const variants = data.variants ?? [];
|
|
831
|
+
count = data.count;
|
|
832
|
+
const touched = /* @__PURE__ */ new Set();
|
|
833
|
+
for (const variant of variants) {
|
|
834
|
+
const productId = String(variant.product_id);
|
|
835
|
+
touched.add(productId);
|
|
836
|
+
const entries = byProduct.get(productId) ?? [];
|
|
837
|
+
byProduct.set(productId, entries);
|
|
838
|
+
for (const price of variant.prices ?? []) {
|
|
839
|
+
if (price.price_list_id) continue;
|
|
840
|
+
entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
|
|
383
841
|
}
|
|
384
|
-
return conflicts;
|
|
385
842
|
}
|
|
843
|
+
yield new Map([...touched].map((id) => [id, fingerprintOf(byProduct.get(id) ?? [])]));
|
|
844
|
+
}
|
|
845
|
+
}
|
|
846
|
+
function fingerprint(doc) {
|
|
847
|
+
const entries = [];
|
|
848
|
+
for (const variant of doc.variants ?? []) {
|
|
849
|
+
for (const price of variant.prices ?? []) {
|
|
850
|
+
if (price.price_list_id) continue;
|
|
851
|
+
entries.push(`${variant.id}:${price.currency_code}:${price.amount}`);
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return fingerprintOf(entries);
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
// src/reconcile/calculated-prices.ts
|
|
858
|
+
var MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS = 30 * 60 * 1e3;
|
|
859
|
+
function fingerprintOf2(variants) {
|
|
860
|
+
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("|");
|
|
861
|
+
}
|
|
862
|
+
async function* fetchPages3(context) {
|
|
863
|
+
const pricing = context.pricingContext;
|
|
864
|
+
if (!pricing) return;
|
|
865
|
+
for (let offset = 0, count = 1; offset < count; offset += STORE_PAGE_SIZE) {
|
|
866
|
+
const params = new URLSearchParams({
|
|
867
|
+
region_id: pricing.region_id ?? "",
|
|
868
|
+
limit: String(STORE_PAGE_SIZE),
|
|
869
|
+
offset: String(offset),
|
|
870
|
+
order: "id",
|
|
871
|
+
fields: STORE_PRICE_FIELDS
|
|
872
|
+
});
|
|
873
|
+
const data = await storeGet(`/store/products?${params}`, context);
|
|
874
|
+
count = data.count;
|
|
875
|
+
yield new Map((data.products ?? []).map((p) => [String(p.id), fingerprintOf2(p.variants ?? [])]));
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
function fingerprint2(doc) {
|
|
879
|
+
return fingerprintOf2(doc.variants ?? []);
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
// src/store-settings.ts
|
|
883
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError7, StoreSettingsError } from "@tallyui/core";
|
|
884
|
+
async function get4(context, path) {
|
|
885
|
+
const response = await fetch(`${context.baseUrl}${path}`, {
|
|
886
|
+
headers: { ...context.headers, "Content-Type": "application/json" },
|
|
887
|
+
signal: context.signal
|
|
888
|
+
});
|
|
889
|
+
if (!response.ok) {
|
|
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);
|
|
892
|
+
throw new StoreSettingsError("failed", `Medusa store settings request failed (HTTP ${response.status})${body?.message ? `: ${body.message}` : ""}`);
|
|
893
|
+
}
|
|
894
|
+
return response.json();
|
|
895
|
+
}
|
|
896
|
+
function resolveRegion(regions, store, choice) {
|
|
897
|
+
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);
|
|
898
|
+
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 })) });
|
|
899
|
+
return region;
|
|
900
|
+
}
|
|
901
|
+
function channelName(key) {
|
|
902
|
+
const names = (key.sales_channels ?? []).map((c) => c.name).filter((name) => name?.trim());
|
|
903
|
+
return names.length > 0 ? names.join(", ") : key.title;
|
|
904
|
+
}
|
|
905
|
+
var medusaStoreSettings = async (context, choice) => {
|
|
906
|
+
const [storeRes, regionsRes, pricePrefRes, apiKeysRes] = await Promise.all([
|
|
907
|
+
get4(context, "/admin/stores?fields=id,default_region_id"),
|
|
908
|
+
get4(context, "/admin/regions?limit=1000&fields=id,name,currency_code,*countries"),
|
|
909
|
+
get4(context, "/admin/price-preferences?limit=1000"),
|
|
910
|
+
get4(context, "/admin/api-keys?type=publishable&limit=1000&fields=id,title,token,revoked_at,sales_channels.id,sales_channels.name")
|
|
911
|
+
]);
|
|
912
|
+
const region = resolveRegion(regionsRes.regions ?? [], storeRes.stores?.[0], choice);
|
|
913
|
+
const pricePreferences = pricePrefRes.price_preferences ?? [];
|
|
914
|
+
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);
|
|
915
|
+
const pricesIncludeTax = pref?.is_tax_inclusive ?? false;
|
|
916
|
+
const countries = region.countries ?? [];
|
|
917
|
+
const chosenCountry = choice?.country?.toLowerCase();
|
|
918
|
+
const countryCode = chosenCountry ? countries.find((c) => c.iso_2.toLowerCase() === chosenCountry)?.iso_2 : countries.length === 1 ? countries[0].iso_2 : void 0;
|
|
919
|
+
let taxRegions = [];
|
|
920
|
+
if (countryCode !== void 0) {
|
|
921
|
+
const taxRegionsRes = await get4(context, `/admin/tax-regions?country_code=${encodeURIComponent(countryCode)}&limit=1000&fields=id,country_code,province_code,*tax_rates`);
|
|
922
|
+
taxRegions = taxRegionsRes.tax_regions ?? [];
|
|
386
923
|
}
|
|
924
|
+
const apiKeys = apiKeysRes.api_keys ?? [];
|
|
925
|
+
const availableKeys = apiKeys.filter((k) => !k.revoked_at);
|
|
926
|
+
if (availableKeys.length === 0) throw new StoreSettingsError("failed", "Medusa has no publishable API key; create one in the admin");
|
|
927
|
+
const channelKey = choice?.channel && availableKeys.find((k) => k.id === choice.channel) || (availableKeys.length === 1 ? availableKeys[0] : void 0);
|
|
928
|
+
if (countryCode === void 0 || !channelKey) {
|
|
929
|
+
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";
|
|
930
|
+
throw new StoreSettingsError("choice_required", message, {
|
|
931
|
+
countries: countries.map((c) => c.iso_2.toLowerCase()),
|
|
932
|
+
channels: availableKeys.map((k) => ({ id: k.id, name: channelName(k) }))
|
|
933
|
+
});
|
|
934
|
+
}
|
|
935
|
+
const countryTaxRegion = taxRegions.find((tr) => tr.province_code === null);
|
|
936
|
+
const eligibleRates = (countryTaxRegion?.tax_rates ?? []).filter((r) => !r.rules || r.rules.length === 0);
|
|
937
|
+
const defaultRate = eligibleRates.find((r) => r.is_default);
|
|
938
|
+
const taxRatesPpm = { default: defaultRate?.rate != null ? Math.round(defaultRate.rate * 1e4) : 0 };
|
|
939
|
+
return {
|
|
940
|
+
currency: region.currency_code.toUpperCase(),
|
|
941
|
+
pricesIncludeTax,
|
|
942
|
+
taxRatesPpm,
|
|
943
|
+
// The publishable key is a public credential, as storefronts embed it, so it may sit here.
|
|
944
|
+
// It never appears in an error message, `choices`, or console output — only in this context.
|
|
945
|
+
pricingContext: {
|
|
946
|
+
region_id: region.id,
|
|
947
|
+
currency_code: region.currency_code.toLowerCase(),
|
|
948
|
+
publishable_key: channelKey.token
|
|
949
|
+
}
|
|
950
|
+
};
|
|
387
951
|
};
|
|
388
952
|
|
|
389
953
|
// src/index.ts
|
|
390
|
-
|
|
954
|
+
import { ConnectorUnauthorizedError as ConnectorUnauthorizedError8 } from "@tallyui/core";
|
|
955
|
+
var medusaSecretKeyAuth = {
|
|
956
|
+
type: "Medusa Admin API",
|
|
957
|
+
fields: [
|
|
958
|
+
{ key: "url", label: "Backend URL", type: "url", placeholder: "https://my-medusa-backend.com", required: true },
|
|
959
|
+
{ key: "api_token", label: "Secret API Key", type: "password", placeholder: "sk_...", required: true }
|
|
960
|
+
],
|
|
961
|
+
// Medusa v2 only accepts secret API keys over HTTP Basic auth, with the
|
|
962
|
+
// key as the username and an empty password. Bearer is for user JWTs.
|
|
963
|
+
getHeaders: (credentials) => ({ Authorization: `Basic ${btoa(`${credentials.api_token}:`)}` })
|
|
964
|
+
};
|
|
965
|
+
var jwtExpiresAt = (token) => {
|
|
966
|
+
try {
|
|
967
|
+
const part = token.split(".")[1].replace(/-/g, "+").replace(/_/g, "/");
|
|
968
|
+
const { exp } = JSON.parse(atob(part.padEnd(Math.ceil(part.length / 4) * 4, "=")));
|
|
969
|
+
return typeof exp === "number" ? new Date(exp * 1e3).toISOString() : void 0;
|
|
970
|
+
} catch {
|
|
971
|
+
return void 0;
|
|
972
|
+
}
|
|
973
|
+
};
|
|
974
|
+
var medusaSignIn = async (baseUrl, { email, password }, init = {}) => {
|
|
975
|
+
const doFetch = init.fetch ?? fetch;
|
|
976
|
+
let res;
|
|
977
|
+
try {
|
|
978
|
+
res = await doFetch(`${baseUrl}/auth/user/emailpass`, {
|
|
979
|
+
method: "POST",
|
|
980
|
+
headers: { "Content-Type": "application/json" },
|
|
981
|
+
signal: init.signal,
|
|
982
|
+
body: JSON.stringify({ email, password })
|
|
983
|
+
});
|
|
984
|
+
} catch (error) {
|
|
985
|
+
if (error?.name === "AbortError" || init.signal?.aborted) throw error;
|
|
986
|
+
throw new SignInError2("failed", `Could not reach Medusa at ${baseUrl}: ${error instanceof Error ? error.message : String(error)}`);
|
|
987
|
+
}
|
|
988
|
+
let body = {};
|
|
989
|
+
let bodyUnparseable = false;
|
|
990
|
+
try {
|
|
991
|
+
const parsed = await res.json();
|
|
992
|
+
if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) body = parsed;
|
|
993
|
+
else bodyUnparseable = true;
|
|
994
|
+
} catch {
|
|
995
|
+
bodyUnparseable = true;
|
|
996
|
+
}
|
|
997
|
+
if (res.status === 401) throw new SignInError2("invalid_credentials", body.message ?? "Invalid email or password");
|
|
998
|
+
if (bodyUnparseable) throw new SignInError2("server_error", `Medusa sent an unreadable response (HTTP ${res.status})`, res.status);
|
|
999
|
+
if (body.location) throw new SignInError2("unsupported", `Medusa wants to continue sign-in at ${body.location}; only email and password are supported`);
|
|
1000
|
+
if (body.mfa_required === true) throw new SignInError2("unsupported", "Medusa requires multi-factor authentication, which this connector does not support");
|
|
1001
|
+
if (body.verification_required === true) throw new SignInError2("unsupported", "Medusa requires email verification, which this connector does not support");
|
|
1002
|
+
if (!res.ok) throw new SignInError2("server_error", body.message ?? `Medusa sign-in failed (HTTP ${res.status})`, res.status);
|
|
1003
|
+
if (typeof body.token !== "string") throw new SignInError2("server_error", `Medusa sign-in response had no token (HTTP ${res.status})`, res.status);
|
|
1004
|
+
const capabilities = await readCapabilities(baseUrl, { Authorization: `Bearer ${body.token}` }, { fetch: doFetch, signal: init.signal });
|
|
1005
|
+
return { token: body.token, expiresAt: jwtExpiresAt(body.token), capabilities };
|
|
1006
|
+
};
|
|
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 });
|
|
1011
|
+
var medusaAdminUserAuth = {
|
|
1012
|
+
type: "Medusa admin user (Bearer JWT)",
|
|
1013
|
+
fields: [
|
|
1014
|
+
{ key: "url", label: "Backend URL", type: "url", placeholder: "https://my-medusa-backend.com", required: true },
|
|
1015
|
+
{ key: "email", label: "Email", type: "text", required: true },
|
|
1016
|
+
{ key: "password", label: "Password", type: "password", required: true }
|
|
1017
|
+
],
|
|
1018
|
+
getHeaders: (credentials) => typeof credentials.token === "string" && credentials.token.length > 0 ? { Authorization: `Bearer ${credentials.token}` } : {},
|
|
1019
|
+
signIn: medusaSignIn
|
|
1020
|
+
};
|
|
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 = {
|
|
391
1046
|
id: "medusa",
|
|
392
1047
|
name: "MedusaJS",
|
|
393
1048
|
description: "Connect to MedusaJS v2 backends via the Admin API",
|
|
394
1049
|
icon: void 0,
|
|
395
1050
|
// 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
|
-
},
|
|
1051
|
+
auth: medusaSecretKeyAuth,
|
|
418
1052
|
schemas: {
|
|
419
1053
|
products: medusaProductSchema
|
|
420
1054
|
},
|
|
@@ -424,14 +1058,43 @@ var medusaConnector = {
|
|
|
424
1058
|
sync: {
|
|
425
1059
|
products: medusaProductSync
|
|
426
1060
|
},
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
}
|
|
1061
|
+
storeSettings: medusaStoreSettings
|
|
1062
|
+
// No capabilities read here: the plugin's routes authenticate users only, so this connector can't send orders through the plugin either.
|
|
430
1063
|
};
|
|
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();
|
|
431
1074
|
export {
|
|
1075
|
+
ConnectorUnauthorizedError8 as ConnectorUnauthorizedError,
|
|
1076
|
+
MEDUSA_CALCULATED_PRICE_RECONCILE_INTERVAL_MS,
|
|
1077
|
+
createMedusaAdminUserConnector,
|
|
1078
|
+
createMedusaConnector,
|
|
1079
|
+
createMedusaCustomer,
|
|
1080
|
+
createMedusaVariantFeedReplication,
|
|
1081
|
+
getMedusaCustomer,
|
|
1082
|
+
medusaAdminUserAuth,
|
|
1083
|
+
medusaAdminUserConnector,
|
|
1084
|
+
medusaCapabilities,
|
|
432
1085
|
medusaConnector,
|
|
1086
|
+
medusaCreateCustomer,
|
|
1087
|
+
medusaGetCustomer,
|
|
433
1088
|
medusaProductReplication,
|
|
434
1089
|
medusaProductSchema,
|
|
435
1090
|
medusaProductSync,
|
|
436
|
-
medusaProductTraits
|
|
1091
|
+
medusaProductTraits,
|
|
1092
|
+
medusaSearchCustomers,
|
|
1093
|
+
medusaSecretKeyAuth,
|
|
1094
|
+
medusaSignIn,
|
|
1095
|
+
medusaStockReconcile,
|
|
1096
|
+
medusaStoreSettings,
|
|
1097
|
+
searchMedusaCustomers,
|
|
1098
|
+
toCustomer,
|
|
1099
|
+
withCalculatedPrices
|
|
437
1100
|
};
|