idosell 0.4.43 → 0.4.47

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/changelog.md CHANGED
@@ -5,27 +5,39 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
- ## [0.4.43] - 2025-06-07
8
+ ## [0.4.47] - 2026-06-24
9
+ ### Added
10
+ - Added optional OAuth2 authentication instead of API key authentication
11
+ - Updated to latest v8.7
12
+
13
+
14
+ ## [0.4.45] - 2026-06-07
15
+ ### Added
16
+ - Added handleRaw to pass raw data instead of request
17
+ - Added test to webhooks
18
+
19
+
20
+ ## [0.4.43] - 2026-06-07
9
21
  ### Changed
10
22
  - Webhook now supports HMAC checking and groups of webhooks
11
23
  - Added raw data to webhook headers and handlers
12
24
 
13
25
 
14
- ## [0.4.41] - 2025-06-07
26
+ ## [0.4.41] - 2026-06-07
15
27
  ### Added
16
28
  - Added webook support
17
29
  - Added LANG_ID enumerator
18
30
  - Added mapProductParameters utils helper
19
31
 
20
32
 
21
- ## [0.4.38] - 2025-06-03
33
+ ## [0.4.38] - 2026-06-03
22
34
  ### Changed
23
35
  - Added enum types from description
24
36
  - Updated types to latest versions
25
37
  - Updated axios version to latest
26
38
  - Added mapping parameters to utils
27
39
 
28
- ## [0.4.34] - 2025-05-27
40
+ ## [0.4.34] - 2026-05-27
29
41
  ### Fixed
30
42
  - Reusing idosell object unintentionally copied some fields
31
43
  - Requiremens check failed on falsy (0 or empty string), not only fails when undefined or null
@@ -33,33 +45,33 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
33
45
  ### Changed
34
46
  - Fixed missing types
35
47
 
36
- ## [0.4.32] - 2025-05-19
48
+ ## [0.4.32] - 2026-05-19
37
49
  ### Changed
38
50
  - Fixed some latest types
39
51
  - Fxied paging
40
52
 
41
- ## [0.4.30] - 2025-05-07
53
+ ## [0.4.30] - 2026-05-07
42
54
  ### Changed
43
55
  - Updated to Idosell Rest API v8.1
44
56
  - Some methods removed from api v8.1, still availible through v7 enpoints - version is enforced for those enpoints
45
57
 
46
- ## [0.4.27] - 2025-04-06
58
+ ## [0.4.27] - 2026-04-06
47
59
  ### Changed
48
60
  - Addded missing promotions types
49
61
  - Fixed paging for promotions
50
62
 
51
- ## [0.4.25] - 2025-04-04
63
+ ## [0.4.25] - 2026-04-04
52
64
  ### Changed
53
65
  - Updated to v7.19
54
66
  - Added promotion routes
55
67
  - Changed routes that have ProductsProducts to Products like getProductsToFacebookCatalog (before: getProductsProductsToFacebookCatalog)
56
68
 
57
- ## [0.4.24] - 2025-03-21
69
+ ## [0.4.24] - 2026-03-21
58
70
  ### Changed
59
71
  - Updated to v7.13
60
72
  - Fixed url format
61
73
 
62
- ## [0.4.23] - 2025-03-11
74
+ ## [0.4.23] - 2026-03-11
63
75
  ### Changed
64
76
  - Added custom error class
65
77
  - Fixed types for ids that can be integer instead of string
package/dist/app.d.ts CHANGED
@@ -7,109 +7,109 @@ import type {
7
7
  } from "./responses.d.ts";
8
8
 
9
9
  export interface ExecutableDumpParams {
10
- url: string;
11
- method: string;
12
- params: Record<string,any>;
10
+ url: string;
11
+ method: string;
12
+ params: Record<string, any>;
13
13
  }
14
14
 
15
15
  export interface ExecutableOptions {
16
- log?: boolean | ((obj: ExecutableDumpParams) => void),
16
+ log?: boolean | ((obj: ExecutableDumpParams) => void),
17
17
  dump?: boolean | ((obj: ExecutableDumpParams) => void),
18
18
  logPage?: boolean | ((text: string) => void),
19
- skipCheck?: boolean
19
+ skipCheck?: boolean
20
20
  }
21
21
 
22
22
  export type DateLike = string | number | Date;
23
23
 
24
- export type JSObject = Record<string,any>;
24
+ export type JSObject = Record<string, any>;
25
25
 
26
26
  export type RequestProxyObject = {
27
- auth: {
28
- url: string,
29
- apiKey: string,
30
- version: number|string
31
- },
32
- params: Record<string, any>,
27
+ auth: {
28
+ url: string,
29
+ apiKey: ApyKeyOrOauthCredentials,
30
+ version: number | string
31
+ },
32
+ params: Record<string, any>,
33
33
  }
34
34
 
35
35
  export type RequirementType = {
36
- any: string[]|true
37
- } | string | ((arg: RequestProxyObject | Record<string,any>) => string|false);
36
+ any: string[] | true
37
+ } | string | ((arg: RequestProxyObject | Record<string, any>) => string | false);
38
38
 
39
39
  export type GatewayRequestProxyObject = {
40
- gate: {
41
- method: 'get'|'post'|'put'|'delete',
42
- node: string
43
- },
44
- appendable?: {
45
- index: number,
46
- arrayNode: string,
47
- except: string[]
48
- },
49
- custom?: Record<string,(..._: any) => false|Record<string,any>>,
50
- snakeCase?: boolean,
51
- paginationObject?: boolean,
52
- next?: boolean,
53
- rootparams?: string|boolean,
54
- arrays?: string[],
55
- req?: RequirementType[],
56
- n?: Record<string,number>
40
+ gate: {
41
+ method: 'get' | 'post' | 'put' | 'delete',
42
+ node: string
43
+ },
44
+ appendable?: {
45
+ index: number,
46
+ arrayNode: string,
47
+ except: string[]
48
+ },
49
+ custom?: Record<string, (..._: any) => false | Record<string, any>>,
50
+ snakeCase?: boolean,
51
+ paginationObject?: boolean,
52
+ next?: boolean,
53
+ rootparams?: string | boolean,
54
+ arrays?: string[],
55
+ req?: RequirementType[],
56
+ n?: Record<string, number>
57
57
  } & RequestProxyObject;
58
58
 
59
59
  export interface Gateway<R = JSObject, P = JSObject> {
60
- /**
61
- * Executes the query to designated API endpoint
62
- * @param options Use options: log - to console log params, url and method, logPage - to console log current page in a loop
63
- * @returns Idosell response
64
- */
65
- exec: (options?: ExecutableOptions) => Promise<R>,
66
-
67
- /**
68
- * @returns Object with currently mapped parameters
69
- */
70
- getParams: () => P,
71
-
72
- /**
73
- * @description Set object as params
74
- */
75
- setParams: (params: P) => this
76
-
77
- /**
78
- * @description Checks if minimal parameters are provided. If not, throws an error.
79
- */
80
- checkParams: () => void
60
+ /**
61
+ * Executes the query to designated API endpoint
62
+ * @param options Use options: log - to console log params, url and method, logPage - to console log current page in a loop
63
+ * @returns Idosell response
64
+ */
65
+ exec: (options?: ExecutableOptions) => Promise<R>,
66
+
67
+ /**
68
+ * @returns Object with currently mapped parameters
69
+ */
70
+ getParams: () => P,
71
+
72
+ /**
73
+ * @description Set object as params
74
+ */
75
+ setParams: (params: P) => this
76
+
77
+ /**
78
+ * @description Checks if minimal parameters are provided. If not, throws an error.
79
+ */
80
+ checkParams: () => void
81
81
  }
