diff --git a/.changeset/cli-plan-command.md b/.changeset/cli-plan-command.md index 95780458..cb217d3b 100644 --- a/.changeset/cli-plan-command.md +++ b/.changeset/cli-plan-command.md @@ -8,6 +8,7 @@ - `--tz Europe/Paris` sets the time zone; by default it is the new `timezone` setting of `.gram/config.yaml` (or of your global config), and only then this machine's. `--available` says when you can cook, as many times as needed: `08:00-22:00` for every day, `fri=18:00-22:00` for a day of the week, `2026-10-09=none` for a date. By default it is the new `availability` setting of `.gram/config.yaml`, written the same way (`gram config set availability 08:00-22:00`), and only then all day - A wait written as a range (`~_{8-16h}`) is made longer or shorter to keep your own work out of the hours you are not available, and the plan says which one and why; what cannot be fixed is listed at the top - `--find 2026-10-12/2026-10-15` lists the serving times that work between two moments, at your meal times (`--meal-times 12:30,20:00`, or the new `mealTimes` setting of `.gram/config.yaml`), best first, and why each of the others does not +- A date that does not exist (`--serve "2026-02-30 20:00"`, a 31st of April in `--find` or `--available`) and a `--now` that cannot be read are refused with a message saying what is expected, instead of planning for another day or stopping with an internal error - `--format text|md|html|json` picks the output, and `--ics plan.ics` also writes a calendar file with an event for every visit to the kitchen, an alarm before it, and the lists in its description - `--mise-en-place`, `--rests`, `--scale` and `--stock` work as they do in `gram view`; the mise en place mode also decides what goes in each visit's list of things to take out - `gram export` and `gram print` render the run sheet instead of the recipe via `--view run-sheet` (the recipe remains the default), supporting `--serve`, `--tz`, and `--available`; without `--serve`, the schedule is organized in relative countdown days (`D-2`, `D-1`, `Day D`). The print document formats one day per page, and `gram export` automatically outputs to `.run-sheet.md` (or `.html`, `.txt`) unless `--output` is specified diff --git a/.changeset/scheduler-package.md b/.changeset/scheduler-package.md index d4676a17..82f4dbdf 100644 --- a/.changeset/scheduler-package.md +++ b/.changeset/scheduler-package.md @@ -12,3 +12,4 @@ - `runSheet(plan)` groups a plan, or a bare schedule, into the days of the recipe (and says which mise en place mode it was made in), the visits to the kitchen (a wait of an hour or more ends one) and the waits that go on without the cook; with the graph and the context, it also says how early each visit could be done, and which exact wait holds it in place; each visit also says when each of its sections starts (`sectionStarts`) - `findServeTimes()` tries each day of a range at your meal times and ranks the serving times that work, with the reasons of the others; `earliestServe()` gives the first one that works if the cook starts now - `parseAvailability(entries)` reads when the cook is available from entries like `08:00-22:00`, `fri=18:00-22:00` or `2026-10-09=none` (the syntax of `gram plan --available` and of the `availability` setting), and says which part is wrong when it cannot +- `isCalendarDate("2026-02-30")` tells a real day from a string that only looks like one; the scheduler refuses a date that does not exist (a 30th of February, a 31st of April) everywhere it reads one, instead of moving it to the next month diff --git a/packages/cli/src/services/plan-flags.ts b/packages/cli/src/services/plan-flags.ts index 05b9f6b7..38a06a11 100644 --- a/packages/cli/src/services/plan-flags.ts +++ b/packages/cli/src/services/plan-flags.ts @@ -1,7 +1,9 @@ import type { Availability } from "@gram-lang/scheduler"; import { WEEKDAYS, + isCalendarDate, parseAvailability as parseEntries, + parseInstant, } from "@gram-lang/scheduler"; import { ExitCode, GramCLIError } from "../errors"; @@ -42,9 +44,33 @@ export function parseServe(value: unknown): string { `Expected --serve like "2026-10-11 13:00" (a local date and time), got "${text}".`, ); } + if (!isCalendarDate(m[1]!)) { + return fail(`--serve "${text}": ${m[1]} is not a day of the calendar.`); + } return `${m[1]}T${m[2]!.padStart(2, "0")}:${m[3]}`; } +/** + * `--now`: the present, an instant with `Z` or an offset + * ("2026-10-11T11:00:00Z") or a local date and time in the time zone of the + * plan. Without it, now. Checked here so a typo is a message, not a stack + * trace raised while the plan is drawn. + */ +export function parseNow(value: unknown, timeZone: string): string { + if (value === undefined || value === null || value === "") { + return new Date().toISOString(); + } + const text = String(value).trim(); + try { + parseInstant(text, timeZone); + return text; + } catch { + return fail( + `Expected --now like "2026-10-11T11:00:00Z" or "2026-10-11T13:00" (a local date and time), got "${text}".`, + ); + } +} + const isTimeZone = (zone: string) => { try { new Intl.DateTimeFormat("en", { timeZone: zone }); @@ -165,7 +191,10 @@ export function parseFindRange(value: unknown): { from: string; to: string } { const parts = text.split("/"); if ( parts.length !== 2 || - !parts.every((p) => LOCAL_BOUND.test(p.trim())) || + !parts.every( + (p) => + LOCAL_BOUND.test(p.trim()) && isCalendarDate(p.trim().slice(0, 10)), + ) || parts[0]!.trim() > parts[1]!.trim() ) { return fail( diff --git a/packages/cli/src/services/plan-options.ts b/packages/cli/src/services/plan-options.ts index 88565bd8..407add3f 100644 --- a/packages/cli/src/services/plan-options.ts +++ b/packages/cli/src/services/plan-options.ts @@ -10,6 +10,7 @@ import { ExitCode, GramCLIError } from "../errors"; import { collectFlag, parseAvailability, + parseNow, parseServe, parseTimeZone, } from "./plan-flags"; @@ -59,13 +60,14 @@ export function resolveKitchenContext( rawArgs: string[] | undefined, config: { timezone?: string; availability?: unknown }, ): KitchenContext { + const timeZone = parseTimeZone(args.tz, config.timezone); return { - timeZone: parseTimeZone(args.tz, config.timezone), + timeZone, availability: parseAvailability( collectFlag(rawArgs ?? [], "available"), config.availability, ), - now: (args.now as string | undefined) ?? new Date().toISOString(), + now: parseNow(args.now, timeZone), }; } diff --git a/packages/cli/tests/plan-cli.test.ts b/packages/cli/tests/plan-cli.test.ts index 60ff3253..2d018ec6 100644 --- a/packages/cli/tests/plan-cli.test.ts +++ b/packages/cli/tests/plan-cli.test.ts @@ -211,6 +211,29 @@ describe("gram plan", () => { expect(code).toBe(1); } }); + + it("refuses a day the calendar does not have, or a present it cannot read, with a message and no stack", () => { + for (const [bad, said] of [ + [ + ["--serve", "2026-02-30 20:00"], + "2026-02-30 is not a day of the calendar", + ], + [ + ["--available", "2026-02-30=none"], + 'Unknown --available key "2026-02-30"', + ], + [["--now", "banana"], 'Expected --now like "2026-10-11T11:00:00Z"'], + ] as const) { + const args = [...PLAN]; + const at = args.indexOf(bad[0]); + if (at === -1) args.push(...bad); + else args[at + 1] = bad[1]; + const { code, out, err } = gram(...args); + expect(code).toBe(1); + expect(out + err).toContain(said); + expect(out + err).not.toContain(" at "); + } + }); }); describe("gram plan without a serving time", () => { diff --git a/packages/cli/tests/plan-flags.test.ts b/packages/cli/tests/plan-flags.test.ts index f5e01a25..bc41ef45 100644 --- a/packages/cli/tests/plan-flags.test.ts +++ b/packages/cli/tests/plan-flags.test.ts @@ -5,6 +5,8 @@ import { resolveExportView } from "../src/services/plan-options"; import { collectFlag, parseAvailability, + parseFindRange, + parseNow, parseServe, parseTimeZone, } from "../src/services/plan-flags"; @@ -54,6 +56,57 @@ describe("parseServe", () => { ); expect(messageOf(() => parseServe(undefined))).toContain("--serve"); }); + + it("refuses a day the calendar does not have, instead of moving it to March", () => { + expect(messageOf(() => parseServe("2026-02-30 20:00"))).toBe( + '--serve "2026-02-30 20:00": 2026-02-30 is not a day of the calendar.', + ); + expect(parseServe("2028-02-29 20:00")).toBe("2028-02-29T20:00"); + }); +}); + +describe("parseFindRange", () => { + it("reads two local bounds", () => { + expect(parseFindRange("2026-10-12/2026-10-15 20:00")).toEqual({ + from: "2026-10-12", + to: "2026-10-15T20:00", + }); + }); + + it("refuses a bound the calendar does not have", () => { + expect(messageOf(() => parseFindRange("2026-02-28/2026-02-31"))).toContain( + 'Expected --find like "2026-10-12/2026-10-15"', + ); + expect( + messageOf(() => parseFindRange("2026-02-30 12:00/2026-03-02")), + ).toContain("--find"); + }); +}); + +describe("parseNow", () => { + it("is now without a value", () => { + const before = Date.now(); + const now = Date.parse(parseNow(undefined, "Europe/Paris")); + expect(now).toBeGreaterThanOrEqual(before); + }); + + it("takes an instant or a local date and time, as written", () => { + expect(parseNow("2026-10-01T09:00:00Z", "Europe/Paris")).toBe( + "2026-10-01T09:00:00Z", + ); + expect(parseNow("2026-10-10T10:00", "Europe/Paris")).toBe( + "2026-10-10T10:00", + ); + }); + + it("refuses what it cannot read, saying what it expects", () => { + expect(messageOf(() => parseNow("banana", "Europe/Paris"))).toBe( + 'Expected --now like "2026-10-11T11:00:00Z" or "2026-10-11T13:00" (a local date and time), got "banana".', + ); + expect(messageOf(() => parseNow("2026-02-30T10:00", "UTC"))).toContain( + "--now", + ); + }); }); describe("parseTimeZone", () => { @@ -128,6 +181,12 @@ describe("parseAvailability", () => { }); }); + it("refuses a date the calendar does not have, which would never apply", () => { + expect(messageOf(() => parseAvailability(["2026-02-30=none"]))).toContain( + 'Unknown --available key "2026-02-30"', + ); + }); + it("reads a weekday in any case, and none as not available", () => { expect(parseAvailability(["SUN=none"])).toMatchObject({ weekdays: { sun: [] }, diff --git a/packages/docs/src/content/docs/docs/reference/api/scheduler.mdx b/packages/docs/src/content/docs/docs/reference/api/scheduler.mdx index 2d712a91..e0338911 100644 --- a/packages/docs/src/content/docs/docs/reference/api/scheduler.mdx +++ b/packages/docs/src/content/docs/docs/reference/api/scheduler.mdx @@ -403,10 +403,13 @@ function parseLocalIso(value: string, timeZone: string): number; // "2026-10-11T function parseInstant(value: string, timeZone: string): number; // ISO instant (with 'Z' or UTC offset) or local time function toLocalIso(utcMinutes: number, timeZone: string): string; // → "2026-10-11T13:00" function toUtcIso(utcMinutes: number): string; // → "2026-10-11T11:00:00Z" +function isCalendarDate(value: string): boolean; // "2028-02-29" → true, "2026-02-30" → false ``` During daylight saving time transitions, an invalid local time (e.g. 02:30 when clocks spring forward) shifts to the next valid time; an ambiguous local time (occurring twice when clocks fall back) resolves to its first occurrence. +A date that does not exist (a 30th of February, a 31st of April) is refused with a `RangeError` rather than moved to the next month. + ## Related resources diff --git a/packages/docs/src/content/docs/fr/docs/reference/api/scheduler.mdx b/packages/docs/src/content/docs/fr/docs/reference/api/scheduler.mdx index d15625ca..c616b725 100644 --- a/packages/docs/src/content/docs/fr/docs/reference/api/scheduler.mdx +++ b/packages/docs/src/content/docs/fr/docs/reference/api/scheduler.mdx @@ -403,10 +403,13 @@ function parseLocalIso(value: string, timeZone: string): number; // "2026-10-11T function parseInstant(value: string, timeZone: string): number; // instant ISO (avec 'Z' ou décalage UTC) ou heure locale function toLocalIso(utcMinutes: number, timeZone: string): string; // → "2026-10-11T13:00" function toUtcIso(utcMinutes: number): string; // → "2026-10-11T11:00:00Z" +function isCalendarDate(value: string): boolean; // "2028-02-29" → true, "2026-02-30" → false ``` Lors du passage à l'heure d'été, une heure locale inexistante (par exemple 02:30 lors de l'avance des horloges) est automatiquement décalée vers la première heure valide suivante ; lors du passage à l'heure d'hiver, une heure ambiguë (apparaissant deux fois lors du recul) est résolue sur sa première occurrence. +Une date qui n'existe pas (un 30 février, un 31 avril) est refusée par une `RangeError` au lieu de glisser au mois suivant. + ## Ressources associées diff --git a/packages/language-server/src/session.ts b/packages/language-server/src/session.ts index d506827b..7c2dbaae 100644 --- a/packages/language-server/src/session.ts +++ b/packages/language-server/src/session.ts @@ -1,4 +1,5 @@ import type { ScaleRequest } from "@gram-lang/kitchen"; +import { isCalendarDate } from "@gram-lang/scheduler"; /** * What the cook chose for this sitting with one recipe, sent by the client in @@ -23,7 +24,7 @@ const SERVE_AT = /^(\d{4}-\d{2}-\d{2})[T ](\d{1,2}):(\d{2})$/; function parseServeAt(raw: unknown): string | undefined { if (typeof raw !== "string") return undefined; const m = SERVE_AT.exec(raw.trim()); - if (!m) return undefined; + if (!m || !isCalendarDate(m[1]!)) return undefined; const hour = Number(m[2]); const minute = Number(m[3]); if (hour > 23 || minute > 59) return undefined; diff --git a/packages/language-server/tests/session.test.ts b/packages/language-server/tests/session.test.ts index aec65e5e..7b0710d5 100644 --- a/packages/language-server/tests/session.test.ts +++ b/packages/language-server/tests/session.test.ts @@ -46,6 +46,8 @@ describe("parseSession", () => { }), ).toEqual({}); expect(parseSession({ serveAt: "2026-10-11T25:00" })).toEqual({}); + // Shaped like a date, but not a day of the calendar. + expect(parseSession({ serveAt: "2026-02-30T20:00" })).toEqual({}); expect(parseSession({ scale: { type: "target", id: "", qty: 3 } })).toEqual( {}, ); diff --git a/packages/scheduler/src/index.ts b/packages/scheduler/src/index.ts index 564fe39c..0273d260 100644 --- a/packages/scheduler/src/index.ts +++ b/packages/scheduler/src/index.ts @@ -65,7 +65,13 @@ export type { TimeRange, } from "./projection"; export { WEEKDAYS, type Weekday } from "./time"; -export { parseInstant, parseLocalIso, toLocalIso, toUtcIso } from "./time"; +export { + isCalendarDate, + parseInstant, + parseLocalIso, + toLocalIso, + toUtcIso, +} from "./time"; export { DEFAULT_MEAL_TIMES, EARLIEST_SERVE_HORIZON_DAYS, diff --git a/packages/scheduler/src/parse-availability.ts b/packages/scheduler/src/parse-availability.ts index f295f97e..d7d81dd8 100644 --- a/packages/scheduler/src/parse-availability.ts +++ b/packages/scheduler/src/parse-availability.ts @@ -1,5 +1,5 @@ import type { Availability, TimeRange } from "./projection"; -import { WEEKDAYS, type Weekday } from "./time"; +import { WEEKDAYS, type Weekday, isCalendarDate } from "./time"; /** The cook is there all day: the availability when nothing says otherwise. */ export const ALL_DAY: Availability = { @@ -23,7 +23,6 @@ export type AvailabilityParse = | ({ ok: false } & AvailabilityProblem); const CLOCK = /^([01]?\d|2[0-4]):([0-5]\d)$/; -const DATE = /^\d{4}-\d{2}-\d{2}$/; function parseRanges(text: string): TimeRange[] | string { if (text === "none") return []; @@ -76,7 +75,7 @@ export function parseAvailability( } else if ((WEEKDAYS as readonly string[]).includes(key)) { const day = key as Weekday; weekdays[day] = [...(weekdays[day] ?? []), ...ranges]; - } else if (DATE.test(key)) { + } else if (isCalendarDate(key)) { dates[key] = [...(dates[key] ?? []), ...ranges]; } else { return { ok: false, reason: "key", entry, part: entry.slice(0, eq) }; diff --git a/packages/scheduler/src/time.ts b/packages/scheduler/src/time.ts index f6c782fb..d24025db 100644 --- a/packages/scheduler/src/time.ts +++ b/packages/scheduler/src/time.ts @@ -107,6 +107,33 @@ export function toUtcIso(utcMinutes: number): string { const LOCAL_ISO = /^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})$/; const DATE_ONLY = /^(\d{4})-(\d{2})-(\d{2})$/; +/** Days in a month (1-12) of a year, leap years included. */ +const daysInMonth = (year: number, month: number) => + new Date(Date.UTC(year, month, 0)).getUTCDate(); + +/** Whether a year, month (1-12) and day name a day that exists. */ +const isRealDay = (year: number, month: number, day: number) => + month >= 1 && month <= 12 && day >= 1 && day <= daysInMonth(year, month); + +/** + * Whether "YYYY-MM-DD" names a day of the calendar: "2026-02-30" has the shape + * of a date but is not one, and would otherwise roll over to March 2. + */ +export function isCalendarDate(value: string): boolean { + const m = DATE_ONLY.exec(value); + return m !== null && isRealDay(Number(m[1]), Number(m[2]), Number(m[3])); +} + +/** The year, month and day of "YYYY-MM-DD", refusing a day that does not exist. */ +function dateParts(date: string): [number, number, number] { + const m = DATE_ONLY.exec(date); + const parts = m?.slice(1).map(Number) as [number, number, number] | undefined; + if (!parts || !isRealDay(...parts)) { + throw new RangeError(`"${date}" is not a valid date`); + } + return parts; +} + /** Minutes since the epoch of a local wall-clock reading read as if it were UTC. */ function wallClockMinutes( year: number, @@ -167,14 +194,7 @@ export function parseLocalIso(value: string, timeZone: string): number { number, number, ]; - if ( - hour > 23 || - minute > 59 || - month < 1 || - month > 12 || - day < 1 || - day > 31 - ) { + if (hour > 23 || minute > 59 || !isRealDay(year, month, day)) { throw new RangeError(`"${value}" is not a valid date-time`); } return localToUtc(year, month, day, hour * 60 + minute, timeZone); @@ -200,30 +220,24 @@ export function localDateTime( minuteOfDay: number, timeZone: string, ): number { - const m = DATE_ONLY.exec(date); - if (!m) throw new RangeError(`"${date}" is not a valid date`); - const [year, month, day] = m.slice(1).map(Number) as [number, number, number]; + const [year, month, day] = dateParts(date); return localToUtc(year, month, day, minuteOfDay, timeZone); } /** The local date `days` after `date` (negative: before), as "YYYY-MM-DD". */ export function addDays(date: string, days: number): string { - const m = DATE_ONLY.exec(date); - if (!m) throw new RangeError(`"${date}" is not a valid date`); - const [year, month, day] = m.slice(1).map(Number) as [number, number, number]; + const [year, month, day] = dateParts(date); const shifted = new Date(Date.UTC(year, month - 1, day + days)); return `${pad(shifted.getUTCFullYear(), 4)}-${pad(shifted.getUTCMonth() + 1)}-${pad(shifted.getUTCDate())}`; } /** Whole local days from `from` to `to` (both "YYYY-MM-DD"). */ export function daysBetween(from: string, to: string): number { - const a = DATE_ONLY.exec(from); - const b = DATE_ONLY.exec(to); - if (!a || !b) - throw new RangeError(`"${from}" or "${to}" is not a valid date`); - const ms = (m: RegExpExecArray) => - Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])); - return Math.round((ms(b) - ms(a)) / (MINUTES_PER_DAY * MS_PER_MINUTE)); + const ms = (date: string) => { + const [year, month, day] = dateParts(date); + return Date.UTC(year, month - 1, day); + }; + return Math.round((ms(to) - ms(from)) / (MINUTES_PER_DAY * MS_PER_MINUTE)); } /** "08:00" to minutes since midnight. */ diff --git a/packages/scheduler/tests/parse-availability.test.ts b/packages/scheduler/tests/parse-availability.test.ts index aa82d1f6..bb031f0f 100644 --- a/packages/scheduler/tests/parse-availability.test.ts +++ b/packages/scheduler/tests/parse-availability.test.ts @@ -45,6 +45,16 @@ describe("parseAvailability", () => { entry: "someday=08:00-22:00", part: "someday", }); + // Shaped like a date, but February has no 30th: it would never apply. + expect(parseAvailability(["2026-02-30=none"])).toEqual({ + ok: false, + reason: "key", + entry: "2026-02-30=none", + part: "2026-02-30", + }); + expect(parseAvailability(["2028-02-29=none"])).toMatchObject({ + ok: true, + }); expect(parseAvailability(["25:00-26:00"])).toMatchObject({ ok: false, reason: "range", diff --git a/packages/scheduler/tests/time.test.ts b/packages/scheduler/tests/time.test.ts index efe904fb..204701c6 100644 --- a/packages/scheduler/tests/time.test.ts +++ b/packages/scheduler/tests/time.test.ts @@ -7,6 +7,8 @@ import { import { addDays, daysBetween, + isCalendarDate, + localDateTime, parseClock, parseInstant, parseLocalIso, @@ -75,6 +77,33 @@ describe("local time", () => { expect(() => parseClock("8h")).toThrow(RangeError); }); + it("refuses a day the month does not have, instead of rolling over", () => { + expect(() => parseLocalIso("2026-02-30T20:00", PARIS)).toThrow( + '"2026-02-30T20:00" is not a valid date-time', + ); + expect(() => parseLocalIso("2026-04-31T20:00", PARIS)).toThrow(RangeError); + expect(() => parseLocalIso("2026-02-29T20:00", PARIS)).toThrow(RangeError); + expect(toLocalIso(parseLocalIso("2028-02-29T20:00", PARIS), PARIS)).toBe( + "2028-02-29T20:00", + ); + expect(() => addDays("2026-02-30", 1)).toThrow(RangeError); + expect(() => daysBetween("2026-02-28", "2026-02-31")).toThrow(RangeError); + expect(() => localDateTime("2026-06-31", 600, PARIS)).toThrow( + '"2026-06-31" is not a valid date', + ); + }); + + it("tells a day of the calendar from a date-shaped string", () => { + expect(isCalendarDate("2026-02-28")).toBe(true); + expect(isCalendarDate("2028-02-29")).toBe(true); + expect(isCalendarDate("2026-02-29")).toBe(false); + expect(isCalendarDate("2026-02-30")).toBe(false); + expect(isCalendarDate("2026-13-01")).toBe(false); + expect(isCalendarDate("2026-00-10")).toBe(false); + expect(isCalendarDate("2026-1-10")).toBe(false); + expect(isCalendarDate("2026-10-11T13:00")).toBe(false); + }); + it("counts days on the calendar", () => { expect(addDays("2026-10-31", 1)).toBe("2026-11-01"); expect(addDays("2026-03-01", -1)).toBe("2026-02-28");