universal-parcel-scraper 0.178.0-main.1306 → 0.181.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.
Files changed (49) hide show
  1. package/README.md +3 -3
  2. package/data/catalog.json +56 -4
  3. package/data/coverage-summary.json +2 -2
  4. package/data/detection-golden.json +16 -0
  5. package/dist/browser/scraper.js +49 -6
  6. package/dist/carriers/5post/adapter.d.ts +22 -0
  7. package/dist/carriers/5post/adapter.js +75 -0
  8. package/dist/carriers/5post/carrier.json +44 -7
  9. package/dist/carriers/5post/numbers.json +22 -22
  10. package/dist/carriers/5post/parser.d.ts +23 -0
  11. package/dist/carriers/5post/parser.js +164 -0
  12. package/dist/carriers/5post/status.d.ts +9 -0
  13. package/dist/carriers/5post/status.js +100 -0
  14. package/dist/carriers/5post/statuses.json +63 -3
  15. package/dist/carriers/ems-vietnam/adapter.d.ts +17 -0
  16. package/dist/carriers/ems-vietnam/adapter.js +60 -0
  17. package/dist/carriers/ems-vietnam/carrier.json +65 -7
  18. package/dist/carriers/ems-vietnam/parser.d.ts +22 -0
  19. package/dist/carriers/ems-vietnam/parser.js +216 -0
  20. package/dist/carriers/ems-vietnam/status.d.ts +7 -0
  21. package/dist/carriers/ems-vietnam/status.js +55 -0
  22. package/dist/carriers/ems-vietnam/statuses.json +16 -0
  23. package/dist/carriers/israel-post/adapter.d.ts +14 -0
  24. package/dist/carriers/israel-post/adapter.js +57 -0
  25. package/dist/carriers/israel-post/carrier.json +40 -7
  26. package/dist/carriers/israel-post/parser.d.ts +6 -0
  27. package/dist/carriers/israel-post/parser.js +77 -0
  28. package/dist/carriers/israel-post/status.d.ts +4 -0
  29. package/dist/carriers/israel-post/status.js +15 -0
  30. package/dist/carriers/israel-post/statuses.json +37 -1
  31. package/dist/carriers/mayiyinfu/carrier.json +54 -0
  32. package/dist/carriers/mayiyinfu/numbers.json +17 -0
  33. package/dist/carriers/mayiyinfu/statuses.json +16 -0
  34. package/dist/carriers/pecom/adapter.d.ts +17 -0
  35. package/dist/carriers/pecom/adapter.js +60 -0
  36. package/dist/carriers/pecom/carrier.json +52 -7
  37. package/dist/carriers/pecom/parser.d.ts +13 -0
  38. package/dist/carriers/pecom/parser.js +214 -0
  39. package/dist/carriers/pecom/status.d.ts +7 -0
  40. package/dist/carriers/pecom/status.js +52 -0
  41. package/dist/carriers/pecom/statuses.json +9 -7
  42. package/dist/core/catalog/statusMaps.js +9 -4
  43. package/dist/data/catalog.json +56 -4
  44. package/dist/generated/catalog.d.ts +38 -5
  45. package/dist/generated/catalog.js +59 -5
  46. package/dist/generated/recognition.js +2 -0
  47. package/dist/generated/registry.js +13 -4
  48. package/dist/server/openapi.json +1 -1
  49. package/package.json +1 -1
