pathao-merchant-sdk 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -6,44 +6,120 @@ var PathaoApiService = class {
6
6
  this.accessToken = null;
7
7
  this.refreshToken = null;
8
8
  this.tokenExpiry = null;
9
+ this.isAuthenticating = false;
10
+ this.authPromise = null;
11
+ this.requestQueue = [];
12
+ this.circuitBreaker = {
13
+ failures: 0,
14
+ lastFailureTime: 0,
15
+ threshold: 5,
16
+ timeout: 6e4,
17
+ // 1 minute
18
+ isOpen: false
19
+ };
9
20
  this.config = {
10
- baseURL: "https://api-hermes.pathao.com",
11
- timeout: 3e4,
12
- ...config
21
+ baseURL: config.baseURL || process.env.PATHAO_BASE_URL || "",
22
+ timeout: config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10),
23
+ clientId: config.clientId || process.env.PATHAO_CLIENT_ID || "",
24
+ clientSecret: config.clientSecret || process.env.PATHAO_CLIENT_SECRET || "",
25
+ username: config.username || process.env.PATHAO_USERNAME || "",
26
+ password: config.password || process.env.PATHAO_PASSWORD || ""
13
27
  };
14
28
  this.pathaoClient = axios.create({
15
- baseURL: this.config.baseURL || "https://api-hermes.pathao.com",
16
- timeout: this.config.timeout || 3e4,
29
+ baseURL: this.config.baseURL || process.env.PATHAO_BASE_URL || "",
30
+ timeout: this.config.timeout || parseInt(process.env.PATHAO_TIMEOUT || "30000", 10),
17
31
  headers: {
18
32
  "Content-Type": "application/json",
19
33
  "Accept": "application/json"
20
34
  }
21
35
  });
36
+ if (!this.config.baseURL) {
37
+ throw new Error("Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable");
38
+ }
22
39
  if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {
23
- throw new Error("Pathao API credentials are required: clientId, clientSecret, username, password");
40
+ throw new Error("Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)");
24
41
  }
25
42
  this.pathaoClient.interceptors.request.use(async (config2) => {
43
+ if (config2.url?.includes("/issue-token")) {
44
+ return config2;
45
+ }
26
46
  await this.ensureAuthenticated();
27
47
  if (this.accessToken) {
28
48
  config2.headers.Authorization = `Bearer ${this.accessToken}`;
29
49
  }
30
50
  return config2;
31
51
  });
52
+ this.pathaoClient.interceptors.response.use(
53
+ (response) => {
54
+ this.circuitBreaker.failures = 0;
55
+ this.circuitBreaker.isOpen = false;
56
+ return response;
57
+ },
58
+ async (error) => {
59
+ if (error.response?.status === 401) {
60
+ this.accessToken = null;
61
+ this.refreshToken = null;
62
+ this.tokenExpiry = null;
63
+ if (error.config && !error.config._retry) {
64
+ error.config._retry = true;
65
+ await this.ensureAuthenticated();
66
+ if (this.accessToken) {
67
+ error.config.headers.Authorization = `Bearer ${this.accessToken}`;
68
+ }
69
+ return this.pathaoClient.request(error.config);
70
+ }
71
+ }
72
+ this.handleCircuitBreaker();
73
+ return Promise.reject(error);
74
+ }
75
+ );
32
76
  }
33
77
  async ensureAuthenticated() {
78
+ if (this.circuitBreaker.isOpen) {
79
+ if (Date.now() - this.circuitBreaker.lastFailureTime > this.circuitBreaker.timeout) {
80
+ this.circuitBreaker.isOpen = false;
81
+ this.circuitBreaker.failures = 0;
82
+ } else {
83
+ throw new Error("Circuit breaker is open. Too many authentication failures.");
84
+ }
85
+ }
34
86
  if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {
35
87
  return;
36
88
  }
89
+ if (this.isAuthenticating && this.authPromise) {
90
+ return this.authPromise;
91
+ }
92
+ this.isAuthenticating = true;
93
+ this.authPromise = this.performAuthentication();
94
+ try {
95
+ await this.authPromise;
96
+ } finally {
97
+ this.isAuthenticating = false;
98
+ this.authPromise = null;
99
+ this.processRequestQueue();
100
+ }
101
+ }
102
+ async performAuthentication() {
37
103
  if (this.refreshToken) {
38
104
  try {
39
105
  await this.refreshAccessToken();
40
106
  return;
41
107
  } catch (error) {
42
- console.warn("Token refresh failed, attempting fresh authentication");
108
+ this.refreshToken = null;
43
109
  }
44
110
  }
45
111
  await this.authenticate();
46
112
  }
