@lonca/trendyol 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Lonca contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/dist/index.cjs CHANGED
@@ -28,7 +28,7 @@ var BrandsResource = class {
28
28
  const size = params.limit ?? DEFAULT_PAGE_SIZE;
29
29
  const data = await this.transport.request({
30
30
  method: "GET",
31
- path: "/sapigw/brands",
31
+ path: "/integration/product/brands",
32
32
  query: { page, size },
33
33
  rateLimiter: this.limiter
34
34
  });
@@ -37,6 +37,576 @@ var BrandsResource = class {
37
37
  return nextCursor !== void 0 ? { items, nextCursor } : { items };
38
38
  }
39
39
  };
40
+ function normalizeCategory(node) {
41
+ return {
42
+ id: String(node.id),
43
+ name: node.name,
44
+ parentId: node.parentId === null || node.parentId === void 0 ? null : String(node.parentId),
45
+ subCategories: (node.subCategories ?? []).map(normalizeCategory)
46
+ };
47
+ }
48
+ function normalizeAttribute(node) {
49
+ const attr = node.attribute ?? { id: 0, name: "" };
50
+ const rawValues = node.attributeValues ?? [];
51
+ const out = {
52
+ id: String(attr.id),
53
+ name: attr.name,
54
+ required: !!node.required,
55
+ allowCustom: !!node.allowCustom,
56
+ varianter: !!node.varianter,
57
+ slicer: !!node.slicer,
58
+ values: rawValues.map((v) => ({ id: String(v.id), name: v.name }))
59
+ };
60
+ if (node.categoryId !== void 0) {
61
+ out.categoryId = String(node.categoryId);
62
+ }
63
+ if (node.allowMultipleAttributeValues !== void 0) {
64
+ out.allowMultipleAttributeValues = node.allowMultipleAttributeValues;
65
+ }
66
+ return out;
67
+ }
68
+ var CategoriesResource = class {
69
+ constructor(transport, limiter) {
70
+ this.transport = transport;
71
+ this.limiter = limiter ?? new core.TokenBucketRateLimiter({ capacity: 50, intervalMs: 6e4 });
72
+ }
73
+ transport;
74
+ limiter;
75
+ /**
76
+ * Fetch the full Trendyol category tree.
77
+ *
78
+ * Trendyol returns the entire tree in one response — there is no pagination.
79
+ * Cache the result aggressively in your application; the tree changes rarely.
80
+ */
81
+ async list() {
82
+ const data = await this.transport.request({
83
+ method: "GET",
84
+ path: "/integration/product/product-categories",
85
+ rateLimiter: this.limiter
86
+ });
87
+ const list = Array.isArray(data) ? data : data.categories;
88
+ return list.map(normalizeCategory);
89
+ }
90
+ /**
91
+ * Fetch the attributes (required and optional) for a single category.
92
+ *
93
+ * Call this before `createProduct V2` so you know which attributes are
94
+ * mandatory — the API rejects products that omit any `required` attribute.
95
+ *
96
+ * @param categoryId Trendyol numeric category ID; accepts `string` or `number`.
97
+ */
98
+ async getAttributes(categoryId) {
99
+ const id = encodeURIComponent(String(categoryId));
100
+ const data = await this.transport.request({
101
+ method: "GET",
102
+ path: `/integration/product/categories/${id}/attributes`,
103
+ rateLimiter: this.limiter
104
+ });
105
+ const list = extractAttributeList(data);
106
+ if (!list) {
107
+ console.error(
108
+ "[@lonca/trendyol] getCategoryAttributes: unexpected response shape:",
109
+ JSON.stringify(data).slice(0, 800)
110
+ );
111
+ return [];
112
+ }
113
+ return list.map(normalizeAttribute);
114
+ }
115
+ };
116
+ function extractAttributeList(data) {
117
+ if (Array.isArray(data)) return data;
118
+ if (data && typeof data === "object") {
119
+ const obj = data;
120
+ if (Array.isArray(obj.categoryAttributes)) {
121
+ return obj.categoryAttributes;
122
+ }
123
+ if (Array.isArray(obj.attributes)) {
124
+ return obj.attributes;
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+ var MAX_ITEMS_PER_REQUEST = 1e3;
130
+ var InventoryResource = class {
131
+ constructor(transport, sellerId) {
132
+ this.transport = transport;
133
+ this.sellerId = sellerId;
134
+ }
135
+ transport;
136
+ sellerId;
137
+ /**
138
+ * Update price and/or stock for one or more SKUs (by barcode).
139
+ *
140
+ * @example
141
+ * ```ts
142
+ * const { batchRequestId } = await client.inventory.update([
143
+ * { barcode: 'ABC123', quantity: 42, salePrice: 199.9, listPrice: 249.9 },
144
+ * { barcode: 'XYZ789', quantity: 0 },
145
+ * ]);
146
+ * const status = await client.products.getBatchStatus(batchRequestId);
147
+ * ```
148
+ *
149
+ * @throws {ValidationError} when `items` is empty or longer than 1000.
150
+ */
151
+ async update(items) {
152
+ if (items.length === 0) {
153
+ throw new core.ValidationError({ message: "updatePriceAndInventory: items must not be empty" });
154
+ }
155
+ if (items.length > MAX_ITEMS_PER_REQUEST) {
156
+ throw new core.ValidationError({
157
+ message: `updatePriceAndInventory: max ${MAX_ITEMS_PER_REQUEST} items per request, got ${items.length}`
158
+ });
159
+ }
160
+ const data = await this.transport.request({
161
+ method: "POST",
162
+ path: `/integration/inventory/sellers/${this.sellerId}/products/price-and-inventory`,
163
+ body: { items }
164
+ });
165
+ return { batchRequestId: data.batchRequestId ?? "" };
166
+ }
167
+ };
168
+ var MAX_PAGE_SIZE = 200;
169
+ var DEFAULT_PAGE_SIZE2 = 50;
170
+ function toIso(epochMs) {
171
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs) || epochMs === 0) {
172
+ return void 0;
173
+ }
174
+ return new Date(epochMs).toISOString();
175
+ }
176
+ function normalizeAddress(node) {
177
+ if (!node) return void 0;
178
+ const out = {};
179
+ if (node.id !== void 0) out.id = String(node.id);
180
+ if (node.firstName !== void 0) out.firstName = node.firstName;
181
+ if (node.lastName !== void 0) out.lastName = node.lastName;
182
+ if (node.fullName !== void 0) out.fullName = node.fullName;
183
+ if (node.company !== void 0) out.company = node.company;
184
+ if (node.address1 !== void 0) out.address1 = node.address1;
185
+ if (node.address2 !== void 0) out.address2 = node.address2;
186
+ if (node.fullAddress !== void 0) out.fullAddress = node.fullAddress;
187
+ if (node.shortAddress !== void 0) out.shortAddress = node.shortAddress;
188
+ if (node.city !== void 0) out.city = node.city;
189
+ if (node.cityCode !== void 0) out.cityCode = node.cityCode;
190
+ if (node.district !== void 0) out.district = node.district;
191
+ if (node.districtId !== void 0) out.districtId = node.districtId;
192
+ if (node.neighborhoodId !== void 0) out.neighborhoodId = node.neighborhoodId;
193
+ if (node.countyId !== void 0) out.countyId = node.countyId;
194
+ if (node.countyName !== void 0) out.countyName = node.countyName;
195
+ if (node.stateName !== void 0) out.stateName = node.stateName;
196
+ if (node.postalCode !== void 0) out.postalCode = node.postalCode;
197
+ if (node.countryCode !== void 0) out.countryCode = node.countryCode;
198
+ if (node.phone !== void 0) out.phone = node.phone;
199
+ if (node.addressLines !== void 0) out.addressLines = node.addressLines;
200
+ return out;
201
+ }
202
+ function normalizeLine(node) {
203
+ const out = {
204
+ id: node.lineId !== void 0 ? String(node.lineId) : "",
205
+ quantity: typeof node.quantity === "number" ? node.quantity : 0,
206
+ productName: node.productName ?? "",
207
+ barcode: node.barcode ?? "",
208
+ lineUnitPrice: typeof node.lineUnitPrice === "number" ? node.lineUnitPrice : 0,
209
+ lineGrossAmount: typeof node.lineGrossAmount === "number" ? node.lineGrossAmount : 0,
210
+ raw: node
211
+ };
212
+ if (node.productSize !== void 0) out.productSize = node.productSize;
213
+ if (node.productColor !== void 0) out.productColor = node.productColor;
214
+ if (node.stockCode !== void 0) out.stockCode = node.stockCode;
215
+ if (node.contentId !== void 0) out.contentId = String(node.contentId);
216
+ if (node.sellerId !== void 0) out.sellerId = String(node.sellerId);
217
+ if (node.productCategoryId !== void 0) out.productCategoryId = String(node.productCategoryId);
218
+ if (node.salesCampaignId !== void 0) out.salesCampaignId = String(node.salesCampaignId);
219
+ if (node.currencyCode !== void 0) out.currencyCode = node.currencyCode;
220
+ if (node.lineSellerDiscount !== void 0) out.lineSellerDiscount = node.lineSellerDiscount;
221
+ if (node.lineTyDiscount !== void 0) out.lineTyDiscount = node.lineTyDiscount;
222
+ if (node.lineTotalDiscount !== void 0) out.lineTotalDiscount = node.lineTotalDiscount;
223
+ if (node.vatRate !== void 0) out.vatRate = node.vatRate;
224
+ if (node.commission !== void 0) out.commission = node.commission;
225
+ if (node.orderLineItemStatusName !== void 0) {
226
+ out.orderLineItemStatusName = node.orderLineItemStatusName;
227
+ }
228
+ if (node.businessUnit !== void 0) out.businessUnit = node.businessUnit;
229
+ if (Array.isArray(node.fastDeliveryOptions)) out.fastDeliveryOptions = node.fastDeliveryOptions;
230
+ if (Array.isArray(node.discountDetails)) {
231
+ out.discountDetails = node.discountDetails;
232
+ }
233
+ return out;
234
+ }
235
+ function normalizeHistory(node) {
236
+ const out = { raw: node };
237
+ if (node.status !== void 0) out.status = node.status;
238
+ const createdAt = toIso(node.createdDate);
239
+ if (createdAt) out.createdAt = createdAt;
240
+ return out;
241
+ }
242
+ function normalizeCustomer(node) {
243
+ const out = {
244
+ firstName: node.customerFirstName ?? "",
245
+ lastName: node.customerLastName ?? ""
246
+ };
247
+ if (node.customerId !== void 0) out.id = String(node.customerId);
248
+ if (node.customerEmail !== void 0) out.email = node.customerEmail;
249
+ if (node.taxNumber !== void 0 && node.taxNumber !== null) out.taxNumber = node.taxNumber;
250
+ if (node.identityNumber !== void 0) out.identityNumber = node.identityNumber;
251
+ return out;
252
+ }
253
+ function normalizePackage(node) {
254
+ const out = {
255
+ id: node.shipmentPackageId !== void 0 ? String(node.shipmentPackageId) : "",
256
+ orderNumber: node.orderNumber ?? "",
257
+ status: node.status ?? "",
258
+ customer: normalizeCustomer(node),
259
+ orderDate: toIso(node.orderDate) ?? "",
260
+ lastModifiedDate: toIso(node.lastModifiedDate) ?? "",
261
+ currencyCode: node.currencyCode ?? "",
262
+ packageTotalPrice: typeof node.packageTotalPrice === "number" ? node.packageTotalPrice : 0,
263
+ packageGrossAmount: typeof node.packageGrossAmount === "number" ? node.packageGrossAmount : 0,
264
+ packageSellerDiscount: typeof node.packageSellerDiscount === "number" ? node.packageSellerDiscount : 0,
265
+ packageTyDiscount: typeof node.packageTyDiscount === "number" ? node.packageTyDiscount : 0,
266
+ packageTotalDiscount: typeof node.packageTotalDiscount === "number" ? node.packageTotalDiscount : 0,
267
+ lines: (node.lines ?? []).map(normalizeLine),
268
+ packageHistories: (node.packageHistories ?? []).map(normalizeHistory),
269
+ raw: node
270
+ };
271
+ if (node.shipmentNumber !== void 0) out.shipmentNumber = String(node.shipmentNumber);
272
+ if (node.originPackageIds !== void 0 && node.originPackageIds !== null) {
273
+ out.originPackageIds = node.originPackageIds.map((id) => String(id));
274
+ }
275
+ if (node.warehouseId !== void 0) out.warehouseId = String(node.warehouseId);
276
+ if (node.supplierId !== void 0) out.supplierId = String(node.supplierId);
277
+ if (node.shipmentPackageStatus !== void 0) {
278
+ out.shipmentPackageStatus = node.shipmentPackageStatus;
279
+ }
280
+ const agreed = toIso(node.agreedDeliveryDate);
281
+ if (agreed) out.agreedDeliveryDate = agreed;
282
+ const estStart = toIso(node.estimatedDeliveryStartDate);
283
+ if (estStart) out.estimatedDeliveryStartDate = estStart;
284
+ const estEnd = toIso(node.estimatedDeliveryEndDate);
285
+ if (estEnd) out.estimatedDeliveryEndDate = estEnd;
286
+ const origin = toIso(node.originShipmentDate);
287
+ if (origin) out.originShipmentDate = origin;
288
+ const invoice = normalizeAddress(node.invoiceAddress);
289
+ if (invoice) out.invoiceAddress = invoice;
290
+ const shipment = normalizeAddress(node.shipmentAddress);
291
+ if (shipment) out.shipmentAddress = shipment;
292
+ if (node.deliveryAddressType !== void 0) out.deliveryAddressType = node.deliveryAddressType;
293
+ if (node.cargoTrackingNumber !== void 0) {
294
+ out.cargoTrackingNumber = String(node.cargoTrackingNumber);
295
+ }
296
+ if (node.cargoProviderName !== void 0) out.cargoProviderName = node.cargoProviderName;
297
+ if (node.cargoProviderId !== void 0) out.cargoProviderId = String(node.cargoProviderId);
298
+ if (node.cargoSenderNumber !== void 0) out.cargoSenderNumber = node.cargoSenderNumber;
299
+ if (node.deliveryType !== void 0) out.deliveryType = node.deliveryType;
300
+ if (node.whoPays !== void 0) out.whoPays = node.whoPays;
301
+ if (node.timeSlotId !== void 0) out.timeSlotId = node.timeSlotId;
302
+ if (typeof node.fastDelivery === "boolean") out.fastDelivery = node.fastDelivery;
303
+ if (node.fastDeliveryType !== void 0) out.fastDeliveryType = node.fastDeliveryType;
304
+ if (typeof node.deliveredByService === "boolean")
305
+ out.deliveredByService = node.deliveredByService;
306
+ if (typeof node.commercial === "boolean") out.commercial = node.commercial;
307
+ if (typeof node.micro === "boolean") out.micro = node.micro;
308
+ if (typeof node.giftBoxRequested === "boolean") out.giftBoxRequested = node.giftBoxRequested;
309
+ if (typeof node["3pByTrendyol"] === "boolean") {
310
+ out.threePByTrendyol = node["3pByTrendyol"];
311
+ }
312
+ if (typeof node.containsDangerousProduct === "boolean") {
313
+ out.containsDangerousProduct = node.containsDangerousProduct;
314
+ }
315
+ if (typeof node.isCod === "boolean") out.isCod = node.isCod;
316
+ if (typeof node.is4P === "boolean") out.is4P = node.is4P;
317
+ if (node.invoiceLink !== void 0) out.invoiceLink = node.invoiceLink;
318
+ if (node.createdBy !== void 0) out.createdBy = node.createdBy;
319
+ return out;
320
+ }
321
+ var OrdersResource = class {
322
+ constructor(transport, sellerId, limiter) {
323
+ this.transport = transport;
324
+ this.sellerId = sellerId;
325
+ this.limiter = limiter ?? new core.TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
326
+ }
327
+ transport;
328
+ sellerId;
329
+ limiter;
330
+ /**
331
+ * List shipment packages for the seller.
332
+ *
333
+ * @example
334
+ * ```ts
335
+ * import { paginate } from '@lonca/core';
336
+ * for await (const pkg of paginate((p) => client.orders.list({ ...p, status: 'Created' }))) {
337
+ * console.log(pkg.id, pkg.status, pkg.customer.firstName);
338
+ * }
339
+ * ```
340
+ */
341
+ async list(params = {}) {
342
+ const size = Math.min(params.limit ?? DEFAULT_PAGE_SIZE2, MAX_PAGE_SIZE);
343
+ const page = params.cursor ? Number.parseInt(params.cursor, 10) : 0;
344
+ const query = { page, size };
345
+ if (params.status) query.status = params.status;
346
+ if (params.orderNumber) query.orderNumber = params.orderNumber;
347
+ if (params.startDate) query.startDate = params.startDate.getTime();
348
+ if (params.endDate) query.endDate = params.endDate.getTime();
349
+ const data = await this.transport.request({
350
+ method: "GET",
351
+ path: `/integration/order/sellers/${this.sellerId}/orders`,
352
+ query,
353
+ rateLimiter: this.limiter
354
+ });
355
+ const items = (data.content ?? []).map(normalizePackage);
356
+ const totalPages = typeof data.totalPages === "number" ? data.totalPages : 0;
357
+ const result = { items };
358
+ if (page + 1 < totalPages) {
359
+ result.nextCursor = String(page + 1);
360
+ }
361
+ return result;
362
+ }
363
+ };
364
+ var DEFAULT_PAGE_SIZE3 = 50;
365
+ var MAX_PAGE_SIZE2 = 1e3;
366
+ function normalizeRef(ref) {
367
+ return {
368
+ id: ref?.id !== void 0 ? String(ref.id) : "",
369
+ name: ref?.name ?? ""
370
+ };
371
+ }
372
+ function normalizeAttribute2(attr) {
373
+ const out = {
374
+ attributeId: attr.attributeId !== void 0 ? String(attr.attributeId) : ""
375
+ };
376
+ if (attr.attributeName !== void 0) out.attributeName = attr.attributeName;
377
+ if (attr.attributeValueId !== void 0) {
378
+ out.attributeValueId = String(attr.attributeValueId);
379
+ }
380
+ if (attr.attributeValue !== void 0) out.attributeValue = attr.attributeValue;
381
+ return out;
382
+ }
383
+ function normalizeImages(images) {
384
+ if (!images) return [];
385
+ return images.map((img) => typeof img === "string" ? img : img?.url).filter((u) => typeof u === "string" && u.length > 0);
386
+ }
387
+ function normalizeStock(stock) {
388
+ if (typeof stock === "number") return stock;
389
+ if (stock && typeof stock === "object" && typeof stock.quantity === "number") {
390
+ return stock.quantity;
391
+ }
392
+ return void 0;
393
+ }
394
+ function normalizeVariant(variant) {
395
+ const out = {
396
+ variantId: variant.variantId !== void 0 ? String(variant.variantId) : "",
397
+ barcode: variant.barcode ?? "",
398
+ attributes: (variant.attributes ?? []).map(normalizeAttribute2),
399
+ raw: variant
400
+ };
401
+ if (typeof variant.commission === "number") out.commission = variant.commission;
402
+ if (variant.productUrl !== void 0) out.productUrl = variant.productUrl;
403
+ if (typeof variant.onSale === "boolean") out.onSale = variant.onSale;
404
+ const stock = normalizeStock(variant.stock);
405
+ if (stock !== void 0) out.stock = stock;
406
+ return out;
407
+ }
408
+ function toIso2(epochMs) {
409
+ if (typeof epochMs !== "number" || !Number.isFinite(epochMs)) return void 0;
410
+ return new Date(epochMs).toISOString();
411
+ }
412
+ function normalizeProduct(node) {
413
+ const out = {
414
+ contentId: node.contentId !== void 0 ? String(node.contentId) : "",
415
+ productMainId: node.productMainId ?? "",
416
+ title: node.title ?? "",
417
+ brand: normalizeRef(node.brand),
418
+ category: normalizeRef(node.category),
419
+ images: normalizeImages(node.images),
420
+ attributes: (node.attributes ?? []).map(normalizeAttribute2),
421
+ variants: (node.variants ?? []).map(normalizeVariant),
422
+ createdAt: toIso2(node.creationDate) ?? "",
423
+ updatedAt: toIso2(node.lastModifiedDate) ?? "",
424
+ raw: node
425
+ };
426
+ if (node.description !== void 0) out.description = node.description;
427
+ if (node.lastModifiedBy !== void 0) out.lastModifiedBy = node.lastModifiedBy;
428
+ return out;
429
+ }
430
+ function normalizeBatchResult(data) {
431
+ const items = (data.items ?? []).map((item) => {
432
+ const result = {};
433
+ if (item.requestItem !== void 0) result.requestItem = item.requestItem;
434
+ if (item.status !== void 0) result.status = item.status;
435
+ if (item.failureReasons !== void 0) result.failureReasons = item.failureReasons;
436
+ return result;
437
+ });
438
+ const out = {
439
+ batchRequestId: typeof data.batchRequestId === "string" ? data.batchRequestId : "",
440
+ status: data.status ?? "PROCESSING",
441
+ items,
442
+ raw: data
443
+ };
444
+ if (typeof data.itemCount === "number") out.itemCount = data.itemCount;
445
+ if (typeof data.failedItemCount === "number") out.failedItemCount = data.failedItemCount;
446
+ const createdAt = toIso2(data.creationDate);
447
+ if (createdAt) out.createdAt = createdAt;
448
+ const lastModifiedAt = toIso2(data.lastModification);
449
+ if (lastModifiedAt) out.lastModifiedAt = lastModifiedAt;
450
+ if (data.sourceType !== void 0) out.sourceType = data.sourceType;
451
+ if (data.batchRequestType !== void 0) out.batchRequestType = data.batchRequestType;
452
+ if (data.notes !== void 0) out.notes = data.notes;
453
+ if (data.objectKey !== void 0) out.objectKey = data.objectKey;
454
+ if (data.storeFrontCode !== void 0) out.storeFrontCode = data.storeFrontCode;
455
+ return out;
456
+ }
457
+ var ProductsResource = class {
458
+ constructor(transport, sellerId, options = {}) {
459
+ this.transport = transport;
460
+ this.sellerId = sellerId;
461
+ this.filterLimiter = options.filterLimiter ?? new core.TokenBucketRateLimiter({ capacity: 2e3, intervalMs: 6e4 });
462
+ this.batchLimiter = options.batchLimiter ?? new core.TokenBucketRateLimiter({ capacity: 1e3, intervalMs: 6e4 });
463
+ }
464
+ transport;
465
+ sellerId;
466
+ filterLimiter;
467
+ batchLimiter;
468
+ /**
469
+ * List approved products. Use `paginate()` from `@lonca/core` to iterate
470
+ * lazily across pages.
471
+ *
472
+ * Trendyol exposes both page-based and `nextPageToken`-based pagination
473
+ * (the latter required when the dataset exceeds 10,000 items). The SDK
474
+ * picks the right strategy automatically — pass our opaque `cursor` from
475
+ * the previous response and we forward it as `nextPageToken`.
476
+ *
477
+ * @example
478
+ * ```ts
479
+ * import { paginate } from '@lonca/core';
480
+ * for await (const product of paginate((p) => client.products.list(p))) {
481
+ * for (const variant of product.variants) {
482
+ * console.log(variant.barcode, product.title);
483
+ * }
484
+ * }
485
+ * ```
486
+ */
487
+ async list(params = {}) {
488
+ const size = Math.min(params.limit ?? DEFAULT_PAGE_SIZE3, MAX_PAGE_SIZE2);
489
+ const query = { size };
490
+ if (params.cursor) {
491
+ query.nextPageToken = params.cursor;
492
+ } else {
493
+ query.page = 0;
494
+ }
495
+ if (params.barcode) query.barcode = params.barcode;
496
+ if (params.startDate) query.startDate = params.startDate.getTime();
497
+ if (params.endDate) query.endDate = params.endDate.getTime();
498
+ const data = await this.transport.request({
499
+ method: "GET",
500
+ path: `/integration/product/sellers/${this.sellerId}/products/approved`,
501
+ query,
502
+ rateLimiter: this.filterLimiter
503
+ });
504
+ const items = (data.content ?? []).map(normalizeProduct);
505
+ const page = { items };
506
+ if (data.nextPageToken) {
507
+ page.nextCursor = data.nextPageToken;
508
+ }
509
+ return page;
510
+ }
511
+ /**
512
+ * Poll a batch request returned by an async write (e.g. `createProducts`,
513
+ * `updatePriceAndInventory`).
514
+ *
515
+ * Trendyol retains batch results for **4 hours** after the originating
516
+ * request — poll within that window.
517
+ *
518
+ * @param batchRequestId The opaque ID returned by the originating call.
519
+ */
520
+ async getBatchStatus(batchRequestId) {
521
+ const id = encodeURIComponent(batchRequestId);
522
+ const data = await this.transport.request({
523
+ method: "GET",
524
+ path: `/integration/product/sellers/${this.sellerId}/products/batch-requests/${id}`,
525
+ rateLimiter: this.batchLimiter
526
+ });
527
+ return normalizeBatchResult(data);
528
+ }
529
+ };
530
+ var VALID_TYPES = /* @__PURE__ */ new Set([
531
+ "SHIPMENT",
532
+ "RETURNING",
533
+ "INVOICE",
534
+ "WAREHOUSE"
535
+ ]);
536
+ function normalizeAddressType(raw) {
537
+ if (raw && VALID_TYPES.has(raw)) {
538
+ return raw;
539
+ }
540
+ const stripped = raw?.replace(/_ADDRESS$/, "");
541
+ if (stripped && VALID_TYPES.has(stripped)) {
542
+ return stripped;
543
+ }
544
+ return "SHIPMENT";
545
+ }
546
+ function normalizeAddress2(node) {
547
+ return {
548
+ id: String(node.id),
549
+ name: node.name,
550
+ addressType: normalizeAddressType(node.addressType),
551
+ isShipmentAddress: node.isShipmentAddress ?? false,
552
+ isReturningAddress: node.isReturningAddress ?? false,
553
+ isInvoiceAddress: node.isInvoiceAddress ?? false,
554
+ isDefault: node.isDefault ?? false,
555
+ address: node.address,
556
+ city: node.city,
557
+ district: node.district,
558
+ postCode: node.postCode,
559
+ fullName: node.fullName
560
+ };
561
+ }
562
+ var DEFAULT_CACHE_TTL_MS = 60 * 60 * 1e3;
563
+ var SuppliersResource = class {
564
+ constructor(transport, sellerId, options = {}) {
565
+ this.transport = transport;
566
+ this.sellerId = sellerId;
567
+ this.cacheTtlMs = options.cacheTtlMs ?? DEFAULT_CACHE_TTL_MS;
568
+ this.limiter = new core.TokenBucketRateLimiter({
569
+ capacity: 1,
570
+ intervalMs: DEFAULT_CACHE_TTL_MS
571
+ });
572
+ }
573
+ transport;
574
+ sellerId;
575
+ cache = null;
576
+ cacheTtlMs;
577
+ limiter;
578
+ inflight = null;
579
+ /**
580
+ * List the seller's registered addresses (shipment, returning, invoice, warehouse).
581
+ *
582
+ * Returns the cached value if it is still fresh. Concurrent calls share a
583
+ * single in-flight request.
584
+ */
585
+ async getAddresses(options = {}) {
586
+ if (!options.forceRefresh && this.cache && this.cache.expiresAt > Date.now()) {
587
+ return this.cache.value;
588
+ }
589
+ if (this.inflight) return this.inflight;
590
+ this.inflight = this.fetchFresh().finally(() => {
591
+ this.inflight = null;
592
+ });
593
+ return this.inflight;
594
+ }
595
+ /** Drop the cache; the next `getAddresses()` call hits the API. */
596
+ invalidateCache() {
597
+ this.cache = null;
598
+ }
599
+ async fetchFresh() {
600
+ const data = await this.transport.request({
601
+ method: "GET",
602
+ path: `/integration/sellers/${this.sellerId}/addresses`,
603
+ rateLimiter: this.limiter
604
+ });
605
+ const items = data.supplierAddresses.map(normalizeAddress2);
606
+ this.cache = { value: items, expiresAt: Date.now() + this.cacheTtlMs };
607
+ return items;
608
+ }
609
+ };
40
610
 
41
611
  // src/auth.ts
42
612
  function buildAuthHeader(apiKey, apiSecret) {
@@ -239,11 +809,21 @@ function createTrendyolClient(opts) {
239
809
  timeoutMs: opts.timeoutMs
240
810
  });
241
811
  return {
242
- brands: new BrandsResource(transport)
812
+ brands: new BrandsResource(transport),
813
+ categories: new CategoriesResource(transport),
814
+ suppliers: new SuppliersResource(transport, opts.sellerId),
815
+ products: new ProductsResource(transport, opts.sellerId),
816
+ inventory: new InventoryResource(transport, opts.sellerId),
817
+ orders: new OrdersResource(transport, opts.sellerId)
243
818
  };
244
819
  }
245
820
 
246
821
  exports.BrandsResource = BrandsResource;
822
+ exports.CategoriesResource = CategoriesResource;
823
+ exports.InventoryResource = InventoryResource;
824
+ exports.OrdersResource = OrdersResource;
825
+ exports.ProductsResource = ProductsResource;
826
+ exports.SuppliersResource = SuppliersResource;
247
827
  exports.createTrendyolClient = createTrendyolClient;
248
828
  //# sourceMappingURL=index.cjs.map
249
829
  //# sourceMappingURL=index.cjs.map