UNPKG

@northguild/gmt

Version:

Date and time library for JavaScript and TypeScript, built on TC39 Temporal: time zones, DST, business days, ISO 8601 strings in and out. Never throws.

62 lines (60 loc) • 2.41 kB
import { parseInstantNanoseconds } from "./instantNanoseconds.js"; import { isObject } from "./isObject.js"; // src/internal/timestampEvents.ts const TIMESTAMP_CLASSES = /* @__PURE__ */ new Set([ "PLN", "EST", "REQ", "ACT" ]); /** One event validated, or `null`. */ function parseEvent(event) { if (!isObject(event)) return null; const { classifier, at, recordedAt } = event; if (!TIMESTAMP_CLASSES.has(classifier) || typeof at !== "string") return null; const atNanoseconds = parseInstantNanoseconds(at); const recordedNanoseconds = parseInstantNanoseconds(recordedAt); if (atNanoseconds === null || recordedNanoseconds === null) return null; return { classifier, at, atNanoseconds, recordedNanoseconds }; } /** * Validate a list of `TimestampEvent`s and put them in recording order, or `null`. * * The shared reading behind `bestAvailable` and `estimateDrift`: * * - Every event must be an object whose `classifier` is exactly `PLN`, `EST`, `REQ` or `ACT` and * whose `at` and `recordedAt` are instants (`Z` or an offset) with no annotation, read as * `parseInstantNanoseconds` reads them: the offset fixes the instant, and a zoned string, a real * zone bracket included, is invalid. One invalid event makes the whole list invalid. * - The result is sorted by `recordedAt`, earliest first. Events recorded at the same instant * keep their input order, so of two ties the later index is the later record. * - `at` is kept exactly as written, so a caller can echo it. * - An empty list is `[]`; the caller decides what that means. * - A hostile value (a throwing getter, a revoked Proxy) is invalid input: `null`, never a throw. * * @param events candidate list of timestamp events * @returns the events in recording order with their instants, or null on invalid input * * @example parseTimestampEvents([]) // [] * @example parseTimestampEvents([{ classifier: "ETA", at: "2024-06-15T12:00:00Z", recordedAt: "2024-06-15T10:00:00Z" }]) // null */ function parseTimestampEvents(events) { try { if (!Array.isArray(events)) return null; const parsed = []; for (const event of events) { const one = parseEvent(event); if (one === null) return null; parsed.push(one); } return parsed.sort((a, b) => a.recordedNanoseconds < b.recordedNanoseconds ? -1 : a.recordedNanoseconds > b.recordedNanoseconds ? 1 : 0); } catch { return null; } } export { parseTimestampEvents };