// Server-side example. No third-party packages required. Never run API keys in a browser. import { pathToFileURL } from 'node:url'; export async function trackPackage(trackingNumber, { apiKey = process.env.RAPIDAPI_KEY, authorization = process.env.TRACKING_API_AUTHORIZATION, fetchImpl = globalThis.fetch, timeoutMs = 15000, } = {}) { if (typeof trackingNumber !== 'string' || !trackingNumber.trim()) throw new Error('A tracking number string is required.'); if (typeof apiKey !== 'string' || !apiKey.trim()) throw new Error('RAPIDAPI_KEY is required.'); if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new Error('A positive timeout is required.'); const url = new URL('https://trackingpackage.p.rapidapi.com/TrackingPackage'); url.searchParams.set('trackingNumber', trackingNumber.trim()); const headers = { 'X-RapidAPI-Key': apiKey, 'X-RapidAPI-Host': url.hostname, Accept: 'application/json' }; if (authorization) headers.Authorization = authorization; let response; try { response = await fetchImpl(url, { headers, signal: AbortSignal.timeout(timeoutMs), redirect: 'error' }); } catch { throw new Error('Tracking request timed out or failed at the network layer.'); } if (!response.ok) { // Do not print an error body: it can contain credentials or shipment data. const error = new Error(`Tracking request failed (HTTP ${response.status}).`); error.status = response.status; error.retryAfter = response.headers.get('retry-after'); throw error; } if (!/\bapplication\/(?:[\w.-]+\+)?json\b/i.test(response.headers.get('content-type') || '')) throw new Error('Expected a JSON tracking response.'); let data; try { data = await response.json(); } catch { throw new Error('Invalid JSON tracking response.'); } if (!data || typeof data !== 'object' || Array.isArray(data) || typeof data.TrackingNumber !== 'string' || typeof data.Status !== 'string' || typeof data.Delivered !== 'boolean') throw new Error('Unexpected tracking response shape.'); if (data.TrackingDetails != null && !Array.isArray(data.TrackingDetails)) throw new Error('Unexpected tracking event list.'); return data; } if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { try { await trackPackage(process.env.TRACKING_NUMBER); console.log('Tracking response received and validated.'); } catch (error) { console.error(error.message); process.exitCode = 1; } }