@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.
63 lines (61 loc) • 2.46 kB
JavaScript
import { isObject } from "./isObject.js";
import { parseInstantNanoseconds } from "./instantNanoseconds.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`/offset) or zoned strings, read as
* `parseInstantNanoseconds` reads them: the offset fixes the instant, a minute-rounded offset
* is read as its bracketed zone's real offset, and the bracket is otherwise not checked. 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 };