82
82
 
83
- export interface PagableGateway<T,R = JSObject, P = JSObject> extends Gateway<R, P> {
84
- /**
83
+ export interface PagableGateway<T, R = JSObject, P = JSObject> extends Gateway<R, P> {
84
+ /**
85
85
  * @returns number of items i.e. products, orders, documents, etc.
86
86
  */
87
- count: () => Promise<number>,
87
+ count: () => Promise<number>,
88
88
 
89
- /**
89
+ /**
90
90
  * Allows to change offset and number of records returned
91
91
  * @param pageNumber - The page number to navigate to.
92
92
  * @param pageSize - The size of page
93
93
  * @returns The updated instance for method chaining.
94
94
  */
95
- page: (pageNumber: number, pageSize?: number) => T
95
+ page: (pageNumber: number, pageSize?: number) => T
96
96
 
97
- /**
98
- * @returns If completed request has more pages
99
- */
100
- hasNext: () => boolean
97
+ /**
98
+ * @returns If completed request has more pages
99
+ */
100
+ hasNext: () => boolean
101
101
  }
102
102
 
103
- export interface AppendableGateway<T,R = JSObject, P = JSObject> extends Gateway<R, P> {
104
- /**
105
- * Start creating next item in list
106
- */
107
- append: () => T
103
+ export interface AppendableGateway<T, R = JSObject, P = JSObject> extends Gateway<R, P> {
104
+ /**
105
+ * Start creating next item in list
106
+ */
107
+ append: () => T
108
108
  }
109
109
 
110
110
  export interface IdosellErrorFaultStructure {
111
- faultCode: number;
112
- faultString: string;
111
+ faultCode: number;
112
+ faultString: string;
113
113
  }
114
114
 
115
115
  // ─── Final normalized shape ──────────────────────────────────────────────────
@@ -244,12 +244,20 @@ export type DispatchResult =
244
244
  | { matched: false; eventType: string }
245
245
  | { matched: false; eventType: null; reason: "validation_failed" };
246
246
 
247
+
248
+ export interface RawWebhookInput {
249
+ headers: Record<string, string>;
250
+ rawBody: string; // always string — pre-parse
251
+ body?: Record<string, unknown>; // optional — caller may pre-parse
252
+ }
253
+
247
254
  export declare class WebhookChain {
248
255
  validateHeaders(validator: HeaderValidator): this;
249
256
  validateSignature(hmacKey: string): this;
250
257
  on<E extends WebhookEventType>(eventType: E, handler: WebhookHandler<E>): this;
251
258
  on<O extends WebhookObjectType>(objectType: O, handler: WebhookObjectHandler<O>): this;
252
259
  handle(req: import("node:http").IncomingMessage | Request): Promise<DispatchResult>;
260
+ handleRaw(req: RawWebhookInput): Promise<DispatchResult>;
253
261
  }
254
262
 
255
263
  export type Webhooks = {
@@ -259,4 +267,11 @@ export type Webhooks = {
259
267
  on<O extends WebhookObjectType>(objectType: O, handler: WebhookObjectHandler<O>): WebhookChain;
260
268
  };
261
269
 
262
- export {};
270
+ export type ApyKeyOrOauthCredentials = string | {
271
+ login: string;
272
+ password: string;
273
+ scope?: ('admin')[];
274
+ token?: string;
275
+ }
276
+
277
+ export { };
package/dist/gates.js CHANGED
@@ -135,6 +135,7 @@ import getPackagesLabels from "./methods/getPackagesLabels.js";
135
135
  import postPackagesLabels from "./methods/postPackagesLabels.js";
136
136
  import postPackages from "./methods/postPackages.js";
137
137
  import putPackages from "./methods/putPackages.js";
138
+ import deletePackages from "./methods/deletePackages.js";
138
139
  import searchPackages from "./methods/searchPackages.js";
139
140
  import postPaymentsCancel from "./methods/postPaymentsCancel.js";
140
141
  import postPaymentsCashback from "./methods/postPaymentsCashback.js";
@@ -473,6 +474,7 @@ const gates = {
473
474
  postPackagesLabels,
474
475
  postPackages,
475
476
  putPackages,
477
+ deletePackages,
476
478
  searchPackages,
477
479
  postPaymentsCancel,
478
480
  postPaymentsCashback,
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable @typescript-eslint/no-empty-object-type */
2
- import type { PagableGateway, AppendableGateway, Gateway, DateLike, JSObject, IdosellErrorFaultStructure, Webhooks, IaiWebhookHeaders } from "./app.d.ts"
2
+ import type { PagableGateway, AppendableGateway, Gateway, DateLike, JSObject, IdosellErrorFaultStructure, Webhooks, IaiWebhookHeaders, ApyKeyOrOauthCredentials } from "./app.d.ts"
3
3
  import type { GetClientsBalanceResponse, BooleanStatusResponse, GetClientsResponse, PostClientsResponse, PutClientsResponse, SearchClientsCrmResponse, GetClientsDeliveryAddressResponse, PostClientsDeliveryAddressResponse, PutClientsDeliveryAddressResponse, VouchersResponse, PutVouchersResponse, SearchClientsGiftcardsResponse, GetClientsGiftcardsTypesResponse, GetClientsMembershipCardsResponse, PutClientsMembershipCardsResponse, SearchClientsNewsletterEmailResponse, SearchClientsNewsletterSmsResponse, GetClientsPayerAddressResponse, PostClientsPayerAddressResponse, PutClientsPayerAddressResponse, GetClientsPricelistsClientsResponse, PutClientsPricelistsClientsResponse, GetClientsPricelistsResponse, PostClientsPricelistsResponse, GetClientsPricelistsProductsResponse, PutClientsPricelistsProductsResponse, GetClientsPricesActiveCardResponse, GetClientsPricesDiscountGroupsResponse, GetClientsPricesDiscountsResponse, PutClientsPricesDiscountsResponse, GetClientsProfitPointsResponse, GetClientsProvinceListResponse, GetClientsTagsResponse, PostClientsTagsResponse, PutClientsTagsResponse, GetConfigVariablesResponse, PutConfigVariablesResponse, GetCouriersAssignedToShippingProfilesResponse, GetCouriersResponse, GetCouriersPickupPointsResponse, PutCouriersPickupPointsResponse, GetCpaCampaignResponse, CmsCampaignResponse, CmsResponse, GetCpaResponse, GetDeliveriesProfilesResponse, GetDeliveriesRegionsResponse, PostDeliveriesRegionsResponse, GetDiscountsGroupsClientsResponse, GetDiscountsGroupsResponse, PostDiscountsGroupsResponse, GetEntriesResponse, PostEntriesResponse, GetEntriesPagesToDisplayResponse, GetEntriesSourcesResponse, GetMenuResponse, PostMenuResponse, PutMenuResponse, PutMenuSortResponse, GetOrdersAnalyticsResponse, GetOrdersAuctionDetailsResponse, PutOrdersCourierResponse, PostOrdersDocumentsCreateResponse, GetOrdersDocumentsResponse, PostOrdersDocumentsResponse, GetOrdersHandlerResponse, GetOrdersHistoryResponse, GetOrdersImagesResponse, PostOrdersImagesResponse, GetOrdersLabelsResponse, SearchOrdersOpinionsResponse, GetOrdersOpinionsRateResponse, SearchOrdersResponse, PostOrdersResponse, PutOrdersResponse, GetOrdersPackagesResponse, PutOrdersPackagesResponse, PutOrdersProductsSerialNumbersResponse, PutOrdersProfitMarginResponse, GetOrdersProfitabilityResponse, GetOrdersStatusesResponse, GetOrdersWarehouseResponse, PostPackagesLabelsResponse, PutPackagesResponse, SearchPackagesResponse, GetPaymentsFormsResponse, GetPaymentsResponse, PostPaymentsResponse, GetPaymentsProfilesResponse, PostPaymentsRepaymentResponse, GetProductsSKUbyBarcodeResponse, GetProductsAttachmentsGetContentResponse, PutProductsAttachmentsResponse, GetProductsAuctionsResponse, GetProductsBrandsResponse, PutProductsBrandsResponse, GetProductsCategoriesResponse, PutProductsCategoriesResponse, SearchProductsCategoriesIdosellResponse, GetProductsCodeExistenceResponse, SearchProductsDeliveryTimeResponse, GetProductsDescriptionsResponse, ProductIdentResponse, PutProductsGroupsSettingsResponse, GetProductsIdBySizecodeResponse, PutProductsImagesResponse, GetProductsMarketingZonesResponse, PutProductsMarketingZonesResponse, GetProductsOmnibusPricesResponse, GetProductsOpinionsResponse, PostProductsOpinionsResponse, GetProductsOpinionsRateResponse, PutProductsParametersResponse, SearchProductsParametersResponse, SearchProductsResponse, PostProductsResponse, PutProductsResponse, PutProductsMarketingPromotionResponse, GetProductsQuestionsResponse, GetProductsReservationsResponse, GetProductsSeriesResponse, PutProductsSeriesResponse, GetProductsSizesResponse, PutProductsSizesResponse, PutProductsStockQuantityResponse, GetProductsStocksResponse, PutProductsStocksResponse, GetProductsStrikethroughPricesResponse, PutProductsSupplierCodeResponse, PutProductsSupplierProductDataResponse, PromotionBoolResponse, SearchPromotionsElementsResponse, SearchPromotionsHistoryResponse, PromotionIdResponse, GetPromotionsResponse, SearchPromotionsListViewResponse, GetPromotionsArchiveResponse, SearchPromotionsArchiveResponse, GetPromotionsSettingsResponse, GetRegulationsHistoryResponse, GetResponsibilityEntitiesResponse, PutResponsibilityEntitiesResponse, GetReturnsResponse, PostReturnsResponse, PutReturnsResponse, PutReturnsSerialNumberResponse, GetRmaResponse, PutRmaResponse, GetRmaStatusesResponse, GetShopsCurrenciesResponse, GetShopsLanguagesResponse, GetSizechartsResponse, PutSizechartsResponse, GetSizesResponse, PutSizesResponse, GetSnippetsCampaignResponse, GetSnippetsCookiesResponse, GetSnippetsResponse, GetSystemConfigResponse, GetSystemCurrenciesResponse, PutSystemCurrenciesResponse, GetSystemProcessesAutomationResponse, GetSystemServerLoadResponse, GetSystemServerTimeResponse, GetSystemShopsDataResponse, GetSystemUnitsResponse, PutSystemUnitsResponse, GetSystemUsersResponse, GetVouchersTypesResponse, GetVouchersResponse, GetWarrantiesCountTotalResponse, PutWarrantiesLanguageDataResponse, GetWarrantiesResponse, PutWarrantiesResponse, GetWmsLocationsResponse, GetWmsStocksdocumentsDocumentsResponse, PostWmsStocksdocumentsDocumentsResponse, PutWmsStocksdocumentsDocumentsResponse, GetWmsStocksdocumentsOpenedDocumentsResponse, GetWmsStocksdocumentsProductsResponse, PutWmsStocksdocumentsProductsResponse, GetWmsSuppliersResponse, PutWmsSuppliersResponse, GetProductsMarketingPromotionResponse, PostProductsMarketingPromotionResponse } from "./responses.d.ts"
4
4
  import type * as RequestParams from "./reqparams.d.ts";
5
5
  import { ENUMS } from "./enums";
@@ -1209,6 +1209,12 @@ export interface PostEntriesRequest extends AppendableGateway<PostEntriesRequest
1209
1209
  blogUrl: (blogUrl: string) => this
1210
1210
  /** News item URL */
1211
1211
  newsUrl: (newsUrl: string) => this
1212
+ /** Meta title of the entry */
1213
+ metaTitle: (metaTitle: string) => this
1214
+ /** Meta description of the entry */
1215
+ metaDescription: (metaDescription: string) => this
1216
+ /** Meta keywords of the entry */
1217
+ metaKeywords: (metaKeywords: string) => this
1212
1218
  /** Add Post to blog entries */
1213
1219
  blog: () => this;
1214
1220
  /** Add Post to news entries */
@@ -2048,6 +2054,11 @@ export interface PutPackagesRequest extends AppendableGateway<PutPackagesRequest
2048
2054
  packages: (packages: RequestParams.PutPackagesParams["orderPackages"][number]["packages"]) => this
2049
2055
  }
2050
2056
 
2057
+ export interface DeletePackagesRequest extends Gateway {
2058
+ /** Parcels's ID */
2059
+ packageId: (value: number|string) => this;
2060
+ }
2061
+
2051
2062
  export interface SearchPackagesRequest extends AppendableGateway<SearchPackagesRequest, SearchPackagesResponse, RequestParams.SearchPackagesParams> {
2052
2063
  /** Consignments numbers. */
2053
2064
  deliveryPackageNumbers: (value: string|string[]) => this;
@@ -2672,7 +2683,7 @@ export interface PutProductsParametersRequest extends AppendableGateway<PutProdu
2672
2683
  card_icons: (card_icons: RequestParams.PutProductsParametersParams["items"][number]["card_icons"]) => this
2673
2684
  /** Icons of section, parameter or value to display on the list of products. */
2674
2685
  link_icons: (link_icons: RequestParams.PutProductsParametersParams["items"][number]["link_icons"]) => this
2675
- /** Parameter's additional feature. 1. Status: context_id = "CONTEXT_STATE" Takes values context_value_id: - CONTEXT_STATE_NEW - New, - CONTEXT_STATE_USED - Used, - CONTEXT_STATE_USED_EXCELLENT - Used - excellent condition - CONTEXT_STATE_USED_VERYGOOD - Used - very good condition - CONTEXT_STATE_USED_CORRECT - Used - good condition - CONTEXT_STATE_USED_ACCEPTABLE - Used - acceptable condition - CONTEXT_STATE_REFURBISHED_EXCELLENT - Refurbished - excellent condition - CONTEXT_STATE_REFURBISHED_VERYGOOD - Refurbished - very good condition - CONTEXT_STATE_REFURBISHED_CORRECT - Refurbished - good condition - CONTEXT_STATE_NEW_OTHERS - New other (see details) - CONTEXT_STATE_NEW_WITH_DEFECTS - New with defects - CONTEXT_STATE_NEW_OEM - New - OEM - CONTEXT_STATE_NEW_OPEN_BOX - New - open box - CONTEXT_STATE_REFURBISHED_BY_PRODUCER - Renewed by a manufacturer, - CONTEXT_STATE_REFURBISHED_BY_SELLER - Renewed by a seller, - CONTEXT_STATE_FOR_PARTS_OR_BROKEN - In parts or damaged. 2. Product weight in grams: context_id = "CONTEXT_STD_UNIT_WEIGHT" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 3. A product's value in milliliters: context_id = "CONTEXT_STD_UNIT_VOLUME" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 4. Sex: context_id = "CONTEXT_SEX" Takes values context_value_id: - CONTEXT_SEX_MAN - Man, - CONTEXT_SEX_WOMAN - Woman, - CONTEXT_SEX_UNISEX - Unisex. 5. Age group: context_id = "CONTEXT_AGE_GROUP" Takes values context_value_id: - CONTEXT_AGE_GROUP_ADULT - Adults, - CONTEXT_AGE_GROUP_MINOR - Children. 6. Maximum number of products in an order: context_id = "CONTEXT_MAX_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 7. Maximum number of products in a wholesale order: context_id = "CONTEXT_MAX_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 8. Minimal number of products in an order: context_id = "CONTEXT_MIN_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 9. Minimum number of products in a wholesale order: context_id = "CONTEXT_MIN_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 10. Maximal number of a single size in an order: context_id = "CONTEXT_MAX_SIZE_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 11. Maximal number of a single size in a wholesale order: context_id = "CONTEXT_MAX_SIZE_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 12. Minimal number of a single size in an order: context_id = "CONTEXT_MIN_SIZE_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 13. Minimal number of a single size in a wholesale order: context_id = "CONTEXT_MIN_SIZE_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 14. Net weight: context_id = "CONTEXT_WEIGHT_NET" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 15. Color: context_id = "CONTEXT_COLOR" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 16. #!TylkoDlaDoroslych!#: context_id = "CONTEXT_ONLY_ADULTS" Takes values context_value_id: - CONTEXT_ONLY_ADULTS_YES - yes, - CONTEXT_ONLY_ADULTS_NO - no. 17. Prescription drug: context_id = "CONTEXT_PRESCRIPTION_MEDICINE" Takes values context_value_id: - CONTEXT_PRESCRIPTION_MEDICINE_YES - yes, - CONTEXT_PRESCRIPTION_MEDICINE_NO - no. 18. Season Rate: context_id = "CONTEXT_SEASON" Takes values context_value_id: - CONTEXT_SEASON_SPRING - Spring, - CONTEXT_SEASON_SUMMER - Summer, - CONTEXT_SEASON_FALL - Autumn, - CONTEXT_SEASON_WINTER - Winter, - CONTEXT_SEASON_SPRING_SUMMER - Spring/Summer, - CONTEXT_SEASON_FALL_WINTER - Autumn/Winter 19. Risk - signal word: context_id = \"CONTEXT_HAZMAT_SIGNAL\" Takes values context_value_id: - CONTEXT_HAZMAT_SIGNAL_DANGER - danger, - CONTEXT_HAZMAT_SIGNAL_WARNING - warnging, - CONTEXT_HAZMAT_SIGNAL_CAUTION - caution, - CONTEXT_HAZMAT_SIGNAL_NOTICE - notice, 20. Risk - warning pictogram context_id = \"CONTEXT_HAZMAT_PICTOGRAM\" Takes values context_value_id: - GHS01, GHS02, GHS03, GHS04, GHS05, GHS06, GHS07, GHS08, GHS09 21. Risk - type of hazard: context_id = \"CONTEXT_HAZMAT_STATEMENT\" Takes values context_value_id: - H200, H201, H202, H203, H204, H205, H220, H221, H222, H223, H224, H225, H226, H228, H240, H241, H242, H250, H251, H252, H260, H261, H270, H271, H272, H280, H281, H290, H300, H301, H302, H304, H310, H311, H312, H314, H315, H317, H318, H319, H330, H331, H332, H334, H335, H336, H340, H341, H350, H351, H360, H361, H362, H370, H371, H372, H373, H400, H410, H411, H412, H413, EUH 001, EUH 014, EUH 018, EUH 019, EUH 044, EUH 029, EUH 031, EUH 032, EUH 066, EUH 070, EUH 071, EUH 201, EUH 201A, EUH 202, EUH 203, EUH 204, EUH 205, EUH 206, EUH 207, EUH 208, EUH 209, EUH 209A, EUH 210, EUH 401 22. Repair score: context_id = \"CONTEXT_REPAIR_SCORE\" Takes values context_value_id: - The value of the additional feature is set automatically based on the parameter's value 23. Safety - information pictogram: context_id = \"CONTEXT_SAFETY_PICTOGRAM\" Takes values context_value_id: - 1 (Not suitable for small children) - 2 (CE mark) 24. Safety - type of warning: context_id = \"CONTEXT_SAFETY_STATEMENT\" Takes values context_value_id: - 1 (Not suitable for children under 3 years) - 2 (Keep out of the reach of children) - 3 (Product contains a button cell or coin battery) - 4 (Use under the direct supervision of adults) - 5 (Required protective gear. Do not use in public traffic) - 6 (Contains toy. Adult supervision recommended) - 7 (To prevent possible injury from entanglement, remove this toy as soon as the child begins to crawl) - 8 (Use only in shallow water under adult supervision) - 9 (Only use under adult supervision) - 10 (This toy does not provide protection) - 11 (Contains fragrances that may cause allergies) - 12 (For household use only). */
2686
+ /** Parameter's additional feature. 1. Status: context_id = "CONTEXT_STATE" Takes values context_value_id: - CONTEXT_STATE_NEW - New, - CONTEXT_STATE_USED - Used, - CONTEXT_STATE_USED_EXCELLENT - Used - excellent condition - CONTEXT_STATE_USED_VERYGOOD - Used - very good condition - CONTEXT_STATE_USED_CORRECT - Used - good condition - CONTEXT_STATE_USED_ACCEPTABLE - Used - acceptable condition - CONTEXT_STATE_REFURBISHED_EXCELLENT - Refurbished - excellent condition - CONTEXT_STATE_REFURBISHED_VERYGOOD - Refurbished - very good condition - CONTEXT_STATE_REFURBISHED_CORRECT - Refurbished - good condition - CONTEXT_STATE_REFURBISHED_ACCEPTABLE - Refurbished - acceptable - CONTEXT_STATE_NEW_OTHERS - New other (see details) - CONTEXT_STATE_NEW_WITH_DEFECTS - New with defects - CONTEXT_STATE_NEW_OEM - New - OEM - CONTEXT_STATE_NEW_OPEN_BOX - New - open box - CONTEXT_STATE_REFURBISHED_BY_PRODUCER - Renewed by a manufacturer, - CONTEXT_STATE_REFURBISHED_BY_SELLER - Renewed by a seller, - CONTEXT_STATE_FOR_PARTS_OR_BROKEN - In parts or damaged. 2. Product weight in grams: context_id = "CONTEXT_STD_UNIT_WEIGHT" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 3. A product's value in milliliters: context_id = "CONTEXT_STD_UNIT_VOLUME" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 4. Sex: context_id = "CONTEXT_SEX" Takes values context_value_id: - CONTEXT_SEX_MAN - Man, - CONTEXT_SEX_WOMAN - Woman, - CONTEXT_SEX_UNISEX - Unisex. 5. Age group: context_id = "CONTEXT_AGE_GROUP" Takes values context_value_id: - CONTEXT_AGE_GROUP_ADULT - Adults, - CONTEXT_AGE_GROUP_MINOR - Children. 6. Maximum number of products in an order: context_id = "CONTEXT_MAX_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 7. Maximum number of products in a wholesale order: context_id = "CONTEXT_MAX_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 8. Minimal number of products in an order: context_id = "CONTEXT_MIN_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 9. Minimum number of products in a wholesale order: context_id = "CONTEXT_MIN_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 10. Maximal number of a single size in an order: context_id = "CONTEXT_MAX_SIZE_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 11. Maximal number of a single size in a wholesale order: context_id = "CONTEXT_MAX_SIZE_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 12. Minimal number of a single size in an order: context_id = "CONTEXT_MIN_SIZE_QUANTITY_PER_RETAIL_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 13. Minimal number of a single size in a wholesale order: context_id = "CONTEXT_MIN_SIZE_QUANTITY_PER_WHOLESALE_ORDER" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 14. Net weight: context_id = "CONTEXT_WEIGHT_NET" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 15. Color: context_id = "CONTEXT_COLOR" Takes values context_value_id: - Value of additional feature is set automatically basing on the parameter's value. 16. #!TylkoDlaDoroslych!#: context_id = "CONTEXT_ONLY_ADULTS" Takes values context_value_id: - CONTEXT_ONLY_ADULTS_YES - yes, - CONTEXT_ONLY_ADULTS_NO - no. 17. Prescription drug: context_id = "CONTEXT_PRESCRIPTION_MEDICINE" Takes values context_value_id: - CONTEXT_PRESCRIPTION_MEDICINE_YES - yes, - CONTEXT_PRESCRIPTION_MEDICINE_NO - no. 18. Season Rate: context_id = "CONTEXT_SEASON" Takes values context_value_id: - CONTEXT_SEASON_SPRING - Spring, - CONTEXT_SEASON_SUMMER - Summer, - CONTEXT_SEASON_FALL - Autumn, - CONTEXT_SEASON_WINTER - Winter, - CONTEXT_SEASON_SPRING_SUMMER - Spring/Summer, - CONTEXT_SEASON_FALL_WINTER - Autumn/Winter 19. Risk - signal word: context_id = \"CONTEXT_HAZMAT_SIGNAL\" Takes values context_value_id: - CONTEXT_HAZMAT_SIGNAL_DANGER - danger, - CONTEXT_HAZMAT_SIGNAL_WARNING - warnging, - CONTEXT_HAZMAT_SIGNAL_CAUTION - caution, - CONTEXT_HAZMAT_SIGNAL_NOTICE - notice, 20. Risk - warning pictogram context_id = \"CONTEXT_HAZMAT_PICTOGRAM\" Takes values context_value_id: - GHS01, GHS02, GHS03, GHS04, GHS05, GHS06, GHS07, GHS08, GHS09 21. Risk - type of hazard: context_id = \"CONTEXT_HAZMAT_STATEMENT\" Takes values context_value_id: - H200, H201, H202, H203, H204, H205, H220, H221, H222, H223, H224, H225, H226, H228, H240, H241, H242, H250, H251, H252, H260, H261, H270, H271, H272, H280, H281, H290, H300, H301, H302, H304, H310, H311, H312, H314, H315, H317, H318, H319, H330, H331, H332, H334, H335, H336, H340, H341, H350, H351, H360, H361, H362, H370, H371, H372, H373, H400, H410, H411, H412, H413, EUH 001, EUH 014, EUH 018, EUH 019, EUH 044, EUH 029, EUH 031, EUH 032, EUH 066, EUH 070, EUH 071, EUH 201, EUH 201A, EUH 202, EUH 203, EUH 204, EUH 205, EUH 206, EUH 207, EUH 208, EUH 209, EUH 209A, EUH 210, EUH 401 22. Repair score: context_id = \"CONTEXT_REPAIR_SCORE\" Takes values context_value_id: - The value of the additional feature is set automatically based on the parameter's value 23. Safety - information pictogram: context_id = \"CONTEXT_SAFETY_PICTOGRAM\" Takes values context_value_id: - 1 (Not suitable for small children) - 2 (CE mark) 24. Safety - type of warning: context_id = \"CONTEXT_SAFETY_STATEMENT\" Takes values context_value_id: - 1 (Not suitable for children under 3 years) - 2 (Keep out of the reach of children) - 3 (Product contains a button cell or coin battery) - 4 (Use under the direct supervision of adults) - 5 (Required protective gear. Do not use in public traffic) - 6 (Contains toy. Adult supervision recommended) - 7 (To prevent possible injury from entanglement, remove this toy as soon as the child begins to crawl) - 8 (Use only in shallow water under adult supervision) - 9 (Only use under adult supervision) - 10 (This toy does not provide protection) - 11 (Contains fragrances that may cause allergies) - 12 (For household use only). */
2676
2687
  context_id: (context_id: number|string) => this
2677
2688
  /** value of additional feature - Values described in context_id. */
2678
2689
  context_value_id: (context_value_id: number|string) => this
@@ -4034,6 +4045,8 @@ export interface GetReturnsRequest extends PagableGateway<GetReturnsRequest, Get
4034
4045
  stock_id: (value: number|string) => this;
4035
4046
  /** Return a set as its constituent products */
4036
4047
  bundleAsProducts: (value: boolean) => this;
4048
+ /** Search by ID of a shop to which a return is sent. */
4049
+ shop_ids: (value: number|string|number[]|string[]) => this;
4037
4050
  /** Define range of dates and their type */
4038
4051
  dates: (dateFrom: DateLike, dateTo: DateLike, type?: "date_add"|"date_end") => this;
4039
4052
  }
@@ -5182,6 +5195,7 @@ export interface Gateways {
5182
5195
  postPackagesLabels: PostPackagesLabelsRequest,
5183
5196
  postPackages: PostPackagesRequest,
5184
5197
  putPackages: PutPackagesRequest,
5198
+ deletePackages: DeletePackagesRequest,
5185
5199
  searchPackages: SearchPackagesRequest,
5186
5200
  postPaymentsCancel: PostPaymentsCancelRequest,
5187
5201
  postPaymentsCashback: PostPaymentsCashbackRequest,
@@ -5420,6 +5434,6 @@ export interface Gateways {
5420
5434
  }
5421
5435
 
5422
5436
  declare const webhooks: Webhooks;
5423
- declare const defaultExport: (url: string, apiKey: string, version?: number | string) => Gateways;
5437
+ declare const defaultExport: (url: string, apiKey: ApyKeyOrOauthCredentials, version?: number | string) => Gateways;
5424
5438
  export default defaultExport;
5425
5439
  export { ENUMS, RequestParams, utils, webhooks, IaiWebhookHeaders }
package/dist/index.js CHANGED
@@ -22,7 +22,12 @@ function normalizeUrl(input = "") {
22
22
  return parsed.origin;
23
23
  }
24
24
  const idosell = (url, apiKey, version = DEFAULT_VERSION) => {
25
- const auth = { url: normalizeUrl(url), apiKey, version, apikey: apiKey ? apiKey.slice(0, 6) + '*'.repeat(20) : "" };
25
+ let hiddenKey = '*'.repeat(10);
26
+ if (typeof apiKey === 'string')
27
+ hiddenKey = apiKey.slice(0, 6) + '*'.repeat(20);
28
+ else
29
+ hiddenKey = `${apiKey.login}:${apiKey.password.slice(0, 4)}${'*'.repeat(6)}`;
30
+ const auth = { url: normalizeUrl(url), apiKey, version, apikey: hiddenKey };
26
31
  Object.defineProperty(auth, 'apiKey', { enumerable: false });
27
32
  const element = { auth, params: {} };
28
33
  return new Proxy(element, gateProxy);
@@ -0,0 +1,6 @@
1
+ import { paramsProxy } from "../params.js";
2
+ export default (object) => {
3
+ object.gate = { method: 'delete', node: '/packages/packages' };
4
+ object.req = ["packageId"];
5
+ return new Proxy(object, paramsProxy);
6
+ };
@@ -2691,7 +2691,7 @@ export type PutProductsAttachmentsParams = {
2691
2691
  /** @description Attachment document types list. */
2692
2692
  documentTypes?: {
2693
2693
  /** @description Document type. */
2694
- documentType?: "energy_label" | "instruction_with_safety_information" | "user_manual" | "installation_instructions" | "product_card" | "guide" | "software_data_processing" | "hardware_data_processing" | "others";
2694
+ documentType?: "energy_label" | "instruction_with_safety_information" | "user_manual" | "installation_instructions" | "product_card" | "guide" | "software_data_processing" | "hardware_data_processing" | "image_of_packaging" | "label_of_packaging" | "declaration_of_conformity" | "image_of_ukca_ce_mark" | "others";
2695
2695
  /** @description Additional description. */
2696
2696
  description?: string;
2697
2697
  }[];
@@ -7260,4 +7260,44 @@ export type GetWmsLocationsParams = {
7260
7260
  resultsLimit?: number;
7261
7261
  };
7262
7262
 
7263
+ export type GetReturnsParams = {
7264
+ /** @description Search by the order serial number to which a return was added. */
7265
+ order_sn?: number;
7266
+ /** @description Search by return ID. */
7267
+ return_id?: number;
7268
+ /** @description Search by a return shipment number from a customer to the shop . */
7269
+ return_shipping_number?: string;
7270
+ /** @description Date range. */
7271
+ range?: {
7272
+ /** @description Data for date range. */
7273
+ date?: {
7274
+ /** @description Beginning date in YYYY-MM-DD format. */
7275
+ date_begin?: string;
7276
+ /** @description Ending date in YYYY-MM-DD format. */
7277
+ date_end?: string;
7278
+ /** */
7279
+ dates_type?: "date_add" | "date_end";
7280
+ };
7281
+ };
7282
+ /** @description Number of results on page. */
7283
+ results_limit?: number;
7284
+ /** @description Result page number. */
7285
+ results_page?: number;
7286
+ /** @description 1 - Return not handled, 2 - Return accepted, 3 - Return not accepted, 13 - Return canceled by the customer, 14 - Return canceled, 15 - Resend the order, 16 - Abort resending order, 17 - A customer generated a return - it will be delivered personally, 18 - A customer generated a return - it will be sent by the customer. */
7287
+ status?: number;
7288
+ /** @description Search by return ID. */
7289
+ return_ids?: number[];
7290
+ /** @description Search by ID of a stock to which a return is sent. */
7291
+ stock_id?: number;
7292
+ /** @description Return a set as its constituent products */
7293
+ bundleAsProducts?: boolean;
7294
+ /** @description Search by ID of a shop to which a return is sent. */
7295
+ shop_ids?: number[];
7296
+ };
7297
+
7298
+ export type DeletePackagesParams = {
7299
+ /** @description Parcels's ID */
7300
+ packageId: number;
7301
+ };
7302
+
7263
7303
  export { };
package/dist/request.js CHANGED
@@ -165,9 +165,26 @@ export const sendRequest = async (request, options = {}) => {
165
165
  if (!options.skipCheck)
166
166
  processRequired(request);
167
167
  const headers = {
168
- 'X-API-KEY': request.auth.apiKey,
169
168
  Accept: 'application/json'
170
169
  };
170
+ if (typeof request.auth.apiKey === 'string') {
171
+ headers['X-API-KEY'] = request.auth.apiKey;
172
+ }
173
+ else {
174
+ const { login, password, scope } = request.auth.apiKey;
175
+ let token = request.auth.apiKey.token;
176
+ if (!token) {
177
+ const base64 = Buffer.from(`${login}:${password}`).toString('base64');
178
+ const response = await axios.post(`${request.auth.url}/api/authorize/1/authorize/accessToken`, { scope: scope ?? ['admin'] }, { headers: {
179
+ authorization: `Basic ${base64}`,
180
+ } });
181
+ if (response.data.access_token) {
182
+ token = response.data.access_token;
183
+ request.auth.apiKey.token = response.data.access_token;
184
+ }
185
+ }
186
+ headers.authorization = `Bearer ${token}`;
187
+ }
171
188
  request.next = false;
172
189
  const { method, node } = request.gate;
173
190
  let url = `${request.auth.url}/api/admin/v${request.auth.version}${node}`;
@@ -1436,6 +1436,12 @@ export type GetEntriesResponse = {
1436
1436
  titleLinkType: string;
1437
1437
  /** @description Provided URL (for link to specified URL option) */
1438
1438
  link: string;
1439
+ /** @description Meta title of the entry */
1440
+ metaTitle: string;
1441
+ /** @description Meta description of the entry */
1442
+ metaDescription: string;
1443
+ /** @description Meta keywords of the entry */
1444
+ metaKeywords: string;
1439
1445
  };
1440
1446
  };
1441
1447
  };
@@ -2002,7 +2008,7 @@ export type GetOrdersPackagesResponse = {
2002
2008
  /** @description Type */
2003
2009
  type: "radio" | "text" | "select" | "checkbox";
2004
2010
  /** @description Default value for option */
2005
- defaultValue: string;
2011
+ defaultValue: string | string[];
2006
2012
  /** @description Available values for the options */
2007
2013
  options?: {
2008
2014
  /** @description Id */
@@ -2910,7 +2916,7 @@ export type PutProductsAttachmentsResponse = {
2910
2916
  /** @description Attachment document types list. */
2911
2917
  documentTypes?: {
2912
2918
  /** @description Document type. */
2913
- documentType?: "energy_label" | "instruction_with_safety_information" | "user_manual" | "installation_instructions" | "product_card" | "guide" | "others";
2919
+ documentType?: "energy_label" | "instruction_with_safety_information" | "user_manual" | "installation_instructions" | "product_card" | "guide" | "software_data_processing" | "hardware_data_processing" | "image_of_packaging" | "label_of_packaging" | "declaration_of_conformity" | "image_of_ukca_ce_mark" | "others";
2914
2920
  /** @description Additional description. */
2915
2921
  description?: string;
2916
2922
  }[];
@@ -7190,6 +7196,45 @@ export type GetSystemShopsDataResponse = {
7190
7196
  }[];
7191
7197
  /** @description Monitoring address protocol from the main Printer window. */
7192
7198
  typeOfPrinterProtocolAdress: string;
7199
+ /** @description List of inherited settings. */
7200
+ shop_inherit_settings: {
7201
+ /** @description Shop ID */
7202
+ shop_id: number;
7203
+ /** @description Determines whether inheritance is active. */
7204
+ shop_inherit_on: "y" | "n";
7205
+ /** @description Shop ID from which the settings are inherited. */
7206
+ shop_inherit_from: number;
7207
+ /** @description Determines whether inheritance in enabled for offers. */
7208
+ shop_inherit_offer: "y" | "n";
7209
+ /** @description Determines whether inheritance in enabled for navigation descriptions. */
7210
+ shop_inherit_navdescs: "y" | "n";
7211
+ /** @description Determines whether inheritance in enabled for configuration. */
7212
+ shop_inherit_config: "y" | "n";
7213
+ /** @description Determines whether inheritance in enabled for country and locale settings. */
7214
+ shop_inherit_country: "y" | "n";
7215
+ /** @description Determines whether inheritance in enabled for banners. */
7216
+ shop_inherit_banners: "y" | "n";
7217
+ /** @description Determines whether inheritance in enabled for HTML and JS snippets. */
7218
+ shop_inherit_snippets: "y" | "n";
7219
+ /** @description Determines whether inheritance in enabled for toplayer settings. */
7220
+ shop_inherit_toplayers: "y" | "n";
7221
+ /** @description Determines whether inheritance in enabled for site masks. */
7222
+ shop_inherit_masks: "y" | "n";
7223
+ /** @description Determines whether inheritance in enabled for CMS pages. */
7224
+ shop_inherit_cms: "y" | "n";
7225
+ /** @description Determines whether inheritance in enabled for CPA programs. */
7226
+ shop_inherit_cpa: "y" | "n";
7227
+ /** @description Determines whether inheritance in enabled for affiliate programs. */
7228
+ shop_inherit_affiliate: "y" | "n";
7229
+ /** @description Determines whether inheritance in enabled for rebate programs. */
7230
+ shop_inherit_rebates: "y" | "n";
7231
+ /** @description Determines whether inheritance in enabled for prices. */
7232
+ shop_inherit_prices: "y" | "n";
7233
+ /** @description Determines whether inheritance in enabled for sale and shipment documents. */
7234
+ shop_inherit_invoices: "y" | "n";
7235
+ /** @description Determines whether inheritance in enabled for process automation. */
7236
+ shop_inherit_automats: "y" | "n";
7237
+ }[];
7193
7238
  };
7194
7239
 
7195
7240
  export type GetSystemUnitsResponse = {
@@ -9610,4 +9655,9 @@ export type GetProductsAttachmentsGetContentResponse = {
9610
9655
  }[];
9611
9656
  };
9612
9657
 
9658
+ export type DeletePackagesResponse = {
9659
+ /** @description request status */
9660
+ result: string;
9661
+ };
9662
+
9613
9663
  export { };
package/dist/webhooks.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /* eslint-disable no-unused-vars */
2
- import { normalizeIaiRequest, WebhookValidationError } from "./webhooks.normalizer.js";
2
+ import { extractHeaders, normalizeIaiRequest, WebhookValidationError } from "./webhooks.normalizer.js";
3
3
  import { createHmac } from "node:crypto";
4
4
  // ─── Runtime constants ────────────────────────────────────────────────────────
5
5
  export const WEBHOOK_OBJECT_TYPE = {
@@ -106,6 +106,14 @@ export class WebhookChain {
106
106
  }
107
107
  async handle(req) {
108
108
  const { headers, body, rawBody } = await normalizeIaiRequest(req);
109
+ return this.dispatch(headers, body, rawBody);
110
+ }
111
+ async handleRaw({ headers: rawHeaders, rawBody, body }) {
112
+ const headers = extractHeaders(rawHeaders);
113
+ const parsedBody = body ?? JSON.parse(rawBody);
114
+ return this.dispatch(headers, parsedBody, rawBody);
115
+ }
116
+ async dispatch(headers, body, rawBody) {
109
117
  if (this.validator !== null) {
110
118
  let valid = false;
111
119
  try {
@@ -118,7 +126,6 @@ export class WebhookChain {
118
126
  return { matched: false, eventType: null, reason: "validation_failed" };
119
127
  }
120
128
  }
121
- // Validate signature if a key was provided
122
129
  if (this.hmacKey) {
123
130
  const computed = createHmac("sha256", this.hmacKey).update(rawBody).digest("hex");
124
131
  if (computed !== headers.signature) {
@@ -39,7 +39,7 @@ function parseAuthHeader(headers) {
39
39
  }
40
40
  return token;
41
41
  }
42
- function extractHeaders(raw) {
42
+ export function extractHeaders(raw) {
43
43
  return {
44
44
  token: parseAuthHeader(raw),
45
45
  apiVersion: parseIntHeader(raw, "x-iai-api-version"),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "idosell",
3
- "version": "0.4.43",
3
+ "version": "0.4.47",
4
4
  "description": "Idosell 3 REST connector",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/gateways.d.ts",
@@ -0,0 +1,7 @@
1
+ import idosell from "./dist/index.ts"
2
+ import { expect, test } from "vitest"
3
+
4
+ test("deletePackagesPackageId", () => {
5
+ const params = idosell().deletePackages.packageId(242).checkParams();
6
+ expect(params).toEqual({"packageId":242});
7
+ })
@@ -0,0 +1,158 @@
1
+ // vitest tests for the webhook dispatcher
2
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
3
+ import { createHmac } from 'node:crypto';
4
+ import { webhooks } from '../dist/webhooks';
5
+ import { normalizeIaiRequest } from '../dist/webhooks.normalizer';
6
+
7
+ const API_VERSION = '8';
8
+ const SIGNATURE_KEY = 'secret-hmac-key';
9
+ const TOKEN = 'authentication-bearer-token'
10
+
11
+ // Helper to build a Request with appropriate headers and body
12
+ function buildRequest({
13
+ body,
14
+ eventType = 'productUpdated',
15
+ objectType = 'product',
16
+ }: {
17
+ body: unknown;
18
+ eventType?: string;
19
+ objectType?: string;
20
+ }) {
21
+ const rawBody = JSON.stringify(body);
22
+ const signature = createHmac('sha256', SIGNATURE_KEY).update(rawBody).digest('hex');
23
+ const headers = new Headers({
24
+ 'Content-Type': 'application/json',
25
+ 'x-iai-api-version': API_VERSION,
26
+ 'x-iai-event-time': new Date().toISOString(),
27
+ 'x-iai-event-type': eventType,
28
+ 'x-iai-event-uid': 'uid-123',
29
+ 'x-iai-object-type': objectType,
30
+ 'x-iai-panel-id': '1',
31
+ 'x-iai-signature': signature,
32
+ 'x-iai-webhook-time': new Date().toISOString(),
33
+ 'authorization': `Bearer ${TOKEN}`,
34
+ });
35
+ return new Request('https://api.example.com/webhook', {
36
+ method: 'POST',
37
+ headers,
38
+ body: rawBody,
39
+ });
40
+ }
41
+
42
+ describe('WebhookChain dispatcher', () => {
43
+ let mockHandler: ReturnType<typeof vi.fn>;
44
+
45
+ beforeEach(() => {
46
+ mockHandler = vi.fn();
47
+ });
48
+
49
+ it('routes a matching event to the registered handler', async () => {
50
+ const requestBody = {
51
+ results: [{ productDisplayedCode: 'ABC123' }],
52
+ };
53
+ const req = buildRequest({ body: requestBody });
54
+
55
+ const chain = webhooks
56
+ .validateHeaders((h) => h.token === TOKEN)
57
+ .validateSignature(SIGNATURE_KEY)
58
+ .on('productUpdated', mockHandler);
59
+
60
+ const result = await chain.handle(req);
61
+
62
+ expect(result).toEqual({ matched: true, eventType: 'productUpdated' });
63
+ expect(mockHandler).toHaveBeenCalledTimes(1);
64
+ const ctx = mockHandler.mock.calls[0][0];
65
+ expect(ctx.body).toEqual(requestBody);
66
+ expect(ctx.headers.eventType).toBe('productUpdated');
67
+ expect(ctx.headers.objectType).toBe('product');
68
+ });
69
+
70
+ it('returns unmatched when no handler is registered for the event', async () => {
71
+ const requestBody = { foo: 'bar' };
72
+ const req = buildRequest({ body: requestBody, eventType: 'orderCreated', objectType: 'order' });
73
+
74
+ const chain = webhooks
75
+ .validateHeaders((h) => h.token === TOKEN)
76
+ .validateSignature(SIGNATURE_KEY);
77
+
78
+ const result = await chain.handle(req);
79
+ expect(result).toEqual({ matched: false, eventType: 'orderCreated' });
80
+ expect(mockHandler).not.toHaveBeenCalled();
81
+ });
82
+
83
+ it('fails validateHeaders when token mismatched', async () => {
84
+ const requestBody = { foo: 'bar' };
85
+ const req = buildRequest({ body: requestBody });
86
+ const chain = webhooks
87
+ .validateHeaders(() => false)
88
+ .validateSignature(SIGNATURE_KEY)
89
+ .on('productUpdated', mockHandler);
90
+ const result = await chain.handle(req);
91
+ expect(result).toEqual({ matched: false, eventType: null, reason: 'validation_failed' });
92
+ });
93
+
94
+ it('fails validateSignature with wrong key', async () => {
95
+ const requestBody = { foo: 'bar' };
96
+ const req = buildRequest({ body: requestBody });
97
+ const chain = webhooks
98
+ .validateHeaders((h) => h.token === TOKEN)
99
+ .validateSignature('wrong-key')
100
+ .on('productUpdated', mockHandler);
101
+ await expect(chain.handle(req)).rejects.toThrow('Invalid webhook signature');
102
+ });
103
+
104
+ it('registers handler for object type "order" and matches order events', async () => {
105
+ const requestBody = { foo: 'bar' };
106
+ const req = buildRequest({ body: requestBody, eventType: 'orderCreated', objectType: 'order' });
107
+ const chain = webhooks
108
+ .validateHeaders((h) => h.token === TOKEN)
109
+ .validateSignature(SIGNATURE_KEY)
110
+ .on('order', mockHandler);
111
+ await expect(chain.handle(req)).resolves.not.toThrow();
112
+ });
113
+
114
+ it('normalizes request and verifies header shape', async () => {
115
+ const requestBody = { foo: 'bar' };
116
+ const req = buildRequest({ body: requestBody });
117
+ const { headers } = await normalizeIaiRequest(req);
118
+ // Basic shape checks
119
+ expect(headers).toMatchObject({
120
+ token: TOKEN,
121
+ apiVersion: Number(API_VERSION),
122
+ eventType: 'productUpdated',
123
+ objectType: 'product',
124
+ panelId: 1,
125
+ signature: expect.any(String),
126
+ });
127
+ // Type checks for dates
128
+ expect(headers.eventTime).toBeInstanceOf(Date);
129
+ expect(headers.webhookTime).toBeInstanceOf(Date);
130
+ });
131
+
132
+ it('handleRaw processes raw webhook input correctly', async () => {
133
+ const requestBody = { foo: 'bar' };
134
+ const rawBody = JSON.stringify(requestBody);
135
+ const rawHeaders = {
136
+ 'content-type': 'application/json',
137
+ 'x-iai-api-version': API_VERSION,
138
+ 'x-iai-event-time': new Date().toISOString(),
139
+ 'x-iai-event-type': 'productUpdated',
140
+ 'x-iai-event-uid': 'uid-123',
141
+ 'x-iai-object-type': 'product',
142
+ 'x-iai-panel-id': '1',
143
+ 'x-iai-signature': createHmac('sha256', SIGNATURE_KEY).update(rawBody).digest('hex'),
144
+ 'x-iai-webhook-time': new Date().toISOString(),
145
+ 'authorization': `Bearer ${TOKEN}`,
146
+ } as Record<string, string>;
147
+ const chain = webhooks
148
+ .validateHeaders((h) => h.token === TOKEN)
149
+ .validateSignature(SIGNATURE_KEY)
150
+ .on('productUpdated', mockHandler);
151
+ const result = await chain.handleRaw({ headers: rawHeaders, rawBody, body: requestBody });
152
+ expect(result).toEqual({ matched: true, eventType: 'productUpdated' });
153
+ expect(mockHandler).toHaveBeenCalledTimes(1);
154
+ const ctx = mockHandler.mock.calls[0][0];
155
+ expect(ctx.body).toEqual(requestBody);
156
+ expect(ctx.headers.objectType).toBe('product');
157
+ });
158
+ });