universal-parcel-scraper 0.1281.2-main.8521 → 0.1281.5-main.8527

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.
@@ -1,5 +1,5 @@
1
1
  import { accepted, readerLanguage, recognizeFromLookup } from '../../core/adapter/index.js';
2
- import { BudgetExceededError, IndeterminateError, MaintenanceError, SchemaError, UpstreamHttpError } from '../../core/errors/index.js';
2
+ import { BudgetExceededError, IndeterminateError, MaintenanceError, SchemaError, UpstreamHttpError, UpstreamNetworkError } from '../../core/errors/index.js';
3
3
  import { runSteps } from '../../core/runner/index.js';
4
4
  import { NOOP_RECORDER } from '../../core/telemetry/index.js';
5
5
  import { decodeText, fetchBounded, userAgentOf } from '../../core/transport/index.js';
@@ -14,6 +14,12 @@ const ORIGIN_RESERVE_MS = 500;
14
14
  const ON_THE_WAY = new Set(['accepted', 'in_transit', 'customs', 'out_for_delivery']);
15
15
  /** The statuses BRT's gateway answers while the server behind it is down, as it is for a while most nights. */
16
16
  const GATEWAY_FAILURES = new Set([502, 503, 504]);
17
+ /**
18
+ * The time a page of BRT's gets while the DPD group's service can stand in for it. BRT answers in a couple of
19
+ * seconds; on those nights its gateway can also hold a request for fifteen before answering, which would spend the
20
+ * whole lookup.
21
+ */
22
+ const PAGE_BEFORE_GROUP_MS = 8_000;
17
23
  export class BrtTracker {
18
24
  options;
19
25
  constructor(options = {}) {
@@ -26,6 +32,7 @@ export class BrtTracker {
26
32
  fetch(raw, context = {}, language = 'en') {
27
33
  const number = normalizeBrtNumber(raw);
28
34
  const budgetMs = context.budgetMs ?? 15_000;
35
+ const groupRoute = number.length === 14 && Boolean(this.options.group);
29
36
  return runSteps({ carrier: 'brt', budgetMs, signal: context.signal,
30
37
  recorder: this.options.recorder ?? NOOP_RECORDER }, [{ id: 'direct', run: async ({ signal, remainingMs }) => {
31
38
  signal.throwIfAborted();
@@ -35,7 +42,7 @@ export class BrtTracker {
35
42
  if (left <= 0)
36
43
  throw new BudgetExceededError('BRT', budgetMs);
37
44
  const { response, bytes } = await fetchBounded(url, { signal, headers: { 'User-Agent': userAgentOf(this.options.userAgent), ...(form ? { 'Content-Type': 'application/x-www-form-urlencoded' } : {}) },
38
- ...(form ? { method: 'POST', body: new URLSearchParams(form).toString() } : {}) }, { provider: 'BRT', timeoutMs: Math.max(1, Math.floor(left)), maxBytes: 1_000_000,
45
+ ...(form ? { method: 'POST', body: new URLSearchParams(form).toString() } : {}) }, { provider: 'BRT', timeoutMs: Math.max(1, Math.floor(groupRoute ? Math.min(left, PAGE_BEFORE_GROUP_MS) : left)), maxBytes: 1_000_000,
39
46
  redirect: 'manual', allowHttpStatuses: [302, 404, 410], fetcher: this.options.fetcher });
40
47
  if (performance.now() >= deadline)
41
48
  throw new BudgetExceededError('BRT', budgetMs);
@@ -131,12 +138,13 @@ export class BrtTracker {
131
138
  },
132
139
  }, {
133
140
  id: 'group',
134
- // While BRT's tracker is down, for maintenance or behind its gateway, the DPD group's guest service
135
- // reads a BRTcode DPD places in Italy, each milestone once and without places. Any other answer
141
+ // While BRT's tracker is down, for maintenance, behind its gateway or out of reach, the DPD group's guest
142
+ // service reads a BRTcode DPD places in Italy, each milestone once and without places. Any other answer
136
143
  // leaves the outage.
137
- enabled: number.length === 14 && Boolean(this.options.group),
144
+ enabled: groupRoute,
138
145
  recovers: (error) => error instanceof MaintenanceError
139
- || (error instanceof UpstreamHttpError && error.provider === 'BRT' && GATEWAY_FAILURES.has(error.status)),
146
+ || (error instanceof UpstreamHttpError && error.provider === 'BRT' && GATEWAY_FAILURES.has(error.status))
147
+ || (error instanceof UpstreamNetworkError && error.provider === 'BRT'),
140
148
  run: async ({ signal, remainingMs, previousError }) => {
141
149
  const answer = await this.options.group(number, { signal, budgetMs: remainingMs }).catch(() => {
142
150
  context.signal?.throwIfAborted();
@@ -4,7 +4,7 @@ export declare const DHLINK_MAX_BYTES: number;
4
4
  /**
5
5
  * DHLink's last-leg partners. The reply gives the last leg's number
6
6
  * (`lastTurnNo`) but names no partner, so the partner is read from the
7
- * number's whole layout. A number no layout fits gives no hand-off.
7
+ * number's whole layout, and its check digit where `valid` checks one. A number no layout fits gives no hand-off.
8
8
  * `beijingClock` marks a partner whose scans DHLink relays on its own
9
9
  * Beijing clock rather than the scan's, and `hubClockPickup` one whose pickup
10
10
  * DHLink's node copies from the partner's first scan, on its hub's clock.
@@ -14,6 +14,7 @@ export declare const DHLINK_MAX_BYTES: number;
14
14
  export declare const DHLINK_LAST_LEGS: readonly {
15
15
  readonly carrier: string;
16
16
  readonly number: RegExp;
17
+ readonly valid?: (number: string) => boolean;
17
18
  readonly beijingClock?: true;
18
19
  readonly hubClockPickup?: true;
19
20
  readonly scanZone?: (place: string, description: string) => string | null;
@@ -1,5 +1,5 @@
1
1
  import { DateTime, FixedOffsetZone } from 'luxon';
2
- import { normalizeTrackingNumber } from '../../core/detection/index.js';
2
+ import { isValidUspsPackageBarcode, normalizeTrackingNumber } from '../../core/detection/index.js';
3
3
  import { IndeterminateError, InvalidInputError, NoHistoryError, NotFoundError, SchemaError } from '../../core/errors/index.js';
4
4
  import { uspsRoundDelivery } from '../../core/result/round.js';
5
5
  import { languageStageStatus } from '../../core/status/index.js';
@@ -59,7 +59,7 @@ const CONTACT = /(?:投递员|快递员|派送员|联系电话|电话[::]|手
59
59
  /**
60
60
  * DHLink's last-leg partners. The reply gives the last leg's number
61
61
  * (`lastTurnNo`) but names no partner, so the partner is read from the
62
- * number's whole layout. A number no layout fits gives no hand-off.
62
+ * number's whole layout, and its check digit where `valid` checks one. A number no layout fits gives no hand-off.
63
63
  * `beijingClock` marks a partner whose scans DHLink relays on its own
64
64
  * Beijing clock rather than the scan's, and `hubClockPickup` one whose pickup
65
65
  * DHLink's node copies from the partner's first scan, on its hub's clock.
@@ -79,6 +79,8 @@ export const DHLINK_LAST_LEGS = [
79
79
  scanZone: (place, description) => gofoScanZone(place.split(',')[0] ?? '', description) },
80
80
  // DPD Switzerland's parcel numbers: fourteen digits from its depots 0600 to 0619.
81
81
  { carrier: 'dpd', number: /^06[01]\d{11}$/ },
82
+ // USPS's package barcodes (IMpb) with their check digit, as LiBaoTongXu's US line gives the last leg.
83
+ { carrier: 'usps', number: /^(?:9[1-5]\d{20}|9[2-4]\d{24})$/, valid: isValidUspsPackageBarcode },
82
84
  ];
83
85
  /** A number DHLink's tracker can be asked for; anything else is not sent. */
84
86
  export function normalizeDhlinkNumber(raw) {
@@ -240,7 +242,7 @@ function roundDelivery(event) {
240
242
  }
241
243
  /** The partner whose layout the whole number has. */
242
244
  function legOf(number) {
243
- const leg = number ? DHLINK_LAST_LEGS.find((candidate) => candidate.number.test(number)) : undefined;
245
+ const leg = number ? DHLINK_LAST_LEGS.find((candidate) => candidate.number.test(number) && (candidate.valid?.(number) ?? true)) : undefined;
244
246
  return leg ? { leg, number } : null;
245
247
  }
246
248
  /** The last leg, when its number's whole layout is one the table maps. */
@@ -3,6 +3,13 @@ export declare const PROVIDER = "Muser International Logistics";
3
3
  export declare const MUSER_MAX_BYTES: number;
4
4
  /** A Muser parcel number; anything else is not one its tracker is asked about. */
5
5
  export declare function normalizeMuserNumber(raw: string): string;
6
+ /** The wording of a delivering network's scan and the town and ZIP Code that follow it past a run of spaces. */
7
+ export declare function muserTrailingPlace(text: string): {
8
+ wording: string;
9
+ place: string;
10
+ } | null;
11
+ /** That town as the place, in the ZIP Code's state when the parcel goes to the United States, without the ZIP Code. */
12
+ export declare function muserTown(place: string, country: string | null): string;
6
13
  /**
7
14
  * The reply of the tracker's `Service.ashx` lookup for one number: `data`
8
15
  * holds an entry per number, with the scans newest first, each a wall clock,
@@ -21,21 +21,30 @@ export function normalizeMuserNumber(raw) {
21
21
  throw new InvalidInputError(PROVIDER, 'Muser parcel numbers are MS, fourteen digits and YD');
22
22
  return number;
23
23
  }
24
- /** A delivering network's scan with its town as the place, in its state when the parcel goes to the United States. */
24
+ /** The wording of a delivering network's scan and the town and ZIP Code that follow it past a run of spaces. */
25
+ export function muserTrailingPlace(text) {
26
+ const split = TRAILING_PLACE.exec(text.trim());
27
+ return split ? { wording: split[1], place: split[2] } : null;
28
+ }
29
+ /** That town as the place, in the ZIP Code's state when the parcel goes to the United States, without the ZIP Code. */
30
+ export function muserTown(place, country) {
31
+ const town = country === 'US' ? TOWN_ZIP.exec(place) : null;
32
+ const state = town ? usZipState(town[2]) : null;
33
+ return state ? `${town[1]}, ${state}` : place;
34
+ }
35
+ /** A delivering network's scan with its town as the place. */
25
36
  function placedScan(row, country) {
26
37
  if (!isRecord(row) || rtb56Text(row, 'track_location', PROVIDER, 120))
27
38
  return row;
28
- const text = (key) => typeof row[key] === 'string' ? row[key].trim() : '';
29
- const place = (TRAILING_PLACE.exec(text('track_description_en')) ?? TRAILING_PLACE.exec(text('track_description')))?.[2];
39
+ const text = (key) => typeof row[key] === 'string' ? row[key] : '';
40
+ const place = (muserTrailingPlace(text('track_description_en')) ?? muserTrailingPlace(text('track_description')))?.place;
30
41
  if (!place)
31
42
  return row;
32
43
  const wording = (key) => {
33
- const own = TRAILING_PLACE.exec(text(key));
34
- return own?.[2] === place ? own[1] : row[key];
44
+ const own = muserTrailingPlace(text(key));
45
+ return own?.place === place ? own.wording : row[key];
35
46
  };
36
- const town = country === 'US' ? TOWN_ZIP.exec(place) : null;
37
- const state = town ? usZipState(town[2]) : null;
38
- return { ...row, track_location: state ? `${town[1]}, ${state}` : place,
47
+ return { ...row, track_location: muserTown(place, country),
39
48
  track_description_en: wording('track_description_en'), track_description: wording('track_description') };
40
49
  }
41
50
  /**
@@ -3,3 +3,9 @@
3
3
  * its other scans locally (adapter.ts). Universal providers that copy them give their UTC digits.
4
4
  */
5
5
  export declare const POSTNL_CUSTOMS_STAMP: RegExp;
6
+ /**
7
+ * PostNL's acceptance and bagging stamps. Its own feed dates them as UTC instants to the fraction of a second when its
8
+ * acceptance centre stamps them, and to the minute on the local clock otherwise. Universal providers drop the fraction
9
+ * and keep the seconds, so a copy with seconds has the UTC digits.
10
+ */
11
+ export declare const POSTNL_ACCEPTANCE_STAMP: RegExp;
@@ -3,3 +3,9 @@
3
3
  * its other scans locally (adapter.ts). Universal providers that copy them give their UTC digits.
4
4
  */
5
5
  export const POSTNL_CUSTOMS_STAMP = /^(?:pre-declaration of the item has been received|item is cleared|duties and taxes confirmed) by customs$/i;
6
+ /**
7
+ * PostNL's acceptance and bagging stamps. Its own feed dates them as UTC instants to the fraction of a second when its
8
+ * acceptance centre stamps them, and to the minute on the local clock otherwise. Universal providers drop the fraction
9
+ * and keep the seconds, so a copy with seconds has the UTC digits.
10
+ */
11
+ export const POSTNL_ACCEPTANCE_STAMP = /^(?:consignment received at the postnl acceptance centre|item is nested to commercial bag|item is being processed)$/i;
@@ -25,7 +25,8 @@ import { countryName, militaryPostOffice } from '../../places/trackingLocation.j
25
25
  import { countryZones, hasSeveralClocks, keepsZone, mainZone } from '../../places/zones.js';
26
26
  import { captureFailure, capturedBodies, loadCapture } from '../shared/capture.js';
27
27
  import { CAINIAO_CHINA_LEG, CAINIAO_CHINA_ZONE } from '../../carriers/aliexpress/clock.js';
28
- import { POSTNL_CUSTOMS_STAMP } from '../../carriers/spring-gds/clock.js';
28
+ import { POSTNL_ACCEPTANCE_STAMP, POSTNL_CUSTOMS_STAMP } from '../../carriers/spring-gds/clock.js';
29
+ import { muserTown, muserTrailingPlace } from '../../carriers/muser/parser.js';
29
30
  import { chinaPostEnglish, chinaPostLabelPlace } from '../../carriers/china-post/status.js';
30
31
  import { correosDeMexicoForeignClock } from '../../carriers/correos-de-mexico/clock.js';
31
32
  import { correosOriginZone } from '../../carriers/correos-spain/clock.js';
@@ -1474,6 +1475,11 @@ function carrierClock(payload, state, number, status = '', destination = null) {
1474
1475
  // read on Dutch time, the clearance came an hour before Cainiao's copy of it, stated +01:00.
1475
1476
  if (carrier === 'spring-gds' && POSTNL_CUSTOMS_STAMP.test(status.trim()))
1476
1477
  return null;
1478
+ // And so do its acceptance and bagging stamps that keep their seconds: read on Dutch time, they came an hour
1479
+ // before PostNL's own UTC stamps of them. Those dated to the minute are on the local clock.
1480
+ if (carrier === 'spring-gds' && POSTNL_ACCEPTANCE_STAMP.test(status.trim())
1481
+ && /T\d{2}:\d{2}:(?!00)\d{2}/.test(typeof state.date === 'string' ? state.date : ''))
1482
+ return null;
1477
1483
  const postnlPlace = carrier === 'spring-gds' ? lastPlace(scanLocation(name, state.location)) : undefined;
1478
1484
  const postnlCountry = countryCode(postnlPlace);
1479
1485
  if (postnlCountry === 'GB')
@@ -1514,6 +1520,8 @@ function carrierClock(payload, state, number, status = '', destination = null) {
1514
1520
  return SWIFTX_LABEL_CLOCK;
1515
1521
  if (carrier === 'swiftx' && swiftxSiteZone(payload, state, scanLocation(name, state.location)))
1516
1522
  return undefined;
1523
+ if (carrier === 'muser' && muserTownZone(scanLocation(name, state.location), destination))
1524
+ return undefined;
1517
1525
  if (ROYAL_MAIL_NAMES.has(key) && royalMailRelay(scanLocation(name, state.location), status, destination))
1518
1526
  return royalMailRelayClock(mislabeledWallTime(state.date) ?? '');
1519
1527
  if (key === '1st') {
@@ -1611,6 +1619,27 @@ const POSTAL_OFFICE = /^([A-Z]{2})[A-Z]{3}[A-Z0-9]$/;
1611
1619
  function destinationOffice(name, location, destination) {
1612
1620
  return POSTAL_FEEDS.has(nameKey(name)) && destination !== null && POSTAL_OFFICE.exec(location)?.[1] === destination;
1613
1621
  }
1622
+ /**
1623
+ * Muser's copy of the delivering network's scan, placed as Muser's own tracker places it (carriers/muser): ParcelsApp
1624
+ * keeps the town and ZIP Code that follow the wording past a run of spaces, which become the place, in the ZIP Code's
1625
+ * state on a parcel to the US.
1626
+ */
1627
+ function muserPlacedRow(payload, raw, destination) {
1628
+ const name = stateCarrierName(payload, raw);
1629
+ if (typeof name !== 'string' || carrierIdFromName(name) !== 'muser' || scanLocation(name, raw.location))
1630
+ return raw;
1631
+ const placed = muserTrailingPlace(typeof raw.status === 'string' ? raw.status : '');
1632
+ return placed ? { ...raw, status: placed.wording, location: muserTown(placed.place, destination) } : raw;
1633
+ }
1634
+ /**
1635
+ * That scan's town clock in the US. Muser's tracker states China's offset on it, at the town's wall clock, and
1636
+ * ParcelsApp has those digits: read on Muser's Chinese clock, a delivery round went out thirteen hours before
1637
+ * Muser's own row of it.
1638
+ */
1639
+ function muserTownZone(location, destination) {
1640
+ const town = destination === 'US' ? /^(.+), ([A-Z]{2})$/.exec(location) : null;
1641
+ return town ? splitRegionTownZone('US', town[2], town[1]) ?? usStateTimeZone(town[2]) : null;
1642
+ }
1614
1643
  /**
1615
1644
  * The zone a scan's place gives it: null for a wall clock no rule can place (a DHL
1616
1645
  * Express facility the rule cannot place, the US post's copy of a scan in Russia at a
@@ -1630,6 +1659,9 @@ function siteZone(payload, state, number, inNorthAmerica = false, status = '', d
1630
1659
  return cttZone(payload, location, state.date, number, destination);
1631
1660
  if (carrier === 'swiftx')
1632
1661
  return swiftxSiteZone(payload, state, location) ?? undefined;
1662
+ const muser = carrier === 'muser' ? muserTownZone(location, destination) : null;
1663
+ if (muser)
1664
+ return muser;
1633
1665
  const relayed = carrier === 'dhlink' && swiftxRelayed(number, destination) ? usStateClock(location) : null;
1634
1666
  if (relayed)
1635
1667
  return relayed;
@@ -2479,11 +2511,12 @@ function parseHistory(payload, trackingNumber, timezone = null, readAt = Date.no
2479
2511
  || (kinds.includes('region') && ((!kinds.includes('abroad') && !boundElsewhere) || destination === 'US' || destination === 'CA'));
2480
2512
  const entries = [];
2481
2513
  const placeholders = placeholderDates(payload.states.flatMap((raw) => isRecord(raw) && !raw.require_fields && !raw.error ? [raw.date] : []));
2482
- for (const raw of payload.states) {
2483
- if (!isRecord(raw))
2514
+ for (const row of payload.states) {
2515
+ if (!isRecord(row))
2484
2516
  throw new SchemaError(SOURCE, 'ParcelsApp returned an invalid event');
2485
- if (raw.require_fields || raw.error)
2517
+ if (row.require_fields || row.error)
2486
2518
  continue;
2519
+ const raw = muserPlacedRow(payload, row, destination);
2487
2520
  // A state can come without a date (an Asendia Spain leg), or with a
2488
2521
  // placeholder for one. It has no place among the dated scans, so it is
2489
2522
  // counted instead of read as the latest.
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.1.0",
3
3
  "info": {
4
4
  "title": "Universal Parcel Scraper",
5
- "version": "0.1281.2-main.8521"
5
+ "version": "0.1281.5-main.8527"
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.1281.2-main.8521",
3
+ "version": "0.1281.5-main.8527",
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",