n8n-nodes-amazon-selling-partner-dnangelx 0.0.12 → 0.0.13

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.
@@ -4,468 +4,287 @@ exports.executeListingsOperation = executeListingsOperation;
4
4
  const n8n_workflow_1 = require("n8n-workflow");
5
5
  const SpApiRequest_1 = require("../helpers/SpApiRequest");
6
6
  const SecurityValidator_1 = require("../core/SecurityValidator");
7
- const MetricsCollector_1 = require("../core/MetricsCollector");
8
- const AuditLogger_1 = require("../core/AuditLogger");
9
- async function extractSellerId() {
10
- const nodeId = this.getNode().id;
11
- try {
12
- const credentials = await this.getCredentials('amazonSpApi');
13
- if (credentials.sellerId && typeof credentials.sellerId === 'string') {
14
- return credentials.sellerId;
7
+ const parseJsonParameter = (value, fieldName, node) => {
8
+ var _a;
9
+ if (value === null || value === undefined || value === '') {
10
+ return undefined;
11
+ }
12
+ if (typeof value === 'string') {
13
+ const trimmed = value.trim();
14
+ if (!trimmed) {
15
+ return undefined;
15
16
  }
16
- const response = await SpApiRequest_1.SpApiRequest.makeRequest(this, {
17
- method: 'GET',
18
- endpoint: '/sellers/v1/marketplaceParticipations',
19
- });
20
- if (response.data && response.data.length > 0) {
21
- const sellerId = response.data[0].sellerId;
22
- if (sellerId) {
23
- AuditLogger_1.auditLogger.logEvent({
24
- nodeId,
25
- action: 'seller_id_extraction',
26
- resource: 'credentials',
27
- details: { sellerId, source: 'marketplace_participations' },
28
- severity: 'low',
29
- source: 'system',
30
- outcome: 'success'
31
- });
32
- return sellerId;
33
- }
17
+ try {
18
+ return JSON.parse(trimmed);
19
+ }
20
+ catch (error) {
21
+ throw new n8n_workflow_1.NodeOperationError(node, `Invalid JSON provided for "${fieldName}": ${(_a = error.message) !== null && _a !== void 0 ? _a : error}`);
34
22
  }
35
- throw new Error('Could not auto-extract seller ID. Please ensure your SP-API credentials include sellerId or have marketplace participations configured.');
36
23
  }
37
- catch (error) {
38
- AuditLogger_1.auditLogger.logEvent({
39
- nodeId,
40
- action: 'seller_id_extraction',
41
- resource: 'credentials',
42
- details: {
43
- error: error instanceof Error ? error.message : 'Unknown error',
44
- source: 'auto_extraction'
45
- },
46
- severity: 'high',
47
- source: 'system',
48
- outcome: 'failure'
49
- });
50
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Failed to extract seller ID: ${error instanceof Error ? error.message : 'Unknown error'}`);
24
+ return value;
25
+ };
26
+ const ensureObjectOrArray = (value, fieldName, node) => {
27
+ const parsed = parseJsonParameter(value, fieldName, node);
28
+ if (parsed === undefined) {
29
+ return undefined;
51
30
  }
52
- }
53
- function formatListingForOutput(listing, marketplaceId) {
54
- const output = {
55
- asin: listing.asin,
56
- sku: listing.sku,
57
- };
58
- if (listing.summaries) {
59
- const relevantSummary = marketplaceId
60
- ? listing.summaries.find(s => s.marketplaceId === marketplaceId)
61
- : listing.summaries[0];
62
- if (relevantSummary) {
63
- output.itemName = relevantSummary.itemName;
64
- output.conditionType = relevantSummary.conditionType;
65
- output.status = relevantSummary.status;
66
- output.fulfillmentChannels = relevantSummary.fulfillmentChannels;
67
- output.createdDate = relevantSummary.createdDate;
68
- output.lastUpdatedDate = relevantSummary.lastUpdatedDate;
69
- output.mainImage = relevantSummary.mainImage;
70
- }
31
+ if (typeof parsed === 'object' && parsed !== null) {
32
+ return parsed;
71
33
  }
72
- if (listing.attributes && marketplaceId) {
73
- const relevantAttributes = listing.attributes.find(a => a.marketplaceId === marketplaceId);
74
- if (relevantAttributes) {
75
- output.attributes = relevantAttributes.attributes.reduce((acc, attr) => {
76
- acc[attr.attributeName] = attr.attributeValue;
77
- return acc;
78
- }, {});
34
+ throw new n8n_workflow_1.NodeOperationError(node, `"${fieldName}" must be a JSON object or array.`);
35
+ };
36
+ const extractSellerIdFromPayload = (data) => {
37
+ if (!data)
38
+ return undefined;
39
+ if (Array.isArray(data)) {
40
+ for (const entry of data) {
41
+ const found = extractSellerIdFromPayload(entry);
42
+ if (found)
43
+ return found;
79
44
  }
45
+ return undefined;
80
46
  }
81
- if (listing.offers && marketplaceId) {
82
- const relevantOffers = listing.offers.find(o => o.marketplaceId === marketplaceId);
83
- if (relevantOffers) {
84
- output.offers = relevantOffers.offers;
85
- }
47
+ if (typeof data !== 'object')
48
+ return undefined;
49
+ const record = data;
50
+ if (typeof record.sellerId === 'string')
51
+ return record.sellerId;
52
+ if (record.payload) {
53
+ const found = extractSellerIdFromPayload(record.payload);
54
+ if (found)
55
+ return found;
86
56
  }
87
- if (listing.issues && marketplaceId) {
88
- const relevantIssues = listing.issues.find(i => i.marketplaceId === marketplaceId);
89
- if (relevantIssues) {
90
- output.issues = relevantIssues.issues;
57
+ if (Array.isArray(record.participations)) {
58
+ for (const part of record.participations) {
59
+ const found = extractSellerIdFromPayload(part);
60
+ if (found)
61
+ return found;
91
62
  }
92
63
  }
93
- if (listing.fulfillmentAvailability && marketplaceId) {
94
- const relevantAvailability = listing.fulfillmentAvailability.find(f => f.marketplaceId === marketplaceId);
95
- if (relevantAvailability) {
96
- output.fulfillmentAvailability = relevantAvailability.fulfillmentAvailability;
97
- }
64
+ return undefined;
65
+ };
66
+ async function extractSellerId() {
67
+ const credentials = await this.getCredentials('amazonSpApi');
68
+ if (credentials.sellerId && typeof credentials.sellerId === 'string') {
69
+ return credentials.sellerId;
98
70
  }
99
- if (listing.procurement && marketplaceId) {
100
- const relevantProcurement = listing.procurement.find(p => p.marketplaceId === marketplaceId);
101
- if (relevantProcurement) {
102
- output.procurement = relevantProcurement;
103
- }
71
+ const response = await SpApiRequest_1.SpApiRequest.makeRequest(this, {
72
+ method: 'GET',
73
+ endpoint: '/sellers/v1/marketplaceParticipations',
74
+ });
75
+ const sellerId = extractSellerIdFromPayload(response.data);
76
+ if (!sellerId) {
77
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Could not auto-extract seller ID. Provide Seller ID in credentials or ensure marketplace participations are accessible.');
104
78
  }
105
- output.marketplaceId = marketplaceId;
106
- output.extractedAt = new Date().toISOString();
107
- return output;
79
+ return sellerId;
108
80
  }
81
+ const getSingleMarketplaceId = (marketplaceIds, nodeId, node) => {
82
+ const validation = SecurityValidator_1.securityValidator.validateMarketplaceIds(marketplaceIds, nodeId);
83
+ if (!validation.isValid) {
84
+ throw new n8n_workflow_1.NodeOperationError(node, `Invalid marketplace IDs: ${validation.errors.join(', ')}`);
85
+ }
86
+ if (marketplaceIds.length !== 1) {
87
+ throw new n8n_workflow_1.NodeOperationError(node, 'Listings Items API requires exactly one Marketplace ID.');
88
+ }
89
+ return marketplaceIds[0];
90
+ };
91
+ const normalizeIncludedData = (value) => {
92
+ if (!value)
93
+ return undefined;
94
+ if (Array.isArray(value))
95
+ return value.join(',');
96
+ return value;
97
+ };
98
+ const pushResults = (items, itemIndex, returnData) => {
99
+ if (!items.length)
100
+ return;
101
+ items.forEach((item) => {
102
+ returnData.push({ json: item, pairedItem: { item: itemIndex } });
103
+ });
104
+ };
109
105
  async function executeListingsOperation(operation, itemIndex) {
110
106
  var _a, _b, _c, _d, _e, _f;
111
107
  const returnData = [];
112
108
  const nodeId = this.getNode().id;
113
- if (operation === 'listAsins') {
114
- try {
115
- const startTime = Date.now();
116
- AuditLogger_1.auditLogger.logEvent({
117
- nodeId,
118
- action: 'operation_start',
119
- resource: 'listings',
120
- details: { operation: 'listAsins', itemIndex },
121
- severity: 'low',
122
- source: 'user',
123
- outcome: 'success'
124
- });
125
- const marketplaceIds = this.getNodeParameter('marketplaceIds', itemIndex);
126
- const additionalOptions = this.getNodeParameter('additionalOptions', itemIndex, {});
127
- const includedData = additionalOptions.includedData || ['summaries'];
128
- const identifiersType = additionalOptions.identifiersType;
129
- const identifiers = additionalOptions.identifiers;
130
- const variationParentSku = additionalOptions.variationParentSku;
131
- const packageHierarchySku = additionalOptions.packageHierarchySku;
132
- const createdAfter = additionalOptions.createdAfter;
133
- const createdBefore = additionalOptions.createdBefore;
134
- const lastUpdatedAfter = additionalOptions.lastUpdatedAfter;
135
- const lastUpdatedBefore = additionalOptions.lastUpdatedBefore;
136
- const withIssueSeverity = additionalOptions.withIssueSeverity;
137
- const withStatus = additionalOptions.withStatus || [];
138
- const withoutStatus = additionalOptions.withoutStatus || [];
139
- const sortBy = additionalOptions.sortBy;
140
- const sortOrder = additionalOptions.sortOrder;
141
- const pageSize = additionalOptions.pageSize || 10;
142
- const returnAll = additionalOptions.returnAll !== false;
143
- const maxResultsLimit = additionalOptions.maxResultsLimit || 1000;
144
- const issueLocale = additionalOptions.issueLocale || 'en_US';
145
- const marketplaceValidation = SecurityValidator_1.securityValidator.validateMarketplaceIds(marketplaceIds, nodeId);
146
- if (!marketplaceValidation.isValid) {
147
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Invalid marketplace IDs: ${marketplaceValidation.errors.join(', ')}`);
148
- }
149
- if (pageSize < 1 || pageSize > 20) {
150
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Page size must be between 1 and 20');
151
- }
152
- const sellerId = await extractSellerId.call(this);
153
- AuditLogger_1.auditLogger.logEvent({
154
- nodeId,
155
- action: 'seller_id_extracted',
156
- resource: 'credentials',
157
- details: { sellerId },
158
- severity: 'low',
159
- source: 'system',
160
- outcome: 'success'
161
- });
162
- const allListings = [];
163
- let nextToken;
164
- let requestCount = 0;
165
- let totalProcessed = 0;
166
- do {
167
- requestCount++;
168
- AuditLogger_1.auditLogger.logEvent({
169
- nodeId,
170
- action: 'api_request_start',
171
- resource: 'listings',
172
- details: {
173
- requestNumber: requestCount,
174
- pageSize,
175
- hasNextToken: !!nextToken,
176
- totalProcessed
177
- },
178
- severity: 'low',
179
- source: 'system',
180
- outcome: 'success'
181
- });
182
- const queryParams = {
183
- marketplaceIds: marketplaceIds.join(','),
184
- includedData: includedData.join(','),
185
- pageSize: pageSize.toString(),
186
- };
187
- if (nextToken) {
188
- queryParams.pageToken = nextToken;
189
- }
190
- if (identifiers) {
191
- queryParams.identifiers = identifiers;
192
- if (identifiersType) {
193
- queryParams.identifiersType = identifiersType;
194
- }
195
- }
196
- if (variationParentSku) {
197
- queryParams.variationParentSku = variationParentSku;
198
- }
199
- if (packageHierarchySku) {
200
- queryParams.packageHierarchySku = packageHierarchySku;
201
- }
202
- if (createdAfter) {
203
- queryParams.createdAfter = createdAfter;
204
- }
205
- if (createdBefore) {
206
- queryParams.createdBefore = createdBefore;
207
- }
208
- if (lastUpdatedAfter) {
209
- queryParams.lastUpdatedAfter = lastUpdatedAfter;
210
- }
211
- if (lastUpdatedBefore) {
212
- queryParams.lastUpdatedBefore = lastUpdatedBefore;
213
- }
214
- if (withIssueSeverity) {
215
- queryParams.withIssueSeverity = withIssueSeverity;
216
- }
217
- if (withStatus.length > 0) {
218
- queryParams.withStatus = withStatus.join(',');
219
- }
220
- if (withoutStatus.length > 0) {
221
- queryParams.withoutStatus = withoutStatus.join(',');
222
- }
223
- if (sortBy) {
224
- queryParams.sortBy = sortBy;
225
- }
226
- if (sortOrder) {
227
- queryParams.sortOrder = sortOrder;
228
- }
229
- if (issueLocale) {
230
- queryParams.issueLocale = issueLocale;
231
- }
232
- const response = await SpApiRequest_1.SpApiRequest.makeRequest(this, {
233
- method: 'GET',
234
- endpoint: `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}`,
235
- query: queryParams,
236
- });
237
- const apiData = response.data;
238
- const listings = (_a = apiData === null || apiData === void 0 ? void 0 : apiData.items) !== null && _a !== void 0 ? _a : [];
239
- if (listings.length > 0) {
240
- allListings.push(...listings);
241
- totalProcessed += listings.length;
242
- AuditLogger_1.auditLogger.logEvent({
243
- nodeId,
244
- action: 'batch_processed',
245
- resource: 'listings',
246
- details: {
247
- batchSize: listings.length,
248
- totalProcessed,
249
- hasNextToken: !!((_c = (_b = apiData.pagination) === null || _b === void 0 ? void 0 : _b.nextToken) !== null && _c !== void 0 ? _c : apiData.nextToken)
250
- },
251
- severity: 'low',
252
- source: 'system',
253
- outcome: 'success'
254
- });
255
- }
256
- nextToken = (_e = (_d = apiData === null || apiData === void 0 ? void 0 : apiData.pagination) === null || _d === void 0 ? void 0 : _d.nextToken) !== null && _e !== void 0 ? _e : apiData === null || apiData === void 0 ? void 0 : apiData.nextToken;
257
- if (totalProcessed >= maxResultsLimit) {
258
- AuditLogger_1.auditLogger.logEvent({
259
- nodeId,
260
- action: 'max_results_reached',
261
- resource: 'listings',
262
- details: { maxResultsLimit, totalProcessed },
263
- severity: 'medium',
264
- source: 'system',
265
- outcome: 'warning'
266
- });
267
- break;
268
- }
269
- if (requestCount >= 100) {
270
- AuditLogger_1.auditLogger.logEvent({
271
- nodeId,
272
- action: 'max_requests_reached',
273
- resource: 'listings',
274
- details: { requestCount, totalProcessed },
275
- severity: 'medium',
276
- source: 'system',
277
- outcome: 'warning'
278
- });
279
- break;
280
- }
281
- } while (nextToken && returnAll);
282
- const outputData = [];
283
- if (marketplaceIds.length === 1) {
284
- allListings.forEach(listing => {
285
- outputData.push(formatListingForOutput(listing, marketplaceIds[0]));
286
- });
287
- }
288
- else {
289
- allListings.forEach(listing => {
290
- marketplaceIds.forEach(marketplaceId => {
291
- outputData.push(formatListingForOutput(listing, marketplaceId));
292
- });
293
- });
294
- }
295
- outputData.forEach(data => {
296
- returnData.push({
297
- json: data,
298
- pairedItem: { item: itemIndex },
299
- });
300
- });
301
- const duration = Date.now() - startTime;
302
- MetricsCollector_1.metricsCollector.recordMetric('operation_duration', duration, { operation: 'listAsins' });
303
- MetricsCollector_1.metricsCollector.recordMetric('api_requests_count', requestCount, { operation: 'listAsins' });
304
- MetricsCollector_1.metricsCollector.recordMetric('results_count', outputData.length, { operation: 'listAsins' });
305
- AuditLogger_1.auditLogger.logEvent({
306
- nodeId,
307
- action: 'operation_completed',
308
- resource: 'listings',
309
- details: {
310
- operation: 'listAsins',
311
- itemIndex,
312
- duration,
313
- requestCount,
314
- totalListings: allListings.length,
315
- outputCount: outputData.length,
316
- marketplaces: marketplaceIds.length,
317
- },
318
- severity: 'low',
319
- source: 'system',
320
- outcome: 'success'
321
- });
109
+ if (operation === 'searchListingsItems2021') {
110
+ const marketplaceIds = this.getNodeParameter('marketplaceIds', itemIndex);
111
+ const marketplaceId = getSingleMarketplaceId(marketplaceIds, nodeId, this.getNode());
112
+ const issueLocale = this.getNodeParameter('issueLocale', itemIndex);
113
+ const includedData = this.getNodeParameter('includedData', itemIndex, []);
114
+ const searchOptions = this.getNodeParameter('searchOptions', itemIndex, {});
115
+ const queryParams = {
116
+ marketplaceIds: marketplaceId,
117
+ };
118
+ const normalizedIncludedData = normalizeIncludedData(includedData);
119
+ if (normalizedIncludedData) {
120
+ queryParams.includedData = normalizedIncludedData;
322
121
  }
323
- catch (error) {
324
- AuditLogger_1.auditLogger.logEvent({
325
- nodeId,
326
- action: 'operation_failed',
327
- resource: 'listings',
328
- details: {
329
- operation: 'listAsins',
330
- itemIndex,
331
- error: error instanceof Error ? error.message : 'Unknown error',
332
- },
333
- severity: 'high',
334
- source: 'system',
335
- outcome: 'failure'
336
- });
337
- if (error instanceof n8n_workflow_1.NodeOperationError) {
338
- throw error;
339
- }
340
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
341
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Amazon SP-API Listings error: ${errorMessage}`);
122
+ if (issueLocale) {
123
+ queryParams.issueLocale = issueLocale;
342
124
  }
343
- }
344
- else if (operation === 'getListingDetails') {
345
- try {
346
- const startTime = Date.now();
347
- AuditLogger_1.auditLogger.logEvent({
348
- nodeId,
349
- action: 'operation_start',
350
- resource: 'listing_details',
351
- details: { operation: 'getListingDetails', itemIndex },
352
- severity: 'low',
353
- source: 'user',
354
- outcome: 'success'
355
- });
356
- const identifierType = this.getNodeParameter('identifierType', itemIndex);
357
- const marketplaceIds = this.getNodeParameter('marketplaceIds', itemIndex);
358
- const detailOptions = this.getNodeParameter('detailOptions', itemIndex, {});
359
- let identifier;
360
- if (identifierType === 'sku') {
361
- identifier = this.getNodeParameter('sku', itemIndex);
362
- }
363
- else {
364
- identifier = this.getNodeParameter('asin', itemIndex);
365
- }
366
- const includedData = detailOptions.includedData || ['summaries', 'attributes', 'offers', 'issues'];
367
- const issueLocale = detailOptions.issueLocale || 'en_US';
368
- const marketplaceValidation = SecurityValidator_1.securityValidator.validateMarketplaceIds(marketplaceIds, nodeId);
369
- if (!marketplaceValidation.isValid) {
370
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Invalid marketplace IDs: ${marketplaceValidation.errors.join(', ')}`);
125
+ if (searchOptions.identifiers) {
126
+ queryParams.identifiers = searchOptions.identifiers;
127
+ if (searchOptions.identifiersType) {
128
+ queryParams.identifiersType = searchOptions.identifiersType;
371
129
  }
372
- if (!identifier || identifier.trim().length === 0) {
373
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'Identifier cannot be empty');
374
- }
375
- const sellerId = await extractSellerId.call(this);
376
- const queryParams = {
377
- marketplaceIds: marketplaceIds.join(','),
378
- includedData: includedData.join(','),
379
- };
380
- if (issueLocale) {
381
- queryParams.issueLocale = issueLocale;
130
+ }
131
+ const optionalFields = [
132
+ 'variationParentSku',
133
+ 'packageHierarchySku',
134
+ 'createdAfter',
135
+ 'createdBefore',
136
+ 'lastUpdatedAfter',
137
+ 'lastUpdatedBefore',
138
+ 'withIssueSeverity',
139
+ 'sortBy',
140
+ 'sortOrder',
141
+ ];
142
+ optionalFields.forEach((field) => {
143
+ if (searchOptions[field]) {
144
+ queryParams[field] = searchOptions[field];
382
145
  }
383
- let endpoint;
384
- if (identifierType === 'sku') {
385
- endpoint = `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(identifier)}`;
146
+ });
147
+ if (Array.isArray(searchOptions.withStatus) && searchOptions.withStatus.length) {
148
+ queryParams.withStatus = searchOptions.withStatus.join(',');
149
+ }
150
+ if (Array.isArray(searchOptions.withoutStatus) && searchOptions.withoutStatus.length) {
151
+ queryParams.withoutStatus = searchOptions.withoutStatus.join(',');
152
+ }
153
+ const pageSize = Number((_a = searchOptions.pageSize) !== null && _a !== void 0 ? _a : 10);
154
+ if (!Number.isNaN(pageSize)) {
155
+ queryParams.pageSize = pageSize;
156
+ }
157
+ const pageToken = (_b = searchOptions.pageToken) !== null && _b !== void 0 ? _b : '';
158
+ const returnAll = searchOptions.returnAll !== false && !pageToken;
159
+ const maxResultsLimit = Number((_c = searchOptions.maxResultsLimit) !== null && _c !== void 0 ? _c : 1000);
160
+ const sellerId = await extractSellerId.call(this);
161
+ let nextToken = undefined;
162
+ let totalProcessed = 0;
163
+ do {
164
+ if (nextToken) {
165
+ queryParams.pageToken = nextToken;
386
166
  }
387
- else {
388
- queryParams.asin = identifier;
389
- endpoint = `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}`;
167
+ else if (pageToken) {
168
+ queryParams.pageToken = pageToken;
390
169
  }
391
170
  const response = await SpApiRequest_1.SpApiRequest.makeRequest(this, {
392
171
  method: 'GET',
393
- endpoint,
172
+ endpoint: `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}`,
394
173
  query: queryParams,
395
174
  });
396
- let listingData;
397
- if (identifierType === 'sku') {
398
- listingData = response.data;
175
+ const apiData = response.data;
176
+ const items = (_d = apiData === null || apiData === void 0 ? void 0 : apiData.items) !== null && _d !== void 0 ? _d : [];
177
+ if (items.length) {
178
+ pushResults(items, itemIndex, returnData);
179
+ totalProcessed += items.length;
399
180
  }
400
- else {
401
- if (((_f = response.data) === null || _f === void 0 ? void 0 : _f.listings) && response.data.listings.length > 0) {
402
- const matchingListing = response.data.listings.find((listing) => listing.asin === identifier);
403
- if (matchingListing) {
404
- listingData = matchingListing;
405
- }
406
- else {
407
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `No listing found for ASIN: ${identifier}`);
408
- }
409
- }
410
- else {
411
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `No listing found for ASIN: ${identifier}`);
412
- }
181
+ nextToken = (_f = (_e = apiData === null || apiData === void 0 ? void 0 : apiData.pagination) === null || _e === void 0 ? void 0 : _e.nextToken) !== null && _f !== void 0 ? _f : apiData === null || apiData === void 0 ? void 0 : apiData.nextToken;
182
+ if (totalProcessed >= maxResultsLimit) {
183
+ break;
413
184
  }
414
- const outputData = [];
415
- marketplaceIds.forEach(marketplaceId => {
416
- outputData.push(formatListingForOutput(listingData, marketplaceId));
417
- });
418
- outputData.forEach(data => {
419
- returnData.push({
420
- json: data,
421
- pairedItem: { item: itemIndex },
422
- });
423
- });
424
- const duration = Date.now() - startTime;
425
- MetricsCollector_1.metricsCollector.recordMetric('operation_duration', duration, { operation: 'getListingDetails' });
426
- MetricsCollector_1.metricsCollector.recordMetric('results_count', outputData.length, { operation: 'getListingDetails' });
427
- AuditLogger_1.auditLogger.logEvent({
428
- nodeId,
429
- action: 'operation_completed',
430
- resource: 'listing_details',
431
- details: {
432
- operation: 'getListingDetails',
433
- itemIndex,
434
- duration,
435
- identifier,
436
- identifierType,
437
- outputCount: outputData.length,
438
- marketplaces: marketplaceIds.length,
439
- },
440
- severity: 'low',
441
- source: 'system',
442
- outcome: 'success'
443
- });
444
- }
445
- catch (error) {
446
- AuditLogger_1.auditLogger.logEvent({
447
- nodeId,
448
- action: 'operation_failed',
449
- resource: 'listing_details',
450
- details: {
451
- operation: 'getListingDetails',
452
- itemIndex,
453
- error: error instanceof Error ? error.message : 'Unknown error',
454
- },
455
- severity: 'high',
456
- source: 'system',
457
- outcome: 'failure'
458
- });
459
- if (error instanceof n8n_workflow_1.NodeOperationError) {
460
- throw error;
185
+ if (!returnAll) {
186
+ break;
461
187
  }
462
- const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
463
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Amazon SP-API Listings error: ${errorMessage}`);
188
+ } while (nextToken);
189
+ if (!returnData.length) {
190
+ returnData.push({ json: { items: [], pagination: { nextToken } }, pairedItem: { item: itemIndex } });
464
191
  }
192
+ return returnData;
465
193
  }
466
- else {
467
- throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Unknown operation: ${operation}`);
194
+ if (operation === 'getListingsItem2021' ||
195
+ operation === 'putListingsItem2021' ||
196
+ operation === 'patchListingsItem2021' ||
197
+ operation === 'deleteListingsItem2021' ||
198
+ operation === 'putListingsItem2020' ||
199
+ operation === 'patchListingsItem2020' ||
200
+ operation === 'deleteListingsItem2020') {
201
+ const marketplaceIds = this.getNodeParameter('marketplaceIds', itemIndex);
202
+ const marketplaceId = getSingleMarketplaceId(marketplaceIds, nodeId, this.getNode());
203
+ const issueLocale = this.getNodeParameter('issueLocale', itemIndex);
204
+ const sku = this.getNodeParameter('sku', itemIndex);
205
+ const sellerId = await extractSellerId.call(this);
206
+ const queryParams = {
207
+ marketplaceIds: marketplaceId,
208
+ };
209
+ if (issueLocale) {
210
+ queryParams.issueLocale = issueLocale;
211
+ }
212
+ let method;
213
+ let endpoint;
214
+ let body;
215
+ switch (operation) {
216
+ case 'getListingsItem2021':
217
+ method = 'GET';
218
+ endpoint = `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(sku)}`;
219
+ const includedData = this.getNodeParameter('includedData', itemIndex, []);
220
+ const normalizedIncludedData = normalizeIncludedData(includedData);
221
+ if (normalizedIncludedData) {
222
+ queryParams.includedData = normalizedIncludedData;
223
+ }
224
+ break;
225
+ case 'putListingsItem2021':
226
+ method = 'PUT';
227
+ endpoint = `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(sku)}`;
228
+ body = ensureObjectOrArray(this.getNodeParameter('bodyJson', itemIndex), 'Body (JSON)', this.getNode());
229
+ if (Array.isArray(body)) {
230
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'PUT body must be a JSON object.');
231
+ }
232
+ const includedDataPut = this.getNodeParameter('includedDataPutPatch', itemIndex, []);
233
+ const normalizedIncludedDataPut = normalizeIncludedData(includedDataPut);
234
+ if (normalizedIncludedDataPut) {
235
+ queryParams.includedData = normalizedIncludedDataPut;
236
+ }
237
+ const modePut = this.getNodeParameter('mode', itemIndex, '');
238
+ if (modePut) {
239
+ queryParams.mode = modePut;
240
+ }
241
+ break;
242
+ case 'patchListingsItem2021':
243
+ method = 'PATCH';
244
+ endpoint = `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(sku)}`;
245
+ body = ensureObjectOrArray(this.getNodeParameter('bodyJson', itemIndex), 'Body (JSON)', this.getNode());
246
+ const includedDataPatch = this.getNodeParameter('includedDataPutPatch', itemIndex, []);
247
+ const normalizedIncludedDataPatch = normalizeIncludedData(includedDataPatch);
248
+ if (normalizedIncludedDataPatch) {
249
+ queryParams.includedData = normalizedIncludedDataPatch;
250
+ }
251
+ const modePatch = this.getNodeParameter('mode', itemIndex, '');
252
+ if (modePatch) {
253
+ queryParams.mode = modePatch;
254
+ }
255
+ break;
256
+ case 'deleteListingsItem2021':
257
+ method = 'DELETE';
258
+ endpoint = `/listings/2021-08-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(sku)}`;
259
+ break;
260
+ case 'putListingsItem2020':
261
+ method = 'PUT';
262
+ endpoint = `/listings/2020-09-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(sku)}`;
263
+ body = ensureObjectOrArray(this.getNodeParameter('bodyJson', itemIndex), 'Body (JSON)', this.getNode());
264
+ if (Array.isArray(body)) {
265
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), 'PUT body must be a JSON object.');
266
+ }
267
+ break;
268
+ case 'patchListingsItem2020':
269
+ method = 'PATCH';
270
+ endpoint = `/listings/2020-09-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(sku)}`;
271
+ body = ensureObjectOrArray(this.getNodeParameter('bodyJson', itemIndex), 'Body (JSON)', this.getNode());
272
+ break;
273
+ case 'deleteListingsItem2020':
274
+ method = 'DELETE';
275
+ endpoint = `/listings/2020-09-01/items/${encodeURIComponent(sellerId)}/${encodeURIComponent(sku)}`;
276
+ break;
277
+ default:
278
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Unknown listings operation: ${operation}`);
279
+ }
280
+ const response = await SpApiRequest_1.SpApiRequest.makeRequest(this, {
281
+ method,
282
+ endpoint,
283
+ query: queryParams,
284
+ body,
285
+ });
286
+ return [{ json: response.data, pairedItem: { item: itemIndex } }];
468
287
  }
469
- return returnData;
288
+ throw new n8n_workflow_1.NodeOperationError(this.getNode(), `Unknown listings operation: ${operation}`);
470
289
  }
471
290
  //# sourceMappingURL=Listings.operations.js.map