@tallyui/connector-medusa 1.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.
@@ -0,0 +1,260 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import { medusaProductTraits } from '../traits/product';
3
+
4
+ /**
5
+ * Realistic MedusaJS v2 product document, shaped like the Admin API response.
6
+ */
7
+ const fullProduct = {
8
+ id: 'prod_01H8X3K4M2N5P7Q9R1S3T5V7',
9
+ title: 'Commercial Espresso Machine',
10
+ handle: 'commercial-espresso-machine',
11
+ status: 'published',
12
+ description: 'High-end commercial espresso machine with dual boilers.',
13
+ thumbnail: 'https://cdn.example/thumb-espresso.jpg',
14
+ is_giftcard: false,
15
+ images: [
16
+ { id: 'img_01', url: 'https://cdn.example/espresso-full.jpg' },
17
+ { id: 'img_02', url: 'https://cdn.example/espresso-back.jpg' },
18
+ ],
19
+ categories: [
20
+ { id: 'pcat_01', name: 'Equipment' },
21
+ { id: 'pcat_02', name: 'Café Gear' },
22
+ ],
23
+ variants: [
24
+ {
25
+ id: 'var_01H',
26
+ sku: 'MED-ESP-001',
27
+ barcode: '9876543210001',
28
+ ean: null,
29
+ upc: null,
30
+ inventory_quantity: 8,
31
+ manage_inventory: true,
32
+ allow_backorder: false,
33
+ prices: [
34
+ { currency_code: 'usd', amount: 89900 },
35
+ { currency_code: 'eur', amount: 82500 },
36
+ ],
37
+ },
38
+ ],
39
+ };
40
+
41
+ const multiVariantProduct = {
42
+ ...fullProduct,
43
+ id: 'prod_multi',
44
+ variants: [
45
+ {
46
+ id: 'var_01',
47
+ sku: 'MED-ESP-S',
48
+ barcode: null,
49
+ ean: '4006381333931',
50
+ upc: null,
51
+ inventory_quantity: 3,
52
+ manage_inventory: true,
53
+ allow_backorder: false,
54
+ prices: [{ currency_code: 'usd', amount: 89900 }],
55
+ },
56
+ {
57
+ id: 'var_02',
58
+ sku: 'MED-ESP-L',
59
+ barcode: null,
60
+ ean: null,
61
+ upc: '036000291452',
62
+ inventory_quantity: 0,
63
+ manage_inventory: true,
64
+ allow_backorder: true,
65
+ prices: [{ currency_code: 'usd', amount: 109900 }],
66
+ },
67
+ ],
68
+ };
69
+
70
+ const giftcardProduct = {
71
+ ...fullProduct,
72
+ id: 'prod_gc',
73
+ is_giftcard: true,
74
+ variants: [
75
+ {
76
+ id: 'var_gc',
77
+ sku: 'GC-50',
78
+ barcode: null,
79
+ ean: null,
80
+ upc: null,
81
+ inventory_quantity: null,
82
+ manage_inventory: false,
83
+ allow_backorder: false,
84
+ prices: [{ currency_code: 'usd', amount: 5000 }],
85
+ },
86
+ ],
87
+ };
88
+
89
+ const minimalProduct = {
90
+ id: 'prod_empty',
91
+ };
92
+
93
+ describe('Medusa product traits', () => {
94
+ describe('getId', () => {
95
+ it('returns the product id', () => {
96
+ expect(medusaProductTraits.getId(fullProduct)).toBe('prod_01H8X3K4M2N5P7Q9R1S3T5V7');
97
+ });
98
+ });
99
+
100
+ describe('getName', () => {
101
+ it('returns the title (not name)', () => {
102
+ expect(medusaProductTraits.getName(fullProduct)).toBe('Commercial Espresso Machine');
103
+ });
104
+
105
+ it('returns empty string for missing title', () => {
106
+ expect(medusaProductTraits.getName(minimalProduct)).toBe('');
107
+ });
108
+ });
109
+
110
+ describe('getSku', () => {
111
+ it('reads SKU from the first variant', () => {
112
+ expect(medusaProductTraits.getSku(fullProduct)).toBe('MED-ESP-001');
113
+ });
114
+
115
+ it('returns undefined when no variants', () => {
116
+ expect(medusaProductTraits.getSku(minimalProduct)).toBeUndefined();
117
+ });
118
+ });
119
+
120
+ describe('getPrice', () => {
121
+ it('converts cents to decimal string', () => {
122
+ expect(medusaProductTraits.getPrice(fullProduct)).toBe('899.00');
123
+ });
124
+
125
+ it('returns undefined when no variants/prices', () => {
126
+ expect(medusaProductTraits.getPrice(minimalProduct)).toBeUndefined();
127
+ });
128
+ });
129
+
130
+ describe('getRegularPrice / getSalePrice / isOnSale', () => {
131
+ it('regular price matches price (Medusa uses price lists, not product-level sales)', () => {
132
+ expect(medusaProductTraits.getRegularPrice(fullProduct)).toBe('899.00');
133
+ });
134
+
135
+ it('sale price is always undefined (handled by price lists)', () => {
136
+ expect(medusaProductTraits.getSalePrice(fullProduct)).toBeUndefined();
137
+ });
138
+
139
+ it('isOnSale is always false (no product-level sale flag)', () => {
140
+ expect(medusaProductTraits.isOnSale(fullProduct)).toBe(false);
141
+ });
142
+ });
143
+
144
+ describe('getImageUrl / getImageUrls', () => {
145
+ it('prefers thumbnail over images[0].url', () => {
146
+ expect(medusaProductTraits.getImageUrl(fullProduct)).toBe('https://cdn.example/thumb-espresso.jpg');
147
+ });
148
+
149
+ it('falls back to images[0].url when no thumbnail', () => {
150
+ const noThumb = { ...fullProduct, thumbnail: null };
151
+ expect(medusaProductTraits.getImageUrl(noThumb)).toBe('https://cdn.example/espresso-full.jpg');
152
+ });
153
+
154
+ it('returns all URLs (thumbnail + images, deduplicated)', () => {
155
+ const urls = medusaProductTraits.getImageUrls(fullProduct);
156
+ expect(urls).toContain('https://cdn.example/thumb-espresso.jpg');
157
+ expect(urls).toContain('https://cdn.example/espresso-full.jpg');
158
+ expect(urls).toContain('https://cdn.example/espresso-back.jpg');
159
+ });
160
+
161
+ it('returns undefined / empty for missing images', () => {
162
+ expect(medusaProductTraits.getImageUrl(minimalProduct)).toBeUndefined();
163
+ expect(medusaProductTraits.getImageUrls(minimalProduct)).toEqual([]);
164
+ });
165
+ });
166
+
167
+ describe('getDescription', () => {
168
+ it('returns the description', () => {
169
+ expect(medusaProductTraits.getDescription(fullProduct)).toBe(
170
+ 'High-end commercial espresso machine with dual boilers.'
171
+ );
172
+ });
173
+
174
+ it('returns undefined when missing', () => {
175
+ expect(medusaProductTraits.getDescription(minimalProduct)).toBeUndefined();
176
+ });
177
+ });
178
+
179
+ describe('getStockStatus', () => {
180
+ it('returns instock when quantity > 0', () => {
181
+ expect(medusaProductTraits.getStockStatus(fullProduct)).toBe('instock');
182
+ });
183
+
184
+ it('returns outofstock when quantity is 0 and no backorder', () => {
185
+ const outOfStock = {
186
+ ...fullProduct,
187
+ variants: [{ ...fullProduct.variants[0], inventory_quantity: 0 }],
188
+ };
189
+ expect(medusaProductTraits.getStockStatus(outOfStock)).toBe('outofstock');
190
+ });
191
+
192
+ it('returns onbackorder when allow_backorder is true', () => {
193
+ expect(medusaProductTraits.getStockStatus(multiVariantProduct)).toBe('instock');
194
+ });
195
+
196
+ it('returns instock when manage_inventory is false', () => {
197
+ expect(medusaProductTraits.getStockStatus(giftcardProduct)).toBe('instock');
198
+ });
199
+
200
+ it('returns unknown when no variants', () => {
201
+ expect(medusaProductTraits.getStockStatus(minimalProduct)).toBe('unknown');
202
+ });
203
+ });
204
+
205
+ describe('getStockQuantity', () => {
206
+ it('returns the first variant quantity', () => {
207
+ expect(medusaProductTraits.getStockQuantity(fullProduct)).toBe(8);
208
+ });
209
+
210
+ it('returns null when no variants', () => {
211
+ expect(medusaProductTraits.getStockQuantity(minimalProduct)).toBeNull();
212
+ });
213
+ });
214
+
215
+ describe('hasVariants / getType', () => {
216
+ it('single variant = no variants', () => {
217
+ expect(medusaProductTraits.hasVariants(fullProduct)).toBe(false);
218
+ });
219
+
220
+ it('multiple variants detected', () => {
221
+ expect(medusaProductTraits.hasVariants(multiVariantProduct)).toBe(true);
222
+ });
223
+
224
+ it('simple type for single variant', () => {
225
+ expect(medusaProductTraits.getType(fullProduct)).toBe('simple');
226
+ });
227
+
228
+ it('variable type for multiple variants', () => {
229
+ expect(medusaProductTraits.getType(multiVariantProduct)).toBe('variable');
230
+ });
231
+
232
+ it('giftcard type detected', () => {
233
+ expect(medusaProductTraits.getType(giftcardProduct)).toBe('giftcard');
234
+ });
235
+ });
236
+
237
+ describe('getBarcode', () => {
238
+ it('returns barcode from first variant', () => {
239
+ expect(medusaProductTraits.getBarcode(fullProduct)).toBe('9876543210001');
240
+ });
241
+
242
+ it('falls back to EAN', () => {
243
+ expect(medusaProductTraits.getBarcode(multiVariantProduct)).toBe('4006381333931');
244
+ });
245
+
246
+ it('returns undefined when no barcode fields', () => {
247
+ expect(medusaProductTraits.getBarcode(minimalProduct)).toBeUndefined();
248
+ });
249
+ });
250
+
251
+ describe('getCategoryNames', () => {
252
+ it('returns category name strings', () => {
253
+ expect(medusaProductTraits.getCategoryNames(fullProduct)).toEqual(['Equipment', 'Café Gear']);
254
+ });
255
+
256
+ it('returns empty array when no categories', () => {
257
+ expect(medusaProductTraits.getCategoryNames(minimalProduct)).toEqual([]);
258
+ });
259
+ });
260
+ });
package/src/index.ts ADDED
@@ -0,0 +1,73 @@
1
+ import type { TallyConnector } from '@tallyui/core';
2
+
3
+ import { medusaProductSchema } from './schemas/products';
4
+ import { medusaProductTraits } from './traits/product';
5
+ import { medusaProductSync } from './sync/products';
6
+ import { medusaProductReplication } from './replication/products';
7
+
8
+ /**
9
+ * MedusaJS v2 connector for Tally UI.
10
+ *
11
+ * Connects to Medusa backends via the Admin API.
12
+ * Products are stored in RxDB using a schema that mirrors the Medusa API shape.
13
+ *
14
+ * ```ts
15
+ * import { medusaConnector } from '@tallyui/connector-medusa';
16
+ * import { ConnectorProvider } from '@tallyui/core';
17
+ *
18
+ * <ConnectorProvider connector={medusaConnector}>
19
+ * <App />
20
+ * </ConnectorProvider>
21
+ * ```
22
+ */
23
+ export const medusaConnector: TallyConnector = {
24
+ id: 'medusa',
25
+ name: 'MedusaJS',
26
+ description: 'Connect to MedusaJS v2 backends via the Admin API',
27
+ icon: undefined, // TODO: Medusa logo
28
+
29
+ auth: {
30
+ type: 'Medusa Admin API',
31
+ fields: [
32
+ {
33
+ key: 'url',
34
+ label: 'Backend URL',
35
+ type: 'url',
36
+ placeholder: 'https://my-medusa-backend.com',
37
+ required: true,
38
+ },
39
+ {
40
+ key: 'api_token',
41
+ label: 'API Token',
42
+ type: 'password',
43
+ placeholder: 'Your admin API token',
44
+ required: true,
45
+ },
46
+ ],
47
+ getHeaders: (credentials) => ({
48
+ Authorization: `Bearer ${credentials.api_token}`,
49
+ }),
50
+ },
51
+
52
+ schemas: {
53
+ products: medusaProductSchema,
54
+ },
55
+
56
+ traits: {
57
+ product: medusaProductTraits,
58
+ },
59
+
60
+ sync: {
61
+ products: medusaProductSync,
62
+ },
63
+
64
+ replication: {
65
+ products: medusaProductReplication,
66
+ },
67
+ };
68
+
69
+ // Re-export pieces for advanced usage
70
+ export { medusaProductSchema } from './schemas/products';
71
+ export { medusaProductTraits } from './traits/product';
72
+ export { medusaProductSync } from './sync/products';
73
+ export { medusaProductReplication } from './replication/products';
@@ -0,0 +1,169 @@
1
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
2
+ import type { SyncContext } from '@tallyui/core';
3
+
4
+ import { medusaProductReplication } from './products';
5
+
6
+ const context: SyncContext = {
7
+ connectorId: 'medusa',
8
+ baseUrl: 'https://my-medusa-backend.com',
9
+ headers: { Authorization: 'Bearer test_token' },
10
+ };
11
+
12
+ describe('medusaProductReplication.pull.handler', () => {
13
+ beforeEach(() => {
14
+ vi.restoreAllMocks();
15
+ });
16
+
17
+ it('fetches products from initial checkpoint (undefined)', async () => {
18
+ const mockProducts = [
19
+ { id: 'prod_01', title: 'Widget', updated_at: '2026-01-01T00:00:00Z' },
20
+ { id: 'prod_02', title: 'Gadget', updated_at: '2026-01-02T00:00:00Z' },
21
+ ];
22
+
23
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
24
+ new Response(JSON.stringify({ products: mockProducts }), { status: 200 }),
25
+ );
26
+
27
+ const result = await medusaProductReplication.pull.handler(undefined, 100, context);
28
+
29
+ expect(result.documents).toHaveLength(2);
30
+ expect(result.documents[0]._deleted).toBe(false);
31
+ expect(result.checkpoint).toEqual({
32
+ offset: 0,
33
+ updated_at: '2026-01-02T00:00:00Z',
34
+ });
35
+
36
+ const calledUrl = (globalThis.fetch as any).mock.calls[0][0];
37
+ expect(calledUrl).toContain('offset=0');
38
+ expect(calledUrl).toContain('limit=100');
39
+ expect(calledUrl).toContain('fields=');
40
+ });
41
+
42
+ it('passes updated_at filter and offset from checkpoint', async () => {
43
+ const mockProducts = [
44
+ { id: 'prod_03', title: 'Thingamajig', updated_at: '2026-02-01T00:00:00Z' },
45
+ ];
46
+
47
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
48
+ new Response(JSON.stringify({ products: mockProducts }), { status: 200 }),
49
+ );
50
+
51
+ const checkpoint = { offset: 50, updated_at: '2026-01-15T00:00:00Z' };
52
+ const result = await medusaProductReplication.pull.handler(checkpoint, 100, context);
53
+
54
+ const calledUrl = (globalThis.fetch as any).mock.calls[0][0];
55
+ expect(calledUrl).toContain('offset=50');
56
+ expect(calledUrl).toContain('updated_at%5Bgte%5D=2026-01-15T00%3A00%3A00Z');
57
+
58
+ // Batch smaller than batchSize resets offset to 0
59
+ expect(result.checkpoint.offset).toBe(0);
60
+ });
61
+
62
+ it('advances offset when batch equals batchSize', async () => {
63
+ const mockProducts = Array.from({ length: 25 }, (_, i) => ({
64
+ id: `prod_${i}`,
65
+ title: `Product ${i}`,
66
+ updated_at: '2026-01-01T00:00:00Z',
67
+ }));
68
+
69
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
70
+ new Response(JSON.stringify({ products: mockProducts }), { status: 200 }),
71
+ );
72
+
73
+ const result = await medusaProductReplication.pull.handler(undefined, 25, context);
74
+
75
+ expect(result.checkpoint.offset).toBe(25);
76
+ });
77
+
78
+ it('throws on non-OK response', async () => {
79
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
80
+ new Response('Internal Server Error', { status: 500 }),
81
+ );
82
+
83
+ await expect(
84
+ medusaProductReplication.pull.handler(undefined, 100, context),
85
+ ).rejects.toThrow('Medusa API error: 500');
86
+ });
87
+
88
+ it('returns lastCheckpoint when no products are returned', async () => {
89
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
90
+ new Response(JSON.stringify({ products: [] }), { status: 200 }),
91
+ );
92
+
93
+ const checkpoint = { offset: 0, updated_at: '2026-01-01T00:00:00Z' };
94
+ const result = await medusaProductReplication.pull.handler(checkpoint, 100, context);
95
+
96
+ expect(result.checkpoint).toEqual(checkpoint);
97
+ });
98
+ });
99
+
100
+ describe('medusaProductReplication.push.handler', () => {
101
+ beforeEach(() => {
102
+ vi.restoreAllMocks();
103
+ });
104
+
105
+ it('sends POST for updates', async () => {
106
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
107
+ new Response(JSON.stringify({}), { status: 200 }),
108
+ );
109
+
110
+ const conflicts = await medusaProductReplication.push!.handler(
111
+ [{
112
+ newDocumentState: { id: 'prod_01', title: 'Updated', _deleted: false } as any,
113
+ assumedMasterState: { id: 'prod_01', title: 'Old', _deleted: false } as any,
114
+ }],
115
+ context,
116
+ );
117
+
118
+ expect(conflicts).toHaveLength(0);
119
+ const [url, opts] = (globalThis.fetch as any).mock.calls[0];
120
+ expect(url).toContain('/admin/products/prod_01');
121
+ expect(opts.method).toBe('POST');
122
+ });
123
+
124
+ it('returns conflicts on server error', async () => {
125
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
126
+ new Response('conflict', { status: 409 }),
127
+ );
128
+
129
+ const conflicts = await medusaProductReplication.push!.handler(
130
+ [{
131
+ newDocumentState: { id: 'prod_01', title: 'Updated', _deleted: false } as any,
132
+ assumedMasterState: { id: 'prod_01', title: 'Server Version', _deleted: false } as any,
133
+ }],
134
+ context,
135
+ );
136
+
137
+ expect(conflicts).toHaveLength(1);
138
+ expect(conflicts[0].title).toBe('Server Version');
139
+ });
140
+
141
+ it('returns conflicts on network failure', async () => {
142
+ vi.spyOn(globalThis, 'fetch').mockRejectedValueOnce(new Error('Network error'));
143
+
144
+ const conflicts = await medusaProductReplication.push!.handler(
145
+ [{
146
+ newDocumentState: { id: 'prod_01', title: 'Updated', _deleted: false } as any,
147
+ assumedMasterState: { id: 'prod_01', title: 'Server Version', _deleted: false } as any,
148
+ }],
149
+ context,
150
+ );
151
+
152
+ expect(conflicts).toHaveLength(1);
153
+ });
154
+
155
+ it('does not return conflict when assumedMasterState is absent', async () => {
156
+ vi.spyOn(globalThis, 'fetch').mockResolvedValueOnce(
157
+ new Response('error', { status: 500 }),
158
+ );
159
+
160
+ const conflicts = await medusaProductReplication.push!.handler(
161
+ [{
162
+ newDocumentState: { id: 'prod_01', title: 'New Product', _deleted: false } as any,
163
+ }],
164
+ context,
165
+ );
166
+
167
+ expect(conflicts).toHaveLength(0);
168
+ });
169
+ });
@@ -0,0 +1,102 @@
1
+ import type { ReplicationAdapter } from '@tallyui/core';
2
+
3
+ export type MedusaProductCheckpoint = {
4
+ offset: number;
5
+ updated_at: string;
6
+ };
7
+
8
+ const MEDUSA_PRODUCT_FIELDS =
9
+ '*variants,*variants.prices,*images,*categories,*tags,*options,*options.values';
10
+
11
+ /**
12
+ * Replication adapter for Medusa v2 products.
13
+ *
14
+ * Implements pull (offset-based pagination with updated_at filtering) and
15
+ * push (POST to update individual products via Admin API). Designed for
16
+ * use with RxDB's replicateRxCollection.
17
+ */
18
+ export const medusaProductReplication: ReplicationAdapter<any, MedusaProductCheckpoint> = {
19
+ pull: {
20
+ async handler(lastCheckpoint, batchSize, context) {
21
+ const params = new URLSearchParams({
22
+ limit: String(batchSize),
23
+ offset: String(lastCheckpoint?.offset ?? 0),
24
+ fields: MEDUSA_PRODUCT_FIELDS,
25
+ });
26
+
27
+ if (lastCheckpoint?.updated_at) {
28
+ params.set('updated_at[gte]', lastCheckpoint.updated_at);
29
+ }
30
+
31
+ const response = await fetch(
32
+ `${context.baseUrl}/admin/products?${params}`,
33
+ {
34
+ headers: {
35
+ ...context.headers,
36
+ 'Content-Type': 'application/json',
37
+ },
38
+ signal: context.signal,
39
+ },
40
+ );
41
+
42
+ if (!response.ok) {
43
+ throw new Error(`Medusa API error: ${response.status}`);
44
+ }
45
+
46
+ const data = await response.json();
47
+ const products: any[] = data.products ?? [];
48
+ const documents = products.map((p) => ({ ...p, _deleted: false }));
49
+
50
+ // Reset offset when batch is smaller than batchSize (end of page)
51
+ const nextOffset = products.length < batchSize
52
+ ? 0
53
+ : (lastCheckpoint?.offset ?? 0) + products.length;
54
+
55
+ const checkpoint: MedusaProductCheckpoint = products.length > 0
56
+ ? {
57
+ offset: nextOffset,
58
+ updated_at: products[products.length - 1].updated_at,
59
+ }
60
+ : lastCheckpoint ?? { offset: 0, updated_at: '' };
61
+
62
+ return { documents, checkpoint };
63
+ },
64
+ },
65
+
66
+ push: {
67
+ async handler(changeRows, context) {
68
+ const conflicts: any[] = [];
69
+
70
+ for (const row of changeRows) {
71
+ const doc = row.newDocumentState as any;
72
+
73
+ try {
74
+ const response = await fetch(
75
+ `${context.baseUrl}/admin/products/${doc.id}`,
76
+ {
77
+ method: 'POST',
78
+ headers: {
79
+ ...context.headers,
80
+ 'Content-Type': 'application/json',
81
+ },
82
+ body: JSON.stringify(doc),
83
+ signal: context.signal,
84
+ },
85
+ );
86
+
87
+ if (!response.ok) {
88
+ if (row.assumedMasterState) {
89
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
90
+ }
91
+ }
92
+ } catch {
93
+ if (row.assumedMasterState) {
94
+ conflicts.push({ ...row.assumedMasterState, _deleted: false });
95
+ }
96
+ }
97
+ }
98
+
99
+ return conflicts;
100
+ },
101
+ },
102
+ };