universal-parcel-scraper 0.373.0-main.2014 → 0.374.0-main.2018

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 CHANGED
@@ -13,7 +13,7 @@ The engine behind [Peek](https://peektracker.com) ([GitHub](https://github.com/p
13
13
  [![License: Apache-2.0](https://img.shields.io/badge/core-Apache--2.0-blue.svg)](LICENSE)
14
14
 
15
15
  <!-- GENERATED:summary -->
16
- **3,500+ carriers** through **403 dedicated adapters** and **5 universal fallbacks**
16
+ **3,500+ carriers** through **405 dedicated adapters** and **5 universal fallbacks**
17
17
 
18
18
  <sub>727 catalog entries · 133 countries represented</sub>
19
19
  <!-- /GENERATED:summary -->
@@ -155,7 +155,7 @@ createTracker({ providers: ['ParcelsApp', 'Ship24', '17TRACK', 'Postal Ninja', '
155
155
  <!-- GENERATED:stages -->
156
156
  <img src="docs/assets/stages.svg" alt="DHL: Die Sendung wurde in das Zustellfahrzeug geladen.; Mondial Relay: En cours de livraison; Correios Brazil: Objeto saiu para entrega ao destinatário; Correos Express: EN REPARTO; Yamato Transport: 配達中; La Poste / Colissimo: DISTOU. All are filed under out_for_delivery." width="760">
157
157
 
158
- The carrier folders record 13,597 such statuses, each filed under one stage.
158
+ The carrier folders record 13,619 such statuses, each filed under one stage.
159
159
  <!-- /GENERATED:stages -->
160
160
 
161
161
  Wording nobody recorded yet goes through a classifier that reads seven European languages.
package/data/catalog.json CHANGED
@@ -27569,7 +27569,8 @@
27569
27569
  "timezone": "America/Lima",
27570
27570
  "tracking": {
27571
27571
  "mode": "automatic",
27572
- "adapter": "universal"
27572
+ "adapter": "urbano",
27573
+ "localClocks": true
27573
27574
  },
27574
27575
  "canaryUrl": "https://www.urbano.com.pe/tracking/",
27575
27576
  "trackingUrlTemplate": "https://www.urbano.com.pe/tracking/{trackingNumber}",
@@ -27581,6 +27582,15 @@
27581
27582
  ],
27582
27583
  "path": "^/tracking/([^/?#]+)/?$"
27583
27584
  },
27585
+ {
27586
+ "domains": [
27587
+ "urbano.com.pe"
27588
+ ],
27589
+ "pathPattern": "^/tracking/?$",
27590
+ "params": [
27591
+ "guides"
27592
+ ]
27593
+ },
27584
27594
  {
27585
27595
  "domains": [
27586
27596
  "app.urbano.com.pe",
@@ -28769,7 +28779,8 @@
28769
28779
  "timezone": "Asia/Riyadh",
28770
28780
  "tracking": {
28771
28781
  "mode": "automatic",
28772
- "adapter": "universal"
28782
+ "adapter": "zajil",
28783
+ "localClocks": true
28773
28784
  },
28774
28785
  "canaryUrl": "https://zajil-express.com/track",
28775
28786
  "trackingUrlTemplate": "https://zajil-express.com/track?tracking_id={trackingNumber}",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "catalog": 727,
3
- "activeAdapters": 403,
3
+ "activeAdapters": 405,
4
4
  "countries": 133,
5
5
  "referenceCarriers": 100,
6
6
  "comparison": {
@@ -20749,19 +20749,28 @@ var Pe = {
20749
20749
  timezone: "America/Lima",
20750
20750
  tracking: {
20751
20751
  mode: "automatic",
20752
- adapter: "universal"
20752
+ adapter: "urbano",
20753
+ localClocks: !0
20753
20754
  },
20754
20755
  canaryUrl: "https://www.urbano.com.pe/tracking/",
20755
20756
  trackingUrlTemplate: "https://www.urbano.com.pe/tracking/{trackingNumber}",
20756
20757
  trackingSearchUrl: "https://www.urbano.com.pe/tracking/",
20757
- linkRules: [{
20758
- domains: ["urbano.com.pe"],
20759
- path: "^/tracking/([^/?#]+)/?$"
20760
- }, {
20761
- domains: ["app.urbano.com.pe", "api.urbano.com.pe"],
20762
- pathPattern: "^/plugin/etracking/etracking/?$",
20763
- params: ["guia"]
20764
- }],
20758
+ linkRules: [
20759
+ {
20760
+ domains: ["urbano.com.pe"],
20761
+ path: "^/tracking/([^/?#]+)/?$"
20762
+ },
20763
+ {
20764
+ domains: ["urbano.com.pe"],
20765
+ pathPattern: "^/tracking/?$",
20766
+ params: ["guides"]
20767
+ },
20768
+ {
20769
+ domains: ["app.urbano.com.pe", "api.urbano.com.pe"],
20770
+ pathPattern: "^/plugin/etracking/etracking/?$",
20771
+ params: ["guia"]
20772
+ }
20773
+ ],
20765
20774
  detectionRules: [{
20766
20775
  pattern: "^G\\d{8}$",
20767
20776
  confidence: "low"
@@ -21641,7 +21650,8 @@ var Pe = {
21641
21650
  timezone: "Asia/Riyadh",
21642
21651
  tracking: {
21643
21652
  mode: "automatic",
21644
- adapter: "universal"
21653
+ adapter: "zajil",
21654
+ localClocks: !0
21645
21655
  },
21646
21656
  canaryUrl: "https://zajil-express.com/track",
21647
21657
  trackingUrlTemplate: "https://zajil-express.com/track?tracking_id={trackingNumber}",
@@ -0,0 +1,17 @@
1
+ import type { AdapterFactory, TrackingContext } from '../../core/adapter/index.js';
2
+ import type { CarrierResult } from '../../core/result/index.js';
3
+ import { type StepRecorder } from '../../core/telemetry/index.js';
4
+ /** The lookup the tracking page on urbano.com.pe makes for the numbers typed in. */
5
+ export declare const URBANO_API = "https://api.urbanoenvios.pe/api/v1/trackingGlobal";
6
+ /** The page's request: one number, looked up as a guía or tracking code rather than a seller's reference. */
7
+ export declare function urbanoLookupBody(number: string): string;
8
+ export declare class UrbanoTracker {
9
+ private readonly options;
10
+ constructor(options?: {
11
+ fetcher?: typeof fetch;
12
+ recorder?: StepRecorder;
13
+ userAgent?: string;
14
+ });
15
+ fetch(raw: string, context?: TrackingContext): Promise<CarrierResult>;
16
+ }
17
+ export declare const adapter: AdapterFactory;
@@ -0,0 +1,66 @@
1
+ import { ChallengeError, SchemaError, TransportError } from '../../core/errors/index.js';
2
+ import { runSteps } from '../../core/runner/index.js';
3
+ import { firstAttemptMs, networkRetryStep } from '../../core/runner/networkRetry.js';
4
+ import { NOOP_RECORDER } from '../../core/telemetry/index.js';
5
+ import { decodeText, fetchBounded, UpstreamHttpError, userAgentOf } from '../../core/transport/index.js';
6
+ import { normalizeUrbanoNumber, parseUrbano, PROVIDER, URBANO_MAX_BYTES } from './parser.js';
7
+ /** The lookup the tracking page on urbano.com.pe makes for the numbers typed in. */
8
+ export const URBANO_API = 'https://api.urbanoenvios.pe/api/v1/trackingGlobal';
9
+ const REDIRECTS = [301, 302, 303, 307, 308];
10
+ // Laravel's answer for a route it does not have, which it gives as HTTP 500.
11
+ const MISSING_ROUTE = /"message"\s*:\s*"The route [^"]* could not be found\./;
12
+ // Bot checks a CDN or firewall could put in place of the reply.
13
+ const CHALLENGE = /_cf_chl_opt|cf-turnstile|challenge-platform|<title>\s*(?:Just a moment|Attention Required)|AwsWafIntegration|awswaf\.com/i;
14
+ /** The page's request: one number, looked up as a guía or tracking code rather than a seller's reference. */
15
+ export function urbanoLookupBody(number) {
16
+ return JSON.stringify({ guia_barra: number, flag_seller: 0 });
17
+ }
18
+ function json(body) {
19
+ try {
20
+ return JSON.parse(body);
21
+ }
22
+ catch (cause) {
23
+ if (CHALLENGE.test(body.slice(0, 64_000)))
24
+ throw new ChallengeError(PROVIDER, 'Urbano answered with a browser check', { cause });
25
+ throw new SchemaError(PROVIDER, 'Urbano returned a reply that is not JSON', { cause });
26
+ }
27
+ }
28
+ export class UrbanoTracker {
29
+ options;
30
+ constructor(options = {}) {
31
+ this.options = options;
32
+ }
33
+ async fetch(raw, context = {}) {
34
+ const number = normalizeUrbanoNumber(raw);
35
+ const read = async (signal, timeoutMs) => {
36
+ const { response, bytes } = await fetchBounded(URBANO_API, { method: 'POST', signal, headers: {
37
+ Accept: 'application/json, text/plain, */*', 'Content-Type': 'application/json', 'User-Agent': userAgentOf(this.options.userAgent),
38
+ }, body: urbanoLookupBody(number) }, { provider: PROVIDER, timeoutMs: Math.max(1, Math.floor(timeoutMs)),
39
+ maxBytes: URBANO_MAX_BYTES, redirect: 'manual', fetcher: this.options.fetcher, allowHttpStatuses: [...REDIRECTS, 404, 410, 500] });
40
+ if (REDIRECTS.includes(response.status))
41
+ throw new TransportError(PROVIDER, 'Urbano redirected its tracking lookup');
42
+ // The page reads a missing parcel from a 200 reply; a 404 or a missing route is a moved lookup.
43
+ const body = decodeText(bytes);
44
+ if (response.status === 404 || response.status === 410 || (response.status === 500 && MISSING_ROUTE.test(body.slice(0, 4_000)))) {
45
+ throw new TransportError(PROVIDER, 'Urbano tracking lookup is unavailable');
46
+ }
47
+ if (response.status === 500)
48
+ throw new UpstreamHttpError(PROVIDER, 500);
49
+ return parseUrbano(json(body), number);
50
+ };
51
+ // A read that fails to reach Urbano, or hangs, gets one more: the first gets
52
+ // half of the budget, so the retry fits in the rest.
53
+ return runSteps({ carrier: 'urbano', budgetMs: context.budgetMs ?? 15_000, signal: context.signal,
54
+ recorder: this.options.recorder ?? NOOP_RECORDER }, [
55
+ { id: 'direct', run: ({ signal, remainingMs }) => read(signal, firstAttemptMs(remainingMs)) },
56
+ networkRetryStep(({ signal, remainingMs }) => read(signal, remainingMs)),
57
+ ]);
58
+ }
59
+ }
60
+ export const adapter = (environment) => {
61
+ const tracker = new UrbanoTracker({ fetcher: environment.fetcher, recorder: environment.recorder, userAgent: environment.userAgent });
62
+ return {
63
+ id: 'urbano', recordsSteps: true, steps: ['direct', 'retry'],
64
+ track: (input, context) => tracker.fetch(input.number, context),
65
+ };
66
+ };
@@ -19,18 +19,75 @@
19
19
  "timezone": "America/Lima",
20
20
  "tracking": {
21
21
  "mode": "automatic",
22
- "adapter": "universal",
23
- "steps": []
22
+ "adapter": "urbano",
23
+ "steps": [
24
+ "direct",
25
+ "retry"
26
+ ],
27
+ "localClocks": true
24
28
  },
25
- "capabilities": [],
29
+ "capabilities": [
30
+ "history",
31
+ "location",
32
+ "provider_code",
33
+ "eta",
34
+ "weight"
35
+ ],
26
36
  "portal": {
27
37
  "url": "https://www.urbano.com.pe/tracking/{trackingNumber}",
28
38
  "searchUrl": "https://www.urbano.com.pe/tracking/",
29
39
  "canaryUrl": "https://www.urbano.com.pe/tracking/",
30
- "shows": [],
31
- "scraped": [],
32
- "discarded": [],
33
- "unavailable": []
40
+ "shows": [
41
+ "status",
42
+ "progress_rail",
43
+ "history",
44
+ "location",
45
+ "eta",
46
+ "weight",
47
+ "service_name",
48
+ "origin",
49
+ "destination",
50
+ "failed_delivery_reason",
51
+ "event_details",
52
+ "courier_name",
53
+ "recipient_name",
54
+ "recipient_id",
55
+ "recipient_address",
56
+ "sender_name",
57
+ "parcel_count",
58
+ "delivery_photos",
59
+ "coordinates"
60
+ ],
61
+ "scraped": [
62
+ "status",
63
+ "history",
64
+ "location",
65
+ "provider_code",
66
+ "eta",
67
+ "weight",
68
+ "failed_delivery_reason"
69
+ ],
70
+ "discarded": [
71
+ "progress_rail",
72
+ "service_name",
73
+ "origin",
74
+ "destination",
75
+ "event_details",
76
+ "courier_name",
77
+ "recipient_name",
78
+ "recipient_id",
79
+ "recipient_address",
80
+ "sender_name",
81
+ "parcel_count",
82
+ "delivery_photos",
83
+ "coordinates"
84
+ ],
85
+ "unavailable": [
86
+ "offset_timestamps",
87
+ "delivered_at",
88
+ "pickup_point",
89
+ "delivery_partner"
90
+ ]
34
91
  },
35
92
  "links": [
36
93
  {
@@ -39,6 +96,15 @@
39
96
  ],
40
97
  "path": "^/tracking/([^/?#]+)/?$"
41
98
  },
99
+ {
100
+ "domains": [
101
+ "urbano.com.pe"
102
+ ],
103
+ "pathPattern": "^/tracking/?$",
104
+ "params": [
105
+ "guides"
106
+ ]
107
+ },
42
108
  {
43
109
  "domains": [
44
110
  "app.urbano.com.pe",
@@ -0,0 +1,17 @@
1
+ import type { CarrierResult } from '../../core/result/index.js';
2
+ export declare const PROVIDER = "Urbano";
3
+ export declare const URBANO_MAX_BYTES: number;
4
+ /** A number for Urbano's tracker, in upper case as the page sends it; anything else is not one Urbano issues. */
5
+ export declare function normalizeUrbanoNumber(raw: string): string;
6
+ /** A scan's wording without a signatory, an ID document, an e-mail address or phone numbers. */
7
+ export declare function urbanoWording(raw: string): string;
8
+ /**
9
+ * The reply of the tracking page's lookup, `POST /api/v1/trackingGlobal`: one
10
+ * entry per number asked. A shipment has `error_sql` 0 or more and names the
11
+ * number asked as its tracking code, guía or barcode. For a number it holds
12
+ * nothing for, the entry is only `error_sql: -1` and the number, and the page
13
+ * draws an empty card: the tracker does not say the shipment does not exist,
14
+ * and it answers an empty or malformed number the same way, so that answer is
15
+ * inconclusive.
16
+ */
17
+ export declare function parseUrbano(payload: unknown, raw: string): CarrierResult;
@@ -0,0 +1,227 @@
1
+ import { normalizeTrackingNumber } from '../../core/detection/index.js';
2
+ import { IndeterminateError, InvalidInputError, NoHistoryError, SchemaError } from '../../core/errors/index.js';
3
+ import { languageStageStatus } from '../../core/status/index.js';
4
+ import { calendarDay } from '../../core/time/index.js';
5
+ import { clean, cleanScalar } from '../../core/transport/index.js';
6
+ import { isRecord } from '../../core/types.js';
7
+ import { urbanoProcessStage, urbanoStage } from './status.js';
8
+ export const PROVIDER = 'Urbano';
9
+ // A long history is about ten kilobytes.
10
+ export const URBANO_MAX_BYTES = 512 * 1024;
11
+ // Guías, their barcodes and tracking codes: letters and digits, with at least one digit.
12
+ const NUMBER = /^(?=[A-Z]*\d)[A-Z0-9]{6,30}$/;
13
+ const CLOCK = /^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2})$/;
14
+ const DAY = /^(\d{4})-(\d{2})-(\d{2})$/;
15
+ // The shipment's own numbers the reply gives; the one asked must be one of them, whole.
16
+ const IDENTITY = ['rastreo', 'cod_seguimiento', 'guia_barra', 'guia_texto'];
17
+ const MAX_ENTRIES = 20;
18
+ const MAX_ROWS = 300;
19
+ const MAX_EVENTS = 100;
20
+ /** A number for Urbano's tracker, in upper case as the page sends it; anything else is not one Urbano issues. */
21
+ export function normalizeUrbanoNumber(raw) {
22
+ const number = raw.length <= 64 ? normalizeTrackingNumber(raw) : '';
23
+ if (!NUMBER.test(number))
24
+ throw new InvalidInputError(PROVIDER, 'Urbano numbers are six to thirty letters and digits');
25
+ return number;
26
+ }
27
+ /** An optional text field; anything but a string is a changed reply. */
28
+ function text(row, key, maxLength = 300) {
29
+ const value = row[key];
30
+ if (value === null || value === undefined)
31
+ return '';
32
+ if (typeof value !== 'string')
33
+ throw new SchemaError(PROVIDER, `Urbano returned an invalid ${key}`);
34
+ return clean(value, maxLength);
35
+ }
36
+ /** A whole number the reply gives as a number or as digits, or null without one. */
37
+ function integer(value) {
38
+ const parsed = typeof value === 'string' && /^\s*-?\d{1,6}\s*$/.test(value) ? Number(value) : value;
39
+ return typeof parsed === 'number' && Number.isSafeInteger(parsed) ? parsed : null;
40
+ }
41
+ // Who signed for or took the parcel and their ID document, after a status
42
+ // ("Firma: … (DNI: …)", as the shipment's summary words a delivery, or
43
+ // "Recibido por …").
44
+ const SIGNATORY = /\s*[(,;\-–]?\s*\b(?:(?:firma|dni|doc(?:umento)?|nombre|recibe)\s*:|(?:recibid[oa]|firmad[oa]|entregad[oa])\s+(?:por|a)\b)[\s\S]*$/i;
45
+ const EMAIL = /[^\s@]+@[^\s@]+/g;
46
+ // A run of six or more digits, with spaces, dots or hyphens between them, as
47
+ // ID card and phone numbers are written.
48
+ const ID_OR_PHONE = /(?<![A-Z\d])\+?\d(?:[\s.-]?\d){5,}(?![A-Z\d])/gi;
49
+ /** A scan's wording without a signatory, an ID document, an e-mail address or phone numbers. */
50
+ export function urbanoWording(raw) {
51
+ const own = raw.replace(SIGNATORY, '').replace(EMAIL, '').replace(ID_OR_PHONE, '');
52
+ return clean(clean(own).replace(/\s+([,;:.])/g, '$1'), 300).replace(/^[\s,;:.\-–]+|[\s,;:\-–]+$/g, '');
53
+ }
54
+ /**
55
+ * A scan's `auditoria`, "2026-05-12 15:47": the wall clock of the station that
56
+ * scanned it, to the minute, with no zone. A time of 00:00 is a scan the
57
+ * tracker kept only the day of.
58
+ */
59
+ function wallClock(value) {
60
+ const match = CLOCK.exec(value);
61
+ const day = match ? calendarDay(Number(match[1]), Number(match[2]), Number(match[3])) : null;
62
+ if (!match || !day || Number(match[4]) > 23 || Number(match[5]) > 59)
63
+ throw new SchemaError(PROVIDER, 'Urbano returned an invalid scan time');
64
+ return match[4] === '00' && match[5] === '00' ? day : `${day}T${match[4]}:${match[5]}:00`;
65
+ }
66
+ /** A calendar day the reply gives as `2026-05-12`, or null without a valid one. */
67
+ function calendarDate(value) {
68
+ const match = DAY.exec(value);
69
+ return match ? calendarDay(Number(match[1]), Number(match[2]), Number(match[3])) : null;
70
+ }
71
+ /**
72
+ * The names the shipment gives its origin and destination stations, by their
73
+ * codes ("LIM": "LIMA", "CUZ": "Urbano Cusco"), without the brand in front.
74
+ */
75
+ function stations(shipment) {
76
+ const names = new Map();
77
+ for (const [codes, name] of [[['origen_iata', 'origen'], 'origen_descri'], [['destino_iata', 'destino'], 'destino_descri']]) {
78
+ const label = text(shipment, name, 80).replace(/^urbano\s+/i, '');
79
+ if (!label)
80
+ continue;
81
+ for (const code of codes) {
82
+ const key = text(shipment, code, 8).toUpperCase();
83
+ if (key && !names.has(key))
84
+ names.set(key, label);
85
+ }
86
+ }
87
+ return names;
88
+ }
89
+ /**
90
+ * A movement as the page draws it: `detalle`, then the `sub_estado` under it,
91
+ * such as a failed visit's reason. The `anotaciones`, which name the courier,
92
+ * the vehicle and manifests, the `comentario`, the photos and the GPS point of
93
+ * the visit are not kept. A movement with neither wording is left out.
94
+ */
95
+ function scanOf(row, index, names) {
96
+ if (!isRecord(row))
97
+ throw new SchemaError(PROVIDER, 'Urbano returned an invalid scan');
98
+ const code = cleanScalar(row.chk, 8).toUpperCase();
99
+ const detail = urbanoWording(text(row, 'detalle'));
100
+ const sub = urbanoWording(text(row, 'sub_estado'));
101
+ const local = wallClock(text(row, 'auditoria', 32));
102
+ const description = detail && sub && !detail.toLowerCase().includes(sub.toLowerCase()) ? `${detail}: ${sub}` : detail || sub;
103
+ if (!description)
104
+ return null;
105
+ const location = names.get(text(row, 'agencia', 8).toUpperCase());
106
+ const staged = urbanoStage(code, detail || sub);
107
+ return { index, event: {
108
+ local_time: local,
109
+ ...(location ? { location } : {}),
110
+ description,
111
+ ...(code ? { provider_code: code } : {}),
112
+ ...(staged ? { stage: staged.stage, stage_source: staged.source } : {}),
113
+ } };
114
+ }
115
+ /** The shipment's scans, newest first; the same scan once. */
116
+ function history(shipment) {
117
+ const rows = shipment.movimientos ?? [];
118
+ if (!Array.isArray(rows))
119
+ throw new SchemaError(PROVIDER, 'Urbano returned a shipment with invalid scans');
120
+ if (rows.length > MAX_ROWS)
121
+ throw new SchemaError(PROVIDER, 'Urbano returned an oversized history');
122
+ const names = stations(shipment);
123
+ const seen = new Set();
124
+ const scans = [];
125
+ rows.forEach((row, index) => {
126
+ const scan = scanOf(row, index, names);
127
+ if (!scan)
128
+ return;
129
+ const { local_time: local, provider_code: code, description, location } = scan.event;
130
+ const key = JSON.stringify([local, code, description, location]);
131
+ if (seen.has(key))
132
+ return;
133
+ seen.add(key);
134
+ scans.push(scan);
135
+ });
136
+ // The reply lists them newest first; scans at one clock keep that order, and
137
+ // a day without a time comes before that day's clocks.
138
+ return scans.sort((a, b) => b.event.local_time.localeCompare(a.event.local_time) || a.index - b.index)
139
+ .map(({ event }) => event);
140
+ }
141
+ /** The parcel's weight in kilograms, when the reply gives a plausible one. */
142
+ function weight(shipment) {
143
+ const value = text(shipment, 'peso', 16);
144
+ const kg = /^\d{1,4}(?:\.\d+)?$/.test(value) ? Number(value) : NaN;
145
+ return kg > 0 && kg < 5_000 ? kg : null;
146
+ }
147
+ /** The shipment's numbers, whole and in the form the adapter asks with. */
148
+ function identifiers(entry) {
149
+ return IDENTITY.map((key) => text(entry, key, 64)).filter(Boolean).map((value) => normalizeTrackingNumber(value));
150
+ }
151
+ function project(shipment) {
152
+ const events = history(shipment);
153
+ if (!events.length)
154
+ throw new NoHistoryError(PROVIDER);
155
+ const newest = events[0];
156
+ const scanned = events.find((event) => event.stage);
157
+ const process = integer(shipment.id_proceso);
158
+ const labelled = process === null ? undefined : urbanoProcessStage(process);
159
+ // The page's label for a return or a wait for collection decides; a label
160
+ // for collection never steps a delivered parcel back.
161
+ const summary = labelled === 'ready_for_pickup' && scanned?.stage === 'delivered' ? undefined : labelled;
162
+ const stage = (summary ?? scanned?.stage);
163
+ const source = summary && summary !== scanned?.stage ? 'carrier_map' : scanned?.stage_source;
164
+ const expected = stage === 'delivered' || stage === 'returned' ? null
165
+ : calendarDate(text(shipment, 'fec_estimada', 16)) ?? calendarDate(text(shipment, 'fecha_estimada', 16));
166
+ const kg = weight(shipment);
167
+ return {
168
+ status: stage ? languageStageStatus(stage) : 'unknown',
169
+ ...(stage ? { current_stage: stage, current_stage_source: source ?? 'carrier_map' } : {}),
170
+ last_status_text: newest.description,
171
+ last_update: null,
172
+ last_update_local: newest.local_time,
173
+ expected_delivery: expected,
174
+ ...(kg !== null ? { weight_kg: kg } : {}),
175
+ events: events.slice(0, MAX_EVENTS),
176
+ ...(events.length > MAX_EVENTS ? { history_truncated: true } : {}),
177
+ };
178
+ }
179
+ /**
180
+ * The reply of the tracking page's lookup, `POST /api/v1/trackingGlobal`: one
181
+ * entry per number asked. A shipment has `error_sql` 0 or more and names the
182
+ * number asked as its tracking code, guía or barcode. For a number it holds
183
+ * nothing for, the entry is only `error_sql: -1` and the number, and the page
184
+ * draws an empty card: the tracker does not say the shipment does not exist,
185
+ * and it answers an empty or malformed number the same way, so that answer is
186
+ * inconclusive.
187
+ */
188
+ export function parseUrbano(payload, raw) {
189
+ const number = normalizeUrbanoNumber(raw);
190
+ if (!isRecord(payload) || typeof payload.success !== 'boolean' || !Array.isArray(payload.data)) {
191
+ throw new SchemaError(PROVIDER, 'Urbano returned an invalid envelope');
192
+ }
193
+ if (!payload.success || (payload.code_error !== undefined && integer(payload.code_error) !== 0)) {
194
+ throw new IndeterminateError(PROVIDER, 'Urbano did not complete the lookup');
195
+ }
196
+ if (payload.data.length > MAX_ENTRIES)
197
+ throw new SchemaError(PROVIDER, 'Urbano returned too many shipments');
198
+ const shipments = [];
199
+ let nothing = null;
200
+ for (const entry of payload.data) {
201
+ if (!isRecord(entry))
202
+ throw new SchemaError(PROVIDER, 'Urbano returned an invalid shipment');
203
+ const code = integer(entry.error_sql);
204
+ if (code === null)
205
+ throw new SchemaError(PROVIDER, 'Urbano returned a shipment without its lookup code');
206
+ if (code >= 0) {
207
+ const own = identifiers(entry);
208
+ if (!own.length)
209
+ throw new SchemaError(PROVIDER, 'Urbano returned a shipment without its number');
210
+ if (own.includes(number))
211
+ shipments.push(entry);
212
+ }
213
+ else if (normalizeTrackingNumber(text(entry, 'guia_barra', 64)) === number) {
214
+ nothing = code;
215
+ }
216
+ }
217
+ if (shipments.length > 1)
218
+ throw new IndeterminateError(PROVIDER, 'Urbano returned several shipments under the number');
219
+ if (shipments.length === 1)
220
+ return project(shipments[0]);
221
+ if (nothing === -1) {
222
+ throw new IndeterminateError(PROVIDER, 'Urbano\'s tracker shows nothing for the number', { reason: 'portal_not_found' });
223
+ }
224
+ if (nothing !== null)
225
+ throw new IndeterminateError(PROVIDER, 'Urbano did not complete the lookup');
226
+ throw new IndeterminateError(PROVIDER, 'Urbano answered for another shipment');
227
+ }
@@ -0,0 +1,9 @@
1
+ import { type ClassifiedWording, type Stage } from '../../core/status/index.js';
2
+ import type { CarrierStatusMap } from '../../core/status/statusMap.js';
3
+ /** The stage Urbano's codes give a scan code. */
4
+ export declare function urbanoMappedStage(code: string): Stage | undefined;
5
+ /** The stage the page's label for a shipment's process gives, when it names one. */
6
+ export declare function urbanoProcessStage(process: number): Stage | undefined;
7
+ /** A scan's stage: its code, else the shared wording rules, else nothing. */
8
+ export declare function urbanoStage(code: string, wording: string): ClassifiedWording | null;
9
+ export declare const statusMap: CarrierStatusMap;
@@ -0,0 +1,45 @@
1
+ import { classifyWording } from '../../core/status/index.js';
2
+ /**
3
+ * Urbano's scan codes (`chk`), with the wording its tracker writes for each.
4
+ * Only codes seen in replies are mapped; another code falls to the wording rules.
5
+ */
6
+ const CODES = new Map([
7
+ ['PU', 'registered'], // "PEDIDO CREADO": the order booked, the parcel not yet with Urbano.
8
+ ['AO', 'accepted'], // "RECIBIMOS EN ORIGEN": received at the origin hub.
9
+ ['CK', 'in_transit'], // "Entro a Pre-Embarque": loaded for the line haul.
10
+ ['DD', 'in_transit'], // "DESPACHAMOS A SU CIUDAD": dispatched to the destination city.
11
+ ['AR', 'in_transit'], // "LLEGO A LA CIUDAD DESTINO": arrived at the destination station.
12
+ ['ER', 'out_for_delivery'], // "SALIO A ENTREGARSE"
13
+ ['CV', 'failed_attempt'], // "INTENTAMOS ENTREGARTE": a visit that did not deliver, its reason after it.
14
+ ['EN', 'delivered'], // "ENTREGAMOS TU PEDIDO"
15
+ ]);
16
+ /**
17
+ * The shipment's `id_proceso` where the tracking page gives it its own label
18
+ * over the progress rail: "Devuelto" and "Listo para recoger". The other
19
+ * steps of the rail follow the scans.
20
+ */
21
+ const PROCESSES = new Map([
22
+ [21, 'returned'],
23
+ [23, 'ready_for_pickup'],
24
+ [24, 'ready_for_pickup'],
25
+ ]);
26
+ /** The stage Urbano's codes give a scan code. */
27
+ export function urbanoMappedStage(code) {
28
+ return CODES.get(code.toUpperCase());
29
+ }
30
+ /** The stage the page's label for a shipment's process gives, when it names one. */
31
+ export function urbanoProcessStage(process) {
32
+ return PROCESSES.get(process);
33
+ }
34
+ /** A scan's stage: its code, else the shared wording rules, else nothing. */
35
+ export function urbanoStage(code, wording) {
36
+ const mapped = urbanoMappedStage(code);
37
+ if (mapped)
38
+ return { stage: mapped, source: 'carrier_map' };
39
+ const worded = classifyWording(wording, 'in_transit');
40
+ return worded.source === 'none' ? null : worded;
41
+ }
42
+ export const statusMap = {
43
+ stage: (code) => (code ? urbanoMappedStage(code) : undefined),
44
+ gaps: [],
45
+ };
@@ -1,6 +1,15 @@
1
1
  {
2
2
  "carrier": "urbano",
3
3
  "entries": [
4
+ {"code": "PU", "wording": "PEDIDO CREADO", "stage": "registered", "language": "es", "confirmedBy": "live", "note": "First movement of a merchant's parcel, booked before Urbano has it; its note reads Pick UP (Auto)."},
5
+ {"code": "AO", "wording": "RECIBIMOS EN ORIGEN", "stage": "accepted", "language": "es", "confirmedBy": "live", "note": "Received at the origin hub; the old e-tracking page words it ADMITIDO EN HUB."},
6
+ {"code": "CK", "wording": "Entro a Pre-Embarque", "stage": "in_transit", "language": "es", "confirmedBy": "live", "note": "Loaded for the line haul; the old e-tracking page words it Checking Pre-Embarque."},
7
+ {"code": "DD", "wording": "DESPACHAMOS A SU CIUDAD", "stage": "in_transit", "language": "es", "confirmedBy": "live", "note": "Dispatched to the destination city."},
8
+ {"code": "AR", "wording": "LLEGO A LA CIUDAD DESTINO", "stage": "in_transit", "language": "es", "confirmedBy": "live", "note": "Arrived at the destination station."},
9
+ {"code": "ER", "wording": "SALIO A ENTREGARSE", "stage": "out_for_delivery", "language": "es", "confirmedBy": "live", "note": "Out with a courier, whose masked name and vehicle the note gives; one run was recorded at 00:00, its day only."},
10
+ {"code": "CV", "wording": "INTENTAMOS ENTREGARTE", "stage": "failed_attempt", "language": "es", "confirmedBy": "live", "note": "A visit that did not deliver; its sub-status gives the reason, such as Direccion Incorrecta."},
11
+ {"code": "EN", "wording": "ENTREGAMOS TU PEDIDO", "stage": "delivered", "language": "es", "confirmedBy": "live", "note": "Delivered; seen with the sub-status Entrega A Titular."},
12
+ {"wording": "Listo para recoger", "stage": "ready_for_pickup", "language": "es", "confirmedBy": "bundle", "note": "Label the tracking page's script shows over the progress rail for process 23 and 24: waiting at an Urbano point for collection."},
4
13
  {"wording": "Admitido en Hub", "stage": "accepted", "language": "es", "confirmedBy": "portal", "note": "Milestone label in the script of Urbano's own tracker on urbano.com.pe. Received at Urbano's hub."},
5
14
  {"wording": "Despachado", "stage": "in_transit", "language": "es", "confirmedBy": "portal", "note": "Milestone label in the script of Urbano's own tracker on urbano.com.pe. Dispatched from the hub."},
6
15
  {"wording": "Arribado", "stage": "in_transit", "language": "es", "confirmedBy": "portal", "note": "Milestone label in the script of Urbano's own tracker on urbano.com.pe. Arrived at the destination station."},
@@ -0,0 +1,15 @@
1
+ import type { AdapterFactory, TrackingContext } from '../../core/adapter/index.js';
2
+ import type { CarrierResult } from '../../core/result/index.js';
3
+ import { type StepRecorder } from '../../core/telemetry/index.js';
4
+ /** The lookup the tracking page on zajil-express.com makes for a shipment, followed by the number. */
5
+ export declare const ZAJIL_API = "https://mobileapi.zajil-express.org/track?shipment=";
6
+ export declare class ZajilTracker {
7
+ private readonly options;
8
+ constructor(options?: {
9
+ fetcher?: typeof fetch;
10
+ recorder?: StepRecorder;
11
+ userAgent?: string;
12
+ });
13
+ fetch(raw: string, context?: TrackingContext): Promise<CarrierResult>;
14
+ }
15
+ export declare const adapter: AdapterFactory;
@@ -0,0 +1,70 @@
1
+ import { ChallengeError, IndeterminateError, SchemaError, TransportError } from '../../core/errors/index.js';
2
+ import { runSteps } from '../../core/runner/index.js';
3
+ import { NOOP_RECORDER } from '../../core/telemetry/index.js';
4
+ import { decodeText, fetchBounded, userAgentOf } from '../../core/transport/index.js';
5
+ import { CARRIER, isZajilNotFound, normalizeZajilNumber, parseZajil, PROVIDER, ZAJIL_MAX_BYTES } from './parser.js';
6
+ /** The lookup the tracking page on zajil-express.com makes for a shipment, followed by the number. */
7
+ export const ZAJIL_API = 'https://mobileapi.zajil-express.org/track?shipment=';
8
+ const REDIRECTS = [301, 302, 303, 307, 308];
9
+ // Bot checks a CDN or firewall could put in place of the reply.
10
+ const CHALLENGE = /_cf_chl_opt|cf-turnstile|challenge-platform|<title>\s*(?:Just a moment|Attention Required|Access Denied)|g-recaptcha|h-captcha|AwsWafIntegration|awswaf\.com/i;
11
+ function json(body) {
12
+ try {
13
+ return JSON.parse(body);
14
+ }
15
+ catch {
16
+ return undefined;
17
+ }
18
+ }
19
+ export class ZajilTracker {
20
+ options;
21
+ constructor(options = {}) {
22
+ this.options = options;
23
+ }
24
+ async fetch(raw, context = {}) {
25
+ const number = normalizeZajilNumber(raw);
26
+ const read = async (signal, timeoutMs) => {
27
+ const { response, bytes } = await fetchBounded(`${ZAJIL_API}${encodeURIComponent(number)}`, { method: 'GET', signal, headers: {
28
+ Accept: 'application/json', 'User-Agent': userAgentOf(this.options.userAgent),
29
+ } }, { provider: PROVIDER, timeoutMs: Math.max(1, Math.floor(timeoutMs)), maxBytes: ZAJIL_MAX_BYTES, redirect: 'manual',
30
+ fetcher: this.options.fetcher, allowHttpStatuses: [...REDIRECTS, 404, 410, 500] });
31
+ if (REDIRECTS.includes(response.status))
32
+ throw new TransportError(PROVIDER, 'Zajil redirected its tracking lookup');
33
+ const body = decodeText(bytes);
34
+ const payload = json(body);
35
+ // The page shows "No Shipment Found" for any failed lookup. The lookup's
36
+ // own error for an unknown number is HTTP 404 with `shipment_not_found`;
37
+ // any other 404 is a moved route.
38
+ if (response.status === 404 || response.status === 410) {
39
+ if (response.status === 404 && isZajilNotFound(payload))
40
+ return parseZajil(payload, number);
41
+ throw new TransportError(PROVIDER, 'Zajil tracking lookup is unavailable', { status: response.status });
42
+ }
43
+ // Its server error, which it also answers for every eleven-digit number it
44
+ // has no shipment for, proves no absence.
45
+ if (response.status === 500) {
46
+ throw new IndeterminateError(PROVIDER, 'Zajil has no shipment for this number or failed to look it up', { reason: 'portal_not_found', status: 500 });
47
+ }
48
+ if (payload === undefined) {
49
+ if (CHALLENGE.test(body.slice(0, 64_000)))
50
+ throw new ChallengeError(PROVIDER, 'Zajil answered with a browser check');
51
+ throw new SchemaError(PROVIDER, 'Zajil returned a reply that is not JSON');
52
+ }
53
+ return parseZajil(payload, number);
54
+ };
55
+ // One read with the whole budget: a number the lookup cannot answer holds
56
+ // the request open until it fails, and a second request would only add
57
+ // another.
58
+ return runSteps({ carrier: CARRIER, budgetMs: context.budgetMs ?? 15_000, signal: context.signal,
59
+ recorder: this.options.recorder ?? NOOP_RECORDER }, [
60
+ { id: 'direct', run: ({ signal, remainingMs }) => read(signal, remainingMs) },
61
+ ]);
62
+ }
63
+ }
64
+ export const adapter = (environment) => {
65
+ const tracker = new ZajilTracker({ fetcher: environment.fetcher, recorder: environment.recorder, userAgent: environment.userAgent });
66
+ return {
67
+ id: CARRIER, recordsSteps: true, steps: ['direct'],
68
+ track: (input, context) => tracker.fetch(input.number, context),
69
+ };
70
+ };
@@ -19,18 +19,53 @@
19
19
  "timezone": "Asia/Riyadh",
20
20
  "tracking": {
21
21
  "mode": "automatic",
22
- "adapter": "universal",
23
- "steps": []
22
+ "adapter": "zajil",
23
+ "steps": [
24
+ "direct"
25
+ ],
26
+ "localClocks": true
24
27
  },
25
- "capabilities": [],
28
+ "capabilities": [
29
+ "location",
30
+ "provider_code",
31
+ "destination_country"
32
+ ],
26
33
  "portal": {
27
34
  "url": "https://zajil-express.com/track?tracking_id={trackingNumber}",
28
35
  "searchUrl": "https://zajil-express.com/track",
29
36
  "canaryUrl": "https://zajil-express.com/track",
30
- "shows": [],
31
- "scraped": [],
32
- "discarded": [],
33
- "unavailable": []
37
+ "shows": [
38
+ "status",
39
+ "progress_rail",
40
+ "scan_times",
41
+ "awb_date",
42
+ "origin",
43
+ "destination"
44
+ ],
45
+ "scraped": [
46
+ "status",
47
+ "scan_times",
48
+ "location",
49
+ "provider_code",
50
+ "destination_country"
51
+ ],
52
+ "discarded": [
53
+ "progress_rail",
54
+ "awb_date",
55
+ "origin",
56
+ "destination"
57
+ ],
58
+ "unavailable": [
59
+ "history",
60
+ "offset_timestamps",
61
+ "eta",
62
+ "weight",
63
+ "service_name",
64
+ "delivered_at",
65
+ "sender_name",
66
+ "recipient_name",
67
+ "proof_of_delivery"
68
+ ]
34
69
  },
35
70
  "links": [
36
71
  {
@@ -0,0 +1,18 @@
1
+ import type { CarrierResult } from '../../core/result/index.js';
2
+ export declare const PROVIDER = "Zajil Express";
3
+ export declare const CARRIER = "zajil";
4
+ export declare const ZAJIL_MAX_BYTES: number;
5
+ /** A number for Zajil's tracker, in upper case; anything else is not one Zajil issues. */
6
+ export declare function normalizeZajilNumber(raw: string): string;
7
+ /** The tracker's answer for a number it does not know: a list holding its one `shipment_not_found` error. */
8
+ export declare function isZajilNotFound(payload: unknown): boolean;
9
+ /**
10
+ * The reply of `mobileapi.zajil-express.org/track?shipment=`, the lookup
11
+ * Zajil's tracking page makes. A shipment carries its current status in
12
+ * `current_update` and `history`, which has held only that status so far; the
13
+ * page shows the status, the route and the status's time. A number the lookup
14
+ * does not know is the `shipment_not_found` list. The shipment must name the
15
+ * number asked. Amounts to collect, branch codes and the feedback field are
16
+ * never read.
17
+ */
18
+ export declare function parseZajil(payload: unknown, raw: string): CarrierResult;
@@ -0,0 +1,149 @@
1
+ import { DateTime } from 'luxon';
2
+ import { normalizeTrackingNumber } from '../../core/detection/index.js';
3
+ import { IndeterminateError, InvalidInputError, NoHistoryError, NotFoundError, SchemaError } from '../../core/errors/index.js';
4
+ import { languageStageStatus } from '../../core/status/index.js';
5
+ import { countryCode } from '../../core/time/index.js';
6
+ import { clean, cleanScalar } from '../../core/transport/index.js';
7
+ import { isRecord } from '../../core/types.js';
8
+ import { zajilMappedStage, zajilStage } from './status.js';
9
+ export const PROVIDER = 'Zajil Express';
10
+ export const CARRIER = 'zajil';
11
+ // A reply is under two kilobytes.
12
+ export const ZAJIL_MAX_BYTES = 256 * 1024;
13
+ // Eleven-digit shipment numbers, twelve-digit house waybills and the older Z references.
14
+ const NUMBER = /^(?:\d{11,12}|Z\d{7})$/;
15
+ // A wall clock to the second, with milliseconds after it.
16
+ const CLOCK = /^(\d{4}-\d{2}-\d{2}T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d)(?:\.\d{1,6})?$/;
17
+ const CODE = /^[A-Za-z_]{1,40}$/;
18
+ // What the reply puts in a field it has no value for.
19
+ const PLACEHOLDER = /^(?:not found|string|-+|false|none|null)$/i;
20
+ const MAX_ROWS = 500;
21
+ const MAX_EVENTS = 100;
22
+ /** A number for Zajil's tracker, in upper case; anything else is not one Zajil issues. */
23
+ export function normalizeZajilNumber(raw) {
24
+ const number = raw.length <= 64 ? normalizeTrackingNumber(raw).toUpperCase() : '';
25
+ if (!NUMBER.test(number))
26
+ throw new InvalidInputError(PROVIDER, 'Zajil numbers are eleven or twelve digits, or Z and seven digits');
27
+ return number;
28
+ }
29
+ /** An optional text field, without the reply's placeholders; `false` is one of them, anything else is a changed reply. */
30
+ function text(row, key, maxLength = 120) {
31
+ const value = row[key];
32
+ if (value === null || value === undefined || value === false)
33
+ return '';
34
+ if (typeof value !== 'string')
35
+ throw new SchemaError(PROVIDER, `Zajil returned an invalid ${key}`);
36
+ const cleaned = clean(value, maxLength);
37
+ return PLACEHOLDER.test(cleaned) ? '' : cleaned;
38
+ }
39
+ /**
40
+ * A status's clock. `date` is a wall clock without a zone, which the page
41
+ * shows as it comes; no offset was verified, so it stays local.
42
+ */
43
+ function wallClock(row) {
44
+ const local = CLOCK.exec(text(row, 'date', 40))?.[1] ?? '';
45
+ // Parsing in UTC checks the calendar digits only; the wall clock keeps no offset.
46
+ const parsed = DateTime.fromISO(local, { zone: 'UTC' });
47
+ // Luxon rolls 24:00 over to the next day; only a clock that reads back unchanged is kept.
48
+ if (!local || !parsed.isValid || parsed.toFormat("yyyy-MM-dd'T'HH:mm:ss") !== local) {
49
+ throw new SchemaError(PROVIDER, 'Zajil returned an invalid status time');
50
+ }
51
+ return local;
52
+ }
53
+ /** The status's wording: the Arabic line the page shows, else its `website_update` value in words. */
54
+ function wording(row, code) {
55
+ return text(row, 'arabic_update') || clean(code.replace(/_/g, ' '), 40);
56
+ }
57
+ function projectRow(row) {
58
+ const code = cleanScalar(row.website_update, 40);
59
+ if (!CODE.test(code))
60
+ throw new SchemaError(PROVIDER, 'Zajil returned a status without its update');
61
+ const description = wording(row, code);
62
+ const local = wallClock(row);
63
+ // The branch or hub, in English; the city when the reply names no place.
64
+ const location = text(row, 'location_name') || text(row, 'location_city');
65
+ const staged = zajilStage(code, description);
66
+ const event = {
67
+ local_time: local,
68
+ ...(location ? { location } : {}),
69
+ description,
70
+ provider_code: code,
71
+ ...(staged ? { stage: staged.stage, stage_source: staged.source } : {}),
72
+ };
73
+ return { key: JSON.stringify([local, code, description, location]), event };
74
+ }
75
+ /** The tracker's answer for a number it does not know: a list holding its one `shipment_not_found` error. */
76
+ export function isZajilNotFound(payload) {
77
+ return Array.isArray(payload) && payload.length === 1 && isRecord(payload[0]) && payload[0].code === 'shipment_not_found';
78
+ }
79
+ /**
80
+ * The reply of `mobileapi.zajil-express.org/track?shipment=`, the lookup
81
+ * Zajil's tracking page makes. A shipment carries its current status in
82
+ * `current_update` and `history`, which has held only that status so far; the
83
+ * page shows the status, the route and the status's time. A number the lookup
84
+ * does not know is the `shipment_not_found` list. The shipment must name the
85
+ * number asked. Amounts to collect, branch codes and the feedback field are
86
+ * never read.
87
+ */
88
+ export function parseZajil(payload, raw) {
89
+ const number = normalizeZajilNumber(raw);
90
+ if (isZajilNotFound(payload))
91
+ throw new NotFoundError(PROVIDER);
92
+ if (!isRecord(payload))
93
+ throw new SchemaError(PROVIDER, 'Zajil returned an invalid envelope');
94
+ const echoed = cleanScalar(payload.shipment, 64).toUpperCase();
95
+ if (!echoed)
96
+ throw new SchemaError(PROVIDER, 'Zajil returned a shipment without its number');
97
+ if (echoed !== number)
98
+ throw new IndeterminateError(PROVIDER, 'Zajil answered for another shipment');
99
+ const listed = payload.history ?? [];
100
+ if (!Array.isArray(listed))
101
+ throw new SchemaError(PROVIDER, 'Zajil returned a shipment with an invalid history');
102
+ const history = listed;
103
+ if (history.length > MAX_ROWS)
104
+ throw new SchemaError(PROVIDER, 'Zajil returned an oversized history');
105
+ const current = payload.current_update ?? null;
106
+ if (current !== null && !isRecord(current))
107
+ throw new SchemaError(PROVIDER, 'Zajil returned an invalid current status');
108
+ const seen = new Set();
109
+ const scans = [];
110
+ for (const row of [...history, ...(current ? [current] : [])]) {
111
+ if (!isRecord(row))
112
+ throw new SchemaError(PROVIDER, 'Zajil returned an invalid status');
113
+ const scan = projectRow(row);
114
+ if (seen.has(scan.key))
115
+ continue;
116
+ seen.add(scan.key);
117
+ scans.push(scan.event);
118
+ }
119
+ // Newest first by wall clock; statuses on one clock keep the reply's order.
120
+ const events = scans.map((event, index) => ({ event, index }))
121
+ .sort((left, right) => right.event.local_time.localeCompare(left.event.local_time) || left.index - right.index)
122
+ .map(({ event }) => event);
123
+ // The shipment's own update is the current status, which the page's rail shows.
124
+ const update = cleanScalar(payload.website_update, 40);
125
+ const summary = zajilMappedStage(update);
126
+ const scanned = events.find((event) => event.stage);
127
+ const stage = (summary ?? scanned?.stage);
128
+ const source = summary ? 'carrier_map' : scanned?.stage_source;
129
+ const newest = events[0];
130
+ const statusText = newest?.description ?? text(payload, 'status');
131
+ if (!newest && !stage)
132
+ throw new NoHistoryError(PROVIDER);
133
+ const destination = text(payload, 'destenation_country', 80);
134
+ const country = destination ? countryCode(destination) : null;
135
+ return {
136
+ status: stage ? languageStageStatus(stage) : 'unknown',
137
+ ...(stage ? { current_stage: stage, current_stage_source: source ?? 'carrier_map' } : {}),
138
+ last_status_text: statusText || null,
139
+ last_update: null,
140
+ last_update_local: typeof newest?.local_time === 'string' ? newest.local_time : null,
141
+ expected_delivery: null,
142
+ ...(country ? { destination_country: country } : destination ? { destination_country_name: destination } : {}),
143
+ // A single status is the current one alone, not a history.
144
+ ...(events.length <= 1 ? { summary_only: true } : {}),
145
+ ...(newest ? {} : CODE.test(update) ? { provider_code: update } : {}),
146
+ events: events.slice(0, MAX_EVENTS),
147
+ ...(events.length > MAX_EVENTS ? { history_truncated: true } : {}),
148
+ };
149
+ }
@@ -0,0 +1,7 @@
1
+ import { type ClassifiedWording, type Stage } from '../../core/status/index.js';
2
+ import type { CarrierStatusMap } from '../../core/status/statusMap.js';
3
+ /** The stage Zajil's `website_update` value gives a status. */
4
+ export declare function zajilMappedStage(code: string): Stage | undefined;
5
+ /** A status's stage: its `website_update` value, else the shared wording rules, else nothing. */
6
+ export declare function zajilStage(code: string, wording: string): ClassifiedWording | null;
7
+ export declare const statusMap: CarrierStatusMap;
@@ -0,0 +1,39 @@
1
+ import { classifyWording } from '../../core/status/index.js';
2
+ /**
3
+ * The `website_update` values of Zajil's tracking lookup, which its page puts
4
+ * on a three-step rail (Processing, In Transit, Delivered), with the stage each
5
+ * means. The page names every value here; `delivered` and `In_Transit` were
6
+ * seen in replies too.
7
+ */
8
+ const UPDATES = new Map([
9
+ ['processing', 'registered'], // The rail's first step: booked, not moving yet.
10
+ ['pickup_scheduled', 'registered'], // A collection is booked; the parcel is still with the shipper.
11
+ ['pickup_completed', 'accepted'],
12
+ ['In_Transit', 'in_transit'],
13
+ ['arrived', 'in_transit'], // At a branch or hub on the way.
14
+ ['out_for_delviery', 'out_for_delivery'], // Zajil's own spelling.
15
+ ['undelivered', 'failed_attempt'],
16
+ ['recheduled', 'failed_attempt'], // A delivery moved to another day, Zajil's own spelling.
17
+ ['ready_for_collection', 'ready_for_pickup'],
18
+ ['delivered', 'delivered'],
19
+ ['returned_to_shipper', 'returned'],
20
+ ['rejected_by_customer', 'exception'], // Refused by the recipient.
21
+ ['cancelled', 'exception'],
22
+ ['Hold', 'exception'],
23
+ ]);
24
+ /** The stage Zajil's `website_update` value gives a status. */
25
+ export function zajilMappedStage(code) {
26
+ return UPDATES.get(code);
27
+ }
28
+ /** A status's stage: its `website_update` value, else the shared wording rules, else nothing. */
29
+ export function zajilStage(code, wording) {
30
+ const mapped = zajilMappedStage(code);
31
+ if (mapped)
32
+ return { stage: mapped, source: 'carrier_map' };
33
+ const worded = classifyWording(wording, 'in_transit');
34
+ return worded.source === 'none' ? null : worded;
35
+ }
36
+ export const statusMap = {
37
+ stage: (code) => (code ? zajilMappedStage(code) : undefined),
38
+ gaps: [],
39
+ };
@@ -1,8 +1,21 @@
1
1
  {
2
2
  "carrier": "zajil",
3
3
  "entries": [
4
- {"wording": "Processing", "stage": "registered", "language": "en", "confirmedBy": "bundle", "note": "Progress label in Zajil's tracking page script, which maps the tracking API's website_update value to it."},
5
- {"code": "In_Transit", "wording": "In Transit", "stage": "in_transit", "language": "en", "confirmedBy": "bundle", "note": "Progress label in Zajil's tracking page script, which maps the tracking API's website_update value to it."},
6
- {"wording": "Delivered", "stage": "delivered", "language": "en", "confirmedBy": "bundle", "note": "Progress label in Zajil's tracking page script, which maps the tracking API's website_update value to it."}
4
+ {"code": "processing", "wording": "Processing", "stage": "registered", "language": "en", "confirmedBy": "bundle", "note": "The tracking page's script puts the processing website_update value on the first step of its rail, under this label."},
5
+ {"code": "In_Transit", "wording": "In Transit", "stage": "in_transit", "language": "en", "confirmedBy": "bundle", "note": "The tracking page's script puts the In_Transit website_update value, and most others, on the second step of its rail, under this label."},
6
+ {"code": "delivered", "wording": "Delivered", "stage": "delivered", "language": "en", "confirmedBy": "bundle", "note": "The tracking page's script puts the delivered website_update value on the last step of its rail, under this label."},
7
+ {"code": "In_Transit", "wording": "جارى عمليه النقل", "stage": "in_transit", "language": "ar", "confirmedBy": "live", "note": "Transport in progress; seen for a shipment released from a hub."},
8
+ {"code": "delivered", "wording": "تم التوصيل", "stage": "delivered", "language": "ar", "confirmedBy": "live"},
9
+ {"code": "pickup_scheduled", "wording": "pickup_scheduled", "stage": "registered", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit. A collection is booked; the parcel is still with the shipper."},
10
+ {"code": "pickup_completed", "wording": "pickup_completed", "stage": "accepted", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit."},
11
+ {"code": "arrived", "wording": "arrived", "stage": "in_transit", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit."},
12
+ {"code": "out_for_delviery", "wording": "out_for_delviery", "stage": "out_for_delivery", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit. The spelling is Zajil's."},
13
+ {"code": "undelivered", "wording": "undelivered", "stage": "failed_attempt", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit."},
14
+ {"code": "recheduled", "wording": "recheduled", "stage": "failed_attempt", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit. A delivery moved to another day; the spelling is Zajil's."},
15
+ {"code": "ready_for_collection", "wording": "ready_for_collection", "stage": "ready_for_pickup", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit."},
16
+ {"code": "returned_to_shipper", "wording": "returned_to_shipper", "stage": "returned", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit."},
17
+ {"code": "rejected_by_customer", "wording": "rejected_by_customer", "stage": "exception", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit. Refused by the recipient."},
18
+ {"code": "cancelled", "wording": "cancelled", "stage": "exception", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit."},
19
+ {"code": "Hold", "wording": "Hold", "stage": "exception", "language": "en", "confirmedBy": "bundle", "note": "A website_update value the tracking page's script names; the page shows it on its rail as In Transit."}
7
20
  ]
8
21
  }
@@ -306,6 +306,7 @@ import { statusMap as tsjy } from '../../carriers/tsjy/status.js';
306
306
  import { statusMap as twsExpress } from '../../carriers/tws-express/status.js';
307
307
  import { statusMap as ubiSmartParcel } from '../../carriers/ubi-smart-parcel/status.js';
308
308
  import { statusMap as ups } from '../../carriers/ups/status.js';
309
+ import { statusMap as urbano } from '../../carriers/urbano/status.js';
309
310
  import { statusMap as urvaam } from '../../carriers/urvaam/status.js';
310
311
  import { statusMap as uzbekistanPost } from '../../carriers/uzbekistan-post/status.js';
311
312
  import { statusMap as vaspExpresso } from '../../carriers/vasp-expresso/status.js';
@@ -323,6 +324,7 @@ import { statusMap as zto } from '../../carriers/zto/status.js';
323
324
  import { statusMap as yunexpress } from '../../carriers/yunexpress/status.js';
324
325
  import { statusMap as yilongLogistics } from '../../carriers/yilong-logistics/status.js';
325
326
  import { statusMap as yurticiKargo } from '../../carriers/yurtici-kargo/status.js';
327
+ import { statusMap as zajil } from '../../carriers/zajil/status.js';
326
328
  import { statusMap as zeleris } from '../../carriers/zeleris/status.js';
327
329
  import { statusMap as universal } from '../../providers/status.js';
328
330
  import { normalizeStatusWording } from '../status/statusMap.js';
@@ -371,10 +373,10 @@ export const STATUS_MAPS = {
371
373
  't-cat': tCat, 't-group': tGroup, taxydema, 'tci-express': tciExpress, 'tcs-pakistan': tcsPakistan, tdn, tealca,
372
374
  'team-global-express': teamGlobalExpress, teleship, 'tforce-freight': tforceFreight, 'thailand-post': thailandPost, thhy, tiki,
373
375
  'tmm-express': tmmExpress, tnt, 'tnt-it': tntIt, toptrans, torrestir, 'total-express': totalExpress, transaher, transmission, tsjy,
374
- 'tws-express': twsExpress, 'ubi-smart-parcel': ubiSmartParcel, ups, urvaam,
376
+ 'tws-express': twsExpress, 'ubi-smart-parcel': ubiSmartParcel, ups, urbano, urvaam,
375
377
  'uzbekistan-post': uzbekistanPost, 'vasp-expresso': vaspExpresso, veloces, venipak, 'viettel-post': viettelPost, 'vinted-go': vintedGo, wanbexpress, whistl, winit, xdp, xlcourier, 'xpo-ltl': xpoLtl,
376
378
  'yilong-logistics': yilongLogistics, yunexpress, zto,
377
- 'yurtici-kargo': yurticiKargo, zeleris,
379
+ 'yurtici-kargo': yurticiKargo, zajil, zeleris,
378
380
  };
379
381
  /** The carrier the app files the universal providers' scans under. */
380
382
  const UNIVERSAL_CARRIER = 'unknown';
@@ -27569,7 +27569,8 @@
27569
27569
  "timezone": "America/Lima",
27570
27570
  "tracking": {
27571
27571
  "mode": "automatic",
27572
- "adapter": "universal"
27572
+ "adapter": "urbano",
27573
+ "localClocks": true
27573
27574
  },
27574
27575
  "canaryUrl": "https://www.urbano.com.pe/tracking/",
27575
27576
  "trackingUrlTemplate": "https://www.urbano.com.pe/tracking/{trackingNumber}",
@@ -27581,6 +27582,15 @@
27581
27582
  ],
27582
27583
  "path": "^/tracking/([^/?#]+)/?$"
27583
27584
  },
27585
+ {
27586
+ "domains": [
27587
+ "urbano.com.pe"
27588
+ ],
27589
+ "pathPattern": "^/tracking/?$",
27590
+ "params": [
27591
+ "guides"
27592
+ ]
27593
+ },
27584
27594
  {
27585
27595
  "domains": [
27586
27596
  "app.urbano.com.pe",
@@ -28769,7 +28779,8 @@
28769
28779
  "timezone": "Asia/Riyadh",
28770
28780
  "tracking": {
28771
28781
  "mode": "automatic",
28772
- "adapter": "universal"
28782
+ "adapter": "zajil",
28783
+ "localClocks": true
28773
28784
  },
28774
28785
  "canaryUrl": "https://zajil-express.com/track",
28775
28786
  "trackingUrlTemplate": "https://zajil-express.com/track?tracking_id={trackingNumber}",
@@ -17564,7 +17564,8 @@ export declare const CARRIER_CATALOG: {
17564
17564
  readonly timezone: "America/Lima";
17565
17565
  readonly tracking: {
17566
17566
  readonly mode: "automatic";
17567
- readonly adapter: "universal";
17567
+ readonly adapter: "urbano";
17568
+ readonly localClocks: true;
17568
17569
  };
17569
17570
  readonly canaryUrl: "https://www.urbano.com.pe/tracking/";
17570
17571
  readonly trackingUrlTemplate: "https://www.urbano.com.pe/tracking/{trackingNumber}";
@@ -17572,6 +17573,10 @@ export declare const CARRIER_CATALOG: {
17572
17573
  readonly linkRules: readonly [{
17573
17574
  readonly domains: readonly ["urbano.com.pe"];
17574
17575
  readonly path: "^/tracking/([^/?#]+)/?$";
17576
+ }, {
17577
+ readonly domains: readonly ["urbano.com.pe"];
17578
+ readonly pathPattern: "^/tracking/?$";
17579
+ readonly params: readonly ["guides"];
17575
17580
  }, {
17576
17581
  readonly domains: readonly ["app.urbano.com.pe", "api.urbano.com.pe"];
17577
17582
  readonly pathPattern: "^/plugin/etracking/etracking/?$";
@@ -18324,7 +18329,8 @@ export declare const CARRIER_CATALOG: {
18324
18329
  readonly timezone: "Asia/Riyadh";
18325
18330
  readonly tracking: {
18326
18331
  readonly mode: "automatic";
18327
- readonly adapter: "universal";
18332
+ readonly adapter: "zajil";
18333
+ readonly localClocks: true;
18328
18334
  };
18329
18335
  readonly canaryUrl: "https://zajil-express.com/track";
18330
18336
  readonly trackingUrlTemplate: "https://zajil-express.com/track?tracking_id={trackingNumber}";
@@ -27570,7 +27570,8 @@ export const CARRIER_CATALOG = {
27570
27570
  "timezone": "America/Lima",
27571
27571
  "tracking": {
27572
27572
  "mode": "automatic",
27573
- "adapter": "universal"
27573
+ "adapter": "urbano",
27574
+ "localClocks": true
27574
27575
  },
27575
27576
  "canaryUrl": "https://www.urbano.com.pe/tracking/",
27576
27577
  "trackingUrlTemplate": "https://www.urbano.com.pe/tracking/{trackingNumber}",
@@ -27582,6 +27583,15 @@ export const CARRIER_CATALOG = {
27582
27583
  ],
27583
27584
  "path": "^/tracking/([^/?#]+)/?$"
27584
27585
  },
27586
+ {
27587
+ "domains": [
27588
+ "urbano.com.pe"
27589
+ ],
27590
+ "pathPattern": "^/tracking/?$",
27591
+ "params": [
27592
+ "guides"
27593
+ ]
27594
+ },
27585
27595
  {
27586
27596
  "domains": [
27587
27597
  "app.urbano.com.pe",
@@ -28770,7 +28780,8 @@ export const CARRIER_CATALOG = {
28770
28780
  "timezone": "Asia/Riyadh",
28771
28781
  "tracking": {
28772
28782
  "mode": "automatic",
28773
- "adapter": "universal"
28783
+ "adapter": "zajil",
28784
+ "localClocks": true
28774
28785
  },
28775
28786
  "canaryUrl": "https://zajil-express.com/track",
28776
28787
  "trackingUrlTemplate": "https://zajil-express.com/track?tracking_id={trackingNumber}",
@@ -378,6 +378,7 @@ import { adapter as ubiSmartParcel } from '../carriers/ubi-smart-parcel/adapter.
378
378
  import { adapter as ukrposhta } from '../carriers/ukrposhta/adapter.js';
379
379
  import { adapter as uniuni } from '../carriers/uniuni/adapter.js';
380
380
  import { adapter as ups } from '../carriers/ups/adapter.js';
381
+ import { adapter as urbano } from '../carriers/urbano/adapter.js';
381
382
  import { adapter as urvaam } from '../carriers/urvaam/adapter.js';
382
383
  import { adapter as usps } from '../carriers/usps/adapter.js';
383
384
  import { adapter as uzbekistanPost } from '../carriers/uzbekistan-post/adapter.js';
@@ -400,6 +401,7 @@ import { adapter as yto } from '../carriers/yto/adapter.js';
400
401
  import { adapter as yunda } from '../carriers/yunda/adapter.js';
401
402
  import { adapter as yunexpress } from '../carriers/yunexpress/adapter.js';
402
403
  import { adapter as yurticiKargo } from '../carriers/yurtici-kargo/adapter.js';
404
+ import { adapter as zajil } from '../carriers/zajil/adapter.js';
403
405
  import { adapter as zeleris } from '../carriers/zeleris/adapter.js';
404
406
  import { adapter as zto } from '../carriers/zto/adapter.js';
405
407
  export const REGISTRY = {
@@ -783,6 +785,7 @@ export const REGISTRY = {
783
785
  "ukrposhta": ukrposhta,
784
786
  "uniuni": uniuni,
785
787
  "ups": ups,
788
+ "urbano": urbano,
786
789
  "urvaam": urvaam,
787
790
  "usps": usps,
788
791
  "uzbekistan-post": uzbekistanPost,
@@ -805,6 +808,7 @@ export const REGISTRY = {
805
808
  "yunda": yunda,
806
809
  "yunexpress": yunexpress,
807
810
  "yurtici-kargo": yurticiKargo,
811
+ "zajil": zajil,
808
812
  "zeleris": zeleris,
809
813
  "zto": zto,
810
814
  },
@@ -1492,7 +1496,7 @@ export const REGISTRY = {
1492
1496
  "unknown": "universal",
1493
1497
  "upaya": "universal",
1494
1498
  "ups": "ups",
1495
- "urbano": "universal",
1499
+ "urbano": "urbano",
1496
1500
  "urvaam": "urvaam",
1497
1501
  "usps": "usps",
1498
1502
  "uzbekistan-post": "uzbekistan-post",
@@ -1530,7 +1534,7 @@ export const REGISTRY = {
1530
1534
  "yunda": "yunda",
1531
1535
  "yunexpress": "yunexpress",
1532
1536
  "yurtici-kargo": "yurtici-kargo",
1533
- "zajil": "universal",
1537
+ "zajil": "zajil",
1534
1538
  "zeleris": "zeleris",
1535
1539
  "zheldor": "universal",
1536
1540
  "zoom-ve": "universal",
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.1.0",
3
3
  "info": {
4
4
  "title": "Universal Parcel Scraper",
5
- "version": "0.373.0"
5
+ "version": "0.374.0"
6
6
  },
7
7
  "paths": {
8
8
  "/health": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "universal-parcel-scraper",
3
- "version": "0.373.0-main.2014",
3
+ "version": "0.374.0-main.2018",
4
4
  "description": "Self-hosted parcel tracking: carrier detection, dedicated scrapers and optional universal providers.",
5
5
  "type": "module",
6
6
  "license": "Apache-2.0",