shipflow 0.3.2 → 0.4.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/README.md +22 -0
- package/dist/carriers/aymakan/adapter.d.ts +15 -29
- package/dist/carriers/aymakan/adapter.d.ts.map +1 -1
- package/dist/carriers/aymakan/index.js +19 -30
- package/dist/carriers/aymakan/index.js.map +3 -3
- package/dist/carriers/smsaexpress/adapter.d.ts +22 -0
- package/dist/carriers/smsaexpress/adapter.d.ts.map +1 -1
- package/dist/carriers/smsaexpress/index.js +55 -3
- package/dist/carriers/smsaexpress/index.js.map +3 -3
- package/dist/core/city-resolver.d.ts +44 -0
- package/dist/core/city-resolver.d.ts.map +1 -0
- package/dist/index-dfx6rbm2.js +36 -0
- package/dist/index-dfx6rbm2.js.map +10 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -9,6 +9,7 @@ Think EasyPost / Shippo, but purpose-built for Saudi Arabia and the GCC.
|
|
|
9
9
|
- **Unified types** — one `CreateShipmentInput`, one `TrackingResult`, one `WebhookEvent`, regardless of carrier
|
|
10
10
|
- **Tree-shakeable** — only the carriers you import are bundled
|
|
11
11
|
- **Auto-validation** — Valibot schemas validate every `createShipment()` call before it hits the network
|
|
12
|
+
- **Booking-time city validation (KSA)** — Saudi shipper/consignee cities are checked against the carrier's own city list before booking; typos fail fast with a field-scoped `ValidationError` instead of an opaque carrier rejection
|
|
12
13
|
- **Webhook parsing** — normalize incoming carrier webhooks into a single event format
|
|
13
14
|
- **Smart retries** — dependency-free retry with jittered backoff that honors carrier `Retry-After` on 429/503, surfacing a `RateLimitError` when the wait is too long to absorb inline
|
|
14
15
|
- **Minimal dependencies** — only [Valibot](https://github.com/fabian-hiller/valibot) for validation; uses the runtime's global `fetch` (Node 20+, Deno, Bun, edge/workers), no axios/node-fetch
|
|
@@ -353,6 +354,27 @@ import {
|
|
|
353
354
|
} from "shipflow";
|
|
354
355
|
```
|
|
355
356
|
|
|
357
|
+
### Booking-time city validation (KSA)
|
|
358
|
+
|
|
359
|
+
On `createShipment()` (including bulk and SMSA 2-way), Aymakan and SMSA
|
|
360
|
+
validate Saudi (`countryCode: "SA"`) shipper/consignee cities against the
|
|
361
|
+
carrier's **own** city list, fetched once and cached for an hour:
|
|
362
|
+
|
|
363
|
+
- A city that resolves (exact/fuzzy, Arabic or English — diacritics, hamza
|
|
364
|
+
variants and the `ال` article are normalized) is rewritten to the carrier's
|
|
365
|
+
canonical English name before booking.
|
|
366
|
+
- A city the carrier does not serve throws a `ValidationError` with
|
|
367
|
+
`field: "shipper.city"` or `field: "consignee.city"` **before** any booking
|
|
368
|
+
request is sent — the same booking would otherwise be rejected server-side
|
|
369
|
+
with an opaque carrier error.
|
|
370
|
+
- Matching never silently reroutes a distinct longer name to a shorter one
|
|
371
|
+
(e.g. `"Riyadh Al Khabra"` is never rewritten to `"Riyadh"`).
|
|
372
|
+
- If the carrier's city lookup is down, validation degrades to pass-through so
|
|
373
|
+
a lookup outage never blocks bookings; non-SA addresses are not validated.
|
|
374
|
+
|
|
375
|
+
Pickups intentionally stay lenient (an invalid pickup city only affects the
|
|
376
|
+
merchant's own pickup request).
|
|
377
|
+
|
|
356
378
|
## Error Handling
|
|
357
379
|
|
|
358
380
|
All errors extend `ShipFlowError` for easy catch-all handling:
|
|
@@ -23,14 +23,6 @@ export declare class AymakanAdapter extends BaseCarrierAdapter {
|
|
|
23
23
|
private citiesCacheTime;
|
|
24
24
|
/** Timestamp of the last failed /cities fetch attempt, if any */
|
|
25
25
|
private citiesFetchFailedAt;
|
|
26
|
-
/** Cache TTL: 1 hour */
|
|
27
|
-
private static readonly CITIES_CACHE_TTL;
|
|
28
|
-
/**
|
|
29
|
-
* After a failed /cities fetch, back off for this long before retrying so a
|
|
30
|
-
* carrier outage doesn't force every shipment/pickup call to re-attempt the
|
|
31
|
-
* multi-retry /cities request.
|
|
32
|
-
*/
|
|
33
|
-
private static readonly CITIES_FAILURE_COOLDOWN;
|
|
34
26
|
constructor(config: AymakanConfig);
|
|
35
27
|
protected getBaseUrl(): string;
|
|
36
28
|
/**
|
|
@@ -39,31 +31,25 @@ export declare class AymakanAdapter extends BaseCarrierAdapter {
|
|
|
39
31
|
*/
|
|
40
32
|
private ensureCitiesLoaded;
|
|
41
33
|
/**
|
|
42
|
-
*
|
|
43
|
-
* -
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
34
|
+
* Resolve a user-input city name to the valid Aymakan English city name via
|
|
35
|
+
* the shared matcher (see core/city-resolver.ts for the strategy). Lenient:
|
|
36
|
+
* falls back to the original input when nothing matches or the cities list
|
|
37
|
+
* is unavailable — used for pickups, where an invalid city only affects the
|
|
38
|
+
* merchant's own pickup request.
|
|
47
39
|
*/
|
|
48
|
-
private
|
|
40
|
+
private resolveCity;
|
|
49
41
|
/**
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
55
|
-
*
|
|
56
|
-
* 4. Match after stripping "ال" prefix from Arabic input
|
|
57
|
-
* 5. Candidate-contains-input match on English name (candidate name contains
|
|
58
|
-
* the input, e.g. "Riyadh" -> "Riyadh City"; requires input length >= 3).
|
|
59
|
-
* The reverse direction is intentionally excluded so a distinct longer
|
|
60
|
-
* city like "Riyadh Al Khabra" is never rerouted to "Riyadh".
|
|
61
|
-
*
|
|
62
|
-
* Falls back to the original input if no match is found.
|
|
42
|
+
* Strict variant used for shipment creation: when Aymakan's own city list is
|
|
43
|
+
* loaded and the input matches nothing in it, the booking would be rejected
|
|
44
|
+
* by the API anyway — fail fast with a clear, field-scoped error instead of
|
|
45
|
+
* an opaque carrier 400. When the list is unavailable (fetch failed /
|
|
46
|
+
* cooldown), fall back to pass-through so a /cities outage never blocks
|
|
47
|
+
* shipment creation.
|
|
63
48
|
*/
|
|
64
|
-
private
|
|
49
|
+
private resolveCityStrict;
|
|
65
50
|
/**
|
|
66
|
-
* Resolve city names in a CreateShipmentInput to valid Aymakan city names
|
|
51
|
+
* Resolve city names in a CreateShipmentInput to valid Aymakan city names,
|
|
52
|
+
* rejecting cities Aymakan does not serve (strict — see resolveCityStrict).
|
|
67
53
|
*/
|
|
68
54
|
private resolveCitiesInInput;
|
|
69
55
|
protected executeCreateShipment(input: CreateShipmentInput): Promise<Shipment>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../src/carriers/aymakan/adapter.ts"],"names":[],"mappings":"AACA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../src/carriers/aymakan/adapter.ts"],"names":[],"mappings":"AACA;;;GAGG;AAaH,OAAO,KAAK,EACV,OAAO,EACP,aAAa,EACb,IAAI,EACJ,mBAAmB,EACnB,eAAe,EACf,MAAM,EACN,aAAa,EACb,QAAQ,EACR,QAAQ,EACR,cAAc,EACd,aAAa,EACb,YAAY,EACb,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,SAAS,CAAC;AAsG7C,MAAM,WAAW,aAAc,SAAQ,aAAa;IAClD,WAAW,EAAE;QACX,MAAM,EAAE,MAAM,CAAC;KAChB,CAAC;CACH;AAED,qBAAa,cAAe,SAAQ,kBAAkB;IACpD,QAAQ,CAAC,IAAI,aAAa;IAC1B,QAAQ,CAAC,kBAAkB,WAAwC;IAEnE,OAAO,CAAC,IAAI,CAAa;IAEzB;;;OAGG;IACH,OAAO,CAAC,QAAQ,CAAC,SAAS,CAA6C;IAEvE,0DAA0D;IAC1D,OAAO,CAAC,WAAW,CAAuB;IAC1C,OAAO,CAAC,eAAe,CAAK;IAC5B,iEAAiE;IACjE,OAAO,CAAC,mBAAmB,CAAK;gBAEpB,MAAM,EAAE,aAAa;IAWjC,SAAS,CAAC,UAAU,IAAI,MAAM;IAU9B;;;OAGG;YACW,kBAAkB;IAwBhC;;;;;;OAMG;IACH,OAAO,CAAC,WAAW;IAOnB;;;;;;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A8BtC,SAAS,IAAI,OAAO,CAAC,IAAI,EAAE,CAAC;IAgB5B,mBAAmB,IAAI,OAAO,CAClC;QACE,EAAE,EAAE,MAAM,CAAC;QACX,IAAI,EAAE,MAAM,CAAC;QACb,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,MAAM,CAAC;QAClB,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,EAAE,CACJ;IAsCK,qBAAqB,CACzB,OAAO,EAAE,eAAe,GACvB,OAAO,CAAC,eAAe,CAAC;IA+BrB,oBAAoB,IAAI,OAAO,CAAC,eAAe,EAAE,CAAC;IAmClD,qBAAqB,CACzB,EAAE,EAAE,MAAM,EACV,OAAO,EAAE,OAAO,CAAC,eAAe,CAAC,GAChC,OAAO,CAAC,eAAe,CAAC;IAyCrB,qBAAqB,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAazD,YAAY,CACV,OAAO,EAAE,OAAO,EAChB,OAAO,CAAC,EAAE;QACR,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACjC,WAAW,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACrC,MAAM,CAAC,EAAE,aAAa,CAAC;KACxB,GACA,YAAY;CAGhB"}
|
|
@@ -1,3 +1,8 @@
|
|
|
1
|
+
import {
|
|
2
|
+
CITIES_CACHE_TTL,
|
|
3
|
+
CITIES_FAILURE_COOLDOWN,
|
|
4
|
+
findCityMatch
|
|
5
|
+
} from "../../index-dfx6rbm2.js";
|
|
1
6
|
import {
|
|
2
7
|
APIError,
|
|
3
8
|
BaseCarrierAdapter,
|
|
@@ -354,8 +359,6 @@ class AymakanAdapter extends BaseCarrierAdapter {
|
|
|
354
359
|
citiesCache = null;
|
|
355
360
|
citiesCacheTime = 0;
|
|
356
361
|
citiesFetchFailedAt = 0;
|
|
357
|
-
static CITIES_CACHE_TTL = 60 * 60 * 1000;
|
|
358
|
-
static CITIES_FAILURE_COOLDOWN = 60 * 1000;
|
|
359
362
|
constructor(config) {
|
|
360
363
|
super(config);
|
|
361
364
|
this.http = new HttpClient({
|
|
@@ -371,10 +374,10 @@ class AymakanAdapter extends BaseCarrierAdapter {
|
|
|
371
374
|
}
|
|
372
375
|
async ensureCitiesLoaded() {
|
|
373
376
|
const now = Date.now();
|
|
374
|
-
if (this.citiesCache && now - this.citiesCacheTime <
|
|
377
|
+
if (this.citiesCache && now - this.citiesCacheTime < CITIES_CACHE_TTL) {
|
|
375
378
|
return;
|
|
376
379
|
}
|
|
377
|
-
if (now - this.citiesFetchFailedAt <
|
|
380
|
+
if (now - this.citiesFetchFailedAt < CITIES_FAILURE_COOLDOWN) {
|
|
378
381
|
if (!this.citiesCache)
|
|
379
382
|
this.citiesCache = [];
|
|
380
383
|
return;
|
|
@@ -388,47 +391,33 @@ class AymakanAdapter extends BaseCarrierAdapter {
|
|
|
388
391
|
this.citiesCache = [];
|
|
389
392
|
}
|
|
390
393
|
}
|
|
391
|
-
static normalizeArabic(text) {
|
|
392
|
-
return text.trim().replace(/[\u064B-\u065F\u0670]/g, "").replace(/[أإآ]/g, "ا").replace(/ة/g, "ه");
|
|
393
|
-
}
|
|
394
394
|
resolveCity(inputCity) {
|
|
395
395
|
if (!this.citiesCache || this.citiesCache.length === 0)
|
|
396
396
|
return inputCity;
|
|
397
397
|
const trimmed = inputCity.trim();
|
|
398
398
|
if (!trimmed)
|
|
399
399
|
return inputCity;
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
const normalizedAr = this.citiesCache.find((c) => c.nameAr && AymakanAdapter.normalizeArabic(c.nameAr) === normalizedInput);
|
|
409
|
-
if (normalizedAr)
|
|
410
|
-
return normalizedAr.nameEn;
|
|
411
|
-
const withoutAl = normalizedInput.startsWith("ال") ? normalizedInput.slice(2) : `ال${normalizedInput}`;
|
|
412
|
-
const alMatch = this.citiesCache.find((c) => c.nameAr && AymakanAdapter.normalizeArabic(c.nameAr) === withoutAl);
|
|
413
|
-
if (alMatch)
|
|
414
|
-
return alMatch.nameEn;
|
|
415
|
-
if (lower.length >= 3) {
|
|
416
|
-
const containsEn = this.citiesCache.find((c) => c.nameEn.toLowerCase().includes(lower));
|
|
417
|
-
if (containsEn)
|
|
418
|
-
return containsEn.nameEn;
|
|
400
|
+
return findCityMatch(trimmed, this.citiesCache)?.nameEn ?? trimmed;
|
|
401
|
+
}
|
|
402
|
+
resolveCityStrict(inputCity, field) {
|
|
403
|
+
if (!this.citiesCache || this.citiesCache.length === 0)
|
|
404
|
+
return inputCity;
|
|
405
|
+
const match = findCityMatch(inputCity, this.citiesCache);
|
|
406
|
+
if (!match) {
|
|
407
|
+
throw new ValidationError(`Unknown ${field.replace(".city", "")} city "${inputCity}": not in Aymakan's supported city list`, { field });
|
|
419
408
|
}
|
|
420
|
-
return
|
|
409
|
+
return match.nameEn;
|
|
421
410
|
}
|
|
422
411
|
resolveCitiesInInput(input) {
|
|
423
412
|
return {
|
|
424
413
|
...input,
|
|
425
414
|
shipper: {
|
|
426
415
|
...input.shipper,
|
|
427
|
-
city: this.
|
|
416
|
+
city: this.resolveCityStrict(input.shipper.city, "shipper.city")
|
|
428
417
|
},
|
|
429
418
|
consignee: {
|
|
430
419
|
...input.consignee,
|
|
431
|
-
city: this.
|
|
420
|
+
city: this.resolveCityStrict(input.consignee.city, "consignee.city")
|
|
432
421
|
}
|
|
433
422
|
};
|
|
434
423
|
}
|
|
@@ -724,4 +713,4 @@ export {
|
|
|
724
713
|
AymakanAdapter
|
|
725
714
|
};
|
|
726
715
|
|
|
727
|
-
//# debugId=
|
|
716
|
+
//# debugId=C3DBDA3066CA8E3964756E2164756E21
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"// file: src/carriers/aymakan/services.ts\n/**\n * Aymakan Service Type Codes\n * Use these constants for type-safe service selection.\n */\n\nexport const AymakanService = {\n /** Default ecommerce service */\n ECOMMERCE: \"ONP\",\n /** Documents or banking docs service */\n DOCUMENTS: \"DOC\",\n /** Same day delivery service */\n SAME_DAY: \"SDD\",\n /** Reverse pickup service */\n REVERSE_PICKUP: \"RVP\",\n /** Exchange service */\n EXCHANGE: \"EXH\",\n /** Lockers service */\n LOCKERS: \"LOC\",\n /** Heavy and bulky service */\n HEAVY: \"BLK\",\n /** Pallet service */\n PALLET: \"PLT\",\n /** Import express (International) */\n IMPORT_EXPRESS: \"IPX\",\n /** Export express (International) */\n EXPORT_EXPRESS: \"EPX\",\n} as const;\n\nexport type AymakanServiceType =\n (typeof AymakanService)[keyof typeof AymakanService];\n\n/**\n * Aymakan Status Codes\n * Maps carrier-specific codes to our unified status.\n */\nexport const AymakanStatusCodes = {\n // Core lifecycle\n \"AY-0001\": \"created\", // Shipment created / AWB created at origin\n \"AY-0002\": \"picked_up\", // Collected from collection point\n \"AY-0003\": \"at_warehouse\", // Received at hub\n \"AY-0004\": \"out_for_delivery\", // Out for final destination\n \"AY-0005\": \"delivered\", // Delivered to customer\n \"AY-0006\": \"exception\", // Not delivered (failed attempt)\n\n // Warehouse / transfer\n \"AY-0026\": \"at_warehouse\", // Received at [City] Warehouse\n \"AY-0027\": \"in_transit\", // Transferred to destination city\n \"AY-0028\": \"in_transit\", // In transit between hubs\n\n // Pending / rescheduled (delivery was attempted but rescheduled)\n \"AY-0032\": \"pending\", // Pending — future delivery / rescheduled\n\n // Terminal states\n \"AY-0007\": \"returned\", // Returned to shipper\n \"AY-0008\": \"cancelled\", // Cancelled\n \"AY-0009\": \"returned\", // Return to origin\n} as const;\n",
|
|
6
6
|
"// file: src/carriers/aymakan/mappers.ts\n/**\n * Aymakan Data Mappers\n * Transform between unified ShipFlow types and Aymakan API formats.\n */\n\nimport { ValidationError, WebhookVerificationError } from \"../../core/errors\";\nimport type {\n Address,\n City,\n CreateShipmentInput,\n CustomerAddress,\n Pickup,\n PickupRequest,\n Shipment,\n ShipmentStatus,\n TrackingEvent,\n TrackingResult,\n WebhookConfig,\n WebhookEvent,\n} from \"../../core/types\";\nimport { AymakanService, AymakanStatusCodes } from \"./services\";\nimport type {\n AymakanAddressRequest,\n AymakanCity,\n AymakanCreateShipmentRequest,\n AymakanNationalAddressRequest,\n AymakanPickupRequest,\n AymakanPickupResponse,\n AymakanShipmentResponse,\n AymakanTrackingEvent,\n AymakanTrackShipmentData,\n AymakanWebhookPayload,\n} from \"./types\";\n\n// ============================================================================\n// STATUS MAPPING\n// ============================================================================\n\nexport function mapAymakanStatus(statusCode: string): ShipmentStatus | undefined {\n const mapped =\n AymakanStatusCodes[statusCode as keyof typeof AymakanStatusCodes];\n return mapped as ShipmentStatus | undefined;\n}\n\n/**\n * The /track endpoint's top-level `status` is a human-readable English label\n * (e.g. \"Received at Warehouse\") rather than an AY code, so `mapAymakanStatus`\n * can never resolve it. This map recovers a real unified status from that label\n * when there are no tracking events to derive it from. Keys are compared\n * case-insensitively.\n */\nconst AymakanStatusLabels: Record<string, ShipmentStatus> = {\n \"awb created at origin\": \"created\",\n \"shipment created\": \"created\",\n \"collected from collection point\": \"picked_up\",\n collected: \"picked_up\",\n \"picked up\": \"picked_up\",\n \"received at hub\": \"at_warehouse\",\n \"received at warehouse\": \"at_warehouse\",\n \"out for delivery\": \"out_for_delivery\",\n \"out for final destination\": \"out_for_delivery\",\n delivered: \"delivered\",\n \"shipment is delivered\": \"delivered\",\n \"transferred to destination city\": \"in_transit\",\n \"in transit\": \"in_transit\",\n \"not delivered\": \"exception\",\n \"failed attempt\": \"exception\",\n pending: \"pending\",\n \"future delivery\": \"pending\",\n returned: \"returned\",\n \"returned to shipper\": \"returned\",\n \"return to origin\": \"returned\",\n cancelled: \"cancelled\",\n canceled: \"cancelled\",\n};\n\n/**\n * Map a human-readable Aymakan status label to a unified status.\n * Returns undefined for unrecognized labels.\n */\nexport function mapAymakanStatusLabel(\n label: string,\n): ShipmentStatus | undefined {\n return AymakanStatusLabels[label.trim().toLowerCase()];\n}\n\n// ============================================================================\n// REQUEST MAPPERS\n// ============================================================================\n\nfunction mapNationalAddress(\n addr?: Address[\"nationalAddress\"],\n): AymakanNationalAddressRequest | undefined {\n if (!addr) return undefined;\n return {\n short_code: addr.shortCode,\n building_number: addr.buildingNumber,\n street_name: addr.streetName,\n district: addr.district,\n additional_number: addr.additionalNumber,\n };\n}\n\n/** Strip non-digit characters from phone numbers (Aymakan requires digits only) */\nexport function sanitizePhone(phone: string): string {\n return phone.replace(/\\D/g, '');\n}\n\n/** Set of valid Aymakan service type codes */\nconst VALID_AYMAKAN_SERVICE_TYPES = new Set(\n Object.values(AymakanService) as string[],\n);\n\n/**\n * Resolve service type to a valid Aymakan code.\n * Returns undefined for unknown values so the API uses its default (ONP/ecommerce).\n */\nfunction resolveServiceType(serviceType?: string): string | undefined {\n if (!serviceType) return undefined;\n if (VALID_AYMAKAN_SERVICE_TYPES.has(serviceType)) return serviceType;\n return undefined;\n}\n\nexport function mapCreateShipmentRequest(\n input: CreateShipmentInput,\n): AymakanCreateShipmentRequest {\n const firstParcel = input.parcels[0];\n const totalPieces = input.parcels.reduce((sum, p) => sum + p.pieces, 0);\n const totalWeight = input.parcels.reduce(\n (sum, p) =>\n sum +\n (p.weight.unit === \"lb\" ? p.weight.value * 0.453592 : p.weight.value),\n 0,\n );\n const totalItems = input.parcels.reduce(\n (sum, p) => sum + (p.itemsCount ?? p.pieces),\n 0,\n );\n\n // COD (collected from the buyer on delivery) and declared/customs value are\n // distinct concepts and must never be conflated. Declared value comes solely\n // from input.declaredValue; COD comes solely from input.cod.\n const codEnabled = input.cod?.enabled === true;\n const declaredValueCurrency = input.declaredValue?.currency ?? \"SAR\";\n\n return {\n requested_by: input.options?.requestedBy ?? input.shipper.name,\n declared_value: input.declaredValue?.amount ?? 0,\n declared_value_currency: declaredValueCurrency,\n reference: input.reference,\n customer_tracking: input.options?.customerTracking,\n service_type: resolveServiceType(input.serviceType),\n is_cod: codEnabled ? 1 : 0,\n cod_amount: codEnabled ? input.cod?.amount : undefined,\n fulfilment_customer_name: input.options?.fulfilmentCustomerName,\n // Top-level currency prefers the COD currency when COD is enabled (it's the\n // amount actually collected), otherwise the declared-value currency.\n currency: codEnabled\n ? (input.cod?.currency ?? \"SAR\")\n : declaredValueCurrency,\n\n // Delivery (consignee)\n delivery_name: input.consignee.name,\n delivery_email: input.consignee.email,\n delivery_city: input.consignee.city,\n delivery_address: input.consignee.line1,\n delivery_neighbourhood:\n input.consignee.neighbourhood ?? input.consignee.state,\n delivery_postcode: input.consignee.postalCode,\n delivery_country: input.consignee.countryCode,\n delivery_phone: sanitizePhone(input.consignee.phone),\n delivery_description: input.consignee.description,\n delivery_national_address: mapNationalAddress(\n input.consignee.nationalAddress,\n ),\n\n // Collection (shipper)\n collection_name: input.shipper.company ?? input.shipper.name,\n collection_email: input.shipper.email,\n collection_city: input.shipper.city,\n collection_address: input.shipper.line1,\n collection_neighbourhood:\n input.shipper.neighbourhood ?? input.shipper.state,\n collection_postcode: input.shipper.postalCode,\n collection_country: input.shipper.countryCode,\n collection_phone: sanitizePhone(input.shipper.phone),\n collection_description: input.shipper.description,\n collection_national_address: mapNationalAddress(\n input.shipper.nationalAddress,\n ),\n\n // Parcel details\n weight: totalWeight,\n length: firstParcel?.dimensions?.length,\n width: firstParcel?.dimensions?.width,\n height: firstParcel?.dimensions?.height,\n pieces: totalPieces,\n items_count: totalItems,\n is_insured: input.options?.isInsured ? 1 : 0,\n\n // International\n international_metadata: input.options?.internationalMetadata\n ? {\n document_id: input.options.internationalMetadata.documentId,\n tax_identification_number: input.options.internationalMetadata.taxId,\n invoice_number: input.options.internationalMetadata.invoiceNumber,\n invoice_date: input.options.internationalMetadata.invoiceDate,\n }\n : undefined,\n };\n}\n\nexport function mapPickupRequest(input: PickupRequest): AymakanPickupRequest {\n return {\n reference: input.trackingNumbers?.[0],\n pickup_date: input.date,\n time_slot: input.timeSlot,\n city: input.city,\n contact_name: input.contactName,\n contact_phone: input.contactPhone,\n address: input.address,\n shipments: input.shipmentCount,\n };\n}\n\nexport function mapCustomerAddressRequest(\n addr: CustomerAddress,\n): AymakanAddressRequest {\n return {\n title: addr.title,\n name: addr.name,\n email: addr.email,\n city: addr.city,\n address: addr.address,\n neighbourhood: addr.neighbourhood,\n postcode: addr.postalCode ?? \"\",\n phone: addr.phone,\n description: addr.description ?? \"\",\n };\n}\n\n// ============================================================================\n// RESPONSE MAPPERS\n// ============================================================================\n\nexport function mapShipmentResponse(data: AymakanShipmentResponse): Shipment {\n // Parse cod_amount: API returns string like \"150.00\", we need number\n const codAmount =\n data.cod_amount != null\n ? typeof data.cod_amount === \"string\"\n ? parseFloat(data.cod_amount)\n : data.cod_amount\n : undefined;\n\n return {\n carrier: \"aymakan\",\n trackingNumber: data.tracking_number,\n customerTracking: data.customer_tracking ?? undefined,\n reference: data.reference ?? undefined,\n status: mapAymakanStatus(data.status) ?? \"created\",\n statusLabel: data.status_label,\n labelUrl: data.label || undefined,\n pdfLabelUrl: data.pdf_label || undefined,\n // Emit a defined COD amount whenever we parsed a real number. A COD of 0\n // means \"no cash collected\", so surface it as undefined, but never let NaN\n // logic on a falsy 0 drop an otherwise valid value.\n codAmount:\n codAmount != null && !Number.isNaN(codAmount) && codAmount !== 0\n ? codAmount\n : undefined,\n declaredValue: data.declared_value,\n currency: data.currency,\n createdAt: new Date(data.created_at),\n raw: data,\n };\n}\n\n/**\n * Parse an Aymakan timestamp. Top-level fields are ISO 8601 (with `T`/`Z`), but\n * `tracking_info[].created_at` values are space-separated \"YYYY-MM-DD HH:MM:SS\"\n * strings in Saudi local time (UTC+3) with no timezone marker. `new Date()`\n * would parse those in the host's local timezone, so normalize to +03:00.\n */\nfunction parseAymakanDate(value: string): Date {\n if (/[TZ]|[+-]\\d{2}:?\\d{2}$/.test(value)) {\n return new Date(value);\n }\n return new Date(`${value.replace(\" \", \"T\")}+03:00`);\n}\n\nexport function mapTrackingEvent(event: AymakanTrackingEvent): TrackingEvent {\n return {\n timestamp: parseAymakanDate(event.created_at),\n statusCode: event.status_code,\n status: mapAymakanStatus(event.status_code) ?? \"unknown\",\n description: event.description,\n descriptionArabic: event.description_ar ?? undefined,\n };\n}\n\nexport function mapTrackingResult(\n data: AymakanTrackShipmentData,\n): TrackingResult {\n const events = (data.tracking_info ?? []).map(mapTrackingEvent);\n\n // The top-level `status` field is a human-readable label on the /track\n // endpoint (e.g. \"Received at Warehouse\") and an AY code on /by_reference.\n // Derive the unified status from the most recent tracking event (whose\n // status_code is always an AY code), falling back to mapping the top-level\n // status. The fallback tries the AY-code map first (handles /by_reference)\n // and then the human-label map (handles /track), so a real state is recovered\n // even when there are no events, then \"unknown\".\n const sortedEvents = events.length\n ? [...events].sort((a, b) => b.timestamp.getTime() - a.timestamp.getTime())\n : [];\n // Some event codes aren't in AymakanStatusCodes and map to \"unknown\" — scan\n // back through older events (newest-first) for the most recent one we can\n // actually recognize, instead of giving up as soon as the latest is unknown.\n const mostRecentRecognizedEvent = sortedEvents.find(\n (e) => e.status !== \"unknown\",\n );\n let status: ShipmentStatus;\n if (mostRecentRecognizedEvent) {\n status = mostRecentRecognizedEvent.status;\n } else {\n // No recognizable event (or none at all) — derive from the top-level\n // status: AY-code map first (/by_reference), then human-label map (/track),\n // else \"unknown\".\n status =\n mapAymakanStatus(data.status) ??\n mapAymakanStatusLabel(data.status) ??\n \"unknown\";\n }\n\n return {\n trackingNumber: data.tracking_number,\n carrier: \"aymakan\",\n reference: data.reference ?? undefined,\n status,\n statusLabel: data.status_label,\n events,\n deliveryDate: data.delivery_date ? new Date(data.delivery_date) : undefined,\n pickupDate: data.pickup_date ? new Date(data.pickup_date) : undefined,\n receivedAt: data.received_at ? new Date(data.received_at) : undefined,\n codAmount: data.cod_amount\n ? Number.isNaN(parseFloat(data.cod_amount))\n ? undefined\n : parseFloat(data.cod_amount)\n : undefined,\n weight: Number.isNaN(parseFloat(data.weight))\n ? undefined\n : parseFloat(data.weight),\n pieces: data.pieces,\n raw: data,\n };\n}\n\nexport function mapCity(city: AymakanCity): City {\n return {\n nameEn: city.city_en,\n nameAr: city.city_ar,\n };\n}\n\nexport function mapPickupResponse(data: AymakanPickupResponse[\"data\"]): Pickup {\n return {\n id: data.id,\n carrier: \"aymakan\",\n status: (\n [\"pending\", \"processing\", \"completed\", \"cancelled\"] as const\n ).includes(data.status as Pickup[\"status\"])\n ? (data.status as Pickup[\"status\"])\n : \"pending\",\n date: data.pickup_date,\n timeSlot: data.time_slot,\n city: data.city,\n contactName: data.contact_name,\n contactPhone: data.contact_phone,\n address: data.address,\n shipmentCount: data.shipments,\n warehouseId: data.warehouse_id,\n warehouseName: data.warehouse_name,\n createdAt: new Date(data.created_at),\n raw: data,\n };\n}\n\n// ============================================================================\n// WEBHOOK MAPPER\n// ============================================================================\n\n/**\n * Timing-safe string comparison to prevent timing attacks on auth tokens.\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n const encoder = new TextEncoder();\n const bufA = encoder.encode(a);\n const bufB = encoder.encode(b);\n if (bufA.byteLength !== bufB.byteLength) return false;\n // Use crypto.subtle-compatible constant-time compare\n let mismatch = 0;\n for (let i = 0; i < bufA.byteLength; i++) {\n mismatch |= bufA[i]! ^ bufB[i]!;\n }\n return mismatch === 0;\n}\n\nexport function parseAymakanWebhook(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n): WebhookEvent {\n const { headers = {}, queryParams = {}, config } = options ?? {};\n\n // Verify auth FIRST, before inspecting the payload shape. These checks depend\n // only on `options` (headers/queryParams/config), so an unauthenticated caller\n // is rejected before any payload-validation detail can leak back to them.\n\n // Verify auth via header (case-insensitive lookup, timing-safe comparison)\n if (config?.authHeader && config?.authValue) {\n const lowerKey = config.authHeader.toLowerCase();\n const headerValue = Object.entries(headers).find(\n ([k]) => k.toLowerCase() === lowerKey,\n )?.[1];\n if (!headerValue || !timingSafeEqual(headerValue, config.authValue)) {\n throw new WebhookVerificationError(\"Invalid webhook auth header\", {\n carrier: \"aymakan\",\n });\n }\n }\n\n // Verify auth via query param (timing-safe comparison)\n if (config?.authQueryParam && config?.authQueryValue) {\n const paramValue = queryParams[config.authQueryParam];\n if (!paramValue || !timingSafeEqual(paramValue, config.authQueryValue)) {\n throw new WebhookVerificationError(\"Invalid webhook auth query param\", {\n carrier: \"aymakan\",\n });\n }\n }\n\n // Validate required fields (only after auth has passed)\n if (\n !payload ||\n typeof payload !== \"object\" ||\n !(\"tracking_number\" in payload) ||\n !(\"status\" in payload)\n ) {\n throw new ValidationError(\n \"Invalid webhook payload: missing required fields\",\n {\n raw: payload,\n },\n );\n }\n\n const data = payload as AymakanWebhookPayload;\n\n const eventType = data.event ?? \"status_update\";\n\n // Validate timestamp\n const timestamp = new Date(data.date_time);\n if (Number.isNaN(timestamp.getTime())) {\n throw new ValidationError(\n \"Invalid webhook payload: invalid date_time value\",\n { raw: data.date_time },\n );\n }\n\n return {\n carrier: \"aymakan\",\n eventType,\n trackingNumber: data.tracking_number,\n reference: data.reference ?? undefined,\n // `status` is a core field present on every webhook regardless of event\n // type, so map it even for weight_update events. Consumers can still branch\n // on `eventType` to detect weight updates.\n status: mapAymakanStatus(data.status) ?? \"unknown\",\n statusCode: data.status,\n statusLabel: data.status_label,\n reasonCode: data.reason_code ?? undefined,\n reasonLabel: data.reason_en ?? undefined,\n timestamp,\n raw: data,\n };\n}\n",
|
|
7
|
-
"// file: src/carriers/aymakan/adapter.ts\n/**\n * Aymakan Carrier Adapter\n * Full implementation of the CarrierAdapter interface for Aymakan API.\n */\n\nimport { APIError, ValidationError } from \"../../core/errors\";\nimport { HttpClient } from \"../../core/http\";\nimport {\n validateCreateShipmentInput,\n validatePickupRequest,\n} from \"../../core/schemas\";\nimport type {\n Address,\n CarrierConfig,\n City,\n CreateShipmentInput,\n CustomerAddress,\n Pickup,\n PickupRequest,\n Shipment,\n TimeSlot,\n TrackingResult,\n WebhookConfig,\n WebhookEvent,\n} from \"../../core/types\";\nimport { BaseCarrierAdapter } from \"../base\";\nimport {\n mapCity,\n mapCreateShipmentRequest,\n mapCustomerAddressRequest,\n mapPickupRequest,\n mapPickupResponse,\n mapShipmentResponse,\n mapTrackingResult,\n parseAymakanWebhook,\n sanitizePhone,\n} from \"./mappers\";\nimport type {\n AymakanAddressResponse,\n AymakanCancelResponse,\n AymakanCitiesResponse,\n AymakanCreateShipmentResponse,\n AymakanPickupResponse,\n AymakanShipmentResponse,\n AymakanTrackResponse,\n} from \"./types\";\n\nconst AYMAKAN_SANDBOX_URL = \"https://dev-api.aymakan.com.sa/v2\";\nconst AYMAKAN_PRODUCTION_URL = \"https://api.aymakan.net/v2\";\n\n/**\n * Aymakan returns logical errors inside a fake-200 envelope (HTTP 200 with an\n * error flag/message in the body). Without an extractor these are swallowed —\n * e.g. cancel endpoints would return `success: undefined` and the adapter would\n * report `false` with no reason. This extractor surfaces those as APIError.\n *\n * Recognised error shapes (all on a 200 body):\n * - `{ error: true, ... }` → Laravel/Aymakan error flag\n * - `{ success: false, ... }` → explicit failure flag\n * - `{ message }` / `{ response }` → human-readable error text\n * - `{ errors: { field: [...] } }` → Laravel field validation errors\n *\n * A bare `{ message }` is NOT treated as an error on its own (many success\n * envelopes carry a `message`); we only flag when `error`/`success:false` is\n * present, or validation `errors` exist.\n */\n/**\n * Pull a human-readable message out of an object-shaped error value, e.g.\n * `{ error: { message: \"...\" } }` or `{ error: { response: \"...\" } }`.\n */\nfunction extractNestedMessage(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (typeof obj.message === \"string\") return obj.message;\n if (typeof obj.response === \"string\") return obj.response;\n }\n return undefined;\n}\n\n/** Join Laravel-style `{ field: [msg, ...] }` validation errors into one string. */\nfunction joinFieldErrors(errors: Record<string, unknown>): string | undefined {\n const parts = Object.values(errors)\n .flat()\n .filter((v): v is string => typeof v === \"string\");\n return parts.length ? parts.join(\"; \") : undefined;\n}\n\nfunction aymakanErrorExtractor(json: unknown): {\n hasError: boolean;\n message?: string;\n errors?: Record<string, string[]>;\n} {\n if (!json || typeof json !== \"object\") {\n return { hasError: false };\n }\n const obj = json as Record<string, unknown>;\n\n const hasValidationErrors =\n !!obj.errors &&\n typeof obj.errors === \"object\" &&\n Object.keys(obj.errors as object).length > 0;\n const hasError = obj.error === true || obj.success === false || hasValidationErrors;\n\n if (!hasError) {\n return { hasError: false };\n }\n\n const message =\n (typeof obj.message === \"string\" && obj.message) ||\n (typeof obj.response === \"string\" && obj.response) ||\n (typeof obj.error === \"string\" && obj.error) ||\n extractNestedMessage(obj.error) ||\n (hasValidationErrors\n ? joinFieldErrors(obj.errors as Record<string, string[]>)\n : undefined) ||\n undefined;\n\n return {\n hasError: true,\n message,\n errors: hasValidationErrors\n ? (obj.errors as Record<string, string[]>)\n : undefined,\n };\n}\n\nexport interface AymakanConfig extends CarrierConfig {\n credentials: {\n apiKey: string;\n };\n}\n\nexport class AymakanAdapter extends BaseCarrierAdapter {\n readonly name = \"aymakan\";\n readonly supportedCountries = [\"SA\", \"AE\", \"BH\", \"KW\", \"OM\", \"QA\"];\n\n private http: HttpClient;\n\n /**\n * Shared options applied to every Aymakan http call so fake-200 error\n * envelopes surface as APIError instead of being silently swallowed.\n */\n private readonly errorOpts = { errorExtractor: aymakanErrorExtractor };\n\n /** Cached Aymakan cities list for city name resolution */\n private citiesCache: City[] | null = null;\n private citiesCacheTime = 0;\n /** Timestamp of the last failed /cities fetch attempt, if any */\n private citiesFetchFailedAt = 0;\n /** Cache TTL: 1 hour */\n private static readonly CITIES_CACHE_TTL = 60 * 60 * 1000;\n /**\n * After a failed /cities fetch, back off for this long before retrying so a\n * carrier outage doesn't force every shipment/pickup call to re-attempt the\n * multi-retry /cities request.\n */\n private static readonly CITIES_FAILURE_COOLDOWN = 60 * 1000;\n\n constructor(config: AymakanConfig) {\n super(config);\n this.http = new HttpClient({\n baseUrl: this.getBaseUrl(),\n carrier: \"aymakan\",\n headers: {\n Authorization: config.credentials.apiKey,\n },\n });\n }\n\n protected getBaseUrl(): string {\n return this.config.mode === \"production\"\n ? AYMAKAN_PRODUCTION_URL\n : AYMAKAN_SANDBOX_URL;\n }\n\n // =========================================================================\n // CITY RESOLUTION\n // =========================================================================\n\n /**\n * Load cities list from Aymakan API and cache it.\n * Silently falls back to empty list on failure so shipments can still be attempted.\n */\n private async ensureCitiesLoaded(): Promise<void> {\n const now = Date.now();\n if (\n this.citiesCache &&\n now - this.citiesCacheTime < AymakanAdapter.CITIES_CACHE_TTL\n ) {\n return;\n }\n // A recent failure is still in its cooldown window — skip re-attempting\n // the /cities fetch and fall back to whatever cache we have (possibly\n // empty), so an outage never hard-blocks shipment/pickup creation.\n if (now - this.citiesFetchFailedAt < AymakanAdapter.CITIES_FAILURE_COOLDOWN) {\n if (!this.citiesCache) this.citiesCache = [];\n return;\n }\n try {\n this.citiesCache = await this.getCities();\n this.citiesCacheTime = now;\n } catch {\n this.citiesFetchFailedAt = now;\n if (!this.citiesCache) this.citiesCache = [];\n }\n }\n\n /**\n * Normalize Arabic text for comparison:\n * - Strip diacritics (tashkeel)\n * - Normalize alef variants (أ إ آ → ا)\n * - Normalize taa marbuta (ة → ه)\n * - Trim whitespace\n */\n private static normalizeArabic(text: string): string {\n return text\n .trim()\n .replace(/[\\u064B-\\u065F\\u0670]/g, \"\") // strip tashkeel\n .replace(/[أإآ]/g, \"ا\") // normalize alef\n .replace(/ة/g, \"ه\"); // normalize taa marbuta\n }\n\n /**\n * Resolve a user-input city name to the valid Aymakan English city name.\n *\n * Matching strategy (first match wins):\n * 1. Exact match on English name (case-insensitive)\n * 2. Exact match on Arabic name\n * 3. Normalized Arabic match (handles tashkeel, alef variants, taa marbuta)\n * 4. Match after stripping \"ال\" prefix from Arabic input\n * 5. Candidate-contains-input match on English name (candidate name contains\n * the input, e.g. \"Riyadh\" -> \"Riyadh City\"; requires input length >= 3).\n * The reverse direction is intentionally excluded so a distinct longer\n * city like \"Riyadh Al Khabra\" is never rerouted to \"Riyadh\".\n *\n * Falls back to the original input if no match is found.\n */\n private resolveCity(inputCity: string): string {\n if (!this.citiesCache || this.citiesCache.length === 0) return inputCity;\n\n const trimmed = inputCity.trim();\n if (!trimmed) return inputCity;\n const lower = trimmed.toLowerCase();\n\n // 1. Exact English match (case-insensitive)\n const exactEn = this.citiesCache.find(\n (c) => c.nameEn.toLowerCase() === lower,\n );\n if (exactEn) return exactEn.nameEn;\n\n // 2. Exact Arabic match\n const exactAr = this.citiesCache.find((c) => c.nameAr === trimmed);\n if (exactAr) return exactAr.nameEn;\n\n // 3. Normalized Arabic match\n const normalizedInput = AymakanAdapter.normalizeArabic(trimmed);\n const normalizedAr = this.citiesCache.find(\n (c) =>\n c.nameAr &&\n AymakanAdapter.normalizeArabic(c.nameAr) === normalizedInput,\n );\n if (normalizedAr) return normalizedAr.nameEn;\n\n // 4. Arabic without \"ال\" prefix\n const withoutAl = normalizedInput.startsWith(\"ال\")\n ? normalizedInput.slice(2)\n : `ال${normalizedInput}`;\n const alMatch = this.citiesCache.find(\n (c) => c.nameAr && AymakanAdapter.normalizeArabic(c.nameAr) === withoutAl,\n );\n if (alMatch) return alMatch.nameEn;\n\n // 5. Candidate-contains-input match on English name (e.g. input \"Riyadh\"\n // resolves to the canonical \"Riyadh City\"). We deliberately match ONLY\n // this direction. The reverse direction (input contains a candidate's\n // name) is excluded because a longer, distinct city such as\n // \"Riyadh Al Khabra\" would otherwise be silently rerouted to \"Riyadh\".\n // Guarded by a minimum input length so very short inputs (1-2 chars)\n // don't spuriously substring-match many candidates.\n if (lower.length >= 3) {\n const containsEn = this.citiesCache.find((c) =>\n c.nameEn.toLowerCase().includes(lower),\n );\n if (containsEn) return containsEn.nameEn;\n }\n\n // No match — return as-is and let the API return a validation error\n return trimmed;\n }\n\n /**\n * Resolve city names in a CreateShipmentInput to valid Aymakan city names.\n */\n private resolveCitiesInInput(\n input: CreateShipmentInput,\n ): CreateShipmentInput {\n return {\n ...input,\n shipper: {\n ...input.shipper,\n city: this.resolveCity(input.shipper.city),\n },\n consignee: {\n ...input.consignee,\n city: this.resolveCity(input.consignee.city),\n },\n };\n }\n\n // =========================================================================\n // SHIPPING\n // =========================================================================\n\n protected async executeCreateShipment(\n input: CreateShipmentInput,\n ): Promise<Shipment> {\n await this.ensureCitiesLoaded();\n const resolved = this.resolveCitiesInInput(input);\n const request = mapCreateShipmentRequest(resolved);\n const response = await this.http.post<AymakanCreateShipmentResponse>(\n \"/shipping/create\",\n request,\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to create shipment\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return mapShipmentResponse(response.shipping);\n }\n\n async createBulkShipments(\n inputs: CreateShipmentInput[],\n ): Promise<Shipment[]> {\n // Nothing to create — avoid an empty request to the carrier.\n if (inputs.length === 0) return [];\n // Aymakan rejects batches larger than 30 (\"Only 30 shipments can be\n // created at a time.\"), so fail fast with a clear error before the request.\n if (inputs.length > 30) {\n throw new ValidationError(\n \"Aymakan bulk create accepts at most 30 shipments per request\",\n { raw: { count: inputs.length } },\n );\n }\n inputs.forEach(validateCreateShipmentInput);\n await this.ensureCitiesLoaded();\n const requests = inputs\n .map((i) => this.resolveCitiesInInput(i))\n .map(mapCreateShipmentRequest);\n const response = await this.http.post<{\n success: boolean;\n message?: string;\n bulk_awb?: string;\n total_shipments?: number;\n shipments: AymakanCreateShipmentResponse[\"shipping\"][];\n }>(\"/shipping/create/bulk_shipping\", { shipments: requests }, this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to create bulk shipments\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n if (!Array.isArray(response.shipments)) {\n throw new APIError(\n \"Aymakan bulk create response is missing the shipments array\",\n { carrier: \"aymakan\", raw: response },\n );\n }\n\n return response.shipments.map(mapShipmentResponse);\n }\n\n async cancelShipment(trackingNumber: string): Promise<boolean> {\n // The errorExtractor surfaces fake-200 error envelopes as APIError, so a\n // real failure throws with the carrier's message rather than silently\n // returning false.\n const response = await this.http.post<AymakanCancelResponse>(\n \"/shipping/cancel\",\n {\n tracking: trackingNumber,\n },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n async cancelByReference(reference: string): Promise<boolean> {\n const response = await this.http.post<AymakanCancelResponse>(\n \"/shipping/cancel_by_reference\",\n { reference },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n async updateDeliveryAddress(\n trackingNumber: string,\n address: Address,\n ): Promise<boolean> {\n await this.ensureCitiesLoaded();\n const resolvedCity = this.resolveCity(address.city);\n // Documented endpoint: POST /shipping/update/delivery_address with the\n // tracking number as a `tracking` field in the JSON body (NOT in the path).\n const response = await this.http.post<{ success: boolean }>(\n \"/shipping/update/delivery_address\",\n {\n tracking: trackingNumber,\n delivery_name: address.name,\n delivery_email: address.email,\n delivery_city: resolvedCity,\n delivery_address: address.line1,\n delivery_neighbourhood: address.neighbourhood,\n delivery_postcode: address.postalCode,\n delivery_country: address.countryCode,\n delivery_phone: sanitizePhone(address.phone),\n },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n // =========================================================================\n // TRACKING\n // =========================================================================\n\n async track(trackingNumber: string): Promise<TrackingResult> {\n const results = await this.trackMultiple([trackingNumber]);\n const result = results[0];\n if (!result) {\n throw new APIError(\"Shipment not found\", { carrier: \"aymakan\" });\n }\n return result;\n }\n\n async trackMultiple(trackingNumbers: string[]): Promise<TrackingResult[]> {\n const ids = trackingNumbers.map(encodeURIComponent).join(\",\");\n const response = await this.http.get<AymakanTrackResponse>(\n `/shipping/track/${ids}`,\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to track shipments\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n if (!Array.isArray(response.data?.shipments)) {\n throw new APIError(\"Aymakan track response is missing data.shipments\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.shipments.map(mapTrackingResult);\n }\n\n async trackByReference(reference: string): Promise<TrackingResult> {\n const response = await this.http.get<AymakanTrackResponse>(\n `/shipping/by_reference/${encodeURIComponent(reference)}`,\n this.errorOpts,\n );\n\n const shipment = response.data?.shipments?.[0];\n if (!response.success || !shipment) {\n throw new APIError(\"Shipment not found\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return mapTrackingResult(shipment);\n }\n\n // =========================================================================\n // LABELS\n // =========================================================================\n\n async getLabel(\n trackingNumber: string,\n _format?: \"PDF\" | \"ZPL\" | \"PNG\",\n ): Promise<string> {\n // Note: this endpoint always returns a single PDF download URL, so the\n // requested `format` cannot be honored.\n const response = await this.http.get<{\n success: boolean;\n error?: boolean;\n message?: string;\n response?: string;\n data: { awb_url: string };\n }>(\n `/shipping/awb/tracking/${encodeURIComponent(trackingNumber)}`,\n this.errorOpts,\n );\n\n if (!response.success || !response.data?.awb_url) {\n const msg = response.message ?? response.response ?? \"Failed to get label\";\n throw new APIError(msg, { carrier: \"aymakan\", raw: response });\n }\n\n return response.data.awb_url;\n }\n\n async getBulkLabels(trackingNumbers: string[]): Promise<string> {\n // Documented as a GET with comma-separated tracking numbers in the path.\n const ids = trackingNumbers.map(encodeURIComponent).join(\",\");\n const response = await this.http.get<{\n success: boolean;\n error?: boolean;\n message?: string;\n response?: string;\n data: { bulk_awb_url: string };\n }>(`/shipping/bulk_awb/trackings/${ids}`, this.errorOpts);\n\n if (!response.success || !response.data?.bulk_awb_url) {\n const msg =\n response.message ?? response.response ?? \"Failed to get bulk labels\";\n throw new APIError(msg, { carrier: \"aymakan\", raw: response });\n }\n\n return response.data.bulk_awb_url;\n }\n\n // =========================================================================\n // PICKUPS\n // =========================================================================\n\n async getPickupCities(): Promise<City[]> {\n const response = await this.http.get<AymakanCitiesResponse>(\n \"/pickup_request/cities\",\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to get pickup cities\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.cities.map(mapCity);\n }\n\n async getTimeSlots(_city: string, date: string): Promise<TimeSlot[]> {\n const response = await this.http.get<{\n success: boolean;\n error?: boolean;\n message?: string;\n data: {\n date: string;\n slots: Record<string, string>;\n };\n }>(`/time_slots/${encodeURIComponent(date)}`, this.errorOpts);\n\n // Aymakan returns error responses for invalid dates (past, Fridays, etc.)\n if (!response.success || response.error || !response.data?.slots) {\n const msg = response.message ?? \"No slots available\";\n throw new APIError(msg, { carrier: \"aymakan\", raw: response });\n }\n\n // data.slots is an object like { \"afternoon\": \"After Noon (02 PM - 06 PM)\" }\n return Object.entries(response.data.slots).map(([id, label]) => ({\n id,\n label,\n }));\n }\n\n async createPickup(input: PickupRequest): Promise<Pickup> {\n validatePickupRequest(input);\n await this.ensureCitiesLoaded();\n const resolvedInput = { ...input, city: this.resolveCity(input.city) };\n const request = mapPickupRequest(resolvedInput);\n const response = await this.http.post<AymakanPickupResponse>(\n \"/pickup_request/create\",\n request,\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to create pickup\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return mapPickupResponse(response.data);\n }\n\n async cancelPickup(pickupId: string | number): Promise<boolean> {\n const response = await this.http.post<{ success: boolean }>(\n \"/pickup_request/cancel\",\n { pickup_request: Number(pickupId) },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n async getPickupRequests(): Promise<Pickup[]> {\n // The list endpoint returns a Laravel paginated structure:\n // { success, data: { pickupRequests: { data: [...] } } }\n const response = await this.http.get<{\n success: boolean;\n data: { pickupRequests: { data: AymakanPickupResponse[\"data\"][] } };\n }>(\"/pickup_request/list\", this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to get pickup requests\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n const list = response.data?.pickupRequests?.data;\n if (!Array.isArray(list)) {\n throw new APIError(\n \"Aymakan pickup list response is missing data.pickupRequests.data\",\n { carrier: \"aymakan\", raw: response },\n );\n }\n\n return list.map(mapPickupResponse);\n }\n\n // =========================================================================\n // CITIES & LOCATIONS\n // =========================================================================\n\n async getCities(): Promise<City[]> {\n const response = await this.http.get<AymakanCitiesResponse>(\n \"/cities\",\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to get cities\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.cities.map(mapCity);\n }\n\n async getDropoffLocations(): Promise<\n {\n id: string;\n name: string;\n address?: string;\n city?: string;\n latitude?: number;\n longitude?: number;\n }[]\n > {\n // The API returns `data` as a flat array of warehouse objects. There is no\n // `id` field — the warehouse code lives in `name` (e.g. \"RUH-WH\").\n const response = await this.http.get<{\n success: boolean;\n data: Array<{\n name: string;\n city?: string;\n address?: string;\n manager?: string;\n mobile_phone?: string;\n email?: string;\n location_lat?: number | null;\n location_lng?: number | null;\n }>;\n }>(\"/dropoff_locations\", this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to get dropoff locations\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.map((loc) => ({\n id: loc.name,\n name: loc.name,\n address: loc.address,\n city: loc.city,\n latitude: loc.location_lat ?? undefined,\n longitude: loc.location_lng ?? undefined,\n }));\n }\n\n // =========================================================================\n // CUSTOMER ADDRESSES\n // =========================================================================\n\n async createCustomerAddress(\n address: CustomerAddress,\n ): Promise<CustomerAddress> {\n const request = mapCustomerAddressRequest(address);\n const response = await this.http.post<AymakanAddressResponse>(\n \"/address/create\",\n request,\n this.errorOpts,\n );\n\n if (!response.success || !response.data?.address) {\n throw new APIError(\"Failed to create address\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n const addr = response.data.address;\n return {\n id: addr.id,\n title: addr.title,\n name: addr.name,\n email: addr.email,\n phone: addr.phone,\n city: addr.city,\n address: addr.address,\n neighbourhood: addr.neighbourhood,\n postalCode: addr.postcode,\n countryCode: addr.country,\n description: addr.description,\n };\n }\n\n async getCustomerAddresses(): Promise<CustomerAddress[]> {\n const response = await this.http.get<{\n success: boolean;\n data: { address: AymakanAddressResponse[\"data\"][\"address\"][] };\n }>(\"/address/list\", this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to get customer addresses\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n if (!Array.isArray(response.data?.address)) {\n throw new APIError(\n \"Aymakan address list response is missing data.address\",\n { carrier: \"aymakan\", raw: response },\n );\n }\n\n return response.data.address.map((addr) => ({\n id: addr.id,\n title: addr.title,\n name: addr.name,\n email: addr.email,\n phone: addr.phone,\n city: addr.city,\n address: addr.address,\n neighbourhood: addr.neighbourhood,\n postalCode: addr.postcode,\n countryCode: addr.country,\n description: addr.description,\n }));\n }\n\n async updateCustomerAddress(\n id: number,\n address: Partial<CustomerAddress>,\n ): Promise<CustomerAddress> {\n const response = await this.http.put<AymakanAddressResponse>(\n \"/address/update\",\n {\n id,\n title: address.title,\n name: address.name,\n email: address.email,\n city: address.city,\n address: address.address,\n neighbourhood: address.neighbourhood,\n postcode: address.postalCode,\n phone: address.phone,\n description: address.description,\n },\n this.errorOpts,\n );\n\n if (!response.success || !response.data?.address) {\n throw new APIError(\"Failed to update address\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n const addr = response.data.address;\n return {\n id: addr.id,\n title: addr.title,\n name: addr.name,\n email: addr.email,\n phone: addr.phone,\n city: addr.city,\n address: addr.address,\n neighbourhood: addr.neighbourhood,\n postalCode: addr.postcode,\n countryCode: addr.country,\n description: addr.description,\n };\n }\n\n async deleteCustomerAddress(id: number): Promise<boolean> {\n // The id must be sent in the JSON request body, not the URL path.\n const response = await this.http.delete<{ success: boolean }>(\n \"/address/delete\",\n { body: { id }, errorExtractor: aymakanErrorExtractor },\n );\n return response.success === true;\n }\n\n // =========================================================================\n // WEBHOOKS\n // =========================================================================\n\n parseWebhook(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n ): WebhookEvent {\n return parseAymakanWebhook(payload, options);\n }\n}\n"
|
|
7
|
+
"// file: src/carriers/aymakan/adapter.ts\n/**\n * Aymakan Carrier Adapter\n * Full implementation of the CarrierAdapter interface for Aymakan API.\n */\n\nimport {\n CITIES_CACHE_TTL,\n CITIES_FAILURE_COOLDOWN,\n findCityMatch,\n} from \"../../core/city-resolver\";\nimport { APIError, ValidationError } from \"../../core/errors\";\nimport { HttpClient } from \"../../core/http\";\nimport {\n validateCreateShipmentInput,\n validatePickupRequest,\n} from \"../../core/schemas\";\nimport type {\n Address,\n CarrierConfig,\n City,\n CreateShipmentInput,\n CustomerAddress,\n Pickup,\n PickupRequest,\n Shipment,\n TimeSlot,\n TrackingResult,\n WebhookConfig,\n WebhookEvent,\n} from \"../../core/types\";\nimport { BaseCarrierAdapter } from \"../base\";\nimport {\n mapCity,\n mapCreateShipmentRequest,\n mapCustomerAddressRequest,\n mapPickupRequest,\n mapPickupResponse,\n mapShipmentResponse,\n mapTrackingResult,\n parseAymakanWebhook,\n sanitizePhone,\n} from \"./mappers\";\nimport type {\n AymakanAddressResponse,\n AymakanCancelResponse,\n AymakanCitiesResponse,\n AymakanCreateShipmentResponse,\n AymakanPickupResponse,\n AymakanShipmentResponse,\n AymakanTrackResponse,\n} from \"./types\";\n\nconst AYMAKAN_SANDBOX_URL = \"https://dev-api.aymakan.com.sa/v2\";\nconst AYMAKAN_PRODUCTION_URL = \"https://api.aymakan.net/v2\";\n\n/**\n * Aymakan returns logical errors inside a fake-200 envelope (HTTP 200 with an\n * error flag/message in the body). Without an extractor these are swallowed —\n * e.g. cancel endpoints would return `success: undefined` and the adapter would\n * report `false` with no reason. This extractor surfaces those as APIError.\n *\n * Recognised error shapes (all on a 200 body):\n * - `{ error: true, ... }` → Laravel/Aymakan error flag\n * - `{ success: false, ... }` → explicit failure flag\n * - `{ message }` / `{ response }` → human-readable error text\n * - `{ errors: { field: [...] } }` → Laravel field validation errors\n *\n * A bare `{ message }` is NOT treated as an error on its own (many success\n * envelopes carry a `message`); we only flag when `error`/`success:false` is\n * present, or validation `errors` exist.\n */\n/**\n * Pull a human-readable message out of an object-shaped error value, e.g.\n * `{ error: { message: \"...\" } }` or `{ error: { response: \"...\" } }`.\n */\nfunction extractNestedMessage(value: unknown): string | undefined {\n if (typeof value === \"string\") return value;\n if (value && typeof value === \"object\") {\n const obj = value as Record<string, unknown>;\n if (typeof obj.message === \"string\") return obj.message;\n if (typeof obj.response === \"string\") return obj.response;\n }\n return undefined;\n}\n\n/** Join Laravel-style `{ field: [msg, ...] }` validation errors into one string. */\nfunction joinFieldErrors(errors: Record<string, unknown>): string | undefined {\n const parts = Object.values(errors)\n .flat()\n .filter((v): v is string => typeof v === \"string\");\n return parts.length ? parts.join(\"; \") : undefined;\n}\n\nfunction aymakanErrorExtractor(json: unknown): {\n hasError: boolean;\n message?: string;\n errors?: Record<string, string[]>;\n} {\n if (!json || typeof json !== \"object\") {\n return { hasError: false };\n }\n const obj = json as Record<string, unknown>;\n\n const hasValidationErrors =\n !!obj.errors &&\n typeof obj.errors === \"object\" &&\n Object.keys(obj.errors as object).length > 0;\n const hasError = obj.error === true || obj.success === false || hasValidationErrors;\n\n if (!hasError) {\n return { hasError: false };\n }\n\n const message =\n (typeof obj.message === \"string\" && obj.message) ||\n (typeof obj.response === \"string\" && obj.response) ||\n (typeof obj.error === \"string\" && obj.error) ||\n extractNestedMessage(obj.error) ||\n (hasValidationErrors\n ? joinFieldErrors(obj.errors as Record<string, string[]>)\n : undefined) ||\n undefined;\n\n return {\n hasError: true,\n message,\n errors: hasValidationErrors\n ? (obj.errors as Record<string, string[]>)\n : undefined,\n };\n}\n\nexport interface AymakanConfig extends CarrierConfig {\n credentials: {\n apiKey: string;\n };\n}\n\nexport class AymakanAdapter extends BaseCarrierAdapter {\n readonly name = \"aymakan\";\n readonly supportedCountries = [\"SA\", \"AE\", \"BH\", \"KW\", \"OM\", \"QA\"];\n\n private http: HttpClient;\n\n /**\n * Shared options applied to every Aymakan http call so fake-200 error\n * envelopes surface as APIError instead of being silently swallowed.\n */\n private readonly errorOpts = { errorExtractor: aymakanErrorExtractor };\n\n /** Cached Aymakan cities list for city name resolution */\n private citiesCache: City[] | null = null;\n private citiesCacheTime = 0;\n /** Timestamp of the last failed /cities fetch attempt, if any */\n private citiesFetchFailedAt = 0;\n\n constructor(config: AymakanConfig) {\n super(config);\n this.http = new HttpClient({\n baseUrl: this.getBaseUrl(),\n carrier: \"aymakan\",\n headers: {\n Authorization: config.credentials.apiKey,\n },\n });\n }\n\n protected getBaseUrl(): string {\n return this.config.mode === \"production\"\n ? AYMAKAN_PRODUCTION_URL\n : AYMAKAN_SANDBOX_URL;\n }\n\n // =========================================================================\n // CITY RESOLUTION\n // =========================================================================\n\n /**\n * Load cities list from Aymakan API and cache it.\n * Silently falls back to empty list on failure so shipments can still be attempted.\n */\n private async ensureCitiesLoaded(): Promise<void> {\n const now = Date.now();\n if (\n this.citiesCache &&\n now - this.citiesCacheTime < CITIES_CACHE_TTL\n ) {\n return;\n }\n // A recent failure is still in its cooldown window — skip re-attempting\n // the /cities fetch and fall back to whatever cache we have (possibly\n // empty), so an outage never hard-blocks shipment/pickup creation.\n if (now - this.citiesFetchFailedAt < CITIES_FAILURE_COOLDOWN) {\n if (!this.citiesCache) this.citiesCache = [];\n return;\n }\n try {\n this.citiesCache = await this.getCities();\n this.citiesCacheTime = now;\n } catch {\n this.citiesFetchFailedAt = now;\n if (!this.citiesCache) this.citiesCache = [];\n }\n }\n\n /**\n * Resolve a user-input city name to the valid Aymakan English city name via\n * the shared matcher (see core/city-resolver.ts for the strategy). Lenient:\n * falls back to the original input when nothing matches or the cities list\n * is unavailable — used for pickups, where an invalid city only affects the\n * merchant's own pickup request.\n */\n private resolveCity(inputCity: string): string {\n if (!this.citiesCache || this.citiesCache.length === 0) return inputCity;\n const trimmed = inputCity.trim();\n if (!trimmed) return inputCity;\n return findCityMatch(trimmed, this.citiesCache)?.nameEn ?? trimmed;\n }\n\n /**\n * Strict variant used for shipment creation: when Aymakan's own city list is\n * loaded and the input matches nothing in it, the booking would be rejected\n * by the API anyway — fail fast with a clear, field-scoped error instead of\n * an opaque carrier 400. When the list is unavailable (fetch failed /\n * cooldown), fall back to pass-through so a /cities outage never blocks\n * shipment creation.\n */\n private resolveCityStrict(\n inputCity: string,\n field: \"shipper.city\" | \"consignee.city\",\n ): string {\n if (!this.citiesCache || this.citiesCache.length === 0) return inputCity;\n const match = findCityMatch(inputCity, this.citiesCache);\n if (!match) {\n throw new ValidationError(\n `Unknown ${field.replace(\".city\", \"\")} city \"${inputCity}\": not in Aymakan's supported city list`,\n { field },\n );\n }\n return match.nameEn;\n }\n\n /**\n * Resolve city names in a CreateShipmentInput to valid Aymakan city names,\n * rejecting cities Aymakan does not serve (strict — see resolveCityStrict).\n */\n private resolveCitiesInInput(\n input: CreateShipmentInput,\n ): CreateShipmentInput {\n return {\n ...input,\n shipper: {\n ...input.shipper,\n city: this.resolveCityStrict(input.shipper.city, \"shipper.city\"),\n },\n consignee: {\n ...input.consignee,\n city: this.resolveCityStrict(input.consignee.city, \"consignee.city\"),\n },\n };\n }\n\n // =========================================================================\n // SHIPPING\n // =========================================================================\n\n protected async executeCreateShipment(\n input: CreateShipmentInput,\n ): Promise<Shipment> {\n await this.ensureCitiesLoaded();\n const resolved = this.resolveCitiesInInput(input);\n const request = mapCreateShipmentRequest(resolved);\n const response = await this.http.post<AymakanCreateShipmentResponse>(\n \"/shipping/create\",\n request,\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to create shipment\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return mapShipmentResponse(response.shipping);\n }\n\n async createBulkShipments(\n inputs: CreateShipmentInput[],\n ): Promise<Shipment[]> {\n // Nothing to create — avoid an empty request to the carrier.\n if (inputs.length === 0) return [];\n // Aymakan rejects batches larger than 30 (\"Only 30 shipments can be\n // created at a time.\"), so fail fast with a clear error before the request.\n if (inputs.length > 30) {\n throw new ValidationError(\n \"Aymakan bulk create accepts at most 30 shipments per request\",\n { raw: { count: inputs.length } },\n );\n }\n inputs.forEach(validateCreateShipmentInput);\n await this.ensureCitiesLoaded();\n const requests = inputs\n .map((i) => this.resolveCitiesInInput(i))\n .map(mapCreateShipmentRequest);\n const response = await this.http.post<{\n success: boolean;\n message?: string;\n bulk_awb?: string;\n total_shipments?: number;\n shipments: AymakanCreateShipmentResponse[\"shipping\"][];\n }>(\"/shipping/create/bulk_shipping\", { shipments: requests }, this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to create bulk shipments\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n if (!Array.isArray(response.shipments)) {\n throw new APIError(\n \"Aymakan bulk create response is missing the shipments array\",\n { carrier: \"aymakan\", raw: response },\n );\n }\n\n return response.shipments.map(mapShipmentResponse);\n }\n\n async cancelShipment(trackingNumber: string): Promise<boolean> {\n // The errorExtractor surfaces fake-200 error envelopes as APIError, so a\n // real failure throws with the carrier's message rather than silently\n // returning false.\n const response = await this.http.post<AymakanCancelResponse>(\n \"/shipping/cancel\",\n {\n tracking: trackingNumber,\n },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n async cancelByReference(reference: string): Promise<boolean> {\n const response = await this.http.post<AymakanCancelResponse>(\n \"/shipping/cancel_by_reference\",\n { reference },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n async updateDeliveryAddress(\n trackingNumber: string,\n address: Address,\n ): Promise<boolean> {\n await this.ensureCitiesLoaded();\n const resolvedCity = this.resolveCity(address.city);\n // Documented endpoint: POST /shipping/update/delivery_address with the\n // tracking number as a `tracking` field in the JSON body (NOT in the path).\n const response = await this.http.post<{ success: boolean }>(\n \"/shipping/update/delivery_address\",\n {\n tracking: trackingNumber,\n delivery_name: address.name,\n delivery_email: address.email,\n delivery_city: resolvedCity,\n delivery_address: address.line1,\n delivery_neighbourhood: address.neighbourhood,\n delivery_postcode: address.postalCode,\n delivery_country: address.countryCode,\n delivery_phone: sanitizePhone(address.phone),\n },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n // =========================================================================\n // TRACKING\n // =========================================================================\n\n async track(trackingNumber: string): Promise<TrackingResult> {\n const results = await this.trackMultiple([trackingNumber]);\n const result = results[0];\n if (!result) {\n throw new APIError(\"Shipment not found\", { carrier: \"aymakan\" });\n }\n return result;\n }\n\n async trackMultiple(trackingNumbers: string[]): Promise<TrackingResult[]> {\n const ids = trackingNumbers.map(encodeURIComponent).join(\",\");\n const response = await this.http.get<AymakanTrackResponse>(\n `/shipping/track/${ids}`,\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to track shipments\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n if (!Array.isArray(response.data?.shipments)) {\n throw new APIError(\"Aymakan track response is missing data.shipments\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.shipments.map(mapTrackingResult);\n }\n\n async trackByReference(reference: string): Promise<TrackingResult> {\n const response = await this.http.get<AymakanTrackResponse>(\n `/shipping/by_reference/${encodeURIComponent(reference)}`,\n this.errorOpts,\n );\n\n const shipment = response.data?.shipments?.[0];\n if (!response.success || !shipment) {\n throw new APIError(\"Shipment not found\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return mapTrackingResult(shipment);\n }\n\n // =========================================================================\n // LABELS\n // =========================================================================\n\n async getLabel(\n trackingNumber: string,\n _format?: \"PDF\" | \"ZPL\" | \"PNG\",\n ): Promise<string> {\n // Note: this endpoint always returns a single PDF download URL, so the\n // requested `format` cannot be honored.\n const response = await this.http.get<{\n success: boolean;\n error?: boolean;\n message?: string;\n response?: string;\n data: { awb_url: string };\n }>(\n `/shipping/awb/tracking/${encodeURIComponent(trackingNumber)}`,\n this.errorOpts,\n );\n\n if (!response.success || !response.data?.awb_url) {\n const msg = response.message ?? response.response ?? \"Failed to get label\";\n throw new APIError(msg, { carrier: \"aymakan\", raw: response });\n }\n\n return response.data.awb_url;\n }\n\n async getBulkLabels(trackingNumbers: string[]): Promise<string> {\n // Documented as a GET with comma-separated tracking numbers in the path.\n const ids = trackingNumbers.map(encodeURIComponent).join(\",\");\n const response = await this.http.get<{\n success: boolean;\n error?: boolean;\n message?: string;\n response?: string;\n data: { bulk_awb_url: string };\n }>(`/shipping/bulk_awb/trackings/${ids}`, this.errorOpts);\n\n if (!response.success || !response.data?.bulk_awb_url) {\n const msg =\n response.message ?? response.response ?? \"Failed to get bulk labels\";\n throw new APIError(msg, { carrier: \"aymakan\", raw: response });\n }\n\n return response.data.bulk_awb_url;\n }\n\n // =========================================================================\n // PICKUPS\n // =========================================================================\n\n async getPickupCities(): Promise<City[]> {\n const response = await this.http.get<AymakanCitiesResponse>(\n \"/pickup_request/cities\",\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to get pickup cities\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.cities.map(mapCity);\n }\n\n async getTimeSlots(_city: string, date: string): Promise<TimeSlot[]> {\n const response = await this.http.get<{\n success: boolean;\n error?: boolean;\n message?: string;\n data: {\n date: string;\n slots: Record<string, string>;\n };\n }>(`/time_slots/${encodeURIComponent(date)}`, this.errorOpts);\n\n // Aymakan returns error responses for invalid dates (past, Fridays, etc.)\n if (!response.success || response.error || !response.data?.slots) {\n const msg = response.message ?? \"No slots available\";\n throw new APIError(msg, { carrier: \"aymakan\", raw: response });\n }\n\n // data.slots is an object like { \"afternoon\": \"After Noon (02 PM - 06 PM)\" }\n return Object.entries(response.data.slots).map(([id, label]) => ({\n id,\n label,\n }));\n }\n\n async createPickup(input: PickupRequest): Promise<Pickup> {\n validatePickupRequest(input);\n await this.ensureCitiesLoaded();\n const resolvedInput = { ...input, city: this.resolveCity(input.city) };\n const request = mapPickupRequest(resolvedInput);\n const response = await this.http.post<AymakanPickupResponse>(\n \"/pickup_request/create\",\n request,\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to create pickup\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return mapPickupResponse(response.data);\n }\n\n async cancelPickup(pickupId: string | number): Promise<boolean> {\n const response = await this.http.post<{ success: boolean }>(\n \"/pickup_request/cancel\",\n { pickup_request: Number(pickupId) },\n this.errorOpts,\n );\n return response.success === true;\n }\n\n async getPickupRequests(): Promise<Pickup[]> {\n // The list endpoint returns a Laravel paginated structure:\n // { success, data: { pickupRequests: { data: [...] } } }\n const response = await this.http.get<{\n success: boolean;\n data: { pickupRequests: { data: AymakanPickupResponse[\"data\"][] } };\n }>(\"/pickup_request/list\", this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to get pickup requests\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n const list = response.data?.pickupRequests?.data;\n if (!Array.isArray(list)) {\n throw new APIError(\n \"Aymakan pickup list response is missing data.pickupRequests.data\",\n { carrier: \"aymakan\", raw: response },\n );\n }\n\n return list.map(mapPickupResponse);\n }\n\n // =========================================================================\n // CITIES & LOCATIONS\n // =========================================================================\n\n async getCities(): Promise<City[]> {\n const response = await this.http.get<AymakanCitiesResponse>(\n \"/cities\",\n this.errorOpts,\n );\n\n if (!response.success) {\n throw new APIError(\"Failed to get cities\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.cities.map(mapCity);\n }\n\n async getDropoffLocations(): Promise<\n {\n id: string;\n name: string;\n address?: string;\n city?: string;\n latitude?: number;\n longitude?: number;\n }[]\n > {\n // The API returns `data` as a flat array of warehouse objects. There is no\n // `id` field — the warehouse code lives in `name` (e.g. \"RUH-WH\").\n const response = await this.http.get<{\n success: boolean;\n data: Array<{\n name: string;\n city?: string;\n address?: string;\n manager?: string;\n mobile_phone?: string;\n email?: string;\n location_lat?: number | null;\n location_lng?: number | null;\n }>;\n }>(\"/dropoff_locations\", this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to get dropoff locations\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n return response.data.map((loc) => ({\n id: loc.name,\n name: loc.name,\n address: loc.address,\n city: loc.city,\n latitude: loc.location_lat ?? undefined,\n longitude: loc.location_lng ?? undefined,\n }));\n }\n\n // =========================================================================\n // CUSTOMER ADDRESSES\n // =========================================================================\n\n async createCustomerAddress(\n address: CustomerAddress,\n ): Promise<CustomerAddress> {\n const request = mapCustomerAddressRequest(address);\n const response = await this.http.post<AymakanAddressResponse>(\n \"/address/create\",\n request,\n this.errorOpts,\n );\n\n if (!response.success || !response.data?.address) {\n throw new APIError(\"Failed to create address\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n const addr = response.data.address;\n return {\n id: addr.id,\n title: addr.title,\n name: addr.name,\n email: addr.email,\n phone: addr.phone,\n city: addr.city,\n address: addr.address,\n neighbourhood: addr.neighbourhood,\n postalCode: addr.postcode,\n countryCode: addr.country,\n description: addr.description,\n };\n }\n\n async getCustomerAddresses(): Promise<CustomerAddress[]> {\n const response = await this.http.get<{\n success: boolean;\n data: { address: AymakanAddressResponse[\"data\"][\"address\"][] };\n }>(\"/address/list\", this.errorOpts);\n\n if (!response.success) {\n throw new APIError(\"Failed to get customer addresses\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n if (!Array.isArray(response.data?.address)) {\n throw new APIError(\n \"Aymakan address list response is missing data.address\",\n { carrier: \"aymakan\", raw: response },\n );\n }\n\n return response.data.address.map((addr) => ({\n id: addr.id,\n title: addr.title,\n name: addr.name,\n email: addr.email,\n phone: addr.phone,\n city: addr.city,\n address: addr.address,\n neighbourhood: addr.neighbourhood,\n postalCode: addr.postcode,\n countryCode: addr.country,\n description: addr.description,\n }));\n }\n\n async updateCustomerAddress(\n id: number,\n address: Partial<CustomerAddress>,\n ): Promise<CustomerAddress> {\n const response = await this.http.put<AymakanAddressResponse>(\n \"/address/update\",\n {\n id,\n title: address.title,\n name: address.name,\n email: address.email,\n city: address.city,\n address: address.address,\n neighbourhood: address.neighbourhood,\n postcode: address.postalCode,\n phone: address.phone,\n description: address.description,\n },\n this.errorOpts,\n );\n\n if (!response.success || !response.data?.address) {\n throw new APIError(\"Failed to update address\", {\n carrier: \"aymakan\",\n raw: response,\n });\n }\n\n const addr = response.data.address;\n return {\n id: addr.id,\n title: addr.title,\n name: addr.name,\n email: addr.email,\n phone: addr.phone,\n city: addr.city,\n address: addr.address,\n neighbourhood: addr.neighbourhood,\n postalCode: addr.postcode,\n countryCode: addr.country,\n description: addr.description,\n };\n }\n\n async deleteCustomerAddress(id: number): Promise<boolean> {\n // The id must be sent in the JSON request body, not the URL path.\n const response = await this.http.delete<{ success: boolean }>(\n \"/address/delete\",\n { body: { id }, errorExtractor: aymakanErrorExtractor },\n );\n return response.success === true;\n }\n\n // =========================================================================\n // WEBHOOKS\n // =========================================================================\n\n parseWebhook(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n ): WebhookEvent {\n return parseAymakanWebhook(payload, options);\n }\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": ";;;;;;;;;;;AAMO,IAAM,iBAAiB;AAAA,EAE5B,WAAW;AAAA,EAEX,WAAW;AAAA,EAEX,UAAU;AAAA,EAEV,gBAAgB;AAAA,EAEhB,UAAU;AAAA,EAEV,SAAS;AAAA,EAET,OAAO;AAAA,EAEP,QAAQ;AAAA,EAER,gBAAgB;AAAA,EAEhB,gBAAgB;AAClB;AASO,IAAM,qBAAqB;AAAA,EAEhC,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EAGX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AAAA,EAGX,WAAW;AAAA,EAGX,WAAW;AAAA,EACX,WAAW;AAAA,EACX,WAAW;AACb;;;AClBO,SAAS,gBAAgB,CAAC,YAAgD;AAAA,EAC/E,MAAM,SACJ,mBAAmB;AAAA,EACrB,OAAO;AAAA;AAUT,IAAM,sBAAsD;AAAA,EAC1D,yBAAyB;AAAA,EACzB,oBAAoB;AAAA,EACpB,mCAAmC;AAAA,EACnC,WAAW;AAAA,EACX,aAAa;AAAA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AA,MACE;AAAA,MACA,OAAO,QAAQ;AAAA,MACf,MAAM,QAAQ;AAAA,MACd,OAAO,QAAQ;AAAA,MACf,MAAM,QAAQ;AAAA,MACd,SAAS,QAAQ;AAAA,MACjB,eAAe,QAAQ;AAAA,MACvB,UAAU,QAAQ;AAAA,MAClB,OAAO,QAAQ;AAAA,MACf,aAAa,QAAQ;AAAA,IACvB,GACA,KAAK,SACP;AAAA,IAEA,IAAI,CAAC,SAAS,WAAW,CAAC,SAAS,MAAM,SAAS;AAAA,MAChD,MAAM,IAAI,SAAS,4BAA4B;AAAA,QAC7C,SAAS;AAAA,QACT,KAAK;AAAA,MACP,CAAC;AAAA,IACH;AAAA,IAEA,MAAM,OAAO,SAAS,KAAK;AAAA,IAC3B,OAAO;AAAA,MACL,IAAI,KAAK;AAAA,MACT,OAAO,KAAK;AAAA,MACZ,MAAM,KAAK;AAAA,MACX,OAAO,KAAK;AAAA,MACZ,OAAO,KAAK;AAAA,MACZ,MAAM,KAAK;AAAA,MACX,SAAS,KAAK;AAAA,MACd,eAAe,KAAK;AAAA,MACpB,YAAY,KAAK;AAAA,MACjB,aAAa,KAAK;AAAA,MAClB,aAAa,KAAK;AAAA,IACpB;AAAA;AAAA,OAGI,sBAAqB,CAAC,IAA8B;AAAA,IAExD,MAAM,WAAW,MAAM,KAAK,KAAK,OAC/B,mBACA,EAAE,MAAM,EAAE,GAAG,GAAG,gBAAgB,sBAAsB,CACxD;AAAA,IACA,OAAO,SAAS,YAAY;AAAA;AAAA,EAO9B,YAAY,CACV,SACA,SAKc;AAAA,IACd,OAAO,oBAAoB,SAAS,OAAO;AAAA;AAE/C;",
|
|
10
|
+
"debugId": "C3DBDA3066CA8E3964756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -14,6 +14,11 @@ export declare class SMSAExpressAdapter extends BaseCarrierAdapter {
|
|
|
14
14
|
readonly name = "smsaexpress";
|
|
15
15
|
readonly supportedCountries: string[];
|
|
16
16
|
private http;
|
|
17
|
+
/** Cached SMSA Saudi cities list for city validation on booking */
|
|
18
|
+
private citiesCache;
|
|
19
|
+
private citiesCacheTime;
|
|
20
|
+
/** Timestamp of the last failed cities-lookup attempt, if any */
|
|
21
|
+
private citiesFetchFailedAt;
|
|
17
22
|
constructor(config: SMSAExpressConfig);
|
|
18
23
|
protected getBaseUrl(): string;
|
|
19
24
|
/**
|
|
@@ -26,6 +31,23 @@ export declare class SMSAExpressAdapter extends BaseCarrierAdapter {
|
|
|
26
31
|
* each would call `Date.now()` independently and disagree).
|
|
27
32
|
*/
|
|
28
33
|
private withOrderNumber;
|
|
34
|
+
/**
|
|
35
|
+
* Load the SMSA Saudi cities list and cache it, mirroring the Aymakan
|
|
36
|
+
* adapter's TTL + failure-cooldown behavior: a lookup outage falls back to
|
|
37
|
+
* an empty cache (pass-through resolution) so it never blocks bookings.
|
|
38
|
+
*/
|
|
39
|
+
private ensureCitiesLoaded;
|
|
40
|
+
/**
|
|
41
|
+
* Validate/normalize a Saudi address city against SMSA's own city list
|
|
42
|
+
* before booking (SMSA's City field is list-validated server-side, so an
|
|
43
|
+
* unknown value previously produced an opaque carrier rejection). Strict:
|
|
44
|
+
* when the list is loaded and nothing matches, fail fast with a clear,
|
|
45
|
+
* field-scoped error. Lenient when the list is unavailable (outage) and for
|
|
46
|
+
* non-SA addresses, whose cities are not in the SA lookup.
|
|
47
|
+
*/
|
|
48
|
+
private resolveCityStrict;
|
|
49
|
+
/** Resolve shipper + consignee cities for a booking (strict — see above). */
|
|
50
|
+
private resolveCitiesInInput;
|
|
29
51
|
protected executeCreateShipment(input: CreateShipmentInput): Promise<Shipment>;
|
|
30
52
|
private createC2BShipment;
|
|
31
53
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../src/carriers/smsaexpress/adapter.ts"],"names":[],"mappings":"AACA;;;GAGG;
|
|
1
|
+
{"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":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_TTL,
|
|
3
|
+
CITIES_FAILURE_COOLDOWN,
|
|
4
|
+
findCityMatch
|
|
5
|
+
} from "../../index-dfx6rbm2.js";
|
|
1
6
|
import {
|
|
2
7
|
APIError,
|
|
3
8
|
BaseCarrierAdapter,
|
|
@@ -349,6 +354,9 @@ class SMSAExpressAdapter extends BaseCarrierAdapter {
|
|
|
349
354
|
"JO"
|
|
350
355
|
];
|
|
351
356
|
http;
|
|
357
|
+
citiesCache = null;
|
|
358
|
+
citiesCacheTime = 0;
|
|
359
|
+
citiesFetchFailedAt = 0;
|
|
352
360
|
constructor(config) {
|
|
353
361
|
super(config);
|
|
354
362
|
this.http = new HttpClient({
|
|
@@ -368,8 +376,52 @@ class SMSAExpressAdapter extends BaseCarrierAdapter {
|
|
|
368
376
|
}
|
|
369
377
|
return { ...input, reference: generateOrderNumber() };
|
|
370
378
|
}
|
|
379
|
+
async ensureCitiesLoaded() {
|
|
380
|
+
const now = Date.now();
|
|
381
|
+
if (this.citiesCache && now - this.citiesCacheTime < CITIES_CACHE_TTL) {
|
|
382
|
+
return;
|
|
383
|
+
}
|
|
384
|
+
if (now - this.citiesFetchFailedAt < CITIES_FAILURE_COOLDOWN) {
|
|
385
|
+
if (!this.citiesCache)
|
|
386
|
+
this.citiesCache = [];
|
|
387
|
+
return;
|
|
388
|
+
}
|
|
389
|
+
try {
|
|
390
|
+
this.citiesCache = await this.getCities();
|
|
391
|
+
this.citiesCacheTime = now;
|
|
392
|
+
} catch {
|
|
393
|
+
this.citiesFetchFailedAt = now;
|
|
394
|
+
if (!this.citiesCache)
|
|
395
|
+
this.citiesCache = [];
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
resolveCityStrict(address, field) {
|
|
399
|
+
if (address.countryCode !== "SA")
|
|
400
|
+
return address.city;
|
|
401
|
+
if (!this.citiesCache || this.citiesCache.length === 0)
|
|
402
|
+
return address.city;
|
|
403
|
+
const match = findCityMatch(address.city, this.citiesCache);
|
|
404
|
+
if (!match) {
|
|
405
|
+
throw new ValidationError(`Unknown ${field.replace(".city", "")} city "${address.city}": not in SMSA's supported city list`, { field });
|
|
406
|
+
}
|
|
407
|
+
return match.nameEn;
|
|
408
|
+
}
|
|
409
|
+
async resolveCitiesInInput(input) {
|
|
410
|
+
await this.ensureCitiesLoaded();
|
|
411
|
+
return {
|
|
412
|
+
...input,
|
|
413
|
+
shipper: {
|
|
414
|
+
...input.shipper,
|
|
415
|
+
city: this.resolveCityStrict(input.shipper, "shipper.city")
|
|
416
|
+
},
|
|
417
|
+
consignee: {
|
|
418
|
+
...input.consignee,
|
|
419
|
+
city: this.resolveCityStrict(input.consignee, "consignee.city")
|
|
420
|
+
}
|
|
421
|
+
};
|
|
422
|
+
}
|
|
371
423
|
async executeCreateShipment(input) {
|
|
372
|
-
const prepared = this.withOrderNumber(input);
|
|
424
|
+
const prepared = await this.resolveCitiesInInput(this.withOrderNumber(input));
|
|
373
425
|
const isC2B = prepared.serviceType !== undefined && C2B_SERVICE_CODES.has(prepared.serviceType.trim().toUpperCase());
|
|
374
426
|
if (isC2B) {
|
|
375
427
|
return this.createC2BShipment(prepared);
|
|
@@ -455,7 +507,7 @@ class SMSAExpressAdapter extends BaseCarrierAdapter {
|
|
|
455
507
|
return response.map(mapOffice);
|
|
456
508
|
}
|
|
457
509
|
async create2WayShipment(input) {
|
|
458
|
-
const prepared = this.withOrderNumber(input);
|
|
510
|
+
const prepared = await this.resolveCitiesInInput(this.withOrderNumber(input));
|
|
459
511
|
const request = mapCreate2WayRequest(prepared);
|
|
460
512
|
const response = await this.http.post("/api/TwoWayShipment/new", request);
|
|
461
513
|
return mapShipmentResponse(response, prepared);
|
|
@@ -485,4 +537,4 @@ export {
|
|
|
485
537
|
SMSAExpressAdapter
|
|
486
538
|
};
|
|
487
539
|
|
|
488
|
-
//# debugId=
|
|
540
|
+
//# debugId=87215A69EE27862E64756E2164756E21
|
|
@@ -4,9 +4,9 @@
|
|
|
4
4
|
"sourcesContent": [
|
|
5
5
|
"// file: src/carriers/smsaexpress/services.ts\n/**\n * SMSA Express Service Type Codes\n * Use these constants for type-safe service selection.\n */\n\nexport const SMSAService = {\n /** E-commerce delivery */\n ECOMMERCE_DELIVERY: \"EDDL\",\n /** Express delivery */\n EXPRESS_DELIVERY: \"EDEL\",\n /** C2B / Reverse pickup */\n C2B_REVERSE: \"EDCR\",\n} as const;\n\nexport type SMSAServiceType = (typeof SMSAService)[keyof typeof SMSAService];\n\n/**\n * SMSA Express Scan Type Codes → Unified ShipmentStatus mapping.\n *\n * Based on /api/track/statuslookup response.\n * Scan types not explicitly listed default to \"unknown\" (see mapSMSAStatus)\n * so operators can detect unmapped codes instead of silently treating them\n * as in-transit.\n */\nexport const SMSAStatusCodes: Record<string, string> = {\n // Delivery\n DL: \"delivered\",\n\n // Out for delivery\n OD: \"out_for_delivery\",\n\n // Arrived at facility\n AF: \"at_warehouse\",\n\n // Hub / sorting\n HOP: \"in_transit\",\n HOR: \"in_transit\",\n HOT: \"in_transit\",\n\n // Picked up / collected\n PU: \"picked_up\",\n PKD: \"picked_up\",\n\n // Customs\n CR: \"in_transit\",\n CH: \"in_transit\",\n\n // Exceptions\n DE: \"exception\",\n DMG: \"exception\",\n MISS: \"exception\",\n\n // Cancelled / returned\n CAN: \"cancelled\",\n RTO: \"returned\",\n RTN: \"returned\",\n\n // Processing\n CC: \"at_warehouse\",\n PP: \"pending\",\n\n // Created / booked\n BK: \"created\",\n NEW: \"created\",\n};\n",
|
|
6
6
|
"// file: src/carriers/smsaexpress/mappers.ts\n/**\n * SMSA Express Data Mappers\n * Transform between unified ShipFlow types and SMSA Express API formats.\n */\n\nimport {\n APIError,\n ValidationError,\n WebhookVerificationError,\n} from \"../../core/errors\";\nimport type {\n City,\n CreateShipmentInput,\n Location,\n Shipment,\n ShipmentStatus,\n TrackingEvent,\n TrackingResult,\n WebhookConfig,\n WebhookEvent,\n} from \"../../core/types\";\nimport { SMSAStatusCodes } from \"./services\";\nimport type {\n SMSACityLookupItem,\n SMSACreate2WayShipmentRequest,\n SMSACreateB2CShipmentRequest,\n SMSACreateC2BShipmentRequest,\n SMSAOfficeLookupItem,\n SMSAShipmentAddress,\n SMSAShipmentResponse,\n SMSATrackingResponse,\n SMSATrackingScan,\n SMSAWebhookShipment,\n} from \"./types\";\n\n// ============================================================================\n// STATUS MAPPING\n// ============================================================================\n\nexport function mapSMSAStatus(scanType: string): ShipmentStatus {\n return (SMSAStatusCodes[scanType] as ShipmentStatus) ?? \"unknown\";\n}\n\n/**\n * Resolve a scan's Date, applying its ScanTimeZone offset when present\n * (consistent with mapTrackingEvent / mapShipmentResponse timestamp handling).\n */\nfunction scanDate(scan: SMSATrackingScan): Date {\n return new Date(\n scan.ScanTimeZone\n ? `${scan.ScanDateTime}${scan.ScanTimeZone}`\n : scan.ScanDateTime,\n );\n}\n\nfunction scanTimestampMs(scan: SMSATrackingScan): number {\n return scanDate(scan).getTime();\n}\n\n/**\n * Derive the current shipment status from tracking scans.\n * Defensively sorts by (zone-adjusted) ScanDateTime descending before taking\n * the latest.\n */\nfunction deriveStatusFromScans(\n scans: SMSATrackingScan[] | undefined,\n isDelivered?: boolean,\n): { status: ShipmentStatus; statusLabel: string } {\n if (isDelivered) {\n return { status: \"delivered\", statusLabel: \"Delivered\" };\n }\n // Records may omit Scans entirely (freshly-booked AWB, partial bulk record).\n const safeScans = scans ?? [];\n if (safeScans.length === 0) {\n return { status: \"unknown\", statusLabel: \"Unknown\" };\n }\n const sorted = [...safeScans].sort(\n (a, b) => scanTimestampMs(b) - scanTimestampMs(a),\n );\n const latest = sorted[0]!;\n return {\n status: mapSMSAStatus(latest.ScanType),\n statusLabel: latest.ScanDescription,\n };\n}\n\n// ============================================================================\n// REQUEST MAPPERS\n// ============================================================================\n\n/**\n * Round a weight to 3 decimal places to avoid float-arithmetic noise\n * (e.g. 0.1 + 0.2 = 0.30000000000000004) leaking into the API payload.\n */\nfunction roundWeight(weight: number): number {\n return Math.round(weight * 1000) / 1000;\n}\n\n/** Strip non-digit characters from phone numbers (SMSA requires digits only). */\nfunction sanitizePhone(phone: string): string {\n return phone.replace(/\\D/g, \"\");\n}\n\n/**\n * Generate a fallback OrderNumber when the caller supplies no reference. Single\n * source of the `ORD-<epoch-ms>` format — the adapter uses it to fix a reference\n * on the input so the booked OrderNumber is surfaced back on the Shipment, and\n * the request mappers reference it as their type-required default.\n */\nexport function generateOrderNumber(): string {\n return `ORD-${Date.now()}`;\n}\n\n/**\n * Format the ShipDate as the Saudi (UTC+3) wall-clock, with no zone suffix.\n *\n * SMSA treats a bare (zone-less) timestamp as Saudi local time (UTC+3) — its\n * own responses come back bare and the response mapper appends `+03:00` to them.\n * Sending `new Date().toISOString().slice(0, 19)` (zero-offset UTC wall-clock)\n * therefore lands a day early between ~21:00–24:00 Saudi time, so shift by +3h\n * before formatting.\n */\nfunction smsaShipDate(): string {\n return new Date(Date.now() + 3 * 60 * 60 * 1000)\n .toISOString()\n .slice(0, 19);\n}\n\nfunction mapAddress(\n addr: CreateShipmentInput[\"shipper\"] | CreateShipmentInput[\"consignee\"],\n opts?: { includeShortCode?: boolean },\n): SMSAShipmentAddress {\n const result: SMSAShipmentAddress = {\n ContactName: addr.name,\n ContactPhoneNumber: sanitizePhone(addr.phone),\n Country: addr.countryCode,\n City: addr.city,\n AddressLine1: addr.line1,\n AddressLine2: addr.line2,\n District: addr.neighbourhood ?? addr.state,\n PostalCode: addr.postalCode,\n };\n\n if (addr.coordinates) {\n result.Coordinates = `${addr.coordinates.latitude},${addr.coordinates.longitude}`;\n }\n\n // ShortCode is valid only on the consignee address per the SMSA spec.\n if (opts?.includeShortCode && addr.nationalAddress?.shortCode) {\n result.ShortCode = addr.nationalAddress.shortCode;\n }\n\n return result;\n}\n\nexport function mapCreateB2CRequest(\n input: CreateShipmentInput,\n): SMSACreateB2CShipmentRequest {\n const totalPieces = input.parcels.reduce((sum, p) => sum + p.pieces, 0);\n const totalWeight = input.parcels.reduce(\n (sum, p) =>\n sum +\n (p.weight.unit === \"lb\" ? p.weight.value * 0.453592 : p.weight.value),\n 0,\n );\n\n const consigneeAddress = mapAddress(input.consignee, {\n includeShortCode: true,\n });\n if (input.options?.metadata?.consigneeId) {\n consigneeAddress.ConsigneeID = input.options.metadata.consigneeId as string;\n }\n\n return {\n ConsigneeAddress: consigneeAddress,\n ShipperAddress: mapAddress(input.shipper),\n OrderNumber: input.reference ?? generateOrderNumber(),\n CODAmount: input.cod?.enabled ? input.cod.amount : 0,\n DeclaredValue: input.declaredValue?.amount ?? 0,\n ContentDescription: input.parcels[0]?.description ?? \"Shipment contents\",\n Parcels: totalPieces,\n // SMSA reads bare timestamps as Saudi local time (UTC+3), so send the\n // UTC+3 wall-clock rather than zero-offset UTC.\n ShipDate: smsaShipDate(),\n // When COD is enabled, its currency is the amount physically collected\n // and must win over the declared-value currency.\n ShipmentCurrency:\n (input.cod?.enabled ? input.cod.currency : undefined) ??\n input.declaredValue?.currency ??\n input.cod?.currency ??\n \"SAR\",\n Weight: roundWeight(totalWeight),\n WeightUnit: \"KG\",\n WaybillType: input.labelFormat === \"ZPL\" ? \"ZPL\" : \"PDF\",\n ServiceCode: input.serviceType,\n SMSARetailID: (input.options?.metadata?.smsaRetailId as string) ?? \"0\",\n VatPaid: (input.options?.metadata?.vatPaid as boolean) ?? true,\n DutyPaid: (input.options?.metadata?.dutyPaid as boolean) ?? false,\n };\n}\n\n/**\n * Map to C2B (reverse pickup) request.\n * In C2B flow, the consignee is the pickup point (customer returning),\n * and the shipper is the return-to address (merchant warehouse).\n */\nexport function mapCreateC2BRequest(\n input: CreateShipmentInput,\n): SMSACreateC2BShipmentRequest {\n const totalPieces = input.parcels.reduce((sum, p) => sum + p.pieces, 0);\n const totalWeight = input.parcels.reduce(\n (sum, p) =>\n sum +\n (p.weight.unit === \"lb\" ? p.weight.value * 0.453592 : p.weight.value),\n 0,\n );\n\n return {\n PickupAddress: mapAddress(input.consignee, { includeShortCode: true }),\n ReturnToAddress: mapAddress(input.shipper),\n OrderNumber: input.reference ?? generateOrderNumber(),\n DeclaredValue: input.declaredValue?.amount ?? 0.1,\n ContentDescription:\n input.parcels[0]?.description ?? \"Return shipment contents\",\n Parcels: totalPieces,\n // SMSA reads bare timestamps as Saudi local time (UTC+3), so send the\n // UTC+3 wall-clock rather than zero-offset UTC.\n ShipDate: smsaShipDate(),\n // When COD is enabled, its currency is the amount physically collected\n // and must win over the declared-value currency.\n ShipmentCurrency:\n (input.cod?.enabled ? input.cod.currency : undefined) ??\n input.declaredValue?.currency ??\n input.cod?.currency ??\n \"SAR\",\n Weight: roundWeight(totalWeight),\n WeightUnit: \"KG\",\n WaybillType: input.labelFormat === \"ZPL\" ? \"ZPL\" : \"PDF\",\n ServiceCode: input.serviceType ?? \"EDCR\",\n SMSARetailID: (input.options?.metadata?.smsaRetailId as string) ?? \"0\",\n };\n}\n\n// ============================================================================\n// RESPONSE MAPPERS\n// ============================================================================\n\nexport function mapShipmentResponse(\n data: SMSAShipmentResponse,\n input: CreateShipmentInput,\n): Shipment {\n const firstWaybill = data.waybills?.[0];\n const trackingNumber = firstWaybill?.awb ?? data.sawb;\n\n if (!trackingNumber) {\n throw new APIError(\"No tracking number in shipment response\", {\n carrier: \"smsaexpress\",\n raw: data,\n });\n }\n\n return {\n carrier: \"smsaexpress\",\n trackingNumber,\n reference: input.reference,\n status: \"created\",\n statusLabel: \"Created\",\n codAmount: input.cod?.enabled ? input.cod.amount : undefined,\n declaredValue: input.declaredValue?.amount,\n // When COD is enabled, its currency is the amount physically collected\n // and must win over the declared-value currency.\n currency:\n (input.cod?.enabled ? input.cod.currency : undefined) ??\n input.declaredValue?.currency ??\n input.cod?.currency ??\n \"SAR\",\n returnLabel: firstWaybill?.returnBarcode\n ? `data:application/pdf;base64,${firstWaybill.returnBarcode}`\n : undefined,\n // Guard a missing createDate so we never build `new Date(\"undefined+03:00\")`\n // (Invalid Date). Append the SMSA timezone (+03:00) only to bare timestamps.\n createdAt: data.createDate\n ? new Date(\n /[Z]$|[+-]\\d{2}(:\\d{2})?$/.test(data.createDate)\n ? data.createDate\n : `${data.createDate}+03:00`,\n )\n : new Date(),\n raw: data,\n };\n}\n\nexport function mapTrackingEvent(scan: SMSATrackingScan): TrackingEvent {\n return {\n timestamp: new Date(\n scan.ScanTimeZone\n ? `${scan.ScanDateTime}${scan.ScanTimeZone}`\n : scan.ScanDateTime,\n ),\n statusCode: scan.ScanType,\n status: mapSMSAStatus(scan.ScanType),\n description: scan.ScanDescription,\n location: scan.City,\n };\n}\n\nexport function mapTrackingResult(data: SMSATrackingResponse): TrackingResult {\n // Real API records (freshly-booked AWB, partial bulk record) may omit Scans\n // entirely; default to [] so a scan-less record yields \"unknown\" instead of\n // throwing (and failing the whole trackMultiple batch).\n const scans = data.Scans ?? [];\n const { status, statusLabel } = deriveStatusFromScans(scans, data.isDelivered);\n\n const deliveredScan = scans.find((s) => s.ScanType === \"DL\");\n const deliveredTimestamp = deliveredScan\n ? new Date(\n deliveredScan.ScanTimeZone\n ? `${deliveredScan.ScanDateTime}${deliveredScan.ScanTimeZone}`\n : deliveredScan.ScanDateTime,\n )\n : undefined;\n\n return {\n trackingNumber: data.AWB,\n carrier: \"smsaexpress\",\n reference: data.Reference || undefined,\n status,\n statusLabel,\n events: scans.map(mapTrackingEvent),\n deliveryDate: deliveredTimestamp,\n codAmount: data.CODAmount > 0 ? data.CODAmount : undefined,\n pieces: data.Pieces,\n raw: data,\n };\n}\n\nexport function mapCity(city: SMSACityLookupItem): City {\n return {\n nameEn: city.cityName,\n code: city.cityCode,\n };\n}\n\nexport function mapOffice(office: SMSAOfficeLookupItem): Location {\n const [lat, lng] = (office.coordinates || \"\")\n .split(\",\")\n .map((s) => parseFloat(s.trim()));\n\n return {\n id: office.code,\n name: office.address,\n nameAr: office.addressAR,\n city: office.cityName,\n latitude: Number.isNaN(lat) ? undefined : lat,\n longitude: Number.isNaN(lng) ? undefined : lng,\n };\n}\n\nexport function mapCreate2WayRequest(\n input: CreateShipmentInput,\n): SMSACreate2WayShipmentRequest {\n const totalPieces = input.parcels.reduce((sum, p) => sum + p.pieces, 0);\n const totalWeight = input.parcels.reduce(\n (sum, p) =>\n sum +\n (p.weight.unit === \"lb\" ? p.weight.value * 0.453592 : p.weight.value),\n 0,\n );\n\n const consigneeAddress = mapAddress(input.consignee, {\n includeShortCode: true,\n });\n if (input.options?.metadata?.consigneeId) {\n consigneeAddress.ConsigneeID = input.options.metadata.consigneeId as string;\n }\n\n return {\n ConsigneeAddress: consigneeAddress,\n ShipperAddress: mapAddress(input.shipper),\n OrderNumber: input.reference ?? generateOrderNumber(),\n DeclaredValue: input.declaredValue?.amount ?? 0,\n ContentDescription: input.parcels[0]?.description ?? \"Shipment contents\",\n Parcels: totalPieces,\n // SMSA reads bare timestamps as Saudi local time (UTC+3), so send the\n // UTC+3 wall-clock rather than zero-offset UTC.\n ShipDate: smsaShipDate(),\n ShipmentCurrency: input.declaredValue?.currency ?? \"SAR\",\n Weight: roundWeight(totalWeight),\n WeightUnit: \"KG\",\n WaybillType: input.labelFormat === \"ZPL\" ? \"ZPL\" : \"PDF\",\n SMSARetailID: (input.options?.metadata?.smsaRetailId as string) ?? \"0\",\n VatPaid: (input.options?.metadata?.vatPaid as boolean) ?? true,\n DutyPaid: (input.options?.metadata?.dutyPaid as boolean) ?? false,\n };\n}\n\n// ============================================================================\n// WEBHOOK MAPPERS\n// ============================================================================\n\n/**\n * Timing-safe string comparison to prevent timing attacks on auth tokens.\n */\nfunction timingSafeEqual(a: string, b: string): boolean {\n const encoder = new TextEncoder();\n const bufA = encoder.encode(a);\n const bufB = encoder.encode(b);\n if (bufA.byteLength !== bufB.byteLength) return false;\n let mismatch = 0;\n for (let i = 0; i < bufA.byteLength; i++) {\n mismatch |= bufA[i]! ^ bufB[i]!;\n }\n return mismatch === 0;\n}\n\nfunction verifyWebhookAuth(options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n}): void {\n const { headers = {}, queryParams = {}, config } = options ?? {};\n\n // Verify auth via header (case-insensitive lookup, timing-safe comparison)\n if (config?.authHeader && config?.authValue) {\n const lowerKey = config.authHeader.toLowerCase();\n const headerValue = Object.entries(headers).find(\n ([k]) => k.toLowerCase() === lowerKey,\n )?.[1];\n if (!headerValue || !timingSafeEqual(headerValue, config.authValue)) {\n throw new WebhookVerificationError(\"Invalid webhook auth header\", {\n carrier: \"smsaexpress\",\n });\n }\n }\n\n // Verify auth via query param (SMSA uses API key as query param, timing-safe)\n if (config?.authQueryParam && config?.authQueryValue) {\n const paramValue = queryParams[config.authQueryParam];\n if (!paramValue || !timingSafeEqual(paramValue, config.authQueryValue)) {\n throw new WebhookVerificationError(\"Invalid webhook auth query param\", {\n carrier: \"smsaexpress\",\n });\n }\n }\n}\n\nfunction mapWebhookShipmentToEvent(\n shipment: SMSAWebhookShipment,\n): WebhookEvent {\n // A webhook record may arrive without Scans; default to [] so a scan-less\n // shipment yields \"unknown\" instead of throwing.\n const scans = shipment.Scans ?? [];\n const { status, statusLabel } = deriveStatusFromScans(\n scans,\n shipment.isDelivered,\n );\n\n // Sort scans descending (zone-adjusted) to get the latest one for\n // timestamp/statusCode.\n const sorted = [...scans].sort(\n (a, b) => scanTimestampMs(b) - scanTimestampMs(a),\n );\n const latestScan = sorted[0];\n const timestamp = latestScan ? scanDate(latestScan) : new Date();\n\n return {\n carrier: \"smsaexpress\",\n eventType: \"status_update\",\n trackingNumber: shipment.AWB,\n reference: shipment.Reference || undefined,\n status,\n statusCode: latestScan?.ScanType ?? \"unknown\",\n statusLabel,\n timestamp,\n raw: shipment,\n };\n}\n\n/**\n * Map a webhook shipment to one WebhookEvent PER scan, in chronological\n * (oldest → newest) order.\n *\n * SMSA can report several new scans for the same shipment in a single\n * webhook call (e.g. AF, OD, DL all at once). Collapsing that into only the\n * latest scan silently drops intermediate transitions/history, so this\n * expands every scan into its own event.\n */\nfunction mapWebhookShipmentToEvents(\n shipment: SMSAWebhookShipment,\n): WebhookEvent[] {\n const scans = shipment.Scans ?? [];\n\n if (scans.length === 0) {\n // No scans to expand — fall back to the single derived (possibly\n // \"unknown\"/isDelivered-driven) event.\n return [mapWebhookShipmentToEvent(shipment)];\n }\n\n const sorted = [...scans].sort(\n (a, b) => scanTimestampMs(a) - scanTimestampMs(b),\n );\n\n return sorted.map((scan, index) => {\n // Only the chronologically-last scan can be elevated to \"delivered\" by\n // the isDelivered flag; earlier scans reflect their own scan type.\n const isLatest = index === sorted.length - 1;\n const status: ShipmentStatus =\n isLatest && shipment.isDelivered\n ? \"delivered\"\n : mapSMSAStatus(scan.ScanType);\n\n return {\n carrier: \"smsaexpress\",\n eventType: \"status_update\",\n trackingNumber: shipment.AWB,\n reference: shipment.Reference || undefined,\n status,\n statusCode: scan.ScanType,\n statusLabel: scan.ScanDescription,\n timestamp: scanDate(scan),\n raw: shipment,\n };\n });\n}\n\nfunction validateWebhookPayload(payload: unknown): SMSAWebhookShipment[] {\n if (!Array.isArray(payload)) {\n throw new ValidationError(\n \"Invalid SMSA webhook payload: expected an array of shipments\",\n { raw: payload },\n );\n }\n\n if (payload.length === 0) {\n throw new ValidationError(\"Invalid SMSA webhook payload: empty array\", {\n raw: payload,\n });\n }\n\n for (const item of payload) {\n // Only AWB is truly required (it becomes the event's trackingNumber). Scans\n // may be absent on a freshly-booked record — every mapper defends with\n // `Scans ?? []` and yields an \"unknown\" status — so requiring it here would\n // wrongly reject valid scan-less webhooks.\n if (!item || typeof item !== \"object\" || !(\"AWB\" in item)) {\n throw new ValidationError(\n \"Invalid SMSA webhook payload: shipment missing required field (AWB)\",\n { raw: item },\n );\n }\n }\n\n return payload as SMSAWebhookShipment[];\n}\n\n/**\n * Parse an SMSA webhook payload and return a single WebhookEvent\n * for the first shipment in the batch.\n *\n * SMSA sends webhooks as an array of shipments. This function returns\n * only the first item — use `parseSMSAWebhookBatch()` for full batch parsing.\n */\nexport function parseSMSAWebhook(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n): WebhookEvent {\n verifyWebhookAuth(options);\n const shipments = validateWebhookPayload(payload);\n return mapWebhookShipmentToEvent(shipments[0]!);\n}\n\n/**\n * Parse an SMSA webhook payload and return a WebhookEvent for every\n * scan of every shipment in the batch (in chronological order per shipment).\n *\n * SMSA sends webhook payloads as an array of shipments, each with their own\n * tracking scans, and a single call can carry multiple new scans for the\n * same shipment (e.g. AF, OD, DL together) — each becomes its own event so\n * no intermediate transition/history is dropped.\n */\nexport function parseSMSAWebhookBatch(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n): WebhookEvent[] {\n verifyWebhookAuth(options);\n const shipments = validateWebhookPayload(payload);\n return shipments.flatMap(mapWebhookShipmentToEvents);\n}\n",
|
|
7
|
-
"// file: src/carriers/smsaexpress/adapter.ts\n/**\n * SMSA Express Carrier Adapter\n * Full implementation of the CarrierAdapter interface for SMSA Express API.\n */\n\nimport { APIError, RateLimitError } from \"../../core/errors\";\nimport { HttpClient } from \"../../core/http\";\nimport type {\n CarrierConfig,\n City,\n CreateShipmentInput,\n Location,\n Shipment,\n TrackingResult,\n WebhookConfig,\n WebhookEvent,\n} from \"../../core/types\";\nimport { BaseCarrierAdapter } from \"../base\";\nimport {\n generateOrderNumber,\n mapCity,\n mapCreate2WayRequest,\n mapCreateB2CRequest,\n mapCreateC2BRequest,\n mapOffice,\n mapShipmentResponse,\n mapTrackingResult,\n parseSMSAWebhook,\n parseSMSAWebhookBatch,\n} from \"./mappers\";\nimport type {\n SMSACityLookupItem,\n SMSAOfficeLookupItem,\n SMSAPushIdDetailsRequest,\n SMSAPushIdDetailsResponse,\n SMSASendInvoiceRequest,\n SMSAShipmentResponse,\n SMSAShortAddressResponse,\n SMSATrackingResponse,\n} from \"./types\";\n\nconst SMSA_SANDBOX_URL = \"https://ecomapis-sandbox.azurewebsites.net\";\nconst SMSA_PRODUCTION_URL = \"https://ecomapis.smsaexpress.com\";\n\n/** Reverse-pickup / C2B service codes */\nconst C2B_SERVICE_CODES = new Set([\"EDCR\"]);\n\nexport interface SMSAExpressConfig extends CarrierConfig {\n credentials: {\n apiKey: string;\n };\n}\n\nexport class SMSAExpressAdapter extends BaseCarrierAdapter {\n readonly name = \"smsaexpress\";\n readonly supportedCountries = [\n \"SA\",\n \"AE\",\n \"BH\",\n \"EG\",\n \"KW\",\n \"OM\",\n \"QA\",\n \"JO\",\n ];\n\n private http: HttpClient;\n\n constructor(config: SMSAExpressConfig) {\n super(config);\n this.http = new HttpClient({\n baseUrl: this.getBaseUrl(),\n carrier: \"smsaexpress\",\n headers: {\n apikey: config.credentials.apiKey,\n },\n });\n }\n\n protected getBaseUrl(): string {\n return this.config.mode === \"production\"\n ? SMSA_PRODUCTION_URL\n : SMSA_SANDBOX_URL;\n }\n\n // =========================================================================\n // SHIPPING\n // =========================================================================\n\n /**\n * Ensure the input carries a `reference` so the OrderNumber the shipment is\n * booked under is the exact value surfaced back on `Shipment.reference` (which\n * the caller needs for {@link trackByReference}). When no reference is\n * supplied we generate one here via the shared {@link generateOrderNumber} and\n * pass this prepared input to BOTH the request mapper and the response mapper,\n * so the request OrderNumber and the response reference always agree (otherwise\n * each would call `Date.now()` independently and disagree).\n */\n private withOrderNumber(input: CreateShipmentInput): CreateShipmentInput {\n if (input.reference) {\n return input;\n }\n return { ...input, reference: generateOrderNumber() };\n }\n\n protected async executeCreateShipment(\n input: CreateShipmentInput,\n ): Promise<Shipment> {\n const prepared = this.withOrderNumber(input);\n const isC2B =\n prepared.serviceType !== undefined &&\n C2B_SERVICE_CODES.has(prepared.serviceType.trim().toUpperCase());\n\n if (isC2B) {\n return this.createC2BShipment(prepared);\n }\n\n const request = mapCreateB2CRequest(prepared);\n const response = await this.http.post<SMSAShipmentResponse>(\n \"/api/shipment/b2c/new\",\n request,\n );\n\n return mapShipmentResponse(response, prepared);\n }\n\n private async createC2BShipment(\n input: CreateShipmentInput,\n ): Promise<Shipment> {\n const request = mapCreateC2BRequest(input);\n const response = await this.http.post<SMSAShipmentResponse>(\n \"/api/c2b/new\",\n request,\n );\n\n return mapShipmentResponse(response, input);\n }\n\n /**\n * Cancel a reverse-pickup (C2B) shipment.\n *\n * **Important:** SMSA only supports cancellation for C2B/reverse-pickup\n * shipments, via the C2B endpoint. B2C shipments cannot be cancelled through\n * the SMSA API: the endpoint responds without a cancellation confirmation,\n * which is surfaced as an {@link APIError} (with `code: \"CANCELLATION_UNCONFIRMED\"`)\n * rather than a misleading `false`. That `code` lets callers distinguish this\n * \"carrier did not confirm\" case from a genuine request failure (network/4xx/5xx)\n * and fall back accordingly. Consistent with the other adapters, this method\n * either returns `true` or throws.\n *\n * Success is detected with a negation-aware check: a cancel token must be\n * present AND no negation token may be. A bare `includes(\"cancelled\")` would\n * wrongly succeed on negatives like \"Shipment cannot be cancelled\",\n * \"not cancelled\" or \"cancellation failed\". Note \"already cancelled\" carries\n * no negation token, so it correctly reports success (idempotent cancel).\n */\n async cancelShipment(trackingNumber: string): Promise<boolean> {\n const response = await this.http.post<string>(\n `/api/c2b/cancel/${encodeURIComponent(trackingNumber)}`,\n );\n // A non-string (JSON) success response is treated as success.\n if (typeof response !== \"string\") {\n return true;\n }\n // Success messages contain a cancel token (e.g. \"Shipment Cancelled\n // Successfully!\"), but so do negative ones (\"Shipment cannot be cancelled\",\n // \"cancellation failed\"). Treat as success only when a cancel token is\n // present AND no negation token is — so \"already cancelled\" (idempotent\n // success) still passes while \"not cancelled\" does not. Anything else means\n // the carrier did NOT cancel — most commonly because this is a B2C shipment,\n // which the SMSA API cannot cancel.\n const hasCancelToken = /cancel/i.test(response);\n const hasNegation =\n /\\b(?:not|can\\s?not|can'?t|cant|unable|fail(?:ed|ure)?|invalid|reject(?:ed)?|error)\\b/i.test(\n response,\n );\n if (hasCancelToken && !hasNegation) {\n return true;\n }\n // Distinguish \"carrier responded but did not confirm cancellation\" from a\n // genuine request failure (network/4xx/5xx, which throws separately via\n // HttpClient) so callers can tell \"unconfirmed\" apart from \"failed\" and\n // fall back accordingly (e.g. B2C shipments cannot be cancelled via the\n // SMSA API at all).\n throw new APIError(\n response.trim() || \"SMSA did not confirm cancellation\",\n {\n carrier: \"smsaexpress\",\n code: \"CANCELLATION_UNCONFIRMED\",\n raw: response,\n },\n );\n }\n\n // =========================================================================\n // TRACKING\n // =========================================================================\n\n async track(trackingNumber: string): Promise<TrackingResult> {\n const response = await this.http.get<SMSATrackingResponse>(\n `/api/track/single/${encodeURIComponent(trackingNumber)}`,\n );\n\n return mapTrackingResult(response);\n }\n\n async trackMultiple(trackingNumbers: string[]): Promise<TrackingResult[]> {\n const response = await this.http.post<SMSATrackingResponse[]>(\n \"/api/track/bulk/\",\n trackingNumbers,\n { retry: true },\n );\n\n return response.map(mapTrackingResult);\n }\n\n async trackByReference(reference: string): Promise<TrackingResult> {\n const response = await this.http.get<SMSATrackingResponse>(\n `/api/track/reference/${encodeURIComponent(reference)}`,\n );\n\n return mapTrackingResult(response);\n }\n\n // =========================================================================\n // LABELS\n // =========================================================================\n\n async getLabel(\n trackingNumber: string,\n _format?: \"PDF\" | \"ZPL\" | \"PNG\",\n ): Promise<string> {\n // SMSA returns the waybill file (base64 PDF) as part of the shipment query.\n // Try B2C first (most common), then C2B as fallback.\n const encoded = encodeURIComponent(trackingNumber);\n\n for (const path of [\n `/api/shipment/b2c/query/${encoded}`,\n `/api/c2b/query/${encoded}`,\n ]) {\n try {\n const response = await this.http.get<SMSAShipmentResponse>(path);\n const waybill = response.waybills?.[0];\n if (waybill?.awbFile) {\n return `data:application/pdf;base64,${waybill.awbFile}`;\n }\n } catch (error) {\n // Only swallow genuine 4xx (non-429) API errors (shipment type mismatch\n // / not found) so we can try the next path. Re-throw everything else:\n // - non-APIError → auth (AuthenticationError) and network (NetworkError)\n // are not APIErrors, so this clause re-throws them;\n // - RateLimitError → a 429 that must propagate, not masquerade as\n // \"No label found\" (it extends APIError, so guard it explicitly);\n // - 5xx server errors.\n if (\n !(error instanceof APIError) ||\n error instanceof RateLimitError ||\n (error.statusCode !== undefined && error.statusCode >= 500)\n ) {\n throw error;\n }\n }\n }\n\n throw new APIError(\"No label found for shipment\", {\n carrier: \"smsaexpress\",\n raw: { trackingNumber },\n });\n }\n\n // =========================================================================\n // CITIES & LOCATIONS\n // =========================================================================\n\n async getCities(countryCode = \"SA\"): Promise<City[]> {\n const response = await this.http.get<SMSACityLookupItem[]>(\n `/api/lookup/cities/${encodeURIComponent(countryCode)}`,\n );\n\n // Guard the shape before mapping: a non-array (e.g. an error object at\n // HTTP 200) would otherwise throw an opaque \"response.map is not a function\"\n // far from the cause.\n if (!Array.isArray(response)) {\n throw new APIError(\"SMSA cities lookup returned an unexpected shape\", {\n carrier: \"smsaexpress\",\n raw: response,\n });\n }\n\n return response.map(mapCity);\n }\n\n async getDropoffLocations(): Promise<Location[]> {\n const response = await this.http.get<SMSAOfficeLookupItem[]>(\n \"/api/lookup/smsaoffices\",\n );\n\n if (!Array.isArray(response)) {\n throw new APIError(\"SMSA offices lookup returned an unexpected shape\", {\n carrier: \"smsaexpress\",\n raw: response,\n });\n }\n\n return response.map(mapOffice);\n }\n\n // =========================================================================\n // 2-WAY SHIPMENT\n // =========================================================================\n\n async create2WayShipment(input: CreateShipmentInput): Promise<Shipment> {\n const prepared = this.withOrderNumber(input);\n const request = mapCreate2WayRequest(prepared);\n const response = await this.http.post<SMSAShipmentResponse>(\n \"/api/TwoWayShipment/new\",\n request,\n );\n\n return mapShipmentResponse(response, prepared);\n }\n\n // =========================================================================\n // INVOICE & ID OPERATIONS (SMSA-specific)\n // =========================================================================\n\n async sendInvoice(request: SMSASendInvoiceRequest): Promise<string> {\n return this.http.post<string>(\"/api/invoice\", request);\n }\n\n async validateShortAddress(\n shortCode: string,\n ): Promise<SMSAShortAddressResponse> {\n return this.http.get<SMSAShortAddressResponse>(\n `/api/Lookup/FullAddressByShortCode/${encodeURIComponent(shortCode)}`,\n );\n }\n\n async pushIdDetails(\n request: SMSAPushIdDetailsRequest,\n ): Promise<SMSAPushIdDetailsResponse> {\n return this.http.post<SMSAPushIdDetailsResponse>(\n \"/api/shipment/identity-details\",\n request,\n );\n }\n\n // =========================================================================\n // WEBHOOKS\n // =========================================================================\n\n parseWebhook(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n ): WebhookEvent {\n return parseSMSAWebhook(payload, options);\n }\n\n /**\n * Parse a batch SMSA webhook payload into multiple events.\n *\n * SMSA sends webhook payloads as an array of shipments, each with their own\n * tracking scans. This method returns a WebhookEvent for every shipment\n * in the payload.\n */\n parseWebhookBatch(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n ): WebhookEvent[] {\n return parseSMSAWebhookBatch(payload, options);\n }\n}\n"
|
|
7
|
+
"// file: src/carriers/smsaexpress/adapter.ts\n/**\n * SMSA Express Carrier Adapter\n * Full implementation of the CarrierAdapter interface for SMSA Express API.\n */\n\nimport {\n CITIES_CACHE_TTL,\n CITIES_FAILURE_COOLDOWN,\n findCityMatch,\n} from \"../../core/city-resolver\";\nimport { APIError, RateLimitError, ValidationError } from \"../../core/errors\";\nimport { HttpClient } from \"../../core/http\";\nimport type {\n CarrierConfig,\n City,\n CreateShipmentInput,\n Location,\n Shipment,\n TrackingResult,\n WebhookConfig,\n WebhookEvent,\n} from \"../../core/types\";\nimport { BaseCarrierAdapter } from \"../base\";\nimport {\n generateOrderNumber,\n mapCity,\n mapCreate2WayRequest,\n mapCreateB2CRequest,\n mapCreateC2BRequest,\n mapOffice,\n mapShipmentResponse,\n mapTrackingResult,\n parseSMSAWebhook,\n parseSMSAWebhookBatch,\n} from \"./mappers\";\nimport type {\n SMSACityLookupItem,\n SMSAOfficeLookupItem,\n SMSAPushIdDetailsRequest,\n SMSAPushIdDetailsResponse,\n SMSASendInvoiceRequest,\n SMSAShipmentResponse,\n SMSAShortAddressResponse,\n SMSATrackingResponse,\n} from \"./types\";\n\nconst SMSA_SANDBOX_URL = \"https://ecomapis-sandbox.azurewebsites.net\";\nconst SMSA_PRODUCTION_URL = \"https://ecomapis.smsaexpress.com\";\n\n/** Reverse-pickup / C2B service codes */\nconst C2B_SERVICE_CODES = new Set([\"EDCR\"]);\n\nexport interface SMSAExpressConfig extends CarrierConfig {\n credentials: {\n apiKey: string;\n };\n}\n\nexport class SMSAExpressAdapter extends BaseCarrierAdapter {\n readonly name = \"smsaexpress\";\n readonly supportedCountries = [\n \"SA\",\n \"AE\",\n \"BH\",\n \"EG\",\n \"KW\",\n \"OM\",\n \"QA\",\n \"JO\",\n ];\n\n private http: HttpClient;\n\n /** Cached SMSA Saudi cities list for city validation on booking */\n private citiesCache: City[] | null = null;\n private citiesCacheTime = 0;\n /** Timestamp of the last failed cities-lookup attempt, if any */\n private citiesFetchFailedAt = 0;\n\n constructor(config: SMSAExpressConfig) {\n super(config);\n this.http = new HttpClient({\n baseUrl: this.getBaseUrl(),\n carrier: \"smsaexpress\",\n headers: {\n apikey: config.credentials.apiKey,\n },\n });\n }\n\n protected getBaseUrl(): string {\n return this.config.mode === \"production\"\n ? SMSA_PRODUCTION_URL\n : SMSA_SANDBOX_URL;\n }\n\n // =========================================================================\n // SHIPPING\n // =========================================================================\n\n /**\n * Ensure the input carries a `reference` so the OrderNumber the shipment is\n * booked under is the exact value surfaced back on `Shipment.reference` (which\n * the caller needs for {@link trackByReference}). When no reference is\n * supplied we generate one here via the shared {@link generateOrderNumber} and\n * pass this prepared input to BOTH the request mapper and the response mapper,\n * so the request OrderNumber and the response reference always agree (otherwise\n * each would call `Date.now()` independently and disagree).\n */\n private withOrderNumber(input: CreateShipmentInput): CreateShipmentInput {\n if (input.reference) {\n return input;\n }\n return { ...input, reference: generateOrderNumber() };\n }\n\n /**\n * Load the SMSA Saudi cities list and cache it, mirroring the Aymakan\n * adapter's TTL + failure-cooldown behavior: a lookup outage falls back to\n * an empty cache (pass-through resolution) so it never blocks bookings.\n */\n private async ensureCitiesLoaded(): Promise<void> {\n const now = Date.now();\n if (this.citiesCache && now - this.citiesCacheTime < CITIES_CACHE_TTL) {\n return;\n }\n if (now - this.citiesFetchFailedAt < CITIES_FAILURE_COOLDOWN) {\n if (!this.citiesCache) this.citiesCache = [];\n return;\n }\n try {\n this.citiesCache = await this.getCities();\n this.citiesCacheTime = now;\n } catch {\n this.citiesFetchFailedAt = now;\n if (!this.citiesCache) this.citiesCache = [];\n }\n }\n\n /**\n * Validate/normalize a Saudi address city against SMSA's own city list\n * before booking (SMSA's City field is list-validated server-side, so an\n * unknown value previously produced an opaque carrier rejection). Strict:\n * when the list is loaded and nothing matches, fail fast with a clear,\n * field-scoped error. Lenient when the list is unavailable (outage) and for\n * non-SA addresses, whose cities are not in the SA lookup.\n */\n private resolveCityStrict(\n address: CreateShipmentInput[\"shipper\"] | CreateShipmentInput[\"consignee\"],\n field: \"shipper.city\" | \"consignee.city\",\n ): string {\n if (address.countryCode !== \"SA\") return address.city;\n if (!this.citiesCache || this.citiesCache.length === 0) return address.city;\n const match = findCityMatch(address.city, this.citiesCache);\n if (!match) {\n throw new ValidationError(\n `Unknown ${field.replace(\".city\", \"\")} city \"${address.city}\": not in SMSA's supported city list`,\n { field },\n );\n }\n return match.nameEn;\n }\n\n /** Resolve shipper + consignee cities for a booking (strict — see above). */\n private async resolveCitiesInInput(\n input: CreateShipmentInput,\n ): Promise<CreateShipmentInput> {\n await this.ensureCitiesLoaded();\n return {\n ...input,\n shipper: {\n ...input.shipper,\n city: this.resolveCityStrict(input.shipper, \"shipper.city\"),\n },\n consignee: {\n ...input.consignee,\n city: this.resolveCityStrict(input.consignee, \"consignee.city\"),\n },\n };\n }\n\n protected async executeCreateShipment(\n input: CreateShipmentInput,\n ): Promise<Shipment> {\n const prepared = await this.resolveCitiesInInput(\n this.withOrderNumber(input),\n );\n const isC2B =\n prepared.serviceType !== undefined &&\n C2B_SERVICE_CODES.has(prepared.serviceType.trim().toUpperCase());\n\n if (isC2B) {\n return this.createC2BShipment(prepared);\n }\n\n const request = mapCreateB2CRequest(prepared);\n const response = await this.http.post<SMSAShipmentResponse>(\n \"/api/shipment/b2c/new\",\n request,\n );\n\n return mapShipmentResponse(response, prepared);\n }\n\n private async createC2BShipment(\n input: CreateShipmentInput,\n ): Promise<Shipment> {\n const request = mapCreateC2BRequest(input);\n const response = await this.http.post<SMSAShipmentResponse>(\n \"/api/c2b/new\",\n request,\n );\n\n return mapShipmentResponse(response, input);\n }\n\n /**\n * Cancel a reverse-pickup (C2B) shipment.\n *\n * **Important:** SMSA only supports cancellation for C2B/reverse-pickup\n * shipments, via the C2B endpoint. B2C shipments cannot be cancelled through\n * the SMSA API: the endpoint responds without a cancellation confirmation,\n * which is surfaced as an {@link APIError} (with `code: \"CANCELLATION_UNCONFIRMED\"`)\n * rather than a misleading `false`. That `code` lets callers distinguish this\n * \"carrier did not confirm\" case from a genuine request failure (network/4xx/5xx)\n * and fall back accordingly. Consistent with the other adapters, this method\n * either returns `true` or throws.\n *\n * Success is detected with a negation-aware check: a cancel token must be\n * present AND no negation token may be. A bare `includes(\"cancelled\")` would\n * wrongly succeed on negatives like \"Shipment cannot be cancelled\",\n * \"not cancelled\" or \"cancellation failed\". Note \"already cancelled\" carries\n * no negation token, so it correctly reports success (idempotent cancel).\n */\n async cancelShipment(trackingNumber: string): Promise<boolean> {\n const response = await this.http.post<string>(\n `/api/c2b/cancel/${encodeURIComponent(trackingNumber)}`,\n );\n // A non-string (JSON) success response is treated as success.\n if (typeof response !== \"string\") {\n return true;\n }\n // Success messages contain a cancel token (e.g. \"Shipment Cancelled\n // Successfully!\"), but so do negative ones (\"Shipment cannot be cancelled\",\n // \"cancellation failed\"). Treat as success only when a cancel token is\n // present AND no negation token is — so \"already cancelled\" (idempotent\n // success) still passes while \"not cancelled\" does not. Anything else means\n // the carrier did NOT cancel — most commonly because this is a B2C shipment,\n // which the SMSA API cannot cancel.\n const hasCancelToken = /cancel/i.test(response);\n const hasNegation =\n /\\b(?:not|can\\s?not|can'?t|cant|unable|fail(?:ed|ure)?|invalid|reject(?:ed)?|error)\\b/i.test(\n response,\n );\n if (hasCancelToken && !hasNegation) {\n return true;\n }\n // Distinguish \"carrier responded but did not confirm cancellation\" from a\n // genuine request failure (network/4xx/5xx, which throws separately via\n // HttpClient) so callers can tell \"unconfirmed\" apart from \"failed\" and\n // fall back accordingly (e.g. B2C shipments cannot be cancelled via the\n // SMSA API at all).\n throw new APIError(\n response.trim() || \"SMSA did not confirm cancellation\",\n {\n carrier: \"smsaexpress\",\n code: \"CANCELLATION_UNCONFIRMED\",\n raw: response,\n },\n );\n }\n\n // =========================================================================\n // TRACKING\n // =========================================================================\n\n async track(trackingNumber: string): Promise<TrackingResult> {\n const response = await this.http.get<SMSATrackingResponse>(\n `/api/track/single/${encodeURIComponent(trackingNumber)}`,\n );\n\n return mapTrackingResult(response);\n }\n\n async trackMultiple(trackingNumbers: string[]): Promise<TrackingResult[]> {\n const response = await this.http.post<SMSATrackingResponse[]>(\n \"/api/track/bulk/\",\n trackingNumbers,\n { retry: true },\n );\n\n return response.map(mapTrackingResult);\n }\n\n async trackByReference(reference: string): Promise<TrackingResult> {\n const response = await this.http.get<SMSATrackingResponse>(\n `/api/track/reference/${encodeURIComponent(reference)}`,\n );\n\n return mapTrackingResult(response);\n }\n\n // =========================================================================\n // LABELS\n // =========================================================================\n\n async getLabel(\n trackingNumber: string,\n _format?: \"PDF\" | \"ZPL\" | \"PNG\",\n ): Promise<string> {\n // SMSA returns the waybill file (base64 PDF) as part of the shipment query.\n // Try B2C first (most common), then C2B as fallback.\n const encoded = encodeURIComponent(trackingNumber);\n\n for (const path of [\n `/api/shipment/b2c/query/${encoded}`,\n `/api/c2b/query/${encoded}`,\n ]) {\n try {\n const response = await this.http.get<SMSAShipmentResponse>(path);\n const waybill = response.waybills?.[0];\n if (waybill?.awbFile) {\n return `data:application/pdf;base64,${waybill.awbFile}`;\n }\n } catch (error) {\n // Only swallow genuine 4xx (non-429) API errors (shipment type mismatch\n // / not found) so we can try the next path. Re-throw everything else:\n // - non-APIError → auth (AuthenticationError) and network (NetworkError)\n // are not APIErrors, so this clause re-throws them;\n // - RateLimitError → a 429 that must propagate, not masquerade as\n // \"No label found\" (it extends APIError, so guard it explicitly);\n // - 5xx server errors.\n if (\n !(error instanceof APIError) ||\n error instanceof RateLimitError ||\n (error.statusCode !== undefined && error.statusCode >= 500)\n ) {\n throw error;\n }\n }\n }\n\n throw new APIError(\"No label found for shipment\", {\n carrier: \"smsaexpress\",\n raw: { trackingNumber },\n });\n }\n\n // =========================================================================\n // CITIES & LOCATIONS\n // =========================================================================\n\n async getCities(countryCode = \"SA\"): Promise<City[]> {\n const response = await this.http.get<SMSACityLookupItem[]>(\n `/api/lookup/cities/${encodeURIComponent(countryCode)}`,\n );\n\n // Guard the shape before mapping: a non-array (e.g. an error object at\n // HTTP 200) would otherwise throw an opaque \"response.map is not a function\"\n // far from the cause.\n if (!Array.isArray(response)) {\n throw new APIError(\"SMSA cities lookup returned an unexpected shape\", {\n carrier: \"smsaexpress\",\n raw: response,\n });\n }\n\n return response.map(mapCity);\n }\n\n async getDropoffLocations(): Promise<Location[]> {\n const response = await this.http.get<SMSAOfficeLookupItem[]>(\n \"/api/lookup/smsaoffices\",\n );\n\n if (!Array.isArray(response)) {\n throw new APIError(\"SMSA offices lookup returned an unexpected shape\", {\n carrier: \"smsaexpress\",\n raw: response,\n });\n }\n\n return response.map(mapOffice);\n }\n\n // =========================================================================\n // 2-WAY SHIPMENT\n // =========================================================================\n\n async create2WayShipment(input: CreateShipmentInput): Promise<Shipment> {\n const prepared = await this.resolveCitiesInInput(\n this.withOrderNumber(input),\n );\n const request = mapCreate2WayRequest(prepared);\n const response = await this.http.post<SMSAShipmentResponse>(\n \"/api/TwoWayShipment/new\",\n request,\n );\n\n return mapShipmentResponse(response, prepared);\n }\n\n // =========================================================================\n // INVOICE & ID OPERATIONS (SMSA-specific)\n // =========================================================================\n\n async sendInvoice(request: SMSASendInvoiceRequest): Promise<string> {\n return this.http.post<string>(\"/api/invoice\", request);\n }\n\n async validateShortAddress(\n shortCode: string,\n ): Promise<SMSAShortAddressResponse> {\n return this.http.get<SMSAShortAddressResponse>(\n `/api/Lookup/FullAddressByShortCode/${encodeURIComponent(shortCode)}`,\n );\n }\n\n async pushIdDetails(\n request: SMSAPushIdDetailsRequest,\n ): Promise<SMSAPushIdDetailsResponse> {\n return this.http.post<SMSAPushIdDetailsResponse>(\n \"/api/shipment/identity-details\",\n request,\n );\n }\n\n // =========================================================================\n // WEBHOOKS\n // =========================================================================\n\n parseWebhook(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n ): WebhookEvent {\n return parseSMSAWebhook(payload, options);\n }\n\n /**\n * Parse a batch SMSA webhook payload into multiple events.\n *\n * SMSA sends webhook payloads as an array of shipments, each with their own\n * tracking scans. This method returns a WebhookEvent for every shipment\n * in the payload.\n */\n parseWebhookBatch(\n payload: unknown,\n options?: {\n headers?: Record<string, string>;\n queryParams?: Record<string, string>;\n config?: WebhookConfig;\n },\n ): WebhookEvent[] {\n return parseSMSAWebhookBatch(payload, options);\n }\n}\n"
|
|
8
8
|
],
|
|
9
|
-
"mappings": ";;;;;;;;;;AAMO,IAAM,cAAc;AAAA,EAEzB,oBAAoB;AAAA,EAEpB,kBAAkB;AAAA,EAElB,aAAa;AACf;AAYO,IAAM,kBAA0C;AAAA,EAErD,IAAI;AAAA,EAGJ,IAAI;AAAA,EAGJ,IAAI;AAAA,EAGJ,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EAGL,IAAI;AAAA,EACJ,KAAK;AAAA,EAGL,IAAI;AAAA,EACJ,IAAI;AAAA,EAGJ,IAAI;AAAA,EACJ,KAAK;AAAA,EACL,MAAM;AAAA,EAGN,KAAK;AAAA,EACL,KAAK;AAAA,EACL,KAAK;AAAA,EAGL,IAAI;AAAA,EACJ,IAAI;AAAA,EAGJ,IAAI;AAAA,EACJ,KAAK;AACP;;;ACzBO,SAAS,aAAa,CAAC,U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"87215A69EE27862E64756E2164756E21",
|
|
11
11
|
"names": []
|
|
12
12
|
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared city matching for carrier adapters that validate the shipper /
|
|
3
|
+
* consignee city against the carrier's own city list before booking.
|
|
4
|
+
*
|
|
5
|
+
* Extracted verbatim from the Aymakan adapter's proven matching strategy so
|
|
6
|
+
* SMSA (and future carriers) enforce identical semantics. The strategy never
|
|
7
|
+
* silently reroutes a distinct longer city to a shorter candidate (see the
|
|
8
|
+
* step-5 direction guard).
|
|
9
|
+
*/
|
|
10
|
+
import type { City } from "./types.js";
|
|
11
|
+
/** How long a fetched carrier city list stays fresh (1 hour). */
|
|
12
|
+
export declare const CITIES_CACHE_TTL: number;
|
|
13
|
+
/**
|
|
14
|
+
* After a failed city-list fetch, don't retry for this long (1 minute) —
|
|
15
|
+
* adapters fall back to pass-through resolution so a carrier /cities outage
|
|
16
|
+
* never hard-blocks shipment creation.
|
|
17
|
+
*/
|
|
18
|
+
export declare const CITIES_FAILURE_COOLDOWN: number;
|
|
19
|
+
/**
|
|
20
|
+
* Normalize Arabic text for comparison:
|
|
21
|
+
* - Strip diacritics (tashkeel)
|
|
22
|
+
* - Normalize alef variants (أ إ آ → ا)
|
|
23
|
+
* - Normalize taa marbuta (ة → ه)
|
|
24
|
+
* - Trim whitespace
|
|
25
|
+
*/
|
|
26
|
+
export declare function normalizeArabicCity(text: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Match a user-input city name against a carrier city list.
|
|
29
|
+
*
|
|
30
|
+
* Matching strategy (first match wins):
|
|
31
|
+
* 1. Exact match on English name (case-insensitive)
|
|
32
|
+
* 2. Exact match on Arabic name
|
|
33
|
+
* 3. Normalized Arabic match (handles tashkeel, alef variants, taa marbuta)
|
|
34
|
+
* 4. Match after toggling the "ال" prefix on the Arabic input
|
|
35
|
+
* 5. Candidate-contains-input match on English name (candidate name contains
|
|
36
|
+
* the input, e.g. "Riyadh" -> "Riyadh City"; requires input length >= 3).
|
|
37
|
+
* The reverse direction is intentionally excluded so a distinct longer
|
|
38
|
+
* city like "Riyadh Al Khabra" is never rerouted to "Riyadh".
|
|
39
|
+
*
|
|
40
|
+
* Returns null when nothing matches — the caller decides whether that means
|
|
41
|
+
* pass-through (lenient) or a validation error (strict).
|
|
42
|
+
*/
|
|
43
|
+
export declare function findCityMatch(inputCity: string, cities: City[]): City | null;
|
|
44
|
+
//# sourceMappingURL=city-resolver.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"city-resolver.d.ts","sourceRoot":"","sources":["../../src/core/city-resolver.ts"],"names":[],"mappings":"AACA;;;;;;;;GAQG;AAEH,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAEpC,iEAAiE;AACjE,eAAO,MAAM,gBAAgB,QAAiB,CAAC;AAE/C;;;;GAIG;AACH,eAAO,MAAM,uBAAuB,QAAY,CAAC;AAEjD;;;;;;GAMG;AACH,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM,CAMxD;AAED;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,aAAa,CAAC,SAAS,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,GAAG,IAAI,GAAG,IAAI,CA4C5E"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
// src/core/city-resolver.ts
|
|
2
|
+
var CITIES_CACHE_TTL = 60 * 60 * 1000;
|
|
3
|
+
var CITIES_FAILURE_COOLDOWN = 60 * 1000;
|
|
4
|
+
function normalizeArabicCity(text) {
|
|
5
|
+
return text.trim().replace(/[\u064B-\u065F\u0670]/g, "").replace(/[أإآ]/g, "ا").replace(/ة/g, "ه");
|
|
6
|
+
}
|
|
7
|
+
function findCityMatch(inputCity, cities) {
|
|
8
|
+
const trimmed = inputCity.trim();
|
|
9
|
+
if (!trimmed || cities.length === 0)
|
|
10
|
+
return null;
|
|
11
|
+
const lower = trimmed.toLowerCase();
|
|
12
|
+
const exactEn = cities.find((c) => c.nameEn.toLowerCase() === lower);
|
|
13
|
+
if (exactEn)
|
|
14
|
+
return exactEn;
|
|
15
|
+
const exactAr = cities.find((c) => c.nameAr === trimmed);
|
|
16
|
+
if (exactAr)
|
|
17
|
+
return exactAr;
|
|
18
|
+
const normalizedInput = normalizeArabicCity(trimmed);
|
|
19
|
+
const normalizedAr = cities.find((c) => c.nameAr && normalizeArabicCity(c.nameAr) === normalizedInput);
|
|
20
|
+
if (normalizedAr)
|
|
21
|
+
return normalizedAr;
|
|
22
|
+
const withoutAl = normalizedInput.startsWith("ال") ? normalizedInput.slice(2) : `ال${normalizedInput}`;
|
|
23
|
+
const alMatch = cities.find((c) => c.nameAr && normalizeArabicCity(c.nameAr) === withoutAl);
|
|
24
|
+
if (alMatch)
|
|
25
|
+
return alMatch;
|
|
26
|
+
if (lower.length >= 3) {
|
|
27
|
+
const containsEn = cities.find((c) => c.nameEn.toLowerCase().includes(lower));
|
|
28
|
+
if (containsEn)
|
|
29
|
+
return containsEn;
|
|
30
|
+
}
|
|
31
|
+
return null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export { CITIES_CACHE_TTL, CITIES_FAILURE_COOLDOWN, findCityMatch };
|
|
35
|
+
|
|
36
|
+
//# debugId=3A9ABF919E4CEDC364756E2164756E21
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../src/core/city-resolver.ts"],
|
|
4
|
+
"sourcesContent": [
|
|
5
|
+
"// file: src/core/city-resolver.ts\n/**\n * Shared city matching for carrier adapters that validate the shipper /\n * consignee city against the carrier's own city list before booking.\n *\n * Extracted verbatim from the Aymakan adapter's proven matching strategy so\n * SMSA (and future carriers) enforce identical semantics. The strategy never\n * silently reroutes a distinct longer city to a shorter candidate (see the\n * step-5 direction guard).\n */\n\nimport type { City } from \"./types\";\n\n/** How long a fetched carrier city list stays fresh (1 hour). */\nexport const CITIES_CACHE_TTL = 60 * 60 * 1000;\n\n/**\n * After a failed city-list fetch, don't retry for this long (1 minute) —\n * adapters fall back to pass-through resolution so a carrier /cities outage\n * never hard-blocks shipment creation.\n */\nexport const CITIES_FAILURE_COOLDOWN = 60 * 1000;\n\n/**\n * Normalize Arabic text for comparison:\n * - Strip diacritics (tashkeel)\n * - Normalize alef variants (أ إ آ → ا)\n * - Normalize taa marbuta (ة → ه)\n * - Trim whitespace\n */\nexport function normalizeArabicCity(text: string): string {\n return text\n .trim()\n .replace(/[\\u064B-\\u065F\\u0670]/g, \"\") // strip tashkeel\n .replace(/[أإآ]/g, \"ا\") // normalize alef\n .replace(/ة/g, \"ه\"); // normalize taa marbuta\n}\n\n/**\n * Match a user-input city name against a carrier city list.\n *\n * Matching strategy (first match wins):\n * 1. Exact match on English name (case-insensitive)\n * 2. Exact match on Arabic name\n * 3. Normalized Arabic match (handles tashkeel, alef variants, taa marbuta)\n * 4. Match after toggling the \"ال\" prefix on the Arabic input\n * 5. Candidate-contains-input match on English name (candidate name contains\n * the input, e.g. \"Riyadh\" -> \"Riyadh City\"; requires input length >= 3).\n * The reverse direction is intentionally excluded so a distinct longer\n * city like \"Riyadh Al Khabra\" is never rerouted to \"Riyadh\".\n *\n * Returns null when nothing matches — the caller decides whether that means\n * pass-through (lenient) or a validation error (strict).\n */\nexport function findCityMatch(inputCity: string, cities: City[]): City | null {\n const trimmed = inputCity.trim();\n if (!trimmed || cities.length === 0) return null;\n const lower = trimmed.toLowerCase();\n\n // 1. Exact English match (case-insensitive)\n const exactEn = cities.find((c) => c.nameEn.toLowerCase() === lower);\n if (exactEn) return exactEn;\n\n // 2. Exact Arabic match\n const exactAr = cities.find((c) => c.nameAr === trimmed);\n if (exactAr) return exactAr;\n\n // 3. Normalized Arabic match\n const normalizedInput = normalizeArabicCity(trimmed);\n const normalizedAr = cities.find(\n (c) => c.nameAr && normalizeArabicCity(c.nameAr) === normalizedInput,\n );\n if (normalizedAr) return normalizedAr;\n\n // 4. Arabic with the \"ال\" prefix toggled\n const withoutAl = normalizedInput.startsWith(\"ال\")\n ? normalizedInput.slice(2)\n : `ال${normalizedInput}`;\n const alMatch = cities.find(\n (c) => c.nameAr && normalizeArabicCity(c.nameAr) === withoutAl,\n );\n if (alMatch) return alMatch;\n\n // 5. Candidate-contains-input match on English name (e.g. input \"Riyadh\"\n // resolves to the canonical \"Riyadh City\"). We deliberately match ONLY\n // this direction. The reverse direction (input contains a candidate's\n // name) is excluded because a longer, distinct city such as\n // \"Riyadh Al Khabra\" would otherwise be silently rerouted to \"Riyadh\".\n // Guarded by a minimum input length so very short inputs (1-2 chars)\n // don't spuriously substring-match many candidates.\n if (lower.length >= 3) {\n const containsEn = cities.find((c) =>\n c.nameEn.toLowerCase().includes(lower),\n );\n if (containsEn) return containsEn;\n }\n\n return null;\n}\n"
|
|
6
|
+
],
|
|
7
|
+
"mappings": ";AAcO,IAAM,mBAAmB,KAAK,KAAK;AAOnC,IAAM,0BAA0B,KAAK;AASrC,SAAS,mBAAmB,CAAC,MAAsB;AAAA,EACxD,OAAO,KACJ,KAAK,EACL,QAAQ,0BAA0B,EAAE,EACpC,QAAQ,UAAU,GAAG,EACrB,QAAQ,MAAM,GAAG;AAAA;AAmBf,SAAS,aAAa,CAAC,WAAmB,QAA6B;AAAA,EAC5E,MAAM,UAAU,UAAU,KAAK;AAAA,EAC/B,IAAI,CAAC,WAAW,OAAO,WAAW;AAAA,IAAG,OAAO;AAAA,EAC5C,MAAM,QAAQ,QAAQ,YAAY;AAAA,EAGlC,MAAM,UAAU,OAAO,KAAK,CAAC,MAAM,EAAE,OAAO,YAAY,MAAM,KAAK;AAAA,EACnE,IAAI;AAAA,IAAS,OAAO;AAAA,EAGpB,MAAM,UAAU,OAAO,KAAK,CAAC,MAAM,EAAE,WAAW,OAAO;AAAA,EACvD,IAAI;AAAA,IAAS,OAAO;AAAA,EAGpB,MAAM,kBAAkB,oBAAoB,OAAO;AAAA,EACnD,MAAM,eAAe,OAAO,KAC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