@lonca/trendyol 0.8.0 → 0.10.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,2917 @@
1
+ import { noopLogger, retry, TimeoutError, NetworkError, LoncaError, ServerError, RateLimitError, NotFoundError, ValidationError, AuthError, TokenBucketRateLimiter } from '@lonca/core';
2
+ import { randomUUID } from 'crypto';
3
+
4
+ // src/resources/brands.ts
5
+ var DEFAULT_PAGE_SIZE = 1e3;
6
+ var BrandsResource = class {
7
+ constructor(transport, limiter) {
8
+ this.transport = transport;
9
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 50, intervalMs: 6e4 });
10
+ }
11
+ transport;
12
+ limiter;
13
+ /**
14
+ * List Trendyol brands, one page at a time.
15
+ *
16
+ * @example
17
+ * ```ts
18
+ * import { paginate } from '@lonca/core';
19
+ * for await (const brand of paginate((p) => client.brands.list(p))) {
20
+ * console.log(brand.id, brand.name);
21
+ * }
22
+ * ```
23
+ */
24
+ async list(params = {}) {
25
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
26
+ const size = params.limit ?? DEFAULT_PAGE_SIZE;
27
+ const data = await this.transport.request({
28
+ method: "GET",
29
+ path: "/integration/product/brands",
30
+ query: { page, size },
31
+ rateLimiter: this.limiter
32
+ });
33
+ const items = data.brands.map((b) => ({ id: String(b.id), name: b.name }));
34
+ const nextCursor = page + 1 < data.totalPages ? String(page + 1) : void 0;
35
+ return nextCursor !== void 0 ? { items, nextCursor } : { items };
36
+ }
37
+ /**
38
+ * Search brands by name. Useful when you need a brand's numeric ID for
39
+ * `createProducts` and don't want to page through the full `list()`
40
+ * (1000 brands per page).
41
+ *
42
+ * **Discovery-first wire fact (verified STAGE 2026-05-25):** Trendyol's
43
+ * doc claims this is a case-sensitive *exact* match, but live behaviour
44
+ * is **substring + case-insensitive** — `search('Trendyol')` returns
45
+ * 17 hits including `TRENDYOLMILLA`, `trendyol vavist`, `Trendyol Üyelik`.
46
+ * Plan for ranking your results client-side if you need an exact match.
47
+ * The endpoint returns an empty array when nothing matches (no 404).
48
+ *
49
+ * @param name The brand name to search for.
50
+ */
51
+ async search(name) {
52
+ const data = await this.transport.request({
53
+ method: "GET",
54
+ path: "/integration/product/brands/by-name",
55
+ query: { name },
56
+ rateLimiter: this.limiter
57
+ });
58
+ return (data ?? []).map((b) => ({ id: String(b.id), name: b.name }));
59
+ }
60
+ };
61
+ function normalizeCategory(node) {
62
+ return {
63
+ id: String(node.id),
64
+ name: node.name,
65
+ parentId: node.parentId === null || node.parentId === void 0 ? null : String(node.parentId),
66
+ subCategories: (node.subCategories ?? []).map(normalizeCategory)
67
+ };
68
+ }
69
+ function normalizeAttribute(node) {
70
+ const attr = node.attribute ?? { id: 0, name: "" };
71
+ const rawValues = node.attributeValues ?? [];
72
+ const out = {
73
+ id: String(attr.id),
74
+ name: attr.name,
75
+ required: !!node.required,
76
+ allowCustom: !!node.allowCustom,
77
+ varianter: !!node.varianter,
78
+ slicer: !!node.slicer,
79
+ values: rawValues.map((v) => ({ id: String(v.id), name: v.name }))
80
+ };
81
+ if (node.categoryId !== void 0) {
82
+ out.categoryId = String(node.categoryId);
83
+ }
84
+ if (node.allowMultipleAttributeValues !== void 0) {
85
+ out.allowMultipleAttributeValues = node.allowMultipleAttributeValues;
86
+ }
87
+ return out;
88
+ }
89
+ var MAX_ATTR_VALUES_PAGE_SIZE = 1e3;
90
+ var DEFAULT_ATTR_VALUES_PAGE_SIZE = 100;
91
+ var CategoriesResource = class {
92
+ constructor(transport, limiter) {
93
+ this.transport = transport;
94
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 50, intervalMs: 6e4 });
95
+ }
96
+ transport;
97
+ limiter;
98
+ /**
99
+ * Fetch the full Trendyol category tree.
100
+ *
101
+ * Trendyol returns the entire tree in one response — there is no pagination.
102
+ * Cache the result aggressively in your application; the tree changes rarely.
103
+ */
104
+ async list() {
105
+ const data = await this.transport.request({
106
+ method: "GET",
107
+ path: "/integration/product/product-categories",
108
+ rateLimiter: this.limiter
109
+ });
110
+ const list = Array.isArray(data) ? data : data.categories;
111
+ return list.map(normalizeCategory);
112
+ }
113
+ /**
114
+ * Fetch the attributes (required and optional) for a single category.
115
+ *
116
+ * Call this before `createProduct V2` so you know which attributes are
117
+ * mandatory — the API rejects products that omit any `required` attribute.
118
+ *
119
+ * @param categoryId Trendyol numeric category ID; accepts `string` or `number`.
120
+ */
121
+ async getAttributes(categoryId) {
122
+ const id = encodeURIComponent(String(categoryId));
123
+ const data = await this.transport.request({
124
+ method: "GET",
125
+ path: `/integration/product/categories/${id}/attributes`,
126
+ rateLimiter: this.limiter
127
+ });
128
+ const list = extractAttributeList(data);
129
+ if (!list) {
130
+ console.error(
131
+ "[@lonca/trendyol] getCategoryAttributes: unexpected response shape:",
132
+ JSON.stringify(data).slice(0, 800)
133
+ );
134
+ return [];
135
+ }
136
+ return list.map(normalizeAttribute);
137
+ }
138
+ /**
139
+ * Fetch the allowed values for a single category attribute (paginated).
140
+ *
141
+ * `getCategoryAttributes` returns attribute metadata + flags but typically
142
+ * omits the value catalog. Use this method to fetch the catalog for an
143
+ * attribute when `allowCustom` is `false` and you need to map your data
144
+ * onto Trendyol's accepted values.
145
+ *
146
+ * @param categoryId Trendyol numeric category ID; accepts `string` or `number`.
147
+ * @param attributeId Attribute ID returned by `getAttributes`.
148
+ * @param params Cursor pagination (max page size 1000; default 100).
149
+ *
150
+ * @example
151
+ * ```ts
152
+ * import { paginate } from '@lonca/core';
153
+ * for await (const value of paginate((p) =>
154
+ * client.categories.getAttributeValues(catId, attrId, p),
155
+ * )) {
156
+ * console.log(value.id, value.name);
157
+ * }
158
+ * ```
159
+ */
160
+ async getAttributeValues(categoryId, attributeId, params = {}) {
161
+ const catId = encodeURIComponent(String(categoryId));
162
+ const attrId = encodeURIComponent(String(attributeId));
163
+ const size = Math.min(params.limit ?? DEFAULT_ATTR_VALUES_PAGE_SIZE, MAX_ATTR_VALUES_PAGE_SIZE);
164
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
165
+ const data = await this.transport.request({
166
+ method: "GET",
167
+ path: `/integration/product/categories/${catId}/attributes/${attrId}/values`,
168
+ query: { page, size },
169
+ rateLimiter: this.limiter
170
+ });
171
+ const items = (data.content ?? []).map((item) => ({
172
+ id: item.attributeValueId !== void 0 ? String(item.attributeValueId) : "",
173
+ name: item.attributeValue ?? item.attributeValueName ?? ""
174
+ }));
175
+ const result = { items };
176
+ const totalPages = typeof data.totalPages === "number" ? data.totalPages : 0;
177
+ if (page + 1 < totalPages) {
178
+ result.nextCursor = String(page + 1);
179
+ }
180
+ return result;
181
+ }
182
+ /**
183
+ * Look up category info for a list of barcodes (Trendyol Export Center
184
+ * / AutoFT endpoint).
185
+ *
186
+ * **Requires Export Center enrollment.** Sellers who have not joined
187
+ * Trendyol's "İhracat Merkezi" program will get an auth error on this
188
+ * endpoint even though their regular Marketplace credentials are valid.
189
+ *
190
+ * @param barcodes 1–N barcodes to look up.
191
+ * @throws {ValidationError} when `barcodes` is empty.
192
+ */
193
+ async getByBarcodes(barcodes) {
194
+ if (!Array.isArray(barcodes) || barcodes.length === 0) {
195
+ throw new ValidationError({ message: "getByBarcodes: barcodes must not be empty" });
196
+ }
197
+ const data = await this.transport.request({
198
+ method: "POST",
199
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/lookup/product-categories/by-barcodes`,
200
+ body: { barcodes },
201
+ rateLimiter: this.limiter
202
+ });
203
+ const matches = Object.entries(data.barcodeCategories ?? {}).map(([barcode, cat]) => ({
204
+ barcode,
205
+ category: {
206
+ id: cat.id !== void 0 ? String(cat.id) : "",
207
+ name: cat.displayName ?? ""
208
+ }
209
+ }));
210
+ return { matches, notFound: data.notFound ?? [] };
211
+ }
212
+ };
213
+ function extractAttributeList(data) {
214
+ if (Array.isArray(data)) return data;
215
+ if (data && typeof data === "object") {
216
+ const obj = data;
217
+ if (Array.isArray(obj.categoryAttributes)) {
218
+ return obj.categoryAttributes;
219
+ }
220
+ if (Array.isArray(obj.attributes)) {
221
+ return obj.attributes;
222
+ }
223
+ }
224
+ return null;
225
+ }
226
+ function toIso(epochMs) {
227
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs) || epochMs === 0) {
228
+ return void 0;
229
+ }
230
+ return new Date(epochMs).toISOString();
231
+ }
232
+ function normalizeClaim(node) {
233
+ const out = {
234
+ id: node.id ?? node.claimId ?? "",
235
+ orderNumber: node.orderNumber ?? "",
236
+ raw: node
237
+ };
238
+ const orderDate = toIso(node.orderDate);
239
+ if (orderDate) out.orderDate = orderDate;
240
+ const claimDate = toIso(node.claimDate);
241
+ if (claimDate) out.claimDate = claimDate;
242
+ if (node.customerFirstName !== void 0) out.customerFirstName = node.customerFirstName;
243
+ if (node.customerLastName !== void 0) out.customerLastName = node.customerLastName;
244
+ return out;
245
+ }
246
+ var ClaimsResource = class {
247
+ constructor(transport, limiter) {
248
+ this.transport = transport;
249
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
250
+ }
251
+ transport;
252
+ limiter;
253
+ /**
254
+ * Create a return claim against an order. Use this to file a return on
255
+ * behalf of a customer (e.g. when they called your CS line). For
256
+ * customer-initiated returns coming from trendyol.com, you receive them
257
+ * via `claims.list()` — no need to call `create`.
258
+ *
259
+ * Returns whatever Trendyol returns (typically the new claim's identifier).
260
+ *
261
+ * @throws {ValidationError} when `claimItems` is empty.
262
+ */
263
+ async create(input) {
264
+ if (!Array.isArray(input?.claimItems) || input.claimItems.length === 0) {
265
+ throw new ValidationError({ message: "claims.create: claimItems must not be empty" });
266
+ }
267
+ return this.transport.request({
268
+ method: "POST",
269
+ path: `/integration/order/sellers/${this.transport.sellerId}/claims/create`,
270
+ body: input,
271
+ rateLimiter: this.limiter
272
+ });
273
+ }
274
+ /**
275
+ * File a seller-side rejection ("ret talebi") against a customer claim.
276
+ *
277
+ * **Wire format: `multipart/form-data`** — the SDK builds the FormData
278
+ * internally from the typed input. `claimItemIdList` is joined with
279
+ * commas (Trendyol expects a single comma-separated string field).
280
+ * Attach supporting docs (PDF / JPEG) via `files: [Blob, ...]`.
281
+ */
282
+ async createIssue(claimId, input) {
283
+ if (!Array.isArray(input?.claimItemIdList) || input.claimItemIdList.length === 0) {
284
+ throw new ValidationError({
285
+ message: "claims.createIssue: claimItemIdList must not be empty"
286
+ });
287
+ }
288
+ if (typeof input.description !== "string" || input.description.length === 0) {
289
+ throw new ValidationError({ message: "claims.createIssue: description is required" });
290
+ }
291
+ if (input.description.length > 500) {
292
+ throw new ValidationError({
293
+ message: `claims.createIssue: description must be \u2264500 chars (got ${input.description.length})`
294
+ });
295
+ }
296
+ const form = new FormData();
297
+ form.append("claimIssueReasonId", String(input.claimIssueReasonId));
298
+ form.append("claimItemIdList", input.claimItemIdList.join(","));
299
+ form.append("description", input.description);
300
+ if (input.files) {
301
+ for (const file of input.files) {
302
+ form.append("files", file);
303
+ }
304
+ }
305
+ return this.transport.request({
306
+ method: "POST",
307
+ path: `/integration/order/sellers/${this.transport.sellerId}/claims/${encodeURIComponent(claimId)}/issue`,
308
+ body: form,
309
+ rateLimiter: this.limiter
310
+ });
311
+ }
312
+ /**
313
+ * Approve specific claim line items. After approval, Trendyol moves
314
+ * those line items into the post-approval refund / return-shipping flow.
315
+ *
316
+ * @throws {ValidationError} when `claimLineItemIdList` is empty.
317
+ */
318
+ async approveLineItems(claimId, input) {
319
+ if (!Array.isArray(input?.claimLineItemIdList) || input.claimLineItemIdList.length === 0) {
320
+ throw new ValidationError({
321
+ message: "claims.approveLineItems: claimLineItemIdList must not be empty"
322
+ });
323
+ }
324
+ return this.transport.request({
325
+ method: "PUT",
326
+ path: `/integration/order/sellers/${this.transport.sellerId}/claims/${encodeURIComponent(claimId)}/items/approve`,
327
+ body: input,
328
+ rateLimiter: this.limiter
329
+ });
330
+ }
331
+ /**
332
+ * List claims (page-based; SDK exposes opaque cursor convention).
333
+ *
334
+ * @example
335
+ * ```ts
336
+ * import { paginate } from '@lonca/core';
337
+ * for await (const c of paginate((p) =>
338
+ * client.claims.list({ ...p, claimItemStatus: 'WaitingInAction' }),
339
+ * )) {
340
+ * console.log(c.id, c.orderNumber, c.claimDate);
341
+ * }
342
+ * ```
343
+ */
344
+ async list(params = {}) {
345
+ const size = Math.min(params.limit ?? 50, 200);
346
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
347
+ const query = { page, size };
348
+ if (params.startDate) query.startDate = params.startDate.getTime();
349
+ if (params.endDate) query.endDate = params.endDate.getTime();
350
+ if (params.claimItemStatus) query.claimItemStatus = params.claimItemStatus;
351
+ const data = await this.transport.request({
352
+ method: "GET",
353
+ path: `/integration/order/sellers/${this.transport.sellerId}/claims`,
354
+ query,
355
+ rateLimiter: this.limiter
356
+ });
357
+ const items = (data.content ?? []).map(normalizeClaim);
358
+ const result = { items };
359
+ const totalPages = typeof data.totalPages === "number" ? data.totalPages : 0;
360
+ if (page + 1 < totalPages) {
361
+ result.nextCursor = String(page + 1);
362
+ }
363
+ return result;
364
+ }
365
+ /**
366
+ * Fetch the catalog of rejection-reason IDs the seller can use on
367
+ * `claims.createIssue()`. Cache the result — it changes rarely.
368
+ *
369
+ * Note: this endpoint is **not seller-scoped** (no `sellerId` in path).
370
+ */
371
+ async getIssueReasons() {
372
+ const data = await this.transport.request({
373
+ method: "GET",
374
+ path: `/integration/order/claim-issue-reasons`,
375
+ rateLimiter: this.limiter
376
+ });
377
+ return (data ?? []).map((r) => ({
378
+ id: typeof r.id === "number" ? r.id : 0,
379
+ name: r.name ?? ""
380
+ }));
381
+ }
382
+ /**
383
+ * Fetch the audit log for a single claim item (state transitions,
384
+ * actor, timestamp). Trendyol's response shape varies — the SDK
385
+ * surfaces each row as `{ raw }` and leaves field extraction to the
386
+ * caller until we observe a stable shape on the wire.
387
+ */
388
+ async getItemAudits(claimItemId) {
389
+ const data = await this.transport.request({
390
+ method: "GET",
391
+ path: `/integration/order/sellers/${this.transport.sellerId}/claims/items/${encodeURIComponent(claimItemId)}/audit`,
392
+ rateLimiter: this.limiter
393
+ });
394
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.content) ? data.content : [];
395
+ return rows.map((row) => ({ raw: row }));
396
+ }
397
+ };
398
+ var MAX_BATCH_ITEMS = 5e3;
399
+ var ExportCenterResource = class {
400
+ constructor(transport, limiter) {
401
+ this.transport = transport;
402
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
403
+ }
404
+ transport;
405
+ limiter;
406
+ // ─── Products ────────────────────────────────────────────────────────────
407
+ /**
408
+ * List Export Center-approved products. Uses Trendyol's `pageKey`
409
+ * pagination — the first call leaves `pageKey` empty; subsequent
410
+ * calls pass the `x-paging-key` value from the previous response.
411
+ */
412
+ async listProducts(params = {}) {
413
+ const query = {};
414
+ if (params.barcodes && params.barcodes.length > 0) query.barcodes = params.barcodes.join(",");
415
+ if (params.pageKey) query.pageKey = params.pageKey;
416
+ if (params.size !== void 0) query.size = params.size;
417
+ const data = await this.transport.request({
418
+ method: "GET",
419
+ path: `/integration/ecgw/v2/${this.transport.sellerId}/products`,
420
+ query: Object.keys(query).length ? query : void 0,
421
+ rateLimiter: this.limiter
422
+ });
423
+ const rows = pickArray(data);
424
+ return rows.map((r) => ({ raw: r ?? {} }));
425
+ }
426
+ /**
427
+ * Create Export Center products. Maximum 5000 per call. Returns a
428
+ * `batchId` you can poll via `getBatchStatus(batchId)`.
429
+ *
430
+ * @throws {ValidationError} when `products` is empty / oversized.
431
+ */
432
+ async createProducts(products) {
433
+ this.assertBatch(products, "createProducts");
434
+ const data = await this.transport.request({
435
+ method: "POST",
436
+ path: `/integration/ecgw/v2/${this.transport.sellerId}/products`,
437
+ body: { products },
438
+ rateLimiter: this.limiter
439
+ });
440
+ return normalizeBatchResponse(data);
441
+ }
442
+ /**
443
+ * Update Export Center prices. **Trendyol allows one price update per
444
+ * barcode per day.** Returns a `batchId`.
445
+ *
446
+ * @throws {ValidationError} when `priceInfos` is empty / oversized.
447
+ */
448
+ async updatePrices(priceInfos) {
449
+ this.assertBatch(priceInfos, "updatePrices");
450
+ const data = await this.transport.request({
451
+ method: "POST",
452
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/prices`,
453
+ body: { priceInfos },
454
+ rateLimiter: this.limiter
455
+ });
456
+ return normalizeBatchResponse(data);
457
+ }
458
+ /**
459
+ * Update Export Center stocks. Returns a `batchId`. Sellers using
460
+ * Trendyol's shared inventory cannot use this endpoint (per portal docs).
461
+ *
462
+ * @throws {ValidationError} when `items` is empty / oversized.
463
+ */
464
+ async updateStocks(items) {
465
+ this.assertBatch(items, "updateStocks");
466
+ const data = await this.transport.request({
467
+ method: "POST",
468
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/stocks`,
469
+ body: { items },
470
+ rateLimiter: this.limiter
471
+ });
472
+ return normalizeBatchResponse(data);
473
+ }
474
+ // ─── Batch status ────────────────────────────────────────────────────────
475
+ /**
476
+ * Look up the status of a previously-submitted batch. Trendyol retains
477
+ * batch records for **24 hours** only — older `batchId`s return `404`.
478
+ */
479
+ async getBatchStatus(batchId) {
480
+ if (!batchId) {
481
+ throw new ValidationError({ message: "exportCenter.getBatchStatus: batchId is required" });
482
+ }
483
+ const data = await this.transport.request({
484
+ method: "GET",
485
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/check-status`,
486
+ query: { batchId },
487
+ rateLimiter: this.limiter
488
+ });
489
+ return normalizeBatchStatus(data);
490
+ }
491
+ // ─── Packages ────────────────────────────────────────────────────────────
492
+ /** List daily Export Center packages (V2 — query-based filters). */
493
+ async listPackagesV2(params = {}) {
494
+ const data = await this.transport.request({
495
+ method: "GET",
496
+ path: `/integration/ecgw/v2/${this.transport.sellerId}/packages`,
497
+ query: {
498
+ trackingNumber: params.trackingNumber,
499
+ status: params.status,
500
+ creationStartDate: params.creationStartDate,
501
+ creationEndDate: params.creationEndDate,
502
+ size: params.size,
503
+ boutiqueId: params.boutiqueId
504
+ },
505
+ rateLimiter: this.limiter
506
+ });
507
+ return pickArray(data).map(normalizePackage);
508
+ }
509
+ /** List Export Center packages (V3 — consolidated, page-based). */
510
+ async listPackagesV3(params = {}) {
511
+ const data = await this.transport.request({
512
+ method: "GET",
513
+ path: `/integration/ecgw/v3/${this.transport.sellerId}/packages`,
514
+ query: {
515
+ status: params.status,
516
+ page: params.offset !== void 0 ? params.offset : void 0,
517
+ size: params.limit,
518
+ creationStartDate: params.creationStartDate,
519
+ creationEndDate: params.creationEndDate
520
+ },
521
+ rateLimiter: this.limiter
522
+ });
523
+ return pickArray(data).map(normalizePackage);
524
+ }
525
+ /** Get the line items inside an Export Center package. */
526
+ async getPackageItems(params) {
527
+ if (!params || !params.packageId) {
528
+ throw new ValidationError({
529
+ message: "exportCenter.getPackageItems: packageId is required"
530
+ });
531
+ }
532
+ const data = await this.transport.request({
533
+ method: "GET",
534
+ path: `/integration/ecgw/v2/${this.transport.sellerId}/packages/items`,
535
+ query: {
536
+ packageId: params.packageId,
537
+ status: params.status,
538
+ page: params.offset,
539
+ size: params.limit
540
+ },
541
+ rateLimiter: this.limiter
542
+ });
543
+ return pickArray(data).map((r) => ({ raw: r ?? {} }));
544
+ }
545
+ // ─── Lookup ──────────────────────────────────────────────────────────────
546
+ /** Get the required attributes for an Export Center category. */
547
+ async getCategoryAttributes(categoryId) {
548
+ if (categoryId === void 0 || categoryId === null || categoryId === "") {
549
+ throw new ValidationError({
550
+ message: "exportCenter.getCategoryAttributes: categoryId is required"
551
+ });
552
+ }
553
+ const data = await this.transport.request({
554
+ method: "GET",
555
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/lookup/product-categories/${encodeURIComponent(String(categoryId))}/attributes`,
556
+ rateLimiter: this.limiter
557
+ });
558
+ return pickArray(data).map((r) => {
559
+ const row = r ?? {};
560
+ const out = { raw: row };
561
+ if (typeof row.attributeId === "number" || typeof row.attributeId === "string") {
562
+ out.attributeId = row.attributeId;
563
+ }
564
+ if (typeof row.attributeName === "string") out.attributeName = row.attributeName;
565
+ if (typeof row.required === "boolean") out.required = row.required;
566
+ if (Array.isArray(row.values)) out.values = row.values;
567
+ return out;
568
+ });
569
+ }
570
+ /** Get the care-instruction lookup values used by `createProducts`. */
571
+ async getCareInstructions() {
572
+ const data = await this.transport.request({
573
+ method: "GET",
574
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/lookup/care-instructions`,
575
+ rateLimiter: this.limiter
576
+ });
577
+ return pickArray(data).map(normalizeNamedRef);
578
+ }
579
+ /** Get the material-composition lookup values used by `createProducts`. */
580
+ async getCompositions() {
581
+ const data = await this.transport.request({
582
+ method: "GET",
583
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/lookup/compositions`,
584
+ rateLimiter: this.limiter
585
+ });
586
+ return pickArray(data).map(normalizeNamedRef);
587
+ }
588
+ /** Get the country-of-origin lookup values used by `createProducts`. */
589
+ async getOrigins() {
590
+ const data = await this.transport.request({
591
+ method: "GET",
592
+ path: `/integration/ecgw/v1/${this.transport.sellerId}/lookup/origins`,
593
+ rateLimiter: this.limiter
594
+ });
595
+ return pickArray(data).map((r) => {
596
+ const row = r ?? {};
597
+ const out = { raw: row };
598
+ if (typeof row.id === "number" || typeof row.id === "string") out.id = row.id;
599
+ if (typeof row.name === "string") out.name = row.name;
600
+ if (typeof row.countryCode === "string") out.countryCode = row.countryCode;
601
+ return out;
602
+ });
603
+ }
604
+ // ─── Helpers ─────────────────────────────────────────────────────────────
605
+ assertBatch(items, methodLabel) {
606
+ if (!Array.isArray(items) || items.length === 0) {
607
+ throw new ValidationError({
608
+ message: `exportCenter.${methodLabel}: items must not be empty`
609
+ });
610
+ }
611
+ if (items.length > MAX_BATCH_ITEMS) {
612
+ throw new ValidationError({
613
+ message: `exportCenter.${methodLabel}: max ${MAX_BATCH_ITEMS} items per call (got ${items.length})`
614
+ });
615
+ }
616
+ }
617
+ };
618
+ function pickArray(data) {
619
+ if (Array.isArray(data)) return data;
620
+ if (data && typeof data === "object") {
621
+ const obj = data;
622
+ if (Array.isArray(obj.content)) return obj.content;
623
+ if (Array.isArray(obj.items)) return obj.items;
624
+ if (Array.isArray(obj.data)) return obj.data;
625
+ if (Array.isArray(obj.products)) return obj.products;
626
+ if (Array.isArray(obj.packages)) return obj.packages;
627
+ }
628
+ return [];
629
+ }
630
+ function normalizeBatchResponse(data) {
631
+ const obj = data && typeof data === "object" ? data : {};
632
+ return {
633
+ batchId: String(obj.batchId ?? obj.batchRequestId ?? obj.id ?? ""),
634
+ raw: obj
635
+ };
636
+ }
637
+ function normalizeBatchStatus(data) {
638
+ const obj = data && typeof data === "object" ? data : {};
639
+ const out = { raw: obj };
640
+ if (typeof obj.batchId === "string") out.batchId = obj.batchId;
641
+ if (typeof obj.status === "string") out.status = obj.status;
642
+ if (typeof obj.itemCount === "number") out.itemCount = obj.itemCount;
643
+ if (typeof obj.failedItemCount === "number") out.failedItemCount = obj.failedItemCount;
644
+ if (Array.isArray(obj.items)) out.items = obj.items;
645
+ return out;
646
+ }
647
+ function normalizePackage(row) {
648
+ const r = row ?? {};
649
+ const out = { raw: r };
650
+ if (typeof r.packageNumber === "string") out.packageNumber = r.packageNumber;
651
+ if (typeof r.status === "string") out.status = r.status;
652
+ return out;
653
+ }
654
+ function normalizeNamedRef(row) {
655
+ const r = row ?? {};
656
+ const out = { raw: r };
657
+ if (typeof r.id === "number" || typeof r.id === "string") out.id = r.id;
658
+ if (typeof r.name === "string") out.name = r.name;
659
+ return out;
660
+ }
661
+ function toIso2(epochMs) {
662
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs) || epochMs === 0) {
663
+ return void 0;
664
+ }
665
+ return new Date(epochMs).toISOString();
666
+ }
667
+ function normalizeRow(row) {
668
+ const out = {
669
+ id: row.id !== void 0 ? String(row.id) : "",
670
+ raw: row
671
+ };
672
+ const tx = toIso2(row.transactionDate);
673
+ if (tx) out.transactionDate = tx;
674
+ if (row.barcode !== void 0) out.barcode = row.barcode;
675
+ if (row.transactionType !== void 0) out.transactionType = row.transactionType;
676
+ if (row.receiptId !== void 0) out.receiptId = row.receiptId;
677
+ if (row.description !== void 0) out.description = row.description;
678
+ if (typeof row.debt === "number") out.debt = row.debt;
679
+ if (typeof row.credit === "number") out.credit = row.credit;
680
+ if (row.paymentPeriod !== void 0) out.paymentPeriod = row.paymentPeriod;
681
+ if (row.commissionRate !== void 0) out.commissionRate = row.commissionRate;
682
+ if (row.commissionAmount !== void 0) out.commissionAmount = row.commissionAmount;
683
+ if (row.commissionInvoiceSerialNumber !== void 0) {
684
+ out.commissionInvoiceSerialNumber = row.commissionInvoiceSerialNumber;
685
+ }
686
+ if (row.sellerRevenue !== void 0) out.sellerRevenue = row.sellerRevenue;
687
+ if (row.orderNumber !== void 0) out.orderNumber = row.orderNumber;
688
+ if (row.paymentOrderId !== void 0) out.paymentOrderId = row.paymentOrderId;
689
+ const pay = toIso2(row.paymentDate);
690
+ if (pay) out.paymentDate = pay;
691
+ if (typeof row.sellerId === "number") out.sellerId = row.sellerId;
692
+ if (row.storeId !== void 0) out.storeId = row.storeId;
693
+ if (row.storeName !== void 0) out.storeName = row.storeName;
694
+ if (row.storeAddress !== void 0) out.storeAddress = row.storeAddress;
695
+ if (row.country !== void 0) out.country = row.country;
696
+ return out;
697
+ }
698
+ var FinanceResource = class {
699
+ constructor(transport, limiter) {
700
+ this.transport = transport;
701
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 100, intervalMs: 6e4 });
702
+ }
703
+ transport;
704
+ limiter;
705
+ async getSettlements(params = {}) {
706
+ return this.queryPage(
707
+ `/integration/finance/che/sellers/${this.transport.sellerId}/settlements`,
708
+ params
709
+ );
710
+ }
711
+ async getOtherFinancials(params = {}) {
712
+ return this.queryPage(
713
+ `/integration/finance/che/sellers/${this.transport.sellerId}/otherfinancials`,
714
+ params
715
+ );
716
+ }
717
+ async queryPage(path, params) {
718
+ const size = Math.min(params.limit ?? 50, 200);
719
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
720
+ const query = { page, size };
721
+ if (params.startDate) query.startDate = params.startDate.getTime();
722
+ if (params.endDate) query.endDate = params.endDate.getTime();
723
+ if (params.transactionType) query.transactionType = params.transactionType;
724
+ const data = await this.transport.request({
725
+ method: "GET",
726
+ path,
727
+ query,
728
+ rateLimiter: this.limiter
729
+ });
730
+ const items = (data.content ?? []).map(normalizeRow);
731
+ const result = { items };
732
+ const totalPages = typeof data.totalPages === "number" ? data.totalPages : 0;
733
+ if (page + 1 < totalPages) {
734
+ result.nextCursor = String(page + 1);
735
+ }
736
+ return result;
737
+ }
738
+ };
739
+ var MAX_ITEMS_PER_REQUEST = 1e3;
740
+ async function pollBatchStatus(getStatus, batchRequestId, opts = {}) {
741
+ const pollIntervalMs = opts.pollIntervalMs ?? 2e3;
742
+ const timeoutMs = opts.timeoutMs ?? 12e4;
743
+ const deadline = Date.now() + timeoutMs;
744
+ for (; ; ) {
745
+ opts.signal?.throwIfAborted();
746
+ const result = await getStatus(batchRequestId);
747
+ if (result.status === "COMPLETED" || result.status === "FAILED") {
748
+ return result;
749
+ }
750
+ if (Date.now() >= deadline) {
751
+ throw new TimeoutError({
752
+ message: `Trendyol batch ${batchRequestId} did not settle within ${timeoutMs}ms (last status: ${result.status})`,
753
+ data: { batchRequestId, lastStatus: result.status, lastResult: result }
754
+ });
755
+ }
756
+ await delay(pollIntervalMs, opts.signal);
757
+ }
758
+ }
759
+ var InventoryResource = class {
760
+ /**
761
+ * @param transport Trendyol transport.
762
+ * @param getBatchStatus Batch-status poller (wired by `createTrendyolClient`
763
+ * to `products.getBatchStatus`). Required only for `updateAndWait`.
764
+ */
765
+ constructor(transport, getBatchStatus) {
766
+ this.transport = transport;
767
+ this.getBatchStatus = getBatchStatus;
768
+ }
769
+ transport;
770
+ getBatchStatus;
771
+ /**
772
+ * Update price and/or stock for one or more SKUs (by barcode).
773
+ *
774
+ * @example
775
+ * ```ts
776
+ * const { batchRequestId } = await client.inventory.update([
777
+ * { barcode: 'ABC123', quantity: 42, salePrice: 199.9, listPrice: 249.9 },
778
+ * { barcode: 'XYZ789', quantity: 0 },
779
+ * ]);
780
+ * const status = await client.products.getBatchStatus(batchRequestId);
781
+ * ```
782
+ *
783
+ * @throws {ValidationError} when `items` is empty or longer than 1000.
784
+ * @throws {ServerError} when Trendyol accepts the request but returns no
785
+ * `batchRequestId` (an unpollable response — surfaced loudly instead of
786
+ * handing back an empty id).
787
+ */
788
+ async update(items) {
789
+ if (items.length === 0) {
790
+ throw new ValidationError({ message: "updatePriceAndInventory: items must not be empty" });
791
+ }
792
+ if (items.length > MAX_ITEMS_PER_REQUEST) {
793
+ throw new ValidationError({
794
+ message: `updatePriceAndInventory: max ${MAX_ITEMS_PER_REQUEST} items per request, got ${items.length}`
795
+ });
796
+ }
797
+ const data = await this.transport.request({
798
+ method: "POST",
799
+ path: `/integration/inventory/sellers/${this.transport.sellerId}/products/price-and-inventory`,
800
+ body: { items }
801
+ });
802
+ if (!data.batchRequestId) {
803
+ throw new ServerError({
804
+ message: "Trendyol updatePriceAndInventory returned no batchRequestId",
805
+ data: { response: data }
806
+ });
807
+ }
808
+ return { batchRequestId: data.batchRequestId };
809
+ }
810
+ /**
811
+ * Submit price/stock updates and wait for them to settle.
812
+ *
813
+ * Splits `items` into chunks of ≤1000, submits each via {@link update}, and
814
+ * polls each `batchRequestId` to a terminal state. Returns one
815
+ * `BatchRequestResult` per chunk (read `failedItemCount` / `items[]` for
816
+ * per-barcode outcomes). Compose `@lonca/core`'s `retry` around this for
817
+ * transient-error resilience.
818
+ *
819
+ * @throws {ValidationError} when `items` is empty.
820
+ * @throws {TimeoutError} when any chunk does not settle within `timeoutMs`;
821
+ * `error.data.batchRequestId` identifies the stuck chunk.
822
+ */
823
+ async updateAndWait(items, opts = {}) {
824
+ if (items.length === 0) {
825
+ throw new ValidationError({ message: "updateAndWait: items must not be empty" });
826
+ }
827
+ const getStatus = this.getBatchStatus;
828
+ if (!getStatus) {
829
+ throw new Error(
830
+ "updateAndWait requires a batch-status poller; obtain the client via createTrendyolClient()"
831
+ );
832
+ }
833
+ const results = [];
834
+ for (const batch of chunk(items, MAX_ITEMS_PER_REQUEST)) {
835
+ const { batchRequestId } = await this.update(batch);
836
+ results.push(await pollBatchStatus(getStatus, batchRequestId, opts));
837
+ }
838
+ return results;
839
+ }
840
+ };
841
+ function chunk(items, size) {
842
+ if (items.length <= size) return [items];
843
+ const chunks = [];
844
+ for (let i = 0; i < items.length; i += size) {
845
+ chunks.push(items.slice(i, i + size));
846
+ }
847
+ return chunks;
848
+ }
849
+ function delay(ms, signal) {
850
+ return new Promise((resolve, reject) => {
851
+ if (signal?.aborted) {
852
+ reject(signal.reason ?? new Error("Aborted"));
853
+ return;
854
+ }
855
+ const onAbort = () => {
856
+ clearTimeout(timer);
857
+ reject(signal?.reason ?? new Error("Aborted"));
858
+ };
859
+ const timer = setTimeout(() => {
860
+ signal?.removeEventListener("abort", onAbort);
861
+ resolve();
862
+ }, ms);
863
+ signal?.addEventListener("abort", onAbort, { once: true });
864
+ });
865
+ }
866
+ var InvoicesResource = class {
867
+ constructor(transport, limiter) {
868
+ this.transport = transport;
869
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 500, intervalMs: 6e4 });
870
+ }
871
+ transport;
872
+ limiter;
873
+ /**
874
+ * Upload an invoice file for a shipment package. **Multipart**: the
875
+ * SDK builds the FormData internally from the typed input.
876
+ *
877
+ * Max 10 MB. Accepted formats: PDF, JPEG, PNG.
878
+ */
879
+ async uploadFile(input) {
880
+ if (!input?.file) {
881
+ throw new ValidationError({ message: "invoices.uploadFile: file is required" });
882
+ }
883
+ if (!input.shipmentPackageId) {
884
+ throw new ValidationError({ message: "invoices.uploadFile: shipmentPackageId is required" });
885
+ }
886
+ const form = new FormData();
887
+ form.append("shipmentPackageId", String(input.shipmentPackageId));
888
+ form.append("file", input.file);
889
+ if (input.invoiceDateTime !== void 0) {
890
+ form.append("invoiceDateTime", String(input.invoiceDateTime));
891
+ }
892
+ if (input.invoiceNumber !== void 0) {
893
+ form.append("invoiceNumber", input.invoiceNumber);
894
+ }
895
+ return this.transport.request({
896
+ method: "POST",
897
+ path: `/integration/sellers/${this.transport.sellerId}/seller-invoice-file`,
898
+ body: form,
899
+ rateLimiter: this.limiter
900
+ });
901
+ }
902
+ /** Register an invoice URL with Trendyol (alternative to uploading the file). */
903
+ async sendLink(input) {
904
+ if (!input?.invoiceLink) {
905
+ throw new ValidationError({ message: "invoices.sendLink: invoiceLink is required" });
906
+ }
907
+ return this.transport.request({
908
+ method: "POST",
909
+ path: `/integration/sellers/${this.transport.sellerId}/seller-invoice-links`,
910
+ body: input,
911
+ rateLimiter: this.limiter
912
+ });
913
+ }
914
+ /** Remove a previously-registered invoice link. */
915
+ async deleteLink(input) {
916
+ return this.transport.request({
917
+ method: "POST",
918
+ path: `/integration/sellers/${this.transport.sellerId}/seller-invoice-links/delete`,
919
+ body: input,
920
+ rateLimiter: this.limiter
921
+ });
922
+ }
923
+ };
924
+ var LabelsResource = class {
925
+ constructor(transport, limiter) {
926
+ this.transport = transport;
927
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 100, intervalMs: 6e4 });
928
+ }
929
+ transport;
930
+ limiter;
931
+ /**
932
+ * Request a common ZPL label for a cargo tracking number. After this
933
+ * returns, call `getCommon()` with the same `cargoTrackingNumber` to
934
+ * retrieve the generated label.
935
+ *
936
+ * @throws {ValidationError} when `format` is missing.
937
+ */
938
+ async createCommon(cargoTrackingNumber, input) {
939
+ if (!input?.format) {
940
+ throw new ValidationError({ message: "labels.createCommon: format is required" });
941
+ }
942
+ return this.transport.request({
943
+ method: "POST",
944
+ path: `/integration/sellers/${this.transport.sellerId}/common-label/${encodeURIComponent(String(cargoTrackingNumber))}`,
945
+ body: input,
946
+ rateLimiter: this.limiter
947
+ });
948
+ }
949
+ /**
950
+ * Retrieve the previously-created common label. Trendyol returns
951
+ * `{ data: [{ label, format }] }`; the SDK surfaces the array as
952
+ * `labels[]` for ergonomic access.
953
+ *
954
+ * Typically `labels.length === 1` per tracking number, but kept as an
955
+ * array to match the wire shape.
956
+ */
957
+ async getCommon(cargoTrackingNumber) {
958
+ const raw = await this.transport.request({
959
+ method: "GET",
960
+ path: `/integration/sellers/${this.transport.sellerId}/common-label/${encodeURIComponent(String(cargoTrackingNumber))}`,
961
+ rateLimiter: this.limiter
962
+ });
963
+ const labels = (raw?.data ?? []).map((row) => ({
964
+ label: row.label ?? "",
965
+ format: row.format ?? "ZPL"
966
+ }));
967
+ return { labels, raw: raw ?? {} };
968
+ }
969
+ };
970
+ function n(rows, extract) {
971
+ const list = Array.isArray(rows) ? rows : [];
972
+ return list.map((r) => {
973
+ const node = r;
974
+ return { ...extract(node), raw: node };
975
+ });
976
+ }
977
+ var LocationsResource = class {
978
+ constructor(transport, limiter) {
979
+ this.transport = transport;
980
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 60, intervalMs: 6e4 });
981
+ }
982
+ transport;
983
+ limiter;
984
+ /** List all supported countries (Türkiye + AZ + GULF + CEE). */
985
+ async getCountries() {
986
+ const data = await this.transport.request({
987
+ method: "GET",
988
+ path: `/integration/member/countries`,
989
+ rateLimiter: this.limiter
990
+ });
991
+ return n(data, (node) => ({
992
+ code: String(node.code ?? node.id ?? ""),
993
+ name: node.name
994
+ }));
995
+ }
996
+ // ─── Domestic (TR / AZ) ───────────────────────────────────────────────
997
+ async getTurkeyCities() {
998
+ return this.cities(`/integration/member/countries/domestic/TR/cities`);
999
+ }
1000
+ async getTurkeyDistricts(cityCode) {
1001
+ return this.districts(
1002
+ `/integration/member/countries/domestic/TR/cities/${encodeURIComponent(String(cityCode))}/districts`
1003
+ );
1004
+ }
1005
+ async getTurkeyNeighborhoods(cityCode, districtCode) {
1006
+ return this.neighborhoods(
1007
+ `/integration/member/countries/domestic/TR/cities/${encodeURIComponent(String(cityCode))}/districts/${encodeURIComponent(String(districtCode))}/neighborhoods`
1008
+ );
1009
+ }
1010
+ async getAzerbaijanCities() {
1011
+ return this.cities(`/integration/member/countries/domestic/AZ/cities`);
1012
+ }
1013
+ async getAzerbaijanDistricts(cityCode) {
1014
+ return this.districts(
1015
+ `/integration/member/countries/domestic/AZ/cities/${encodeURIComponent(String(cityCode))}/districts`
1016
+ );
1017
+ }
1018
+ // ─── International (GULF / CEE) ───────────────────────────────────────
1019
+ async getCitiesByCountry(countryCode) {
1020
+ return this.cities(`/integration/member/countries/${encodeURIComponent(countryCode)}/cities`);
1021
+ }
1022
+ async getDistrictsByCity(countryCode, cityId) {
1023
+ return this.districts(
1024
+ `/integration/member/countries/${encodeURIComponent(countryCode)}/cities/${encodeURIComponent(String(cityId))}/districts`
1025
+ );
1026
+ }
1027
+ // ─── Shared paginators ────────────────────────────────────────────────
1028
+ async cities(path) {
1029
+ const data = await this.transport.request({
1030
+ method: "GET",
1031
+ path,
1032
+ rateLimiter: this.limiter
1033
+ });
1034
+ return n(data, (node) => ({
1035
+ code: String(node.code ?? node.id ?? ""),
1036
+ name: node.name,
1037
+ countryCode: node.countryCode
1038
+ }));
1039
+ }
1040
+ async districts(path) {
1041
+ const data = await this.transport.request({
1042
+ method: "GET",
1043
+ path,
1044
+ rateLimiter: this.limiter
1045
+ });
1046
+ return n(data, (node) => ({
1047
+ code: String(node.code ?? node.id ?? ""),
1048
+ name: node.name,
1049
+ cityCode: node.cityCode !== void 0 ? String(node.cityCode) : void 0
1050
+ }));
1051
+ }
1052
+ async neighborhoods(path) {
1053
+ const data = await this.transport.request({
1054
+ method: "GET",
1055
+ path,
1056
+ rateLimiter: this.limiter
1057
+ });
1058
+ return n(data, (node) => ({
1059
+ code: String(node.code ?? node.id ?? ""),
1060
+ name: node.name,
1061
+ districtCode: node.districtCode !== void 0 ? String(node.districtCode) : void 0
1062
+ }));
1063
+ }
1064
+ };
1065
+ var MAX_PAGE_SIZE = 200;
1066
+ var DEFAULT_PAGE_SIZE2 = 50;
1067
+ function toIso3(epochMs) {
1068
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs) || epochMs === 0) {
1069
+ return void 0;
1070
+ }
1071
+ return new Date(epochMs).toISOString();
1072
+ }
1073
+ function normalizeAddress(node) {
1074
+ if (!node) return void 0;
1075
+ const out = {};
1076
+ if (node.id !== void 0) out.id = String(node.id);
1077
+ if (node.firstName !== void 0) out.firstName = node.firstName;
1078
+ if (node.lastName !== void 0) out.lastName = node.lastName;
1079
+ if (node.fullName !== void 0) out.fullName = node.fullName;
1080
+ if (node.company !== void 0) out.company = node.company;
1081
+ if (node.address1 !== void 0) out.address1 = node.address1;
1082
+ if (node.address2 !== void 0) out.address2 = node.address2;
1083
+ if (node.fullAddress !== void 0) out.fullAddress = node.fullAddress;
1084
+ if (node.shortAddress !== void 0) out.shortAddress = node.shortAddress;
1085
+ if (node.city !== void 0) out.city = node.city;
1086
+ if (node.cityCode !== void 0) out.cityCode = node.cityCode;
1087
+ if (node.district !== void 0) out.district = node.district;
1088
+ if (node.districtId !== void 0) out.districtId = node.districtId;
1089
+ if (node.neighborhoodId !== void 0) out.neighborhoodId = node.neighborhoodId;
1090
+ if (node.countyId !== void 0) out.countyId = node.countyId;
1091
+ if (node.countyName !== void 0) out.countyName = node.countyName;
1092
+ if (node.stateName !== void 0) out.stateName = node.stateName;
1093
+ if (node.postalCode !== void 0) out.postalCode = node.postalCode;
1094
+ if (node.countryCode !== void 0) out.countryCode = node.countryCode;
1095
+ if (node.phone !== void 0) out.phone = node.phone;
1096
+ if (node.addressLines !== void 0) out.addressLines = node.addressLines;
1097
+ return out;
1098
+ }
1099
+ function normalizeLine(node) {
1100
+ const out = {
1101
+ id: node.lineId !== void 0 ? String(node.lineId) : "",
1102
+ quantity: typeof node.quantity === "number" ? node.quantity : 0,
1103
+ productName: node.productName ?? "",
1104
+ barcode: node.barcode ?? "",
1105
+ lineUnitPrice: typeof node.lineUnitPrice === "number" ? node.lineUnitPrice : 0,
1106
+ lineGrossAmount: typeof node.lineGrossAmount === "number" ? node.lineGrossAmount : 0,
1107
+ raw: node
1108
+ };
1109
+ if (node.productSize !== void 0) out.productSize = node.productSize;
1110
+ if (node.productColor !== void 0) out.productColor = node.productColor;
1111
+ if (node.stockCode !== void 0) out.stockCode = node.stockCode;
1112
+ if (node.contentId !== void 0) out.contentId = String(node.contentId);
1113
+ if (node.sellerId !== void 0) out.sellerId = String(node.sellerId);
1114
+ if (node.productCategoryId !== void 0) out.productCategoryId = String(node.productCategoryId);
1115
+ if (node.salesCampaignId !== void 0) out.salesCampaignId = String(node.salesCampaignId);
1116
+ if (node.currencyCode !== void 0) out.currencyCode = node.currencyCode;
1117
+ if (node.lineSellerDiscount !== void 0) out.lineSellerDiscount = node.lineSellerDiscount;
1118
+ if (node.lineTyDiscount !== void 0) out.lineTyDiscount = node.lineTyDiscount;
1119
+ if (node.lineTotalDiscount !== void 0) out.lineTotalDiscount = node.lineTotalDiscount;
1120
+ if (node.vatRate !== void 0) out.vatRate = node.vatRate;
1121
+ if (node.commission !== void 0) out.commission = node.commission;
1122
+ if (node.orderLineItemStatusName !== void 0) {
1123
+ out.orderLineItemStatusName = node.orderLineItemStatusName;
1124
+ }
1125
+ if (node.businessUnit !== void 0) out.businessUnit = node.businessUnit;
1126
+ if (Array.isArray(node.fastDeliveryOptions)) out.fastDeliveryOptions = node.fastDeliveryOptions;
1127
+ if (Array.isArray(node.discountDetails)) {
1128
+ out.discountDetails = node.discountDetails;
1129
+ }
1130
+ return out;
1131
+ }
1132
+ function normalizeHistory(node) {
1133
+ const out = { raw: node };
1134
+ if (node.status !== void 0) out.status = node.status;
1135
+ const createdAt = toIso3(node.createdDate);
1136
+ if (createdAt) out.createdAt = createdAt;
1137
+ return out;
1138
+ }
1139
+ function normalizeCustomer(node) {
1140
+ const out = {
1141
+ firstName: node.customerFirstName ?? "",
1142
+ lastName: node.customerLastName ?? ""
1143
+ };
1144
+ if (node.customerId !== void 0) out.id = String(node.customerId);
1145
+ if (node.customerEmail !== void 0) out.email = node.customerEmail;
1146
+ if (node.taxNumber !== void 0 && node.taxNumber !== null) out.taxNumber = node.taxNumber;
1147
+ if (node.identityNumber !== void 0) out.identityNumber = node.identityNumber;
1148
+ return out;
1149
+ }
1150
+ function normalizePackage2(node) {
1151
+ const pkgId = node.shipmentPackageId ?? node.id;
1152
+ const out = {
1153
+ id: pkgId !== void 0 ? String(pkgId) : "",
1154
+ orderNumber: node.orderNumber ?? "",
1155
+ status: node.status ?? "",
1156
+ customer: normalizeCustomer(node),
1157
+ orderDate: toIso3(node.orderDate) ?? "",
1158
+ lastModifiedDate: toIso3(node.lastModifiedDate) ?? "",
1159
+ currencyCode: node.currencyCode ?? "",
1160
+ packageTotalPrice: typeof node.packageTotalPrice === "number" ? node.packageTotalPrice : 0,
1161
+ packageGrossAmount: typeof node.packageGrossAmount === "number" ? node.packageGrossAmount : 0,
1162
+ packageSellerDiscount: typeof node.packageSellerDiscount === "number" ? node.packageSellerDiscount : 0,
1163
+ packageTyDiscount: typeof node.packageTyDiscount === "number" ? node.packageTyDiscount : 0,
1164
+ packageTotalDiscount: typeof node.packageTotalDiscount === "number" ? node.packageTotalDiscount : 0,
1165
+ lines: (node.lines ?? []).map(normalizeLine),
1166
+ packageHistories: (node.packageHistories ?? []).map(normalizeHistory),
1167
+ raw: node
1168
+ };
1169
+ if (node.shipmentNumber !== void 0) out.shipmentNumber = String(node.shipmentNumber);
1170
+ if (node.originPackageIds !== void 0 && node.originPackageIds !== null) {
1171
+ out.originPackageIds = node.originPackageIds.map((id) => String(id));
1172
+ }
1173
+ if (node.warehouseId !== void 0) out.warehouseId = String(node.warehouseId);
1174
+ if (node.supplierId !== void 0) out.supplierId = String(node.supplierId);
1175
+ if (node.shipmentPackageStatus !== void 0) {
1176
+ out.shipmentPackageStatus = node.shipmentPackageStatus;
1177
+ }
1178
+ const agreed = toIso3(node.agreedDeliveryDate);
1179
+ if (agreed) out.agreedDeliveryDate = agreed;
1180
+ const estStart = toIso3(node.estimatedDeliveryStartDate);
1181
+ if (estStart) out.estimatedDeliveryStartDate = estStart;
1182
+ const estEnd = toIso3(node.estimatedDeliveryEndDate);
1183
+ if (estEnd) out.estimatedDeliveryEndDate = estEnd;
1184
+ const origin = toIso3(node.originShipmentDate);
1185
+ if (origin) out.originShipmentDate = origin;
1186
+ const invoice = normalizeAddress(node.invoiceAddress);
1187
+ if (invoice) out.invoiceAddress = invoice;
1188
+ const shipment = normalizeAddress(node.shipmentAddress);
1189
+ if (shipment) out.shipmentAddress = shipment;
1190
+ if (node.deliveryAddressType !== void 0) out.deliveryAddressType = node.deliveryAddressType;
1191
+ if (node.cargoTrackingNumber !== void 0) {
1192
+ out.cargoTrackingNumber = String(node.cargoTrackingNumber);
1193
+ }
1194
+ if (node.cargoProviderName !== void 0) out.cargoProviderName = node.cargoProviderName;
1195
+ if (node.cargoProviderId !== void 0) out.cargoProviderId = String(node.cargoProviderId);
1196
+ if (node.cargoSenderNumber !== void 0) out.cargoSenderNumber = node.cargoSenderNumber;
1197
+ if (node.deliveryType !== void 0) out.deliveryType = node.deliveryType;
1198
+ if (node.whoPays !== void 0) out.whoPays = node.whoPays;
1199
+ if (node.timeSlotId !== void 0) out.timeSlotId = node.timeSlotId;
1200
+ if (typeof node.fastDelivery === "boolean") out.fastDelivery = node.fastDelivery;
1201
+ if (node.fastDeliveryType !== void 0) out.fastDeliveryType = node.fastDeliveryType;
1202
+ if (typeof node.deliveredByService === "boolean")
1203
+ out.deliveredByService = node.deliveredByService;
1204
+ if (typeof node.commercial === "boolean") out.commercial = node.commercial;
1205
+ if (typeof node.micro === "boolean") out.micro = node.micro;
1206
+ if (typeof node.giftBoxRequested === "boolean") out.giftBoxRequested = node.giftBoxRequested;
1207
+ if (typeof node["3pByTrendyol"] === "boolean") {
1208
+ out.threePByTrendyol = node["3pByTrendyol"];
1209
+ }
1210
+ if (typeof node.containsDangerousProduct === "boolean") {
1211
+ out.containsDangerousProduct = node.containsDangerousProduct;
1212
+ }
1213
+ if (typeof node.isCod === "boolean") out.isCod = node.isCod;
1214
+ if (typeof node.is4P === "boolean") out.is4P = node.is4P;
1215
+ if (node.invoiceLink !== void 0) out.invoiceLink = node.invoiceLink;
1216
+ if (node.createdBy !== void 0) out.createdBy = node.createdBy;
1217
+ return out;
1218
+ }
1219
+ var OrdersResource = class {
1220
+ constructor(transport, limiter) {
1221
+ this.transport = transport;
1222
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
1223
+ }
1224
+ transport;
1225
+ limiter;
1226
+ /**
1227
+ * List shipment packages for the seller.
1228
+ *
1229
+ * @example
1230
+ * ```ts
1231
+ * import { paginate } from '@lonca/core';
1232
+ * for await (const pkg of paginate((p) => client.orders.list({ ...p, status: 'Created' }))) {
1233
+ * console.log(pkg.id, pkg.status, pkg.customer.firstName);
1234
+ * }
1235
+ * ```
1236
+ */
1237
+ async list(params = {}) {
1238
+ const size = Math.min(params.limit ?? DEFAULT_PAGE_SIZE2, MAX_PAGE_SIZE);
1239
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
1240
+ const query = { page, size };
1241
+ if (params.status) query.status = params.status;
1242
+ if (params.orderNumber) query.orderNumber = params.orderNumber;
1243
+ if (params.startDate) query.startDate = params.startDate.getTime();
1244
+ if (params.endDate) query.endDate = params.endDate.getTime();
1245
+ const data = await this.transport.request({
1246
+ method: "GET",
1247
+ path: `/integration/order/sellers/${this.transport.sellerId}/orders`,
1248
+ query,
1249
+ rateLimiter: this.limiter
1250
+ });
1251
+ const items = (data.content ?? []).map(normalizePackage2);
1252
+ const totalPages = typeof data.totalPages === "number" ? data.totalPages : 0;
1253
+ const result = { items };
1254
+ if (page + 1 < totalPages) {
1255
+ result.nextCursor = String(page + 1);
1256
+ }
1257
+ return result;
1258
+ }
1259
+ /**
1260
+ * Push a shipment-package status update.
1261
+ *
1262
+ * Trendyol restricts the seller-side push to two transitions:
1263
+ * - `Picking` — order picked up from the shelf / being prepared
1264
+ * - `Invoiced` — invoice issued, ready for cargo handoff
1265
+ *
1266
+ * Other transitions (`Shipped`, `Delivered`, etc.) are driven by Trendyol
1267
+ * or the cargo provider — call `processAlternativeDelivery` or
1268
+ * `manualDeliverByPackageId` if you ship outside Trendyol's cargo
1269
+ * network.
1270
+ *
1271
+ * Returns void; Trendyol responds with 200 + empty body on success.
1272
+ */
1273
+ async updatePackageStatus(packageId, input) {
1274
+ await this.transport.request({
1275
+ method: "PUT",
1276
+ path: this.packagePath(packageId),
1277
+ body: input,
1278
+ rateLimiter: this.limiter
1279
+ });
1280
+ }
1281
+ /**
1282
+ * Notify Trendyol that one or more line items cannot be supplied
1283
+ * ("Tedarik Edememe Bildirimi"). Marks the listed line IDs as
1284
+ * `UnSupplied`. Trendyol cancels those quantities and notifies the
1285
+ * customer.
1286
+ *
1287
+ * `reasonId` is a numeric code Trendyol publishes separately — consult
1288
+ * the seller panel or the "Tedarik Edememe" docs for current values.
1289
+ *
1290
+ * Returns void; Trendyol responds with 200 + empty body on success.
1291
+ */
1292
+ async cancelPackageItem(packageId, input) {
1293
+ if (!Array.isArray(input?.lines) || input.lines.length === 0) {
1294
+ throw new ValidationError({ message: "cancelPackageItem: lines must not be empty" });
1295
+ }
1296
+ await this.transport.request({
1297
+ method: "PUT",
1298
+ path: `${this.packagePath(packageId)}/items/unsupplied`,
1299
+ body: input,
1300
+ rateLimiter: this.limiter
1301
+ });
1302
+ }
1303
+ /**
1304
+ * Extend the agreed delivery date for a shipment package by 1, 2, or 3 days.
1305
+ * Trendyol enforces the [1, 3] range server-side; the SDK validates client-side
1306
+ * to fail fast.
1307
+ *
1308
+ * Returns void; Trendyol responds with 200 + empty body on success.
1309
+ */
1310
+ async extendDeliveryDate(packageId, extendedDayCount) {
1311
+ if (![1, 2, 3].includes(extendedDayCount)) {
1312
+ throw new ValidationError({
1313
+ message: `extendDeliveryDate: extendedDayCount must be 1, 2, or 3 (got ${extendedDayCount})`
1314
+ });
1315
+ }
1316
+ await this.transport.request({
1317
+ method: "PUT",
1318
+ path: `${this.packagePath(packageId)}/extended-agreed-delivery-date`,
1319
+ body: { extendedDayCount },
1320
+ rateLimiter: this.limiter
1321
+ });
1322
+ }
1323
+ /**
1324
+ * Notify Trendyol of an alternative delivery channel — used when the
1325
+ * seller is shipping via a non-Trendyol cargo provider. Trendyol then
1326
+ * either SMSes the customer the tracking link (when `isPhoneNumber` is
1327
+ * `true`) or stores the tracking URL on the package directly.
1328
+ *
1329
+ * Returns void; Trendyol responds with 200 + empty body on success.
1330
+ */
1331
+ async processAlternativeDelivery(packageId, input) {
1332
+ await this.transport.request({
1333
+ method: "PUT",
1334
+ path: `${this.packagePath(packageId)}/alternative-delivery`,
1335
+ body: input,
1336
+ rateLimiter: this.limiter
1337
+ });
1338
+ }
1339
+ /**
1340
+ * Split a shipment package by moving a set of line IDs into a new
1341
+ * package. The original package keeps the remaining lines.
1342
+ *
1343
+ * @param packageId The package to split.
1344
+ * @param orderLineIds Line IDs to move into the new package (1+).
1345
+ * @throws {ValidationError} when `orderLineIds` is empty.
1346
+ */
1347
+ async splitPackage(packageId, orderLineIds) {
1348
+ if (!Array.isArray(orderLineIds) || orderLineIds.length === 0) {
1349
+ throw new ValidationError({ message: "splitPackage: orderLineIds must not be empty" });
1350
+ }
1351
+ await this.transport.request({
1352
+ method: "POST",
1353
+ path: `${this.packagePath(packageId)}/split`,
1354
+ body: { orderLineIds },
1355
+ rateLimiter: this.limiter
1356
+ });
1357
+ }
1358
+ /**
1359
+ * Split a shipment package by quantity. Each `QuantitySplit` entry
1360
+ * carves a single line into multiple packages — e.g. `{ orderLineId: 100,
1361
+ * quantities: [2, 2, 1] }` splits 5 units of line 100 into three packages
1362
+ * of 2 + 2 + 1.
1363
+ *
1364
+ * @throws {ValidationError} when `quantitySplit` is empty.
1365
+ */
1366
+ async splitPackageByQuantity(packageId, quantitySplit) {
1367
+ if (!Array.isArray(quantitySplit) || quantitySplit.length === 0) {
1368
+ throw new ValidationError({
1369
+ message: "splitPackageByQuantity: quantitySplit must not be empty"
1370
+ });
1371
+ }
1372
+ await this.transport.request({
1373
+ method: "POST",
1374
+ path: `${this.packagePath(packageId)}/quantity-split`,
1375
+ body: { quantitySplit },
1376
+ rateLimiter: this.limiter
1377
+ });
1378
+ }
1379
+ /**
1380
+ * Split a shipment package into multiple new packages by grouping line
1381
+ * IDs. Each `SplitGroup` becomes one new package containing the listed
1382
+ * line IDs.
1383
+ *
1384
+ * @throws {ValidationError} when `splitGroups` is empty.
1385
+ */
1386
+ async multiSplitPackage(packageId, splitGroups) {
1387
+ if (!Array.isArray(splitGroups) || splitGroups.length === 0) {
1388
+ throw new ValidationError({ message: "multiSplitPackage: splitGroups must not be empty" });
1389
+ }
1390
+ await this.transport.request({
1391
+ method: "POST",
1392
+ path: `${this.packagePath(packageId)}/multi-split`,
1393
+ body: { splitGroups },
1394
+ rateLimiter: this.limiter
1395
+ });
1396
+ }
1397
+ /**
1398
+ * Split a shipment package into multiple new packages, each containing a
1399
+ * mix of line items at specific quantities. This is the most expressive
1400
+ * split — use it when you need fine-grained control over which line IDs
1401
+ * and how many of each end up in each new package.
1402
+ *
1403
+ * @throws {ValidationError} when `splitPackages` is empty.
1404
+ */
1405
+ async splitMultiPackagesByQuantity(packageId, splitPackages) {
1406
+ if (!Array.isArray(splitPackages) || splitPackages.length === 0) {
1407
+ throw new ValidationError({
1408
+ message: "splitMultiPackagesByQuantity: splitPackages must not be empty"
1409
+ });
1410
+ }
1411
+ await this.transport.request({
1412
+ method: "POST",
1413
+ path: `${this.packagePath(packageId)}/split-packages`,
1414
+ body: { splitPackages },
1415
+ rateLimiter: this.limiter
1416
+ });
1417
+ }
1418
+ /**
1419
+ * Change the cargo provider on an existing shipment package. Use one of
1420
+ * Trendyol's documented marketplace cargo codes (`'YKMP'`, `'ARASMP'`,
1421
+ * `'SURATMP'`, etc.) — see `TrendyolCargoProvider` for the full list.
1422
+ */
1423
+ async changeCargoProvider(packageId, cargoProvider) {
1424
+ await this.transport.request({
1425
+ method: "PUT",
1426
+ path: `${this.packagePath(packageId)}/cargo-providers`,
1427
+ body: { cargoProvider },
1428
+ rateLimiter: this.limiter
1429
+ });
1430
+ }
1431
+ /**
1432
+ * Mark a shipment package as manually delivered via its package ID.
1433
+ * Used when the seller delivered the order outside Trendyol's cargo
1434
+ * network and needs to flip the package to `Delivered` after handover.
1435
+ *
1436
+ * No request body; Trendyol responds with 200 + empty body on success.
1437
+ */
1438
+ async manualDeliverByPackageId(packageId) {
1439
+ await this.transport.request({
1440
+ method: "PUT",
1441
+ path: `${this.packagePath(packageId)}/manual-invoice-delivery`,
1442
+ rateLimiter: this.limiter
1443
+ });
1444
+ }
1445
+ /**
1446
+ * Manual-deliver variant that takes the cargo tracking number instead
1447
+ * of the package ID. Useful when you only have the tracking number on
1448
+ * hand (e.g., from a cargo provider webhook).
1449
+ *
1450
+ * Note the path structure: tracking number sits at a sibling location,
1451
+ * not under `/shipment-packages/{id}/...`.
1452
+ */
1453
+ async manualDeliverByTrackingNumber(cargoTrackingNumber) {
1454
+ await this.transport.request({
1455
+ method: "PUT",
1456
+ path: `/integration/order/sellers/${this.transport.sellerId}/shipment-packages/manual-invoice-delivery-by-tracking-number/${encodeURIComponent(String(cargoTrackingNumber))}`,
1457
+ rateLimiter: this.limiter
1458
+ });
1459
+ }
1460
+ /**
1461
+ * Mark a package as delivered through an authorized service ("yetkili
1462
+ * servis"). For appliance / installation-required products that are
1463
+ * delivered + installed by a third-party service partner.
1464
+ */
1465
+ async markDeliveredByService(packageId) {
1466
+ await this.transport.request({
1467
+ method: "PUT",
1468
+ path: `${this.packagePath(packageId)}/delivered-by-service`,
1469
+ rateLimiter: this.limiter
1470
+ });
1471
+ }
1472
+ /**
1473
+ * Update box / packaging metadata on a shipment package (desi value
1474
+ * and/or number of boxes). Either field can be sent alone.
1475
+ */
1476
+ async updateBoxInfo(packageId, input) {
1477
+ await this.transport.request({
1478
+ method: "PUT",
1479
+ path: `${this.packagePath(packageId)}/box-info`,
1480
+ body: input,
1481
+ rateLimiter: this.limiter
1482
+ });
1483
+ }
1484
+ /**
1485
+ * Update labor costs for one or more order lines.
1486
+ *
1487
+ * **Wire note:** Trendyol's request body is a raw array (no envelope),
1488
+ * not `{ items: [...] }`. The SDK forwards `items` verbatim.
1489
+ *
1490
+ * @throws {ValidationError} when `items` is empty.
1491
+ */
1492
+ async updateLaborCosts(packageId, items) {
1493
+ if (!Array.isArray(items) || items.length === 0) {
1494
+ throw new ValidationError({ message: "updateLaborCosts: items must not be empty" });
1495
+ }
1496
+ await this.transport.request({
1497
+ method: "PUT",
1498
+ path: `${this.packagePath(packageId)}/labor-costs`,
1499
+ body: items,
1500
+ rateLimiter: this.limiter
1501
+ });
1502
+ }
1503
+ /**
1504
+ * Reassign a shipment package to a different warehouse. `warehouseId`
1505
+ * comes from `client.suppliers.getAddresses()` (filter by `isShipmentAddress`).
1506
+ */
1507
+ async updateWarehouse(packageId, warehouseId) {
1508
+ await this.transport.request({
1509
+ method: "PUT",
1510
+ path: `${this.packagePath(packageId)}/warehouse`,
1511
+ body: { warehouseId },
1512
+ rateLimiter: this.limiter
1513
+ });
1514
+ }
1515
+ /**
1516
+ * Stream variant of `list()`. Trendyol's `getShipmentPackagesStream`
1517
+ * returns the same `ShipmentPackage` shape but paginates with an opaque
1518
+ * cursor — useful when the dataset is large and page-based pagination
1519
+ * would hit the 10 000-record cap.
1520
+ *
1521
+ * @example
1522
+ * ```ts
1523
+ * import { paginate } from '@lonca/core';
1524
+ * for await (const pkg of paginate((p) =>
1525
+ * client.orders.listStream({ ...p, packageItemStatuses: 'Created,Picking' }),
1526
+ * )) {
1527
+ * console.log(pkg.id, pkg.status);
1528
+ * }
1529
+ * ```
1530
+ */
1531
+ async listStream(params = {}) {
1532
+ const size = Math.min(params.limit ?? DEFAULT_PAGE_SIZE2, MAX_PAGE_SIZE);
1533
+ const query = { size };
1534
+ if (params.cursor) query.nextCursor = params.cursor;
1535
+ if (params.packageItemStatuses) query.packageItemStatuses = params.packageItemStatuses;
1536
+ if (params.lastModifiedStartDate) {
1537
+ query.lastModifiedStartDate = params.lastModifiedStartDate.getTime();
1538
+ }
1539
+ if (params.lastModifiedEndDate) {
1540
+ query.lastModifiedEndDate = params.lastModifiedEndDate.getTime();
1541
+ }
1542
+ const data = await this.transport.request({
1543
+ method: "GET",
1544
+ path: `/integration/order/sellers/${this.transport.sellerId}/orders/stream`,
1545
+ query,
1546
+ rateLimiter: this.limiter
1547
+ });
1548
+ const items = (data.content ?? []).map(normalizePackage2);
1549
+ const result = { items };
1550
+ if (data.hasMore && data.nextCursor) {
1551
+ result.nextCursor = data.nextCursor;
1552
+ }
1553
+ return result;
1554
+ }
1555
+ /**
1556
+ * Fetch the per-parcel cargo-fee breakdown for a single cargo invoice
1557
+ * (Trendyol's `getCargoInvoiceItems`). Useful for reconciling Trendyol's
1558
+ * cargo deductions against your shipped packages.
1559
+ *
1560
+ * `invoiceSerialNumber` is sourced from the Current Account Statement
1561
+ * ("Cari Hesap Ekstresi") with `transactionType=DeductionInvoices`.
1562
+ *
1563
+ * Page-based pagination internally (cursor encodes the page index).
1564
+ */
1565
+ async getCargoInvoiceItems(invoiceSerialNumber, params = {}) {
1566
+ const size = Math.min(params.limit ?? 500, 500);
1567
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
1568
+ const data = await this.transport.request({
1569
+ method: "GET",
1570
+ path: `/integration/finance/che/sellers/${this.transport.sellerId}/cargo-invoice/${encodeURIComponent(invoiceSerialNumber)}/items`,
1571
+ query: { page, size },
1572
+ rateLimiter: this.limiter
1573
+ });
1574
+ const items = (data.content ?? []).map((row) => {
1575
+ const out = { raw: row };
1576
+ if (row.shipmentPackageType !== void 0) out.shipmentPackageType = row.shipmentPackageType;
1577
+ if (row.parcelUniqueId !== void 0) {
1578
+ out.parcelUniqueId = typeof row.parcelUniqueId === "string" ? row.parcelUniqueId : String(row.parcelUniqueId);
1579
+ }
1580
+ if (row.orderNumber !== void 0) out.orderNumber = row.orderNumber;
1581
+ if (typeof row.amount === "number") out.amount = row.amount;
1582
+ if (typeof row.desi === "number") out.desi = row.desi;
1583
+ return out;
1584
+ });
1585
+ const totalPages = typeof data.totalPages === "number" ? data.totalPages : 0;
1586
+ const result = { items };
1587
+ if (page + 1 < totalPages) {
1588
+ result.nextCursor = String(page + 1);
1589
+ }
1590
+ return result;
1591
+ }
1592
+ /**
1593
+ * Notify Trendyol that a shipped package was returned to you (manual
1594
+ * return flow, e.g. customer dropped it at your address or you got the
1595
+ * package back without going through Trendyol's return cargo).
1596
+ *
1597
+ * No body; Trendyol responds with 200 + empty body on success.
1598
+ */
1599
+ async manualReturnByPackageId(packageId) {
1600
+ await this.transport.request({
1601
+ method: "PUT",
1602
+ path: `${this.packagePath(packageId)}/manual-return`,
1603
+ rateLimiter: this.limiter
1604
+ });
1605
+ }
1606
+ /**
1607
+ * Manual-return variant that takes the cargo tracking number instead of
1608
+ * the package ID. Useful when the cargo provider's webhook only carries
1609
+ * the tracking number.
1610
+ *
1611
+ * Sibling path (not under `/{packageId}/...`).
1612
+ */
1613
+ async manualReturnByTrackingNumber(cargoTrackingNumber) {
1614
+ await this.transport.request({
1615
+ method: "PUT",
1616
+ path: `/integration/order/sellers/${this.transport.sellerId}/shipment-packages/manual-return-by-tracking-number/${encodeURIComponent(String(cargoTrackingNumber))}`,
1617
+ rateLimiter: this.limiter
1618
+ });
1619
+ }
1620
+ /**
1621
+ * Fetch Trendyol Express compensation tickets (claims filed when a
1622
+ * shipment is lost or damaged in transit). Page-based pagination
1623
+ * internally; the SDK exposes the cursor convention.
1624
+ *
1625
+ * Note the different base path — `/integration/tex/compensation/...`,
1626
+ * not the regular `/integration/order/...`.
1627
+ *
1628
+ * @example
1629
+ * ```ts
1630
+ * import { paginate } from '@lonca/core';
1631
+ * const tickets = await client.orders.getCompensationTickets({
1632
+ * startDate: new Date('2026-01-01'),
1633
+ * endDate: new Date('2026-02-01'),
1634
+ * });
1635
+ * for (const t of tickets.items) {
1636
+ * console.log(t.orderNumber, t.currentState, t.stateMessage);
1637
+ * }
1638
+ * ```
1639
+ */
1640
+ async getCompensationTickets(params = {}) {
1641
+ const size = Math.min(params.limit ?? 200, 200);
1642
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
1643
+ const query = { page, size };
1644
+ if (params.startDate) query.startDate = params.startDate.getTime();
1645
+ if (params.endDate) query.endDate = params.endDate.getTime();
1646
+ const res = await this.transport.request({
1647
+ method: "GET",
1648
+ path: `/integration/tex/compensation/sellers/${this.transport.sellerId}/tickets`,
1649
+ query,
1650
+ rateLimiter: this.limiter
1651
+ });
1652
+ const tickets = Array.isArray(res.data) ? res.data : res.data?.items ?? res.data?.content ?? res.content ?? [];
1653
+ const items = tickets.map((t) => {
1654
+ const itemDetails = (t.itemDetails ?? []).map((d) => {
1655
+ const out2 = {};
1656
+ if (typeof d.itemAmount === "number") out2.itemAmount = d.itemAmount;
1657
+ if (d.itemCode !== void 0) out2.itemCode = d.itemCode;
1658
+ if (typeof d.itemCount === "number") out2.itemCount = d.itemCount;
1659
+ if (d.itemName !== void 0) out2.itemName = d.itemName;
1660
+ return out2;
1661
+ });
1662
+ const out = {
1663
+ itemDetails,
1664
+ raw: t
1665
+ };
1666
+ if (t.cargoProvider !== void 0) out.cargoProvider = t.cargoProvider;
1667
+ if (t.compensateReason !== void 0) out.compensateReason = t.compensateReason;
1668
+ const createdAt = toIso3(t.createDate);
1669
+ if (createdAt) out.createdAt = createdAt;
1670
+ if (t.currentState !== void 0) {
1671
+ out.currentState = t.currentState;
1672
+ }
1673
+ if (t.deliveryNumber !== void 0) out.deliveryNumber = t.deliveryNumber;
1674
+ if (t.orderNumber !== void 0) out.orderNumber = t.orderNumber;
1675
+ if (t.requestedBy !== void 0) out.requestedBy = t.requestedBy;
1676
+ if (t.stateMessage !== void 0) out.stateMessage = t.stateMessage;
1677
+ if (t.totalItemsAmount !== void 0) out.totalItemsAmount = t.totalItemsAmount;
1678
+ return out;
1679
+ });
1680
+ const result = { items };
1681
+ const total = typeof res.totalCount === "number" ? res.totalCount : 0;
1682
+ if ((page + 1) * size < total) {
1683
+ result.nextCursor = String(page + 1);
1684
+ }
1685
+ return result;
1686
+ }
1687
+ packagePath(packageId) {
1688
+ return `/integration/order/sellers/${this.transport.sellerId}/shipment-packages/${encodeURIComponent(String(packageId))}`;
1689
+ }
1690
+ };
1691
+ var DEFAULT_PAGE_SIZE3 = 50;
1692
+ var MAX_PAGE_SIZE2 = 1e3;
1693
+ var MAX_BUYBOX_BARCODES = 10;
1694
+ function normalizeRef(ref) {
1695
+ return {
1696
+ id: ref?.id !== void 0 ? String(ref.id) : "",
1697
+ name: ref?.name ?? ""
1698
+ };
1699
+ }
1700
+ function normalizeAttribute2(attr) {
1701
+ const out = {
1702
+ attributeId: attr.attributeId !== void 0 ? String(attr.attributeId) : ""
1703
+ };
1704
+ if (attr.attributeName !== void 0) out.attributeName = attr.attributeName;
1705
+ if (attr.attributeValueId !== void 0) {
1706
+ out.attributeValueId = String(attr.attributeValueId);
1707
+ }
1708
+ if (attr.attributeValue !== void 0) out.attributeValue = attr.attributeValue;
1709
+ return out;
1710
+ }
1711
+ function normalizeImages(images) {
1712
+ if (!images) return [];
1713
+ return images.map((img) => typeof img === "string" ? img : img?.url).filter((u) => typeof u === "string" && u.length > 0);
1714
+ }
1715
+ function normalizeStock(stock) {
1716
+ if (typeof stock === "number") return stock;
1717
+ if (stock && typeof stock === "object" && typeof stock.quantity === "number") {
1718
+ return stock.quantity;
1719
+ }
1720
+ return void 0;
1721
+ }
1722
+ function normalizeVariant(variant) {
1723
+ const out = {
1724
+ variantId: variant.variantId !== void 0 ? String(variant.variantId) : "",
1725
+ barcode: variant.barcode ?? "",
1726
+ attributes: (variant.attributes ?? []).map(normalizeAttribute2),
1727
+ raw: variant
1728
+ };
1729
+ if (typeof variant.commission === "number") out.commission = variant.commission;
1730
+ if (variant.productUrl !== void 0) out.productUrl = variant.productUrl;
1731
+ if (typeof variant.onSale === "boolean") out.onSale = variant.onSale;
1732
+ const stock = normalizeStock(variant.stock);
1733
+ if (stock !== void 0) out.stock = stock;
1734
+ return out;
1735
+ }
1736
+ function toIso4(epochMs) {
1737
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs)) return void 0;
1738
+ return new Date(epochMs).toISOString();
1739
+ }
1740
+ function normalizeProduct(node) {
1741
+ const out = {
1742
+ contentId: node.contentId !== void 0 ? String(node.contentId) : "",
1743
+ productMainId: node.productMainId ?? "",
1744
+ title: node.title ?? "",
1745
+ brand: normalizeRef(node.brand),
1746
+ category: normalizeRef(node.category),
1747
+ images: normalizeImages(node.images),
1748
+ attributes: (node.attributes ?? []).map(normalizeAttribute2),
1749
+ variants: (node.variants ?? []).map(normalizeVariant),
1750
+ createdAt: toIso4(node.creationDate) ?? "",
1751
+ updatedAt: toIso4(node.lastModifiedDate) ?? "",
1752
+ raw: node
1753
+ };
1754
+ if (node.description !== void 0) out.description = node.description;
1755
+ if (node.lastModifiedBy !== void 0) out.lastModifiedBy = node.lastModifiedBy;
1756
+ return out;
1757
+ }
1758
+ function normalizeUnapprovedRejectReason(r) {
1759
+ const out = {};
1760
+ if (r.rejectReason !== void 0) out.rejectReason = r.rejectReason;
1761
+ if (r.rejectReasonDetail !== void 0) out.rejectReasonDetail = r.rejectReasonDetail;
1762
+ return out;
1763
+ }
1764
+ function normalizeUnapproved(node) {
1765
+ const imagesSource = node.images ?? node.media;
1766
+ const out = {
1767
+ productMainId: node.productMainId ?? "",
1768
+ brand: normalizeRef(node.brand),
1769
+ category: normalizeRef(node.category),
1770
+ barcode: node.barcode ?? "",
1771
+ title: node.title ?? "",
1772
+ images: normalizeImages(imagesSource),
1773
+ attributes: (node.attributes ?? []).map(normalizeAttribute2),
1774
+ rejectReasonDetails: (node.rejectReasonDetails ?? []).map(normalizeUnapprovedRejectReason),
1775
+ raw: node
1776
+ };
1777
+ if (node.supplierId !== void 0) out.supplierId = String(node.supplierId);
1778
+ if (node.status !== void 0) out.status = node.status;
1779
+ if (node.description !== void 0) out.description = node.description;
1780
+ if (typeof node.quantity === "number") out.quantity = node.quantity;
1781
+ if (typeof node.listPrice === "number") out.listPrice = node.listPrice;
1782
+ if (typeof node.salePrice === "number") out.salePrice = node.salePrice;
1783
+ if (typeof node.vatRate === "number") out.vatRate = node.vatRate;
1784
+ if (node.dimensionalWeight !== void 0 && node.dimensionalWeight !== null) {
1785
+ out.dimensionalWeight = node.dimensionalWeight;
1786
+ }
1787
+ if (node.stockCode !== void 0) out.stockCode = node.stockCode;
1788
+ if (node.origin !== void 0) out.origin = node.origin;
1789
+ if (node.locationBasedDelivery !== void 0) {
1790
+ out.locationBasedDelivery = node.locationBasedDelivery;
1791
+ }
1792
+ if (node.lotNumber !== void 0) out.lotNumber = node.lotNumber;
1793
+ if (node.specialConsumptionTax !== void 0) {
1794
+ out.specialConsumptionTax = node.specialConsumptionTax;
1795
+ }
1796
+ if (node.sgrPrice !== void 0) out.sgrPrice = node.sgrPrice;
1797
+ const createdAt = toIso4(node.createDateTime);
1798
+ if (createdAt) out.createdAt = createdAt;
1799
+ const updatedAt = toIso4(node.lastUpdateDate);
1800
+ if (updatedAt) out.updatedAt = updatedAt;
1801
+ const priceChanged = toIso4(node.lastPriceChangeDate);
1802
+ if (priceChanged) out.lastPriceChangedAt = priceChanged;
1803
+ const stockChanged = toIso4(node.lastStockChangeDate);
1804
+ if (stockChanged) out.lastStockChangedAt = stockChanged;
1805
+ return out;
1806
+ }
1807
+ function normalizeBuyboxInfo(node) {
1808
+ const out = {
1809
+ barcode: node.barcode ?? "",
1810
+ raw: node
1811
+ };
1812
+ if (typeof node.buyboxOrder === "number") out.buyboxOrder = node.buyboxOrder;
1813
+ if (typeof node.buyboxPrice === "number") out.buyboxPrice = node.buyboxPrice;
1814
+ if (typeof node.hasMultipleSeller === "boolean") {
1815
+ out.hasMultipleSeller = node.hasMultipleSeller;
1816
+ }
1817
+ if (node.secondBuyboxPrice !== void 0) out.secondBuyboxPrice = node.secondBuyboxPrice;
1818
+ if (node.thirdBuyboxPrice !== void 0) out.thirdBuyboxPrice = node.thirdBuyboxPrice;
1819
+ return out;
1820
+ }
1821
+ function normalizeProductBase(data) {
1822
+ const out = {
1823
+ barcode: data.barcode ?? "",
1824
+ approved: !!data.approved,
1825
+ archived: !!data.archived,
1826
+ raw: data
1827
+ };
1828
+ const approvedAt = toIso4(data.approvedDate);
1829
+ if (approvedAt) out.approvedAt = approvedAt;
1830
+ if (data.listingId !== void 0) out.listingId = data.listingId;
1831
+ if (data.contentId !== void 0) out.contentId = String(data.contentId);
1832
+ return out;
1833
+ }
1834
+ function normalizeBatchResult(data) {
1835
+ const items = (data.items ?? []).map((item) => {
1836
+ const result = {};
1837
+ if (item.requestItem !== void 0) result.requestItem = item.requestItem;
1838
+ if (item.status !== void 0) result.status = item.status;
1839
+ if (item.failureReasons !== void 0) result.failureReasons = item.failureReasons;
1840
+ return result;
1841
+ });
1842
+ const out = {
1843
+ batchRequestId: typeof data.batchRequestId === "string" ? data.batchRequestId : "",
1844
+ status: data.status ?? "PROCESSING",
1845
+ items,
1846
+ raw: data
1847
+ };
1848
+ if (typeof data.itemCount === "number") out.itemCount = data.itemCount;
1849
+ if (typeof data.failedItemCount === "number") out.failedItemCount = data.failedItemCount;
1850
+ const createdAt = toIso4(data.creationDate);
1851
+ if (createdAt) out.createdAt = createdAt;
1852
+ const lastModifiedAt = toIso4(data.lastModification);
1853
+ if (lastModifiedAt) out.lastModifiedAt = lastModifiedAt;
1854
+ if (data.sourceType !== void 0) out.sourceType = data.sourceType;
1855
+ if (data.batchRequestType !== void 0) out.batchRequestType = data.batchRequestType;
1856
+ if (data.notes !== void 0) out.notes = data.notes;
1857
+ if (data.objectKey !== void 0) out.objectKey = data.objectKey;
1858
+ if (data.storeFrontCode !== void 0) out.storeFrontCode = data.storeFrontCode;
1859
+ return out;
1860
+ }
1861
+ var MAX_WRITE_ITEMS = 1e3;
1862
+ var DELETE_RATE_PER_MIN = 100;
1863
+ var ProductsResource = class {
1864
+ constructor(transport, options = {}) {
1865
+ this.transport = transport;
1866
+ this.filterLimiter = options.filterLimiter ?? new TokenBucketRateLimiter({ capacity: 2e3, intervalMs: 6e4 });
1867
+ this.batchLimiter = options.batchLimiter ?? new TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
1868
+ this.buyboxLimiter = options.buyboxLimiter ?? new TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
1869
+ this.writeLimiter = options.writeLimiter ?? new TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
1870
+ this.deleteLimiter = options.deleteLimiter ?? new TokenBucketRateLimiter({ capacity: DELETE_RATE_PER_MIN, intervalMs: 6e4 });
1871
+ }
1872
+ transport;
1873
+ filterLimiter;
1874
+ batchLimiter;
1875
+ buyboxLimiter;
1876
+ writeLimiter;
1877
+ deleteLimiter;
1878
+ validateBarcodes(barcodes, methodLabel) {
1879
+ if (!Array.isArray(barcodes) || barcodes.length === 0) {
1880
+ throw new ValidationError({ message: `${methodLabel}: barcodes must not be empty` });
1881
+ }
1882
+ if (barcodes.length > MAX_WRITE_ITEMS) {
1883
+ throw new ValidationError({
1884
+ message: `${methodLabel}: max ${MAX_WRITE_ITEMS} barcodes per call (got ${barcodes.length})`
1885
+ });
1886
+ }
1887
+ }
1888
+ async submitWrite(endpoint, items, methodLabel) {
1889
+ if (!Array.isArray(items) || items.length === 0) {
1890
+ throw new ValidationError({ message: `${methodLabel}: items must not be empty` });
1891
+ }
1892
+ if (items.length > MAX_WRITE_ITEMS) {
1893
+ throw new ValidationError({
1894
+ message: `${methodLabel}: max ${MAX_WRITE_ITEMS} items per call (got ${items.length})`
1895
+ });
1896
+ }
1897
+ const data = await this.transport.request({
1898
+ method: "POST",
1899
+ path: `/integration/product/sellers/${this.transport.sellerId}${endpoint}`,
1900
+ body: { items },
1901
+ rateLimiter: this.writeLimiter
1902
+ });
1903
+ return { batchRequestId: data?.batchRequestId ?? "" };
1904
+ }
1905
+ /**
1906
+ * List approved products. Use `paginate()` from `@lonca/core` to iterate
1907
+ * lazily across pages.
1908
+ *
1909
+ * Trendyol exposes both page-based and `nextPageToken`-based pagination
1910
+ * (the latter required when the dataset exceeds 10,000 items). The SDK
1911
+ * picks the right strategy automatically — pass our opaque `cursor` from
1912
+ * the previous response and we forward it as `nextPageToken`.
1913
+ *
1914
+ * @example
1915
+ * ```ts
1916
+ * import { paginate } from '@lonca/core';
1917
+ * for await (const product of paginate((p) => client.products.list(p))) {
1918
+ * for (const variant of product.variants) {
1919
+ * console.log(variant.barcode, product.title);
1920
+ * }
1921
+ * }
1922
+ * ```
1923
+ */
1924
+ async list(params = {}) {
1925
+ const size = Math.min(params.limit ?? DEFAULT_PAGE_SIZE3, MAX_PAGE_SIZE2);
1926
+ const query = { size };
1927
+ if (params.cursor) {
1928
+ query.nextPageToken = params.cursor;
1929
+ } else {
1930
+ query.page = 0;
1931
+ }
1932
+ if (params.barcode) query.barcode = params.barcode;
1933
+ if (params.startDate) query.startDate = params.startDate.getTime();
1934
+ if (params.endDate) query.endDate = params.endDate.getTime();
1935
+ const data = await this.transport.request({
1936
+ method: "GET",
1937
+ path: `/integration/product/sellers/${this.transport.sellerId}/products/approved`,
1938
+ query,
1939
+ rateLimiter: this.filterLimiter
1940
+ });
1941
+ const items = (data.content ?? []).map(normalizeProduct);
1942
+ const page = { items };
1943
+ if (data.nextPageToken) {
1944
+ page.nextCursor = data.nextPageToken;
1945
+ }
1946
+ return page;
1947
+ }
1948
+ /**
1949
+ * Poll a batch request returned by an async write (e.g. `createProducts`,
1950
+ * `updatePriceAndInventory`).
1951
+ *
1952
+ * Trendyol retains batch results for **4 hours** after the originating
1953
+ * request — poll within that window.
1954
+ *
1955
+ * @param batchRequestId The opaque ID returned by the originating call.
1956
+ */
1957
+ async getBatchStatus(batchRequestId) {
1958
+ const id = encodeURIComponent(batchRequestId);
1959
+ const data = await this.transport.request({
1960
+ method: "GET",
1961
+ path: `/integration/product/sellers/${this.transport.sellerId}/products/batch-requests/${id}`,
1962
+ rateLimiter: this.batchLimiter
1963
+ });
1964
+ return normalizeBatchResult(data);
1965
+ }
1966
+ /**
1967
+ * List **unapproved** (draft / rejected / pending-review) products.
1968
+ *
1969
+ * Wire shape is intentionally flatter than the approved-product shape:
1970
+ * each barcode is one top-level item with `barcode`, `quantity`, `salePrice`
1971
+ * etc. at the root. Rejected drafts carry `rejectReasonDetails` so you can
1972
+ * surface why Trendyol's content team turned them down.
1973
+ *
1974
+ * Pagination follows the same convention as `list()`: `cursor` from the
1975
+ * previous response forwards as `nextPageToken`.
1976
+ *
1977
+ * @example
1978
+ * ```ts
1979
+ * const page = await client.products.listUnapproved({ limit: 50 });
1980
+ * for (const draft of page.items) {
1981
+ * if (draft.status === 'rejected') {
1982
+ * console.warn(draft.barcode, draft.rejectReasonDetails);
1983
+ * }
1984
+ * }
1985
+ * ```
1986
+ */
1987
+ async listUnapproved(params = {}) {
1988
+ const size = Math.min(params.limit ?? DEFAULT_PAGE_SIZE3, MAX_PAGE_SIZE2);
1989
+ const query = { size };
1990
+ if (params.cursor) {
1991
+ query.nextPageToken = params.cursor;
1992
+ } else {
1993
+ query.page = 0;
1994
+ }
1995
+ if (params.barcode) query.barcode = params.barcode;
1996
+ if (params.startDate) query.startDate = params.startDate.getTime();
1997
+ if (params.endDate) query.endDate = params.endDate.getTime();
1998
+ if (params.dateQueryType) query.dateQueryType = params.dateQueryType;
1999
+ if (params.supplierId !== void 0) query.supplierId = params.supplierId;
2000
+ const data = await this.transport.request({
2001
+ method: "GET",
2002
+ path: `/integration/product/sellers/${this.transport.sellerId}/products/unapproved`,
2003
+ query,
2004
+ rateLimiter: this.filterLimiter
2005
+ });
2006
+ const items = (data.content ?? []).map(normalizeUnapproved);
2007
+ const page = { items };
2008
+ if (data.nextPageToken) {
2009
+ page.nextCursor = data.nextPageToken;
2010
+ }
2011
+ return page;
2012
+ }
2013
+ /**
2014
+ * Fetch the basic lifecycle status of a single product by barcode.
2015
+ *
2016
+ * Cheap and useful as a polling primitive after `createProducts`: poll
2017
+ * this endpoint until `approved` flips to `true` (or use
2018
+ * `client.products.getBatchStatus()` to track the originating batch).
2019
+ *
2020
+ * @param barcode The product barcode to look up.
2021
+ */
2022
+ async getBase(barcode) {
2023
+ const code = encodeURIComponent(barcode);
2024
+ const data = await this.transport.request({
2025
+ method: "GET",
2026
+ path: `/integration/product/sellers/${this.transport.sellerId}/product/${code}`,
2027
+ rateLimiter: this.filterLimiter
2028
+ });
2029
+ return normalizeProductBase(data);
2030
+ }
2031
+ /**
2032
+ * Fetch buybox information for up to 10 barcodes in one call.
2033
+ *
2034
+ * Returns rank (`buyboxOrder === 1` means you hold the buybox), the
2035
+ * current buybox price, and — beyond the spec — the second and third
2036
+ * competing prices when other sellers are present.
2037
+ *
2038
+ * @param barcodes 1–10 product barcodes.
2039
+ * @throws {ValidationError} when `barcodes` is empty or longer than 10.
2040
+ */
2041
+ async getBuyboxInfo(barcodes) {
2042
+ if (!Array.isArray(barcodes) || barcodes.length === 0) {
2043
+ throw new ValidationError({
2044
+ message: "getBuyboxInfo: barcodes must be a non-empty array"
2045
+ });
2046
+ }
2047
+ if (barcodes.length > MAX_BUYBOX_BARCODES) {
2048
+ throw new ValidationError({
2049
+ message: `getBuyboxInfo: max ${MAX_BUYBOX_BARCODES} barcodes per call (got ${barcodes.length})`
2050
+ });
2051
+ }
2052
+ const data = await this.transport.request({
2053
+ method: "POST",
2054
+ path: `/integration/product/sellers/${this.transport.sellerId}/products/buybox-information`,
2055
+ body: { barcodes },
2056
+ rateLimiter: this.buyboxLimiter
2057
+ });
2058
+ const list = data.buyboxInfo ?? data.content ?? [];
2059
+ return list.map(normalizeBuyboxInfo);
2060
+ }
2061
+ /**
2062
+ * Create products (V2). Async batch — returns a `batchRequestId` you can
2063
+ * poll with `getBatchStatus`. Max 1000 items per call.
2064
+ *
2065
+ * Trendyol requires the full V2 attribute payload — fetch via
2066
+ * `categories.getAttributes` (and `categories.getAttributeValues` for
2067
+ * values when `allowCustom === false`). Shipment / returning warehouse
2068
+ * IDs come from `suppliers.getAddresses`.
2069
+ *
2070
+ * @throws {ValidationError} when `items` is empty or longer than 1000.
2071
+ */
2072
+ async create(items) {
2073
+ return this.submitWrite("/v2/products", items, "createProducts");
2074
+ }
2075
+ /**
2076
+ * Update **content** of approved products (title, description, images,
2077
+ * attributes). Identified by `contentId`. Partial update is supported
2078
+ * except for attributes — if you update ANY attribute, send ALL of them.
2079
+ *
2080
+ * @throws {ValidationError} when `items` is empty or longer than 1000.
2081
+ */
2082
+ async updateContent(items) {
2083
+ return this.submitWrite("/products/content-bulk-update", items, "updateContent");
2084
+ }
2085
+ /**
2086
+ * Update **variant** fields of approved products (stockCode, vatRate,
2087
+ * dimensionalWeight, warehouse IDs, location-based delivery, lot). Identified
2088
+ * by `barcode`. The barcode itself cannot be changed via this endpoint.
2089
+ *
2090
+ * @throws {ValidationError} when `items` is empty or longer than 1000.
2091
+ */
2092
+ async updateVariants(items) {
2093
+ return this.submitWrite("/products/variant-bulk-update", items, "updateVariants");
2094
+ }
2095
+ /**
2096
+ * Update **unapproved** (draft) products. Identified by `barcode`. All
2097
+ * other fields are optional partial updates. Use this to fix drafts that
2098
+ * Trendyol rejected — `client.products.listUnapproved` surfaces the
2099
+ * `rejectReasonDetails` you need to act on.
2100
+ *
2101
+ * **Gotcha (verified live STAGE 2026-05-25):** Trendyol's V2 spec claims
2102
+ * only `barcode` is required, but the endpoint returns HTTP 500
2103
+ * (`TrendyolSystemException` / `TypeError`) when too many optional fields
2104
+ * are omitted. In practice, send at least `title`, `description`,
2105
+ * `productMainId`, `brandId`, `categoryId`, `stockCode`,
2106
+ * `dimensionalWeight`, `vatRate`, `images[]`, and `attributes[]` (an
2107
+ * empty array is OK for the latter). The SDK forwards your payload
2108
+ * as-is; trim fields only if you have verified the server accepts it.
2109
+ *
2110
+ * @throws {ValidationError} when `items` is empty or longer than 1000.
2111
+ */
2112
+ async updateUnapproved(items) {
2113
+ return this.submitWrite("/products/unapproved-bulk-update", items, "updateUnapproved");
2114
+ }
2115
+ /**
2116
+ * Update product **delivery information** (deliveryDuration,
2117
+ * fastDeliveryType). Identified by `barcode`.
2118
+ *
2119
+ * @throws {ValidationError} when `items` is empty or longer than 1000.
2120
+ */
2121
+ async updateDeliveryInfo(items) {
2122
+ return this.submitWrite("/products/delivery-info-bulk-update", items, "updateDeliveryInfo");
2123
+ }
2124
+ /**
2125
+ * Delete products by barcode. Trendyol allows deletion of unapproved
2126
+ * products and approved products that have been archived for more than a
2127
+ * day (and have not been sales-stopped by Trendyol).
2128
+ *
2129
+ * Async batch — returns `{ batchRequestId }` to poll via `getBatchStatus`.
2130
+ * Separately rate-limited at **100 req/min** (much tighter than create/update).
2131
+ *
2132
+ * @param barcodes 1–1000 barcodes.
2133
+ * @throws {ValidationError} when `barcodes` is empty or longer than 1000.
2134
+ */
2135
+ async delete(barcodes) {
2136
+ this.validateBarcodes(barcodes, "delete");
2137
+ const data = await this.transport.request({
2138
+ method: "DELETE",
2139
+ path: `/integration/product/sellers/${this.transport.sellerId}/products`,
2140
+ body: { items: barcodes.map((barcode) => ({ barcode })) },
2141
+ rateLimiter: this.deleteLimiter
2142
+ });
2143
+ return { batchRequestId: data?.batchRequestId ?? "" };
2144
+ }
2145
+ /**
2146
+ * Archive products by barcode (Trendyol's `archived=true` state).
2147
+ * Archived products are not visible to customers; pair with `delete`
2148
+ * after the 24-hour archive cool-down to remove them entirely.
2149
+ *
2150
+ * Async batch — returns `{ batchRequestId }`.
2151
+ *
2152
+ * @throws {ValidationError} when `barcodes` is empty or longer than 1000.
2153
+ */
2154
+ async archive(barcodes) {
2155
+ return this.setArchivedState(barcodes, true, "archive");
2156
+ }
2157
+ /**
2158
+ * Unarchive products by barcode (Trendyol's `archived=false` state).
2159
+ * Restores visibility for previously-archived products.
2160
+ *
2161
+ * @throws {ValidationError} when `barcodes` is empty or longer than 1000.
2162
+ */
2163
+ async unarchive(barcodes) {
2164
+ return this.setArchivedState(barcodes, false, "unarchive");
2165
+ }
2166
+ async setArchivedState(barcodes, archived, methodLabel) {
2167
+ this.validateBarcodes(barcodes, methodLabel);
2168
+ const data = await this.transport.request({
2169
+ method: "PUT",
2170
+ path: `/integration/product/sellers/${this.transport.sellerId}/products/archive-state`,
2171
+ body: { items: barcodes.map((barcode) => ({ barcode, archived })) },
2172
+ rateLimiter: this.writeLimiter
2173
+ });
2174
+ return { batchRequestId: data?.batchRequestId ?? "" };
2175
+ }
2176
+ /**
2177
+ * Unlock products whose sale was paused by Trendyol due to pricing
2178
+ * issues (under/over-pricing, critical price error, supplier issues).
2179
+ * Restores selling status for the listed barcodes.
2180
+ *
2181
+ * Async batch — returns `{ batchRequestId }`.
2182
+ *
2183
+ * @throws {ValidationError} when `barcodes` is empty or longer than 1000.
2184
+ */
2185
+ async unlock(barcodes) {
2186
+ this.validateBarcodes(barcodes, "unlock");
2187
+ const data = await this.transport.request({
2188
+ method: "PUT",
2189
+ path: `/integration/product/sellers/${this.transport.sellerId}/products/unlock`,
2190
+ body: { items: barcodes.map((barcode) => ({ barcode })) },
2191
+ rateLimiter: this.writeLimiter
2192
+ });
2193
+ return { batchRequestId: data?.batchRequestId ?? "" };
2194
+ }
2195
+ };
2196
+ function toIso5(epochMs) {
2197
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs) || epochMs === 0) {
2198
+ return void 0;
2199
+ }
2200
+ return new Date(epochMs).toISOString();
2201
+ }
2202
+ function normalizeAnswer(a) {
2203
+ if (!a) return void 0;
2204
+ const out = {};
2205
+ if (a.text !== void 0) out.text = a.text;
2206
+ const createdAt = toIso5(a.creationDate);
2207
+ if (createdAt) out.createdAt = createdAt;
2208
+ if (a.status !== void 0) out.status = a.status;
2209
+ return out;
2210
+ }
2211
+ function normalizeQuestion(node) {
2212
+ const out = {
2213
+ id: node.id !== void 0 ? String(node.id) : "",
2214
+ raw: node
2215
+ };
2216
+ if (node.text !== void 0) out.text = node.text;
2217
+ if (node.customerId !== void 0) out.customerId = String(node.customerId);
2218
+ if (node.userName !== void 0) out.userName = node.userName;
2219
+ if (typeof node.showUserName === "boolean") out.showUserName = node.showUserName;
2220
+ if (node.status !== void 0) out.status = node.status;
2221
+ if (typeof node.public === "boolean") out.public = node.public;
2222
+ if (node.productMainId !== void 0) out.productMainId = node.productMainId;
2223
+ if (node.productName !== void 0) out.productName = node.productName;
2224
+ if (node.imageUrl !== void 0) out.imageUrl = node.imageUrl;
2225
+ if (node.webUrl !== void 0) out.webUrl = node.webUrl;
2226
+ const createdAt = toIso5(node.creationDate);
2227
+ if (createdAt) out.createdAt = createdAt;
2228
+ if (node.answeredDateMessage !== void 0) out.answeredDateMessage = node.answeredDateMessage;
2229
+ const answer = normalizeAnswer(node.answer);
2230
+ if (answer) out.answer = answer;
2231
+ const rejectedAnswer = normalizeAnswer(node.rejectedAnswer);
2232
+ if (rejectedAnswer) out.rejectedAnswer = rejectedAnswer;
2233
+ const rejectedAt = toIso5(node.rejectedDate);
2234
+ if (rejectedAt) out.rejectedAt = rejectedAt;
2235
+ if (node.reason !== void 0) out.reason = node.reason;
2236
+ if (node.reportReason !== void 0) out.reportReason = node.reportReason;
2237
+ const reportedAt = toIso5(node.reportedDate);
2238
+ if (reportedAt) out.reportedAt = reportedAt;
2239
+ return out;
2240
+ }
2241
+ var QuestionsResource = class {
2242
+ constructor(transport, limiter) {
2243
+ this.transport = transport;
2244
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 500, intervalMs: 6e4 });
2245
+ }
2246
+ transport;
2247
+ limiter;
2248
+ /** Fetch a single question by its numeric ID. */
2249
+ async get(questionId) {
2250
+ const data = await this.transport.request({
2251
+ method: "GET",
2252
+ path: `/integration/qna/sellers/${this.transport.sellerId}/questions/${encodeURIComponent(String(questionId))}`,
2253
+ rateLimiter: this.limiter
2254
+ });
2255
+ return normalizeQuestion(data);
2256
+ }
2257
+ /**
2258
+ * Filter questions by barcode / date range / status. Page-based
2259
+ * pagination internally; SDK exposes the opaque-cursor convention.
2260
+ */
2261
+ async list(params = {}) {
2262
+ const size = Math.min(params.limit ?? 50, 200);
2263
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
2264
+ const query = { page, size };
2265
+ if (params.barcode) query.barcode = params.barcode;
2266
+ if (params.startDate) query.startDate = params.startDate.getTime();
2267
+ if (params.endDate) query.endDate = params.endDate.getTime();
2268
+ if (params.status) query.status = params.status;
2269
+ const data = await this.transport.request({
2270
+ method: "GET",
2271
+ path: `/integration/qna/sellers/${this.transport.sellerId}/questions/filter`,
2272
+ query,
2273
+ rateLimiter: this.limiter
2274
+ });
2275
+ const items = (data.content ?? []).map(normalizeQuestion);
2276
+ const result = { items };
2277
+ const totalPages = typeof data.totalPages === "number" ? data.totalPages : 0;
2278
+ if (page + 1 < totalPages) {
2279
+ result.nextCursor = String(page + 1);
2280
+ }
2281
+ return result;
2282
+ }
2283
+ /**
2284
+ * Reply to a question. Trendyol enforces 10–2000 characters on the
2285
+ * answer text; the SDK pre-validates client-side.
2286
+ *
2287
+ * @throws {ValidationError} when `text` is outside the 10–2000 char range.
2288
+ */
2289
+ async answer(questionId, text) {
2290
+ if (typeof text !== "string" || text.length < 10) {
2291
+ throw new ValidationError({
2292
+ message: `questions.answer: text must be at least 10 chars (got ${text?.length ?? 0})`
2293
+ });
2294
+ }
2295
+ if (text.length > 2e3) {
2296
+ throw new ValidationError({
2297
+ message: `questions.answer: text must be at most 2000 chars (got ${text.length})`
2298
+ });
2299
+ }
2300
+ return this.transport.request({
2301
+ method: "POST",
2302
+ path: `/integration/qna/sellers/${this.transport.sellerId}/questions/${encodeURIComponent(String(questionId))}/answers`,
2303
+ body: { text },
2304
+ rateLimiter: this.limiter
2305
+ });
2306
+ }
2307
+ };
2308
+ var VALID_TYPES = /* @__PURE__ */ new Set([
2309
+ "SHIPMENT",
2310
+ "RETURNING",
2311
+ "INVOICE",
2312
+ "WAREHOUSE"
2313
+ ]);
2314
+ function normalizeAddressType(raw) {
2315
+ if (raw && VALID_TYPES.has(raw)) {
2316
+ return raw;
2317
+ }
2318
+ const stripped = raw?.replace(/_ADDRESS$/, "");
2319
+ if (stripped && VALID_TYPES.has(stripped)) {
2320
+ return stripped;
2321
+ }
2322
+ return "SHIPMENT";
2323
+ }
2324
+ function normalizeAddress2(node) {
2325
+ return {
2326
+ id: String(node.id),
2327
+ name: node.name,
2328
+ addressType: normalizeAddressType(node.addressType),
2329
+ isShipmentAddress: node.isShipmentAddress ?? false,
2330
+ isReturningAddress: node.isReturningAddress ?? false,
2331
+ isInvoiceAddress: node.isInvoiceAddress ?? false,
2332
+ isDefault: node.isDefault ?? false,
2333
+ address: node.address,
2334
+ city: node.city,
2335
+ district: node.district,
2336
+ postCode: node.postCode,
2337
+ fullName: node.fullName
2338
+ };
2339
+ }
2340
+ var DEFAULT_CACHE_TTL_MS = 60 * 60 * 1e3;
2341
+ var SuppliersResource = class {
2342
+ constructor(transport, options = {}) {
2343
+ this.transport = transport;
2344
+ this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
2345
+ this.limiter = new TokenBucketRateLimiter({
2346
+ capacity: 1,
2347
+ intervalMs: DEFAULT_CACHE_TTL_MS
2348
+ });
2349
+ }
2350
+ transport;
2351
+ cache = null;
2352
+ cacheTtlMs;
2353
+ limiter;
2354
+ inflight = null;
2355
+ /**
2356
+ * List the seller's registered addresses (shipment, returning, invoice, warehouse).
2357
+ *
2358
+ * Returns the cached value if it is still fresh. Concurrent calls share a
2359
+ * single in-flight request.
2360
+ */
2361
+ async getAddresses(options = {}) {
2362
+ if (!options.forceRefresh && this.cache && this.cache.expiresAt > Date.now()) {
2363
+ return this.cache.value;
2364
+ }
2365
+ if (this.inflight) return this.inflight;
2366
+ this.inflight = this.fetchFresh().finally(() => {
2367
+ this.inflight = null;
2368
+ });
2369
+ return this.inflight;
2370
+ }
2371
+ /** Drop the cache; the next `getAddresses()` call hits the API. */
2372
+ invalidateCache() {
2373
+ this.cache = null;
2374
+ }
2375
+ async fetchFresh() {
2376
+ const data = await this.transport.request({
2377
+ method: "GET",
2378
+ path: `/integration/sellers/${this.transport.sellerId}/addresses`,
2379
+ rateLimiter: this.limiter
2380
+ });
2381
+ const items = data.supplierAddresses.map(normalizeAddress2);
2382
+ this.cache = { value: items, expiresAt: Date.now() + this.cacheTtlMs };
2383
+ return items;
2384
+ }
2385
+ };
2386
+ var TestOrdersResource = class {
2387
+ constructor(transport, limiter) {
2388
+ this.transport = transport;
2389
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 60, intervalMs: 6e4 });
2390
+ }
2391
+ transport;
2392
+ limiter;
2393
+ /**
2394
+ * Create a test order with the given customer / addresses / lines. The
2395
+ * SDK forwards the typed payload verbatim — drill into Trendyol's
2396
+ * `createTestOrder` doc for inner field rules.
2397
+ *
2398
+ * @throws {ValidationError} when required top-level fields are missing.
2399
+ */
2400
+ async create(input) {
2401
+ for (const k of ["customer", "invoiceAddress", "shippingAddress", "seller", "lines"]) {
2402
+ if (!input?.[k]) {
2403
+ throw new ValidationError({ message: `testOrders.create: ${k} is required` });
2404
+ }
2405
+ }
2406
+ return this.transport.request({
2407
+ method: "POST",
2408
+ path: `/integration/test/order/orders/core`,
2409
+ body: input,
2410
+ rateLimiter: this.limiter
2411
+ });
2412
+ }
2413
+ /** Push a test shipment package to the given status. */
2414
+ async updateStatus(packageId, status) {
2415
+ return this.transport.request({
2416
+ method: "PUT",
2417
+ path: `/integration/test/order/sellers/${this.transport.sellerId}/shipment-packages/${encodeURIComponent(String(packageId))}/status`,
2418
+ body: { status },
2419
+ rateLimiter: this.limiter
2420
+ });
2421
+ }
2422
+ /** Move test claims to the `WaitingInAction` state. */
2423
+ async setClaimsWaitingInAction() {
2424
+ return this.transport.request({
2425
+ method: "PUT",
2426
+ path: `/integration/test/order/sellers/${this.transport.sellerId}/claims/waiting-in-action`,
2427
+ rateLimiter: this.limiter
2428
+ });
2429
+ }
2430
+ };
2431
+ var VideosResource = class {
2432
+ constructor(transport, options = {}) {
2433
+ this.transport = transport;
2434
+ this.createLimiter = options.createLimiter ?? new TokenBucketRateLimiter({ capacity: 200, intervalMs: 6e4 });
2435
+ this.listLimiter = options.listLimiter ?? new TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
2436
+ }
2437
+ transport;
2438
+ createLimiter;
2439
+ listLimiter;
2440
+ /**
2441
+ * Queue a video for upload. Trendyol downloads from the URL in the
2442
+ * body asynchronously; poll `list()` (filtered by id) for status.
2443
+ *
2444
+ * @throws {ValidationError} when `input` is empty / not an object.
2445
+ */
2446
+ async create(input) {
2447
+ if (!input || typeof input !== "object") {
2448
+ throw new ValidationError({ message: "videos.create: input is required" });
2449
+ }
2450
+ return this.transport.request({
2451
+ method: "POST",
2452
+ path: `/integration/video/sellers/${this.transport.sellerId}/videos`,
2453
+ body: input,
2454
+ rateLimiter: this.createLimiter
2455
+ });
2456
+ }
2457
+ /** List the seller's integration videos (optionally filtered by id / status). */
2458
+ async list(params = {}) {
2459
+ const data = await this.transport.request({
2460
+ method: "GET",
2461
+ path: `/integration/video/sellers/${this.transport.sellerId}/videos`,
2462
+ query: {
2463
+ id: params.id,
2464
+ sellerIntegrationStatus: params.sellerIntegrationStatus,
2465
+ page: params.offset,
2466
+ size: params.limit
2467
+ },
2468
+ rateLimiter: this.listLimiter
2469
+ });
2470
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.content) ? data.content : Array.isArray(data?.items) ? data.items : [];
2471
+ return rows.map((r) => {
2472
+ const row = r ?? {};
2473
+ const out = { raw: row };
2474
+ if (typeof row.id === "string") out.id = row.id;
2475
+ if (typeof row.status === "string") out.status = row.status;
2476
+ return out;
2477
+ });
2478
+ }
2479
+ };
2480
+ function normalizeWebhook(node) {
2481
+ const out = {
2482
+ id: node.id !== void 0 ? String(node.id) : "",
2483
+ raw: node
2484
+ };
2485
+ if (node.url !== void 0) out.url = node.url;
2486
+ if (node.authenticationType !== void 0) out.authenticationType = node.authenticationType;
2487
+ if (node.username !== void 0) out.username = node.username;
2488
+ if (node.apiKey !== void 0) out.apiKey = node.apiKey;
2489
+ if (node.subscribedStatuses !== void 0) out.subscribedStatuses = node.subscribedStatuses;
2490
+ if (typeof node.active === "boolean") out.active = node.active;
2491
+ else if (typeof node.isActive === "boolean") out.active = node.isActive;
2492
+ else if (typeof node.status === "string") out.active = node.status.toUpperCase() === "ACTIVE";
2493
+ return out;
2494
+ }
2495
+ var WebhooksResource = class {
2496
+ constructor(transport, limiter) {
2497
+ this.transport = transport;
2498
+ this.limiter = limiter ?? new TokenBucketRateLimiter({ capacity: 50, intervalMs: 6e4 });
2499
+ }
2500
+ transport;
2501
+ limiter;
2502
+ /**
2503
+ * Create a new webhook subscription. Trendyol caps subscriptions at 15
2504
+ * per seller — the SDK does NOT pre-check (you'd need to call `list()`
2505
+ * first), but Trendyol returns 400 when the cap is exceeded.
2506
+ *
2507
+ * @throws {ValidationError} when `url` or `authenticationType` is missing.
2508
+ */
2509
+ async create(input) {
2510
+ this.validateInput(input, "create");
2511
+ return this.transport.request({
2512
+ method: "POST",
2513
+ path: `/integration/sellers/${this.transport.sellerId}/webhooks`,
2514
+ body: input,
2515
+ rateLimiter: this.limiter
2516
+ });
2517
+ }
2518
+ /** List all registered webhook subscriptions. */
2519
+ async list() {
2520
+ const data = await this.transport.request({
2521
+ method: "GET",
2522
+ path: `/integration/sellers/${this.transport.sellerId}/webhooks`,
2523
+ rateLimiter: this.limiter
2524
+ });
2525
+ const rows = Array.isArray(data) ? data : Array.isArray(data?.webhooks) ? data.webhooks : Array.isArray(data?.content) ? data.content : [];
2526
+ return rows.map((r) => normalizeWebhook(r));
2527
+ }
2528
+ /**
2529
+ * Update a webhook subscription. Same input shape as `create`; replaces
2530
+ * the whole subscription (Trendyol does NOT partially update).
2531
+ */
2532
+ async update(webhookId, input) {
2533
+ this.validateInput(input, "update");
2534
+ return this.transport.request({
2535
+ method: "PUT",
2536
+ path: this.webhookPath(webhookId),
2537
+ body: input,
2538
+ rateLimiter: this.limiter
2539
+ });
2540
+ }
2541
+ /** Permanently delete a webhook subscription. */
2542
+ async delete(webhookId) {
2543
+ return this.transport.request({
2544
+ method: "DELETE",
2545
+ path: this.webhookPath(webhookId),
2546
+ rateLimiter: this.limiter
2547
+ });
2548
+ }
2549
+ /** Re-activate a previously-deactivated webhook subscription. */
2550
+ async activate(webhookId) {
2551
+ return this.transport.request({
2552
+ method: "PUT",
2553
+ path: `${this.webhookPath(webhookId)}/activate`,
2554
+ rateLimiter: this.limiter
2555
+ });
2556
+ }
2557
+ /**
2558
+ * Deactivate a webhook subscription. Trendyol automatically deactivates
2559
+ * a subscription after persistent delivery failures (and sends 2 emails);
2560
+ * use `activate()` to bring it back online once your endpoint is healthy.
2561
+ */
2562
+ async deactivate(webhookId) {
2563
+ return this.transport.request({
2564
+ method: "PUT",
2565
+ path: `${this.webhookPath(webhookId)}/deactivate`,
2566
+ rateLimiter: this.limiter
2567
+ });
2568
+ }
2569
+ validateInput(input, method) {
2570
+ if (!input?.url || typeof input.url !== "string") {
2571
+ throw new ValidationError({ message: `webhooks.${method}: url is required` });
2572
+ }
2573
+ if (input.authenticationType !== "BASIC_AUTHENTICATION" && input.authenticationType !== "API_KEY") {
2574
+ throw new ValidationError({
2575
+ message: `webhooks.${method}: authenticationType must be 'BASIC_AUTHENTICATION' or 'API_KEY'`
2576
+ });
2577
+ }
2578
+ if (input.authenticationType === "BASIC_AUTHENTICATION") {
2579
+ if (!input.username || !input.password) {
2580
+ throw new ValidationError({
2581
+ message: `webhooks.${method}: BASIC_AUTHENTICATION requires username + password`
2582
+ });
2583
+ }
2584
+ } else if (!input.apiKey) {
2585
+ throw new ValidationError({
2586
+ message: `webhooks.${method}: API_KEY requires apiKey`
2587
+ });
2588
+ }
2589
+ if (input.subscribedStatuses && input.subscribedStatuses.length === 0) ;
2590
+ }
2591
+ webhookPath(webhookId) {
2592
+ return `/integration/sellers/${this.transport.sellerId}/webhooks/${encodeURIComponent(String(webhookId))}`;
2593
+ }
2594
+ };
2595
+
2596
+ // src/capabilities.ts
2597
+ var trendyolCapabilities = {
2598
+ /** Trendyol has no time-bounded / scheduled pricing (`pricings[]`). */
2599
+ scheduledPricing: false,
2600
+ /** `inventory.update` accepts stock-only items (`quantity` with no price). */
2601
+ stockOnlyBatch: true,
2602
+ /** Products expose `updatedAt`, so last-write-wins guards are supported. */
2603
+ listingUpdatedAt: true
2604
+ };
2605
+
2606
+ // src/auth.ts
2607
+ function buildAuthHeader(apiKey, apiSecret) {
2608
+ const token = Buffer.from(`${apiKey}:${apiSecret}`, "utf8").toString("base64");
2609
+ return `Basic ${token}`;
2610
+ }
2611
+ function buildUserAgent(sellerId, integratorName) {
2612
+ return `${sellerId} - ${integratorName}`;
2613
+ }
2614
+ function mapHttpError(status, body, retryAfterMs) {
2615
+ const data = { body };
2616
+ const issues = normalizeErrorIssues(body);
2617
+ switch (status) {
2618
+ case 401:
2619
+ return new AuthError({
2620
+ message: "Trendyol authentication failed (check apiKey / apiSecret)",
2621
+ status,
2622
+ data,
2623
+ issues
2624
+ });
2625
+ case 403:
2626
+ return new ValidationError({
2627
+ message: "Trendyol forbidden (check User-Agent header or endpoint path)",
2628
+ status,
2629
+ data,
2630
+ issues
2631
+ });
2632
+ case 404:
2633
+ return new NotFoundError({ message: "Trendyol resource not found", status, data, issues });
2634
+ case 429:
2635
+ return new RateLimitError({
2636
+ message: "Trendyol rate limit exceeded",
2637
+ status,
2638
+ retryAfterMs,
2639
+ data,
2640
+ issues
2641
+ });
2642
+ case 500:
2643
+ case 502:
2644
+ case 503:
2645
+ case 504:
2646
+ return new ServerError({
2647
+ message: `Trendyol server error (${status})`,
2648
+ status,
2649
+ data,
2650
+ issues
2651
+ });
2652
+ default:
2653
+ return new LoncaError({
2654
+ code: "UNKNOWN",
2655
+ message: `Trendyol unexpected response (${status})`,
2656
+ status,
2657
+ data,
2658
+ issues,
2659
+ retryable: false
2660
+ });
2661
+ }
2662
+ }
2663
+ function normalizeErrorIssues(body) {
2664
+ const errors = extractErrorsArray(body);
2665
+ if (!errors) return [];
2666
+ const issues = [];
2667
+ for (const entry of errors) {
2668
+ if (typeof entry === "string") {
2669
+ issues.push({ message: entry });
2670
+ continue;
2671
+ }
2672
+ if (entry && typeof entry === "object") {
2673
+ const e = entry;
2674
+ if (typeof e.message !== "string") continue;
2675
+ const issue = { message: e.message };
2676
+ if (typeof e.field === "string") issue.field = e.field;
2677
+ if (typeof e.code === "string") issue.code = e.code;
2678
+ issues.push(issue);
2679
+ }
2680
+ }
2681
+ return issues;
2682
+ }
2683
+ function extractErrorsArray(body) {
2684
+ if (!body || typeof body !== "object") return void 0;
2685
+ const b = body;
2686
+ if (Array.isArray(b.errors)) return b.errors;
2687
+ const nested = b.body;
2688
+ if (nested && typeof nested === "object") {
2689
+ const n2 = nested;
2690
+ if (Array.isArray(n2.errors)) return n2.errors;
2691
+ }
2692
+ return void 0;
2693
+ }
2694
+ function parseRetryAfter(header) {
2695
+ if (!header) return void 0;
2696
+ const seconds = Number(header);
2697
+ if (!Number.isNaN(seconds)) return Math.max(0, seconds * 1e3);
2698
+ const epoch = Date.parse(header);
2699
+ if (!Number.isNaN(epoch)) return Math.max(0, epoch - Date.now());
2700
+ return void 0;
2701
+ }
2702
+
2703
+ // src/transport.ts
2704
+ var BASE_URLS = {
2705
+ prod: "https://apigw.trendyol.com",
2706
+ stage: "https://stageapigw.trendyol.com"
2707
+ };
2708
+ var TrendyolTransport = class {
2709
+ constructor(config) {
2710
+ this.config = config;
2711
+ this.baseUrl = BASE_URLS[config.env];
2712
+ this.logger = config.logger ?? noopLogger;
2713
+ this.timeoutMs = config.timeoutMs ?? 3e4;
2714
+ this.fetchImpl = config.fetch ?? fetch;
2715
+ }
2716
+ config;
2717
+ baseUrl;
2718
+ logger;
2719
+ timeoutMs;
2720
+ fetchImpl;
2721
+ /** Seller ID this transport is configured with. Resources read it for path-building. */
2722
+ get sellerId() {
2723
+ return this.config.sellerId;
2724
+ }
2725
+ async request(opts) {
2726
+ return retry(
2727
+ async (attempt) => {
2728
+ if (opts.rateLimiter) await opts.rateLimiter.acquire(opts.signal);
2729
+ const url = this.buildUrl(opts.path, opts.query);
2730
+ const correlationId = randomUUID();
2731
+ const headers = this.buildHeaders(correlationId);
2732
+ const init = {
2733
+ method: opts.method,
2734
+ headers,
2735
+ signal: this.composeSignal(opts.signal)
2736
+ };
2737
+ if (opts.body !== void 0 && opts.method !== "GET") {
2738
+ if (opts.body instanceof FormData) {
2739
+ init.body = opts.body;
2740
+ delete headers["Content-Type"];
2741
+ } else {
2742
+ init.body = JSON.stringify(opts.body);
2743
+ }
2744
+ }
2745
+ this.logger.debug("trendyol.request", {
2746
+ method: opts.method,
2747
+ url,
2748
+ correlationId,
2749
+ attempt
2750
+ });
2751
+ let response;
2752
+ try {
2753
+ response = await this.fetchImpl(url, init);
2754
+ } catch (err) {
2755
+ if (err instanceof Error && err.name === "AbortError") {
2756
+ throw new TimeoutError({
2757
+ message: `Trendyol request timed out after ${this.timeoutMs}ms`,
2758
+ cause: err
2759
+ });
2760
+ }
2761
+ throw new NetworkError({
2762
+ message: "Trendyol network failure",
2763
+ cause: err
2764
+ });
2765
+ }
2766
+ if (!response.ok) {
2767
+ const body = await safeJson(response);
2768
+ const retryAfterMs = parseRetryAfter(response.headers.get("retry-after"));
2769
+ const error = mapHttpError(response.status, body, retryAfterMs);
2770
+ this.logger.warn("trendyol.error", {
2771
+ method: opts.method,
2772
+ url,
2773
+ correlationId,
2774
+ status: response.status,
2775
+ code: error.code,
2776
+ retryable: error.retryable
2777
+ });
2778
+ throw error;
2779
+ }
2780
+ this.logger.debug("trendyol.response", {
2781
+ correlationId,
2782
+ status: response.status
2783
+ });
2784
+ if (response.status === 204) return void 0;
2785
+ return await safeJson(response);
2786
+ },
2787
+ {
2788
+ signal: opts.signal,
2789
+ onRetry: (err, attempt, delay2) => {
2790
+ if (err instanceof LoncaError) {
2791
+ this.logger.warn("trendyol.retry", {
2792
+ attempt,
2793
+ delayMs: delay2,
2794
+ code: err.code,
2795
+ status: err.status
2796
+ });
2797
+ }
2798
+ }
2799
+ }
2800
+ );
2801
+ }
2802
+ buildUrl(path, query) {
2803
+ const url = new URL(path, this.baseUrl);
2804
+ if (query) {
2805
+ for (const [key, value] of Object.entries(query)) {
2806
+ if (value === void 0) continue;
2807
+ url.searchParams.set(key, String(value));
2808
+ }
2809
+ }
2810
+ return url.toString();
2811
+ }
2812
+ buildHeaders(correlationId) {
2813
+ return {
2814
+ Authorization: buildAuthHeader(this.config.apiKey, this.config.apiSecret),
2815
+ "x-clientip": this.config.clientIp ?? "127.0.0.1",
2816
+ "x-correlationid": correlationId,
2817
+ "x-agentname": this.config.integratorName,
2818
+ "User-Agent": buildUserAgent(this.config.sellerId, this.config.integratorName),
2819
+ "Content-Type": "application/json",
2820
+ Accept: "application/json"
2821
+ };
2822
+ }
2823
+ composeSignal(external) {
2824
+ const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
2825
+ if (!external) return timeoutSignal;
2826
+ return AbortSignal.any([external, timeoutSignal]);
2827
+ }
2828
+ };
2829
+ async function safeJson(response) {
2830
+ const text = await response.text();
2831
+ if (!text) return void 0;
2832
+ try {
2833
+ return JSON.parse(text);
2834
+ } catch {
2835
+ return text;
2836
+ }
2837
+ }
2838
+
2839
+ // src/client.ts
2840
+ function buildClient(transport) {
2841
+ const products = new ProductsResource(transport);
2842
+ return {
2843
+ brands: new BrandsResource(transport),
2844
+ categories: new CategoriesResource(transport),
2845
+ suppliers: new SuppliersResource(transport),
2846
+ products,
2847
+ inventory: new InventoryResource(transport, (id) => products.getBatchStatus(id)),
2848
+ orders: new OrdersResource(transport),
2849
+ claims: new ClaimsResource(transport),
2850
+ webhooks: new WebhooksResource(transport),
2851
+ questions: new QuestionsResource(transport),
2852
+ invoices: new InvoicesResource(transport),
2853
+ finance: new FinanceResource(transport),
2854
+ labels: new LabelsResource(transport),
2855
+ testOrders: new TestOrdersResource(transport),
2856
+ locations: new LocationsResource(transport),
2857
+ exportCenter: new ExportCenterResource(transport),
2858
+ videos: new VideosResource(transport),
2859
+ capabilities: trendyolCapabilities
2860
+ };
2861
+ }
2862
+
2863
+ // src/testing.ts
2864
+ function createFakeTrendyolClient(seed = {}) {
2865
+ const batchRequestId = seed.batchRequestId ?? "fake-batch-1";
2866
+ const batchStatus = seed.batchStatus ?? "COMPLETED";
2867
+ const fakeFetch = (input, init) => {
2868
+ const rawUrl = typeof input === "string" ? input : input instanceof URL ? input.href : input.url;
2869
+ const url = new URL(rawUrl);
2870
+ const req = {
2871
+ method: (init?.method ?? "GET").toUpperCase(),
2872
+ path: url.pathname,
2873
+ query: url.searchParams,
2874
+ body: parseBody(init?.body)
2875
+ };
2876
+ const handled = seed.handler?.(req);
2877
+ const data = handled !== void 0 ? handled : defaultResponse(req, batchRequestId, batchStatus);
2878
+ return Promise.resolve(jsonResponse(data));
2879
+ };
2880
+ const transport = new TrendyolTransport({
2881
+ sellerId: 1,
2882
+ apiKey: "fake",
2883
+ apiSecret: "fake",
2884
+ env: "stage",
2885
+ integratorName: "fake",
2886
+ fetch: fakeFetch
2887
+ });
2888
+ return buildClient(transport);
2889
+ }
2890
+ function defaultResponse(req, batchRequestId, batchStatus) {
2891
+ if (req.method === "POST" && req.path.endsWith("/products/price-and-inventory")) {
2892
+ return { batchRequestId };
2893
+ }
2894
+ if (req.method === "GET" && req.path.includes("/products/batch-requests/")) {
2895
+ const id = decodeURIComponent(req.path.split("/").pop() ?? batchRequestId);
2896
+ return { batchRequestId: id, status: batchStatus, itemCount: 0, failedItemCount: 0, items: [] };
2897
+ }
2898
+ return {};
2899
+ }
2900
+ function parseBody(body) {
2901
+ if (typeof body !== "string") return void 0;
2902
+ try {
2903
+ return JSON.parse(body);
2904
+ } catch {
2905
+ return body;
2906
+ }
2907
+ }
2908
+ function jsonResponse(data) {
2909
+ return new Response(JSON.stringify(data), {
2910
+ status: 200,
2911
+ headers: { "content-type": "application/json" }
2912
+ });
2913
+ }
2914
+
2915
+ export { createFakeTrendyolClient };
2916
+ //# sourceMappingURL=testing.js.map
2917
+ //# sourceMappingURL=testing.js.map