113
+ processRequestQueue() {
114
+ const queue = [...this.requestQueue];
115
+ this.requestQueue = [];
116
+ queue.forEach(({ resolve }) => {
117
+ try {
118
+ resolve();
119
+ } catch (error) {
120
+ }
121
+ });
122
+ }
47
123
  async authenticate() {
48
124
  try {
49
125
  const response = await this.pathaoClient.post("/aladdin/api/v1/issue-token", {
@@ -56,9 +132,10 @@ var PathaoApiService = class {
56
132
  this.accessToken = response.data.access_token;
57
133
  this.refreshToken = response.data.refresh_token;
58
134
  this.tokenExpiry = Date.now() + response.data.expires_in * 1e3 - 6e4;
59
- console.log("Pathao authentication successful");
135
+ this.circuitBreaker.failures = 0;
136
+ this.circuitBreaker.isOpen = false;
60
137
  } catch (error) {
61
- console.error("Pathao authentication failed:", error);
138
+ this.handleCircuitBreaker();
62
139
  throw new Error(`Authentication failed: ${this.getErrorMessage(error)}`);
63
140
  }
64
141
  }
@@ -76,9 +153,10 @@ var PathaoApiService = class {
76
153
  this.accessToken = response.data.access_token;
77
154
  this.refreshToken = response.data.refresh_token;
78
155
  this.tokenExpiry = Date.now() + response.data.expires_in * 1e3 - 6e4;
79
- console.log("Pathao token refresh successful");
156
+ this.circuitBreaker.failures = 0;
157
+ this.circuitBreaker.isOpen = false;
80
158
  } catch (error) {
81
- console.error("Pathao token refresh failed:", error);
159
+ this.handleCircuitBreaker();
82
160
  throw new Error(`Token refresh failed: ${this.getErrorMessage(error)}`);
83
161
  }
84
162
  }
@@ -92,33 +170,19 @@ var PathaoApiService = class {
92
170
  }
93
171
  return error.message || "Unknown error";
94
172
  }
173
+ handleCircuitBreaker() {
174
+ this.circuitBreaker.failures++;
175
+ this.circuitBreaker.lastFailureTime = Date.now();
176
+ if (this.circuitBreaker.failures >= this.circuitBreaker.threshold) {
177
+ this.circuitBreaker.isOpen = true;
178
+ }
179
+ }
95
180
  // Official Pathao API: Create Order
96
181
  async createOrder(orderData) {
97
182
  try {
98
- console.log("Creating Pathao order:", {
99
- store_id: orderData.store_id,
100
- merchant_order_id: orderData.merchant_order_id,
101
- recipient_name: orderData.recipient_name,
102
- recipient_phone: orderData.recipient_phone,
103
- delivery_type: orderData.delivery_type,
104
- item_type: orderData.item_type,
105
- item_weight: orderData.item_weight,
106
- amount_to_collect: orderData.amount_to_collect
107
- });
108
183
  const response = await this.pathaoClient.post("/aladdin/api/v1/orders", orderData);
109
- console.log("Pathao order created successfully:", {
110
- consignment_id: response.data.data?.consignment_id,
111
- invoice_id: response.data.data?.invoice_id,
112
- status: response.data.data?.status
113
- });
114
184
  return response.data;
115
185
  } catch (error) {
116
- console.error("Pathao order creation failed:", {
117
- error: error.message,
118
- response: error.response?.data,
119
- status: error.response?.status,
120
- orderData
121
- });
122
186
  const errorMessage = this.getErrorMessage(error);
123
187
  throw new Error(`Failed to create Pathao order: ${errorMessage}`);
124
188
  }
@@ -126,27 +190,9 @@ var PathaoApiService = class {
126
190
  // Official Pathao API: Create Store
127
191
  async createStore(storeData) {
128
192
  try {
129
- console.log("Creating Pathao store:", {
130
- name: storeData.name,
131
- contact_name: storeData.contact_name,
132
- city_id: storeData.city_id,
133
- zone_id: storeData.zone_id,
134
- area_id: storeData.area_id
135
- });
136
193
  const response = await this.pathaoClient.post("/aladdin/api/v1/stores", storeData);
137
- console.log("Pathao store created successfully:", {
138
- store_id: response.data.data?.store_id,
139
- name: response.data.data?.name,
140
- status: response.data.data?.status
141
- });
142
194
  return response.data;
143
195
  } catch (error) {
144
- console.error("Pathao store creation failed:", {
145
- error: error.message,
146
- response: error.response?.data,
147
- status: error.response?.status,
148
- storeData
149
- });
150
196
  const errorMessage = this.getErrorMessage(error);
151
197
  throw new Error(`Failed to create Pathao store: ${errorMessage}`);
152
198
  }
@@ -155,9 +201,8 @@ var PathaoApiService = class {
155
201
  async getStores() {
156
202
  try {
157
203
  const response = await this.pathaoClient.get("/aladdin/api/v1/stores");
158
- return response.data.data || [];
204
+ return response.data;
159
205
  } catch (error) {
160
- console.error("Failed to fetch Pathao stores:", error);
161
206
  const errorMessage = this.getErrorMessage(error);
162
207
  throw new Error(`Failed to fetch Pathao stores: ${errorMessage}`);
163
208
  }
@@ -165,29 +210,9 @@ var PathaoApiService = class {
165
210
  // Official Pathao API: Calculate Price
166
211
  async calculatePrice(priceData) {
167
212
  try {
168
- console.log("Calculating Pathao price:", {
169
- store_id: priceData.store_id,
170
- item_type: priceData.item_type,
171
- item_weight: priceData.item_weight,
172
- delivery_type: priceData.delivery_type,
173
- recipient_city: priceData.recipient_city,
174
- recipient_zone: priceData.recipient_zone,
175
- recipient_area: priceData.recipient_area
176
- });
177
- const response = await this.pathaoClient.post("/aladdin/api/v1/merchant/price-check", priceData);
178
- console.log("Pathao price calculated:", {
179
- delivery_charge: response.data.data?.delivery_charge,
180
- cod_charge: response.data.data?.cod_charge,
181
- total_charge: response.data.data?.total_charge
182
- });
213
+ const response = await this.pathaoClient.post("/aladdin/api/v1/merchant/price-plan", priceData);
183
214
  return response.data;
184
215
  } catch (error) {
185
- console.error("Pathao price calculation failed:", {
186
- error: error.message,
187
- response: error.response?.data,
188
- status: error.response?.status,
189
- priceData
190
- });
191
216
  const errorMessage = this.getErrorMessage(error);
192
217
  throw new Error(`Failed to calculate Pathao price: ${errorMessage}`);
193
218
  }
@@ -195,21 +220,29 @@ var PathaoApiService = class {
195
220
  // Official Pathao API: Get Cities
196
221
  async getCities() {
197
222
  try {
198
- const response = await this.pathaoClient.get("/aladdin/api/v1/cities");
223
+ const response = await this.pathaoClient.get("/aladdin/api/v1/city-list");
199
224
  return response.data;
200
225
  } catch (error) {
201
- console.error("Failed to fetch Pathao cities:", error);
202
226
  const errorMessage = this.getErrorMessage(error);
203
227
  throw new Error(`Failed to fetch Pathao cities: ${errorMessage}`);
204
228
  }
205
229
  }
206
- // Official Pathao API: Get Areas
207
- async getAreas() {
230
+ // Official Pathao API: Get Zones for a City
231
+ async getZones(cityId) {
232
+ try {
233
+ const response = await this.pathaoClient.get(`/aladdin/api/v1/cities/${cityId}/zone-list`);
234
+ return response.data;
235
+ } catch (error) {
236
+ const errorMessage = this.getErrorMessage(error);
237
+ throw new Error(`Failed to fetch Pathao zones: ${errorMessage}`);
238
+ }
239
+ }
240
+ // Official Pathao API: Get Areas for a Zone
241
+ async getAreas(zoneId) {
208
242
  try {
209
- const response = await this.pathaoClient.get("/aladdin/api/v1/areas");
243
+ const response = await this.pathaoClient.get(`/aladdin/api/v1/zones/${zoneId}/area-list`);
210
244
  return response.data;
211
245
  } catch (error) {
212
- console.error("Failed to fetch Pathao areas:", error);
213
246
  const errorMessage = this.getErrorMessage(error);
214
247
  throw new Error(`Failed to fetch Pathao areas: ${errorMessage}`);
215
248
  }
@@ -217,14 +250,23 @@ var PathaoApiService = class {
217
250
  // Official Pathao API: Get Order Status
218
251
  async getOrderStatus(consignmentId) {
219
252
  try {
220
- const response = await this.pathaoClient.get(`/aladdin/api/v1/orders/${consignmentId}`);
253
+ const response = await this.pathaoClient.get(`/aladdin/api/v1/orders/${consignmentId}/info`);
221
254
  return response.data;
222
255
  } catch (error) {
223
- console.error("Failed to fetch Pathao order status:", error);
224
256
  const errorMessage = this.getErrorMessage(error);
225
257
  throw new Error(`Failed to fetch Pathao order status: ${errorMessage}`);
226
258
  }
227
259
  }
260
+ // Official Pathao API: Create Bulk Order
261
+ async createBulkOrder(orders) {
262
+ try {
263
+ const response = await this.pathaoClient.post("/aladdin/api/v1/orders/bulk", { orders });
264
+ return response.data;
265
+ } catch (error) {
266
+ const errorMessage = this.getErrorMessage(error);
267
+ throw new Error(`Failed to create bulk Pathao orders: ${errorMessage}`);
268
+ }
269
+ }
228
270
  // Helper method to validate phone number
229
271
  static validatePhoneNumber(phone) {
230
272
  const cleanPhone = phone.replace(/\D/g, "");
@@ -252,6 +294,42 @@ var PathaoApiService = class {
252
294
  const trimmed = name.trim();
253
295
  return trimmed.length >= 3 && trimmed.length <= 100;
254
296
  }
297
+ // Helper method to validate store name
298
+ static validateStoreName(name) {
299
+ const trimmed = name.trim();
300
+ return trimmed.length >= 3 && trimmed.length <= 50;
301
+ }
302
+ // Helper method to validate contact name
303
+ static validateContactName(name) {
304
+ const trimmed = name.trim();
305
+ return trimmed.length >= 3 && trimmed.length <= 50;
306
+ }
307
+ // Helper method to validate contact number
308
+ static validateContactNumber(phone) {
309
+ const cleanPhone = phone.replace(/\D/g, "");
310
+ return cleanPhone.length === 11;
311
+ }
312
+ // Helper method to validate store address
313
+ static validateStoreAddress(address) {
314
+ const trimmed = address.trim();
315
+ return trimmed.length >= 15 && trimmed.length <= 120;
316
+ }
317
+ // Method to clear authentication state (useful for testing)
318
+ clearAuth() {
319
+ this.accessToken = null;
320
+ this.refreshToken = null;
321
+ this.tokenExpiry = null;
322
+ this.isAuthenticating = false;
323
+ this.authPromise = null;
324
+ this.requestQueue = [];
325
+ this.circuitBreaker = {
326
+ failures: 0,
327
+ lastFailureTime: 0,
328
+ threshold: 5,
329
+ timeout: 6e4,
330
+ isOpen: false
331
+ };
332
+ }
255
333
  };
256
334
 
257
335
  // src/types.ts
@@ -265,12 +343,7 @@ var ItemType = /* @__PURE__ */ ((ItemType2) => {
265
343
  ItemType2[ItemType2["PARCEL"] = 2] = "PARCEL";
266
344
  return ItemType2;
267
345
  })(ItemType || {});
268
- var StoreType = /* @__PURE__ */ ((StoreType2) => {
269
- StoreType2[StoreType2["PICKUP_POINT"] = 1] = "PICKUP_POINT";
270
- StoreType2[StoreType2["SERVICE_POINT"] = 2] = "SERVICE_POINT";
271
- return StoreType2;
272
- })(StoreType || {});
273
346
 
274
- export { DeliveryType, ItemType, PathaoApiService, StoreType };
347
+ export { DeliveryType, ItemType, PathaoApiService };
275
348
  //# sourceMappingURL=index.mjs.map
276
349
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pathao-api.ts","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AAA,MAAM,OAAA,GAAU,KAAK,IAAA,EAAK;AAC1B,IAAA,OAAO,OAAA,CAAQ,MAAA,IAAU,CAAA,IAAK,OAAA,CAAQ,MAAA,IAAU,GAAA;AAAA,EAClD;AACF;;;ACnHO,IAAK,YAAA,qBAAAC,aAAAA,KAAL;AACL,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,YAAS,EAAA,CAAA,GAAT,QAAA;AACA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAFU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAML,IAAK,QAAA,qBAAAC,SAAAA,KAAL;AACL,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,cAAW,CAAA,CAAA,GAAX,UAAA;AACA,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,YAAS,CAAA,CAAA,GAAT,QAAA;AAFU,EAAA,OAAAA,SAAAA;AAAA,CAAA,EAAA,QAAA,IAAA,EAAA;AAML,IAAK,SAAA,qBAAAC,UAAAA,KAAL;AACL,EAAAA,UAAAA,CAAAA,UAAAA,CAAA,kBAAe,CAAA,CAAA,GAAf,cAAA;AACA,EAAAA,UAAAA,CAAAA,UAAAA,CAAA,mBAAgB,CAAA,CAAA,GAAhB,eAAA;AAFU,EAAA,OAAAA,UAAAA;AAAA,CAAA,EAAA,SAAA,IAAA,EAAA","file":"index.mjs","sourcesContent":["/**\n * Pathao Merchant API Service (Unofficial SDK)\n * \n * This is an unofficial SDK for the Pathao Merchant API.\n * \n * API Details (based on public documentation):\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - Live URL: https://api-hermes.pathao.com\n * - All endpoints use /aladdin/api/v1/ prefix\n * \n * Features implemented:\n * - Token-based authentication with refresh token support\n * - Store management (create, list stores)\n * - Order creation (single and bulk)\n * - Order tracking and status\n * - Dynamic price calculation\n * - City, zone, and area management\n */\n\nimport axios, { AxiosError, AxiosInstance } from 'axios';\nimport {\n PathaoAreaResponse,\n PathaoAuthResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStoreRequest,\n PathaoStoreResponse,\n} from './types';\n\nexport class PathaoApiService {\n private pathaoClient: AxiosInstance;\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private tokenExpiry: number | null = null;\n private config: PathaoConfig;\n\n constructor(config: PathaoConfig) {\n this.config = {\n baseURL: 'https://api-hermes.pathao.com',\n timeout: 30000,\n ...config,\n };\n\n this.pathaoClient = axios.create({\n baseURL: this.config.baseURL || 'https://api-hermes.pathao.com',\n timeout: this.config.timeout || 30000,\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n });\n\n // Validate required credentials\n if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {\n throw new Error('Pathao API credentials are required: clientId, clientSecret, username, password');\n }\n\n // Add request interceptor for authentication\n this.pathaoClient.interceptors.request.use(async (config) => {\n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return config;\n });\n }\n\n private async ensureAuthenticated(): Promise<void> {\n if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {\n return; // Token is still valid\n }\n\n if (this.refreshToken) {\n try {\n await this.refreshAccessToken();\n return;\n } catch (error) {\n console.warn('Token refresh failed, attempting fresh authentication');\n }\n }\n\n await this.authenticate();\n }\n\n private async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n username: this.config.username,\n password: this.config.password,\n grant_type: 'password',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n console.log('Pathao authentication successful');\n } catch (error) {\n console.error('Pathao authentication failed:', error);\n throw new Error(`Authentication failed: ${this.getErrorMessage(error)}`);\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n if (!this.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n refresh_token: this.refreshToken,\n grant_type: 'refresh_token',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n console.log('Pathao token refresh successful');\n } catch (error) {\n console.error('Pathao token refresh failed:', error);\n throw new Error(`Token refresh failed: ${this.getErrorMessage(error)}`);\n }\n }\n\n private getErrorMessage(error: any): string {\n if (error instanceof AxiosError) {\n const pathaoError = error.response?.data as PathaoError;\n if (pathaoError?.message) {\n return pathaoError.message;\n }\n return error.message;\n }\n return error.message || 'Unknown error';\n }\n\n // Official Pathao API: Create Order\n async createOrder(orderData: PathaoOrderRequest): Promise<PathaoOrderResponse> {\n try {\n console.log('Creating Pathao order:', {\n store_id: orderData.store_id,\n merchant_order_id: orderData.merchant_order_id,\n recipient_name: orderData.recipient_name,\n recipient_phone: orderData.recipient_phone,\n delivery_type: orderData.delivery_type,\n item_type: orderData.item_type,\n item_weight: orderData.item_weight,\n amount_to_collect: orderData.amount_to_collect,\n });\n \n const response = await this.pathaoClient.post<PathaoOrderResponse>('/aladdin/api/v1/orders', orderData);\n \n console.log('Pathao order created successfully:', {\n consignment_id: response.data.data?.consignment_id,\n invoice_id: response.data.data?.invoice_id,\n status: response.data.data?.status,\n });\n \n return response.data;\n } catch (error: any) {\n console.error('Pathao order creation failed:', {\n error: error.message,\n response: error.response?.data,\n status: error.response?.status,\n orderData,\n });\n \n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to create Pathao order: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(storeData: PathaoStoreRequest): Promise<PathaoStoreResponse> {\n try {\n console.log('Creating Pathao store:', {\n name: storeData.name,\n contact_name: storeData.contact_name,\n city_id: storeData.city_id,\n zone_id: storeData.zone_id,\n area_id: storeData.area_id,\n });\n \n const response = await this.pathaoClient.post<PathaoStoreResponse>('/aladdin/api/v1/stores', storeData);\n \n console.log('Pathao store created successfully:', {\n store_id: response.data.data?.store_id,\n name: response.data.data?.name,\n status: response.data.data?.status,\n });\n \n return response.data;\n } catch (error: any) {\n console.error('Pathao store creation failed:', {\n error: error.message,\n response: error.response?.data,\n status: error.response?.status,\n storeData,\n });\n \n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to create Pathao store: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(): Promise<PathaoStoreResponse[]> {\n try {\n const response = await this.pathaoClient.get<{ data: PathaoStoreResponse[] }>('/aladdin/api/v1/stores');\n return response.data.data || [];\n } catch (error: any) {\n console.error('Failed to fetch Pathao stores:', error);\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao stores: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(priceData: PathaoPriceRequest): Promise<PathaoPriceResponse> {\n try {\n console.log('Calculating Pathao price:', {\n store_id: priceData.store_id,\n item_type: priceData.item_type,\n item_weight: priceData.item_weight,\n delivery_type: priceData.delivery_type,\n recipient_city: priceData.recipient_city,\n recipient_zone: priceData.recipient_zone,\n recipient_area: priceData.recipient_area,\n });\n \n const response = await this.pathaoClient.post<PathaoPriceResponse>('/aladdin/api/v1/merchant/price-check', priceData);\n \n console.log('Pathao price calculated:', {\n delivery_charge: response.data.data?.delivery_charge,\n cod_charge: response.data.data?.cod_charge,\n total_charge: response.data.data?.total_charge,\n });\n \n return response.data;\n } catch (error: any) {\n console.error('Pathao price calculation failed:', {\n error: error.message,\n response: error.response?.data,\n status: error.response?.status,\n priceData,\n });\n \n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to calculate Pathao price: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>('/aladdin/api/v1/cities');\n return response.data;\n } catch (error: any) {\n console.error('Failed to fetch Pathao cities:', error);\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao cities: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Areas\n async getAreas(): Promise<PathaoAreaResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoAreaResponse>('/aladdin/api/v1/areas');\n return response.data;\n } catch (error: any) {\n console.error('Failed to fetch Pathao areas:', error);\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao areas: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(consignmentId: string): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(`/aladdin/api/v1/orders/${consignmentId}`);\n return response.data;\n } catch (error: any) {\n console.error('Failed to fetch Pathao order status:', error);\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao order status: ${errorMessage}`);\n }\n }\n\n // Helper method to validate phone number\n static validatePhoneNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, '');\n return cleanPhone.length === 11 && cleanPhone.startsWith('01');\n }\n\n // Helper method to format phone number\n static formatPhoneNumber(phone: string): string {\n const cleanPhone = phone.replace(/\\D/g, '');\n if (cleanPhone.length === 11 && cleanPhone.startsWith('01')) {\n return cleanPhone;\n }\n throw new Error('Invalid phone number format. Must be 11 digits starting with 01');\n }\n\n // Helper method to validate address\n static validateAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 10 && trimmed.length <= 220;\n }\n\n // Helper method to validate weight\n static validateWeight(weight: number): boolean {\n return weight >= 0.5 && weight <= 10;\n }\n\n // Helper method to validate recipient name\n static validateRecipientName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 100;\n }\n}\n","/**\n * Pathao Courier API Types\n * \n * Official API Details:\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - Live URL: https://api-hermes.pathao.com\n * - All endpoints use /aladdin/api/v1/ prefix\n */\n\n// Official Pathao API Authentication Response\nexport interface PathaoAuthResponse {\n token_type: string;\n expires_in: number;\n access_token: string;\n refresh_token: string;\n}\n\n// Official Pathao Order Creation Request\nexport interface PathaoOrderRequest {\n store_id: number;\n merchant_order_id?: string; // Optional - Your order tracking ID\n recipient_name: string; // Required - 3-100 characters\n recipient_phone: string; // Required - 11 characters\n recipient_secondary_phone?: string; // Optional - 11 characters\n recipient_address: string; // Required - 10-220 characters\n recipient_city?: number; // Optional - Auto-detected if not provided\n recipient_zone?: number; // Optional - Auto-detected if not provided\n recipient_area?: number; // Optional - Auto-detected if not provided\n delivery_type: number; // Required - 48 (Normal), 12 (On Demand)\n item_type: number; // Required - 1 (Document), 2 (Parcel)\n special_instruction?: string; // Optional\n item_quantity: number; // Required\n item_weight: number; // Required - 0.5-10 kg\n item_description?: string; // Optional\n amount_to_collect: number; // Required - COD amount (0 for non-COD)\n}\n\n// Official Pathao Store Creation Request\nexport interface PathaoStoreRequest {\n name: string;\n contact_name: string;\n contact_number: string;\n address: string;\n city_id: number;\n zone_id: number;\n area_id: number;\n store_type: number; // 1 (Pickup Point), 2 (Service Point)\n}\n\n// Official Pathao Order Response\nexport interface PathaoOrderResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n invoice_id: string;\n merchant_order_id: string;\n store_id: number;\n recipient_name: string;\n recipient_phone: string;\n recipient_address: string;\n recipient_city: string;\n recipient_zone: string;\n recipient_area: string;\n delivery_type: string;\n item_type: string;\n item_quantity: number;\n item_weight: number;\n item_description: string;\n amount_to_collect: number;\n special_instruction: string;\n status: string;\n created_at: string;\n updated_at: string;\n };\n}\n\n// Official Pathao Store Response\nexport interface PathaoStoreResponse {\n type: string;\n code: number;\n message: string;\n data: {\n store_id: number;\n name: string;\n contact_name: string;\n contact_number: string;\n address: string;\n city_id: number;\n zone_id: number;\n area_id: number;\n store_type: number;\n status: string;\n created_at: string;\n updated_at: string;\n };\n}\n\n// Official Pathao Price Calculation Request\nexport interface PathaoPriceRequest {\n store_id: number;\n item_type: number;\n item_weight: number;\n delivery_type: number;\n recipient_city: number;\n recipient_zone: number;\n recipient_area: number;\n}\n\n// Official Pathao Price Response\nexport interface PathaoPriceResponse {\n type: string;\n code: number;\n message: string;\n data: {\n store_id: number;\n item_type: string;\n item_weight: number;\n delivery_type: string;\n recipient_city: string;\n recipient_zone: string;\n recipient_area: string;\n delivery_charge: number;\n cod_charge: number;\n total_charge: number;\n currency: string;\n };\n}\n\n// Official Pathao City Response\nexport interface PathaoCityResponse {\n type: string;\n code: number;\n message: string;\n data: Array<{\n city_id: number;\n city_name: string;\n zone_list: Array<{\n zone_id: number;\n zone_name: string;\n area_list: Array<{\n area_id: number;\n area_name: string;\n }>;\n }>;\n }>;\n}\n\n// Official Pathao Order Status Response\nexport interface PathaoOrderStatusResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n invoice_id: string;\n merchant_order_id: string;\n store_id: number;\n recipient_name: string;\n recipient_phone: string;\n recipient_address: string;\n recipient_city: string;\n recipient_zone: string;\n recipient_area: string;\n delivery_type: string;\n item_type: string;\n item_quantity: number;\n item_weight: number;\n item_description: string;\n amount_to_collect: number;\n special_instruction: string;\n status: string;\n status_updated_at: string;\n created_at: string;\n updated_at: string;\n };\n}\n\n// Official Pathao Area Response\nexport interface PathaoAreaResponse {\n type: string;\n code: number;\n message: string;\n data: Array<{\n area_id: number;\n area_name: string;\n zone_id: number;\n zone_name: string;\n city_id: number;\n city_name: string;\n }>;\n}\n\n// Configuration options for PathaoApiService\nexport interface PathaoConfig {\n clientId: string;\n clientSecret: string;\n username: string;\n password: string;\n baseURL?: string;\n timeout?: number;\n}\n\n// Error response from Pathao API\nexport interface PathaoError {\n type: string;\n code: number;\n message: string;\n errors?: Record<string, string[]>;\n validation?: Record<string, string[]>;\n}\n\n// Delivery types enum\nexport enum DeliveryType {\n NORMAL = 48,\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Store types enum\nexport enum StoreType {\n PICKUP_POINT = 1,\n SERVICE_POINT = 2\n}\n"]}
1
+ {"version":3,"sources":["../src/pathao-api.ts","../src/types.ts"],"names":["config","DeliveryType","ItemType"],"mappings":";;;AAsCO,IAAM,mBAAN,MAAuB;AAAA,EAiB5B,YAAY,MAAA,EAAsB;AAflC,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AACrC,IAAA,IAAA,CAAQ,YAAA,GAA8B,IAAA;AACtC,IAAA,IAAA,CAAQ,WAAA,GAA6B,IAAA;AAErC,IAAA,IAAA,CAAQ,gBAAA,GAA4B,KAAA;AACpC,IAAA,IAAA,CAAQ,WAAA,GAAoC,IAAA;AAC5C,IAAA,IAAA,CAAQ,eAA+E,EAAC;AACxF,IAAA,IAAA,CAAQ,cAAA,GAAiB;AAAA,MACvB,QAAA,EAAU,CAAA;AAAA,MACV,eAAA,EAAiB,CAAA;AAAA,MACjB,SAAA,EAAW,CAAA;AAAA,MACX,OAAA,EAAS,GAAA;AAAA;AAAA,MACT,MAAA,EAAQ;AAAA,KACV;AAGE,IAAA,IAAA,CAAK,MAAA,GAAS;AAAA,MACZ,OAAA,EAAS,MAAA,CAAO,OAAA,IAAW,OAAA,CAAQ,IAAI,eAAA,IAAmB,EAAA;AAAA,MAC1D,OAAA,EAAS,OAAO,OAAA,IAAW,QAAA,CAAS,QAAQ,GAAA,CAAI,cAAA,IAAkB,SAAS,EAAE,CAAA;AAAA,MAC7E,QAAA,EAAU,MAAA,CAAO,QAAA,IAAY,OAAA,CAAQ,IAAI,gBAAA,IAAoB,EAAA;AAAA,MAC7D,YAAA,EAAc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AAS,EAAA,CAAA,GAAT,QAAA;AACA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAFU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAML,IAAK,QAAA,qBAAAC,SAAAA,KAAL;AACL,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,cAAW,CAAA,CAAA,GAAX,UAAA;AACA,EAAAA,SAAAA,CAAAA,SAAAA,CAAA,YAAS,CAAA,CAAA,GAAT,QAAA;AAFU,EAAA,OAAAA,SAAAA;AAAA,CAAA,EAAA,QAAA,IAAA,EAAA","file":"index.mjs","sourcesContent":["/**\n * Pathao Merchant API Service (Unofficial SDK)\n * \n * This is an unofficial SDK for the Pathao Merchant API.\n * \n * API Details (based on public documentation):\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n * \n * Features implemented:\n * - Token-based authentication with refresh token support\n * - Store management (create, list stores)\n * - Order creation (single and bulk)\n * - Order tracking and status\n * - Dynamic price calculation\n * - City, zone, and area management\n */\n\nimport axios, { AxiosError, AxiosInstance } from 'axios';\nimport {\n PathaoAreaResponse,\n PathaoAuthResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStoreCreateResponse,\n PathaoStoreListResponse,\n PathaoStoreRequest,\n PathaoZoneResponse,\n} from './types';\n\nexport class PathaoApiService {\n private pathaoClient: AxiosInstance;\n private accessToken: string | null = null;\n private refreshToken: string | null = null;\n private tokenExpiry: number | null = null;\n private config: PathaoConfig;\n private isAuthenticating: boolean = false;\n private authPromise: Promise<void> | null = null;\n private requestQueue: Array<{ resolve: () => void; reject: (error: Error) => void }> = [];\n private circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: 5,\n timeout: 60000, // 1 minute\n isOpen: false,\n };\n\n constructor(config: PathaoConfig) {\n this.config = {\n baseURL: config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout: config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10),\n clientId: config.clientId || process.env.PATHAO_CLIENT_ID || '',\n clientSecret: config.clientSecret || process.env.PATHAO_CLIENT_SECRET || '',\n username: config.username || process.env.PATHAO_USERNAME || '',\n password: config.password || process.env.PATHAO_PASSWORD || '',\n };\n\n this.pathaoClient = axios.create({\n baseURL: this.config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout: this.config.timeout || parseInt(process.env.PATHAO_TIMEOUT || '30000', 10),\n headers: {\n 'Content-Type': 'application/json',\n 'Accept': 'application/json',\n },\n });\n\n // Validate required configuration\n if (!this.config.baseURL) {\n throw new Error('Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable');\n }\n \n if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {\n throw new Error('Pathao API credentials are required: clientId, clientSecret, username, password. You can provide them via constructor config or environment variables (PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME, PATHAO_PASSWORD)');\n }\n\n // Add request interceptor for authentication\n this.pathaoClient.interceptors.request.use(async (config) => {\n // Skip auth for token requests to prevent infinite loops\n if (config.url?.includes('/issue-token')) {\n return config;\n }\n \n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return config;\n });\n\n // Add response interceptor for error handling\n this.pathaoClient.interceptors.response.use(\n (response) => {\n // Reset circuit breaker on successful request\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n return response;\n },\n async (error) => {\n if (error.response?.status === 401) {\n // Token expired, clear tokens and retry\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n \n // Retry the request once\n if (error.config && !error.config._retry) {\n error.config._retry = true;\n await this.ensureAuthenticated();\n if (this.accessToken) {\n error.config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n return this.pathaoClient.request(error.config);\n }\n }\n \n // Handle circuit breaker\n this.handleCircuitBreaker();\n return Promise.reject(error);\n },\n );\n }\n\n private async ensureAuthenticated(): Promise<void> {\n // Check circuit breaker\n if (this.circuitBreaker.isOpen) {\n if (Date.now() - this.circuitBreaker.lastFailureTime > this.circuitBreaker.timeout) {\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.failures = 0;\n } else {\n throw new Error('Circuit breaker is open. Too many authentication failures.');\n }\n }\n\n if (this.accessToken && this.tokenExpiry && Date.now() < this.tokenExpiry) {\n return; // Token is still valid\n }\n\n // If already authenticating, wait for it to complete\n if (this.isAuthenticating && this.authPromise) {\n return this.authPromise;\n }\n\n // Start authentication process\n this.isAuthenticating = true;\n this.authPromise = this.performAuthentication();\n\n try {\n await this.authPromise;\n } finally {\n this.isAuthenticating = false;\n this.authPromise = null;\n // Process queued requests\n this.processRequestQueue();\n }\n }\n\n private async performAuthentication(): Promise<void> {\n if (this.refreshToken) {\n try {\n await this.refreshAccessToken();\n return;\n } catch (error) {\n // Refresh failed, try fresh authentication\n this.refreshToken = null;\n }\n }\n\n await this.authenticate();\n }\n\n private processRequestQueue(): void {\n const queue = [...this.requestQueue];\n this.requestQueue = [];\n \n queue.forEach(({ resolve }) => {\n try {\n resolve();\n } catch (error) {\n // Ignore errors in queued requests\n }\n });\n }\n\n private async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n username: this.config.username,\n password: this.config.password,\n grant_type: 'password',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful auth\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw new Error(`Authentication failed: ${this.getErrorMessage(error)}`);\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n if (!this.refreshToken) {\n throw new Error('No refresh token available');\n }\n\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>('/aladdin/api/v1/issue-token', {\n client_id: this.config.clientId,\n client_secret: this.config.clientSecret,\n refresh_token: this.refreshToken,\n grant_type: 'refresh_token',\n });\n\n this.accessToken = response.data.access_token;\n this.refreshToken = response.data.refresh_token;\n this.tokenExpiry = Date.now() + (response.data.expires_in * 1000) - 60000; // 1 minute buffer\n\n // Reset circuit breaker on successful refresh\n this.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n } catch (error) {\n this.handleCircuitBreaker();\n throw new Error(`Token refresh failed: ${this.getErrorMessage(error)}`);\n }\n }\n\n private getErrorMessage(error: unknown): string {\n if (error instanceof AxiosError) {\n const pathaoError = error.response?.data as PathaoError;\n if (pathaoError?.message) {\n return pathaoError.message;\n }\n return error.message;\n }\n return (error as Error).message || 'Unknown error';\n }\n\n private handleCircuitBreaker(): void {\n this.circuitBreaker.failures++;\n this.circuitBreaker.lastFailureTime = Date.now();\n \n if (this.circuitBreaker.failures >= this.circuitBreaker.threshold) {\n this.circuitBreaker.isOpen = true;\n }\n }\n\n // Official Pathao API: Create Order\n async createOrder(orderData: PathaoOrderRequest): Promise<PathaoOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoOrderResponse>('/aladdin/api/v1/orders', orderData);\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to create Pathao order: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(storeData: PathaoStoreRequest): Promise<PathaoStoreCreateResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoStoreCreateResponse>('/aladdin/api/v1/stores', storeData);\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to create Pathao store: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>('/aladdin/api/v1/stores');\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao stores: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(priceData: PathaoPriceRequest): Promise<PathaoPriceResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoPriceResponse>('/aladdin/api/v1/merchant/price-plan', priceData);\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to calculate Pathao price: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>('/aladdin/api/v1/city-list');\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao cities: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Zones for a City\n async getZones(cityId: number): Promise<PathaoZoneResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoZoneResponse>(`/aladdin/api/v1/cities/${cityId}/zone-list`);\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao zones: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Areas for a Zone\n async getAreas(zoneId: number): Promise<PathaoAreaResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoAreaResponse>(`/aladdin/api/v1/zones/${zoneId}/area-list`);\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao areas: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(consignmentId: string): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(`/aladdin/api/v1/orders/${consignmentId}/info`);\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to fetch Pathao order status: ${errorMessage}`);\n }\n }\n\n // Official Pathao API: Create Bulk Order\n async createBulkOrder(\n orders: PathaoOrderRequest[],\n ): Promise<{ message: string; type: string; code: number; data: boolean }> {\n try {\n const response = await this.pathaoClient.post<{\n message: string;\n type: string;\n code: number;\n data: boolean;\n }>('/aladdin/api/v1/orders/bulk', { orders });\n return response.data;\n } catch (error: unknown) {\n const errorMessage = this.getErrorMessage(error);\n throw new Error(`Failed to create bulk Pathao orders: ${errorMessage}`);\n }\n }\n\n // Helper method to validate phone number\n static validatePhoneNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, '');\n return cleanPhone.length === 11 && cleanPhone.startsWith('01');\n }\n\n // Helper method to format phone number\n static formatPhoneNumber(phone: string): string {\n const cleanPhone = phone.replace(/\\D/g, '');\n if (cleanPhone.length === 11 && cleanPhone.startsWith('01')) {\n return cleanPhone;\n }\n throw new Error('Invalid phone number format. Must be 11 digits starting with 01');\n }\n\n // Helper method to validate address\n static validateAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 10 && trimmed.length <= 220;\n }\n\n // Helper method to validate weight\n static validateWeight(weight: number): boolean {\n return weight >= 0.5 && weight <= 10;\n }\n\n // Helper method to validate recipient name\n static validateRecipientName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 100;\n }\n\n // Helper method to validate store name\n static validateStoreName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact name\n static validateContactName(name: string): boolean {\n const trimmed = name.trim();\n return trimmed.length >= 3 && trimmed.length <= 50;\n }\n\n // Helper method to validate contact number\n static validateContactNumber(phone: string): boolean {\n const cleanPhone = phone.replace(/\\D/g, '');\n return cleanPhone.length === 11;\n }\n\n // Helper method to validate store address\n static validateStoreAddress(address: string): boolean {\n const trimmed = address.trim();\n return trimmed.length >= 15 && trimmed.length <= 120;\n }\n\n // Method to clear authentication state (useful for testing)\n clearAuth(): void {\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n this.isAuthenticating = false;\n this.authPromise = null;\n this.requestQueue = [];\n this.circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: 5,\n timeout: 60000,\n isOpen: false,\n };\n }\n}\n","/**\n * Pathao Courier API Types\n * \n * Official API Details:\n * - Authentication: OAuth2 with client_id, client_secret, username, password\n * - All endpoints use /aladdin/api/v1/ prefix\n * - Base URL can be set via PATHAO_BASE_URL environment variable or constructor config\n * - Timeout can be set via PATHAO_TIMEOUT environment variable or constructor config\n */\n\n// Official Pathao API Authentication Response\nexport interface PathaoAuthResponse {\n token_type: string;\n expires_in: number;\n access_token: string;\n refresh_token: string;\n}\n\n// Official Pathao Order Creation Request\nexport interface PathaoOrderRequest {\n store_id: number;\n merchant_order_id?: string; // Optional - Your order tracking ID\n recipient_name: string; // Required - 3-100 characters\n recipient_phone: string; // Required - 11 characters\n recipient_secondary_phone?: string; // Optional - 11 characters\n recipient_address: string; // Required - 10-220 characters\n recipient_city?: number; // Optional - Auto-detected if not provided\n recipient_zone?: number; // Optional - Auto-detected if not provided\n recipient_area?: number; // Optional - Auto-detected if not provided\n delivery_type: number; // Required - 48 (Normal), 12 (On Demand)\n item_type: number; // Required - 1 (Document), 2 (Parcel)\n special_instruction?: string; // Optional\n item_quantity: number; // Required\n item_weight: number; // Required - 0.5-10 kg\n item_description?: string; // Optional\n amount_to_collect: number; // Required - COD amount (0 for non-COD)\n}\n\n// Official Pathao Store Creation Request\nexport interface PathaoStoreRequest {\n name: string; // 3-50 characters\n contact_name: string; // 3-50 characters\n contact_number: string; // 11 characters\n secondary_contact?: string; // Optional - 11 characters\n otp_number?: string; // Optional - OTP for orders\n address: string; // 15-120 characters\n city_id: number;\n zone_id: number;\n area_id: number;\n}\n\n// Official Pathao Order Response\nexport interface PathaoOrderResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n delivery_fee: number;\n };\n}\n\n// Official Pathao Store Creation Response\nexport interface PathaoStoreCreateResponse {\n type: string;\n code: number;\n message: string;\n data: {\n store_name: string; // Only store_name returned on creation\n };\n}\n\n// Official Pathao Store List Item (from GET /stores)\nexport interface PathaoStore {\n store_id: number;\n store_name: string;\n store_address: string;\n is_active: number; // 1 for active, 0 for deactivated\n city_id: number;\n zone_id: number;\n hub_id: number;\n is_default_store: boolean;\n is_default_return_store: boolean;\n}\n\n// Official Pathao Store List Response\nexport interface PathaoStoreListResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: PathaoStore[];\n total: number;\n current_page: number;\n per_page: number;\n total_in_page: number;\n last_page: number;\n path: string;\n to: number;\n from: number;\n last_page_url: string;\n first_page_url: string;\n };\n}\n\n// Official Pathao Price Calculation Request\nexport interface PathaoPriceRequest {\n store_id: number;\n item_type: number;\n item_weight: number;\n delivery_type: number;\n recipient_city: number;\n recipient_zone: number;\n}\n\n// Official Pathao Price Response\nexport interface PathaoPriceResponse {\n type: string;\n code: number;\n message: string;\n data: {\n price: number; // Calculated price for given item\n discount: number; // Discount for the given item\n promo_discount: number; // Promo discount for the given item\n plan_id: number; // Price plan id for the given item\n cod_enabled: number; // 1 if COD enabled, 0 if not\n cod_percentage: number; // Cash on delivery percentage\n additional_charge: number; // If there is any additional charge\n final_price: number; // Your final price for the given item\n };\n}\n\n// Official Pathao City Response\nexport interface PathaoCityResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n city_id: number;\n city_name: string;\n }>;\n };\n}\n\n// Official Pathao Order Status Response\nexport interface PathaoOrderStatusResponse {\n type: string;\n code: number;\n message: string;\n data: {\n consignment_id: string;\n merchant_order_id: string;\n order_status: string;\n order_status_slug: string;\n updated_at: string;\n invoice_id: string | null;\n };\n}\n\n// Official Pathao Zone Response\nexport interface PathaoZoneResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n zone_id: number;\n zone_name: string;\n }>;\n };\n}\n\n// Official Pathao Area Response\nexport interface PathaoAreaResponse {\n type: string;\n code: number;\n message: string;\n data: {\n data: Array<{\n area_id: number;\n area_name: string;\n home_delivery_available: boolean;\n pickup_available: boolean;\n }>;\n };\n}\n\n// Configuration options for PathaoApiService\nexport interface PathaoConfig {\n clientId: string;\n clientSecret: string;\n username: string;\n password: string;\n baseURL: string;\n timeout?: number;\n}\n\n// Error response from Pathao API\nexport interface PathaoError {\n type: string;\n code: number;\n message: string;\n errors?: Record<string, string[]>;\n validation?: Record<string, string[]>;\n}\n\n// Delivery types enum\nexport enum DeliveryType {\n NORMAL = 48,\n ON_DEMAND = 12\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2\n}\n\n// Store types enum (removed as not used in official API)\n// export enum StoreType {\n// PICKUP_POINT = 1,\n// SERVICE_POINT = 2\n// }\n"]}
package/package.json CHANGED
@@ -1,14 +1,24 @@
1
1
  {
2
2
  "name": "pathao-merchant-sdk",
3
- "version": "1.1.0",
3
+ "version": "2.0.0",
4
4
  "description": "Unofficial Pathao Merchant API SDK for Node.js and TypeScript",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",
7
7
  "types": "dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js"
13
+ }
14
+ },
15
+ "sideEffects": false,
8
16
  "files": [
9
17
  "dist",
10
18
  "README.md",
11
- "LICENSE"
19
+ "LICENSE",
20
+ "CHANGELOG.md",
21
+ "CONTRIBUTING.md"
12
22
  ],
13
23
  "scripts": {
14
24
  "build": "tsup",