@sp-api-sdk/common
Advanced tools
+10
-0
@@ -47,2 +47,12 @@ "use strict"; | ||
| const package_1 = require("./utils/package"); | ||
| /** | ||
| * Creates a pre-configured Axios instance for a Selling Partner API client. | ||
| * | ||
| * The instance handles authentication, rate-limit retries, error wrapping, | ||
| * and optional request/response logging. | ||
| * | ||
| * @param configuration - Client configuration options. | ||
| * @param rateLimits - Per-endpoint rate limits used for retry delay calculation. | ||
| * @returns An object containing the configured Axios instance and the resolved API endpoint. | ||
| */ | ||
| function createAxiosInstance({ auth, restrictedDataToken, region, userAgent = `${package_1.packageJson.name}/${package_1.packageJson.version}`, sandbox = false, rateLimiting, logging, }, rateLimits) { | ||
@@ -49,0 +59,0 @@ const regionConfiguration = regions_1.sellingPartnerRegions[region]; |
@@ -6,5 +6,14 @@ "use strict"; | ||
| const axios_1 = require("axios"); | ||
| /** | ||
| * Error thrown when a Selling Partner API request fails. | ||
| * | ||
| * Wraps the underlying Axios error with a message that includes the API name, | ||
| * version, and HTTP status code (or "No response" for network errors). | ||
| */ | ||
| class SellingPartnerApiError extends axios_1.AxiosError { | ||
| /** The original error message from the failed HTTP request. */ | ||
| innerMessage; | ||
| /** The API name extracted from the request URL path (e.g. `"orders"`). */ | ||
| apiName; | ||
| /** The API version extracted from the request URL path (e.g. `"v0"`). */ | ||
| apiVersion; | ||
@@ -11,0 +20,0 @@ constructor(error) { |
| "use strict"; | ||
| Object.defineProperty(exports, "__esModule", { value: true }); | ||
| exports.sellingPartnerRegions = void 0; | ||
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| exports.sellingPartnerRegions = { | ||
@@ -5,0 +6,0 @@ na: { |
+10
-0
@@ -8,2 +8,12 @@ import axios, { isAxiosError } from 'axios'; | ||
| import { packageJson } from './utils/package'; | ||
| /** | ||
| * Creates a pre-configured Axios instance for a Selling Partner API client. | ||
| * | ||
| * The instance handles authentication, rate-limit retries, error wrapping, | ||
| * and optional request/response logging. | ||
| * | ||
| * @param configuration - Client configuration options. | ||
| * @param rateLimits - Per-endpoint rate limits used for retry delay calculation. | ||
| * @returns An object containing the configured Axios instance and the resolved API endpoint. | ||
| */ | ||
| export function createAxiosInstance({ auth, restrictedDataToken, region, userAgent = `${packageJson.name}/${packageJson.version}`, sandbox = false, rateLimiting, logging, }, rateLimits) { | ||
@@ -10,0 +20,0 @@ const regionConfiguration = sellingPartnerRegions[region]; |
| import { URL } from 'node:url'; | ||
| import { AxiosError } from 'axios'; | ||
| /** | ||
| * Error thrown when a Selling Partner API request fails. | ||
| * | ||
| * Wraps the underlying Axios error with a message that includes the API name, | ||
| * version, and HTTP status code (or "No response" for network errors). | ||
| */ | ||
| export class SellingPartnerApiError extends AxiosError { | ||
| /** The original error message from the failed HTTP request. */ | ||
| innerMessage; | ||
| /** The API name extracted from the request URL path (e.g. `"orders"`). */ | ||
| apiName; | ||
| /** The API version extracted from the request URL path (e.g. `"v0"`). */ | ||
| apiVersion; | ||
@@ -7,0 +16,0 @@ constructor(error) { |
@@ -0,1 +1,2 @@ | ||
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| export const sellingPartnerRegions = { | ||
@@ -2,0 +3,0 @@ na: { |
@@ -8,30 +8,63 @@ import axios, { type AxiosError, type Method } from 'axios'; | ||
| type ErrorLogConfig = Exclude<Parameters<typeof errorLogger>[1], undefined>; | ||
| /** Per-endpoint rate limit definition used for retry delay calculation. */ | ||
| export interface RateLimit { | ||
| /** Regular expression matched against the request URL pathname. */ | ||
| urlRegex: RegExp; | ||
| /** Sustained request rate in requests per second. */ | ||
| rate: number; | ||
| /** Maximum burst size (number of requests allowed before throttling). */ | ||
| burst: number; | ||
| /** HTTP method this rate limit applies to. */ | ||
| method: Method; | ||
| } | ||
| /** Parameters passed to the {@link ClientConfiguration.rateLimiting} `onRetry` callback. */ | ||
| export interface OnRetryParameters { | ||
| /** Delay in milliseconds before the next retry attempt. */ | ||
| delay: number; | ||
| /** Rate limit (requests per second) used to calculate the delay, if available. */ | ||
| rateLimit?: number; | ||
| /** Number of retry attempts so far. */ | ||
| retryCount: number; | ||
| /** The Axios error that triggered the retry. */ | ||
| error: AxiosError; | ||
| } | ||
| /** Configuration options for creating a Selling Partner API Axios instance. */ | ||
| export interface ClientConfiguration { | ||
| /** Authentication handler that provides LWA access tokens. */ | ||
| auth: SellingPartnerApiAuth; | ||
| /** Restricted Data Token to use instead of the standard access token. */ | ||
| restrictedDataToken?: string; | ||
| /** Selling Partner API region to send requests to. */ | ||
| region: SellingPartnerRegion; | ||
| /** Custom `User-Agent` header value. */ | ||
| userAgent?: string; | ||
| /** When `true`, requests are sent to the sandbox endpoint. Defaults to `false`. */ | ||
| sandbox?: boolean; | ||
| /** Rate-limiting and retry configuration for 429 responses. */ | ||
| rateLimiting?: { | ||
| /** When `true`, automatically retries throttled (HTTP 429) requests. */ | ||
| retry: boolean; | ||
| /** Optional callback invoked before each retry attempt. */ | ||
| onRetry?: (retryInfo: OnRetryParameters) => void; | ||
| }; | ||
| /** Axios request/response/error logging configuration. Pass `true` to use defaults. */ | ||
| logging?: { | ||
| /** Log outgoing requests. */ | ||
| request?: RequestLogConfig | true; | ||
| /** Log incoming responses. */ | ||
| response?: ResponseLogConfig | true; | ||
| /** Log request errors. */ | ||
| error?: ErrorLogConfig | true; | ||
| }; | ||
| } | ||
| /** | ||
| * Creates a pre-configured Axios instance for a Selling Partner API client. | ||
| * | ||
| * The instance handles authentication, rate-limit retries, error wrapping, | ||
| * and optional request/response logging. | ||
| * | ||
| * @param configuration - Client configuration options. | ||
| * @param rateLimits - Per-endpoint rate limits used for retry delay calculation. | ||
| * @returns An object containing the configured Axios instance and the resolved API endpoint. | ||
| */ | ||
| export declare function createAxiosInstance({ auth, restrictedDataToken, region, userAgent, sandbox, rateLimiting, logging, }: ClientConfiguration, rateLimits: RateLimit[]): { | ||
@@ -38,0 +71,0 @@ axios: axios.AxiosInstance; |
| import { AxiosError } from 'axios'; | ||
| /** | ||
| * Error thrown when a Selling Partner API request fails. | ||
| * | ||
| * Wraps the underlying Axios error with a message that includes the API name, | ||
| * version, and HTTP status code (or "No response" for network errors). | ||
| */ | ||
| export declare class SellingPartnerApiError<T = unknown, D = any> extends AxiosError<T, D> { | ||
| /** The original error message from the failed HTTP request. */ | ||
| readonly innerMessage: string; | ||
| /** The API name extracted from the request URL path (e.g. `"orders"`). */ | ||
| readonly apiName?: string; | ||
| /** The API version extracted from the request URL path (e.g. `"v0"`). */ | ||
| readonly apiVersion?: string; | ||
| constructor(error: AxiosError<T, D>); | ||
| } |
@@ -0,1 +1,2 @@ | ||
| /** Selling Partner API region identifier. */ | ||
| export type SellingPartnerRegion = 'na' | 'eu' | 'fe'; | ||
@@ -9,3 +10,4 @@ interface RegionConfiguration { | ||
| } | ||
| /** AWS region and endpoint mapping for each Selling Partner API region. */ | ||
| export declare const sellingPartnerRegions: Record<SellingPartnerRegion, RegionConfiguration>; | ||
| export {}; |
+4
-4
@@ -5,3 +5,3 @@ { | ||
| "description": "Selling Parner API common library", | ||
| "version": "2.1.29", | ||
| "version": "2.1.30", | ||
| "main": "dist/cjs/index.js", | ||
@@ -23,4 +23,4 @@ "module": "dist/es/index.js", | ||
| "dependencies": { | ||
| "@sp-api-sdk/auth": "2.2.23", | ||
| "axios": "^1.13.5", | ||
| "@sp-api-sdk/auth": "2.2.24", | ||
| "axios": "^1.13.6", | ||
| "axios-logger": "^2.8.1", | ||
@@ -48,3 +48,3 @@ "axios-retry": "^4.5.0", | ||
| ], | ||
| "gitHead": "2c1fe783fb7c2204e7e19d4f85fa2bdf822e4593" | ||
| "gitHead": "ed62de76baf24107227aacb576cd494b2ecbf0b5" | ||
| } |
+99
-1
@@ -12,4 +12,102 @@ # `@sp-api-sdk/common` | ||
| - `npm install @sp-api-sdk/common` | ||
| ```sh | ||
| npm install @sp-api-sdk/common | ||
| ``` | ||
| > **Note:** You typically do not need to install this package directly. It is automatically included as a dependency of every API client package. | ||
| ## Overview | ||
| This package provides the shared infrastructure used by all API client packages: | ||
| - **Axios instance factory** with authentication, rate limiting, logging, and error handling | ||
| - **Region configuration** for NA, EU, and FE endpoints (production and sandbox) | ||
| - **Error handling** with `SellingPartnerApiError` | ||
| ## Client Configuration | ||
| The `ClientConfiguration` interface is used by all API client constructors: | ||
| ```typescript | ||
| import { type ClientConfiguration } from "@sp-api-sdk/common"; | ||
| ``` | ||
| | Option | Type | Required | Description | | ||
| | --------------------- | ----------------------- | -------- | ----------------------------------------------- | | ||
| | `auth` | `SellingPartnerApiAuth` | Yes | Authentication instance from `@sp-api-sdk/auth` | | ||
| | `region` | `'na' \| 'eu' \| 'fe'` | Yes | Selling Partner API region | | ||
| | `sandbox` | `boolean` | No | Use sandbox endpoints (default: `false`) | | ||
| | `rateLimiting` | `object` | No | Rate limiting retry configuration | | ||
| | `logging` | `object` | No | Request/response/error logging configuration | | ||
| | `restrictedDataToken` | `string` | No | Restricted Data Token for accessing PII | | ||
| | `userAgent` | `string` | No | Custom user-agent header | | ||
| ## Regions | ||
| Three regions are supported, each with production and sandbox endpoints: | ||
| | Region | Code | AWS Region | Production Endpoint | | ||
| | ------------- | ---- | ---------- | ----------------------------------------- | | ||
| | North America | `na` | us-east-1 | `https://sellingpartnerapi-na.amazon.com` | | ||
| | Europe | `eu` | eu-west-1 | `https://sellingpartnerapi-eu.amazon.com` | | ||
| | Far East | `fe` | us-west-2 | `https://sellingpartnerapi-fe.amazon.com` | | ||
| When `sandbox` is set to `true`, the sandbox variant of the endpoint is used (e.g. `https://sandbox.sellingpartnerapi-eu.amazon.com`). | ||
| ## Rate Limiting | ||
| When `rateLimiting.retry` is enabled, the SDK automatically retries HTTP 429 responses. The retry delay is calculated as follows: | ||
| 1. If the response includes an `x-amzn-ratelimit-limit` header, the delay is derived from it. | ||
| 2. Otherwise, the SDK falls back to the documented rate limits for the specific endpoint. | ||
| 3. If no rate limit information is available, a 60-second default delay is used. | ||
| You can optionally provide an `onRetry` callback to be notified on every retry: | ||
| ```typescript | ||
| rateLimiting: { | ||
| retry: true, | ||
| onRetry: ({delay, rateLimit, retryCount, error}) => { | ||
| console.log(`Retry #${retryCount}, waiting ${delay}ms (rate limit: ${rateLimit})`) | ||
| }, | ||
| } | ||
| ``` | ||
| ## Logging | ||
| Logging is powered by [axios-logger](https://github.com/hg-pyun/axios-logger) and can be configured independently for requests, responses, and errors: | ||
| ```typescript | ||
| logging: { | ||
| request: true, // or a RequestLogConfig object | ||
| response: true, // or a ResponseLogConfig object | ||
| error: true, // or an ErrorLogConfig object | ||
| } | ||
| ``` | ||
| Pass `true` to use sensible defaults (no headers logged for requests, headers logged for responses). Pass a configuration object to customize the behavior. | ||
| By default, `request` and `response` loggers use `console.info`, and the `error` logger uses `console.error`. | ||
| > **Warning:** Enabling `headers: true` in the request logger will log authentication tokens. This should be disabled in production. | ||
| ## Error Handling | ||
| API errors are wrapped in `SellingPartnerApiError`, which extends `AxiosError` and adds context: | ||
| ```typescript | ||
| import { SellingPartnerApiError } from "@sp-api-sdk/common"; | ||
| try { | ||
| await client.getOrders({ marketplaceIds: ["A1PA6795UKMFR9"] }); | ||
| } catch (error) { | ||
| if (error instanceof SellingPartnerApiError) { | ||
| console.error(error.message); // e.g. "orders (v0) error: Response code 403" | ||
| console.error(error.apiName); // e.g. "orders" | ||
| console.error(error.apiVersion); // e.g. "v0" | ||
| console.error(error.innerMessage); // Original axios error message | ||
| } | ||
| } | ||
| ``` | ||
| ## License | ||
@@ -16,0 +114,0 @@ |
29333
42.84%521
19.22%127
337.93%+ Added
- Removed
Updated
Updated