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.

479 lines (477 loc) • 23.3 kB
import { Temporal } from "./temporal.js"; import { MAX_EPOCH_NANOSECONDS } from "./epochNanoseconds.js"; import { isCalendarArithmeticCompatNeeded, isDayRoundClampCompatNeeded, isTransitionSearchCompatNeeded } from "./temporalCompat/capabilities.js"; import { stringOptionOrDefault } from "./typedOptions.js"; import { durationFrom } from "./durationFrom.js"; import { calendarDateAdd } from "./temporalCompat/calendarDateArithmetic.js"; import { MAX_TRANSITIONS_BEFORE_MAXIMUM, NEXT_TRANSITION_HORIZON_NANOSECONDS, epochNanosecondsFor, interpretISODateTimeOffset, isNamedTimeZone, isNearRangeEdge, isValidEpoch, missedNextTransition, missedPreviousTransition, needsOwnDayBoundsSearch, needsOwnStartOfDaySearch, startOfDayEpochNanoseconds, timeZoneIdOf } from "./zonedWallClock.js"; import { nextTransitionAfter, previousTransitionBefore } from "./zonedTransitionSearch.js"; // src/internal/zonedWallClockOperations.ts const NANOSECONDS_PER_HOUR = 36e11; const DISAMBIGUATION_PROBE = new Temporal.PlainDateTime(2e3, 1, 1); /** An ISO date far from the limits, used only to validate an `overflow` option. */ const OVERFLOW_PROBE = new Temporal.PlainDate(2e3, 1, 1); /** Re-throws `error` unless `recover` computes a TC39 result (it returns null when out of scope). */ function recoverAtRangeEdge(error, recover) { const recovered = recover(); if (recovered === null) throw error; return recovered; } function isAtRangeEdge(timeZone, date) { return isNamedTimeZone(timeZone) && isNearRangeEdge(date); } /** * True when the polyfill's `GetStartOfDay` may return a valid-looking wrong value for this date (or * this zoned value's date): a transition skipping its midnight lies before the polyfill's * 1847-01-01 transition search floor (defect 3), or the polyfill's search can skip or stall on two * changes in one step (defect 5, while the D13 probe fails). */ function needsOwnStartOfDay(timeZone, value) { return isNamedTimeZone(timeZone) && needsOwnStartOfDaySearch(timeZone, value); } /** `needsOwnStartOfDay` for a measure that also reads the next day's start. */ function needsOwnDayBounds(zoned) { return isNamedTimeZone(zoned.timeZoneId) && needsOwnDayBoundsSearch(zoned.timeZoneId, zoned); } function inZoneOf(epochNanoseconds, zoned) { return new Temporal.ZonedDateTime(epochNanoseconds, zoned.timeZoneId, zoned.calendarId); } function plainToZonedAtEdge(plain, timeZoneLike, disambiguation) { let timeZone; try { timeZone = timeZoneIdOf(timeZoneLike); DISAMBIGUATION_PROBE.toZonedDateTime("UTC", { disambiguation }); } catch { return null; } const isDate = plain instanceof Temporal.PlainDate; const date = isDate ? plain : plain.toPlainDate(); if (!isAtRangeEdge(timeZone, date)) return null; if (isDate) return plainDateFromOwnStartOfDay(plain, timeZone); return new Temporal.ZonedDateTime(epochNanosecondsFor(timeZone, plain, disambiguation ?? "compatible"), timeZone, plain.calendarId); } function plainDateFromOwnStartOfDay(date, timeZone) { return new Temporal.ZonedDateTime(startOfDayEpochNanoseconds(timeZone, date), timeZone, date.calendarId); } /** A PlainDate's start of day before the polyfill's transition search floor, or null. */ function plainDateBeforeTransitionSearch(date, timeZoneLike) { let timeZone; try { timeZone = timeZoneIdOf(timeZoneLike); } catch { return null; } return needsOwnStartOfDay(timeZone, date) ? plainDateFromOwnStartOfDay(date, timeZone) : null; } /** * `PlainDate#toZonedDateTime(timeZone)` (start of day) or * `PlainDateTime#toZonedDateTime(timeZone, { disambiguation })`, correct at the range limits and * (start of day) before 1847. * * @param plain the date (resolved to its start of day) or date-time to place in `timeZone` * @param timeZone IANA identifier, offset time zone, or RFC 9557 string carrying one * @param disambiguation Temporal disambiguation for a PlainDateTime (ignored for a PlainDate) * @returns the resolved Temporal.ZonedDateTime; throws where TC39 Temporal throws */ function plainToZoned(plain, timeZone, disambiguation) { if (plain instanceof Temporal.PlainDate) { const own = plainDateBeforeTransitionSearch(plain, timeZone); if (own !== null) return own; } try { return plain instanceof Temporal.PlainDate ? plain.toZonedDateTime(timeZone) : plain.toZonedDateTime(timeZone, { disambiguation }); } catch (error) { return recoverAtRangeEdge(error, () => plainToZonedAtEdge(plain, timeZone, disambiguation)); } } function startOfDayFromOwn(zoned) { return inZoneOf(startOfDayEpochNanoseconds(zoned.timeZoneId, zoned.toPlainDate()), zoned); } function startOfDayAtEdge(zoned) { return isAtRangeEdge(zoned.timeZoneId, zoned.toPlainDate()) ? startOfDayFromOwn(zoned) : null; } /** * `ZonedDateTime#startOfDay`, correct at the range limits and before 1847. * * @param zoned the value whose local day to start * @returns the first valid wall-clock time of that day; throws where TC39 Temporal throws */ function zonedStartOfDay(zoned) { if (needsOwnStartOfDay(zoned.timeZoneId, zoned)) return startOfDayFromOwn(zoned); try { return zoned.startOfDay(); } catch (error) { return recoverAtRangeEdge(error, () => startOfDayAtEdge(zoned)); } } function withPlainTimeAtEdge(zoned, time) { if (time === void 0) return startOfDayAtEdge(zoned); const date = zoned.toPlainDate(); let wall; try { wall = date.toPlainDateTime(Temporal.PlainTime.from(time)); } catch { return null; } if (!isAtRangeEdge(zoned.timeZoneId, date)) return null; return inZoneOf(epochNanosecondsFor(zoned.timeZoneId, wall, "compatible"), zoned); } /** * `ZonedDateTime#withPlainTime`, correct at the range limits and (start of day) before 1847. * * @param zoned the value whose local date to keep * @param time the new wall-clock time; omitted means the start of the day * @returns the resolved Temporal.ZonedDateTime; throws where TC39 Temporal throws */ function zonedWithPlainTime(zoned, time) { if (time === void 0 && needsOwnStartOfDay(zoned.timeZoneId, zoned)) return startOfDayFromOwn(zoned); try { return zoned.withPlainTime(time); } catch (error) { return recoverAtRangeEdge(error, () => withPlainTimeAtEdge(zoned, time)); } } function hoursInDayAtEdge(zoned) { return isAtRangeEdge(zoned.timeZoneId, zoned.toPlainDate()) ? hoursInDayFromOwnStartOfDay(zoned) : null; } function hoursInDayFromOwnStartOfDay(zoned) { const date = zoned.toPlainDate(); const start = startOfDayEpochNanoseconds(zoned.timeZoneId, date); const end = startOfDayEpochNanoseconds(zoned.timeZoneId, date.add({ days: 1 })); return Number(end - start) / NANOSECONDS_PER_HOUR; } /** * `ZonedDateTime#hoursInDay`, correct at the range limits and before 1847. * * @param zoned the value whose local day to measure * @returns hours from this day's start to the next day's start; throws where TC39 Temporal throws */ function zonedHoursInDay(zoned) { if (needsOwnDayBounds(zoned)) return hoursInDayFromOwnStartOfDay(zoned); try { return zoned.hoursInDay; } catch (error) { return recoverAtRangeEdge(error, () => hoursInDayAtEdge(zoned)); } } /** The earliest transition after `zoned`, found by walking back from the maximum instant. */ function earliestTransitionBeforeMaximum(zoned) { if (zoned.epochNanoseconds >= 8640000000000000000000n) return null; const maximum = inZoneOf(MAX_EPOCH_NANOSECONDS, zoned); let earliest = inZoneOf(8640000000000000000000n - 1n, zoned).offsetNanoseconds === maximum.offsetNanoseconds ? null : maximum; let cursor = maximum.getTimeZoneTransition("previous"); for (let step = 0; cursor !== null && cursor.epochNanoseconds > zoned.epochNanoseconds; step++) { if (step >= 64) throw new RangeError(`Too many transitions in ${zoned.timeZoneId} before the maximum instant`); earliest = cursor; cursor = cursor.getTimeZoneTransition("previous"); } return earliest; } /** `transition` unless it is null or lies outside the caller's limit. */ function withinLimit(transition, isInside) { return transition !== null && isInside(transition.epochNanoseconds) ? transition : null; } function polyfillNextTransition(zoned) { if (isNamedTimeZone(zoned.timeZoneId)) { const missed = missedNextTransition(zoned.timeZoneId, zoned.epochNanoseconds); if (missed !== null) return inZoneOf(missed, zoned); } const next = zoned.getTimeZoneTransition("next"); if (next !== null || !isNamedTimeZone(zoned.timeZoneId) || 8640000000000000000000n - zoned.epochNanoseconds > NEXT_TRANSITION_HORIZON_NANOSECONDS) return next; return earliestTransitionBeforeMaximum(zoned); } /** * `ZonedDateTime#getTimeZoneTransition("next")`: TC39 `GetNamedTimeZoneNextTransition`, the first * offset change strictly after `zoned`. * * - While the D13 probe fails (two changes inside one of the polyfill's 14-day search steps are * skipped, or stall it for ever), a named zone is searched by GMT's own bounded search * (`zonedTransitionSearch.ts`) and the polyfill's search is never called. * - Otherwise the polyfill answers, corrected before 1847 (defect 3: it never searches there, so * the change is found by bisection first) and within its three-year horizon of the maximum * instant (defect 2: its forward scan gives up once a step would pass the maximum, so a `null` * is re-checked by walking back from the maximum). * * @param zoned the instant to search after (exclusive) * @param until optional: the last instant to search, in epoch nanoseconds (inclusive). A caller * that needs only changes up to there passes it so the search reads no further * @returns the next transition, or null when there is none up to `until` or, without it, none * that Temporal reports */ function zonedNextTransition(zoned, until) { if (isNamedTimeZone(zoned.timeZoneId) && isTransitionSearchCompatNeeded()) { const found = nextTransitionAfter(zoned.timeZoneId, zoned.epochNanoseconds, until); return found === null ? null : inZoneOf(found, zoned); } const next = polyfillNextTransition(zoned); return until === void 0 ? next : withinLimit(next, (epochNanoseconds) => epochNanoseconds <= until); } function polyfillPreviousTransition(zoned) { const previous = zoned.getTimeZoneTransition("previous"); if (previous !== null || !isNamedTimeZone(zoned.timeZoneId)) return previous; const missed = missedPreviousTransition(zoned.timeZoneId, zoned.epochNanoseconds); return missed === null ? null : inZoneOf(missed, zoned); } /** * `ZonedDateTime#getTimeZoneTransition("previous")`: TC39 `GetNamedTimeZonePreviousTransition`, * the last offset change strictly before `zoned`. * * - While the D13 probe fails, a named zone is searched by GMT's own bounded search and the * polyfill's search is never called (see `zonedNextTransition`). * - Otherwise the polyfill answers, corrected before 1847 (defect 3): when it finds nothing in a * named zone, the span from the minimum instant to its floor is checked by comparing offsets * and bisecting. * * @param zoned the instant to search before (exclusive) * @param since optional: where the search stops, in epoch nanoseconds (exclusive). A caller that * needs only changes after there passes it so the search reads no further back * @returns the previous transition, or null when there is none after `since` or, without it, none */ function zonedPreviousTransition(zoned, since) { if (isNamedTimeZone(zoned.timeZoneId) && isTransitionSearchCompatNeeded()) { const found = previousTransitionBefore(zoned.timeZoneId, zoned.epochNanoseconds, since); return found === null ? null : inZoneOf(found, zoned); } const previous = polyfillPreviousTransition(zoned); return since === void 0 ? previous : withinLimit(previous, (epochNanoseconds) => epochNanoseconds > since); } function hasDateUnits(duration) { return duration.years !== 0 || duration.months !== 0 || duration.weeks !== 0 || duration.days !== 0; } function timeUnitsNanoseconds(duration) { return BigInt(duration.hours) * 3600000000000n + BigInt(duration.minutes) * 60000000000n + BigInt(duration.seconds) * 1000000000n + BigInt(duration.milliseconds) * 1000000n + BigInt(duration.microseconds) * 1000n + BigInt(duration.nanoseconds); } /** TC39 `AddZonedDateTime` for a duration with calendar units, at the range limits. */ function addAtEdge(zoned, durationLike, overflow, sign) { let duration; let wall; try { const parsed = durationFrom(durationLike); duration = sign === 1 ? parsed : parsed.negated(); const start = zoned.toPlainDateTime(); const { years, months, weeks, days } = duration; wall = calendarDateAdd(start.toPlainDate(), { years, months, weeks, days }, overflow === void 0 ? "constrain" : overflow).toPlainDateTime(start.toPlainTime()); } catch { return null; } if (!hasDateUnits(duration) || !isAtRangeEdge(zoned.timeZoneId, wall.toPlainDate())) return null; const result = epochNanosecondsFor(zoned.timeZoneId, wall, "compatible") + timeUnitsNanoseconds(duration); if (!isValidEpoch(result)) throw new RangeError(`${zoned.toString()} + ${duration.toString()} is outside the supported range`); return inZoneOf(result, zoned); } /** * TC39 §6.5.5 `AddZonedDateTime` for a signed duration with calendar units: `CalendarDateAdd` runs * in `calendarDateAdd` (the Temporal compat layer, CORE-6 S5); the intermediate wall clock (added * date, original time) resolves with `GetEpochNanosecondsFor(timeZone, dateTime, disambiguation)` * through GMT's own `plainToZoned`, so a gap or an overlap landing honours `disambiguation`; the * time units are then added in exact time and never re-resolved. */ function addDateThenTime(zoned, duration, overflow, disambiguation) { OVERFLOW_PROBE.add({ days: 0 }, { overflow }); const wall = zoned.toPlainDateTime(); const { years, months, weeks, days } = duration; const result = plainToZoned(calendarDateAdd(wall.toPlainDate(), { years, months, weeks, days }, overflow === void 0 ? "constrain" : overflow).toPlainDateTime(wall.toPlainTime()), zoned.timeZoneId, disambiguation).epochNanoseconds + timeUnitsNanoseconds(duration); if (!isValidEpoch(result)) throw new RangeError(`${zoned.toString()} + ${duration.toString()} is outside the supported range`); return inZoneOf(result, zoned); } /** * `AddZonedDateTime` through the Temporal compat layer, or null when `zoned`'s calendar needs no * compat or the duration has no calendar units. */ function addWithCalendarCompat(zoned, durationLike, overflow, sign) { if (!isCalendarArithmeticCompatNeeded(zoned.calendarId)) return null; const parsed = durationFrom(durationLike); const duration = sign === 1 ? parsed : parsed.negated(); if (!hasDateUnits(duration)) return null; return addDateThenTime(zoned, duration, overflow, "compatible"); } /** * `ZonedDateTime#add`, correct at the range limits and in calendars the polyfill gets wrong. * * @param zoned the starting value * @param duration the duration to add * @param options Temporal `overflow` for the calendar part * @returns the sum; throws where TC39 Temporal throws */ function addToZoned(zoned, duration, options) { const viaCompat = addWithCalendarCompat(zoned, duration, options?.overflow, 1); if (viaCompat !== null) return viaCompat; try { return zoned.add(duration, options); } catch (error) { return recoverAtRangeEdge(error, () => addAtEdge(zoned, duration, options?.overflow, 1)); } } /** * `ZonedDateTime#subtract`, correct at the range limits. * * @param zoned the starting value * @param duration the duration to subtract * @param options Temporal `overflow` for the calendar part * @returns the difference; throws where TC39 Temporal throws */ function subtractFromZoned(zoned, duration, options) { const viaCompat = addWithCalendarCompat(zoned, duration, options?.overflow, -1); if (viaCompat !== null) return viaCompat; try { return zoned.subtract(duration, options); } catch (error) { return recoverAtRangeEdge(error, () => addAtEdge(zoned, duration, options?.overflow, -1)); } } /** * `addToZoned` / `subtractFromZoned` with a caller-chosen `disambiguation` for the intermediate * wall-clock date-time — TC39 Temporal §6.5.5 AddZonedDateTime with the "compatible" argument of * its `GetEpochNanosecondsFor` step replaced by `disambiguation`. * * - The date portion (years, months, weeks, days) is added to the wall-clock date, keeping the * wall-clock time. That intermediate date-time is resolved with `disambiguation` whenever it is * not a single instant: in a fall-back overlap "earlier"/"compatible" take the earlier instant and * "later" the later one; in a spring-forward gap "earlier" shifts it back by the gap length and * "later"/"compatible" forward (DisambiguatePossibleEpochNanoseconds); "reject" throws for both. * - The time portion is then added in exact time and is never re-resolved. * - With no date portion, the whole duration is exact time and `disambiguation` never applies. * - Each option is converted to a string once, as Temporal GetOption converts it. * * @param zoned the starting value * @param duration the duration to add or subtract * @param sign 1 to add, -1 to subtract * @param options Temporal `overflow` for the calendar part and `disambiguation` * @returns the result; throws where TC39 Temporal throws, or when "reject" meets a gap or overlap */ function addToZonedDisambiguated(zoned, duration, sign, options) { const overflow = options.overflow === void 0 ? void 0 : `${options.overflow}`; const disambiguation = `${options.disambiguation}`; DISAMBIGUATION_PROBE.toZonedDateTime("UTC", { disambiguation }); const parsed = durationFrom(duration); if (disambiguation === "compatible" || !hasDateUnits(parsed)) return (sign === 1 ? addToZoned : subtractFromZoned)(zoned, parsed, { overflow }); return addDateThenTime(zoned, sign === 1 ? parsed : parsed.negated(), overflow, disambiguation); } /** TC39 `ZonedDateTime#with` at the range limits. */ function withAtEdge(zoned, fields, options) { let wall; try { Temporal.ZonedDateTime.from(zoned, options); wall = zoned.toPlainDateTime().with(fields, { overflow: options?.overflow }); } catch { return null; } const offset = { nanoseconds: BigInt(zoned.offsetNanoseconds) }; if (!isAtRangeEdge(zoned.timeZoneId, wall.toPlainDate())) return null; return inZoneOf(interpretISODateTimeOffset(zoned.timeZoneId, wall, offset, stringOptionOrDefault(options?.disambiguation, "compatible"), stringOptionOrDefault(options?.offset, "prefer"), false), zoned); } /** * `ZonedDateTime#with`, correct at the range limits. * * @param zoned the value to change * @param fields the date and time fields to set * @param options Temporal `overflow` / `disambiguation` / `offset` (default `"prefer"`) * @returns the changed value; throws where TC39 Temporal throws */ function withZonedFields(zoned, fields, options) { try { return zoned.with(fields, options); } catch (error) { return recoverAtRangeEdge(error, () => withAtEdge(zoned, fields, options)); } } /** Rounding modes that never move a non-negative progress past the start of the day. */ const ROUNDS_TOWARD_START = /* @__PURE__ */ new Set(["floor", "trunc"]); /** Rounding modes that move any positive progress to the start of the next day. */ const ROUNDS_TOWARD_END = /* @__PURE__ */ new Set(["ceil", "expand"]); /** * Half modes that resolve an exact half upward. Half-floor, half-trunc and half-even (0 is the * even quotient) resolve it to the start. */ const HALF_ROUNDS_TOWARD_END = /* @__PURE__ */ new Set(["halfCeil", "halfExpand"]); /** TC39 `RoundTimeDurationToIncrement` for `0 <= progress < length`: either 0 or `length`. */ function roundDayProgress(progress, length, roundingMode) { if (progress === 0n || ROUNDS_TOWARD_START.has(roundingMode)) return 0n; if (ROUNDS_TOWARD_END.has(roundingMode)) return length; const twice = progress * 2n; if (twice === length) return HALF_ROUNDS_TOWARD_END.has(roundingMode) ? length : 0n; return twice < length ? 0n : length; } /** * TC39 `ZonedDateTime#round` with `smallestUnit: "day"`, from GMT's own `GetStartOfDay`: to the * start of this day or the next. */ function roundToDayFromOwnStartOfDay(zoned, date, roundingMode) { const start = startOfDayEpochNanoseconds(zoned.timeZoneId, date); const end = startOfDayEpochNanoseconds(zoned.timeZoneId, date.add({ days: 1 })); return inZoneOf(start + roundDayProgress((zoned.epochNanoseconds < end ? zoned.epochNanoseconds : end - 1n) - start, end - start, roundingMode), zoned); } function isDayUnit(unit) { return unit === "day" || unit === "days"; } function roundAtEdge(zoned, roundTo) { const date = zoned.toPlainDate(); let roundedWall; try { roundedWall = zoned.toPlainDateTime().round(roundTo); } catch { return null; } if (!isAtRangeEdge(zoned.timeZoneId, date)) return null; if (isDayUnit(roundTo.smallestUnit)) return roundToDayFromOwnStartOfDay(zoned, date, roundTo.roundingMode ?? "halfExpand"); return inZoneOf(interpretISODateTimeOffset(zoned.timeZoneId, roundedWall, { nanoseconds: BigInt(zoned.offsetNanoseconds) }, "compatible", "prefer", false), zoned); } /** * Convert `roundingIncrement` and `roundingMode` once, in the order `ZonedDateTime#round` reads them. * * - Temporal GetOption converts the value it reads: ToNumber for `roundingIncrement`, ToString for * `roundingMode`. The steps after this compare the mode with `===`, so a mode given as an object * (`new String("floor")`) must reach them as the plain string, or it falls through to another * mode's branch. * - The unary plus and the template literal are ToNumber and ToString exactly, so a symbol or a * bigint throws the TypeError Temporal throws. `undefined` stays `undefined` (the default). * - `smallestUnit` is left as it is: both callers pass a unit they have already checked is one of * the unit strings. * * @param options the caller's options, each member read once * @returns the same options, increment and mode as primitives */ function convertRoundTo(options) { const { roundingIncrement, roundingMode, smallestUnit } = options; const increment = roundingIncrement === void 0 ? void 0 : +roundingIncrement; const mode = roundingMode === void 0 ? void 0 : `${roundingMode}`; return { smallestUnit, ...increment === void 0 ? {} : { roundingIncrement: increment }, ...mode === void 0 ? {} : { roundingMode: mode } }; } /** * `ZonedDateTime#round`, correct at the range limits and, by day, before 1847. * * @param zoned the value to round * @param roundTo Temporal `smallestUnit` (day or smaller) / `roundingIncrement` / `roundingMode` * @returns the rounded value; throws where TC39 Temporal throws */ function roundZonedDateTime(zoned, options) { const roundTo = convertRoundTo(options); if (isDayUnit(roundTo.smallestUnit) && isNamedTimeZone(zoned.timeZoneId) && (isDayRoundClampCompatNeeded() || needsOwnDayBounds(zoned))) { zoned.toPlainDateTime().round(roundTo); try { return roundToDayFromOwnStartOfDay(zoned, zoned.toPlainDate(), roundTo.roundingMode ?? "halfExpand"); } catch (error) { if (!isAtRangeEdge(zoned.timeZoneId, zoned.toPlainDate())) throw error; } } try { return zoned.round(roundTo); } catch (error) { return recoverAtRangeEdge(error, () => roundAtEdge(zoned, roundTo)); } } export { addToZoned, addToZonedDisambiguated, plainToZoned, roundZonedDateTime, subtractFromZoned, withZonedFields, zonedHoursInDay, zonedNextTransition, zonedPreviousTransition, zonedStartOfDay, zonedWithPlainTime };