Skip to content
← Public packages

@kentcdodds/quiet-hours

Quiet hours for Kent's bots: 10 PM to 8 AM MT (DST-aware) clock, shared overnight queue, override, and the 8 AM digest of finished work and open decisions.

FollowFork

Files

clock.ts

147 lines · 5.3 KB · TypeScript
/**
 * Pure, DST-aware quiet-hours clock math. Never uses a fixed UTC offset:
 * every conversion goes through `Intl.DateTimeFormat` with the IANA zone, so
 * the window follows MDT/MST automatically (e.g. the Nov 1, 2026 and
 * Mar 14, 2027 transitions in America/Denver).
 */

export const QUIET_TIME_ZONE = 'America/Denver'
/** Quiet starts at this local hour (10:00 PM). */
export const QUIET_START_HOUR = 22
/** Quiet ends at this local hour (8:00 AM). */
export const QUIET_END_HOUR = 8

export type WallTime = {
	year: number
	month: number
	day: number
	hour: number
	minute: number
	second: number
}

const formatters = new Map<string, Intl.DateTimeFormat>()

function formatterFor(timeZone: string) {
	let formatter = formatters.get(timeZone)
	if (!formatter) {
		formatter = new Intl.DateTimeFormat('en-US', {
			timeZone,
			hourCycle: 'h23',
			year: 'numeric',
			month: '2-digit',
			day: '2-digit',
			hour: '2-digit',
			minute: '2-digit',
			second: '2-digit',
		})
		formatters.set(timeZone, formatter)
	}
	return formatter
}

/** Wall-clock parts for an instant in `timeZone`. */
export function wallTime(instant: Date, timeZone = QUIET_TIME_ZONE): WallTime {
	const parts: Record<string, number> = {}
	for (const part of formatterFor(timeZone).formatToParts(instant)) {
		if (part.type !== 'literal') parts[part.type] = Number(part.value)
	}
	return {
		year: parts.year,
		month: parts.month,
		day: parts.day,
		hour: parts.hour === 24 ? 0 : parts.hour,
		minute: parts.minute,
		second: parts.second,
	}
}

/** Offset (ms) of `timeZone` from UTC at `instantMs`. Derived, never hard-coded. */
export function zoneOffsetMs(instantMs: number, timeZone = QUIET_TIME_ZONE): number {
	const w = wallTime(new Date(instantMs), timeZone)
	const asUtc = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, w.second)
	return asUtc - Math.floor(instantMs / 1000) * 1000
}

/**
 * The instant at which `timeZone` shows the given wall time. Handles DST:
 * a wall time inside a spring-forward gap resolves forward; one inside a
 * fall-back overlap resolves to the earlier instant.
 */
export function instantForWallTime(
	w: Pick<WallTime, 'year' | 'month' | 'day' | 'hour' | 'minute'>,
	timeZone = QUIET_TIME_ZONE,
): Date {
	const guess = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute, 0)
	const first = guess - zoneOffsetMs(guess, timeZone)
	const second = guess - zoneOffsetMs(first, timeZone)
	if (first === second) return new Date(first)
	// Offsets disagree: we are near a transition. Prefer the candidate whose
	// wall time matches; otherwise (gap) take the later instant.
	const candidates = [Math.min(first, second), Math.max(first, second)]
	for (const candidate of candidates) {
		const back = wallTime(new Date(candidate), timeZone)
		if (back.hour === w.hour && back.minute === w.minute && back.day === w.day) {
			return new Date(candidate)
		}
	}
	return new Date(Math.max(first, second))
}

/** Calendar date `days` after the given local date (pure calendar math). */
export function addLocalDays(
	date: Pick<WallTime, 'year' | 'month' | 'day'>,
	days: number,
): Pick<WallTime, 'year' | 'month' | 'day'> {
	const d = new Date(Date.UTC(date.year, date.month - 1, date.day + days))
	return { year: d.getUTCFullYear(), month: d.getUTCMonth() + 1, day: d.getUTCDate() }
}

/** `YYYY-MM-DD` local date for an instant. */
export function localDateKey(instant: Date, timeZone = QUIET_TIME_ZONE): string {
	const w = wallTime(instant, timeZone)
	return `${w.year}-${String(w.month).padStart(2, '0')}-${String(w.day).padStart(2, '0')}`
}

/** Next instant strictly after `now` whose local wall time is `hour:00`. */
export function nextLocalHour(now: Date, hour: number, timeZone = QUIET_TIME_ZONE): Date {
	const today = wallTime(now, timeZone)
	for (let offset = 0; offset <= 2; offset += 1) {
		const date = addLocalDays(today, offset)
		const candidate = instantForWallTime({ ...date, hour, minute: 0 }, timeZone)
		if (candidate.getTime() > now.getTime()) return candidate
	}
	throw new Error('unreachable: no local ' + hour + ':00 within two days')
}

/** Most recent instant at or before `now` whose local wall time is `hour:00`. */
export function previousLocalHour(now: Date, hour: number, timeZone = QUIET_TIME_ZONE): Date {
	const today = wallTime(now, timeZone)
	for (let offset = 0; offset >= -2; offset -= 1) {
		const date = addLocalDays(today, offset)
		const candidate = instantForWallTime({ ...date, hour, minute: 0 }, timeZone)
		if (candidate.getTime() <= now.getTime()) return candidate
	}
	throw new Error('unreachable: no local ' + hour + ':00 within two days')
}

/** True when local time is inside 10:00 PM (inclusive) to 8:00 AM (exclusive). */
export function isQuietByClock(now: Date, timeZone = QUIET_TIME_ZONE): boolean {
	const { hour } = wallTime(now, timeZone)
	return hour >= QUIET_START_HOUR || hour < QUIET_END_HOUR
}

export type ClockWindow = {
	quiet: boolean
	/** When the current state (quiet or not) ends, as an ISO instant. */
	until: string
}

/** Clock-only quiet state for `now` (every day, weekends included). */
export function clockWindow(now: Date, timeZone = QUIET_TIME_ZONE): ClockWindow {
	const quiet = isQuietByClock(now, timeZone)
	const until = quiet
		? nextLocalHour(now, QUIET_END_HOUR, timeZone)
		: nextLocalHour(now, QUIET_START_HOUR, timeZone)
	return { quiet, until: until.toISOString() }
}