import { Value, ValueType, numberValue, stringValue, boolValue, uomValue, datetimeValue, errorValue, type DatetimeGrain } from "@solve-js/vm/Value"; import type { LineExecutionContext } from "@solve-js/vm/VM"; import { valueKindName } from "@solve-js/vm/VMConversion"; import { calendarOf } from "@solve-js/calendar/DateCalendar"; import { isWeekend } from "@solve-js/vm/BusinessDays"; import { weekOf } from "@solve-js/calendar/WeekShape"; import { dayNumber, isoWeekNumber } from "@solve-js/calendar/Gregorian"; import { convertUnit, getMeasure } from "@solve-js/uom/UomConverter"; import { parseIso8601, unixTimestampToEpochMs, formatIso8601Local } from "../Iso8601"; import { writeDurationInUnit } from "@solve-js/packages/time/IsoDuration"; /** * `CALL_PLUGIN` handlers backing the datetime package's workdays/weekday/ * timestamp features (see `DatetimePackage.ts`). Grouped in one file since * they're all small, single-purpose Value -> Value functions with no * shared state, mirrors `time/parselets/TimezonePluginFunctions.ts`'s * organization for the same kind of grouping. * * Every handler that reads a date field does so through the calendar backend * on its execution context (`calendarOf(context)`), so the weekday it names * is the one the VM's own date opcodes would land on for the same engine. */ /** * `workdays in ` -> the number of Mon-Fri workdays in that span, * as a plain Number. * * SCOPE DECISION (documented here and in `WorkdaysInParselet.ts`): no * anchor date is specified by this phrase's grammar at all, "workdays in * 3 weeks" doesn't say "starting when", so this is computed via a pure * deterministic ratio (5 workdays per full 7-day week, plus the remainder * capped at 5) rather than walking an actual calendar from "now". That * would make the result depend on which day of the week "now" happens to * be when evaluated, a non-deterministic, hard-to-test result for the * exact same input expression. This IS anchor-independent and exact for * any whole-week span (3 weeks = 21 days = exactly 15 workdays, regardless * of start day); for a partial-week remainder it's a reasonable capped * approximation, not a real calendar walk. Weekends-only by nature: with no * anchor date there is no calendar day to test against a holiday calendar, so * unlike the offset/`between` forms this consults none. See * `DatetimePackage.ts`'s holiday scope note. */ function workdaysInDurationHandler(args: Value[]): Value { const v = args[0]; let totalDays: number; if (v.type === ValueType.Uom && v.unit) { const measure = getMeasure(v.unit); if (measure !== "time") { return errorValue( "WORKDAYS_IN_EXPECTED_DURATION", `"workdays in" expects a time duration, got unit "${v.unit}"` ); } totalDays = convertUnit(v.toNumber(), v.unit, "day"); } else { // A bare Number is treated as already being a count of days. totalDays = v.toNumber(); } // Counted on the magnitude, with the sign put back afterwards. Running // the ratio directly on a negative day count borrowed a whole week from // Math.floor() and then handed the borrowed days back through the // remainder, so "workdays in -3 days" answered -1 instead of -3 and // "workdays in -10 days" answered -6 instead of -8. A negative span // reaches here whenever the duration came from a variable or a // subtraction rather than a typed literal. const sign = totalDays < 0 ? -1 : 1; const magnitudeDays = Math.abs(totalDays); const fullWeeks = Math.floor(magnitudeDays / 7); const remainderDays = magnitudeDays - fullWeeks * 7; const workdays = sign * (fullWeeks * 5 + Math.min(remainderDays, 5)); return numberValue(workdays); } const WEEKDAY_NAMES = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", ]; /** * Guards the date-field extractors below (weekday/month/week/is-a-weekend). * * The grammar-driven call sites always build a Datetime by construction, * but the `as` converter forms don't: ` as week` reaches the same * handler, so `90 days as week` would otherwise read a duration's raw ms as * if it were an epoch and answer "week 1" with a straight face. Returning * an error instead is the difference between a wrong answer and a * diagnosable one. */ function asEpochMs(value: Value, fieldName: string): number | Value { if (value.type === ValueType.Datetime) return value.toNumber(); return errorValue( "DATE_FIELD_EXPECTED_DATE", `"${fieldName}" expects a date, but got ${valueKindName(value)}.` ); } /** * `day of the week on ` / `what day is it in ` / * ` as weekday` -> the weekday name (e.g. "Tuesday") as a String. * * The text is English, and the value records which weekday it names * (`Value.calendarName`, #757), so the formatter writes it in the reader's * language (`Dienstag` under `de`) while a comparison with `"Tuesday"` still * holds. */ function weekdayOnDateHandler(args: Value[], context?: LineExecutionContext): Value { const epochMs = asEpochMs(args[0], "weekday"); if (typeof epochMs !== "number") return epochMs; return namedFromDate("weekday", calendarOf(context).fields(epochMs).weekday, WEEKDAY_NAMES); } /** A weekday or month name as a String that records which one it is. See `Value.calendarName`. */ function namedFromDate(kind: "weekday" | "month", index: number, names: readonly string[]): Value { const value = stringValue(names[index]); value.calendarName = { kind, index }; return value; } const MONTH_NAMES = [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December", ]; /** * `what month is it on ` / ` as month` -> the month name * (e.g. "December") as a String value. * * English text that records which month it names, exactly like the weekday * directly above, so the formatter writes it in the reader's language (`März` * under `de`, #757) and the two neighbouring fields agree about localisation. */ function monthOnDateHandler(args: Value[], context?: LineExecutionContext): Value { const epochMs = asEpochMs(args[0], "month"); if (typeof epochMs !== "number") return epochMs; return namedFromDate("month", calendarOf(context).fields(epochMs).month0, MONTH_NAMES); } /** * `what week is it on ` / ` as week` -> the ISO-8601 week * number (1-53) as a plain Number. * * The local calendar date is read through the backend; the week it falls in * is then zone-free arithmetic (`calendar/Gregorian.ts`'s `isoWeekNumber`), * which is where the Monday-start, first-Thursday rule lives. */ function weekOnDateHandler(args: Value[], context?: LineExecutionContext): Value { const epochMs = asEpochMs(args[0], "week"); if (typeof epochMs !== "number") return epochMs; const d = calendarOf(context).fields(epochMs); return numberValue(isoWeekNumber(d.year, d.month0, d.day)); } /** True for a weekend day: the engine's weekend (`date.weekend`, #702), Saturday and Sunday unless set. */ function isWeekendDate(epochMs: number, context?: LineExecutionContext): boolean { return isWeekend(epochMs, calendarOf(context), weekOf(context).weekend); } /** ` is a weekend` -> Boolean. */ function isWeekendOnDateHandler(args: Value[], context?: LineExecutionContext): Value { const epochMs = asEpochMs(args[0], "is a weekend"); if (typeof epochMs !== "number") return epochMs; return boolValue(isWeekendDate(epochMs, context)); } /** * ` is a workday` / `is a weekday` -> Boolean. * * Every day outside the engine's weekend (Monday to Friday unless * `date.weekend` says otherwise, #702), and deliberately blind to the holiday * calendar: this answers "is this a weekday", a question about the week's * shape, not "is this a working day in my region". Keeping it weekend-based means the predicate is a * pure function of the date, decidable without any host configuration, and * `is a workday` stays the exact complement of `is a weekend`. The working-day * ARITHMETIC (offsets and `between`) is what consults the calendar. See * `DatetimePackage.ts`'s holiday scope note. */ function isWorkdayOnDateHandler(args: Value[], context?: LineExecutionContext): Value { const epochMs = asEpochMs(args[0], "is a workday"); if (typeof epochMs !== "number") return epochMs; return boolValue(!isWeekendDate(epochMs, context)); } /** * ` between and ` -> the UNSIGNED span between the two * endpoints as a `Uom("ms")`, which the caller then converts into the * requested unit via `UOM_CONVERT_IN` (identical to how * `UntilSinceParselet` feeds that opcode). * * A plugin function rather than a `SUB`: "between" has no direction in * English, so `days between A and B` must equal `days between B and A`, * and there is no ABS opcode to apply after a signed subtraction. * Arguments arrive in push order, so `args[0]` is the first endpoint as * written, though by construction the result doesn't depend on that. */ /** Milliseconds in a day, the factor the unit machinery converts an "ms" span by. */ const MS_PER_DAY = 86_400_000; /** * The span between two dates, as an unsigned "ms" quantity the unit * machinery then converts into whatever unit the line asked for. * * Measured as a calendar distance when both endpoints are local midnight, * and as elapsed time otherwise. The difference is a daylight-saving * transition: a 23- or 25-hour day used to leak into the answer, so * `days between 01/01/2024 and 01/06/2024` was 151.96 days in London and * 152.04 in Auckland, when the answer is 152 days for every reader. The * hour is real, but it is not what "how many days between these two dates" * asks: two calendar days apart is two days wherever you read it. * * The boundary: either endpoint carrying a time of day makes this elapsed * time again, because `hours between 09:00 and 17:30` is a duration and the * transition genuinely belongs in it. */ function spanBetweenDatesHandler(args: Value[], context?: LineExecutionContext): Value { const from = args[0].toNumber(); const to = args[1].toNumber(); const calendar = calendarOf(context); const fromFields = calendar.fields(from); const toFields = calendar.fields(to); const bothAreDates = calendar.localMidnight(fromFields.year, fromFields.month0, fromFields.day) === from && calendar.localMidnight(toFields.year, toFields.month0, toFields.day) === to; if (bothAreDates) { const days = Math.abs( dayNumber(toFields.year, toFields.month0, toFields.day) - dayNumber(fromFields.year, fromFields.month0, fromFields.day), ); return uomValue(days * MS_PER_DAY, "ms"); } return uomValue(Math.abs(from - to), "ms"); } /** Days in a week, which is how far apart two of the same weekday are. */ const DAYS_PER_WEEK = 7; /** * How many times a weekday falls between two dates, both ends included. * * `fridays between 01/06/2026 and 31/08/2026` is 13. The nearest approximation * before this was `weeks between`, which ignores which weekday the range starts * and ends on and so is wrong at both ends. * * Both endpoints are included, deliberately: a range written to a Friday was * written to include it, and someone counting shifts or rent days means the * ones on the boundary. It follows that a single day that is the weekday counts * as one, and `friday until ` counts today. * * The endpoints are read as calendar days rather than instants, so a time of * day on either (which `until` and `since` always carry, since they measure * from now) neither adds nor removes a day. Order does not matter: a weekday * falls in a range the same number of times whichever end you start from. */ function weekdaysBetweenHandler(args: Value[], context?: LineExecutionContext): Value { const target = Math.trunc(args[2].toNumber()); if (!Number.isInteger(target) || target < 0 || target > 6) { return errorValue("INVALID_WEEKDAY", `A weekday is a day of the week, and ${args[2].toNumber()} is not one`); } const calendar = calendarOf(context); const a = calendar.fields(args[0].toNumber()); const b = calendar.fields(args[1].toNumber()); const dayA = dayNumber(a.year, a.month0, a.day); const dayB = dayNumber(b.year, b.month0, b.day); const start = Math.min(dayA, dayB); const end = Math.max(dayA, dayB); const startWeekday = start === dayA ? a.weekday : b.weekday; // The first occurrence at or after the start, then every seventh day. const first = start + (((target - startWeekday) % DAYS_PER_WEEK) + DAYS_PER_WEEK) % DAYS_PER_WEEK; if (first > end) return numberValue(0); return numberValue(Math.floor((end - first) / DAYS_PER_WEEK) + 1); } /** * ` to date` / ` to date` -> a Datetime * value. Dispatches on the RUNTIME value type (a `CALL_PLUGIN` handler * runs at VM-execution time, after the left-hand expression has already * been evaluated to a concrete Value) rather than at parse time, since the * left-hand expression could be a string literal, a bare number literal, * or an arbitrary variable/expression of either type. * * Real ambiguity resolved here: a bare Number could be a SECONDS or a * MILLISECONDS Unix timestamp for the same real-world date. See * `Iso8601.ts`'s `unixTimestampToEpochMs()`/`MS_TIMESTAMP_THRESHOLD` doc * comment for the exact magnitude threshold and reasoning. */ function toDateFromAnyHandler(args: Value[], context?: LineExecutionContext): Value { const v = args[0]; if (v.type === ValueType.Datetime) { return v; // already a date — "date to date" is a harmless no-op } if (v.type === ValueType.String) { const ms = parseIso8601(v.value as string, calendarOf(context)); if (ms === null) { return errorValue( "INVALID_ISO8601_STRING", `"${v.value}" is not a recognizable ISO8601 date/time string` ); } return datetimeValue(ms); } const ms = unixTimestampToEpochMs(v.toNumber()); // Past this a JavaScript date is invalid, and it was written as NaN text: // `(2^53) as iso8601` answered "NaN-NaN-NaNTNaN:NaN:NaN-NaN:NaN". Found by the // adversarial sweep's numeric edges. Written as a negated `<=` so NaN is // refused too. if (!(Math.abs(ms) <= LATEST_INSTANT_MS)) { return errorValue( "DATE_OUT_OF_RANGE", "This timestamp is outside the dates the engine can hold, which reach about 273,000 years either side of 1970.", ); } return datetimeValue(ms); } /** The furthest instant from 1970 a JavaScript date can hold, in milliseconds: a hundred million days. */ const LATEST_INSTANT_MS = 8.64e15; /** * ` as iso8601`: a date, a Unix timestamp or ISO 8601 text, written as * ISO 8601. * * It formatted `value.toNumber()` as epoch milliseconds whatever the value was, * so a timestamp in seconds, the usual kind, was read as milliseconds: * `1710000000 as iso8601` answered a day in January 1970. It now reads its * argument as `to date` does ({@link toDateFromAnyHandler}): a date as it is, a * number through the same seconds-or-milliseconds threshold, text through the * ISO 8601 parser. A length of time is written as an ISO 8601 duration * (`PT1H30M`, #760). Anything else (another quantity, money, true or false, a * list) is refused by name rather than read through its number. * * @param value - The value to write. * @param context - The line's context, for the calendar backend. * @returns The ISO 8601 text, or an error Value. */ export function asIso8601(value: Value, context?: LineExecutionContext): Value { // A length of time is written as an ISO 8601 duration, `90 minutes as // iso8601` as PT1H30M (#760). It was refused here, and before that read as // epoch milliseconds. See packages/time/IsoDuration.ts. if (value.type === ValueType.Uom && value.unit !== undefined) { const duration = writeDurationInUnit(value.toNumber(), value.unit); if (duration === null) { return errorValue("AS_ISO8601_DURATION_TOO_LONG", "This length of time is too large to write as an ISO 8601 duration with exact digits."); } if (duration !== undefined) return stringValue(duration); } const readable = value.type === ValueType.Datetime || value.type === ValueType.Number || value.type === ValueType.String; if (!readable) { return errorValue( "AS_ISO8601_NEEDS_DATE", "as iso8601 writes a date, a Unix timestamp (in seconds or milliseconds) or ISO 8601 text, and this value is none of them.", ); } const date = toDateFromAnyHandler([value], context); if (date.type === ValueType.Error) return date; return stringValue(formatIso8601Local(date.toNumber(), calendarOf(context))); } /** Whether a value is something `to date` reads: a date, a Unix timestamp or ISO 8601 text. */ function readsAsDate(value: Value): boolean { return value.type === ValueType.Datetime || value.type === ValueType.Number || value.type === ValueType.String; } /** * ` as date`, the `as` spelling of `to date` (#701): a Unix timestamp * (in seconds or milliseconds, read through the same threshold) or ISO 8601 * text, as a date; a date as it is. A quantity, money, true or false or a list * is refused by name, as `as iso8601` refuses it, rather than read through its * number. * * @param value - The value to read. * @param context - The line's context, for the calendar backend. * @returns The date, or an error Value. */ export function asDate(value: Value, context?: LineExecutionContext): Value { if (!readsAsDate(value)) { return errorValue("AS_DATE_NEEDS_TIMESTAMP", "as date reads a Unix timestamp (in seconds or milliseconds), ISO 8601 text or a date, and this value is none of them."); } return toDateFromAnyHandler([value], context); } /** * ` as timestamp`, the `as` spelling of `to timestamp` (#701): a date, * or ISO 8601 text, as a Unix timestamp in whole seconds. A number is read as * a timestamp first, as `as date` reads it, so one in milliseconds comes back * in seconds rather than divided twice. * * @param value - The value to write. * @param context - The line's context, for the calendar backend. * @returns The timestamp in seconds, or an error Value. */ export function asTimestamp(value: Value, context?: LineExecutionContext): Value { const date = asDate(value, context); if (date.type === ValueType.Error) { return date.errorCode === "AS_DATE_NEEDS_TIMESTAMP" ? errorValue("AS_TIMESTAMP_NEEDS_DATE", "as timestamp writes a date, ISO 8601 text or a Unix timestamp, and this value is none of them.") : date; } return toTimestampFromAnyHandler([date], context); } /** * ` as time` (#708): a date and time shown as the time of day alone, * the way a clock time is. The instant does not change, only how it is shown, * and the time is counted from its own day, so it shows no day shift until * arithmetic moves it. Only a date is read: a number or text has no time of * day of its own to show, and `5 as time` would otherwise be a moment in * 1970, so each is refused, as a quantity is. * * @param value - The value to show. * @param _context - The line's context; the day is the value's own, so no calendar is read. * @returns The same instant with the time-of-day grain, or an error Value. */ export function asTime(value: Value, _context?: LineExecutionContext): Value { if (value.type !== ValueType.Datetime) { return errorValue("AS_TIME_NEEDS_DATE", "as time shows a date and time as its time of day, and this value is not a date. To read a Unix timestamp first, write it as a date: 1710000000 as date as time."); } const ms = value.toNumber(); return datetimeValue(ms, "time", value.zone, ms); } /** * Attach the grain and the zone an ISO literal's own text named. See * {@link datetimeLiteralGrain}. */ function datetimeLiteralGrainHandler(args: Value[]): Value { const instant = args[0]; const grain = args[1].value as DatetimeGrain; const zone = args[2].value as string; return datetimeValue(instant.toNumber(), grain, zone === "" ? undefined : zone); } /** * ` to timestamp` / `current timestamp` -> a Unix timestamp in * SECONDS (rounded down), as a plain Number. * * Also accepts a String (parsed as ISO8601 first) for robustness, though * the primary grammar this backs (`ToTimestampParselet.ts`) always feeds * it an already-Datetime-typed left-hand expression; `CurrentTimestampParselet.ts` * feeds it a fresh `DATE_NOW` result via the same opcode, reusing this one * handler for both call sites. */ function toTimestampFromAnyHandler(args: Value[], context?: LineExecutionContext): Value { const v = args[0]; if (v.type === ValueType.String) { const ms = parseIso8601(v.value as string, calendarOf(context)); if (ms === null) { return errorValue( "INVALID_ISO8601_STRING", `"${v.value}" is not a recognizable ISO8601 date/time string` ); } return numberValue(Math.floor(ms / 1000)); } // Datetime (epoch ms) or a plain Number already representing epoch ms. return numberValue(Math.floor(v.toNumber() / 1000)); } /** * Count the Mon-Fri workdays in a duration. * * Uses a deterministic ratio rather than walking a calendar, because the * phrase carries no anchor date. See the handler for the full reasoning. */ export const workdaysInDuration = workdaysInDurationHandler; /** * Day-of-week name for a date, as a String value. */ export const weekdayOnDate = weekdayOnDateHandler; /** * Month name for a date, as a String value. */ export const monthOnDate = monthOnDateHandler; /** * ISO week number for a date, as a Number value. */ export const weekOnDate = weekOnDateHandler; /** * Whether a date falls on a Saturday or Sunday. */ export const isWeekendOnDate = isWeekendOnDateHandler; /** * Whether a date falls Monday to Friday. The complement of * {@link isWeekendOnDate}, with no holiday calendar involved. */ export const isWorkdayOnDate = isWorkdayOnDateHandler; /** * Elapsed time between two dates, as a duration value. */ export const spanBetweenDates = spanBetweenDatesHandler; /** `fridays between A and B`, and the `until`/`since` spellings of the same count. */ export const weekdaysBetween = weekdaysBetweenHandler; /** * Coerce a Unix timestamp, ISO 8601 string or epoch number to a * Datetime. */ export const toDateFromAny = toDateFromAnyHandler; /** * Coerce a date to whole Unix seconds. The inverse of * {@link toDateFromAny}. */ export const toTimestampFromAny = toTimestampFromAnyHandler; /** * Fasten the grain and the zone an ISO literal named onto the Datetime the * `DATE_LITERAL` opcode just pushed. * * Reached only from `DateLiteralParselet` and only for a literal that carries * a time of day: a plain calendar date is the opcode on its own, and pays * nothing for this. The arguments are the value, the grain as a string and the * zone reference (empty when the literal named none). A plugin call rather * than a bytecode operand, because the operand would move * `SerializedBytecode` and with it every stored snapshot. */ export const datetimeLiteralGrain = datetimeLiteralGrainHandler;