@@ -0,0 +1,60 @@
1
+ import { accepted, recognizeFromLookup } from '../../core/adapter/index.js';
2
+ import { ChallengeError, SchemaError, TransportError } from '../../core/errors/index.js';
3
+ import { runSteps } from '../../core/runner/index.js';
4
+ import { NOOP_RECORDER } from '../../core/telemetry/index.js';
5
+ import { decodeText, fetchBounded, userAgentOf } from '../../core/transport/index.js';
6
+ import { EMS_VIETNAM_MAX_BYTES, normalizeEmsVietnamNumber, parseEmsVietnam, PROVIDER } from './parser.js';
7
+ /** The lookup the tracking page on ems.com.vn makes for the number typed in. */
8
+ export const EMS_VIETNAM_API = 'https://api.myems.vn/TrackAndTraceItemCode';
9
+ const REDIRECTS = [301, 302, 303, 307, 308];
10
+ // Bot checks Cloudflare, in front of the service, could put in place of the reply.
11
+ const CHALLENGE = /_cf_chl_opt|cf-turnstile|<title>\s*Just a moment|challenge-platform|<title>\s*Attention Required/i;
12
+ /** The address the page asks: the number with `EMS` after it, and the Vietnamese wording. */
13
+ export function emsVietnamLookupUrl(number) {
14
+ return `${EMS_VIETNAM_API}?itemcode=${encodeURIComponent(`${number}EMS`)}&language=0`;
15
+ }
16
+ function json(body) {
17
+ try {
18
+ return JSON.parse(body);
19
+ }
20
+ catch (cause) {
21
+ if (CHALLENGE.test(body.slice(0, 64_000)))
22
+ throw new ChallengeError(PROVIDER, 'EMS Vietnam answered with a browser check', { cause });
23
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned a reply that is not JSON', { cause });
24
+ }
25
+ }
26
+ export class EmsVietnamTracker {
27
+ options;
28
+ constructor(options = {}) {
29
+ this.options = options;
30
+ }
31
+ async fetch(raw, context = {}) {
32
+ const number = normalizeEmsVietnamNumber(raw);
33
+ const read = async (signal, timeoutMs) => {
34
+ const { response, bytes } = await fetchBounded(emsVietnamLookupUrl(number), { method: 'GET', signal, headers: {
35
+ Accept: 'application/json, text/plain, */*', 'User-Agent': userAgentOf(this.options.userAgent),
36
+ } }, { provider: PROVIDER, timeoutMs: Math.max(1, Math.floor(timeoutMs)), maxBytes: EMS_VIETNAM_MAX_BYTES,
37
+ redirect: 'manual', fetcher: this.options.fetcher, allowHttpStatuses: [...REDIRECTS, 404, 410] });
38
+ if (REDIRECTS.includes(response.status))
39
+ throw new TransportError(PROVIDER, 'EMS Vietnam redirected its tracking lookup');
40
+ // The service answers an unknown number with HTTP 200; a 404 is a moved route.
41
+ if (response.status === 404 || response.status === 410)
42
+ throw new TransportError(PROVIDER, 'EMS Vietnam tracking lookup is unavailable');
43
+ return parseEmsVietnam(json(decodeText(bytes)), number);
44
+ };
45
+ // One read with the whole budget, as the page allows thirty seconds: some
46
+ // numbers take the service twenty seconds or more to answer.
47
+ return runSteps({ carrier: 'ems-vietnam', budgetMs: context.budgetMs ?? 30_000, signal: context.signal,
48
+ recorder: this.options.recorder ?? NOOP_RECORDER }, [
49
+ { id: 'direct', run: ({ signal, remainingMs }) => read(signal, remainingMs) },
50
+ ]);
51
+ }
52
+ }
53
+ export const adapter = (environment) => {
54
+ const tracker = new EmsVietnamTracker({ fetcher: environment.fetcher, recorder: environment.recorder, userAgent: environment.userAgent });
55
+ return {
56
+ id: 'ems-vietnam', recordsSteps: true, steps: ['direct'],
57
+ track: (input, context) => tracker.fetch(input.number, context),
58
+ recognize: (number, context) => recognizeFromLookup(() => tracker.fetch(number, context), () => accepted(() => normalizeEmsVietnamNumber(number))),
59
+ };
60
+ };
@@ -19,18 +19,76 @@
19
19
  "timezone": "Asia/Ho_Chi_Minh",
20
20
  "tracking": {
21
21
  "mode": "automatic",
22
- "adapter": "universal",
23
- "steps": []
22
+ "adapter": "ems-vietnam",
23
+ "steps": [
24
+ "direct"
25
+ ],
26
+ "recognition": {
27
+ "rank": 962,
28
+ "pattern": "^E[A-Z]\\d{9}VN$"
29
+ },
30
+ "localClocks": true
24
31
  },
25
- "capabilities": [],
32
+ "capabilities": [
33
+ "history",
34
+ "location",
35
+ "provider_code",
36
+ "delivered_at",
37
+ "weight",
38
+ "destination_country"
39
+ ],
26
40
  "portal": {
27
41
  "url": "https://ems.com.vn/tra-cuu/tra-cuu-buu-gui?code={trackingNumber}",
28
42
  "searchUrl": "https://www.ems.com.vn/tra-cuu/tra-cuu-buu-gui",
29
43
  "canaryUrl": "https://www.ems.com.vn/tra-cuu/tra-cuu-buu-gui",
30
- "shows": [],
31
- "scraped": [],
32
- "discarded": [],
33
- "unavailable": []
44
+ "shows": [
45
+ "status",
46
+ "history",
47
+ "location",
48
+ "provider_code",
49
+ "delivered_at",
50
+ "weight",
51
+ "origin_country",
52
+ "destination_country",
53
+ "acceptance_office",
54
+ "delivery_office",
55
+ "sender_name",
56
+ "sender_address",
57
+ "recipient_name",
58
+ "recipient_address",
59
+ "customer_reference",
60
+ "office_addresses",
61
+ "contact_details",
62
+ "failed_delivery_reason"
63
+ ],
64
+ "scraped": [
65
+ "status",
66
+ "history",
67
+ "location",
68
+ "provider_code",
69
+ "delivered_at",
70
+ "weight",
71
+ "destination_country"
72
+ ],
73
+ "discarded": [
74
+ "origin_country",
75
+ "acceptance_office",
76
+ "delivery_office",
77
+ "sender_name",
78
+ "sender_address",
79
+ "recipient_name",
80
+ "recipient_address",
81
+ "customer_reference",
82
+ "office_addresses",
83
+ "contact_details",
84
+ "failed_delivery_reason"
85
+ ],
86
+ "unavailable": [
87
+ "eta",
88
+ "service_name",
89
+ "offset_timestamps",
90
+ "proof_of_delivery"
91
+ ]
34
92
  },
