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.

1,411 lines • 53.6 kB
import { Temporal } from "./temporal.js";
import { MIN_EPOCH_NANOSECONDS } from "./epochNanoseconds.js";
import { isObject } from "./isObject.js";
import { zoneFrame } from "./zoneFrame.js";
import { formatHourDuration } from "./hourDurationString.js";
import { parseScheduleDisambiguation } from "./operatingSchedule.js";
import { WallClockRejected, calendarScale, datePlusDays, localDateOf, operatorDayScale, parseDayStartTime, periodAfter, periodsEndingAt, resolveWallClock } from "./dutyPeriods.js";
import { parseDutyLog } from "./dutyLog.js";
import { MAX_PERIOD_COUNT, parseDutyRules, usesOperatorDays } from "./dutyRules.js";
import { countEvents, countInRange, createRunStore, endingAtOrBefore, entryHolding, firstEndingAfter, firstEntryIn, firstStartingAtOrAfter, firstWhere, interruptionResetAt, lastAtLeastUntil, lastEntryBefore, latestAtLeast, latestPairFrom, logStartBefore, runEndingAt, runIndex, runsMatching, runsUntil, timeInBefore, viewRun } from "./dutyRunIndex.js";

// src/internal/dutyEngine.ts
/** A window a call cannot place in Temporal's range. Caught by the public function. */
var Unrepresentable = class extends RangeError {};
/**
* A count as a number, exactly. Past `Number.MAX_SAFE_INTEGER` a number would round it, so the
* call is refused instead.
*/
function exactCount(value) {
	if (value > BigInt(Number.MAX_SAFE_INTEGER)) throw new Unrepresentable("a count past the safe integers");
	return Number(value);
}
const duration = (nanoseconds) => ({ duration: nanoseconds > 0n ? nanoseconds : 0n });
const tally = (value) => ({ count: value > 0 ? value : 0 });
const max = (a, b) => a > b ? a : b;
const min = (a, b) => a < b ? a : b;
const length = (run) => run.end - run.start;
/**
* Read the log, rules and options `evaluateDutyLog` and `dutyViolations` take, all-or-nothing.
*
* - `options` must be an object with a valid `timeZone`; `dayStartTime` is optional, but a rule
*   that counts operator days needs it; `disambiguation` is `"compatible"` when absent. Each
*   member is read once.
*
* @param log candidate duty log
* @param rules candidate rules
* @param options candidate `{ timeZone, dayStartTime?, disambiguation? }`
* @returns the context and resolved rules, or null on invalid input
*/
function prepareDutyCall(log, rules, options) {
	const entries = parseDutyLog(log);
	const resolved = parseDutyRules(rules);
	if (entries === null || resolved === null || !isObject(options)) return null;
	const { timeZone, dayStartTime } = options;
	const disambiguation = parseScheduleDisambiguation(options);
	const frame = zoneFrame(timeZone);
	const time = dayStartTime === void 0 ? null : parseDayStartTime(dayStartTime);
	if (frame === null || disambiguation === null || dayStartTime !== void 0 && time === null || time === null && resolved.some(usesOperatorDays)) return null;
	return {
		context: {
			entries,
			frame,
			dayStartTime: time,
			disambiguation,
			scales: /* @__PURE__ */ new Map(),
			wallClocks: /* @__PURE__ */ new Map(),
			windowInstances: /* @__PURE__ */ new Map(),
			store: createRunStore(entries)
		},
		rules: resolved
	};
}
function scaleFor(context, unit) {
	const known = context.scales.get(unit);
	if (known !== void 0) return known;
	let scale;
	if (unit === "operatorDay") {
		if (context.dayStartTime === null) throw new Unrepresentable("operator days need dayStartTime");
		scale = operatorDayScale(context.frame, context.dayStartTime, context.disambiguation);
	} else scale = calendarScale(context.frame, unit);
	context.scales.set(unit, scale);
	return scale;
}
/**
* Read a status list a helper takes: an array of strings, `[]` allowed. Each element is read once.
*
* @param value candidate status list
* @returns the statuses, or null when `value` is not an array of strings
*/
function readStatusList(value) {
	if (!Array.isArray(value)) return null;
	const statuses = /* @__PURE__ */ new Set();
	const count = value.length;
	for (let index = 0; index < count; index++) {
		const status = value[index];
		if (typeof status !== "string") return null;
		statuses.add(status);
	}
	return statuses;
}
/**
* Maximal runs of touching entries whose status passes `test`, merged as `mergeIntervals` merges
* them (CORE-6): touching entries join, and a gap or another status ends a run.
*/
function runsOf(log, test) {
	return runsMatching(log, (status) => test.has(status));
}
/**
* The parts of ordered, separate runs inside `[from, to)`, empty parts dropped: `clipRuns`, with
* the runs before `from` skipped by a binary search instead of read one by one.
*/
function runsBetween(runs, from, to) {
	let low = 0;
	let high = runs.length;
	for (let step = 0; step < 33 && low < high; step++) {
		const middle = low + high >> 1;
		if (runs[middle].end <= from) low = middle + 1;
		else high = middle;
	}
	const inside = [];
	for (let index = low; index < runs.length; index++) {
		const run = runs[index];
		if (run.start >= to) break;
		inside.push({
			start: max(run.start, from),
			end: min(run.end, to)
		});
	}
	return inside;
}
/** The parts of runs inside `[from, to)`, empty parts dropped. */
function clipRuns(runs, from, to) {
	const clipped = [];
	for (const run of runs) {
		const start = max(run.start, from);
		const end = min(run.end, to);
		if (start < end) clipped.push({
			start,
			end
		});
	}
	return clipped;
}
/** Time in `statuses` inside `[from, to)`. */
function timeIn(log, statuses, from, to) {
	let total = 0n;
	for (const entry of log) if (statuses.has(entry.status)) {
		const start = max(entry.start, from);
		const end = min(entry.end, to);
		total += end > start ? end - start : 0n;
	}
	return total;
}
/**
* The paired rests among runs of rest: two runs in a row, each shorter than `fullRest` and at
* least `pair.each`, the longer at least `pair.one` and both together at least `pair.combined`.
*
* - A run of `fullRest` or more is a rest on its own: it pairs with nothing, and no pair spans it.
* - A run shorter than `pair.each` is neither half of a pair nor a break between two runs.
* - Pairs may chain: of runs a, b and c, both (a, b) and (b, c) are returned when both qualify.
*
* @param runs runs of rest, in order
* @param fullRest the length at which a run is a full rest
* @param pair the three floors
* @returns the qualifying pairs, in order
*/
function restPairs(runs, fullRest, pair) {
	const pairs = [];
	let previous;
	for (const run of runs) {
		const taken = length(run);
		if (taken >= fullRest) {
			previous = void 0;
			continue;
		}
		if (taken < pair.each) continue;
		if (previous !== void 0) {
			const before = length(previous);
			if (max(before, taken) >= pair.one && before + taken >= pair.combined) pairs.push({
				first: previous,
				second: run
			});
		}
		previous = run;
	}
	return pairs;
}
/** A period repeated `times` over: `times` × its length, or `times` × its count. */
function repeated(period, times) {
	return period.kind === "elapsed" ? {
		kind: "elapsed",
		length: period.length * BigInt(times)
	} : {
		...period,
		count: period.count * times
	};
}
/** The window a period names at `at`: sliding for elapsed time, whole periods otherwise. */
function windowOf(context, period, at, anchor) {
	if (period.kind === "elapsed") return {
		span: {
			start: max(at - period.length, MIN_EPOCH_NANOSECONDS),
			end: at
		},
		basis: "elapsed",
		rolling: true
	};
	const scale = scaleFor(context, period.unit);
	const span = periodsEndingAt(scale, period.count, anchor);
	if (span === null) throw new Unrepresentable("period outside the instant range");
	return {
		span,
		basis: scale.basis,
		rolling: period.count > 1
	};
}
/** The end of the `periods`-th period, the one `from` falls in counting as the first. */
function boundaryAfter(context, period, periods, from) {
	if (period.kind === "elapsed") return from + period.length * BigInt(periods);
	const scale = scaleFor(context, period.unit);
	const first = scale.containing(from);
	const last = first === null ? null : periodAfter(scale, first, period.count * periods - 1);
	if (last === null) throw new Unrepresentable("period outside the instant range");
	return last.end;
}
const basisOf = (window) => window.basis;
const groupingOf = (window) => window.rolling ? "slide" : "period";
/** A cap: holds while `used` is at most `limit`. */
function capped(used, limit, rest) {
	const usedValue = "duration" in used ? used.duration : BigInt(used.count);
	const limitValue = "duration" in limit ? limit.duration : BigInt(limit.count);
	const remaining = limitValue - usedValue;
	return {
		satisfied: usedValue <= limitValue,
		used,
		limit,
		remaining: "duration" in limit ? duration(remaining) : tally(Number(remaining)),
		excess: usedValue - limitValue,
		...rest
	};
}
/** A floor: holds while `used` is at least `limit`, or `met` says otherwise. */
function floored(used, limit, met, rest) {
	return {
		satisfied: met,
		used: duration(used),
		limit: duration(limit),
		remaining: duration(limit - used),
		excess: limit - used,
		...rest
	};
}
/** How a list of rest runs measures against a `restRequirement`'s floors. */
function restChecks(rule, lengths) {
	const sorted = [...lengths].sort((a, b) => a > b ? -1 : a < b ? 1 : 0);
	const longest = sorted[0] ?? 0n;
	const checks = [];
	let counted = sorted.reduce((sum, value) => sum + value, 0n);
	if (rule.composition !== null) {
		const { maxPeriods, longestAtLeast, othersAtLeast } = rule.composition;
		const others = sorted.slice(1).filter((value) => value >= othersAtLeast).slice(0, maxPeriods - 1);
		counted = min(counted, others.reduce((sum, value) => sum + value, longest));
		checks.push({
			used: longest,
			limit: longestAtLeast
		});
	}
	if (rule.composite !== null) {
		const { consecutive, additional, blockMinimum } = rule.composite;
		const blocks = sorted.slice(1).filter((value) => value >= blockMinimum).reduce((sum, value) => sum + value, 0n);
		checks.push({
			used: longest,
			limit: consecutive
		});
		checks.push({
			used: max(longest - consecutive, 0n) + blocks,
			limit: additional
		});
		counted = min(counted, longest + blocks);
	}
	checks.push({
		used: counted,
		limit: rule.minimum
	});
	const failing = checks.find((check) => check.used < check.limit);
	return {
		met: failing === void 0,
		failing,
		total: checks[checks.length - 1]
	};
}
/** Rest runs with rest added from `at` to `end`, joined to a run that reaches `at`. */
function withRestUntil(runs, at, end) {
	const last = runs[runs.length - 1];
	return last !== void 0 && last.end === at ? [...runs.slice(0, -1), {
		start: last.start,
		end
	}] : [...runs, {
		start: at,
		end
	}];
}
/** `resolveWallClock` under the call's policy, each local date-time resolved once per call. */
function wallClockOf(context, date, time) {
	const key = `${date.toString()}T${time.toString()}`;
	const known = context.wallClocks.get(key);
	if (known !== void 0) return known;
	const resolved = resolveWallClock(context.frame, date, time, context.disambiguation);
	context.wallClocks.set(key, resolved);
	return resolved;
}
/**
* The whole local windows inside `[from, to)` in the reference zone, their edges resolved under
* the call's `disambiguation`.
*
* - `strict`: under `"reject"`, a window with a repeated or skipped edge that reaches `[from, to)`
*   throws `WallClockRejected`. Without it, such an edge is read `"compatible"`: for rest that is
*   only supposed (the best case of a window not yet over), or for finding candidate instants.
*/
function localWindowsIn(context, window, from, to, strict) {
	const found = [];
	const instances = windowInstances(context, window, from, to);
	let low = 0;
	let high = instances.length;
	for (let step = 0; step < 33 && low < high; step++) {
		const middle = low + high >> 1;
		if (instances[middle].end <= from) low = middle + 1;
		else high = middle;
	}
	for (let index = low; index < instances.length; index++) {
		const instance = instances[index];
		if (instance.start >= to) break;
		if (strict && instance.rejected && instance.end > from) throw new WallClockRejected("a local window the zone repeats or skips");
		if (instance.start < instance.end && instance.start >= from && instance.end <= to) found.push({
			start: instance.start,
			end: instance.end
		});
	}
	return found;
}
/** Two days: how far either side of a request the window instances are resolved and kept. */
const WINDOW_MARGIN = 172800000000000n;
/** The instances of a local window on the dates `first` to `last`, in date order. */
function instancesOn(context, window, first, last) {
	const instances = [];
	let date = first;
	for (let step = 0; date !== null && Temporal.PlainDate.compare(date, last) <= 0; step++) {
		if (step > 2 * 1e4) throw new Unrepresentable("too many local windows");
		const next = datePlusDays(date, 1);
		const start = wallClockOf(context, date, window.from);
		const end = window.wraps && next === null ? null : wallClockOf(context, window.wraps ? next : date, window.to);
		if (start !== null && end !== null) instances.push({
			start: start.at,
			end: end.at,
			rejected: start.rejected || end.rejected
		});
		date = next;
	}
	return instances;
}
/** How close a request must be to a stretch already resolved to extend it: thirty days. */
const WINDOW_JOIN = 2592000000000000n;
/**
* Every instance of a local window on the local dates around `[from, to)`, resolved once per call
* and kept, so each later evaluation only filters them.
*
* - A request near a stretch of dates already kept resolves only the dates it adds, so a scan
*   that moves along the log resolves each date once. A request far from every stretch starts a
*   stretch of its own: the dates between two far-apart rests are never resolved.
* - One request may need at most `2 × MAX_PERIOD_COUNT` dates; past that it throws
*   `Unrepresentable`. What is kept from earlier requests does not count against it.
*/
function windowInstances(context, window, from, to) {
	const key = `${window.from.toString()}-${window.to.toString()}`;
	const stretches = context.windowInstances.get(key) ?? [];
	const covering = stretches.find((stretch) => stretch.from <= from && stretch.to >= to);
	if (covering !== void 0) return covering.instances;
	const wantedFrom = from - WINDOW_MARGIN;
	const wantedTo = to + WINDOW_MARGIN;
	const wanted = datePlusDays(localDateOf(context.frame, wantedFrom), -1);
	const until = localDateOf(context.frame, wantedTo - 1n);
	if (wanted === null || wanted.until(until, { largestUnit: "day" }).days > 2 * 1e4) throw new Unrepresentable("too many local windows");
	const known = stretches.find((stretch) => stretch.from - WINDOW_JOIN <= wantedTo && stretch.to + WINDOW_JOIN >= wantedFrom);
	const spanFrom = known === void 0 ? wantedFrom : min(known.from, wantedFrom);
	const spanTo = known === void 0 ? wantedTo : max(known.to, wantedTo);
	const first = known !== void 0 && Temporal.PlainDate.compare(known.first, wanted) < 0 ? known.first : wanted;
	const last = known !== void 0 && Temporal.PlainDate.compare(known.last, until) > 0 ? known.last : until;
	let instances;
	if (known === void 0) instances = instancesOn(context, window, first, last);
	else {
		const before = datePlusDays(known.first, -1);
		const after = datePlusDays(known.last, 1);
		instances = [
			...before !== null && Temporal.PlainDate.compare(first, before) <= 0 ? instancesOn(context, window, first, before) : [],
			...known.instances,
			...after !== null && Temporal.PlainDate.compare(after, last) <= 0 ? instancesOn(context, window, after, last) : []
		];
	}
	const stretch = {
		from: spanFrom,
		to: spanTo,
		first,
		last,
		instances
	};
	context.windowInstances.set(key, [...stretches.filter((other) => other !== known), stretch]);
	return instances;
}
/** How many free periods one run of rest holds. */
function freePeriodsIn(context, rule, run, strict) {
	if (rule.containing === null) return length(run) / rule.minimum;
	const { window, count } = rule.containing;
	const instances = localWindowsIn(context, window, run.start, run.end, strict);
	let cursor = run.start;
	let first = 0;
	let found = 0;
	for (let step = 0; step <= instances.length; step++) {
		for (; first < instances.length; first++) if (instances[first].start >= cursor) break;
		const last = instances[first + count - 1];
		const end = last === void 0 ? null : max(cursor + rule.minimum, last.end);
		if (end === null || end > run.end) break;
		found++;
		cursor = end;
	}
	return BigInt(found);
}
function evaluateFreePeriod(context, rule, at, anchor) {
	const window = windowOf(context, rule.within, at, anchor);
	const rests = runIndex(context.store, rule.restStatuses).runs;
	const countIn = (from, to, extendTo) => {
		const inside = runsBetween(rests, from, to);
		const runs = extendTo === void 0 ? inside : withRestUntil(inside, at, extendTo);
		const strict = extendTo === void 0;
		return runs.reduce((sum, run) => sum + freePeriodsIn(context, rule, run, strict), 0n);
	};
	const enough = (count) => count >= BigInt(rule.atLeast);
	const { span } = window;
	const found = exactCount(countIn(span.start, min(span.end, at)));
	const unfinished = span.end > at;
	const met = found >= rule.atLeast || unfinished && enough(countIn(span.start, at, span.end));
	let dueBy = null;
	if (found >= rule.atLeast && rule.atLeast > 0) {
		if (rule.within.kind === "elapsed") {
			const windowLength = rule.within.length;
			let low = at;
			let high = at + windowLength;
			for (let step = 0; step < 90 && high - low > 1n; step++) {
				const middle = (low + high) / 2n;
				if (enough(countIn(middle - windowLength, at))) low = middle;
				else high = middle;
			}
			dueBy = low;
		} else {
			const scale = scaleFor(context, rule.within.unit);
			const count = rule.within.count;
			const first = scale.containing(span.start);
			const unitAt = (index) => {
				const found = first === null ? null : periodAfter(scale, first, index);
				if (found === null) throw new Unrepresentable("period outside the instant range");
				return found;
			};
			let low = 1;
			let high = count;
			for (let step = 0; step < 32 && low < high; step++) {
				const middle = low + high >> 1;
				if (!enough(countIn(unitAt(middle).start, at))) high = middle;
				else low = middle + 1;
			}
			dueBy = unitAt(low + count - 1).end;
		}
	} else if (met) dueBy = span.end;
	return {
		satisfied: met,
		used: tally(found),
		limit: tally(rule.atLeast),
		remaining: tally(rule.atLeast - found),
		window: span,
		periodBasis: basisOf(window),
		dueBy,
		resetAt: null,
		excess: BigInt(rule.atLeast - found),
		grouping: groupingOf(window)
	};
}
/**
* The stretches without rest in the log as it stood at `at`: each runs from the end of one rest to
* the start of the next, the last to `at` (or nowhere, when a rest reaches `at`). The log's first
* entry starts one too, as a rest ending there would: time before the log is unknown, but the work
* logged before the first rest is a stretch without rest like any other.
*/
function restGaps(rests, logStart, at) {
	const taken = rests.count;
	const resting = rests.last !== void 0 && rests.last.end === at;
	const prepended = logStart !== void 0 && (taken === 0 || viewRun(rests, 0).start !== logStart);
	const startAt = (gap) => prepended ? gap === 0 ? logStart : viewRun(rests, gap - 1).end : viewRun(rests, gap).end;
	const endAt = (gap) => {
		const next = prepended ? gap : gap + 1;
		return next < taken ? viewRun(rests, next).start : resting ? startAt(gap) : at;
	};
	return {
		count: prepended ? taken + 1 : taken,
		resting,
		startAt,
		endAt
	};
}
/**
* The longest stretch without rest touching `[from, to)`, found from the first that ends after
* `from`.
*/
function widestGap(gaps, from, to) {
	let widest = 0n;
	for (let gap = firstWhere(gaps.count, (position) => gaps.endAt(position) > from); gap < gaps.count && gaps.startAt(gap) < to; gap++) widest = max(widest, gaps.endAt(gap) - gaps.startAt(gap));
	return widest;
}
/** The widest stretch without rest in `[from, upper)` at `at`, and when the next rest falls due. */
function widestRestGap(context, index, at, from, upper, maxGap) {
	const gaps = restGaps(runsUntil(index, at), logStartBefore(context.store, at), at);
	return {
		widest: widestGap(gaps, from, upper),
		dueBy: gaps.count > 0 && !gaps.resting ? gaps.startAt(gaps.count - 1) + maxGap : null
	};
}
function evaluateRestRequirement(context, rule, at, anchor) {
	const window = windowOf(context, rule.per, at, anchor);
	const { span } = window;
	const index = runIndex(context.store, rule.restStatuses);
	const upper = min(span.end, at);
	const inside = span.start < upper ? runsBetween(index.runs, span.start, upper) : [];
	const actual = restChecks(rule, inside.map(length));
	const met = actual.met || span.end > at && restChecks(rule, withRestUntil(inside, at, span.end).map(length)).met;
	const shown = (met ? void 0 : actual.failing) ?? actual.total;
	const rest = {
		window: span,
		periodBasis: basisOf(window),
		resetAt: null,
		grouping: groupingOf(window)
	};
	if (rule.maxGap !== null) {
		const { widest, dueBy } = widestRestGap(context, index, at, span.start, upper, rule.maxGap);
		if (widest > rule.maxGap) return {
			satisfied: false,
			used: duration(widest),
			limit: duration(rule.maxGap),
			remaining: duration(0n),
			excess: widest - rule.maxGap,
			dueBy,
			...rest
		};
		return floored(shown.used, shown.limit, met, {
			...rest,
			dueBy
		});
	}
	return floored(shown.used, shown.limit, met, {
		...rest,
		dueBy: null
	});
}
/** The rest right before a duty, measured whole, against the duty before it (`orFactor`). */
function restBeforeDutyScaled(rule, orFactor, { rests, dutyStart, onDuty, logStart }) {
	const rest = runEndingAt(rests, dutyStart);
	const restStart = rest?.start ?? dutyStart;
	const dutyFrom = latestAtLeast(rests, endingAtOrBefore(rests, restStart), rule.minimum)?.end ?? min(logStart, restStart);
	const previousDuty = restStart - dutyFrom;
	const { numerator, denominator } = orFactor.k;
	const scaled = (previousDuty * numerator + denominator - 1n) / denominator;
	const limit = max(rule.minimum, max(scaled, orFactor.floor));
	const used = rest === void 0 ? 0n : length(rest);
	return {
		...floored(used, limit, !onDuty || used >= limit, {
			window: {
				start: dutyFrom,
				end: dutyStart
			},
			periodBasis: "elapsed",
			dueBy: null,
			resetAt: null,
			grouping: "start"
		}),
		beforeLog: restStart <= logStart,
		key: restStart
	};
}
/** The longest run of rest inside `[windowStart, dutyStart)`, the latest on a tie. */
function longestRestInside(rests, windowStart, dutyStart) {
	let rest;
	for (let position = firstEndingAfter(rests, windowStart); position < rests.count; position++) {
		const run = viewRun(rests, position);
		if (run.start >= dutyStart) break;
		const inside = min(run.end, dutyStart) - max(run.start, windowStart);
		if (inside > 0n && (rest === void 0 || inside >= rest.inside)) rest = {
			run,
			inside
		};
	}
	return rest;
}
/** The rest before a duty: the longest inside the window, against the minimum. */
function restBeforeDutyWithin(rule, { rests, dutyStart, onDuty }) {
	const windowStart = max(dutyStart - rule.within, MIN_EPOCH_NANOSECONDS);
	const rest = longestRestInside(rests, windowStart, dutyStart);
	const used = rest?.inside ?? 0n;
	return {
		...floored(used, rule.minimum, !onDuty || used >= rule.minimum, {
			window: {
				start: windowStart,
				end: dutyStart
			},
			periodBasis: "elapsed",
			dueBy: null,
			resetAt: null,
			grouping: "start"
		}),
		key: rest?.run.start ?? windowStart
	};
}
function evaluateRestBeforeDuty(context, rule, at) {
	const { store } = context;
	const rests = runsUntil(runIndex(store, rule.restStatuses), at);
	const last = lastEntryBefore(store, at);
	const onDuty = last !== void 0 && last.end === at && !rule.restStatuses.has(last.status);
	const started = {
		rests,
		dutyStart: onDuty ? runsUntil(runIndex(store, { not: rule.restStatuses }), at).last.start : at,
		onDuty,
		logStart: logStartBefore(store, at) ?? at
	};
	return rule.orFactor === null ? restBeforeDutyWithin(rule, started) : restBeforeDutyScaled(rule, rule.orFactor, started);
}
function evaluateRule(context, rule, at, anchor) {
	if (rule.kind === "freePeriod") return evaluateFreePeriod(context, rule, at, anchor);
	const { store } = context;
	const first = logStartBefore(store, at) ?? at;
	const viewOf = (test) => runsUntil(runIndex(store, test), at);
	const timeOf = (test, from, to) => timeInBefore(runIndex(store, test), from, to, at);
	switch (rule.kind) {
		case "cumulativeCap": {
			const reset = lastAtLeastUntil(viewOf(rule.since.statuses), rule.since.consecutive);
			const from = reset?.end ?? first;
			return capped(duration(timeOf(rule.statuses, from, at)), duration(rule.cap), {
				window: {
					start: from,
					end: at
				},
				periodBasis: null,
				dueBy: null,
				resetAt: reset?.end ?? null,
				grouping: "start"
			});
		}
		case "elapsedWindow": {
			const rests = viewOf(rule.since.statuses);
			const after = lastAtLeastUntil(rests, rule.since.consecutive)?.end ?? null;
			const opener = firstEntryIn(store, rule.startStatuses, after, at);
			if (opener === void 0) return {
				satisfied: true,
				used: duration(0n),
				limit: duration(rule.length),
				remaining: duration(rule.length),
				window: null,
				periodBasis: null,
				dueBy: null,
				resetAt: after,
				excess: 0n,
				grouping: "start"
			};
			let opensAt = opener.start;
			let second;
			if (rule.exclude !== null) {
				const latest = latestPairFrom(rests, firstStartingAtOrAfter(rests, opener.start), rule.since.consecutive, rule.exclude);
				if (latest !== void 0) {
					opensAt = latest.first.end;
					second = latest.second;
				}
			}
			let closesAt = opensAt + rule.length;
			let limit = rule.length;
			let excluded = 0n;
			let extended = false;
			for (let pass = 0; pass < 2; pass++) {
				if (excluded === 0n && second !== void 0 && second.start < closesAt) {
					excluded = length(second);
					closesAt += excluded;
				}
				if (!extended && rule.extension !== null && opener.start <= rule.extension.from && rule.extension.from < closesAt) {
					extended = true;
					closesAt += rule.extension.by;
					limit += rule.extension.by;
				}
			}
			const late = timeOf(rule.restrictedStatuses, closesAt, at);
			return {
				satisfied: late === 0n,
				used: duration(at - opensAt - excluded),
				limit: duration(limit),
				remaining: duration(closesAt - at),
				window: {
					start: opensAt,
					end: closesAt
				},
				periodBasis: "elapsed",
				dueBy: closesAt,
				resetAt: after,
				excess: late,
				grouping: "start"
			};
		}
		case "requiredInterruption": {
			const breaks = viewOf({
				not: rule.countedStatuses,
				within: rule.outsideStatuses
			});
			const resetAt = interruptionResetAt(breaks, rule.minimum, rule.orderedSplit);
			const from = resetAt ?? first;
			return capped(duration(timeOf(rule.countedStatuses, from, at)), duration(rule.after), {
				window: {
					start: from,
					end: at
				},
				periodBasis: null,
				dueBy: null,
				resetAt,
				grouping: "start"
			});
		}
		case "rollingCap": {
			const window = windowOf(context, rule.window, at, anchor);
			const reset = rule.reset === null ? void 0 : lastAtLeastUntil(viewOf(rule.reset.statuses), rule.reset.consecutive);
			const from = reset !== void 0 && reset.end > window.span.start ? reset.end : window.span.start;
			const to = min(window.span.end, at);
			let used = timeOf(rule.statuses, from, to);
			let limit = rule.cap;
			if (rule.precondition !== null) {
				const { restStatuses, minimum, beforeHours } = rule.precondition;
				const rest = (from < to ? runsBetween(runIndex(store, restStatuses).runs, from, to) : []).find((run) => length(run) >= minimum);
				const before = rest === void 0 ? used : timeOf(rule.statuses, from, rest.start);
				if (rest === void 0 || before > beforeHours) {
					limit = beforeHours;
					used = before;
				}
			}
			return capped(duration(used), duration(limit), {
				window: {
					start: from,
					end: window.span.end
				},
				periodBasis: basisOf(window),
				dueBy: null,
				resetAt: reset?.end ?? null,
				grouping: groupingOf(window)
			});
		}
		case "fixedPeriodCap": {
			const window = windowOf(context, repeated(rule.period, rule.adjacent), at, anchor);
			const total = timeOf(rule.statuses, window.span.start, min(window.span.end, at));
			const rest = {
				window: window.span,
				periodBasis: basisOf(window),
				dueBy: null,
				resetAt: null,
				grouping: groupingOf(window)
			};
			if (!rule.average) return capped(duration(total), duration(rule.cap), rest);
			const periods = BigInt(rule.adjacent);
			const allowed = rule.cap * periods;
			return {
				satisfied: total <= allowed,
				used: duration((total + periods - 1n) / periods),
				limit: duration(rule.cap),
				remaining: duration(allowed - total),
				excess: total - allowed,
				...rest
			};
		}
		case "restRequirement": return evaluateRestRequirement(context, rule, at, anchor);
		case "restBeforeDuty": return evaluateRestBeforeDuty(context, rule, at);
		case "quota": {
			const continuing = entryHolding(store, at);
			const running = continuing !== void 0 && rule.statuses.has(continuing.status);
			const runs = viewOf(rule.statuses);
			const sizes = {
				minimum: rule.minimum,
				maximum: rule.maximum
			};
			const skipEndingAt = running ? at : null;
			if ("every" in rule.reset) {
				const window = windowOf(context, rule.reset.every, at, anchor);
				const to = min(window.span.end, at);
				const found = countEvents(runs, sizes, {
					from: window.span.start,
					to
				}, skipEndingAt);
				return capped(tally(found), tally(rule.count), {
					window: window.span,
					periodBasis: basisOf(window),
					dueBy: null,
					resetAt: null,
					grouping: groupingOf(window)
				});
			}
			const reset = lastAtLeastUntil(viewOf(rule.reset.statuses), rule.reset.consecutive);
			const from = reset?.end ?? first;
			return capped(tally(countEvents(runs, sizes, {
				from,
				to: null
			}, skipEndingAt)), tally(rule.count), {
				window: {
					start: from,
					end: at
				},
				periodBasis: null,
				dueBy: null,
				resetAt: reset?.end ?? null,
				grouping: "start"
			});
		}
		case "dueBy": {
			const events = viewOf(rule.statuses);
			const event = lastAtLeastUntil(events, rule.minimum);
			const reset = rule.reset === null ? void 0 : lastAtLeastUntil(viewOf(rule.reset.statuses), rule.reset.consecutive);
			const clock = event === void 0 ? reset?.end ?? null : reset === void 0 ? event.end : max(event.end, reset.end);
			const from = clock ?? first;
			const due = boundaryAfter(context, rule.period, rule.periods, from);
			const latest = events.last;
			const pending = latest !== void 0 && latest.end === at && latest.start <= due;
			return {
				satisfied: at <= due || pending,
				used: duration(at - from),
				limit: duration(due - from),
				remaining: duration(due - at),
				window: {
					start: from,
					end: due
				},
				periodBasis: rule.period.kind === "elapsed" ? "elapsed" : scaleFor(context, rule.period.unit).basis,
				dueBy: due,
				resetAt: clock,
				excess: at - due,
				grouping: "start"
			};
		}
		case "pattern": {
			const window = windowOf(context, repeated(rule.period, rule.lookback), at, anchor);
			const { span } = window;
			const to = min(span.end, at);
			const unfinished = span.end > at;
			const counts = /* @__PURE__ */ new Map();
			for (const named of rule.classes) {
				const runs = viewOf(named.statuses);
				const qualifies = (run) => run.start >= span.start && run.start < to && length(run) >= named.minimum;
				const found = countEvents(runs, {
					minimum: named.minimum,
					maximum: null
				}, {
					from: span.start,
					to
				}, null);
				const last = runs.last;
				let best = found;
				if (unfinished) {
					let firstStart = at;
					if (last !== void 0 && last.end === at && !qualifies(last) && last.start >= span.start) {
						best += 1;
						firstStart = last.start + named.minimum;
					}
					if (firstStart < span.end) {
						const room = span.end - firstStart;
						best += Number(min((room + named.minimum - 1n) / named.minimum, BigInt(Number.MAX_SAFE_INTEGER)));
					}
				}
				counts.set(named.label, {
					found,
					best
				});
			}
			const slack = rule.require.map((required) => {
				const tallied = counts.get(required.label);
				return {
					...required,
					found: tallied.found,
					actual: tallied.found - required.atLeast,
					best: tallied.best - required.atLeast
				};
			});
			const tightest = slack.reduce((worst, item) => item.actual < worst.actual ? item : worst);
			return {
				satisfied: slack.every((item) => item.actual >= 0) || unfinished && slack.every((item) => item.best >= 0),
				used: tally(tightest.found),
				limit: tally(tightest.atLeast),
				remaining: tally(-tightest.actual),
				window: span,
				periodBasis: basisOf(window),
				dueBy: null,
				resetAt: null,
				excess: BigInt(-tightest.actual),
				grouping: groupingOf(window)
			};
		}
		case "occurrenceCap": {
			const scale = scaleFor(context, rule.per.unit);
			const runs = viewOf(rule.statuses);
			const blocks = [];
			let blockAnchor = anchor;
			for (let index = 0; index < rule.lookback; index++) {
				const block = periodsEndingAt(scale, rule.per.count, blockAnchor);
				if (block === null) throw new Unrepresentable("period outside the instant range");
				blocks.push(block);
				blockAnchor = block.start - 1n;
			}
			const occupied = blocks.filter((block) => {
				const to = min(block.end, at);
				const position = rule.byInitiationDate ? firstStartingAtOrAfter(runs, block.start) : firstEndingAfter(runs, block.start);
				return position < runs.count && viewRun(runs, position).start < to;
			}).length;
			const earliest = blocks[blocks.length - 1];
			const latest = blocks[0];
			return capped(tally(occupied), tally(rule.maximum), {
				window: {
					start: earliest.start,
					end: latest.end
				},
				periodBasis: scale.basis,
				dueBy: null,
				resetAt: null,
				grouping: rule.lookback * rule.per.count > 1 ? "slide" : "period"
			});
		}
		case "usageLookback": {
			const window = windowOf(context, rule.notWithin, at, anchor);
			const reset = lastAtLeastUntil(viewOf(rule.reset.statuses), rule.reset.consecutive);
			const from = reset !== void 0 && reset.end > window.span.start ? reset.end : window.span.start;
			const found = countInRange(rule.uses, rule.notWithin.kind === "elapsed" ? max(from, at - rule.notWithin.length + 1n) : from, rule.notWithin.kind === "elapsed" ? at + 1n : min(at + 1n, window.span.end));
			return capped(tally(found), tally(1), {
				window: {
					start: from,
					end: window.span.end
				},
				periodBasis: basisOf(window),
				dueBy: null,
				resetAt: reset?.end ?? null,
				grouping: groupingOf(window)
			});
		}
	}
}
const instantText = (nanoseconds) => Temporal.Instant.fromEpochNanoseconds(nanoseconds).toString();
function measureText(measure) {
	if (measure === null) return null;
	if (!("duration" in measure)) return measure.count;
	const text = formatHourDuration(measure.duration);
	if (text === "") throw new Unrepresentable("a duration past Temporal's range");
	return text;
}
function spanText(span) {
	return {
		start: instantText(span.start),
		end: instantText(span.end)
	};
}
/**
* Evaluate every rule at one instant.
*
* @param context the call's context
* @param rules the resolved rules
* @param at the instant, epoch nanoseconds
* @returns one outcome per rule, in order
*/
function evaluateDutyRules(context, rules, at) {
	return rules.map((rule) => {
		const evaluation = evaluateRule(context, rule, at, at - 1n);
		return {
			label: rule.label,
			kind: rule.kind,
			severity: rule.severity,
			satisfied: evaluation.satisfied,
			used: measureText(evaluation.used),
			limit: measureText(evaluation.limit),
			remaining: measureText(evaluation.remaining),
			window: evaluation.window === null ? null : spanText(evaluation.window),
			periodBasis: evaluation.periodBasis,
			dueBy: evaluation.dueBy === null ? null : instantText(evaluation.dueBy),
			resetAt: evaluation.resetAt === null ? null : instantText(evaluation.resetAt)
		};
	});
}
/** The elapsed lengths a rule's window slides by, for the candidate instants of a range. */
function slideLengths(rule) {
	const periods = [];
	switch (rule.kind) {
		case "rollingCap":
			periods.push(rule.window);
			break;
		case "restRequirement":
			periods.push(rule.per);
			break;
		case "freePeriod":
			periods.push(rule.within);
			break;
		case "quota":
			if ("every" in rule.reset) periods.push(rule.reset.every);
			break;
		case "pattern":
			periods.push(repeated(rule.period, rule.lookback));
			break;
		case "usageLookback": periods.push(rule.notWithin);
	}
	return periods.flatMap((period) => period.kind === "elapsed" ? [period.length] : []);
}
/** The local units a rule counts in, whose boundaries are candidate instants of a range. */
function unitsOf(rule) {
	const periods = [];
	switch (rule.kind) {
		case "rollingCap":
			periods.push(rule.window);
			break;
		case "fixedPeriodCap":
			periods.push(rule.period);
			break;
		case "restRequirement":
			periods.push(rule.per);
			break;
		case "freePeriod":
			periods.push(rule.within);
			break;
		case "quota":
			if ("every" in rule.reset) periods.push(rule.reset.every);
			break;
		case "dueBy":
		case "pattern":
			periods.push(rule.period);
			break;
		case "occurrenceCap":
			periods.push(rule.per);
			break;
		case "usageLookback": periods.push(rule.notWithin);
	}
	return periods.flatMap((period) => period.kind === "units" ? [period.unit] : []);
}
const NANOSECONDS_PER_DAY = 86400000000000n;
/**
* More than any one local period of a unit can last: its longest calendar length plus a week. A
* clock change moves the wall clock by less than 48 hours, since Temporal holds every offset
* strictly within ±24 hours, so neither a skipped date nor a repeated stretch can add a week.
*/
const LONGER_THAN_ANY = {
	operatorDay: 8n * NANOSECONDS_PER_DAY,
	day: 8n * NANOSECONDS_PER_DAY,
	week: 14n * NANOSECONDS_PER_DAY,
	month: 38n * NANOSECONDS_PER_DAY,
	year: 373n * NANOSECONDS_PER_DAY
};
/**
* Call `visit` with the end of every period of `scale` that ends inside `(from, until]`, starting
* with the one `from` falls in.
*
* - Throws `Unrepresentable` when more than `MAX_PERIOD_COUNT` periods end there, or for a period
*   Temporal cannot hold.
* - A span of `MAX_PERIOD_COUNT + 1` times `LONGER_THAN_ANY` or more certainly holds more ends
*   than that, so it is refused without a lookup. A shorter span is walked, and the walk decides.
*/
function walkBoundaries(scale, unit, from, until, visit) {
	if (from >= until) return;
	if (until - from >= BigInt(1e4 + 1) * LONGER_THAN_ANY[unit]) throw new Unrepresentable("too many periods in the range");
	let current = scale.containing(from);
	for (let step = 0; current !== null && current.end <= until; step++) {
		if (step >= 1e4) throw new Unrepresentable("too many periods in the range");
		visit(current.end);
		current = scale.containing(current.end);
	}
	if (current === null) throw new Unrepresentable("period outside the instant range");
}
/**
* The runs whose lengths a rule compares with floors, and the floors: where a run reaches a floor
* (`start + floor`), or, inside a sliding window, shrinks below it (`end + length − floor`), the
* rule's answer can change between entry bounds.
*/
function runFloors(rule) {
	switch (rule.kind) {
		case "cumulativeCap": return [{
			test: rule.since.statuses,
			floors: [rule.since.consecutive],
			sliding: false
		}];
		case "elapsedWindow": return [{
			test: rule.since.statuses,
			floors: [rule.since.consecutive, ...rule.exclude === null ? [] : [rule.exclude.each, rule.exclude.one]],
			sliding: false
		}];
		case "requiredInterruption": return [{
			test: {
				not: rule.countedStatuses,
				within: rule.outsideStatuses
			},
			floors: [rule.minimum, ...rule.orderedSplit ?? []],
			sliding: false
		}];
		case "rollingCap": return [...rule.reset === null ? [] : [{
			test: rule.reset.statuses,
			floors: [rule.reset.consecutive],
			sliding: false
		}], ...rule.precondition === null ? [] : [{
			test: rule.precondition.restStatuses,
			floors: [rule.precondition.minimum],
			sliding: true
		}]];
		case "restRequirement": {
			const floors = [rule.minimum];
			if (rule.composition !== null) {
				floors.push(rule.composition.longestAtLeast);
				if (rule.composition.othersAtLeast > 0n) floors.push(rule.composition.othersAtLeast);
			}
			if (rule.composite !== null) floors.push(rule.composite.consecutive, rule.composite.blockMinimum, rule.composite.consecutive + rule.composite.additional);
			return [{
				test: rule.restStatuses,
				floors,
				sliding: true
			}];
		}
		case "freePeriod": return [];
		case "quota": return "every" in rule.reset ? [] : [{
			test: rule.reset.statuses,
			floors: [rule.reset.consecutive],
			sliding: false
		}];
		case "dueBy": return [{
			test: rule.statuses,
			floors: [rule.minimum],
			sliding: false
		}, ...rule.reset === null ? [] : [{
			test: rule.reset.statuses,
			floors: [rule.reset.consecutive],
			sliding: false
		}]];
		case "pattern": return rule.classes.map((named) => ({
			test: named.statuses,
			floors: [named.minimum],
			sliding: false
		}));
		case "usageLookback": return [{
			test: rule.reset.statuses,
			floors: [rule.reset.consecutive],
			sliding: false
		}];
		default: return [];
	}
}
/**
* The instants at which a rule's answer can change, inside `(start, end]`.
*
* A rule's measures are piecewise linear in the instant evaluated, so a failed window shows at a
* breakpoint or just either side of one:
*
* - every entry bound and use, those bounds shifted by the rule's sliding lengths, and every
*   boundary of its local periods;
* - where a run reaches or, in a sliding window, shrinks past a floor the rule compares it with;
* - for a rest rule that picks its longest runs, where two runs cross as the longest;
* - where a gap passes `maxGap`, a rest falls due, and a free period gains or loses a local window;
* - the first instant after `start`, so a window failing as the range opens is seen.
*/
function candidateInstants(context, rule, range) {
	const logEnd = context.entries[context.entries.length - 1]?.end;
	if (logEnd === void 0) return [];
	const until = min(range.end, logEnd);
	const base = [];
	for (const entry of context.entries) base.push(entry.start, entry.end);
	if (rule.kind === "usageLookback") base.push(...rule.uses);
	if (rule.kind === "elapsedWindow" && rule.extension !== null) base.push(rule.extension.from);
	const points = /* @__PURE__ */ new Set([range.start + 1n, until]);
	const add = (point) => {
		if (point > range.start && point <= until) points.add(point);
	};
	const around = (point) => {
		add(point - 1n);
		add(point);
		add(point + 1n);
		if (points.size > MAX_CANDIDATE_INSTANTS) throw new Unrepresentable("too many instants to check");
	};
	for (const point of base) around(point);
	const shifts = slideLengths(rule);
	for (const shift of shifts) for (const point of base) around(point + shift);
	for (const { test, floors, sliding } of runFloors(rule)) for (const run of runIndex(context.store, test).runs) for (const floor of floors) {
		around(run.start + floor);
		if (sliding) for (const shift of shifts) around(run.end + shift - floor);
	}
	if (rule.kind === "elapsedWindow" && rule.exclude !== null) {
		const fullRest = rule.since.consecutive;
		let partner;
		for (const run of runIndex(context.store, rule.since.statuses).runs) {
			if (partner !== void 0) around(run.start + rule.exclude.combined - length(partner));
			const taken = length(run);
			if (taken >= fullRest) partner = void 0;
			else if (taken >= rule.exclude.each) partner = run;
		}
	}
	if (rule.kind === "restRequirement") {
		const rests = runIndex(context.store, rule.restStatuses).runs;
		const ranks = rule.composition !== null || rule.composite !== null;
		if (rule.maxGap !== null) for (const start of [...rests.map((run) => run.end), ...context.entries.slice(0, 1).map((entry) => entry.start)]) around(start + rule.maxGap);
		for (const shift of ranks ? shifts : []) {
			const near = rests.filter((run) => run.end >= range.start - 2n * shift && run.start <= until + 2n * shift);
			for (let index = 0; index < near.length; index++) {
				const earlier = near[index];
				for (let other = firstWhere(near.length, (position) => near[position].end > earlier.start - 2n * shift); other < near.length; other++) {
					const later = near[other];
					if (later.start - earlier.end >= 2n * shift) break;
					const crossing = (earlier.end + shift + later.start) / 2n;
					around(crossing);
					around(crossing + 1n);
					around(earlier.end + shift - length(later));
					around(later.start + length(earlier));
				}
			}
		}
	}
	if (rule.kind === "freePeriod") {
		const minimum = rule.minimum;
		const farthest = (BigInt(rule.atLeast) + 1n) * minimum + shifts.reduce((longest, shift) => max(longest, shift), 0n);
		const rests = runIndex(context.store, rule.restStatuses).runs.filter((run) => run.end + farthest >= range.start && run.start <= until + 1n);
		const reach = BigInt(rule.atLeast) + 1n;
		const multiplesFrom = (origin, last) => {
			const first = max(0n, floorDivide(range.start - origin, minimum) - 1n);
			const final = min(last, floorDivide(until - origin, minimum) + 1n);
			for (let multiple = first; multiple <= final; multiple++) around(origin + multiple * minimum);
		};
		const multiplesBefore = (origin, last) => {
			const first = max(0n, floorDivide(origin - until, minimum) - 1n);
			const final = min(last, floorDivide(origin - range.start, minimum) + 1n);
			for (let multiple = first; multiple <= final; multiple++) around(origin - multiple * minimum);
		};
		for (const run of rests) {
			const multiples = min(length(run) / minimum + 1n, reach);
			multiplesFrom(run.start, multiples);
			for (const shift of shifts) multiplesBefore(run.end + shift, multiples);
			if (rule.containing !== null) {
				const windows = localWindowsIn(context, rule.containing.window, run.start, run.end, false);
				for (const window of windows) {
					multiplesFrom(window.end, multiples);
					for (const shift of shifts) around(window.start + shift);
				}
			}
		}
	}
	if (rule.kind === "dueBy") {
		const clocks = [
			context.entries[0]?.start,
			...runIndex(context.store, rule.statuses).runs.filter((run) => length(run) >= rule.minimum).map((run) => run.end),
			...rule.reset === null ? [] : runIndex(context.store, rule.reset.statuses).runs.filter((run) => length(run) >= rule.reset.consecutive).map((run) => run.end)
		];
		for (const clock of clocks) if (clock !== void 0) around(boundaryAfter(context, rule.period, rule.periods, clock));
	}
	const from = max(range.start, firstEvidence(context, rule));
	for (const unit of unitsOf(rule)) walkBoundaries(scaleFor(context, unit), unit, from, until, around);
	return [...points].filter((point) => point > range.start && point <= until).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
}
/** `a / b` rounded down, for a positive `b`: bigint division rounds towards zero. */
function floorDivide(a, b) {
	return a >= 0n ? a / b : -((-a + b - 1n) / b);
}
/**
* The worse of two failures, `a` the earlier: the larger excess, and on a tie the earlier, whose
* window is the first to show it (a cap's window ends when the time over it was worked, not after
* the rest that followed).
*/
function worse(a, b) {
	return b.evaluation.excess > a.evaluation.excess ? b : a;
}
const keyOf = (evaluation) => evaluation.key ?? evaluation.window.start;
/** Whether a failure continues a violation: no passing check between, or the same key. */
function continues(violation, failure) {
	return violation.grouping === "slide" ? violation.open : keyOf(failure.evaluation) === violation.key;
}
/** A violation's report after one more failure: the last check of a period, else the worst. */
function report(violation, failure) {
	return violation.grouping === "period" ? failure : worse(violation.worst, failure);
}
/** The kinds that hold rest to a floor, which the record does not judge before the log starts. */
const FLOOR_KINDS = /* @__PURE__ */ new Set([
	"restRequirement",
	"freePeriod",
	"pattern",
	"restBeforeDuty"
]);
/**
* The most instants one rule may be checked at in one range. A log of a year has a few tens of
* thousands; more than this is refused rather than checked one by one.
*/
const MAX_CANDIDATE_INSTANTS = 1e6;
/** Thirty days: how far past a range's end the scan reads at a time, so a period walk stays short. */
const FORWARD_CHUNK = 2592000000000000n;
/**
* The earliest instant a rule has anything to fail on: the log's first entry, or for
* `usageLookback` its first use when that is earlier. Undefined for an empty log.
*/
function firstEvidence(context, rule) {
	const first = context.entries[0]?.start;
	return first === void 0 ? void 0 : [first, ...rule.kind === "usageLookback" ? rule.uses : []].reduce(min);
}
/**
* The violations of one rule, each listed in the range it began in and reported by its worst
* window, which may end after the range.
*
* - Failures inside `range` are grouped into violations as `scanDutyViolations` describes.
* - The first is dropped when it was already failing at `range.start`: it belongs to the range
*   before. So two adjacent ranges list every violation once.
* - The last is followed past `range.end` to its worst window, up to the log's last entry, never
*   into time the log does not cover.
*/
function ruleViolations(context, rule, asked) {
	const evidence = firstEvidence(context, rule);
	if (evidence === void 0) return [];
	const range = {
		start: max(asked.start, evidence - 1n),
		end: asked.end
	};
	const logStart = context.entries[0]?.start;
	const judgesRest = FLOOR_KINDS.has(rule.kind);
	const check = (at) => {
		const evaluation = evaluateRule(context, rule, at, at - 1n);
		return {
			evaluation,
			failure: evaluation.window !== null && !(judgesRest && logStart !== void 0 && (evaluation.window.start < logStart || evaluation.beforeLog === true)) && !evaluation.satisfied ? {
				evaluation,
				at
			} : null
		};
	};
	const violations = [];
	const candidates = candidateInstants(context, rule, range);
	let firstChecked;
	for (const at of candidates) {
		const { failure } = check(at);
		const last = violations[violations.length - 1];
		if (firstChecked === void 0) firstChecked = failure;
		if (failure === null) {
			if (last !== void 0) last.open = false;
		} else if (last !== void 0 && continues(last, failure)) last.worst = report(last, failure);
		else violations.push({
			worst: failure,
			grouping: failure.evaluation.grouping,
			key: keyOf(failure.evaluation),
			open: true
		});
	}
	const first = violations[0];
	if (first !== void 0) {
		let before;
		if (first.grouping === "slide") before = firstChecked !== void 0 && firstChecked !== null && check(range.start).failure !== null;
		else {
			const key = first.key;
			before = key < range.start && candidateInstants(context, rule, {
				start: key,
				end: range.start
			}).some((at) => {
				const { failure } = check(at);
				return failure !== null && continues(first, failure);
			});
		}
		if (before) violations.shift();
	}
	const last = violations[violations.length - 1];
	const logEnd = context.entries[context.entries.length - 1]?.end;
	if (last !== void 0 && logEnd !== void 0 && logEnd > range.end && (last.grouping !== "slide" || last.open)) {
		let cursor = range.end;
		let going = true;
		for (let chunk = 0; going && cursor < logEnd && chunk <= 1e4; chunk++) {
			const until = min(cursor + FORWARD_CHUNK, logEnd);
			for (const at of candidateInstants(context, rule, {
				start: cursor,
				end: until
			})) {
				const { evaluation, failure } = check(at);
				if (last.grouping === "slide") {
					if (failure === null) {
						going = false;
						break;
					}
					last.worst = report(last, failure);
				} else if (evaluation.window === null || keyOf(evaluation) !== last.key) {
					going = false;
					break;
				} else if (failure !== null) last.worst = report(last, failure);
			}
			cursor = until;
		}
	}
	return violations.map((violation) => violation.worst);
}
/**
* Every violation of the rules whose severity is `"violation"` inside a range. A moving window's
* failures are one violation while no check passes between them; a count since a reset, or one
* fixed period, is one violation however often it is checked. Each is reported by its worst
* window and listed in the range it began in.
*
* @param context the call's context
* @param rules the resolved rules
* @param range the range, epoch nanoseconds
* @returns the violations, ordered by window start and then by rule
*/
function scanDutyViolations(context, rules, range) {
	const found = [];
	rules.forEach((rule, order) => {
		if (rule.severity === "violation") for (const failure of ruleViolations(context, rule, range)) found.push({
			order,
			label: rule.label,
			failure
		});
	});
	return found.sort((a, b) => {
		const aStart = a.failure.evaluation.window.start;
		const bStart = b.failure.evaluation.window.start;
		return aStart < bStart ? -1 : aStart > bStart ? 1 : a.order - b.order;
	}).map(({ label, failure }) => ({
		label,
		window: spanText(failure.evaluation.window),
		used: measureText(failure.evaluation.used),
		limit: measureText(failure.evaluation.limit)
	}));
}

export { Unrepresentable, clipRuns, evaluateDutyRules, prepareDutyCall, readStatusList, restPairs, runsOf, scanDutyViolations, timeIn, walkBoundaries };