pathao-merchant-sdk 2.3.1 → 3.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.js CHANGED
@@ -7,10 +7,24 @@ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
7
7
  var axios__default = /*#__PURE__*/_interopDefault(axios);
8
8
 
9
9
  // src/pathao-api.ts
10
+ function isSafeToRetry(config) {
11
+ const url = config.url ?? "";
12
+ return config.method?.toLowerCase() === "get" || url.includes("/issue-token") || url.includes("/merchant/price-plan");
13
+ }
14
+ function kindForStatus(status) {
15
+ if (status === 400 || status === 422) return "validation";
16
+ if (status === 401) return "auth";
17
+ if (status === 403) return "forbidden";
18
+ if (status === 404) return "not_found";
19
+ if (status === 429) return "rate_limited";
20
+ if (status !== void 0 && status >= 500) return "unavailable";
21
+ return "unexpected";
22
+ }
10
23
  var PathaoApiError = class extends Error {
11
24
  constructor(message, options = {}) {
12
25
  super(message);
13
26
  this.name = "PathaoApiError";
27
+ this.kind = options.kind ?? kindForStatus(options.status ?? options.code);
14
28
  this.status = options.status;
15
29
  this.code = options.code;
16
30
  this.type = options.type;
@@ -18,6 +32,14 @@ var PathaoApiError = class extends Error {
18
32
  this.validation = options.validation;
19
33
  this.responseData = options.responseData;
20
34
  }
35
+ /**
36
+ * True for transient failures (`unavailable`, `rate_limited`). For
37
+ * createOrder / createBulkOrder a 5xx may hide a booking that went through:
38
+ * look the order up before retrying a create.
39
+ */
40
+ get retryable() {
41
+ return this.kind === "unavailable" || this.kind === "rate_limited";
42
+ }
21
43
  };
22
44
  var PathaoApiService = class _PathaoApiService {
23
45
  constructor(config, options) {
@@ -28,18 +50,17 @@ var PathaoApiService = class _PathaoApiService {
28
50
  this.authPromise = null;
29
51
  this.hasValidated = false;
30
52
  this.debug = false;
31
- const parsedTimeout = parseInt(process.env.PATHAO_TIMEOUT || "", 10);
32
- const envTimeout = Number.isNaN(parsedTimeout) || parsedTimeout <= 0 ? 3e4 : parsedTimeout;
33
- const timeout = config.timeout ?? envTimeout;
53
+ this.nextRequestAt = 0;
34
54
  this.config = {
35
- baseURL: config.baseURL || process.env.PATHAO_BASE_URL || "",
36
- timeout,
37
- clientId: config.clientId || process.env.PATHAO_CLIENT_ID || "",
38
- clientSecret: config.clientSecret || process.env.PATHAO_CLIENT_SECRET || "",
39
- username: config.username || process.env.PATHAO_USERNAME || "",
40
- password: config.password || process.env.PATHAO_PASSWORD || ""
55
+ baseURL: config.baseURL ?? "",
56
+ timeout: config.timeout ?? 3e4,
57
+ clientId: config.clientId,
58
+ clientSecret: config.clientSecret,
59
+ username: config.username,
60
+ password: config.password
41
61
  };
42
62
  this.debug = options?.debug || false;
63
+ this.minRequestIntervalMs = Math.max(0, options?.minRequestIntervalMs ?? 0);
43
64
  this.circuitBreaker = {
44
65
  failures: 0,
45
66
  lastFailureTime: 0,
@@ -50,6 +71,10 @@ var PathaoApiService = class _PathaoApiService {
50
71
  this.pathaoClient = axios__default.default.create({
51
72
  ...this.config.baseURL ? { baseURL: this.config.baseURL } : {},
52
73
  timeout: this.config.timeout,
74
+ // Pathao has no reason to redirect, and a 307/308 would re-send the
75
+ // issue-token body (client secret, password) to wherever it points.
76
+ // With 0, any 3xx rejects like an error status.
77
+ maxRedirects: 0,
53
78
  headers: {
54
79
  "Content-Type": "application/json",
55
80
  Accept: "application/json",
@@ -57,6 +82,7 @@ var PathaoApiService = class _PathaoApiService {
57
82
  }
58
83
  });
59
84
  this.pathaoClient.interceptors.request.use(async (config2) => {
85
+ await this.waitForRequestSlot();
60
86
  if (config2.url?.includes("/issue-token")) {
61
87
  return config2;
62
88
  }
@@ -80,9 +106,10 @@ var PathaoApiService = class _PathaoApiService {
80
106
  this.circuitBreaker.failures = 0;
81
107
  this.circuitBreaker.isOpen = false;
82
108
  if (this.debug) {
109
+ const isTokenResponse = response.config.url?.includes("/issue-token");
83
110
  console.log(`[Pathao SDK] Response ${response.status}`, {
84
111
  url: response.config.url,
85
- data: response.data
112
+ data: isTokenResponse ? "[REDACTED]" : response.data
86
113
  });
87
114
  }
88
115
  return response;
@@ -101,15 +128,17 @@ var PathaoApiService = class _PathaoApiService {
101
128
  return this.pathaoClient.request(error.config);
102
129
  }
103
130
  }
104
- if (error.response?.status === 429 && error.config && !error.config._rateLimitRetry) {
131
+ const retryAfterSeconds = parseInt(
132
+ error.response?.headers?.["retry-after"] ?? "",
133
+ 10
134
+ );
135
+ if (error.response?.status === 429 && error.config && !error.config._rateLimitRetry && retryAfterSeconds > 0) {
105
136
  error.config._rateLimitRetry = true;
106
- const retryAfterHeader = error.response.headers["retry-after"];
107
- const delayMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1e3 : 1e3;
108
- await this.delay(delayMs);
137
+ await this.delay(retryAfterSeconds * 1e3);
109
138
  return this.pathaoClient.request(error.config);
110
139
  }
111
140
  const status = error.response?.status;
112
- if (status !== void 0 && status >= 500 && error.config) {
141
+ if (status !== void 0 && status >= 500 && error.config && isSafeToRetry(error.config)) {
113
142
  const retryCount = error.config._retryCount ?? 0;
114
143
  if (retryCount < 2) {
115
144
  error.config._retryCount = retryCount + 1;
@@ -117,8 +146,8 @@ var PathaoApiService = class _PathaoApiService {
117
146
  return this.pathaoClient.request(error.config);
118
147
  }
119
148
  }
120
- const isUserError = status !== void 0 && status >= 400 && status < 500 && status !== 401 && status !== 429;
121
- if (!isUserError) {
149
+ const tripsBreaker = status === void 0 || status >= 500 || status === 401;
150
+ if (tripsBreaker) {
122
151
  this.handleCircuitBreaker();
123
152
  }
124
153
  return Promise.reject(error);
@@ -130,25 +159,21 @@ var PathaoApiService = class _PathaoApiService {
130
159
  return;
131
160
  }
132
161
  if (!this.config.baseURL) {
133
- throw this.toPathaoApiError(
134
- new Error(
135
- "Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable"
136
- ),
137
- "Configuration validation failed"
162
+ throw new PathaoApiError(
163
+ "Configuration validation failed: Pathao API baseURL is required. Pass it in the config, or use PathaoApiService.fromEnv() with PATHAO_BASE_URL set",
164
+ { kind: "config" }
138
165
  );
139
166
  }
140
167
  if (!this.config.baseURL.startsWith("https://")) {
141
- throw this.toPathaoApiError(
142
- new Error("Pathao API baseURL must use HTTPS (https://)"),
143
- "Configuration validation failed"
168
+ throw new PathaoApiError(
169
+ "Configuration validation failed: Pathao API baseURL must use HTTPS (https://)",
170
+ { kind: "config" }
144
171
  );
145
172
  }
146
173
  if (!this.config.clientId || !this.config.clientSecret || !this.config.username || !this.config.password) {
147
- throw this.toPathaoApiError(
148
- new Error(
149
- "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)"
150
- ),
151
- "Configuration validation failed"
174
+ throw new PathaoApiError(
175
+ "Configuration validation failed: Pathao API credentials are required: clientId, clientSecret, username, password. Pass them in the config, or use PathaoApiService.fromEnv() with PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME and PATHAO_PASSWORD set",
176
+ { kind: "config" }
152
177
  );
153
178
  }
154
179
  this.hasValidated = true;
@@ -160,8 +185,8 @@ var PathaoApiService = class _PathaoApiService {
160
185
  this.circuitBreaker.failures = 0;
161
186
  } else {
162
187
  throw new PathaoApiError(
163
- "Circuit breaker is open. Too many authentication failures. Try again later.",
164
- { code: 503 }
188
+ "Circuit breaker is open after repeated network, server or authentication failures. Try again later.",
189
+ { code: 503, kind: "unavailable" }
165
190
  );
166
191
  }
167
192
  }
@@ -262,7 +287,9 @@ var PathaoApiService = class _PathaoApiService {
262
287
  type: pathaoError?.type,
263
288
  errors: pathaoError?.errors,
264
289
  validation: pathaoError?.validation,
265
- responseData: pathaoError ?? axiosLike.response?.data
290
+ responseData: pathaoError ?? axiosLike.response?.data,
291
+ // No response at all: timeout or network failure.
292
+ ...axiosLike.response ? {} : { kind: "unavailable" }
266
293
  }
267
294
  );
268
295
  }
@@ -275,21 +302,24 @@ var PathaoApiService = class _PathaoApiService {
275
302
  this.circuitBreaker.isOpen = true;
276
303
  }
277
304
  }
305
+ // Reserves the next free slot synchronously, then waits for it, so
306
+ // concurrent callers queue in call order.
307
+ async waitForRequestSlot() {
308
+ if (this.minRequestIntervalMs <= 0) return;
309
+ const now = Date.now();
310
+ const at = Math.max(now, this.nextRequestAt);
311
+ this.nextRequestAt = at + this.minRequestIntervalMs;
312
+ if (at > now) await this.delay(at - now);
313
+ }
278
314
  delay(ms) {
279
315
  return new Promise((resolve) => setTimeout(resolve, ms));
280
316
  }
281
317
  // Official Pathao API: Create Order
282
318
  async createOrder(orderData) {
283
319
  try {
284
- if (!_PathaoApiService.validatePhoneNumber(orderData.recipient_phone)) {
285
- throw new PathaoApiError("Validation failed: Invalid recipient_phone format", { code: 400 });
286
- }
287
- if (!_PathaoApiService.validateWeight(orderData.item_weight)) {
288
- throw new PathaoApiError("Validation failed: Invalid item_weight (must be 0.5 to 10)", { code: 400 });
289
- }
290
320
  const response = await this.pathaoClient.post(
291
321
  "/aladdin/api/v1/orders",
292
- orderData
322
+ _PathaoApiService.prepareOrder(orderData)
293
323
  );
294
324
  return response.data;
295
325
  } catch (error) {
@@ -398,28 +428,67 @@ var PathaoApiService = class _PathaoApiService {
398
428
  // Official Pathao API: Create Bulk Order
399
429
  async createBulkOrder(orders) {
400
430
  try {
431
+ const prepared = orders.map((order, i) => _PathaoApiService.prepareOrder(order, `orders[${i}]: `));
401
432
  const response = await this.pathaoClient.post(
402
433
  "/aladdin/api/v1/orders/bulk",
403
- { orders }
434
+ { orders: prepared }
404
435
  );
405
436
  return response.data;
406
437
  } catch (error) {
407
438
  throw this.toPathaoApiError(error, "Failed to create bulk Pathao orders");
408
439
  }
409
440
  }
441
+ // Validates an order and returns it with phones normalised to 01XXXXXXXXX,
442
+ // so local checks catch what Pathao would reject with a 422 and what is
443
+ // sent is what was validated.
444
+ static prepareOrder(order, prefix = "") {
445
+ const fail = (message) => {
446
+ throw new PathaoApiError(`Validation failed: ${prefix}${message}`, { code: 400 });
447
+ };
448
+ const phone = _PathaoApiService.normalizePhoneNumber(order.recipient_phone ?? "");
449
+ if (!phone) fail("Invalid recipient_phone format");
450
+ let secondary = null;
451
+ if (order.recipient_secondary_phone) {
452
+ secondary = _PathaoApiService.normalizePhoneNumber(order.recipient_secondary_phone);
453
+ if (!secondary) fail("Invalid recipient_secondary_phone format");
454
+ }
455
+ if (!_PathaoApiService.validateRecipientName(order.recipient_name ?? "")) {
456
+ fail("Invalid recipient_name (must be 3 to 100 characters)");
457
+ }
458
+ if (!_PathaoApiService.validateAddress(order.recipient_address ?? "")) {
459
+ fail("Invalid recipient_address (must be 10 to 220 characters)");
460
+ }
461
+ if (!_PathaoApiService.validateWeight(order.item_weight)) {
462
+ fail("Invalid item_weight (must be 0.5 to 10)");
463
+ }
464
+ return {
465
+ ...order,
466
+ recipient_phone: phone,
467
+ ...secondary ? { recipient_secondary_phone: secondary } : {}
468
+ };
469
+ }
470
+ /**
471
+ * Normalise a Bangladeshi mobile number to 01XXXXXXXXX. Accepts +8801…,
472
+ * 8801… and 01…, with spaces, dashes, dots or parentheses. Returns null for
473
+ * anything that isn't a BD mobile number (operator prefixes 013–019).
474
+ */
475
+ static normalizePhoneNumber(phone) {
476
+ const digits = phone.replace(/[\s\-().]/g, "").replace(/^\+/, "");
477
+ const local = digits.startsWith("880") ? `0${digits.slice(3)}` : digits;
478
+ return /^01[3-9]\d{8}$/.test(local) ? local : null;
479
+ }
410
480
  // Helper method to validate phone number
411
481
  static validatePhoneNumber(phone) {
412
- const cleanPhone = phone.replace(/\D/g, "");
413
- return cleanPhone.length === 11 && cleanPhone.startsWith("01");
482
+ return _PathaoApiService.normalizePhoneNumber(phone) !== null;
414
483
  }
415
484
  // Helper method to format phone number
416
485
  static formatPhoneNumber(phone) {
417
- const cleanPhone = phone.replace(/\D/g, "");
418
- if (cleanPhone.length === 11 && cleanPhone.startsWith("01")) {
419
- return cleanPhone;
486
+ const normalized = _PathaoApiService.normalizePhoneNumber(phone);
487
+ if (normalized) {
488
+ return normalized;
420
489
  }
421
490
  throw new Error(
422
- "Invalid phone number format. Must be 11 digits starting with 01"
491
+ "Invalid phone number format. Must be a Bangladeshi mobile number (01XXXXXXXXX or +8801XXXXXXXXX)"
423
492
  );
424
493
  }
425
494
  // Helper method to validate address
@@ -448,8 +517,7 @@ var PathaoApiService = class _PathaoApiService {
448
517
  }
449
518
  // Helper method to validate contact number
450
519
  static validateContactNumber(phone) {
451
- const cleanPhone = phone.replace(/\D/g, "");
452
- return cleanPhone.length === 11 && cleanPhone.startsWith("01");
520
+ return _PathaoApiService.normalizePhoneNumber(phone) !== null;
453
521
  }
454
522
  // Helper method to validate store address
455
523
  static validateStoreAddress(address) {
@@ -476,6 +544,10 @@ var PathaoApiService = class _PathaoApiService {
476
544
  password: process.env.PATHAO_PASSWORD || "",
477
545
  baseURL: process.env.PATHAO_BASE_URL || ""
478
546
  };
547
+ const timeout = parseInt(process.env.PATHAO_TIMEOUT || "", 10);
548
+ if (timeout > 0) {
549
+ config.timeout = timeout;
550
+ }
479
551
  return new _PathaoApiService(config, options);
480
552
  }
481
553
  // Static factory method to create instance from configuration object
@@ -498,6 +570,44 @@ var PathaoApiService = class _PathaoApiService {
498
570
  }
499
571
  };
500
572
 
573
+ // src/status.ts
574
+ var PATHAO_RATE_LIMIT_PER_MINUTE = 60;
575
+ var PATHAO_STATUS_RETENTION_DAYS = 90;
576
+ var LIFECYCLE = {
577
+ "pending": "created",
578
+ "created": "created",
579
+ "order-created": "created",
580
+ "pickup-requested": "created",
581
+ "assigned-for-pickup": "created",
582
+ "picked": "picked_up",
583
+ "pickup-failed": "on_hold",
584
+ "pickup-cancelled": "cancelled",
585
+ "at-the-sorting-hub": "in_transit",
586
+ "in-transit": "in_transit",
587
+ "received-at-last-mile-hub": "in_transit",
588
+ "assigned-for-delivery": "out_for_delivery",
589
+ "delivered": "delivered",
590
+ "partial-delivery": "partial",
591
+ "delivery-failed": "on_hold",
592
+ "on-hold": "on_hold",
593
+ // Marked for return; the parcel only comes back with returned-to-merchant.
594
+ "returned": "returning",
595
+ "return": "returning",
596
+ "return-id-created": "returning",
597
+ "return-in-transit": "returning",
598
+ "paid-return": "returning",
599
+ "exchanged": "returning",
600
+ "exchange": "returning",
601
+ "returned-to-merchant": "returned"
602
+ };
603
+ function toLifecycleStatus(value) {
604
+ const key = value.trim().toLowerCase().replace(/^order\./, "").replace(/[\s_]+/g, "-");
605
+ return LIFECYCLE[key] ?? "unknown";
606
+ }
607
+ function isFinalLifecycleStatus(status) {
608
+ return status === "delivered" || status === "partial" || status === "returned" || status === "cancelled";
609
+ }
610
+
501
611
  // src/types.ts
502
612
  var DeliveryType = /* @__PURE__ */ ((DeliveryType2) => {
503
613
  DeliveryType2[DeliveryType2["NORMAL"] = 48] = "NORMAL";
@@ -512,7 +622,11 @@ var ItemType = /* @__PURE__ */ ((ItemType2) => {
512
622
 
513
623
  exports.DeliveryType = DeliveryType;
514
624
  exports.ItemType = ItemType;
625
+ exports.PATHAO_RATE_LIMIT_PER_MINUTE = PATHAO_RATE_LIMIT_PER_MINUTE;
626
+ exports.PATHAO_STATUS_RETENTION_DAYS = PATHAO_STATUS_RETENTION_DAYS;
515
627
  exports.PathaoApiError = PathaoApiError;
516
628
  exports.PathaoApiService = PathaoApiService;
629
+ exports.isFinalLifecycleStatus = isFinalLifecycleStatus;
630
+ exports.toLifecycleStatus = toLifecycleStatus;
517
631
  //# sourceMappingURL=index.js.map
518
632
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/pathao-api.ts","../src/types.ts"],"names":["axios","config","AxiosError","DeliveryType","ItemType"],"mappings":";;;;;;;;;AAwCO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EAQxC,WAAA,CACE,OAAA,EACA,OAAA,GAOI,EAAC,EACL;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,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O,IAAK,YAAA,qBAAAC,aAAAA,KAAL;AAEL,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,YAAS,EAAA,CAAA,GAAT,QAAA;AAEA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAJU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAQL,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.js","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 PathaoBulkOrderResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStore,\n PathaoStoreCreateResponse,\n PathaoStoreListResponse,\n PathaoStoreRequest,\n PathaoZoneResponse,\n} from './types';\n\nexport class PathaoApiError extends Error {\n status: number | undefined;\n code: number | undefined;\n type: string | undefined;\n errors: Record<string, string[]> | undefined;\n validation: Record<string, string[]> | undefined;\n responseData: unknown;\n\n constructor(\n message: string,\n options: {\n status?: number | undefined;\n code?: number | undefined;\n type?: string | undefined;\n errors?: Record<string, string[]> | undefined;\n validation?: Record<string, string[]> | undefined;\n responseData?: unknown;\n } = {},\n ) {\n super(message);\n this.name = 'PathaoApiError';\n this.status = options.status;\n this.code = options.code;\n this.type = options.type;\n this.errors = options.errors;\n this.validation = options.validation;\n this.responseData = options.responseData;\n }\n}\n\n// Internal resolved config with guaranteed timeout\ninterface ResolvedPathaoConfig extends PathaoConfig {\n timeout: number;\n}\n\n// Circuit breaker configuration\nexport interface CircuitBreakerConfig {\n threshold?: number; // Default: 5\n timeout?: number; // Default: 60000ms\n}\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: ResolvedPathaoConfig;\n private isAuthenticating: boolean = false;\n private authPromise: Promise<void> | null = null;\n private hasValidated: boolean = false;\n private debug: boolean = false;\n private circuitBreaker: {\n failures: number;\n lastFailureTime: number;\n threshold: number;\n timeout: number;\n isOpen: boolean;\n };\n\n constructor(config: PathaoConfig, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }) {\n const parsedTimeout = parseInt(process.env.PATHAO_TIMEOUT || '', 10);\n const envTimeout = Number.isNaN(parsedTimeout) || parsedTimeout <= 0 ? 30000 : parsedTimeout;\n const timeout: number = config.timeout ?? envTimeout;\n\n this.config = {\n baseURL: config.baseURL || process.env.PATHAO_BASE_URL || '',\n timeout,\n clientId: config.clientId || process.env.PATHAO_CLIENT_ID || '',\n clientSecret:\n 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.debug = options?.debug || false;\n this.circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: options?.circuitBreaker?.threshold ?? 5,\n timeout: options?.circuitBreaker?.timeout ?? 60000,\n isOpen: false,\n };\n\n this.pathaoClient = axios.create({\n ...(this.config.baseURL ? { baseURL: this.config.baseURL } : {}),\n timeout: this.config.timeout,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': `pathao-merchant-sdk node/${process.version}`,\n },\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 // Validate configuration on first API call\n this.validateConfiguration();\n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n\n if (this.debug) {\n const safeHeaders = { ...config.headers } as Record<string, unknown>;\n if (safeHeaders['Authorization']) safeHeaders['Authorization'] = 'Bearer [REDACTED]';\n console.log(`[Pathao SDK] ${config.method?.toUpperCase()} ${config.url}`, {\n headers: safeHeaders,\n data: config.data,\n });\n }\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\n if (this.debug) {\n console.log(`[Pathao SDK] Response ${response.status}`, {\n url: response.config.url,\n data: response.data,\n });\n }\n\n return response;\n },\n async (error) => {\n if (error.response?.status === 401) {\n // Token expired, clear tokens and retry once\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n\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 // Respect Retry-After on 429 (rate limit), retry once\n if (error.response?.status === 429 && error.config && !error.config._rateLimitRetry) {\n error.config._rateLimitRetry = true;\n const retryAfterHeader = error.response.headers['retry-after'] as string | undefined;\n const delayMs = retryAfterHeader ? parseInt(retryAfterHeader, 10) * 1000 : 1000;\n await this.delay(delayMs);\n return this.pathaoClient.request(error.config);\n }\n\n // Retry transient 5xx errors with exponential backoff (max 2 retries)\n const status: number | undefined = error.response?.status;\n if (status !== undefined && status >= 500 && error.config) {\n const retryCount: number = (error.config._retryCount as number | undefined) ?? 0;\n if (retryCount < 2) {\n error.config._retryCount = retryCount + 1;\n await this.delay(Math.min(500 * 2 ** retryCount, 4000));\n return this.pathaoClient.request(error.config);\n }\n }\n\n // Handle circuit breaker for network, 5xx, or specific auth/rate-limit failures\n const isUserError = status !== undefined && status >= 400 && status < 500 && status !== 401 && status !== 429;\n if (!isUserError) {\n this.handleCircuitBreaker();\n }\n return Promise.reject(error);\n },\n );\n }\n\n private validateConfiguration(): void {\n // Only validate once\n if (this.hasValidated) {\n return;\n }\n\n if (!this.config.baseURL) {\n throw this.toPathaoApiError(\n new Error(\n 'Pathao API baseURL is required. You can provide it via constructor config or PATHAO_BASE_URL environment variable',\n ),\n 'Configuration validation failed',\n );\n }\n\n if (!this.config.baseURL.startsWith('https://')) {\n throw this.toPathaoApiError(\n new Error('Pathao API baseURL must use HTTPS (https://)'),\n 'Configuration validation failed',\n );\n }\n\n if (\n !this.config.clientId ||\n !this.config.clientSecret ||\n !this.config.username ||\n !this.config.password\n ) {\n throw this.toPathaoApiError(\n new Error(\n '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 'Configuration validation failed',\n );\n }\n\n this.hasValidated = true;\n }\n\n private async ensureAuthenticated(): Promise<void> {\n // Check circuit breaker\n if (this.circuitBreaker.isOpen) {\n if (\n Date.now() - this.circuitBreaker.lastFailureTime >\n this.circuitBreaker.timeout\n ) {\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.failures = 0;\n } else {\n throw new PathaoApiError(\n 'Circuit breaker is open. Too many authentication failures. Try again later.',\n { code: 503 },\n );\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 }\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 async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n '/aladdin/api/v1/issue-token',\n {\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\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 this.toPathaoApiError(error, 'Authentication failed');\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n '/aladdin/api/v1/issue-token',\n {\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\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 this.toPathaoApiError(error, 'Token refresh failed');\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 if (error instanceof Error) return error.message;\n return 'Unknown error';\n }\n\n private toPathaoApiError(error: unknown, context: string): PathaoApiError {\n if (error instanceof PathaoApiError) {\n return error;\n }\n\n const messageFallback = this.getErrorMessage(error);\n const hasResponse = (e: unknown): e is { response?: AxiosError['response'] } =>\n typeof e === 'object' && e !== null && 'response' in e;\n const axiosLike =\n error instanceof AxiosError\n ? error\n : hasResponse(error)\n ? error\n : null;\n if (axiosLike) {\n const pathaoError = axiosLike.response?.data as PathaoError | undefined;\n return new PathaoApiError(\n `${context}: ${pathaoError?.message || messageFallback}`,\n {\n status: axiosLike.response?.status,\n code: pathaoError?.code ?? axiosLike.response?.status,\n type: pathaoError?.type,\n errors: pathaoError?.errors,\n validation: pathaoError?.validation,\n responseData: pathaoError ?? axiosLike.response?.data,\n },\n );\n }\n\n return new PathaoApiError(`${context}: ${messageFallback}`);\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 private delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n // Official Pathao API: Create Order\n async createOrder(\n orderData: PathaoOrderRequest,\n ): Promise<PathaoOrderResponse> {\n try {\n if (!PathaoApiService.validatePhoneNumber(orderData.recipient_phone)) {\n throw new PathaoApiError('Validation failed: Invalid recipient_phone format', { code: 400 });\n }\n if (!PathaoApiService.validateWeight(orderData.item_weight)) {\n throw new PathaoApiError('Validation failed: Invalid item_weight (must be 0.5 to 10)', { code: 400 });\n }\n\n const response = await this.pathaoClient.post<PathaoOrderResponse>(\n '/aladdin/api/v1/orders',\n orderData,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao order');\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(\n storeData: PathaoStoreRequest,\n ): Promise<PathaoStoreCreateResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoStoreCreateResponse>(\n '/aladdin/api/v1/stores',\n storeData,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao store');\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(page?: number): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>(\n '/aladdin/api/v1/stores',\n page !== undefined ? { params: { page } } : undefined,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao stores');\n }\n }\n\n // Official Pathao API: Get All Stores (Auto-paginating helper)\n async getStoresAll(): Promise<PathaoStore[]> {\n try {\n let currentPage = 1;\n let lastPage = 1;\n const allStores: PathaoStore[] = [];\n\n do {\n const response = await this.getStores(currentPage);\n if (response.data?.data) {\n allStores.push(...response.data.data);\n }\n lastPage = response.data?.last_page || 1;\n currentPage++;\n } while (currentPage <= lastPage);\n\n return allStores;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch all Pathao stores');\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(\n priceData: PathaoPriceRequest,\n ): Promise<PathaoPriceResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoPriceResponse>(\n '/aladdin/api/v1/merchant/price-plan',\n priceData,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to calculate Pathao price');\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>(\n '/aladdin/api/v1/city-list',\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao cities');\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>(\n `/aladdin/api/v1/cities/${cityId}/zone-list`,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao zones');\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>(\n `/aladdin/api/v1/zones/${zoneId}/area-list`,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao areas');\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(\n consignmentId: string,\n ): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(\n `/aladdin/api/v1/orders/${encodeURIComponent(consignmentId)}/info`,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao order status');\n }\n }\n\n // Official Pathao API: Create Bulk Order\n async createBulkOrder(\n orders: PathaoOrderRequest[],\n ): Promise<PathaoBulkOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoBulkOrderResponse>(\n '/aladdin/api/v1/orders/bulk', { orders });\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create bulk Pathao orders');\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(\n 'Invalid phone number format. Must be 11 digits starting with 01',\n );\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 && cleanPhone.startsWith('01');\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.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.lastFailureTime = 0;\n }\n\n // Static factory method to create instance from environment variables\n static fromEnv(options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n const config: PathaoConfig = {\n clientId: process.env.PATHAO_CLIENT_ID || '',\n clientSecret: process.env.PATHAO_CLIENT_SECRET || '',\n username: process.env.PATHAO_USERNAME || '',\n password: process.env.PATHAO_PASSWORD || '',\n baseURL: process.env.PATHAO_BASE_URL || '',\n };\n return new PathaoApiService(config, options);\n }\n\n // Static factory method to create instance from configuration object\n static fromConfig(\n config: PathaoConfig,\n options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig },\n ): PathaoApiService {\n return new PathaoApiService(config, options);\n }\n\n // Named constructor for sandbox environment\n static sandbox(credentials: Omit<PathaoConfig, 'baseURL'>, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://courier-api-sandbox.pathao.com' },\n options,\n );\n }\n\n // Named constructor for production environment\n static production(credentials: Omit<PathaoConfig, 'baseURL'>, options?: { debug?: boolean; circuitBreaker?: CircuitBreakerConfig }): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://api-hermes.pathao.com' },\n options,\n );\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: DeliveryType; // Required - DeliveryType.NORMAL (48) or DeliveryType.ON_DEMAND (12)\n item_type: ItemType; // Required - ItemType.DOCUMENT (1) or ItemType.PARCEL (2)\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; // Only present if provided in the request\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: 0 | 1; // 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: ItemType;\n item_weight: number;\n delivery_type: DeliveryType;\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: 0 | 1; // 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; // Only present if provided at order creation\n order_status: string;\n order_status_slug: string;\n updated_at: string; // Format: \"YYYY-MM-DD HH:MM:SS\"\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; // Optional - defaults to 30000 if not provided\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/**\n * Delivery type codes defined by the Pathao API.\n * Values correspond to Pathao's internal delivery_type IDs.\n * @see https://developers.pathao.com - Order Creation endpoint\n */\nexport enum DeliveryType {\n /** Standard delivery (API value: 48) */\n NORMAL = 48,\n /** Same-day on-demand delivery (API value: 12) */\n ON_DEMAND = 12,\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2,\n}\n\n// Official Pathao Bulk Order Response\nexport interface PathaoBulkOrderResponse {\n message: string;\n type: string;\n code: number;\n data: boolean;\n}\n"]}
1
+ {"version":3,"sources":["../src/pathao-api.ts","../src/status.ts","../src/types.ts"],"names":["axios","config","AxiosError","DeliveryType","ItemType"],"mappings":";;;;;;;;;AA0CA,SAAS,cAAc,MAAA,EAA4E;AACjG,EAAA,MAAM,GAAA,GAAM,OAAO,GAAA,IAAO,EAAA;AAC1B,EAAA,OACE,MAAA,CAAO,MAAA,EAAQ,WAAA,EAAY,KAAM,KAAA,IACjC,GAAA,CAAI,QAAA,CAAS,cAAc,CAAA,IAC3B,GAAA,CAAI,QAAA,CAAS,sBAAsB,CAAA;AAEvC;AAoBA,SAAS,cAAc,MAAA,EAA6C;AAClE,EAAA,IAAI,MAA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;AACzF,EAAA,OAAO,WAAW,WAAA,IAAe,MAAA,KAAW,SAAA,IAAa,MAAA,KAAW,cAAc,MAAA,KAAW,WAAA;AAC/F;;;ACsIO,IAAK,YAAA,qBAAAC,aAAAA,KAAL;AAEL,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,YAAS,EAAA,CAAA,GAAT,QAAA;AAEA,EAAAA,aAAAA,CAAAA,aAAAA,CAAA,eAAY,EAAA,CAAA,GAAZ,WAAA;AAJU,EAAA,OAAAA,aAAAA;AAAA,CAAA,EAAA,YAAA,IAAA,EAAA;AAQL,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.js","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 * - The constructor reads only the config it is given. Use fromEnv() to read\n * PATHAO_* environment variables (including PATHAO_TIMEOUT).\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 PathaoBulkOrderResponse,\n PathaoCityResponse,\n PathaoConfig,\n PathaoError,\n PathaoOrderRequest,\n PathaoOrderResponse,\n PathaoOrderStatusResponse,\n PathaoPriceRequest,\n PathaoPriceResponse,\n PathaoStore,\n PathaoStoreCreateResponse,\n PathaoStoreListResponse,\n PathaoStoreRequest,\n PathaoZoneResponse,\n} from './types';\n\n// GETs, token grants and the read-only price-plan POST can be repeated\n// without side effects. Order and store creation cannot.\nfunction isSafeToRetry(config: { method?: string | undefined; url?: string | undefined }): boolean {\n const url = config.url ?? '';\n return (\n config.method?.toLowerCase() === 'get' ||\n url.includes('/issue-token') ||\n url.includes('/merchant/price-plan')\n );\n}\n\nexport type PathaoErrorKind =\n /** Input rejected, by this SDK before sending or by Pathao (HTTP 400/422). */\n | 'validation'\n /** Missing or wrong baseURL / credentials, caught before any request. */\n | 'config'\n /** Rejected credentials or token (HTTP 401). */\n | 'auth'\n /** HTTP 403. */\n | 'forbidden'\n /** Unknown consignment, store or resource (HTTP 404). */\n | 'not_found'\n /** HTTP 429. Back off; see PATHAO_RATE_LIMIT_PER_MINUTE. */\n | 'rate_limited'\n /** 5xx, timeout, network failure or open circuit breaker. */\n | 'unavailable'\n /** A response this SDK doesn't understand. Inspect `responseData`. */\n | 'unexpected';\n\nfunction kindForStatus(status: number | undefined): PathaoErrorKind {\n if (status === 400 || status === 422) return 'validation';\n if (status === 401) return 'auth';\n if (status === 403) return 'forbidden';\n if (status === 404) return 'not_found';\n if (status === 429) return 'rate_limited';\n if (status !== undefined && status >= 500) return 'unavailable';\n return 'unexpected';\n}\n\nexport class PathaoApiError extends Error {\n kind: PathaoErrorKind;\n status: number | undefined;\n code: number | undefined;\n type: string | undefined;\n errors: Record<string, string[]> | undefined;\n validation: Record<string, string[]> | undefined;\n responseData: unknown;\n\n constructor(\n message: string,\n options: {\n status?: number | undefined;\n code?: number | undefined;\n type?: string | undefined;\n errors?: Record<string, string[]> | undefined;\n validation?: Record<string, string[]> | undefined;\n responseData?: unknown;\n kind?: PathaoErrorKind | undefined;\n } = {},\n ) {\n super(message);\n this.name = 'PathaoApiError';\n this.kind = options.kind ?? kindForStatus(options.status ?? options.code);\n this.status = options.status;\n this.code = options.code;\n this.type = options.type;\n this.errors = options.errors;\n this.validation = options.validation;\n this.responseData = options.responseData;\n }\n\n /**\n * True for transient failures (`unavailable`, `rate_limited`). For\n * createOrder / createBulkOrder a 5xx may hide a booking that went through:\n * look the order up before retrying a create.\n */\n get retryable(): boolean {\n return this.kind === 'unavailable' || this.kind === 'rate_limited';\n }\n}\n\n// Internal resolved config with guaranteed timeout\ninterface ResolvedPathaoConfig extends PathaoConfig {\n timeout: number;\n}\n\n// Circuit breaker configuration\nexport interface CircuitBreakerConfig {\n threshold?: number; // Default: 5\n timeout?: number; // Default: 60000ms\n}\n\nexport interface PathaoClientOptions {\n /** Log requests and responses (tokens and Authorization redacted). */\n debug?: boolean;\n circuitBreaker?: CircuitBreakerConfig;\n /**\n * Minimum gap between requests from this instance, in ms. Requests queue\n * instead of tripping Pathao's 60/min limit (PATHAO_RATE_LIMIT_PER_MINUTE).\n * 1500 keeps one instance near 40/min, leaving headroom for other callers\n * sharing the credentials. Default 0 (no spacing).\n */\n minRequestIntervalMs?: number;\n}\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: ResolvedPathaoConfig;\n private isAuthenticating: boolean = false;\n private authPromise: Promise<void> | null = null;\n private hasValidated: boolean = false;\n private debug: boolean = false;\n private minRequestIntervalMs: number;\n private nextRequestAt = 0;\n private circuitBreaker: {\n failures: number;\n lastFailureTime: number;\n threshold: number;\n timeout: number;\n isOpen: boolean;\n };\n\n constructor(config: PathaoConfig, options?: PathaoClientOptions) {\n // Explicit config is read as given, never topped up from process.env: in\n // a multi-tenant app a blank field would otherwise pick up the platform's\n // own Pathao account. Env-based setup is fromEnv().\n this.config = {\n baseURL: config.baseURL ?? '',\n timeout: config.timeout ?? 30000,\n clientId: config.clientId,\n clientSecret: config.clientSecret,\n username: config.username,\n password: config.password,\n };\n\n this.debug = options?.debug || false;\n this.minRequestIntervalMs = Math.max(0, options?.minRequestIntervalMs ?? 0);\n this.circuitBreaker = {\n failures: 0,\n lastFailureTime: 0,\n threshold: options?.circuitBreaker?.threshold ?? 5,\n timeout: options?.circuitBreaker?.timeout ?? 60000,\n isOpen: false,\n };\n\n this.pathaoClient = axios.create({\n ...(this.config.baseURL ? { baseURL: this.config.baseURL } : {}),\n timeout: this.config.timeout,\n // Pathao has no reason to redirect, and a 307/308 would re-send the\n // issue-token body (client secret, password) to wherever it points.\n // With 0, any 3xx rejects like an error status.\n maxRedirects: 0,\n headers: {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n 'User-Agent': `pathao-merchant-sdk node/${process.version}`,\n },\n });\n\n // Add request interceptor for authentication\n this.pathaoClient.interceptors.request.use(async (config) => {\n // Every request counts against Pathao's limit, token grants and\n // retries included, so space them all.\n await this.waitForRequestSlot();\n\n // Skip auth for token requests to prevent infinite loops\n if (config.url?.includes('/issue-token')) {\n return config;\n }\n\n // Validate configuration on first API call\n this.validateConfiguration();\n await this.ensureAuthenticated();\n if (this.accessToken) {\n config.headers.Authorization = `Bearer ${this.accessToken}`;\n }\n\n if (this.debug) {\n const safeHeaders = { ...config.headers } as Record<string, unknown>;\n if (safeHeaders['Authorization']) safeHeaders['Authorization'] = 'Bearer [REDACTED]';\n console.log(`[Pathao SDK] ${config.method?.toUpperCase()} ${config.url}`, {\n headers: safeHeaders,\n data: config.data,\n });\n }\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\n if (this.debug) {\n // Token grants carry access_token / refresh_token; never log them.\n const isTokenResponse = response.config.url?.includes('/issue-token');\n console.log(`[Pathao SDK] Response ${response.status}`, {\n url: response.config.url,\n data: isTokenResponse ? '[REDACTED]' : response.data,\n });\n }\n\n return response;\n },\n async (error) => {\n if (error.response?.status === 401) {\n // Token expired, clear tokens and retry once\n this.accessToken = null;\n this.refreshToken = null;\n this.tokenExpiry = null;\n\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 // Pathao's gateway allows 60 requests per rolling minute and its 429\n // carries no Retry-After, so a blind short retry always fails. Retry\n // once only when the server says how long to wait; otherwise hand the\n // 429 to the caller.\n const retryAfterSeconds = parseInt(\n (error.response?.headers?.['retry-after'] as string | undefined) ?? '',\n 10,\n );\n if (\n error.response?.status === 429 &&\n error.config &&\n !error.config._rateLimitRetry &&\n retryAfterSeconds > 0\n ) {\n error.config._rateLimitRetry = true;\n await this.delay(retryAfterSeconds * 1000);\n return this.pathaoClient.request(error.config);\n }\n\n // Retry transient 5xx errors with exponential backoff (max 2 retries),\n // but only for requests that are safe to repeat. A 5xx on a create\n // (a gateway 502/504 in front of a slow success) may already have\n // booked the consignment; re-POSTing can book it again.\n const status: number | undefined = error.response?.status;\n if (status !== undefined && status >= 500 && error.config && isSafeToRetry(error.config)) {\n const retryCount: number = (error.config._retryCount as number | undefined) ?? 0;\n if (retryCount < 2) {\n error.config._retryCount = retryCount + 1;\n await this.delay(Math.min(500 * 2 ** retryCount, 4000));\n return this.pathaoClient.request(error.config);\n }\n }\n\n // Trip the circuit breaker on outages (network, 5xx) and auth failures.\n // A 429 is not an outage: counting it locked out every call for the\n // breaker timeout and re-tripped each time the rate window reset.\n const tripsBreaker = status === undefined || status >= 500 || status === 401;\n if (tripsBreaker) {\n this.handleCircuitBreaker();\n }\n return Promise.reject(error);\n },\n );\n }\n\n private validateConfiguration(): void {\n // Only validate once\n if (this.hasValidated) {\n return;\n }\n\n if (!this.config.baseURL) {\n throw new PathaoApiError(\n 'Configuration validation failed: Pathao API baseURL is required. Pass it in the config, or use PathaoApiService.fromEnv() with PATHAO_BASE_URL set',\n { kind: 'config' },\n );\n }\n\n if (!this.config.baseURL.startsWith('https://')) {\n throw new PathaoApiError(\n 'Configuration validation failed: Pathao API baseURL must use HTTPS (https://)',\n { kind: 'config' },\n );\n }\n\n if (\n !this.config.clientId ||\n !this.config.clientSecret ||\n !this.config.username ||\n !this.config.password\n ) {\n throw new PathaoApiError(\n 'Configuration validation failed: Pathao API credentials are required: clientId, clientSecret, username, password. Pass them in the config, or use PathaoApiService.fromEnv() with PATHAO_CLIENT_ID, PATHAO_CLIENT_SECRET, PATHAO_USERNAME and PATHAO_PASSWORD set',\n { kind: 'config' },\n );\n }\n\n this.hasValidated = true;\n }\n\n private async ensureAuthenticated(): Promise<void> {\n // Check circuit breaker\n if (this.circuitBreaker.isOpen) {\n if (\n Date.now() - this.circuitBreaker.lastFailureTime >\n this.circuitBreaker.timeout\n ) {\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.failures = 0;\n } else {\n throw new PathaoApiError(\n 'Circuit breaker is open after repeated network, server or authentication failures. Try again later.',\n { code: 503, kind: 'unavailable' },\n );\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 }\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 async authenticate(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n '/aladdin/api/v1/issue-token',\n {\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\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 this.toPathaoApiError(error, 'Authentication failed');\n }\n }\n\n private async refreshAccessToken(): Promise<void> {\n try {\n const response = await this.pathaoClient.post<PathaoAuthResponse>(\n '/aladdin/api/v1/issue-token',\n {\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\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 this.toPathaoApiError(error, 'Token refresh failed');\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 if (error instanceof Error) return error.message;\n return 'Unknown error';\n }\n\n private toPathaoApiError(error: unknown, context: string): PathaoApiError {\n if (error instanceof PathaoApiError) {\n return error;\n }\n\n const messageFallback = this.getErrorMessage(error);\n const hasResponse = (e: unknown): e is { response?: AxiosError['response'] } =>\n typeof e === 'object' && e !== null && 'response' in e;\n const axiosLike =\n error instanceof AxiosError\n ? error\n : hasResponse(error)\n ? error\n : null;\n if (axiosLike) {\n const pathaoError = axiosLike.response?.data as PathaoError | undefined;\n return new PathaoApiError(\n `${context}: ${pathaoError?.message || messageFallback}`,\n {\n status: axiosLike.response?.status,\n code: pathaoError?.code ?? axiosLike.response?.status,\n type: pathaoError?.type,\n errors: pathaoError?.errors,\n validation: pathaoError?.validation,\n responseData: pathaoError ?? axiosLike.response?.data,\n // No response at all: timeout or network failure.\n ...(axiosLike.response ? {} : { kind: 'unavailable' as const }),\n },\n );\n }\n\n return new PathaoApiError(`${context}: ${messageFallback}`);\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 // Reserves the next free slot synchronously, then waits for it, so\n // concurrent callers queue in call order.\n private async waitForRequestSlot(): Promise<void> {\n if (this.minRequestIntervalMs <= 0) return;\n const now = Date.now();\n const at = Math.max(now, this.nextRequestAt);\n this.nextRequestAt = at + this.minRequestIntervalMs;\n if (at > now) await this.delay(at - now);\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n\n // Official Pathao API: Create Order\n async createOrder(\n orderData: PathaoOrderRequest,\n ): Promise<PathaoOrderResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoOrderResponse>(\n '/aladdin/api/v1/orders',\n PathaoApiService.prepareOrder(orderData),\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao order');\n }\n }\n\n // Official Pathao API: Create Store\n async createStore(\n storeData: PathaoStoreRequest,\n ): Promise<PathaoStoreCreateResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoStoreCreateResponse>(\n '/aladdin/api/v1/stores',\n storeData,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create Pathao store');\n }\n }\n\n // Official Pathao API: Get Store List\n async getStores(page?: number): Promise<PathaoStoreListResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoStoreListResponse>(\n '/aladdin/api/v1/stores',\n page !== undefined ? { params: { page } } : undefined,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao stores');\n }\n }\n\n // Official Pathao API: Get All Stores (Auto-paginating helper)\n async getStoresAll(): Promise<PathaoStore[]> {\n try {\n let currentPage = 1;\n let lastPage = 1;\n const allStores: PathaoStore[] = [];\n\n do {\n const response = await this.getStores(currentPage);\n if (response.data?.data) {\n allStores.push(...response.data.data);\n }\n lastPage = response.data?.last_page || 1;\n currentPage++;\n } while (currentPage <= lastPage);\n\n return allStores;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch all Pathao stores');\n }\n }\n\n // Official Pathao API: Calculate Price\n async calculatePrice(\n priceData: PathaoPriceRequest,\n ): Promise<PathaoPriceResponse> {\n try {\n const response = await this.pathaoClient.post<PathaoPriceResponse>(\n '/aladdin/api/v1/merchant/price-plan',\n priceData,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to calculate Pathao price');\n }\n }\n\n // Official Pathao API: Get Cities\n async getCities(): Promise<PathaoCityResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoCityResponse>(\n '/aladdin/api/v1/city-list',\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao cities');\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>(\n `/aladdin/api/v1/cities/${cityId}/zone-list`,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao zones');\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>(\n `/aladdin/api/v1/zones/${zoneId}/area-list`,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao areas');\n }\n }\n\n // Official Pathao API: Get Order Status\n async getOrderStatus(\n consignmentId: string,\n ): Promise<PathaoOrderStatusResponse> {\n try {\n const response = await this.pathaoClient.get<PathaoOrderStatusResponse>(\n `/aladdin/api/v1/orders/${encodeURIComponent(consignmentId)}/info`,\n );\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to fetch Pathao order status');\n }\n }\n\n // Official Pathao API: Create Bulk Order\n async createBulkOrder(\n orders: PathaoOrderRequest[],\n ): Promise<PathaoBulkOrderResponse> {\n try {\n const prepared = orders.map((order, i) => PathaoApiService.prepareOrder(order, `orders[${i}]: `));\n const response = await this.pathaoClient.post<PathaoBulkOrderResponse>(\n '/aladdin/api/v1/orders/bulk', { orders: prepared });\n return response.data;\n } catch (error: unknown) {\n throw this.toPathaoApiError(error, 'Failed to create bulk Pathao orders');\n }\n }\n\n // Validates an order and returns it with phones normalised to 01XXXXXXXXX,\n // so local checks catch what Pathao would reject with a 422 and what is\n // sent is what was validated.\n private static prepareOrder(order: PathaoOrderRequest, prefix = ''): PathaoOrderRequest {\n const fail = (message: string): never => {\n throw new PathaoApiError(`Validation failed: ${prefix}${message}`, { code: 400 });\n };\n const phone = PathaoApiService.normalizePhoneNumber(order.recipient_phone ?? '');\n if (!phone) fail('Invalid recipient_phone format');\n let secondary: string | null = null;\n if (order.recipient_secondary_phone) {\n secondary = PathaoApiService.normalizePhoneNumber(order.recipient_secondary_phone);\n if (!secondary) fail('Invalid recipient_secondary_phone format');\n }\n if (!PathaoApiService.validateRecipientName(order.recipient_name ?? '')) {\n fail('Invalid recipient_name (must be 3 to 100 characters)');\n }\n if (!PathaoApiService.validateAddress(order.recipient_address ?? '')) {\n fail('Invalid recipient_address (must be 10 to 220 characters)');\n }\n if (!PathaoApiService.validateWeight(order.item_weight)) {\n fail('Invalid item_weight (must be 0.5 to 10)');\n }\n return {\n ...order,\n recipient_phone: phone as string,\n ...(secondary ? { recipient_secondary_phone: secondary } : {}),\n };\n }\n\n /**\n * Normalise a Bangladeshi mobile number to 01XXXXXXXXX. Accepts +8801…,\n * 8801… and 01…, with spaces, dashes, dots or parentheses. Returns null for\n * anything that isn't a BD mobile number (operator prefixes 013–019).\n */\n static normalizePhoneNumber(phone: string): string | null {\n const digits = phone.replace(/[\\s\\-().]/g, '').replace(/^\\+/, '');\n const local = digits.startsWith('880') ? `0${digits.slice(3)}` : digits;\n return /^01[3-9]\\d{8}$/.test(local) ? local : null;\n }\n\n // Helper method to validate phone number\n static validatePhoneNumber(phone: string): boolean {\n return PathaoApiService.normalizePhoneNumber(phone) !== null;\n }\n\n // Helper method to format phone number\n static formatPhoneNumber(phone: string): string {\n const normalized = PathaoApiService.normalizePhoneNumber(phone);\n if (normalized) {\n return normalized;\n }\n throw new Error(\n 'Invalid phone number format. Must be a Bangladeshi mobile number (01XXXXXXXXX or +8801XXXXXXXXX)',\n );\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 return PathaoApiService.normalizePhoneNumber(phone) !== null;\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.circuitBreaker.failures = 0;\n this.circuitBreaker.isOpen = false;\n this.circuitBreaker.lastFailureTime = 0;\n }\n\n // Static factory method to create instance from environment variables\n static fromEnv(options?: PathaoClientOptions): PathaoApiService {\n const config: PathaoConfig = {\n clientId: process.env.PATHAO_CLIENT_ID || '',\n clientSecret: process.env.PATHAO_CLIENT_SECRET || '',\n username: process.env.PATHAO_USERNAME || '',\n password: process.env.PATHAO_PASSWORD || '',\n baseURL: process.env.PATHAO_BASE_URL || '',\n };\n const timeout = parseInt(process.env.PATHAO_TIMEOUT || '', 10);\n if (timeout > 0) {\n config.timeout = timeout;\n }\n return new PathaoApiService(config, options);\n }\n\n // Static factory method to create instance from configuration object\n static fromConfig(\n config: PathaoConfig,\n options?: PathaoClientOptions,\n ): PathaoApiService {\n return new PathaoApiService(config, options);\n }\n\n // Named constructor for sandbox environment\n static sandbox(credentials: Omit<PathaoConfig, 'baseURL'>, options?: PathaoClientOptions): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://courier-api-sandbox.pathao.com' },\n options,\n );\n }\n\n // Named constructor for production environment\n static production(credentials: Omit<PathaoConfig, 'baseURL'>, options?: PathaoClientOptions): PathaoApiService {\n return new PathaoApiService(\n { ...credentials, baseURL: 'https://api-hermes.pathao.com' },\n options,\n );\n }\n}\n\n","/**\n * Shared order lifecycle for Pathao webhook events and order-status slugs.\n *\n * Both describe the same parcel journey. `toLifecycleStatus` maps either one\n * to a small stable vocabulary, so consumers don't each keep a map of spelling\n * variants (\"Pickup Requested\", \"pickup-requested\", \"order.pickup-requested\").\n * Zero dependencies: safe to import from the webhooks entry point.\n */\n\nexport type PathaoLifecycleStatus =\n | 'created'\n | 'picked_up'\n | 'in_transit'\n | 'out_for_delivery'\n | 'delivered'\n | 'partial'\n | 'on_hold'\n /** On its way back. Not back yet: don't restock on this. */\n | 'returning'\n /** Back with the merchant. */\n | 'returned'\n | 'cancelled';\n\n/** Pathao's gateway allows 60 requests per rolling minute, with no Retry-After on its 429. */\nexport const PATHAO_RATE_LIMIT_PER_MINUTE = 60;\n\n/** getOrderStatus only finds orders for roughly this many days after creation. */\nexport const PATHAO_STATUS_RETENTION_DAYS = 90;\n\n// Keys are webhook event names without \"order.\", plus the kebab-cased status\n// labels Pathao uses elsewhere: order_status_slug values seen in production\n// (\"Pending\", \"In Transit\", \"Return\") and the labels in Pathao's own\n// WooCommerce plugin (\"Order_Created\", \"Return\", \"exchange\").\nconst LIFECYCLE: Readonly<Record<string, PathaoLifecycleStatus>> = {\n 'pending': 'created',\n 'created': 'created',\n 'order-created': 'created',\n 'pickup-requested': 'created',\n 'assigned-for-pickup': 'created',\n 'picked': 'picked_up',\n 'pickup-failed': 'on_hold',\n 'pickup-cancelled': 'cancelled',\n 'at-the-sorting-hub': 'in_transit',\n 'in-transit': 'in_transit',\n 'received-at-last-mile-hub': 'in_transit',\n 'assigned-for-delivery': 'out_for_delivery',\n 'delivered': 'delivered',\n 'partial-delivery': 'partial',\n 'delivery-failed': 'on_hold',\n 'on-hold': 'on_hold',\n // Marked for return; the parcel only comes back with returned-to-merchant.\n 'returned': 'returning',\n 'return': 'returning',\n 'return-id-created': 'returning',\n 'return-in-transit': 'returning',\n 'paid-return': 'returning',\n 'exchanged': 'returning',\n 'exchange': 'returning',\n 'returned-to-merchant': 'returned',\n};\n\n/**\n * Map a webhook event (`order.delivered`) or an order-status slug / display\n * string (`Pickup Requested`, `pickup_requested`) to a lifecycle status.\n * Returns `'unknown'` for anything that isn't a lifecycle change\n * (`order.updated`, `order.paid`, store events) or that this SDK hasn't seen.\n */\nexport function toLifecycleStatus(value: string): PathaoLifecycleStatus | 'unknown' {\n const key = value\n .trim()\n .toLowerCase()\n .replace(/^order\\./, '')\n .replace(/[\\s_]+/g, '-');\n return LIFECYCLE[key] ?? 'unknown';\n}\n\n/** Delivered, partially delivered, back with the merchant, or cancelled. */\nexport function isFinalLifecycleStatus(status: PathaoLifecycleStatus | 'unknown'): boolean {\n return status === 'delivered' || status === 'partial' || status === 'returned' || status === 'cancelled';\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 * - Config is passed explicitly, or read from PATHAO_* env vars by fromEnv()\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: DeliveryType; // Required - DeliveryType.NORMAL (48) or DeliveryType.ON_DEMAND (12)\n item_type: ItemType; // Required - ItemType.DOCUMENT (1) or ItemType.PARCEL (2)\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; // Only present if provided in the request\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: 0 | 1; // 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: ItemType;\n item_weight: number;\n delivery_type: DeliveryType;\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: 0 | 1; // 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; // Only present if provided at order creation\n order_status: string;\n order_status_slug: string;\n updated_at: string; // Format: \"YYYY-MM-DD HH:MM:SS\"\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; // Optional - defaults to 30000 if not provided\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/**\n * Delivery type codes defined by the Pathao API.\n * Values correspond to Pathao's internal delivery_type IDs.\n * @see https://developers.pathao.com - Order Creation endpoint\n */\nexport enum DeliveryType {\n /** Standard delivery (API value: 48) */\n NORMAL = 48,\n /** Same-day on-demand delivery (API value: 12) */\n ON_DEMAND = 12,\n}\n\n// Item types enum\nexport enum ItemType {\n DOCUMENT = 1,\n PARCEL = 2,\n}\n\n// Official Pathao Bulk Order Response\nexport interface PathaoBulkOrderResponse {\n message: string;\n type: string;\n code: number;\n data: boolean;\n}\n"]}