@thorprovider/medusa-extended 1.14.1 → 1.14.2

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 DELETED
@@ -1,2210 +0,0 @@
1
- "use strict";
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
- var __getOwnPropNames = Object.getOwnPropertyNames;
5
- var __hasOwnProp = Object.prototype.hasOwnProperty;
6
- var __export = (target, all) => {
7
- for (var name in all)
8
- __defProp(target, name, { get: all[name], enumerable: true });
9
- };
10
- var __copyProps = (to, from, except, desc) => {
11
- if (from && typeof from === "object" || typeof from === "function") {
12
- for (let key of __getOwnPropNames(from))
13
- if (!__hasOwnProp.call(to, key) && key !== except)
14
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
- }
16
- return to;
17
- };
18
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
-
20
- // src/index.ts
21
- var src_exports = {};
22
- __export(src_exports, {
23
- DropshipperClient: () => DropshipperClient,
24
- MedusaAdminClient: () => MedusaAdminClient,
25
- RecoveryClient: () => RecoveryClient
26
- });
27
- module.exports = __toCommonJS(src_exports);
28
-
29
- // src/admin.ts
30
- var import_adapters2 = require("@thorprovider/adapters");
31
-
32
- // src/request-resilience.ts
33
- var import_adapters = require("@thorprovider/adapters");
34
- var DEFAULT_RETRY_CONFIG = {
35
- maxRetries: 3,
36
- initialDelayMs: 300,
37
- backoffMultiplier: 2,
38
- maxDelayMs: 5e3,
39
- timeoutMs: 1e4,
40
- retryableStatusCodes: [408, 429, 500, 502, 503, 504]
41
- };
42
- function sleep(ms) {
43
- return new Promise((resolve) => setTimeout(resolve, ms));
44
- }
45
- function calculateDelay(attempt, config) {
46
- const delay = config.initialDelayMs * Math.pow(config.backoffMultiplier, attempt);
47
- return Math.min(delay, config.maxDelayMs);
48
- }
49
- function isRetryableError(error, config) {
50
- const err = error;
51
- if (err.name === "TypeError" || err.message?.includes("fetch failed")) return true;
52
- if (err.name === "AbortError" || err.message?.includes("timeout")) return true;
53
- if (typeof err.status === "number" && config.retryableStatusCodes.includes(err.status)) return true;
54
- return false;
55
- }
56
- async function fetchWithRetry(url, init, retryConfig) {
57
- const config = { ...DEFAULT_RETRY_CONFIG, ...retryConfig };
58
- const method = (init.method || "GET").toUpperCase();
59
- const isMutation = ["POST", "PUT", "PATCH", "DELETE"].includes(method);
60
- let lastError;
61
- for (let attempt = 0; attempt <= config.maxRetries; attempt++) {
62
- try {
63
- const controller = new AbortController();
64
- const timeoutId = setTimeout(() => controller.abort(), config.timeoutMs);
65
- const response = await fetch(url, { ...init, signal: controller.signal });
66
- clearTimeout(timeoutId);
67
- if (!response.ok && config.retryableStatusCodes.includes(response.status)) {
68
- const error = new Error(`HTTP ${response.status}: ${response.statusText}`);
69
- error.status = response.status;
70
- throw error;
71
- }
72
- return response;
73
- } catch (error) {
74
- lastError = error;
75
- const isTimeoutOrNetwork = error instanceof Error && (error.name === "AbortError" || error.message?.includes("timeout") || error.message?.includes("fetch failed"));
76
- if (isMutation && isTimeoutOrNetwork) {
77
- break;
78
- }
79
- const shouldRetry = attempt < config.maxRetries && isRetryableError(error, config);
80
- if (shouldRetry) {
81
- await sleep(calculateDelay(attempt, config));
82
- continue;
83
- }
84
- break;
85
- }
86
- }
87
- throw lastError instanceof Error ? lastError : new Error("Backend request failed");
88
- }
89
- async function fetchBackendWithResilience(url, init, retryConfig) {
90
- try {
91
- return await import_adapters.backendCircuitBreaker.execute(() => fetchWithRetry(url, init, retryConfig));
92
- } catch (error) {
93
- const message = error instanceof Error ? error.message : String(error);
94
- throw new import_adapters.ProviderAPIError(`Backend request failed: ${message}`, "backend", 503);
95
- }
96
- }
97
-
98
- // src/admin.ts
99
- var MedusaAdminClient = class {
100
- baseUrl;
101
- apiKey;
102
- logger;
103
- constructor(config) {
104
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
105
- this.apiKey = config.apiKey;
106
- this.logger = (0, import_adapters2.createLogger)("MedusaAdminClient", config.debug);
107
- }
108
- // -----------------------------------------------------------------------
109
- // Private — HTTP helper
110
- // -----------------------------------------------------------------------
111
- async request(method, path, body) {
112
- const url = `${this.baseUrl}${path}`;
113
- this.logger.debug(`[admin] ${method} ${path}`);
114
- const headers = {
115
- "x-medusa-access-token": this.apiKey,
116
- "Content-Type": "application/json"
117
- };
118
- const init = {
119
- method,
120
- headers,
121
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
122
- };
123
- let response;
124
- try {
125
- response = await fetchBackendWithResilience(url, init);
126
- } catch (networkError) {
127
- throw new import_adapters2.ProviderAPIError(
128
- `[admin] Network error on ${method} ${path}: ${networkError.message}`,
129
- "NETWORK_ERROR",
130
- networkError
131
- );
132
- }
133
- if (!response.ok) {
134
- let message = `HTTP ${response.status}`;
135
- try {
136
- const json = await response.json();
137
- message = json?.message ?? message;
138
- } catch {
139
- }
140
- throw new import_adapters2.ProviderAPIError(
141
- `[admin] ${method} ${path} failed: ${message}`,
142
- `ADMIN_API_${response.status}`,
143
- response.status
144
- );
145
- }
146
- return response.json();
147
- }
148
- // -----------------------------------------------------------------------
149
- // 3.1 — Sales Channel: Customers
150
- // -----------------------------------------------------------------------
151
- /**
152
- * Paginated list of customers linked to a sales channel.
153
- *
154
- * `GET /admin/thor/sales-channels/:id/customers`
155
- */
156
- async getChannelCustomers(salesChannelId, options = {}) {
157
- const { limit = 20, offset = 0 } = options;
158
- return this.request(
159
- "GET",
160
- `/admin/thor/sales-channels/${salesChannelId}/customers?limit=${limit}&offset=${offset}`
161
- );
162
- }
163
- // -----------------------------------------------------------------------
164
- // 3.2 — Sales Channel: API Keys
165
- // -----------------------------------------------------------------------
166
- /**
167
- * Publishable API keys associated with a sales channel.
168
- *
169
- * `GET /admin/thor/sales-channels/:id/api-keys`
170
- */
171
- async getChannelApiKeys(salesChannelId) {
172
- return this.request(
173
- "GET",
174
- `/admin/thor/sales-channels/${salesChannelId}/api-keys`
175
- );
176
- }
177
- // -----------------------------------------------------------------------
178
- // 3.3 — Sales Channel: Categories
179
- // -----------------------------------------------------------------------
180
- /**
181
- * Product categories assigned to a sales channel.
182
- *
183
- * `GET /admin/thor/sales-channels/:id/categories`
184
- */
185
- async getChannelCategories(salesChannelId, options = {}) {
186
- const { limit = 20, offset = 0, include_descendants = false } = options;
187
- const qs = new URLSearchParams({
188
- limit: String(limit),
189
- offset: String(offset),
190
- include_descendants: String(include_descendants)
191
- });
192
- return this.request(
193
- "GET",
194
- `/admin/thor/sales-channels/${salesChannelId}/categories?${qs}`
195
- );
196
- }
197
- // -----------------------------------------------------------------------
198
- // 3.4 — Category: Sales Channels
199
- // -----------------------------------------------------------------------
200
- /**
201
- * Sales channels to which a category is assigned.
202
- *
203
- * `GET /admin/thor/categories/:id/sales-channels`
204
- */
205
- async getCategorySalesChannels(categoryId) {
206
- return this.request(
207
- "GET",
208
- `/admin/thor/categories/${categoryId}/sales-channels`
209
- );
210
- }
211
- // -----------------------------------------------------------------------
212
- // 3.5 — Category: Assign to Sales Channels
213
- // -----------------------------------------------------------------------
214
- /**
215
- * Assign a category to one or more sales channels (idempotent).
216
- *
217
- * `POST /admin/thor/categories/:id/sales-channels`
218
- */
219
- async assignCategoryToChannels(categoryId, body) {
220
- return this.request(
221
- "POST",
222
- `/admin/thor/categories/${categoryId}/sales-channels`,
223
- body
224
- );
225
- }
226
- // -----------------------------------------------------------------------
227
- // 3.6 — Category: Unassign from Sales Channels
228
- // -----------------------------------------------------------------------
229
- /**
230
- * Remove category assignment from one or more sales channels (idempotent).
231
- *
232
- * `DELETE /admin/thor/categories/:id/sales-channels`
233
- */
234
- async unassignCategoryFromChannels(categoryId, body) {
235
- return this.request(
236
- "DELETE",
237
- `/admin/thor/categories/${categoryId}/sales-channels`,
238
- body
239
- );
240
- }
241
- // -----------------------------------------------------------------------
242
- // 3.7 — Collection: Sales Channels
243
- // -----------------------------------------------------------------------
244
- /**
245
- * Sales channels to which a collection is assigned.
246
- *
247
- * `GET /admin/thor/collections/:id/sales-channels`
248
- */
249
- async getCollectionSalesChannels(collectionId) {
250
- return this.request(
251
- "GET",
252
- `/admin/thor/collections/${collectionId}/sales-channels`
253
- );
254
- }
255
- // -----------------------------------------------------------------------
256
- // 3.8 — Collection: Assign to Sales Channels
257
- // -----------------------------------------------------------------------
258
- /**
259
- * Assign a collection to one or more sales channels (idempotent).
260
- *
261
- * `POST /admin/thor/collections/:id/sales-channels`
262
- */
263
- async assignCollectionToChannels(collectionId, body) {
264
- return this.request(
265
- "POST",
266
- `/admin/thor/collections/${collectionId}/sales-channels`,
267
- body
268
- );
269
- }
270
- // -----------------------------------------------------------------------
271
- // 3.9 — Collection: Unassign from Sales Channels
272
- // -----------------------------------------------------------------------
273
- /**
274
- * Remove collection assignment from one or more sales channels (idempotent).
275
- *
276
- * `DELETE /admin/thor/collections/:id/sales-channels`
277
- */
278
- async unassignCollectionFromChannels(collectionId, body) {
279
- return this.request(
280
- "DELETE",
281
- `/admin/thor/collections/${collectionId}/sales-channels`,
282
- body
283
- );
284
- }
285
- // -----------------------------------------------------------------------
286
- // 3.10 — Storefront Config: Read
287
- // -----------------------------------------------------------------------
288
- /**
289
- * Read the visual storefront configuration for a channel.
290
- * `:id` is the `sales_channel_id`.
291
- *
292
- * `GET /admin/thor/storefront-config/:id`
293
- */
294
- async getStorefrontConfig(salesChannelId) {
295
- return this.request(
296
- "GET",
297
- `/admin/thor/storefront-config/${salesChannelId}`
298
- );
299
- }
300
- // -----------------------------------------------------------------------
301
- // 3.11 — Storefront Config: Update
302
- // -----------------------------------------------------------------------
303
- /**
304
- * Update the visual storefront configuration for a channel.
305
- * Triggers the `storefront_config.updated` event → ISR webhook.
306
- *
307
- * `PUT /admin/thor/storefront-config/:id`
308
- */
309
- async updateStorefrontConfig(salesChannelId, body) {
310
- return this.request(
311
- "PUT",
312
- `/admin/thor/storefront-config/${salesChannelId}`,
313
- body
314
- );
315
- }
316
- // -----------------------------------------------------------------------
317
- // 3.12 — Site Designer Config: Read
318
- // -----------------------------------------------------------------------
319
- /**
320
- * Read the active Site Designer configuration for a channel, including the
321
- * last 10 history entries.
322
- *
323
- * `GET /admin/thor/site-config/:sales_channel_id`
324
- */
325
- async getSiteConfig(salesChannelId) {
326
- return this.request(
327
- "GET",
328
- `/admin/thor/site-config/${salesChannelId}`
329
- );
330
- }
331
- // -----------------------------------------------------------------------
332
- // 3.13 — Site Designer Config: Update
333
- // -----------------------------------------------------------------------
334
- /**
335
- * Update the Site Designer configuration for a channel.
336
- * Creates a new history entry on every PUT.
337
- *
338
- * `PUT /admin/thor/site-config/:sales_channel_id`
339
- */
340
- async updateSiteConfig(salesChannelId, body) {
341
- return this.request(
342
- "PUT",
343
- `/admin/thor/site-config/${salesChannelId}`,
344
- body
345
- );
346
- }
347
- // -----------------------------------------------------------------------
348
- // 3.14 — Site Designer Config: History
349
- // -----------------------------------------------------------------------
350
- /**
351
- * Full paginated history of Site Designer versions for a channel.
352
- * Entries are immutable — they are never deleted.
353
- *
354
- * `GET /admin/thor/site-config/:sales_channel_id/history`
355
- */
356
- async getSiteConfigHistory(salesChannelId, options = {}) {
357
- const { limit = 20, offset = 0 } = options;
358
- return this.request(
359
- "GET",
360
- `/admin/thor/site-config/${salesChannelId}/history?limit=${limit}&offset=${offset}`
361
- );
362
- }
363
- // -----------------------------------------------------------------------
364
- // 3.15 — Site Designer Config: Restore
365
- // -----------------------------------------------------------------------
366
- /**
367
- * Restore a previous Site Designer version.
368
- * Internally runs the update workflow with the stored config of the target
369
- * version — this creates a **new** history entry and does NOT mutate past
370
- * entries.
371
- *
372
- * `POST /admin/thor/site-config/:sales_channel_id/restore/:version`
373
- */
374
- async restoreSiteConfig(salesChannelId, version) {
375
- return this.request(
376
- "POST",
377
- `/admin/thor/site-config/${salesChannelId}/restore/${encodeURIComponent(version)}`
378
- );
379
- }
380
- };
381
-
382
- // src/dropshipper.ts
383
- var import_adapters3 = require("@thorprovider/adapters");
384
- var DropshipperClient = class {
385
- baseUrl;
386
- token;
387
- logger;
388
- constructor(config) {
389
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
390
- this.token = config.token;
391
- this.logger = (0, import_adapters3.createLogger)("DropshipperClient", config.debug);
392
- }
393
- // -------------------------------------------------------------------------
394
- // Private — HTTP helper
395
- // -------------------------------------------------------------------------
396
- async request(method, path, body) {
397
- const url = `${this.baseUrl}${path}`;
398
- this.logger.debug(`[dropshipper] ${method} ${path}`);
399
- const headers = {
400
- Authorization: `Bearer ${this.token}`,
401
- "Content-Type": "application/json"
402
- };
403
- const init = {
404
- method,
405
- headers,
406
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
407
- };
408
- let response;
409
- try {
410
- response = await fetchBackendWithResilience(url, init);
411
- } catch (networkError) {
412
- throw new import_adapters3.ProviderAPIError(
413
- `[dropshipper] Network error on ${method} ${path}: ${networkError.message}`,
414
- "NETWORK_ERROR",
415
- networkError
416
- );
417
- }
418
- if (!response.ok) {
419
- let message = `HTTP ${response.status}`;
420
- try {
421
- const json = await response.json();
422
- message = json?.message ?? message;
423
- } catch {
424
- }
425
- throw new import_adapters3.ProviderAPIError(
426
- `[dropshipper] ${method} ${path} failed: ${message}`,
427
- `DROPSHIPPER_API_${response.status}`,
428
- response.status
429
- );
430
- }
431
- return response.json();
432
- }
433
- // -------------------------------------------------------------------------
434
- // Unified Query
435
- // -------------------------------------------------------------------------
436
- /**
437
- * Resolve multiple entities in a single request.
438
- *
439
- * `POST /admin/thor/dropshipper/query`
440
- *
441
- * Entities are resolved in parallel (per layer) and errors are isolated per
442
- * entity: `response.errors[key]` holds the per-entity error while the rest
443
- * of `data` still resolves. `data[key]` is an array (list entities) or a
444
- * single object (singular entities such as account, balance, me).
445
- *
446
- * @example
447
- * ```typescript
448
- * const { data } = await client.query({
449
- * entities: [
450
- * { entity: 'capabilities' },
451
- * { entity: 'me' },
452
- * { entity: 'account' },
453
- * ],
454
- * });
455
- * ```
456
- */
457
- async query(input) {
458
- return this.request(
459
- "POST",
460
- "/admin/thor/dropshipper/query",
461
- input
462
- );
463
- }
464
- // -------------------------------------------------------------------------
465
- // Capabilities
466
- // -------------------------------------------------------------------------
467
- /**
468
- * Fetch dashboard capabilities from the backend.
469
- *
470
- * `GET /admin/thor/dropshipper/capabilities`
471
- */
472
- async getCapabilities() {
473
- return this.request(
474
- "GET",
475
- "/admin/thor/dropshipper/capabilities"
476
- );
477
- }
478
- /**
479
- * Fetch the authenticated dropshipper's personal profile including
480
- * first_name, last_name, email, avatar_url, and linked sales channel.
481
- *
482
- * `GET /admin/thor/dropshipper/me`
483
- */
484
- async getMyProfile() {
485
- return this.request(
486
- "GET",
487
- "/admin/thor/dropshipper/me"
488
- );
489
- }
490
- /**
491
- * Send a chat message to the AI assistant (catalog intelligence).
492
- * The conversation is stateless — the client sends the full message
493
- * history on every request.
494
- *
495
- * `POST /admin/thor/dropshipper/ai/chat`
496
- *
497
- * @example
498
- * ```typescript
499
- * const { answer, sources } = await client.chatAssistant({
500
- * messages: [{ role: 'user', content: 'productos con mejor margen' }],
501
- * });
502
- * ```
503
- */
504
- async chatAssistant(body) {
505
- return this.request(
506
- "POST",
507
- "/admin/thor/dropshipper/ai/chat",
508
- body
509
- );
510
- }
511
- /**
512
- * Stream the AI assistant's reply.
513
- *
514
- * Unlike `chatAssistant`, this surfaces the model's progress: the backend
515
- * resolves the intent first and then streams the answer token by token
516
- * (catalog searches) or returns the full answer in one shot (`default`).
517
- * The response is normalized into a single `ReadableStream<ChatStreamEvent>`
518
- * so callers can show a live "thinking" label and render text incrementally.
519
- *
520
- * `POST /admin/thor/dropshipper/ai/chat`
521
- */
522
- async chatAssistantStream(body) {
523
- const url = `${this.baseUrl}/admin/thor/dropshipper/ai/chat`;
524
- this.logger.debug("[dropshipper] POST /admin/thor/dropshipper/ai/chat (stream)");
525
- const init = {
526
- method: "POST",
527
- headers: {
528
- Authorization: `Bearer ${this.token}`,
529
- "Content-Type": "application/json",
530
- Accept: "text/event-stream"
531
- },
532
- body: JSON.stringify(body)
533
- };
534
- let response;
535
- try {
536
- response = await fetchBackendWithResilience(url, init, {
537
- timeoutMs: 6e4,
538
- maxRetries: 1
539
- });
540
- } catch (networkError) {
541
- throw new import_adapters3.ProviderAPIError(
542
- `[dropshipper] Network error on POST /admin/thor/dropshipper/ai/chat: ${networkError.message}`,
543
- "NETWORK_ERROR",
544
- networkError
545
- );
546
- }
547
- if (!response.ok) {
548
- let message = `HTTP ${response.status}`;
549
- let errorCode;
550
- let requestId;
551
- let details;
552
- try {
553
- const json = await response.json();
554
- message = json?.message ?? message;
555
- errorCode = json?.error_code ?? json?.type;
556
- requestId = json?.request_id;
557
- details = json?.details;
558
- } catch {
559
- }
560
- this.logger.error(
561
- `[dropshipper] POST /admin/thor/dropshipper/ai/chat failed status=${response.status} message=${message}` + (errorCode ? ` error_code=${errorCode}` : "") + (requestId ? ` request_id=${requestId}` : "") + (details ? ` details=${details}` : "")
562
- );
563
- throw new import_adapters3.ProviderAPIError(
564
- `[dropshipper] POST /admin/thor/dropshipper/ai/chat failed: ${message}`,
565
- `DROPSHIPPER_API_${response.status}`,
566
- response.status,
567
- {
568
- message,
569
- status: response.status,
570
- errorCode,
571
- requestId,
572
- details
573
- }
574
- );
575
- }
576
- const contentType = response.headers.get("content-type") ?? "";
577
- if (contentType.includes("text/event-stream") && response.body) {
578
- return mapUiMessageStreamToEvents(response.body, this.logger);
579
- }
580
- const data = await response.json();
581
- return new ReadableStream({
582
- start(controller) {
583
- controller.enqueue({ type: "start", intent: data.intent });
584
- controller.enqueue({ type: "text-delta", delta: data.answer });
585
- controller.enqueue({
586
- type: "finish",
587
- intent: data.intent,
588
- sources: data.sources ?? []
589
- });
590
- controller.close();
591
- }
592
- });
593
- }
594
- /**
595
- * Cheap liveness probe for the AI assistant.
596
- *
597
- * The backend performs no LLM or retrieval work, so this is safe to poll
598
- * (e.g. from a dashboard availability indicator). Returns 200 with
599
- * `available: true` when the assistant is configured; the backend answers
600
- * HTTP 503 with `available: false` when `AI_GATEWAY_API_KEY` is missing.
601
- *
602
- * Deliberately does NOT go through `fetchBackendWithResilience`: that layer
603
- * funnels every call through the SHARED `backendCircuitBreaker`, and the
604
- * definitive 503 "not configured" answer would count as failures and could
605
- * open the circuit, taking down all dropshipper API traffic. A health probe
606
- * must stay isolated, with no retries and a short timeout.
607
- *
608
- * `GET /admin/thor/dropshipper/ai/health`
609
- */
610
- async chatAssistantHealth() {
611
- const url = `${this.baseUrl}/admin/thor/dropshipper/ai/health`;
612
- const controller = new AbortController();
613
- const timeoutId = setTimeout(() => controller.abort(), 5e3);
614
- let response;
615
- try {
616
- response = await fetch(url, {
617
- method: "GET",
618
- headers: { Authorization: `Bearer ${this.token}` },
619
- signal: controller.signal,
620
- cache: "no-store"
621
- });
622
- } catch (error) {
623
- clearTimeout(timeoutId);
624
- throw new import_adapters3.ProviderAPIError(
625
- `[dropshipper] Network error on GET /admin/thor/dropshipper/ai/health: ${error.message}`,
626
- "NETWORK_ERROR",
627
- 0
628
- );
629
- }
630
- clearTimeout(timeoutId);
631
- if (response.status === 503) {
632
- try {
633
- const body = await response.json();
634
- if (body && typeof body.available === "boolean") {
635
- return body;
636
- }
637
- } catch {
638
- }
639
- }
640
- if (!response.ok) {
641
- throw new import_adapters3.ProviderAPIError(
642
- `[dropshipper] GET /admin/thor/dropshipper/ai/health failed: HTTP ${response.status}`,
643
- `DROPSHIPPER_API_${response.status}`,
644
- response.status
645
- );
646
- }
647
- return response.json();
648
- }
649
- // -------------------------------------------------------------------------
650
- // Notifications
651
- // -------------------------------------------------------------------------
652
- /**
653
- * List feed notifications for the authenticated dropshipper.
654
- *
655
- * `GET /admin/thor/dropshipper/notifications`
656
- */
657
- async getNotifications(options = {}) {
658
- const { limit = 20, offset = 0 } = options;
659
- const qs = new URLSearchParams({
660
- limit: String(limit),
661
- offset: String(offset)
662
- });
663
- return this.request(
664
- "GET",
665
- `/admin/thor/dropshipper/notifications?${qs}`
666
- );
667
- }
668
- /**
669
- * Get the authenticated dropshipper's notification preferences.
670
- *
671
- * `GET /admin/thor/dropshipper/notifications/preferences`
672
- */
673
- async getNotificationPreferences() {
674
- return this.request(
675
- "GET",
676
- "/admin/thor/dropshipper/notifications/preferences"
677
- );
678
- }
679
- /**
680
- * Update the authenticated dropshipper's notification preferences.
681
- *
682
- * `PATCH /admin/thor/dropshipper/notifications/preferences`
683
- */
684
- async updateNotificationPreferences(body) {
685
- return this.request(
686
- "PATCH",
687
- "/admin/thor/dropshipper/notifications/preferences",
688
- body
689
- );
690
- }
691
- // -------------------------------------------------------------------------
692
- // Onboarding (Solo X)
693
- // -------------------------------------------------------------------------
694
- /**
695
- * Create a new dropshipper account (sales channel + user + price list).
696
- *
697
- * `POST /admin/thor/dropshipper/onboard`
698
- */
699
- async onboardDropshipper(body) {
700
- return this.request(
701
- "POST",
702
- "/admin/thor/dropshipper/onboard",
703
- body
704
- );
705
- }
706
- // -------------------------------------------------------------------------
707
- // Products (Solo Y)
708
- // -------------------------------------------------------------------------
709
- /**
710
- * List products available in Y's channel with cost/margin data.
711
- *
712
- * `GET /admin/thor/dropshipper/products`
713
- */
714
- async getProducts(options = {}) {
715
- const { q, category_id, collection_id, status, in_stock, limit = 20, offset = 0 } = options;
716
- const qs = new URLSearchParams({
717
- limit: String(limit),
718
- offset: String(offset),
719
- ...q ? { q } : {},
720
- ...category_id ? { category_id } : {},
721
- ...collection_id ? { collection_id } : {},
722
- ...status ? { status } : {},
723
- ...in_stock !== void 0 ? { in_stock: String(in_stock) } : {}
724
- });
725
- return this.request(
726
- "GET",
727
- `/admin/thor/dropshipper/products?${qs}`
728
- );
729
- }
730
- /**
731
- * Validate cart items for checkout — returns current availableQuantity, sale_price,
732
- * and cost_price for each variant so the client can detect stale prices or
733
- * insufficient stock before creating an order or converting a draft.
734
- *
735
- * `POST /admin/thor/dropshipper/checkout/validate`
736
- */
737
- async validateCheckoutItems(body) {
738
- return this.request(
739
- "POST",
740
- "/admin/thor/dropshipper/checkout/validate",
741
- body
742
- );
743
- }
744
- /**
745
- * Check whether cost prices have changed since the last acknowledgment.
746
- * Compares a hash of all base cost prices from the channel's price list
747
- * against a stored snapshot on the dropshipper account.
748
- *
749
- * `GET /admin/thor/dropshipper/cost-prices/has-changes`
750
- */
751
- async checkCostPriceChanges() {
752
- return this.request(
753
- "GET",
754
- "/admin/thor/dropshipper/cost-prices/has-changes"
755
- );
756
- }
757
- /**
758
- * Get the full diff of cost price changes since the last acknowledgment.
759
- * Returns product/variant info with old and new cost prices.
760
- *
761
- * `GET /admin/thor/dropshipper/cost-prices/changes`
762
- */
763
- async getCostPriceChanges() {
764
- return this.request(
765
- "GET",
766
- "/admin/thor/dropshipper/cost-prices/changes"
767
- );
768
- }
769
- /**
770
- * Acknowledge current cost prices as reviewed. Stores the current hash
771
- * and snapshot so subsequent checks will not report these prices as changed.
772
- *
773
- * `POST /admin/thor/dropshipper/cost-prices/acknowledge`
774
- */
775
- async acknowledgeCostPriceChanges() {
776
- return this.request(
777
- "POST",
778
- "/admin/thor/dropshipper/cost-prices/acknowledge"
779
- );
780
- }
781
- /**
782
- * Toggle whether a product is visible in the public store for the current sales channel.
783
- * This does not mutate the shared global Medusa product status.
784
- *
785
- * `POST /admin/thor/dropshipper/products/:id/status`
786
- */
787
- async updateProductStatus(productId, body) {
788
- return this.request(
789
- "POST",
790
- `/admin/thor/dropshipper/products/${productId}/status`,
791
- body
792
- );
793
- }
794
- /**
795
- * Fetch custom attribute values assigned to a product, grouped by attribute.
796
- *
797
- * `GET /admin/thor/dropshipper/products/:id/attributes`
798
- */
799
- async getProductAttributes(productId) {
800
- return this.request(
801
- "GET",
802
- `/admin/thor/dropshipper/products/${productId}/attributes`
803
- );
804
- }
805
- /**
806
- * List attribute definitions (with their possible values) scoped to the
807
- * dropshipper's channel. Only attributes linked to at least one channel
808
- * product are returned.
809
- *
810
- * `GET /admin/thor/dropshipper/attributes`
811
- */
812
- async getAttributes() {
813
- return this.request(
814
- "GET",
815
- "/admin/thor/dropshipper/attributes"
816
- );
817
- }
818
- // -------------------------------------------------------------------------
819
- // Prices (Solo Y)
820
- // -------------------------------------------------------------------------
821
- /**
822
- * Bulk-update product and variant margins on Y's channel price list.
823
- *
824
- * `PUT /admin/thor/dropshipper/prices`
825
- */
826
- async updatePrices(body) {
827
- return this.request(
828
- "PUT",
829
- "/admin/thor/dropshipper/prices",
830
- body
831
- );
832
- }
833
- // -------------------------------------------------------------------------
834
- // Orders (Y + X for set-payment-collector)
835
- // -------------------------------------------------------------------------
836
- /**
837
- * Paginated list of orders in Y's channel.
838
- *
839
- * `GET /admin/thor/dropshipper/orders`
840
- */
841
- async getOrders(options = {}) {
842
- const { status, payment_collector, settlement_status, from, to, q, customer_id, limit = 20, offset = 0 } = options;
843
- const qs = new URLSearchParams({
844
- limit: String(limit),
845
- offset: String(offset),
846
- ...status ? { status } : {},
847
- ...payment_collector ? { payment_collector } : {},
848
- ...settlement_status ? { settlement_status } : {},
849
- ...from ? { from } : {},
850
- ...to ? { to } : {},
851
- ...q ? { q } : {},
852
- ...customer_id ? { customer_id } : {}
853
- });
854
- return this.request(
855
- "GET",
856
- `/admin/thor/dropshipper/orders?${qs}`
857
- );
858
- }
859
- /**
860
- * Full detail for a single order with profit breakdown.
861
- *
862
- * `GET /admin/thor/dropshipper/orders/:id`
863
- */
864
- async getOrder(orderId) {
865
- return this.request(
866
- "GET",
867
- `/admin/thor/dropshipper/orders/${orderId}`
868
- );
869
- }
870
- /**
871
- * List shipping groups and their valid options for a manual dropshipper order.
872
- *
873
- * `POST /admin/thor/dropshipper/orders/shipping-options`
874
- */
875
- async getOrderShippingOptions(body) {
876
- return this.request(
877
- "POST",
878
- "/admin/thor/dropshipper/orders/shipping-options",
879
- {
880
- ...body,
881
- currency_code: body.currency_code.toLowerCase()
882
- }
883
- );
884
- }
885
- /**
886
- * Manually create an order on behalf of a customer.
887
- *
888
- * `POST /admin/thor/dropshipper/orders`
889
- */
890
- async createOrder(body) {
891
- return this.request(
892
- "POST",
893
- "/admin/thor/dropshipper/orders",
894
- body
895
- );
896
- }
897
- /**
898
- * Validate a gift card code for the dropshipper's channel (existence, status,
899
- * currency and channel restriction). Balance is returned when valid.
900
- *
901
- * `POST /admin/thor/dropshipper/gift-cards/validate`
902
- */
903
- async validateGiftCard(body) {
904
- return this.request(
905
- "POST",
906
- "/admin/thor/dropshipper/gift-cards/validate",
907
- body
908
- );
909
- }
910
- /**
911
- * Preview order totals (including taxes) without creating the order.
912
- *
913
- * Replicates the creation pipeline (pricing honoring `unit_price`, region,
914
- * shipping groups) and computes tax lines with the Medusa tax module, so the
915
- * totals match what the created order will produce.
916
- *
917
- * `POST /admin/thor/dropshipper/orders/preview-totals`
918
- */
919
- async previewOrderTotals(body) {
920
- return this.request(
921
- "POST",
922
- "/admin/thor/dropshipper/orders/preview-totals",
923
- {
924
- ...body,
925
- currency_code: body.currency_code.toLowerCase()
926
- }
927
- );
928
- }
929
- /**
930
- * Set who collects payment for an order (Solo X).
931
- *
932
- * `POST /admin/thor/dropshipper/orders/:id/set-payment-collector`
933
- */
934
- async setPaymentCollector(orderId, body) {
935
- return this.request(
936
- "POST",
937
- `/admin/thor/dropshipper/orders/${orderId}/set-payment-collector`,
938
- body
939
- );
940
- }
941
- /**
942
- * Change the payment method of a confirmed order.
943
- *
944
- * `POST /admin/thor/dropshipper/orders/:id/set-payment-method`
945
- */
946
- async setPaymentMethod(orderId, body) {
947
- return this.request(
948
- "POST",
949
- `/admin/thor/dropshipper/orders/${orderId}/set-payment-method`,
950
- body
951
- );
952
- }
953
- // -------------------------------------------------------------------------
954
- // Order Cancel & Edits (Solo Y) — B-04
955
- // -------------------------------------------------------------------------
956
- /**
957
- * Cancel a dropshipper order.
958
- *
959
- * `POST /admin/thor/dropshipper/orders/:id/cancel`
960
- */
961
- async cancelOrder(orderId) {
962
- return this.request(
963
- "POST",
964
- `/admin/thor/dropshipper/orders/${orderId}/cancel`
965
- );
966
- }
967
- /**
968
- * Create an order edit for a dropshipper order.
969
- *
970
- * `POST /admin/thor/dropshipper/orders/:id/edit`
971
- */
972
- async createOrderEdit(orderId, body = {}) {
973
- return this.request(
974
- "POST",
975
- `/admin/thor/dropshipper/orders/${orderId}/edit`,
976
- body
977
- );
978
- }
979
- /**
980
- * Add an item to the active order edit.
981
- *
982
- * `POST /admin/thor/dropshipper/orders/:id/edit/items`
983
- */
984
- async addOrderEditItem(orderId, body) {
985
- return this.request(
986
- "POST",
987
- `/admin/thor/dropshipper/orders/${orderId}/edit/items`,
988
- body
989
- );
990
- }
991
- /**
992
- * Confirm the active order edit, applying changes to the order.
993
- *
994
- * `POST /admin/thor/dropshipper/orders/:id/edit/confirm`
995
- */
996
- async confirmOrderEdit(orderId) {
997
- return this.request(
998
- "POST",
999
- `/admin/thor/dropshipper/orders/${orderId}/edit/confirm`
1000
- );
1001
- }
1002
- /**
1003
- * Get all notes for an order.
1004
- *
1005
- * `GET /admin/thor/dropshipper/orders/:id/notes`
1006
- */
1007
- async getOrderNotes(orderId) {
1008
- return this.request(
1009
- "GET",
1010
- `/admin/thor/dropshipper/orders/${orderId}/notes`
1011
- );
1012
- }
1013
- /**
1014
- * Create a new note for an order.
1015
- *
1016
- * `POST /admin/thor/dropshipper/orders/:id/notes`
1017
- */
1018
- async createOrderNote(orderId, body) {
1019
- return this.request(
1020
- "POST",
1021
- `/admin/thor/dropshipper/orders/${orderId}/notes`,
1022
- body
1023
- );
1024
- }
1025
- /**
1026
- * Delete a note from an order.
1027
- *
1028
- * `DELETE /admin/thor/dropshipper/orders/:id/notes/:noteId`
1029
- */
1030
- async deleteOrderNote(orderId, noteId) {
1031
- return this.request(
1032
- "DELETE",
1033
- `/admin/thor/dropshipper/orders/${orderId}/notes/${noteId}`
1034
- );
1035
- }
1036
- // -------------------------------------------------------------------------
1037
- // Custom Categories (Solo Y)
1038
- // -------------------------------------------------------------------------
1039
- /**
1040
- * List Medusa provider categories linked to Y's channel (read-only).
1041
- *
1042
- * `GET /admin/thor/dropshipper/categories/provider`
1043
- */
1044
- async getProviderCategories() {
1045
- return this.request(
1046
- "GET",
1047
- "/admin/thor/dropshipper/categories/provider"
1048
- );
1049
- }
1050
- /**
1051
- * List Y's custom product categories.
1052
- *
1053
- * `GET /admin/thor/dropshipper/categories`
1054
- */
1055
- async getCategories(options = {}) {
1056
- const { parent_id, include_children } = options;
1057
- const qs = new URLSearchParams({
1058
- ...parent_id ? { parent_id } : {},
1059
- ...include_children !== void 0 ? { include_children: String(include_children) } : {}
1060
- });
1061
- const query = qs.toString() ? `?${qs}` : "";
1062
- return this.request(
1063
- "GET",
1064
- `/admin/thor/dropshipper/categories${query}`
1065
- );
1066
- }
1067
- /**
1068
- * Create a custom category in Y's channel.
1069
- *
1070
- * `POST /admin/thor/dropshipper/categories`
1071
- */
1072
- async createCategory(body) {
1073
- return this.request(
1074
- "POST",
1075
- "/admin/thor/dropshipper/categories",
1076
- body
1077
- );
1078
- }
1079
- /**
1080
- * Update a custom category.
1081
- *
1082
- * `PUT /admin/thor/dropshipper/categories/:id`
1083
- */
1084
- async updateCategory(categoryId, body) {
1085
- return this.request(
1086
- "PUT",
1087
- `/admin/thor/dropshipper/categories/${categoryId}`,
1088
- body
1089
- );
1090
- }
1091
- /**
1092
- * Delete a custom category.
1093
- *
1094
- * `DELETE /admin/thor/dropshipper/categories/:id`
1095
- */
1096
- async deleteCategory(categoryId, options = {}) {
1097
- const qs = options.force ? "?force=true" : "";
1098
- return this.request(
1099
- "DELETE",
1100
- `/admin/thor/dropshipper/categories/${categoryId}${qs}`
1101
- );
1102
- }
1103
- /**
1104
- * List product-to-category mappings, optionally filtered by product.
1105
- *
1106
- * `GET /admin/thor/dropshipper/category-mappings`
1107
- */
1108
- async getCategoryMappings(options = {}) {
1109
- const qs = options.product_id ? `?product_id=${options.product_id}` : "";
1110
- return this.request(
1111
- "GET",
1112
- `/admin/thor/dropshipper/category-mappings${qs}`
1113
- );
1114
- }
1115
- /**
1116
- * Map a product to a custom category.
1117
- *
1118
- * `POST /admin/thor/dropshipper/category-mappings`
1119
- */
1120
- async createCategoryMapping(body) {
1121
- return this.request(
1122
- "POST",
1123
- `/admin/thor/dropshipper/category-mappings`,
1124
- body
1125
- );
1126
- }
1127
- /**
1128
- * Remove a product-to-category mapping.
1129
- *
1130
- * `DELETE /admin/thor/dropshipper/category-mappings/:id`
1131
- */
1132
- async deleteCategoryMapping(mappingId) {
1133
- return this.request(
1134
- "DELETE",
1135
- `/admin/thor/dropshipper/category-mappings/${mappingId}`
1136
- );
1137
- }
1138
- // -------------------------------------------------------------------------
1139
- // Customers (Solo Y)
1140
- // -------------------------------------------------------------------------
1141
- /**
1142
- * Paginated list of customers in Y's channel.
1143
- *
1144
- * `GET /admin/thor/dropshipper/customers`
1145
- */
1146
- async getCustomers(options = {}) {
1147
- const { q, has_orders, from, limit = 20, offset = 0, order } = options;
1148
- const qs = new URLSearchParams({
1149
- limit: String(limit),
1150
- offset: String(offset),
1151
- ...q ? { q } : {},
1152
- ...has_orders !== void 0 ? { has_orders: String(has_orders) } : {},
1153
- ...from ? { from } : {},
1154
- ...order ? { order } : {}
1155
- });
1156
- return this.request(
1157
- "GET",
1158
- `/admin/thor/dropshipper/customers?${qs}`
1159
- );
1160
- }
1161
- /**
1162
- * Backwards-compatible alias used by the dashboard checkout flow.
1163
- */
1164
- async getChannelCustomers(_channelId, options = {}) {
1165
- return this.getCustomers(options);
1166
- }
1167
- /**
1168
- * Full detail for a single customer.
1169
- *
1170
- * `GET /admin/thor/dropshipper/customers/:id`
1171
- */
1172
- async getCustomer(customerId) {
1173
- return this.request(
1174
- "GET",
1175
- `/admin/thor/dropshipper/customers/${customerId}`
1176
- );
1177
- }
1178
- /**
1179
- * Create a customer scoped to Y's channel.
1180
- *
1181
- * `POST /admin/thor/dropshipper/customers`
1182
- */
1183
- async createCustomer(body) {
1184
- return this.request(
1185
- "POST",
1186
- "/admin/thor/dropshipper/customers",
1187
- body
1188
- );
1189
- }
1190
- /**
1191
- * Update a customer scoped to Y's channel.
1192
- *
1193
- * `POST /admin/thor/dropshipper/customers/:id`
1194
- */
1195
- async updateCustomer(customerId, body) {
1196
- return this.request(
1197
- "POST",
1198
- `/admin/thor/dropshipper/customers/${customerId}`,
1199
- body
1200
- );
1201
- }
1202
- // -------------------------------------------------------------------------
1203
- // Customer Addresses (Solo Y) — B-06
1204
- // -------------------------------------------------------------------------
1205
- /**
1206
- * Transform a raw snake_case address from the API into a camelCase Address.
1207
- */
1208
- transformAddress(raw) {
1209
- return {
1210
- id: raw.id ?? void 0,
1211
- firstName: raw.first_name ?? "",
1212
- lastName: raw.last_name ?? "",
1213
- company: raw.company ?? void 0,
1214
- address1: raw.address_1 ?? "",
1215
- address2: raw.address_2 ?? void 0,
1216
- city: raw.city ?? "",
1217
- province: raw.province ?? "",
1218
- postalCode: raw.postal_code ?? "",
1219
- countryCode: raw.country_code ?? "",
1220
- phone: raw.phone ?? void 0,
1221
- isDefault: raw.is_default ?? void 0,
1222
- isDefaultBilling: raw.is_default_billing ?? void 0,
1223
- isDefaultShipping: raw.is_default_shipping ?? void 0,
1224
- metadata: raw.address_name ? { ...raw.metadata ?? {}, label: raw.address_name } : raw.metadata ?? void 0
1225
- };
1226
- }
1227
- /**
1228
- * List addresses for a customer in Y's channel.
1229
- *
1230
- * `GET /admin/thor/dropshipper/customers/:id/addresses`
1231
- */
1232
- async getCustomerAddresses(customerId) {
1233
- const raw = await this.request("GET", `/admin/thor/dropshipper/customers/${customerId}/addresses`);
1234
- return {
1235
- addresses: raw.addresses.map((a) => this.transformAddress(a)),
1236
- count: raw.count
1237
- };
1238
- }
1239
- /**
1240
- * Create a new address for a customer.
1241
- *
1242
- * `POST /admin/thor/dropshipper/customers/:id/addresses`
1243
- */
1244
- async createCustomerAddress(customerId, body) {
1245
- const raw = await this.request(
1246
- "POST",
1247
- `/admin/thor/dropshipper/customers/${customerId}/addresses`,
1248
- body
1249
- );
1250
- return { address: this.transformAddress(raw.address) };
1251
- }
1252
- /**
1253
- * Update an existing customer address.
1254
- *
1255
- * `POST /admin/thor/dropshipper/customers/:id/addresses/:addressId`
1256
- */
1257
- async updateCustomerAddress(customerId, addressId, body) {
1258
- const raw = await this.request(
1259
- "POST",
1260
- `/admin/thor/dropshipper/customers/${customerId}/addresses/${addressId}`,
1261
- body
1262
- );
1263
- return { address: this.transformAddress(raw.address) };
1264
- }
1265
- /**
1266
- * Delete a customer address.
1267
- *
1268
- * `DELETE /admin/thor/dropshipper/customers/:id/addresses/:addressId`
1269
- */
1270
- async deleteCustomerAddress(customerId, addressId) {
1271
- return this.request(
1272
- "DELETE",
1273
- `/admin/thor/dropshipper/customers/${customerId}/addresses/${addressId}`
1274
- );
1275
- }
1276
- // -------------------------------------------------------------------------
1277
- // Account & Settlements (Y read-only)
1278
- // -------------------------------------------------------------------------
1279
- /**
1280
- * Y's account info with current balance.
1281
- *
1282
- * `GET /admin/thor/dropshipper/account`
1283
- */
1284
- async getAccount() {
1285
- return this.request(
1286
- "GET",
1287
- "/admin/thor/dropshipper/account"
1288
- );
1289
- }
1290
- /**
1291
- * Get the authenticated dropshipper's business policy text.
1292
- * Returns an empty string when no policy is set.
1293
- *
1294
- * `GET /admin/thor/dropshipper/account/policies`
1295
- */
1296
- async getBusinessPolicy() {
1297
- return this.request(
1298
- "GET",
1299
- "/admin/thor/dropshipper/account/policies"
1300
- );
1301
- }
1302
- /**
1303
- * Update the authenticated dropshipper's business policy text.
1304
- * The value is trimmed server-side before being persisted.
1305
- *
1306
- * `PATCH /admin/thor/dropshipper/account/policies`
1307
- */
1308
- async updateBusinessPolicy(body) {
1309
- return this.request(
1310
- "PATCH",
1311
- "/admin/thor/dropshipper/account/policies",
1312
- body
1313
- );
1314
- }
1315
- /**
1316
- * Orders where Y owes money to X (Y collected payment, needs to pay costs).
1317
- *
1318
- * `GET /admin/thor/dropshipper/account/payable`
1319
- */
1320
- async getPayable() {
1321
- return this.request(
1322
- "GET",
1323
- "/admin/thor/dropshipper/account/payable"
1324
- );
1325
- }
1326
- /**
1327
- * Orders where X owes money to Y (X collected COD, needs to transfer profit).
1328
- *
1329
- * `GET /admin/thor/dropshipper/account/receivable`
1330
- */
1331
- async getReceivable() {
1332
- return this.request(
1333
- "GET",
1334
- "/admin/thor/dropshipper/account/receivable"
1335
- );
1336
- }
1337
- /**
1338
- * List settlements (Y sees own; X can filter by account_id).
1339
- *
1340
- * `GET /admin/thor/dropshipper/settlements`
1341
- */
1342
- async getSettlements(options = {}) {
1343
- const { status, type, account_id, limit = 20, offset = 0 } = options;
1344
- const qs = new URLSearchParams({
1345
- limit: String(limit),
1346
- offset: String(offset),
1347
- ...status ? { status } : {},
1348
- ...type ? { type } : {},
1349
- ...account_id ? { account_id } : {}
1350
- });
1351
- return this.request(
1352
- "GET",
1353
- `/admin/thor/dropshipper/settlements?${qs}`
1354
- );
1355
- }
1356
- /**
1357
- * Full detail for a single settlement record.
1358
- *
1359
- * `GET /admin/thor/dropshipper/settlements/:id`
1360
- */
1361
- async getSettlement(settlementId) {
1362
- return this.request(
1363
- "GET",
1364
- `/admin/thor/dropshipper/settlements/${settlementId}`
1365
- );
1366
- }
1367
- /**
1368
- * Consolidated financial balance for the authenticated dropshipper.
1369
- *
1370
- * `GET /admin/thor/dropshipper/account/balance`
1371
- */
1372
- async getAccountBalance() {
1373
- return this.request(
1374
- "GET",
1375
- "/admin/thor/dropshipper/account/balance"
1376
- );
1377
- }
1378
- /**
1379
- * Unified financial order list for the authenticated dropshipper.
1380
- *
1381
- * `GET /admin/thor/dropshipper/account/orders`
1382
- */
1383
- async getAccountOrders(options = {}) {
1384
- const { tab, status, limit = 20, offset = 0, q } = options;
1385
- const qs = new URLSearchParams({
1386
- limit: String(limit),
1387
- offset: String(offset),
1388
- ...tab ? { tab } : {},
1389
- ...status ? { status } : {},
1390
- ...q ? { q } : {}
1391
- });
1392
- return this.request(
1393
- "GET",
1394
- `/admin/thor/dropshipper/account/orders?${qs}`
1395
- );
1396
- }
1397
- // -------------------------------------------------------------------------
1398
- // Admin Settlements (Solo X)
1399
- // -------------------------------------------------------------------------
1400
- /**
1401
- * Create a settlement record for a dropshipper account.
1402
- *
1403
- * `POST /admin/thor/dropshipper/admin/settlements`
1404
- */
1405
- async createSettlement(body) {
1406
- return this.request(
1407
- "POST",
1408
- "/admin/thor/dropshipper/admin/settlements",
1409
- body
1410
- );
1411
- }
1412
- /**
1413
- * Confirm a pending settlement (marks it as paid/received).
1414
- *
1415
- * `POST /admin/thor/dropshipper/admin/settlements/:id/confirm`
1416
- */
1417
- async confirmSettlement(settlementId, body = {}) {
1418
- return this.request(
1419
- "POST",
1420
- `/admin/thor/dropshipper/admin/settlements/${settlementId}/confirm`,
1421
- body
1422
- );
1423
- }
1424
- /**
1425
- * Cancel a pending settlement.
1426
- *
1427
- * `POST /admin/thor/dropshipper/admin/settlements/:id/cancel`
1428
- */
1429
- async cancelSettlement(settlementId, body = {}) {
1430
- return this.request(
1431
- "POST",
1432
- `/admin/thor/dropshipper/admin/settlements/${settlementId}/cancel`,
1433
- body
1434
- );
1435
- }
1436
- // -------------------------------------------------------------------------
1437
- // Admin Settlements — list (Solo X)
1438
- // -------------------------------------------------------------------------
1439
- /**
1440
- * X views all settlement records across all dropshipper accounts.
1441
- *
1442
- * `GET /admin/thor/dropshipper/admin/settlements`
1443
- */
1444
- async getAdminSettlements(options = {}) {
1445
- const { status, type, account_id, limit = 20, offset = 0 } = options;
1446
- const qs = new URLSearchParams({
1447
- limit: String(limit),
1448
- offset: String(offset),
1449
- ...status ? { status } : {},
1450
- ...type ? { type } : {},
1451
- ...account_id ? { account_id } : {}
1452
- });
1453
- return this.request(
1454
- "GET",
1455
- `/admin/thor/dropshipper/admin/settlements?${qs}`
1456
- );
1457
- }
1458
- // -------------------------------------------------------------------------
1459
- // Admin Account Management (Solo X)
1460
- // -------------------------------------------------------------------------
1461
- /**
1462
- * List all dropshipper accounts.
1463
- *
1464
- * `GET /admin/thor/dropshipper/admin/accounts`
1465
- */
1466
- async getAdminAccounts() {
1467
- return this.request(
1468
- "GET",
1469
- "/admin/thor/dropshipper/admin/accounts"
1470
- );
1471
- }
1472
- /**
1473
- * Full balance detail for a specific dropshipper account.
1474
- *
1475
- * `GET /admin/thor/dropshipper/admin/accounts/:id/balance`
1476
- */
1477
- async getAdminAccountBalance(accountId) {
1478
- return this.request(
1479
- "GET",
1480
- `/admin/thor/dropshipper/admin/accounts/${accountId}/balance`
1481
- );
1482
- }
1483
- /**
1484
- * List all dropshipper price lists.
1485
- *
1486
- * `GET /admin/thor/dropshipper/admin/price-lists`
1487
- */
1488
- async getAdminPriceLists() {
1489
- return this.request(
1490
- "GET",
1491
- "/admin/thor/dropshipper/admin/price-lists"
1492
- );
1493
- }
1494
- /**
1495
- * Utility: look up which sales channel a user belongs to.
1496
- *
1497
- * `GET /admin/thor/dropshipper/admin/user-channel`
1498
- */
1499
- async getUserChannel() {
1500
- return this.request(
1501
- "GET",
1502
- "/admin/thor/dropshipper/admin/user-channel"
1503
- );
1504
- }
1505
- // -------------------------------------------------------------------------
1506
- // Financial Endpoints — Group A (Admin X)
1507
- // -------------------------------------------------------------------------
1508
- /**
1509
- * List orders with financial detail for a dropshipper account (Admin only).
1510
- *
1511
- * `GET /admin/thor/dropshipper/admin/accounts/:id/orders`
1512
- */
1513
- async getAdminAccountOrders(accountId, options = {}) {
1514
- const { tab, status, limit = 20, offset = 0, q } = options;
1515
- const qs = new URLSearchParams({
1516
- limit: String(limit),
1517
- offset: String(offset),
1518
- ...tab ? { tab } : {},
1519
- ...status ? { status } : {},
1520
- ...q ? { q } : {}
1521
- });
1522
- return this.request(
1523
- "GET",
1524
- `/admin/thor/dropshipper/admin/accounts/${accountId}/orders?${qs}`
1525
- );
1526
- }
1527
- /**
1528
- * List financial movements for a dropshipper account (Admin only).
1529
- *
1530
- * `GET /admin/thor/dropshipper/admin/accounts/:id/settlements`
1531
- */
1532
- async getAdminAccountSettlements(accountId, options = {}) {
1533
- const { type, status, limit = 20, offset = 0 } = options;
1534
- const qs = new URLSearchParams({
1535
- limit: String(limit),
1536
- offset: String(offset),
1537
- ...type ? { type } : {},
1538
- ...status ? { status } : {}
1539
- });
1540
- return this.request(
1541
- "GET",
1542
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements?${qs}`
1543
- );
1544
- }
1545
- /**
1546
- * Manually resolve a guarantee on an order (Admin only).
1547
- *
1548
- * `POST /admin/thor/dropshipper/admin/accounts/:id/guarantee/:order_id`
1549
- */
1550
- async resolveGuarantee(accountId, orderId, body) {
1551
- return this.request(
1552
- "POST",
1553
- `/admin/thor/dropshipper/admin/accounts/${accountId}/guarantee/${orderId}`,
1554
- body
1555
- );
1556
- }
1557
- /**
1558
- * Create an internal compensation (netting) between DS and Thor debts (Admin only).
1559
- *
1560
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/compensacion`
1561
- */
1562
- async createCompensacion(accountId, body) {
1563
- return this.request(
1564
- "POST",
1565
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/compensacion`,
1566
- body
1567
- );
1568
- }
1569
- /**
1570
- * Create a financial adjustment (Admin only).
1571
- *
1572
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/ajuste`
1573
- */
1574
- async createAjuste(accountId, body) {
1575
- return this.request(
1576
- "POST",
1577
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/ajuste`,
1578
- body
1579
- );
1580
- }
1581
- // -------------------------------------------------------------------------
1582
- // Financial Endpoints — Group B (Admin X)
1583
- // -------------------------------------------------------------------------
1584
- /**
1585
- * Register a cobro — DS pays Thor the product cost (Admin only).
1586
- *
1587
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/cobro`
1588
- */
1589
- async createCobro(accountId, body) {
1590
- return this.request(
1591
- "POST",
1592
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/cobro`,
1593
- body
1594
- );
1595
- }
1596
- /**
1597
- * Register a pago — Thor pays the dropshipper their commission (Admin only).
1598
- *
1599
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/pago`
1600
- */
1601
- async createPago(accountId, body) {
1602
- return this.request(
1603
- "POST",
1604
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/pago`,
1605
- body
1606
- );
1607
- }
1608
- /**
1609
- * Reverse a confirmed financial movement (Admin only).
1610
- *
1611
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/:mov_id/reverso`
1612
- */
1613
- async reverseSettlement(accountId, movementId, body) {
1614
- return this.request(
1615
- "POST",
1616
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/${movementId}/reverso`,
1617
- body
1618
- );
1619
- }
1620
- /**
1621
- * Confirm a pending financial movement (Admin only).
1622
- *
1623
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/:mov_id/confirm`
1624
- */
1625
- async confirmSettlementMovement(accountId, movementId, body = {}) {
1626
- return this.request(
1627
- "POST",
1628
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/${movementId}/confirm`,
1629
- body
1630
- );
1631
- }
1632
- /**
1633
- * Cancel a pending financial movement draft (Admin only).
1634
- *
1635
- * `POST /admin/thor/dropshipper/admin/accounts/:id/settlements/:mov_id/cancel`
1636
- */
1637
- async cancelSettlementMovement(accountId, movementId, body) {
1638
- return this.request(
1639
- "POST",
1640
- `/admin/thor/dropshipper/admin/accounts/${accountId}/settlements/${movementId}/cancel`,
1641
- body
1642
- );
1643
- }
1644
- /**
1645
- * Get financial analysis for a dropshipper order (Admin only).
1646
- *
1647
- * `GET /admin/thor/dropshipper/admin/orders/:id/financial-analysis`
1648
- */
1649
- async getOrderFinancialAnalysis(orderId) {
1650
- return this.request(
1651
- "GET",
1652
- `/admin/thor/dropshipper/admin/orders/${orderId}/financial-analysis`
1653
- );
1654
- }
1655
- /**
1656
- * Register a partial or full payment for an order.
1657
- *
1658
- * `POST /admin/thor/dropshipper/orders/:id/payment`
1659
- */
1660
- async registerOrderPayment(orderId, body) {
1661
- return this.request(
1662
- "POST",
1663
- `/admin/thor/dropshipper/orders/${orderId}/payment`,
1664
- body
1665
- );
1666
- }
1667
- // -------------------------------------------------------------------------
1668
- // Promotions (Solo Y)
1669
- // -------------------------------------------------------------------------
1670
- /**
1671
- * List Y's promotions (discount codes).
1672
- *
1673
- * `GET /admin/thor/dropshipper/promotions`
1674
- */
1675
- async getPromotions(options = {}) {
1676
- const { type, limit = 20, offset = 0 } = options;
1677
- const qs = new URLSearchParams({
1678
- limit: String(limit),
1679
- offset: String(offset),
1680
- ...type ? { type } : {}
1681
- });
1682
- return this.request(
1683
- "GET",
1684
- `/admin/thor/dropshipper/promotions?${qs}`
1685
- );
1686
- }
1687
- /**
1688
- * Create a promotion for Y's channel.
1689
- *
1690
- * `POST /admin/thor/dropshipper/promotions`
1691
- */
1692
- async createPromotion(body) {
1693
- return this.request(
1694
- "POST",
1695
- "/admin/thor/dropshipper/promotions",
1696
- body
1697
- );
1698
- }
1699
- /**
1700
- * Get a single promotion by ID.
1701
- *
1702
- * `GET /admin/thor/dropshipper/promotions/:id`
1703
- */
1704
- async getPromotion(promotionId) {
1705
- return this.request(
1706
- "GET",
1707
- `/admin/thor/dropshipper/promotions/${promotionId}`
1708
- );
1709
- }
1710
- /**
1711
- * Update an existing promotion.
1712
- *
1713
- * `PUT /admin/thor/dropshipper/promotions/:id`
1714
- */
1715
- async updatePromotion(promotionId, body) {
1716
- return this.request(
1717
- "PUT",
1718
- `/admin/thor/dropshipper/promotions/${promotionId}`,
1719
- body
1720
- );
1721
- }
1722
- /**
1723
- * Delete a promotion.
1724
- *
1725
- * `DELETE /admin/thor/dropshipper/promotions/:id`
1726
- */
1727
- async deletePromotion(promotionId) {
1728
- return this.request(
1729
- "DELETE",
1730
- `/admin/thor/dropshipper/promotions/${promotionId}`
1731
- );
1732
- }
1733
- // -------------------------------------------------------------------------
1734
- // Dashboard (Solo Y)
1735
- // -------------------------------------------------------------------------
1736
- /**
1737
- * Aggregate stats for Y's dashboard (revenue, profit, top products).
1738
- *
1739
- * `GET /admin/thor/dropshipper/dashboard/stats`
1740
- */
1741
- async getDashboardStats(options = {}) {
1742
- const { period, from, to, currency_code } = options;
1743
- const qs = new URLSearchParams({
1744
- ...period ? { period } : {},
1745
- ...from ? { from } : {},
1746
- ...to ? { to } : {},
1747
- ...currency_code ? { currency_code } : {}
1748
- });
1749
- const query = qs.toString() ? `?${qs}` : "";
1750
- return this.request(
1751
- "GET",
1752
- `/admin/thor/dropshipper/dashboard/stats${query}`
1753
- );
1754
- }
1755
- // -------------------------------------------------------------------------
1756
- // Storefront (V — end customer, uses publishable API key)
1757
- // -------------------------------------------------------------------------
1758
- /**
1759
- * Public endpoint: dropshipper-scoped categories for the storefront.
1760
- * Typically called with a publishable API key rather than a JWT.
1761
- *
1762
- * `GET /store/thor/dropshipper-categories`
1763
- */
1764
- async getStorefrontCategories() {
1765
- return this.request(
1766
- "GET",
1767
- "/store/thor/dropshipper-categories"
1768
- );
1769
- }
1770
- // -------------------------------------------------------------------------
1771
- // Draft Orders
1772
- // -------------------------------------------------------------------------
1773
- /**
1774
- * List all draft orders in the dropshipper's channel.
1775
- *
1776
- * `GET /admin/thor/dropshipper/draft-orders`
1777
- */
1778
- async getDraftOrders(options = {}) {
1779
- const { customer_id, from, to, q, limit = 20, offset = 0 } = options;
1780
- const qs = new URLSearchParams({
1781
- limit: String(limit),
1782
- offset: String(offset),
1783
- ...customer_id ? { customer_id } : {},
1784
- ...from ? { from } : {},
1785
- ...to ? { to } : {},
1786
- ...q ? { q } : {}
1787
- });
1788
- return this.request(
1789
- "GET",
1790
- `/admin/thor/dropshipper/draft-orders?${qs}`
1791
- );
1792
- }
1793
- /**
1794
- * Get a specific draft order by ID.
1795
- *
1796
- * `GET /admin/thor/dropshipper/draft-orders/:id`
1797
- */
1798
- async getDraftOrder(draftOrderId) {
1799
- return this.request(
1800
- "GET",
1801
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}`
1802
- );
1803
- }
1804
- /**
1805
- * Create a new draft order.
1806
- *
1807
- * `POST /admin/thor/dropshipper/draft-orders`
1808
- */
1809
- async createDraftOrder(body) {
1810
- return this.request(
1811
- "POST",
1812
- "/admin/thor/dropshipper/draft-orders",
1813
- body
1814
- );
1815
- }
1816
- /**
1817
- * Update a draft order.
1818
- *
1819
- * `POST /admin/thor/dropshipper/draft-orders/:id`
1820
- */
1821
- async updateDraftOrder(draftOrderId, body) {
1822
- return this.request(
1823
- "POST",
1824
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}`,
1825
- body
1826
- );
1827
- }
1828
- /**
1829
- * Convert a draft order to a real order.
1830
- *
1831
- * `POST /admin/thor/dropshipper/draft-orders/:id/convert`
1832
- */
1833
- async convertDraftOrder(draftOrderId, body) {
1834
- return this.request(
1835
- "POST",
1836
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}/convert`,
1837
- body
1838
- );
1839
- }
1840
- /**
1841
- * Delete a draft order.
1842
- *
1843
- * `DELETE /admin/thor/dropshipper/draft-orders/:id`
1844
- */
1845
- async deleteDraftOrder(draftOrderId) {
1846
- return this.request(
1847
- "DELETE",
1848
- `/admin/thor/dropshipper/draft-orders/${draftOrderId}`
1849
- );
1850
- }
1851
- // -------------------------------------------------------------------------
1852
- // Geo-reference
1853
- // -------------------------------------------------------------------------
1854
- /**
1855
- * List all geo-reference countries.
1856
- *
1857
- * `GET /admin/geo-reference`
1858
- */
1859
- async getGeoCountries() {
1860
- return this.request("GET", "/admin/geo-reference");
1861
- }
1862
- /**
1863
- * List provinces/states for a country.
1864
- *
1865
- * `GET /admin/geo-reference/countries/:iso_2/provinces`
1866
- */
1867
- async getGeoProvinces(iso2) {
1868
- return this.request(
1869
- "GET",
1870
- `/admin/geo-reference/countries/${iso2}/provinces`
1871
- );
1872
- }
1873
- /**
1874
- * List cities for a province/state.
1875
- *
1876
- * `GET /admin/geo-reference/provinces/:code/cities`
1877
- */
1878
- async getGeoCities(code) {
1879
- return this.request(
1880
- "GET",
1881
- `/admin/geo-reference/provinces/${code}/cities`
1882
- );
1883
- }
1884
- };
1885
- async function* parseSse(stream, logger) {
1886
- const reader = stream.getReader();
1887
- const decoder = new TextDecoder();
1888
- let buffer = "";
1889
- let frameIndex = 0;
1890
- try {
1891
- while (true) {
1892
- const { done, value } = await reader.read();
1893
- if (done) break;
1894
- buffer += decoder.decode(value, { stream: true });
1895
- const lines = buffer.split(/\r?\n/);
1896
- buffer = lines.pop() ?? "";
1897
- for (const line of lines) {
1898
- const trimmed = line.trim();
1899
- if (!trimmed.startsWith("data:")) continue;
1900
- const payload = trimmed.slice(5).trim();
1901
- if (!payload || payload === "[DONE]") continue;
1902
- frameIndex += 1;
1903
- try {
1904
- yield JSON.parse(payload);
1905
- } catch (err) {
1906
- logger?.warn(
1907
- `[dropshipper] sse-malformed-frame frame=${frameIndex} payload=${payload.slice(0, 200)}`
1908
- );
1909
- }
1910
- }
1911
- }
1912
- const tail = buffer.trim();
1913
- if (tail.startsWith("data:")) {
1914
- const payload = tail.slice(5).trim();
1915
- if (payload && payload !== "[DONE]") {
1916
- frameIndex += 1;
1917
- try {
1918
- yield JSON.parse(payload);
1919
- } catch (err) {
1920
- logger?.warn(
1921
- `[dropshipper] sse-malformed-frame frame=${frameIndex} payload=${payload.slice(0, 200)}`
1922
- );
1923
- }
1924
- }
1925
- }
1926
- } finally {
1927
- reader.releaseLock();
1928
- }
1929
- }
1930
- function mapUiMessageStreamToEvents(stream, logger) {
1931
- return new ReadableStream({
1932
- async start(controller) {
1933
- let eventCount = 0;
1934
- for await (const raw of parseSse(stream, logger)) {
1935
- const chunk = raw;
1936
- switch (chunk.type) {
1937
- case "start":
1938
- controller.enqueue({
1939
- type: "start",
1940
- intent: chunk.messageMetadata?.intent
1941
- });
1942
- eventCount += 1;
1943
- break;
1944
- case "text-delta":
1945
- if (chunk.delta !== void 0) {
1946
- controller.enqueue({ type: "text-delta", delta: chunk.delta });
1947
- eventCount += 1;
1948
- }
1949
- break;
1950
- case "finish":
1951
- controller.enqueue({
1952
- type: "finish",
1953
- intent: chunk.messageMetadata?.intent ?? "default",
1954
- sources: chunk.messageMetadata?.sources ?? []
1955
- });
1956
- eventCount += 1;
1957
- break;
1958
- case "error":
1959
- logger?.warn(
1960
- `[dropshipper] chat-stream-error errorText=${chunk.errorText}`
1961
- );
1962
- controller.enqueue({
1963
- type: "error",
1964
- errorText: chunk.errorText ?? "Error inesperado del asistente."
1965
- });
1966
- eventCount += 1;
1967
- break;
1968
- default:
1969
- logger?.debug(
1970
- `[dropshipper] chat-stream-unknown-frame type=${chunk.type}`
1971
- );
1972
- }
1973
- }
1974
- logger?.debug(`[dropshipper] chat-stream-completed events=${eventCount}`);
1975
- controller.close();
1976
- },
1977
- cancel() {
1978
- stream.cancel?.();
1979
- }
1980
- });
1981
- }
1982
-
1983
- // src/recovery.ts
1984
- var import_adapters4 = require("@thorprovider/adapters");
1985
- var RecoveryClient = class {
1986
- baseUrl;
1987
- logger;
1988
- constructor(config) {
1989
- this.baseUrl = config.baseUrl.replace(/\/$/, "");
1990
- this.logger = (0, import_adapters4.createLogger)("RecoveryClient", config.debug);
1991
- }
1992
- // -------------------------------------------------------------------------
1993
- // Private — HTTP helper
1994
- // -------------------------------------------------------------------------
1995
- async request(method, path, body, retryConfig) {
1996
- const url = `${this.baseUrl}${path}`;
1997
- this.logger.debug(`[recovery] ${method} ${path}`);
1998
- const headers = {
1999
- "Content-Type": "application/json"
2000
- };
2001
- const init = {
2002
- method,
2003
- headers,
2004
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
2005
- };
2006
- let response;
2007
- try {
2008
- response = await fetchBackendWithResilience(url, init, retryConfig);
2009
- } catch (networkError) {
2010
- throw new import_adapters4.ProviderAPIError(
2011
- `[recovery] Network error on ${method} ${path}: ${networkError.message}`,
2012
- "NETWORK_ERROR",
2013
- networkError
2014
- );
2015
- }
2016
- if (!response.ok) {
2017
- let message = `HTTP ${response.status}`;
2018
- let details;
2019
- try {
2020
- const json = await response.json();
2021
- message = json?.message ?? message;
2022
- details = json && typeof json === "object" ? json : void 0;
2023
- } catch {
2024
- }
2025
- throw new import_adapters4.ProviderAPIError(
2026
- `[recovery] ${method} ${path} failed: ${message}`,
2027
- `RECOVERY_API_${response.status}`,
2028
- response.status,
2029
- details
2030
- );
2031
- }
2032
- if ((response.headers.get("content-type") ?? "").includes("application/json")) {
2033
- try {
2034
- return await response.json();
2035
- } catch {
2036
- return {};
2037
- }
2038
- }
2039
- return {};
2040
- }
2041
- // -------------------------------------------------------------------------
2042
- // Password reset
2043
- // -------------------------------------------------------------------------
2044
- /**
2045
- * Solicita un email de reset de contraseña para el actor `user`
2046
- * (dropshippers). El backend responde de forma uniforme exista o no la
2047
- * cuenta (anti enumeración).
2048
- *
2049
- * `POST /dropshipper/auth/emailpass/reset-password`
2050
- */
2051
- async requestUserPasswordReset(email) {
2052
- await this.request("POST", "/dropshipper/auth/emailpass/reset-password", {
2053
- email
2054
- });
2055
- }
2056
- /**
2057
- * Verifica un token de reset de contraseña sin consumirlo. Devuelve el
2058
- * email enmascarado (p. ej. `j***@ejemplo.com`) solo cuando `status === 'valid'`.
2059
- *
2060
- * `GET /dropshipper/auth/emailpass/reset-password/verify`
2061
- */
2062
- async verifyUserPasswordResetToken(token) {
2063
- return this.request("GET", `/dropshipper/auth/emailpass/reset-password/verify?token=${encodeURIComponent(token)}`);
2064
- }
2065
- /**
2066
- * Confirma el reset: re-verifica el token (sin consumir), luego consume el
2067
- * token vía `POST /dropshipper/auth/emailpass/update`. El email se deriva del
2068
- * propio JWT en el backend; aquí solo se envía la nueva contraseña. Nunca
2069
- * devuelve auto-login: al éxito, la UI redirige a /login.
2070
- */
2071
- async confirmUserPasswordReset(token, password) {
2072
- const verify = await this.verifyUserPasswordResetToken(token);
2073
- if (verify.status !== "valid") {
2074
- return { ok: false, status: verify.status };
2075
- }
2076
- try {
2077
- const headers = {
2078
- Authorization: `Bearer ${token}`,
2079
- "Content-Type": "application/json"
2080
- };
2081
- const response = await fetchBackendWithResilience(`${this.baseUrl}/dropshipper/auth/emailpass/update`, {
2082
- method: "POST",
2083
- headers,
2084
- body: JSON.stringify({ password })
2085
- });
2086
- if (!response.ok) {
2087
- throw new import_adapters4.ProviderAPIError(
2088
- `[recovery] POST /dropshipper/auth/emailpass/update failed: HTTP ${response.status}`,
2089
- "RECOVERY_API_" + response.status,
2090
- response.status
2091
- );
2092
- }
2093
- return { ok: true };
2094
- } catch (error) {
2095
- this.logger.warn("[recovery] confirmUserPasswordReset failed, re-verifying", error);
2096
- try {
2097
- const recheck = await this.verifyUserPasswordResetToken(token);
2098
- return { ok: false, status: recheck.status };
2099
- } catch {
2100
- return { ok: false, status: "invalid" };
2101
- }
2102
- }
2103
- }
2104
- // -------------------------------------------------------------------------
2105
- // Account activation
2106
- // -------------------------------------------------------------------------
2107
- /**
2108
- * Verifica un token de activación de cuenta dropshipper sin consumirlo.
2109
- *
2110
- * `GET /store/dropshipper/applications/activate/verify`
2111
- */
2112
- async verifyActivationToken(token) {
2113
- return this.request("GET", `/store/dropshipper/applications/activate/verify?token=${encodeURIComponent(token)}`);
2114
- }
2115
- /**
2116
- * Activa la cuenta: re-verifica el token (sin consumir), luego consume el
2117
- * token vía `POST /store/dropshipper/applications/activate` y establece la
2118
- * contraseña inicial. Al éxito, la UI redirige a /login sin auto-login.
2119
- */
2120
- async activateAccount(token, password) {
2121
- const verify = await this.verifyActivationToken(token);
2122
- if (verify.status !== "valid") {
2123
- return { ok: false, status: verify.status };
2124
- }
2125
- try {
2126
- await this.request("POST", "/store/dropshipper/applications/activate", { token, password });
2127
- return { ok: true };
2128
- } catch (error) {
2129
- this.logger.warn("[recovery] activateAccount failed, re-verifying", error);
2130
- try {
2131
- const recheck = await this.verifyActivationToken(token);
2132
- return { ok: false, status: recheck.status };
2133
- } catch {
2134
- return { ok: false, status: "invalid" };
2135
- }
2136
- }
2137
- }
2138
- // -------------------------------------------------------------------------
2139
- // Dropshipper application submission
2140
- // -------------------------------------------------------------------------
2141
- /**
2142
- * Envía una solicitud de acceso dropshipper al endpoint público.
2143
- *
2144
- * `POST /public/dropshipper/applications`
2145
- *
2146
- * No requiere autenticación. Devuelve un resultado discriminado:
2147
- * - `{ ok: true }` → 201, solicitud creada (`application.number`).
2148
- * - `{ ok: false, reason: 'conflict' }` → 409, email ya registrado; la
2149
- * solicitud existente incluye `status_label`/`reason` para la UI.
2150
- * - `{ ok: false, reason: 'rate_limited' }` → 429, se respetó el límite del
2151
- * backend; `retryAfterSeconds` indica cuándo reintentar.
2152
- * - `{ ok: false, reason: 'invalid_data' }` → 400, validación del backend.
2153
- *
2154
- * Los errores de red/5xx se re-lanzan como `ProviderAPIError` para que el
2155
- * llamador los categorice (p. ej. con `parseError`). El 429 no se reintenta
2156
- * (`retryableStatusCodes` sin 429) para que el caller reciba de inmediato el
2157
- * `retry_after_seconds` del backend y pueda bloquear el envío.
2158
- */
2159
- async submitApplication(body) {
2160
- try {
2161
- const response = await this.request(
2162
- "POST",
2163
- "/public/dropshipper/applications",
2164
- body,
2165
- { retryableStatusCodes: [408, 500, 502, 503, 504] }
2166
- );
2167
- return { ok: true, application: response.application };
2168
- } catch (error) {
2169
- if (error instanceof import_adapters4.ProviderAPIError) {
2170
- const details = error.details ?? {};
2171
- if (error.status === 409 && details.application) {
2172
- return {
2173
- ok: false,
2174
- reason: "conflict",
2175
- application: details.application
2176
- };
2177
- }
2178
- if (error.status === 429 && typeof details.retry_after_seconds === "number") {
2179
- return {
2180
- ok: false,
2181
- reason: "rate_limited",
2182
- retryAfterSeconds: details.retry_after_seconds
2183
- };
2184
- }
2185
- if (error.status === 400 && details?.type === "challenge_failed") {
2186
- return {
2187
- ok: false,
2188
- reason: "challenge_failed",
2189
- ...typeof details.message === "string" ? { message: details.message } : {}
2190
- };
2191
- }
2192
- if (error.status === 400) {
2193
- return {
2194
- ok: false,
2195
- reason: "invalid_data",
2196
- fields: details.fields
2197
- };
2198
- }
2199
- }
2200
- throw error;
2201
- }
2202
- }
2203
- };
2204
- // Annotate the CommonJS export names for ESM import in node:
2205
- 0 && (module.exports = {
2206
- DropshipperClient,
2207
- MedusaAdminClient,
2208
- RecoveryClient
2209
- });
2210
- //# sourceMappingURL=index.js.map