35
93
  "links": [
36
94
  {
@@ -0,0 +1,22 @@
1
+ import type { CarrierResult } from '../../core/result/index.js';
2
+ export declare const PROVIDER = "EMS Vietnam";
3
+ export declare const EMS_VIETNAM_MAX_BYTES: number;
4
+ /** A UPU S10 number, in upper case; anything else is not one EMS Vietnam issues. */
5
+ export declare function normalizeEmsVietnamNumber(raw: string): string;
6
+ /**
7
+ * A scan's wording, code and office. The wording loses its code, the office
8
+ * and what follows it (the customer-service line), a postman's name, a
9
+ * receiver or signer and phone numbers.
10
+ */
11
+ export declare function emsVietnamScanText(raw: string): {
12
+ code: string;
13
+ description: string;
14
+ office: string;
15
+ };
16
+ /**
17
+ * The reply of `TrackAndTraceItemCode` for one number. `Code` "00" carries the
18
+ * record, whose `TBL_INFO.MAE1` must be the number asked; its scans are in
19
+ * `List_TBL_DINH_VI`, oldest first. A number the tracker does not know comes
20
+ * back with every field null, which the page reports as not found.
21
+ */
22
+ export declare function parseEmsVietnam(payload: unknown, raw: string): CarrierResult;
@@ -0,0 +1,216 @@
1
+ import { DateTime } from 'luxon';
2
+ import { isValidS10TrackingNumber, 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 { firstOccurrence } from '../../core/time/index.js';
6
+ import { clean, cleanScalar } from '../../core/transport/index.js';
7
+ import { isRecord } from '../../core/types.js';
8
+ import { emsVietnamStage } from './status.js';
9
+ export const PROVIDER = 'EMS Vietnam';
10
+ // A long history is under twenty kilobytes.
11
+ export const EMS_VIETNAM_MAX_BYTES = 512 * 1024;
12
+ const ZONE = 'Asia/Ho_Chi_Minh';
13
+ const DATE = /^(\d{2})\/(\d{2})\/(\d{4})$/;
14
+ const CLOCK = /^\d{2}:\d{2}:\d{2}$/;
15
+ // The delivery table's clock on the international exchange's rows: "1/12/2026 9:56:00 AM".
16
+ const DATED_CLOCK = /^\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{2}:\d{2} [AP]M$/;
17
+ const MAX_ROWS = 500;
18
+ const MAX_EVENTS = 100;
19
+ const LISTS = ['List_TBL_DINH_VI', 'List_TBL_DELIVERY', 'List_TBL_DELIVERY_lIST'];
20
+ /** A UPU S10 number, in upper case; anything else is not one EMS Vietnam issues. */
21
+ export function normalizeEmsVietnamNumber(raw) {
22
+ const number = raw.length <= 64 ? normalizeTrackingNumber(raw).toUpperCase() : '';
23
+ if (!isValidS10TrackingNumber(number))
24
+ throw new InvalidInputError(PROVIDER, 'EMS Vietnam numbers are UPU S10 numbers');
25
+ return number;
26
+ }
27
+ /** An optional text field; anything but a string is a changed reply. */
28
+ function text(row, key, maxLength = 500) {
29
+ const value = row[key];
30
+ if (value === null || value === undefined)
31
+ return '';
32
+ if (typeof value !== 'string')
33
+ throw new SchemaError(PROVIDER, `EMS Vietnam returned an invalid ${key}`);
34
+ return clean(value.normalize('NFC'), maxLength);
35
+ }
36
+ // The UPU event code some scans start with: "EMI - Phát thành công (Delivered)".
37
+ const CODE = /^([A-Z]{3})\s+-\s+/;
38
+ // The office that scanned, after the wording: "(100000: Office - Province)".
39
+ const OFFICE = /\(\s*\d{6}\s*:/;
40
+ // The office in the older layout's position field: "100000 - Office".
41
+ const LEGACY_OFFICE = /^\d{6}\s*-\s*(.+)$/;
42
+ // The customer-service contact the acceptance scan names.
43
+ const HELPLINE = /\(\s*Đầu mối CSKH[^)]*\)?/gi;
44
+ // The postman the older layout names after the handover: "Đã giao cho bưu tá: name SĐT: phone".
45
+ const POSTMAN = /(bưu tá(?: phát)?)\s*:[\s\S]*$/i;
46
+ // A receiver, a signer or a phone after its label: the rest of the wording goes.
47
+ const PERSON = /\s*[,;.\-–]?\s*(?:(?:người nhận|người ký|ký nhận|điện thoại|s?[đð]t)\s*:|s[đð]t\b)[\s\S]*$/i;
48
+ // A run of nine or more digits, with spaces, brackets, dots or hyphens
49
+ // between them, as phone numbers are written.
50
+ const PHONE = /(?<![A-Z\d])\+?\d(?:[\s().-]{0,2}\d){8,}(?![A-Z\d])/gi;
51
+ /** The text inside the bracket that opens at `start`, and where it ends. */
52
+ function bracketed(value, start) {
53
+ let depth = 0;
54
+ for (let index = start; index < value.length; index++) {
55
+ if (value[index] === '(')
56
+ depth++;
57
+ if (value[index] === ')' && --depth === 0)
58
+ return { inner: value.slice(start + 1, index), end: index + 1 };
59
+ }
60
+ return { inner: value.slice(start + 1), end: value.length };
61
+ }
62
+ /**
63
+ * A scan's wording, code and office. The wording loses its code, the office
64
+ * and what follows it (the customer-service line), a postman's name, a
65
+ * receiver or signer and phone numbers.
66
+ */
67
+ export function emsVietnamScanText(raw) {
68
+ const value = clean(raw.normalize('NFC'), 1000);
69
+ const code = CODE.exec(value)?.[1] ?? '';
70
+ let rest = code ? value.replace(CODE, '') : value;
71
+ let office = '';
72
+ const at = rest.search(OFFICE);
73
+ if (at >= 0) {
74
+ const { inner } = bracketed(rest, at);
75
+ office = clean(inner.replace(/^\s*\d{6}\s*:/, ''), 120);
76
+ rest = rest.slice(0, at);
77
+ }
78
+ const description = clean(rest.replace(HELPLINE, '').replace(POSTMAN, '$1').replace(PERSON, '').replace(PHONE, ''))
79
+ .replace(/^[\s,;:.\-–]+|[\s,;:\-–]+$/g, '');
80
+ return { code, description, office };
81
+ }
82
+ /** The wall clock of `NGAY` (day/month/year) and `GIO`, to the second. */
83
+ function wallClock(row) {
84
+ const date = DATE.exec(text(row, 'NGAY', 16));
85
+ const clock = text(row, 'GIO', 16);
86
+ const wall = date ? `${date[3]}-${date[2]}-${date[1]}T${clock}` : '';
87
+ // Parsing in UTC checks the calendar digits only. Luxon rolls 24:00:00 over to the next day.
88
+ const checked = DateTime.fromISO(wall, { zone: 'UTC' });
89
+ if (!date || !CLOCK.test(clock) || !checked.isValid || checked.toFormat("yyyy-MM-dd'T'HH:mm:ss") !== wall) {
90
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned an invalid scan time');
91
+ }
92
+ return wall;
93
+ }
94
+ function projectRow(row) {
95
+ const scan = emsVietnamScanText(text(row, 'TRANG_THAI', 1000));
96
+ if (!scan.description)
97
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned a scan without wording');
98
+ const legacy = LEGACY_OFFICE.exec(text(row, 'VI_TRI', 300));
99
+ const office = scan.office || clean(legacy?.[1], 120);
100
+ const wall = wallClock(row);
101
+ // A scan at a Vietnamese post office, by its six-digit office code, is on
102
+ // Vietnam's clock, which has no daylight saving. Anything else keeps its wall clock.
103
+ const vietnamese = Boolean(scan.office || legacy);
104
+ const clock = vietnamese
105
+ ? { time: firstOccurrence(DateTime.fromISO(wall, { zone: ZONE })).toISO({ suppressMilliseconds: true }) }
106
+ : { local_time: wall };
107
+ const staged = emsVietnamStage(scan.code, scan.description);
108
+ const event = {
109
+ ...clock,
110
+ ...(office ? { location: office } : {}),
111
+ description: scan.description,
112
+ ...(scan.code ? { provider_code: scan.code } : {}),
113
+ ...(staged ? { stage: staged.stage, stage_source: staged.source } : {}),
114
+ };
115
+ return { key: JSON.stringify([wall, scan.code, scan.description, office]), event, wall };
116
+ }
117
+ function rows(payload, key) {
118
+ const value = payload[key] ?? [];
119
+ if (!Array.isArray(value))
120
+ throw new SchemaError(PROVIDER, `EMS Vietnam returned an invalid ${key}`);
121
+ if (value.length > MAX_ROWS)
122
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned an oversized history');
123
+ if (value.some((row) => !isRecord(row)))
124
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned an invalid scan');
125
+ return value;
126
+ }
127
+ /** The two-letter code before the country's name: "VN - VIETNAM". */
128
+ function country(info) {
129
+ return /^([A-Z]{2})\s*-/.exec(text(info, 'Nuoc_Phat', 80))?.[1] ?? null;
130
+ }
131
+ /** `KHOI_LUONG`, in grams. */
132
+ function weightKg(info) {
133
+ const grams = cleanScalar(info.KHOI_LUONG, 16);
134
+ return /^\d{1,7}(?:\.\d+)?$/.test(grams) && Number(grams) > 0 ? Number(grams) / 1000 : null;
135
+ }
136
+ /**
137
+ * The reply of `TrackAndTraceItemCode` for one number. `Code` "00" carries the
138
+ * record, whose `TBL_INFO.MAE1` must be the number asked; its scans are in
139
+ * `List_TBL_DINH_VI`, oldest first. A number the tracker does not know comes
140
+ * back with every field null, which the page reports as not found.
141
+ */
142
+ export function parseEmsVietnam(payload, raw) {
143
+ const number = normalizeEmsVietnamNumber(raw);
144
+ if (!isRecord(payload) || !Object.hasOwn(payload, 'Code')) {
145
+ // The service's own failure, as ASP.NET words it: a message and nothing else of the reply.
146
+ if (isRecord(payload) && typeof payload.Message === 'string' && !Object.hasOwn(payload, 'TBL_INFO')
147
+ && LISTS.every((key) => !Object.hasOwn(payload, key)))
148
+ throw new IndeterminateError(PROVIDER, 'EMS Vietnam did not complete the lookup');
149
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned an invalid envelope');
150
+ }
151
+ const code = payload.Code;
152
+ if (code === null) {
153
+ if (payload.TBL_INFO === null && LISTS.every((key) => payload[key] === null))
154
+ throw new NotFoundError(PROVIDER);
155
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned a record without its result code');
156
+ }
157
+ if (typeof code !== 'string')
158
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned an invalid result code');
159
+ if (code !== '00') {
160
+ // The former reply's explicit answer: "Không tìm thấy thông tin bưu gửi".
161
+ if (code === '99' && /không tìm thấy/i.test(text(payload, 'Message', 200)))
162
+ throw new NotFoundError(PROVIDER);
163
+ throw new IndeterminateError(PROVIDER, 'EMS Vietnam did not complete the lookup');
164
+ }
165
+ const info = payload.TBL_INFO;
166
+ if (info !== null && info !== undefined && !isRecord(info))
167
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned an invalid item record');
168
+ const scans = rows(payload, 'List_TBL_DINH_VI');
169
+ const deliveries = rows(payload, 'List_TBL_DELIVERY');
170
+ // An international item whose Vietnamese record has expired keeps only the
171
+ // delivery table, which names no item: nothing binds it to the number.
172
+ if (!info || !Object.keys(info).length)
173
+ throw new IndeterminateError(PROVIDER, 'EMS Vietnam answered without naming the item');
174
+ if (typeof info.MAE1 !== 'string')
175
+ throw new SchemaError(PROVIDER, 'EMS Vietnam returned an item without its number');
176
+ if (clean(info.MAE1, 64).toUpperCase() !== number)
177
+ throw new IndeterminateError(PROVIDER, 'EMS Vietnam answered for another item');
178
+ const seen = new Set();
179
+ const projected = [];
180
+ for (const row of scans) {
181
+ const scan = projectRow(row);
182
+ if (seen.has(scan.key))
183
+ continue;
184
+ seen.add(scan.key);
185
+ projected.push(scan);
186
+ }
187
+ if (!projected.length)
188
+ throw new NoHistoryError(PROVIDER);
189
+ // Newest first. The page lists the scans oldest first, a later one of the
190
+ // same second after the earlier; a reply listed newest first stays as it is.
191
+ const oldestFirst = projected[0].wall <= projected.at(-1).wall;
192
+ const events = (oldestFirst ? projected.reverse() : projected).map(({ event }) => event);
193
+ const newest = events[0];
194
+ const current = events.find((event) => event.stage);
195
+ const stage = current?.stage;
196
+ const delivered = stage === 'delivered' && typeof current.time === 'string' ? current.time : null;
197
+ // Domestic delivery rows give the time alone and repeat the history's delivery
198
+ // scans. Rows dated in full are the international exchange's scans, which
199
+ // the history does not hold.
200
+ const abroad = deliveries.some((row) => DATED_CLOCK.test(text(row, 'GIO_TRANG_THAI', 32)));
201
+ const destination = country(info);
202
+ const weight = weightKg(info);
203
+ return {
204
+ status: stage ? languageStageStatus(stage) : 'unknown',
205
+ ...(stage ? { current_stage: stage, current_stage_source: current.stage_source } : {}),
206
+ last_status_text: newest.description,
207
+ last_update: typeof newest.time === 'string' ? newest.time : null,
208
+ ...(typeof newest.local_time === 'string' ? { last_update_local: newest.local_time } : {}),
209
+ expected_delivery: null,
210
+ ...(delivered ? { delivered_at: delivered } : {}),
211
+ ...(weight ? { weight_kg: weight } : {}),
212
+ ...(destination ? { destination_country: destination } : {}),
213
+ events: events.slice(0, MAX_EVENTS),
214
+ ...(abroad || events.length > MAX_EVENTS ? { history_truncated: true } : {}),
215
+ };
216
+ }
@@ -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 EMS Vietnam's own vocabulary gives a scan's code or wording. */
4
+ export declare function emsVietnamMappedStage(code: string | null, wording: string): Stage | undefined;
5
+ /** A scan's stage: its code or wording, else the shared wording rules, else nothing. */
6
+ export declare function emsVietnamStage(code: string, wording: string): ClassifiedWording | null;
7
+ export declare const statusMap: CarrierStatusMap;
@@ -0,0 +1,55 @@
1
+ import { classifyWording } from '../../core/status/index.js';
2
+ import { normalizeStatusWording } from '../../core/status/statusMap.js';
3
+ /**
4
+ * The UPU EMS event codes the tracker puts before some scans' wording. Only
5
+ * codes seen in replies are mapped; another code falls to the wording.
6
+ */
7
+ const CODES = new Map([
8
+ ['EMA', 'accepted'], // Posting / Collection.
9
+ ['EDG', 'out_for_delivery'], // Item out for physical delivery.
10
+ ['EMH', 'failed_attempt'], // Attempted / Unsuccessful delivery.
11
+ ['EMI', 'delivered'],
12
+ ]);
13
+ /** The scans without a code, by their whole wording in `normalizeStatusWording` form. */
14
+ const WORDINGS = new Map([
15
+ ['đã phân hướng lấy hàng (data out for pickup)', 'registered'], // A courier is assigned to collect the parcel.
16
+ ['đang đi thu gom', 'registered'], // The courier is on the way to collect it.
17
+ ['nhận hàng thành công (picked up)', 'accepted'],
18
+ ['chấp nhận gửi', 'accepted'],
19
+ ['đi khỏi bưu cục (departure from po)', 'in_transit'],
20
+ ['đã vận chuyển đi khỏi bưu cục (transport departure from po)', 'in_transit'],
21
+ ['đã đến bưu cục (arrival at po)', 'in_transit'],
22
+ ['đã vận chuyển đến bưu cục (transport arrival at po)', 'in_transit'],
23
+ ['xác nhận đến bưu gửi theo túi, arrival at po by postbag', 'in_transit'],
24
+ ['đã đóng chuyến thư đi', 'in_transit'], // Closed into an outgoing mail bag.
25
+ ['[bđ8]đã xác nhận đi', 'in_transit'],
26
+ ['[bđ8]đã tới bưu cục nhận', 'in_transit'],
27
+ ['đã xác nhận đến', 'in_transit'],
28
+ ['đã giao cho bưu tá', 'out_for_delivery'],
29
+ ['phát thành công', 'delivered'],
30
+ ['đã phát thành công', 'delivered'],
31
+ ]);
32
+ const NOTES = new Map([
33
+ ['phát hành phiếu nhờ thu', 'The slip for a cash-on-delivery amount is issued at acceptance; it moves nothing.'],
34
+ ['routed', 'The item joins a delivery round, with its out-for-delivery scan at the same minute; it moves nothing on its own.'],
35
+ ['đã thu tiền khách hàng', 'The cash-on-delivery amount taken from the recipient, beside the delivery scan; it moves nothing.'],
36
+ ['đã thu tiền bưu tá', 'The office takes the cash the postman collected, after the delivery; it moves nothing.'],
37
+ ]);
38
+ /** The stage EMS Vietnam's own vocabulary gives a scan's code or wording. */
39
+ export function emsVietnamMappedStage(code, wording) {
40
+ return (code ? CODES.get(code.toUpperCase()) : undefined) ?? WORDINGS.get(normalizeStatusWording(wording.normalize('NFC')));
41
+ }
42
+ /** A scan's stage: its code or wording, else the shared wording rules, else nothing. */
43
+ export function emsVietnamStage(code, wording) {
44
+ const mapped = emsVietnamMappedStage(code || null, wording);
45
+ if (mapped)
46
+ return { stage: mapped, source: 'carrier_map' };
47
+ if (!code && NOTES.has(normalizeStatusWording(wording.normalize('NFC'))))
48
+ return null;
49
+ const worded = classifyWording(wording, 'in_transit');
50
+ return worded.source === 'none' ? null : worded;
51
+ }
52
+ export const statusMap = {
53
+ stage: (code, wording) => emsVietnamMappedStage(code, wording),
54
+ gaps: [...NOTES].map(([wording, note]) => ({ wording, note })),
55
+ };
@@ -1,6 +1,22 @@
1
1
  {
2
2
  "carrier": "ems-vietnam",
3
3
  "entries": [
4
+ {"code": "EMA", "wording": "Chấp nhận gửi (Posting / Collection)", "stage": "accepted", "language": "vi", "confirmedBy": "live", "note": "Followed by the accepting office and a customer-service contact in brackets, left out here."},
5
+ {"wording": "Đã phân hướng lấy hàng (Data out for Pickup)", "stage": "registered", "language": "vi", "confirmedBy": "live", "note": "A courier is assigned to collect the parcel from the sender."},
6
+ {"wording": "Đang đi thu gom", "stage": "registered", "language": "vi", "confirmedBy": "live", "note": "The courier is on the way to collect the parcel."},
7
+ {"wording": "Nhận hàng thành công (Picked up)", "stage": "accepted", "language": "vi", "confirmedBy": "live"},
8
+ {"wording": "Phát hành phiếu nhờ thu", "language": "vi", "confirmedBy": "live", "unmapped": true, "note": "The slip for a cash-on-delivery amount, issued at acceptance; it moves nothing."},
9
+ {"wording": "Đi khỏi bưu cục (Departure from PO)", "stage": "in_transit", "language": "vi", "confirmedBy": "live"},
10
+ {"wording": "Đã vận chuyển đi khỏi bưu cục (Transport departure from PO)", "stage": "in_transit", "language": "vi", "confirmedBy": "live"},
11
+ {"wording": "Đã vận chuyển đến bưu cục (Transport arrival at PO)", "stage": "in_transit", "language": "vi", "confirmedBy": "live"},
12
+ {"wording": "Xác nhận đến bưu gửi theo túi, Arrival at PO by Postbag", "stage": "in_transit", "language": "vi", "confirmedBy": "live"},
13
+ {"wording": "Đã đến bưu cục (Arrival at PO)", "stage": "in_transit", "language": "vi", "confirmedBy": "live"},
14
+ {"code": "EDG", "wording": "Đã giao bưu tá phát - Item out for physical delivery", "stage": "out_for_delivery", "language": "vi", "confirmedBy": "live"},
15
+ {"wording": "Routed", "language": "vi", "confirmedBy": "live", "unmapped": true, "note": "The item joins a delivery round, at the same second as its out-for-delivery scan; it moves nothing on its own."},
16
+ {"code": "EMH", "wording": "Phát không thành công (Attempted / Unsuccessful delivery)", "stage": "failed_attempt", "language": "vi", "confirmedBy": "live", "note": "The delivery table gives the reason, such as the recipient being away; the adapter does not read it."},
17
+ {"code": "EMI", "wording": "Phát thành công (Delivered)", "stage": "delivered", "language": "vi", "confirmedBy": "live"},
18
+ {"wording": "Đã thu tiền khách hàng", "language": "vi", "confirmedBy": "live", "unmapped": true, "note": "The cash-on-delivery amount taken from the recipient, beside the delivery scan; it moves nothing."},
19
+ {"wording": "Đã thu tiền bưu tá", "language": "vi", "confirmedBy": "live", "unmapped": true, "note": "The office takes the cash the postman collected, after the delivery; it moves nothing."},
4
20
  {"wording": "Chấp nhận gửi", "stage": "accepted", "language": "vi", "confirmedBy": "portal", "note": "Followed by a customer-service contact in brackets. Seen in an archived reply of EMS Vietnam's tracking API, which its tracking page calls."},
5
21
  {"wording": "Đã đóng chuyến thư đi", "stage": "in_transit", "language": "vi", "confirmedBy": "portal", "note": "Dispatched in an outgoing mail bag. Seen in an archived reply of EMS Vietnam's tracking API, which its tracking page calls."},
6
22
  {"wording": "[BĐ8]Đã xác nhận đi", "stage": "in_transit", "language": "vi", "confirmedBy": "portal", "note": "Departure confirmed. Seen in an archived reply of EMS Vietnam's tracking API, which its tracking page calls."},
@@ -0,0 +1,14 @@
1
+ import { type AdapterFactory, type 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
+ export declare const ISRAEL_POST_ENDPOINT = "https://apimftprd.israelpost.co.il/itemtracecert/items//";
5
+ export declare class IsraelPostTracker {
6
+ private readonly options;
7
+ constructor(options?: {
8
+ fetcher?: typeof fetch;
9
+ recorder?: StepRecorder;
10
+ userAgent?: string;
11
+ });
12
+ fetch(raw: string, context?: TrackingContext): Promise<CarrierResult>;
13
+ }
14
+ export declare const adapter: AdapterFactory;
@@ -0,0 +1,57 @@
1
+ import { accepted, recognizeFromLookup } from '../../core/adapter/index.js';
2
+ import { ChallengeError, SchemaError, TransportError, UpstreamHttpError } from '../../core/errors/index.js';
3
+ import { runSteps } from '../../core/runner/index.js';
4
+ import { firstAttemptMs, networkRetryStep } from '../../core/runner/networkRetry.js';
5
+ import { NOOP_RECORDER } from '../../core/telemetry/index.js';
6
+ import { decodeText, fetchBounded, parseJsonBytes, userAgentOf } from '../../core/transport/index.js';
7
+ import { normalizeIsraelPostNumber, parseIsraelPost, PROVIDER } from './parser.js';
8
+ // The Android app's addPackageByCodeRequestWithoutLogin joins these two slashes.
9
+ export const ISRAEL_POST_ENDPOINT = 'https://apimftprd.israelpost.co.il/itemtracecert/items//';
10
+ // Shared across installs of com.israelpost.israelpost for anonymous tracking.
11
+ const SUBSCRIPTION_KEY = '856e324428194b8885732347153fe47f'; // gitleaks:allow
12
+ const BLOCKED = /<title>\s*(?:Access Denied|Just a moment|Attention Required)|_cf_chl_opt|cf-turnstile|הגישה נחסמה/i;
13
+ export class IsraelPostTracker {
14
+ options;
15
+ constructor(options = {}) {
16
+ this.options = options;
17
+ }
18
+ async fetch(raw, context = {}) {
19
+ const number = normalizeIsraelPostNumber(raw);
20
+ const read = async (signal, timeoutMs) => {
21
+ let bytes;
22
+ try {
23
+ ({ bytes } = await fetchBounded(ISRAEL_POST_ENDPOINT + number, { method: 'GET', signal,
24
+ headers: { Accept: 'application/json', 'Content-Type': 'application/json',
25
+ 'Ocp-Apim-Subscription-Key': SUBSCRIPTION_KEY, 'User-Agent': userAgentOf(this.options.userAgent) } }, { provider: PROVIDER, timeoutMs: Math.max(1, Math.floor(timeoutMs)), maxBytes: 256_000, redirect: 'manual', fetcher: this.options.fetcher }));
26
+ }
27
+ catch (error) {
28
+ if (error instanceof UpstreamHttpError && [301, 302, 303, 307, 308, 404, 410].includes(error.status)) {
29
+ throw new TransportError(PROVIDER, 'Israel Post tracking endpoint is unavailable', { cause: error });
30
+ }
31
+ throw error;
32
+ }
33
+ let payload;
34
+ try {
35
+ payload = parseJsonBytes(bytes, PROVIDER);
36
+ }
37
+ catch (cause) {
38
+ if (BLOCKED.test(decodeText(bytes.subarray(0, 64_000))))
39
+ throw new ChallengeError(PROVIDER, 'Israel Post answered with a block page', { cause });
40
+ throw new SchemaError(PROVIDER, 'Israel Post returned invalid tracking JSON', { cause });
41
+ }
42
+ return parseIsraelPost(payload, number);
43
+ };
44
+ return runSteps({ carrier: 'israel-post', budgetMs: context.budgetMs ?? 20_000, signal: context.signal,
45
+ recorder: this.options.recorder ?? NOOP_RECORDER }, [
46
+ { id: 'direct', run: ({ signal, remainingMs }) => read(signal, firstAttemptMs(remainingMs)) },
47
+ networkRetryStep(({ signal, remainingMs }) => read(signal, remainingMs)),
48
+ ]);
49
+ }
50
+ }
51
+ export const adapter = environment => {
52
+ const tracker = new IsraelPostTracker({ fetcher: environment.fetcher, recorder: environment.recorder, userAgent: environment.userAgent });
53
+ return { id: 'israel-post', recordsSteps: true, steps: ['direct', 'retry'],
54
+ track: (input, context) => tracker.fetch(input.number, context),
55
+ recognize: (number, context) => recognizeFromLookup(() => tracker.fetch(number, context), () => accepted(() => normalizeIsraelPostNumber(number))),
56
+ };
57
+ };
@@ -17,18 +17,44 @@
17
17
  "timezone": "Asia/Jerusalem",
18
18
  "tracking": {
19
19
  "mode": "automatic",
20
- "adapter": "universal",
21
- "steps": []
20
+ "adapter": "israel-post",
21
+ "steps": [
22
+ "direct",
23
+ "retry"
24
+ ],
25
+ "recognition": {
26
+ "rank": 81
27
+ },
28
+ "localClocks": true
22
29
  },
23
- "capabilities": [],
30
+ "capabilities": [
31
+ "history",
32
+ "provider_code"
33
+ ],
24
34
  "portal": {
25
35
  "url": "https://israelpost.co.il/%D7%9E%D7%A2%D7%A7%D7%91-%D7%9E%D7%A9%D7%9C%D7%95%D7%97%D7%99%D7%9D?OpenForm&itemcode={trackingNumber}",
26
36
  "searchUrl": "https://israelpost.co.il/%D7%9E%D7%A2%D7%A7%D7%91-%D7%9E%D7%A9%D7%9C%D7%95%D7%97%D7%99%D7%9D",
27
37
  "canaryUrl": "https://israelpost.co.il/",
28
- "shows": [],
29
- "scraped": [],
30
- "discarded": [],
31
- "unavailable": []
38
+ "shows": [
39
+ "status",
40
+ "history",
41
+ "location"
42
+ ],
43
+ "scraped": [
44
+ "status",
45
+ "history",
46
+ "provider_code"
47
+ ],
48
+ "discarded": [
49
+ "recipient",
50
+ "sender",
51
+ "address",
52
+ "payment_link"
53
+ ],
54
+ "unavailable": [
55
+ "scan_times",
56
+ "offset_timestamps"
57
+ ]
32
58
  },
33
59
  "links": [
34
60
  {
@@ -57,6 +83,13 @@
57
83
  "id": "israel-post-1",
58
84
  "pattern": "^\\d{11}IL$",
59
85
  "confidence": "high"
86
+ },
87
+ {
88
+ "id": "israel-post-s10",
89
+ "pattern": "^[A-Z]{2}\\d{9}IL$",
90
+ "confidence": "low",
91
+ "preferred": true,
92
+ "checksum": "s10"
60
93
  }
61
94
  ]
62
95
  }
@@ -0,0 +1,6 @@
1
+ import type { CarrierResult } from '../../core/result/index.js';
2
+ export declare const PROVIDER = "Israel Post";
3
+ /** Postal S10 items, including imports, and Israel Post's domestic courier identifiers. */
4
+ export declare function normalizeIsraelPostNumber(raw: string): string;
5
+ /** The native guest read returns an identity and Maslul, newest first. */
6
+ export declare function parseIsraelPost(payload: unknown, raw: string): CarrierResult;