From 1332223e1cddea32069b34a3c835f0cf9583a44a Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 17:38:34 -0500 Subject: [PATCH 1/4] Feat: Add consumer agent skills and /skills routes --- ai/skills/.gitkeep | 0 ai/skills/native-dates-plugins.md | 178 ++++++++++++++++ ai/skills/native-dates.md | 316 +++++++++++++++++++++++++++++ docs/src/lib/skills.js | 46 +++++ docs/src/pages/llms-full.txt.js | 18 +- docs/src/pages/llms.txt.js | 16 +- docs/src/pages/skills/[name].md.js | 14 ++ package.json | 1 + 8 files changed, 581 insertions(+), 8 deletions(-) delete mode 100644 ai/skills/.gitkeep create mode 100644 ai/skills/native-dates-plugins.md create mode 100644 ai/skills/native-dates.md create mode 100644 docs/src/lib/skills.js create mode 100644 docs/src/pages/skills/[name].md.js diff --git a/ai/skills/.gitkeep b/ai/skills/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/ai/skills/native-dates-plugins.md b/ai/skills/native-dates-plugins.md new file mode 100644 index 0000000..fe0a171 --- /dev/null +++ b/ai/skills/native-dates-plugins.md @@ -0,0 +1,178 @@ +--- +title: Plugins, Loose Parsing, Zone Aliases, and Polyfill for native-dates +description: Companion guide for @native-dates/plugins (zones, loose, legacy-date), @native-dates/polyfill, and authoring custom native-dates plugins. Use whenever code parses non-ISO or slash dates ('11/06/2026', 'Oct 17, 2026', { loose: true, dayFirst }), resolves city names ('Berlin', 'Tokyo') or timezone abbreviations ('EST', 'PT', 'CET', zoneAliases), shims legacy Date.prototype getters (getFullYear, getMonth, getDay), polyfills Temporal for Safari/older browsers, or extends native-dates prototypes. +keywords: ["@native-dates/plugins", "@native-dates/polyfill", "temporal-polyfill", zones, loose, legacy-date, dayFirst, zoneAliases, timezones, getFullYear, getTimezoneOffset, sideEffects, missingPlugin] +audience: usage +skill: native-dates-plugins +type: skill +--- + +# Plugins, Loose Parsing, Zone Aliases, and Polyfill for native-dates + +> **Skill:** `native-dates-plugins` +> **Purpose:** Guide to `@native-dates/plugins/{zones,loose,legacy-date}`, `@native-dates/polyfill`, and custom plugin authoring + +Optional conveniences that add lookup tables, `Date.parse` fallbacks, or legacy shims live in `@native-dates/plugins` so core `native-dates` stays ~14 kB Brotli with zero dependencies. Each plugin is a side-effect subpath module that installs its hooks or prototype methods once at import time, and `@native-dates/polyfill` conditionally loads `temporal-polyfill` only on runtimes missing `globalThis.Temporal`. + +**Golden rule: Import plugins as bare subpaths (`import '@native-dates/plugins/loose'`) at startup with no `.use()` call, and remember `{ loose: true }` returns `null` only for malformed input data while still throwing on invalid caller options like a bad `zone` or `locale`.** + +--- + +## What You'd Get Wrong + +**1. `@native-dates/plugins` has no root export and no `.use()` or `.extend()` registration.** Plugins self-attach when their subpath is imported; forgetting the import before passing `{ loose: true }`, `dayFirst`, or `zoneAliases` throws `RangeError` with `code: 'missingPlugin'`. + +```js +// ❌ WRONG - no root barrel and no dayjs.extend() / .use() call +import { loose, zones } from '@native-dates/plugins'; +datetime.extend(loose); + +// ✅ RIGHT - bare subpath imports register hooks once process-wide (and merge TypeScript declarations) +import '@native-dates/plugins/loose'; +import '@native-dates/plugins/zones'; +import { date, datetime } from 'native-dates'; + +datetime('Nov 16, 2026 9:30am', { zone: 'Berlin', loose: true }); +``` + +**2. `{ loose: true }` returns `null` for unreadable input data, NOT for invalid caller configuration.** Passing an unknown `zone` or `locale` alongside `{ loose: true }` still throws `unknownZone` or `unknownLocale` so programmer typos are never masked as empty user input. + +```js +// ❌ WRONG assumption - expecting { loose: true } to swallow a bad zone option +datetime('2026-11-16', { zone: 'Mars/Olympus', loose: true }); // throws RangeError [unknownZone] + +// ✅ RIGHT - { loose: true } turns malformed input strings/numbers into null (and rejects rolled-forward 'Feb 30') +date('not a date', { loose: true }); // null +date('Feb 30, 2026', { loose: true }); // null (Date.parse rollover into March is caught and rejected) +``` + +**3. Bare IANA `'EST'`, `'MST'`, and `'HST'` behave differently once `@native-dates/plugins/zones` is imported.** Without the plugin, `Temporal` treats `'EST'` as a legacy fixed `-05:00` zone with no daylight saving time. `@native-dates/plugins/zones` maps `'EST'`, `'EDT'`, `'ET'`, and `'Eastern'` to `'America/New_York'` (`'MST'` -> `'America/Denver'`, `'PST'`/`'PT'` -> `'America/Los_Angeles'`) so summer dates observe DST. Use `'-05:00'` when you genuinely want a fixed year-round offset. + +**4. `legacy-date` reads local `Date` getters in `dt.zone`, not the host machine's OS timezone, and throws `immutable` on setters.** Calling `dt.getHours()` or `dt.getDay()` returns the hour and `0`–`6` weekday in `dt.zone` regardless of the server's timezone, while `dt.getMonth()` returns `0`–`11` to match `Date.prototype.getMonth()` (unlike `dt.month`, which stays `1`–`12`). + +```js +import '@native-dates/plugins/legacy-date'; +import { datetime } from 'native-dates'; + +const tokyo = datetime('2026-11-16T00:30:00Z', 'Asia/Tokyo'); +tokyo.getHours(); // 9 (09:30 in Tokyo, even on a UTC server) +tokyo.getMonth(); // 10 (0-indexed legacy shim; tokyo.month is still 11) +tokyo.setHours(12); // throws RangeError [immutable] — use tokyo.set('hour', 12) instead +``` + +**5. `@native-dates/polyfill` uses top-level `await` on its default entry.** Default `import '@native-dates/polyfill'` dynamically imports `temporal-polyfill` only when `!globalThis.Temporal` so modern browsers download 0 polyfill bytes. In CommonJS or bundler targets that disallow top-level `await`, import `'@native-dates/polyfill/sync'` instead, and list `temporal-polyfill` (`>=0.3.0`) in your app's `dependencies`. + +--- + +## @native-dates/plugins/zones + +Resolves city names, common timezone abbreviations, case/diacritic variations, IANA tzdb link names, and custom `zoneAliases` anywhere a `zone` is accepted (`datetime`, `now`, `today`, `in`, `at`, `configure`). + +```js +import '@native-dates/plugins/zones'; +import { timezones } from '@native-dates/plugins/zones'; +import { configure, datetime } from 'native-dates'; + +datetime('2026-11-16T09:30', 'Berlin').zone; // 'Europe/Berlin' +datetime('2026-11-16T09:30', 'são_paulo').zone; // 'America/Sao_Paulo' +datetime('2026-11-16T09:30', 'PT').zone; // 'America/Los_Angeles' + +configure({ zoneAliases: { hq: 'Europe/Berlin', warehouse: 'America/Chicago' } }); +datetime('2026-11-16T09:30', 'hq').zone; // 'Europe/Berlin' +``` + +| Resolution layer | Examples | Notes | +|---|---|---| +| `configure({ zoneAliases })` | `{ hq: 'Europe/Berlin' }` | Highest precedence; pass `{ hq: null }` to delete one alias or `zoneAliases: null` to clear all | +| Exported `timezones` map | `ET`, `CT`, `MT`, `PT`, `UK`, `CET`, `IST` (`Asia/Kolkata`), `JST`, `AET`, `BRT`, `NZT`, `SGT` | Mutable object (`timezones.IST = 'Asia/Jerusalem'`) for ambiguous regional codes | +| Built-in abbreviations | `EST`/`EDT`/`Eastern`, `CST`/`CDT`, `MST`/`MDT`, `PST`/`PDT`/`Pacific`, `BST`, `CEST`, `GMT`, `Z` | Maps to full DST-observing IANA zones (`GMT` and `Z` -> `'UTC'`) | +| Runtime IANA & city lookup | `'los angeles'`, `'buenos aires'`, `'ho chi minh'`, `'europe/paris'` | Case-, underscore-, and accent-insensitive against `Intl.supportedValuesOf('timeZone')` and `Temporal` | + +--- + +## @native-dates/plugins/loose + +Enables `{ loose: true }` and `dayFirst` on `datetime()`, `date()`, `time()`, `duration()`, `monthDay()`, `dayMonth()`, `yearMonth()`, `monthYear()`, `dateRange()`, `datetimeRange()`, `timeRange()`, and `configure({ dayFirst })`. + +```js +import '@native-dates/plugins/loose'; +import { configure, date, datetime, monthDay, yearMonth } from 'native-dates'; + +date('11/06/2026', { loose: true }); // CalendarDate(2026-11-06) — US month-first default +date('06/11/2026', { loose: true, dayFirst: true }); // CalendarDate(2026-11-06) — European day-first +datetime('Sep 6, 2026 9:30 PM EDT', { loose: true, zone: 'America/New_York' }); +monthDay('17 octobre', { loose: true, locale: 'fr' }); // MonthDay(10-17) +yearMonth('noviembre de 2026', { loose: true, locale: 'es' }); // YearMonth(2026-11) +date('', { loose: true }); // null +``` + +| Input / Option | Behavior under `{ loose: true }` | +|---|---| +| Numeric slash/dot/dash `'06/11/2026'` | Month-first by default; set `{ dayFirst: true }` per call or `configure({ dayFirst: true })` globally for `DD/MM/YYYY` | +| Rolled-forward calendar dates (`'Feb 30, 2026'`, `'11/31/2026'`) | Caught and returned as `null` instead of letting `Date.parse` silently roll into the next month | +| Named months in `monthDay` / `yearMonth` | Matches English first (so `'Mar 17'` stays March even under `'fi'`), then `Intl` month names in `{ locale }` or `configure({ locale })` | +| Unreadable strings, `null`, `undefined`, `NaN` | Returns `null` (`TypeScript` return type widens to `T \| null` when `{ loose: true }` is passed) | +| Two-digit ISO `'10-17'` in `dayMonth()` | Always stays month-first (`October 17`) so ISO `toJSON()` strings round-trip, whereas `'17/10'` reads day-first | + +--- + +## @native-dates/plugins/legacy-date + +Attaches `Date.prototype` read methods onto `DateTime.prototype` for incremental migration where downstream helpers still call `Date` getters directly (note: `.toJSDate()` is already in core without this plugin). + +- **Zone-aware local getters:** `getFullYear()`, `getMonth()` (`0`–`11`), `getDate()` (`1`–`31`), `getDay()` (`0`–`6`, Sunday = `0`), `getHours()`, `getMinutes()`, `getSeconds()`, `getMilliseconds()`, and `getTimezoneOffset()` (minutes positive west of UTC, matching `Date`) all evaluate in `this.zone`. +- **UTC & string getters:** `getTime()`, `getUTCFullYear()`, `getUTCMonth()`, `getUTCDate()`, `getUTCDay()`, `getUTCHours()`, `getUTCMinutes()`, `getUTCSeconds()`, `getUTCMilliseconds()`, `toISOString()` (fixed `.sssZ`), `toLocaleString(locales?, options?)`, `toLocaleDateString(...)`, `toLocaleTimeString(...)` (defaulting to `this.locale()` and `this.zone`). +- **Mutator guard:** All 15 `set*` / `setUTC*` methods (`setHours`, `setMonth`, `setTime`, ...) throw `RangeError` with `code: 'immutable'`. + +--- + +## @native-dates/polyfill + +```js +// Entrypoint of an app supporting Safari or older browsers (install temporal-polyfill >= 0.3.0): +import '@native-dates/polyfill'; +import { now, today } from 'native-dates'; +``` + +- **`@native-dates/polyfill` (default):** Checks `if (!globalThis.Temporal)` and runs `await import('temporal-polyfill')`, splitting the polyfill into an on-demand chunk skipped by Chrome, Firefox, Edge, and Node `>=26`. +- **`@native-dates/polyfill/sync`:** Synchronous import of `temporal-polyfill` for CommonJS bundles or build targets without top-level `await`. + +--- + +## Authoring Custom Plugins + +1. **Mutate `Class.prototype` purely:** Instances are frozen, so plugin methods return new instances (`this.plus(...)`, `new CalendarDate(...)`) rather than mutating `this`. +2. **Check brands, never `constructor.name`:** Use `IS_DATE_TIME`, `IS_CALENDAR_DATE`, `IS_TIME`, `IS_DURATION`, `IS_MONTH_DAY`, `IS_YEAR_MONTH`, `IS_RANGE`, or `kindOf(value)` from `'native-dates'` so checks survive realms and duplicate bundler copies. +3. **Declare `"sideEffects"` and `"peerDependencies"`:** Mark plugin entry files in `"sideEffects": ["./index.js"]` (never `"sideEffects": false`, or bundlers drop bare `import 'my-plugin'` statements) and put `"native-dates"` in `peerDependencies`. +4. **Augment TypeScript types:** Use `declare module 'native-dates' { interface CalendarDate { ... } }`. + +--- + +## Quick Reference + +```js +import '@native-dates/polyfill'; // only when targeting runtimes without native Temporal +import '@native-dates/plugins/zones'; +import '@native-dates/plugins/loose'; +import '@native-dates/plugins/legacy-date'; +import { configure, date, datetime } from 'native-dates'; + +configure({ + dayFirst: true, + zoneAliases: { office: 'Europe/London' }, +}); + +const parsed = date(userInput, { loose: true }); // CalendarDate | null ('16/11/2026' -> 2026-11-16) +const meeting = datetime('2026-11-16T14:00', 'office'); // zone: 'Europe/London' +meeting.getHours(); // 14 (via legacy-date) +``` + +**Golden rule: Import plugins as bare subpaths (`import '@native-dates/plugins/loose'`) at startup with no `.use()` call, and remember `{ loose: true }` returns `null` only for malformed input data while still throwing on invalid caller options like a bad `zone` or `locale`.** + +--- + +## Related Skills + +| Skill | Use when... | +|---|---| +| `native-dates` | Core classes (`DateTime`, `CalendarDate`, `Time`, `Duration`, `MonthDay`, `YearMonth`, ranges), DST-safe arithmetic, `format()` presets and tokens, `.locale()`, `weekStart`, `compare()`, and error codes | diff --git a/ai/skills/native-dates.md b/ai/skills/native-dates.md new file mode 100644 index 0000000..373e678 --- /dev/null +++ b/ai/skills/native-dates.md @@ -0,0 +1,316 @@ +--- +title: Dates, Times, Zones, Durations, and Ranges with native-dates +description: Core guide for building with native-dates (and @native-dates/core). Use whenever code creates, parses, shifts, rounds, compares, ranges over, or formats dates, clock times, zoned timestamps, durations, billing months, or recurring month-days, handles DST or HTTP Accept-Language locales, or migrates off Date, Moment, Day.js, or raw Temporal. For city/abbreviation zones, { loose: true } parsing, legacy Date getters, or the Safari Temporal polyfill, also load native-dates-plugins. +keywords: [native-dates, "@native-dates/core", datetime, date, time, duration, monthDay, yearMonth, dateRange, datetimeRange, timeRange, today, now, fromNow, weekStart, dayOfWeek, epochSeconds, epochMilliseconds, configure, Temporal, Intl, DST] +audience: usage +skill: native-dates +type: skill +--- + +# Dates, Times, Zones, Durations, and Ranges with native-dates + +> **Skill:** `native-dates` +> **Purpose:** Core mental model, pitfalls, and API reference for `native-dates` (`@native-dates/core`) + +`native-dates` wraps the platform's `Temporal` and `Intl` APIs with immutable classes and zero runtime dependencies. Instead of routing every concept through one `Date` object, each kind of value has its own class and factory so invalid operations (adding hours to a calendar date, comparing a date to a zoned timestamp, or mutating a shared instance) fail immediately with a coded error. + +**Golden rule: Pick the noun that matches the data (`datetime` for an exact moment in a zone, `date` for a calendar day, `time` for a wall clock, `yearMonth` or `monthDay` for partial dates), chain immutable methods rather than mutating, and pass explicit IANA zones or per-value `.locale()` in server code.** + +--- + +## What You'd Get Wrong + +**1. Trailing `Z` and numeric offsets (`-05:00`) fix the instant, not `.zone`.** Database and JSON timestamps routinely arrive with `Z`. Adopting `'UTC'` as `.zone` would silently disable daylight-saving rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls. `.zone` comes from the explicit `zone` argument, a bracketed `[Zone]` suffix, `configure({ zone })`, or the runtime's local zone, while `toString()` and `toJSON()` always serialize standard ISO 8601 UTC (`...Z`). + +```js +// ❌ WRONG - assuming 'Z' sets .zone to 'UTC' +const dt = datetime('2026-03-08T04:30:00Z'); +dt.zone; // local or configured zone (NOT 'UTC') + +// ✅ RIGHT - pass 'UTC' when you want UTC wall-clock fields, or pass the user's IANA zone for DST-safe math +const utc = datetime('2026-03-08T04:30:00Z', 'UTC'); +const ny = datetime('2026-03-08T04:30:00Z', 'America/New_York').plus(1, 'day'); // crosses spring-forward at local 23:30 +ny.toJSON(); // '2026-03-09T03:30:00.000Z' +``` + +**2. `month` is `1`–`12` and `dayOfWeek` is ISO `1`–`7` (`7` = Sunday), not `0`-indexed.** `isWeekday()` is `true` Monday–Friday (`1`–`5`) and `false` on weekends (`6`–`7`). In token patterns, `'E'` outputs `'1'`–`'7'` while `'d'` keeps Moment/Day.js's `'0'`–`'6'` (`'0'` = Sunday). + +```js +// ❌ WRONG - JS Date / Moment 0-indexed months or Sunday = 0 on .dayOfWeek +date(2026, 0, 15); // RangeError [invalidDate] +if (d.dayOfWeek === 0) { /* never true: Sunday is 7 */ } + +// ✅ RIGHT - 1 = January..12 = December, 1 = Monday..7 = Sunday +const d = date(2026, 1, 15); +d.month; // 1 +date('2026-11-15').dayOfWeek; // 7 (Sunday) +date('2026-11-15').format('E'); // '7' (token 'd' prints '0') +``` + +**3. Unix timestamp properties require an explicit unit — there is no bare `.epoch` or `.timestamp`.** Shells, Python, SQL, and JWT `exp`/`iat` claims count seconds while `Date.now()` counts milliseconds, so every epoch property names its unit. + +```js +// ❌ WRONG - undefined! No .epoch or .timestamp property exists +const exp = now().epoch; + +// ✅ RIGHT - choose epochSeconds (Number, floored), epochMilliseconds (Number), or epochNanoseconds (BigInt) +const jwtExp = now().plus(15, 'minutes').epochSeconds; +const ms = now().epochMilliseconds; // also returned by valueOf() +``` + +**4. `next()` and `previous()` step to weekdays or `MonthDay`s and preserve clock time; `startOfNext()` and `startOfPrevious()` step to unit boundaries at `00:00`.** Passing a unit like `'month'` to `next()` throws `unknownDayOfWeek`, and passing a number like `2` to `startOfNext()` throws `unknownUnit`. + +```js +// ❌ WRONG - passing a calendar unit to next() +datetime('2026-11-16T09:30', 'UTC').next('month'); // throws [unknownDayOfWeek] + +// ✅ RIGHT - use next('friday') for same-clock weekday steps, startOfNext('month') for 00:00 unit boundaries +datetime('2026-11-16T09:30', 'UTC').next('friday'); // 2026-11-20T09:30:00Z +datetime('2026-11-16T09:30', 'UTC').startOfNext('month'); // 2026-12-01T00:00:00Z +``` + +**5. `DateRange` is closed `[start, end]`, while `DateTimeRange` and `TimeRange` are half-open `[start, end)`.** "Monday to Friday" includes Friday (`5` days), so `checkIn.for(3, 'days')` automatically subtracts 1 day from `end` (`Sep 1` through `Sep 3`). `DateTimeRange` and `TimeRange` exclude `end` so adjacent slots (`09:00`–`10:00`, `10:00`–`11:00`) do not overlap, and `TimeRange` wraps across midnight when `end < start` (`Time.prototype.until()` stays signed within a single `00:00`–`23:59` day). + +```js +// ❌ WRONG - adding 3 days manually to build a 3-night/3-day DateRange spans 4 inclusive days +const bad = date('2026-09-01').to(date('2026-09-01').plus(3, 'days')); // 4 days! + +// ✅ RIGHT - use .for(3, 'days') for a span, or .to() / .through() with the inclusive end date +const stay = date('2026-09-01').for(3, 'days'); // 2026-09-01 through 2026-09-03 (duration: 3 days) +const slot = time('22:00').to('06:00'); // overnight TimeRange (duration: 8 hours) +``` + +**6. `Duration` keeps written fields until `.balance()`, totals via `.total(unit)` / `.as(unit)` (never `.in()`), and refuses `days(1).minus(hours(1))`.** There is no `.normalize()` method. Subtracting clock units from calendar days throws `conflictingSigns` because DST days are 23 or 25 hours, and converting/comparing unanchored months or years against days/hours throws `missingAnchor` unless measured with `a.until(b)`. + +```js +// ❌ WRONG - .normalize(), .in('hours'), or mixing calendar day and hour signs on a Duration +minutes(90).normalize(); // TypeError: not a function +hours(36).in('days'); // TypeError: not a function +days(1).minus(hours(1)); // RangeError [conflictingSigns] + +// ✅ RIGHT - use .balance(), .total(unit) / .as(unit), and chain mixed calendar + clock steps on DateTime +minutes(90).balance(); // Duration(PT1H30M) -> hours: 1, minutes: 30 +hours(36).total('days'); // 1.5 +dt.plus(1, 'day').minus(1, 'hour'); // DST-accurate chaining +date('2026-01-15').until('2026-04-15', 'days'); // 90 (anchored via until) +``` + +**7. `.locale()` affects both formatting and default week start (`startOf('week')`), while `weekOfYear` stays ISO Monday.** On multi-user servers, attach `.locale(req.headers['accept-language'])` to values instead of mutating process-wide `configure({ locale })`, and pass `'monday'` explicitly when keying stored weekly buckets. + +```js +// ❌ WRONG - mutating global configure() per HTTP request, or assuming startOf('week') is Monday in en-US +configure({ locale: req.headers['accept-language'] }); +const bucket = rowDate.startOf('week').toString(); // Sunday in en-US, Monday in de-DE, Saturday in ar-EG! + +// ✅ RIGHT - attach locale per value, and pass firstDay when week keys must not shift by locale +const localized = datetime(row.at, user.zone).locale(req.headers['accept-language']); +const isoWeekKey = localized.date.startOf('week', 'monday').toString(); +``` + +**8. Core rejects ambiguous inputs and city/abbreviation zones without plugins, and strips error prose in production.** `'11/06/2026'` and `{ loose: true }` require `@native-dates/plugins/loose`, `'Berlin'` and `'PST'` require `@native-dates/plugins/zones`, `compare(date, datetime)` throws `conflictingKinds`, `CalendarDate` / `Time` throw `unsupportedComparison` on `<` or `-`, and `err.message` explanations fold out of production builds — branch on `err.code` and `err.at`, never `err.message` substrings. + +--- + +## Choosing the Right Noun + +| Class | Factories | Represents | Key rule | +|---|---|---|---| +| `DateTime` | `datetime(input, zoneOrOpts?)`, `now(zone?)`, `startOfToday(zone?)`, `endOfToday(zone?)` | Exact instant + IANA zone (`Temporal.ZonedDateTime`) | DST-aware; `toString()` / `toJSON()` emit UTC `...Z`; `<` / `valueOf()` use `epochMilliseconds` | +| `CalendarDate` | `date(input, opts?)`, `date(y, m, d)`, `today(zone?)`, `tomorrow(zone?)`, `yesterday(zone?)` | Calendar day (`Temporal.PlainDate`) | Refuses clock units (`hours`) and `<` / `-`; two-arg `date(2026, 11)` throws `missingDay` | +| `Time` | `time(input, zoneOrOpts?)`, `time(h, m, s?)` | Wall-clock time (`Temporal.PlainTime`) | Wraps modulo 24h on `plus`/`minus`; accepts `'9am'`, `'17:30'`, `'9:05:08.428'` | +| `Duration` | `duration(input, unitOrOpts?)`, `years(n)`..`milliseconds(n)` | Span of units (`Temporal.Duration`) | 8 unit helpers (`years`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`); use `duration(n, 'microseconds' \| 'nanoseconds')` for sub-ms | +| `MonthDay` | `monthDay(input, opts?)`, `monthDay(m, d)`, `dayMonth(input, opts?)`, `dayMonth(d, m)` | Recurring month + day (`Temporal.PlainMonthDay`) | No linear order (`equals()`, `fallsOn()` / `isOn()`); Feb 29 falls on Feb 28 in non-leap years | +| `YearMonth` | `yearMonth(input, opts?)`, `yearMonth(y, m)`, `monthYear(input, opts?)`, `monthYear(m, y)` | Billing/calendar month (`Temporal.PlainYearMonth`) | Only `years`, `quarters`, `months` arithmetic; `monthYear('11/26')` adds `YearMonth.century` (`2000`) | +| `DateRange`, `DateTimeRange`, `TimeRange` | `dateRange(s, e?, opts?)`, `datetimeRange(...)`, `timeRange(...)`, `pt.to(end)`, `pt.for(n, unit)`, `pt.range(unit)` | Interval between two points | `DateRange` is `[start, end]` (also `date.through(end)`); `DateTimeRange` & `TimeRange` are `[start, end)` | + +Every instance is `Object.freeze`d on construction with `.text` as its first enumerable own property. Cross between types with `.date`, `.time`, `.monthDay`, `.yearMonth`, `date.at(time?, zone?)`, `time.on(date, zone?)`, `monthDay.in(year)`, `yearMonth.on(day)` (`yearMonth.start` / `.end`), `range.in(zone)`, or `.as('date' | 'time' | 'datetime' | 'monthDay' | 'yearMonth' | 'duration')`. + +--- + +## DateTime + +```js +import { datetime, endOfToday, now, startOfToday } from 'native-dates'; + +const dt = datetime('2026-11-16T09:30', 'America/Los_Angeles'); +const shifted = dt.plus(2, 'days').at('14:00').in('Europe/Berlin'); +``` + +- **Accepted inputs:** ISO strings (`'2026-11-16'`, `'2026-11-16T09:30'`, `'2026-11-16T17:30Z'`, `'2026-11-16T09:30-08:00[America/Los_Angeles]'`), year-first `'2026/11/16 9:30'`, epoch milliseconds (`Number`, truncated if fractional), `Date`, `{ year, month, day, hour, ... }`, `CalendarDate`, `DateTime`, or `Temporal.{ZonedDateTime,Instant,PlainDateTime,PlainDate}`. Passing `null`/`undefined` throws `missingDateTime` (use `now()`). +- **Own properties:** `text`, `year`, `month` (`1`–`12`), `day` (`1`–`31`), `dayOfWeek` (`1`–`7`), `hour` (`0`–`23`), `minute`, `second`, `millisecond`, `zone` (IANA ID), `offset` (`'-08:00'`), `epochMilliseconds`. +- **Getters & predicates:** `microsecond`, `nanosecond`, `epochSeconds`, `epochNanoseconds` (`BigInt`), `weekStart`, `quarter` (`1`–`4`), `dayOfYear`, `weekOfYear` (ISO), `daysInMonth`, `daysInYear`, `hoursInDay` (`23`/`24`/`25` across DST), `date`, `time`, `monthDay`, `yearMonth`, `isLeapYear()`, `isWeekday()`, `isWeekend()`, `isPast()`, `isFuture()`, `isToday()`, `isTomorrow()`, `isYesterday()`. +- **Transforms:** `plus(n, unit)` / `add`, `minus(n, unit)` / `subtract` (also accepts `'1h 30m'`, `{ days: 2 }`, or `Duration`), `set(field, value)` / `set({ year, month })` (clamps existing day on month/year change, rejects out-of-range explicit fields), `at(time)` (wall clock in `this.zone`), `in(zone)` (same instant in new zone), `startOf(unit, firstDay?)`, `endOf(unit, firstDay?)` (inclusive last ms/ns — prefer `range(unit)` for `< end` queries), `startOfNext(unitOrWeekday, firstDay?)`, `startOfPrevious(unitOrWeekday, firstDay?)`, `next(weekdayOrMonthDay)`, `previous(weekdayOrMonthDay)`, `round(inc, unit?)`, `floor(inc, unit?)`, `ceil(inc, unit?)`, `locale(tag?)` / `lang`. +- **Comparisons & spans:** `equals(other)`, `isBefore(other)`, `isAfter(other)`, `isSame(other, unit?, firstDay?)`, `until(other, unit?)`, `since(other, unit?)`, `from(other?, locale?)` / `formatRelative`, `fromNow(locale?)`, `to(endOrDuration, unit?)` / `for`, `range(unit, firstDay?)`, `toString()`, `toJSON()`, `toJSDate()`, `toTemporal()`. + +--- + +## CalendarDate + +```js +import { date, today, tomorrow, yesterday } from 'native-dates'; + +const due = today('America/New_York').plus(2, 'weeks').next('friday'); +``` + +- **Accepted inputs:** `'2026-11-16'`, `'2026/11/16'`, `'2026.11.16'`, `'2026-1-5'`, `(year, month, day)` integers, `{ year, month, day }`, `DateTime`, `Date`, instant strings (resolved in `zone`), or `Temporal.PlainDate`. Bare single numbers throw `invalidDate` (`datetime(ms).date` or `date(y, m, d)`). +- **Clock guard:** Refuses clock units (`hours`, `minutes`, ...) with `unsupportedUnit`; attach a clock first via `.at('00:00', zone)`. +- **Day-specific methods:** Shares `DateTime`'s calendar properties, `plus`/`minus`, `set`, `startOf`/`endOf`, `startOfNext`/`startOfPrevious`, `next`/`previous`, `isSame`, `until`/`since` (returns `Duration` in days or `Number` when `unit` is passed), `from`/`fromNow`, plus `.through(end)` (alias for `.to(end)`), `.at(time?, zone?)` -> `DateTime`, and `.points(step, unit?, zone?)` / `.split(step, unit?, zone?)` / `.splitBy` across that date's zoned day. + +--- + +## Time + +```js +import { time } from 'native-dates'; + +const shiftStart = time('9:30am').plus(45, 'minutes'); // Time(10:15:00) +const scheduled = shiftStart.on('2026-11-16', 'America/Chicago'); // DateTime +``` + +- **Accepted inputs:** `'09:30'`, `'9am'`, `'5:30:15 pm'`, `time(9, 30, 0)`, `{ hour, minute }`, `DateTime`, `Date`, instant strings (resolved in `zone`), or `Temporal.PlainTime`. Single bare hour integer is accepted in `time(9)` -> `09:00` (`set` / arithmetic wrap around midnight). +- **Methods:** `plus`/`minus`, `set`, `startOf`/`endOf`, `startOfNext(unit)` / `startOfPrevious(unit)` (clock units only), `round`/`floor`/`ceil`, `equals`/`isBefore`/`isAfter`/`isSame`, `until(other, unit?)` / `since(other, unit?)` (within a single `00:00`–`23:59` day), `to(end, unit?)` / `for`, `on(day, zone?)` -> `DateTime`, `format(spec?, locale?)`, `toString()`. + +--- + +## Duration + +```js +import { days, duration, hours, minutes } from 'native-dates'; + +const span = duration('2h 45m').plus(30, 'minutes').balance(); // 3 hours, 15 minutes +span.total('hours'); // 3.25 +``` + +- **Accepted inputs:** ISO 8601 (`'PT1H30M'`, `'-P2D'`), natural phrases (`'1h 30m'`, `'2 weeks, 3 days'`, `'90 mins'`, `'1.5 hours'` -> spills fractional units down to nanoseconds), `(count, unit)`, `{ hours: 1, minutes: 30 }`, or `Temporal.Duration`. +- **Properties & methods:** `text`, `years`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`, `microseconds`, `nanoseconds`, `sign` (`-1 | 0 | 1`), `anchor`, `isZero()`, `isNegative()`, `toFields()`, `plus`/`add`, `minus`/`subtract` (borrows signs automatically across fixed ratios `1y = 12mo` and `1w = 7d`), `times(factor)`, `negated()`, `abs()`, `balance(largestUnit?)`, `round(smallestUnit)`, `total(unit)` / `as(unit)`, `toMilliseconds()` / `valueOf()`, `compare(other)`, `equals(other)`, `format('long' | 'short' | 'narrow' | 'digital', locale?)`. + +--- + +## MonthDay and YearMonth + +```js +import { dayMonth, monthDay, monthYear, yearMonth } from 'native-dates'; + +const birthday = monthDay('10-17'); // or monthDay(10, 17), dayMonth('17/10') +birthday.in(2027); // CalendarDate(2027-10-17) +birthday.next('2026-11-16'); // CalendarDate(2027-10-17) — strictly after reference date + +const billing = monthYear('11/26'); // YearMonth(2026-11) +billing.start; // CalendarDate(2026-11-01) +billing.end; // CalendarDate(2026-11-30) +``` + +- **`MonthDay`:** `month` (`1`–`12`), `day` (`1`–`31`), `in(year)` -> `CalendarDate` (Feb 29 constrains to Feb 28 in non-leap years), `next(fromDay?)` / `after(day)`, `previous(fromDay?)` / `last(fromDay?)` / `before(day)`, `fallsOn(day)` / `isOn(day)` (Feb 29 falls on Feb 28 in non-leap years, whereas `equals()` checks exact `month` & `day` and rejects slash/dot strings as order-ambiguous), `isToday(zone?)`, `isTomorrow(zone?)`, `isYesterday(zone?)`. Note: two-digit `'MM-DD'` with a hyphen always parses month-first even in `dayMonth('10-17')`. +- **`YearMonth`:** `year`, `month`, `quarter`, `daysInMonth`, `daysInYear`, `isLeapYear()`, `start`, `end`, `on(day)` -> `CalendarDate`, `plus`/`minus` (`years`, `quarters`, `months` only), `set`, `contains(day)` / `includes(day)`, `equals`/`isBefore`/`isAfter`/`compare`, `isPast(zone?)`/`isFuture(zone?)`, `until(other, unit?)`/`since(other, unit?)`. `YearMonth` `'short'` preset prints 4-digit years (`'11/2026'`); use `.format('MM/YY')` for 2-digit card expiries. + +--- + +## DateRange, DateTimeRange, and TimeRange + +```js +import { date, dateRange, datetimeRange, timeRange } from 'native-dates'; + +const sprint = date('2026-11-02').for(2, 'weeks'); // 2026-11-02 through 2026-11-15 +const daysInSprint = sprint.points('day'); // 14 CalendarDate instances +const weeks = sprint.split(1, 'week'); // [DateRange(Nov 2..Nov 8), DateRange(Nov 9..Nov 15)] +``` + +- **Construction:** `point.to(end)`, `point.for(amount, unit)` / `point.for(duration)`, `date.through(end)`, `point.range(unit, firstDay?)`, or `dateRange` / `datetimeRange` / `timeRange` with `(start, end, options?)` or a single interval string (`'2026-09-01/2026-09-07'`, `'2026-09-01 to 2026-09-07'`, `'09:00-17:00'`). +- **Properties & methods:** `text`, `kind` (`'date' | 'datetime' | 'time'`), `start`, `end`, `duration` (`Duration`), `isEmpty()` (`false` on all `DateRange`s; `start.equals(end)` on `DateTimeRange`/`TimeRange`), `contains(pointOrRange)` / `includes`, `overlaps(otherRange)`, `intersection(otherRange)` (returns range or `null`; throws `unsupportedIntersection` if two overnight `TimeRange`s overlap in two disjoint windows), `equals(other)`, `points(step, unit?)` (`step` > 0, e.g. `'day'`, `'30m'`, `(15, 'minutes')`), `split(step, unit?)` / `splitBy`, `in(zone)` (converts inclusive `DateRange` `[start, end]` to half-open `DateTimeRange` `[start 00:00, (end + 1d) 00:00)` in `zone`; throws `unsupportedZone` on `TimeRange`), `format(spec?, locale?)`, `toString()` (`'start/end'`). + +--- + +## format, monthNames, and weekdayNames + +`value.format(spec?, locale?)` accepts four kinds of `spec`: + +1. **Built-in presets:** `'short'`, `'medium'` (default, except `'short'` on `Time`), `'long'`, `'full'`, `'date'`, `'time'`, `'month'`, `'text'`, plus Moment/Day.js localized presets `'LT'`, `'LTS'`, `'L'`, `'l'`, `'LL'`, `'ll'`, `'LLL'`, `'lll'`, `'LLLL'`, `'llll'`. (`Duration.prototype.format` accepts `'long'` default, `'short'`, `'narrow'`, `'digital'`.) +2. **Custom named formats** registered via `configure({ formats: { invoice: 'YYYY-MM-DD' } })` (checked before built-in presets; `value.text` and bare `value.format()` stay on built-in defaults). +3. **`Intl.DateTimeFormat` options objects** (`{ month: 'short', day: 'numeric', weekday: 'short' }`) — fields absent on a noun (such as `hour` on `CalendarDate` or `year` on `Time`) are stripped automatically. +4. **Token patterns** (literal text escaped in `[brackets]`, `'T'` allowed bare; digits and years stay Western ASCII/Gregorian): + +| Tokens | Output | +|---|---| +| `YYYY`, `YY`, `Q` | 4-digit year, 2-digit year, quarter (`1`–`4`) | +| `M`, `MM`, `MMM`, `MMMM` | Month `1`–`12`, padded `01`–`12`, localized Gregorian short/long name (auto-inflected after day tokens) | +| `D`, `DD`, `Do`, `DDD`, `DDDD` | Day of month, padded, ordinal (`'16th'`, `'6.'`, `'6日'`), day of year, 3-digit day of year | +| `E`, `d`, `dd`, `ddd`, `dddd` | ISO weekday `1`–`7` (`7` = Sun), Moment weekday `0`–`6` (`0` = Sun), narrow (`'Mo'`), short, long | +| `W`, `WW` | ISO week of year (`1`–`53`), padded | +| `H`, `HH`, `h`, `hh`, `a`, `A` | 24h hour, 12h hour (`1`–`12`), localized am/pm | +| `m`, `mm`, `s`, `ss`, `S`, `SS`, `SSS` | Minute, second, fractional digits (`1`–`3`) | +| `Z`, `ZZ`, `z`/`zz`, `zzz`/`zzzz` | Offset `'-08:00'`, `'-0800'`, localized short/long zone name | +| `X`, `x`, `[text]` | Epoch seconds, epoch milliseconds, escaped literal text | + +- `monthNames(style = 'long' | 'short', locale?)`: 12 Gregorian month names (`0` = Jan..`11` = Dec). +- `weekdayNames(style = 'short' | 'long' | 'narrow', firstDay?, locale?)`: 7 weekday names rotated to start on `firstDay` / `weekStart` / locale's first day (note: `locale` is the **3rd** argument!). + +--- + +## configure, compare, and Guards + +```js +import { compare, configure, dayOfWeek, earliest, kindOf, latest } from 'native-dates'; + +configure({ + zone: 'America/New_York', // default IANA zone (null resets to system) + locale: 'en-US', // default locale (null resets to system) + weekStart: 'monday', // 1..7 or day name (null resets to locale-driven) + formats: { sql: 'YYYY-MM-DD HH:mm:ss' }, // null clears + weekdayNames: { lv: { narrow: { fri: 'Pk', sun: 'Sv' } } }, // width in [narrow, short, long] + ordinals: { fr: (day) => (day === 1 ? '1er' : day) }, +}); +``` + +- **`compare(a, b)` / `earliest(...items)` / `latest(...items)`:** Sorts `DateTime`, `CalendarDate`, `Time`, `YearMonth`, `Duration` (in `compare`), or same-kind ranges (accepts a single array or rest args in `earliest`/`latest`). A bare `Number` in first position (`compare(Date.now(), dt)`) is epoch milliseconds; a trailing `Number` after a `Time` (`compare(time('09:00'), 9)`) coerces to an hour. Mixing kinds (`compare(date, datetime)`) throws `conflictingKinds`. +- **`dayOfWeek(input)`:** Converts `'monday'`..`'sunday'`, 3-letter prefixes (`'mon'`), `1`–`7`, or `0` (mapped to `7`) into ISO `1`–`7`. +- **Cross-realm guards & brands:** `kindOf(x)` returns `'datetime' | 'date' | 'time' | 'duration' | 'monthDay' | 'yearMonth' | 'dateRange' | 'datetimeRange' | 'timeRange' | undefined`. Guards `isDateTime`, `isCalendarDate`, `isTime`, `isDuration`, `isMonthDay`, `isYearMonth`, `isDateRange`, `isDateTimeRange`, `isTimeRange` and `instanceof` use `Symbol.for` brands (`IS_DATE_TIME`, etc.) so they work across realms and duplicate bundles. + +--- + +## Errors + +Every refusal throws `RangeError` or `TypeError` formatted as `dates refused [code] ` with `.code` and `.at` properties: + +| Error code | Thrown when | +|---|---| +| `missingDateTime`, `missingDate`, `missingTime`, `missingMonthDay`, `missingYearMonth`, `missingDay`, `missingPoints`, `missingAnchor`, `missingPlugin` | Required argument, day (`date(2026, 11)`), anchor (`months(2).total('days')`), or plugin (`{ loose: true }` without `@native-dates/plugins/loose`) is missing | +| `invalidDateTime`, `invalidDate`, `invalidTime`, `invalidDuration`, `invalidMonthDay`, `invalidYearMonth`, `invalidRange`, `invalidStep`, `invalidNumber`, `invalidFraction`, `invalidYear`, `invalidDay`, `invalidPoint` | Unparseable syntax, out-of-range calendar field (`Feb 30`), non-positive `points()` step, or `end < start` on `DateRange`/`DateTimeRange` | +| `unknownZone`, `unknownLocale`, `unknownUnit`, `unknownDayOfWeek`, `unknownFormat`, `unknownKind`, `unknownSetting`, `unknownWidth` | Unrecognized IANA zone, BCP 47 tag, unit, weekday, token/preset, `as(kind)` target, or `configure()` key | +| `unsupportedUnit`, `unsupportedToken`, `unsupportedComparison`, `unsupportedZone`, `unsupportedCalendar`, `unsupportedIntersection` | Valid unit/token applied to a noun that lacks it (`hours` on `CalendarDate`), `<` / `-` coercion on non-`DateTime` points, or double-window overnight `TimeRange` intersection | +| `conflictingSigns`, `conflictingKinds`, `conflictingRanges` | `days(1).minus(hours(1))`, `compare(date, datetime)`, or passing a `TimeRange` to `dateRange()` | + +--- + +## Quick Reference + +```js +import { date, datetime, days, hours, monthDay, now, time, today, yearMonth } from 'native-dates'; + +// Zoned moment + DST-safe math + UTC wire output +const kickoff = datetime('2026-03-08T04:30:00Z', 'America/New_York').plus(1, 'day').at('09:30'); +kickoff.toJSON(); // '2026-03-09T13:30:00.000Z' +kickoff.epochSeconds; // 1773063000 + +// Calendar day + inclusive range + unit boundary +const billingWindow = today('Europe/Berlin').startOfNext('month').for(1, 'month'); // inclusive DateRange +const eachDay = billingWindow.points('day'); + +// Server-safe per-request locale + pinned ISO Monday week key +const userTime = datetime(row.createdAt, user.zone).locale(req.headers['accept-language']); +const label = userTime.fromNow(); // localized relative phrase +const weekBucket = userTime.date.startOf('week', 'monday').toString(); + +// Anchored calendar span vs fixed duration balancing +const ageDays = date('2026-01-15').until('2026-04-15', 'days'); // 90 +const totalHrs = hours(1).plus(days(2)).total('hours'); // 49 +``` + +**Golden rule: Pick the noun that matches the data (`datetime` for an exact moment in a zone, `date` for a calendar day, `time` for a wall clock, `yearMonth` or `monthDay` for partial dates), chain immutable methods rather than mutating, and pass explicit IANA zones or per-value `.locale()` in server code.** + +--- + +## Related Skills + +| Skill | Use when... | +|---|---| +| `native-dates-plugins` | Resolving city names (`'Berlin'`) or zone abbreviations (`'PST'`), parsing untrusted/slash strings with `{ loose: true, dayFirst }`, shimming legacy `Date` getters, loading `@native-dates/polyfill` for Safari, or writing a custom plugin | diff --git a/docs/src/lib/skills.js b/docs/src/lib/skills.js new file mode 100644 index 0000000..82a3ce9 --- /dev/null +++ b/docs/src/lib/skills.js @@ -0,0 +1,46 @@ +// reads downstream user skills from ai/skills/**/*.md for /skills/.md and /llms*.txt +import { existsSync, readdirSync, readFileSync } from 'node:fs'; +import { basename, resolve } from 'node:path'; +import { parse } from 'yaml'; + +import { PACKAGE_DIR } from './sizes.js'; + +const AUDIENCE_ORDER = ['essentials', 'usage', 'authoring']; + +function walkMarkdown(dir) { + if (!existsSync(dir)) { return []; } + return readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = resolve(dir, entry.name); + if (entry.isDirectory()) { return walkMarkdown(full); } + return entry.isFile() && entry.name.endsWith('.md') && entry.name !== 'README.md' ? [full] : []; + }); +} + +export function shippedSkills() { + const skillsRoot = resolve(PACKAGE_DIR, 'ai/skills'); + return walkMarkdown(skillsRoot) + .map((file) => { + const raw = readFileSync(file, 'utf8'); + const [, front = '', body = raw] = raw.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/) ?? []; + const data = front ? parse(front) : {}; + const stem = basename(file, '.md'); + const skill = data.skill ?? stem; + return { + skill, + title: data.title ?? skill, + description: data.description ?? '', + audience: data.audience ?? 'usage', + keywords: data.keywords ?? [], + type: data.type ?? 'skill', + raw, + body: `${body.replace(/^\s*\s*/, '').trim()}\n`, + }; + }) + .sort((a, b) => { + const rank = (audience) => { + const index = AUDIENCE_ORDER.indexOf(audience); + return index === -1 ? AUDIENCE_ORDER.length : index; + }; + return rank(a.audience) - rank(b.audience) || a.skill.localeCompare(b.skill); + }); +} diff --git a/docs/src/pages/llms-full.txt.js b/docs/src/pages/llms-full.txt.js index a6cd691..9c316eb 100644 --- a/docs/src/pages/llms-full.txt.js +++ b/docs/src/pages/llms-full.txt.js @@ -1,12 +1,22 @@ -// /llms-full.txt: every docs page's markdown in one file, in the sidebar's order +// /llms-full.txt: downstream agent skills first, followed by every docs page in sidebar order import { getCollection } from 'astro:content'; import { SECTIONS } from '../lib/nav.js'; import { markdownFor } from '../lib/page-markdown.js'; +import { shippedSkills } from '../lib/skills.js'; export async function GET({ site }) { + const skills = shippedSkills().map((entry) => + `\n\n${entry.body}` + ); const docs = new Map((await getCollection('docs')).map((e) => [e.id, e])); - const order = [...new Set(SECTIONS.flatMap((s) => s.groups.flatMap((g) => g.items.map((it) => it.slug.split('#')[0]))))]; - const pages = order.filter((id) => docs.has(id)).map((id) => `\n\n${markdownFor(docs.get(id))}`); - return new Response(pages.join('\n---\n\n'), { headers: { 'content-type': 'text/plain; charset=utf-8' } }); + const order = [ + ...new Set(SECTIONS.flatMap((s) => s.groups.flatMap((g) => g.items.map((it) => it.slug.split('#')[0])))), + ]; + const pages = order.filter((id) => docs.has(id)).map((id) => + `\n\n${markdownFor(docs.get(id))}` + ); + return new Response([...skills, ...pages].join('\n---\n\n'), { + headers: { 'content-type': 'text/plain; charset=utf-8' }, + }); } diff --git a/docs/src/pages/llms.txt.js b/docs/src/pages/llms.txt.js index 6bc78fa..6089e12 100644 --- a/docs/src/pages/llms.txt.js +++ b/docs/src/pages/llms.txt.js @@ -1,14 +1,20 @@ import { getCollection } from 'astro:content'; import { SECTIONS } from '../lib/nav.js'; +import { shippedSkills } from '../lib/skills.js'; -// links docs pages to /.md and examples to // because examples have no raw markdown route +// links agent skills first, then docs pages to /.md and examples to // export async function GET({ site }) { const docs = new Map((await getCollection('docs')).map((e) => [e.id, e])); const examples = new Map((await getCollection('examples')).map((e) => [`examples/${e.id}`, e])); const url = (path) => new URL(path, site).href; - const sections = SECTIONS.map((section) => { + const skillLines = shippedSkills().map((entry) => + `- [${entry.title}](${url(`/skills/${entry.skill}.md`)}): ${entry.description}` + ); + const skillSection = skillLines.length ? [`## Agent Skills\n\n${skillLines.join('\n')}`] : []; + + const docSections = SECTIONS.map((section) => { const seen = new Set(); const lines = section.groups.flatMap((g) => g.items).flatMap(({ slug }) => { if (slug.includes('#') || seen.has(slug)) { return []; } @@ -26,9 +32,11 @@ export async function GET({ site }) { > A readable, immutable date and time library built on the browser's Temporal and Intl APIs with zero dependencies. Core includes zoned datetimes, calendar dates, times, durations, year-months, month-days, ranges, formatting, and relative time. Opt-in subpath plugins add city and abbreviation zones, loose parsing, and legacy Date methods. -Every page below is also served as markdown at its path plus \`.md\`. The full docs in one file: ${url('/llms-full.txt')} +Every page below is also served as markdown at its path plus \`.md\`. The full docs in one file: ${ + url('/llms-full.txt') + } -${sections.join('\n\n')} +${[...skillSection, ...docSections].join('\n\n')} `; return new Response(body, { headers: { 'content-type': 'text/plain; charset=utf-8' } }); } diff --git a/docs/src/pages/skills/[name].md.js b/docs/src/pages/skills/[name].md.js new file mode 100644 index 0000000..9c984ad --- /dev/null +++ b/docs/src/pages/skills/[name].md.js @@ -0,0 +1,14 @@ +import { shippedSkills } from '../../lib/skills.js'; + +export function getStaticPaths() { + return shippedSkills().map((entry) => ({ + params: { name: entry.skill }, + props: { skill: entry }, + })); +} + +export function GET({ props }) { + return new Response(props.skill.raw, { + headers: { 'content-type': 'text/markdown; charset=utf-8' }, + }); +} diff --git a/package.json b/package.json index 872e7a3..b62d7ec 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,7 @@ "files": [ "src", "types", + "ai/skills", "README.md", "LICENSE" ], From f741a3fcdb0e86e55ba90f939af71261a6f8928d Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 18:00:45 -0500 Subject: [PATCH 2/4] Docs: Refine Consumer Skills from Cold Evals and Gate YAML Frontmatter --- ai/README.md | 4 +- ai/contributing/plan/landed.md | 1 + ai/contributing/plan/roadmap.md | 1 - ai/skills/native-dates-plugins.md | 186 +++++++++++--------- ai/skills/native-dates.md | 276 ++++++++++++++++-------------- package.json | 1 + tools/gates/ai.js | 15 +- tools/gates/ai.test.js | 42 +++++ 8 files changed, 314 insertions(+), 212 deletions(-) create mode 100644 tools/gates/ai.test.js diff --git a/ai/README.md b/ai/README.md index 6daa1ca..2fc5967 100644 --- a/ai/README.md +++ b/ai/README.md @@ -4,13 +4,13 @@ | Path | Audience | In npm package | |---|---|---| -| [`skills/`](skills/) | Agents building an app with `native-dates` | Planned (pre-1.0) | +| [`skills/`](skills/) | Agents building an app with `native-dates` | Yes | | [`contributing/`](contributing/README.md) | Contributors working on `native-dates` | No | | `workspace/` | Local scratch files, ignored by git | No | ## Consumer Skills -Files in [skills](skills/) will be included in the npm package for coding agents reading from installed dependencies, served by the docs site at `/skills/.md`, and listed in `/llms.txt` once authored (`contributing/plan/roadmap.md`). +Files in [skills](skills/) ([`native-dates.md`](skills/native-dates.md) and [`native-dates-plugins.md`](skills/native-dates-plugins.md)) are included in the npm package for coding agents reading from installed dependencies, served by the docs site at `/skills/.md`, and listed in `/llms.txt` and `/llms-full.txt`. Downstream agents receive a skill on its own without the rest of this repository. Read the [authoring standard](contributing/standards/ai-author-context.md) and the [skill workflow](contributing/workflows/author-user-skill.md) before writing or editing one. diff --git a/ai/contributing/plan/landed.md b/ai/contributing/plan/landed.md index ffc6e7e..66accdb 100644 --- a/ai/contributing/plan/landed.md +++ b/ai/contributing/plan/landed.md @@ -4,6 +4,7 @@ Completed roadmap items, newest first. When a planned feature in [`roadmap.md`]( | Date | Milestone | Summary | Brotli delta | |---|---|---|---| +| 2026-11-20 | Consumer agent skills | Downstream usage skills in [`ai/skills/`](../../skills/native-dates.md) published with the npm package and served at `/skills/.md`, `/llms.txt`, and `/llms-full.txt` | 0 B | | 2026-11-20 | North star | Project goals and design principles in [`north-star.md`](../north-star.md) | 0 B | | 2026-11-19 | Test suite | Unit and Chromium Playwright test suites across core, plugins, and polyfill | 0 B | | 2026-11-18 | Type declarations | Hand-authored `.d.ts` declarations, JSDoc examples, and `@see` links to `nativedates.dev` | 0 B | diff --git a/ai/contributing/plan/roadmap.md b/ai/contributing/plan/roadmap.md index d0247a7..b700b5b 100644 --- a/ai/contributing/plan/roadmap.md +++ b/ai/contributing/plan/roadmap.md @@ -6,7 +6,6 @@ Larger features with open design details keep a spec in `scopes/.md`. | Feature | Status | Summary | |---|---|---| -| Consumer agent skills | Ready to build | Publish downstream usage skills in `ai/skills/` with the npm package and serve them at `/skills/.md` and `/llms.txt` on the docs site | | Benchmark suite | Needs design | Automated browser benchmark suite in `bench/` measuring parsing, arithmetic, formatting, and range iteration across changes | | Documentation translations | Ready to build | Translated and reviewed guides, API references, and examples across the 8 supported locales | diff --git a/ai/skills/native-dates-plugins.md b/ai/skills/native-dates-plugins.md index fe0a171..928bbd8 100644 --- a/ai/skills/native-dates-plugins.md +++ b/ai/skills/native-dates-plugins.md @@ -1,6 +1,6 @@ --- title: Plugins, Loose Parsing, Zone Aliases, and Polyfill for native-dates -description: Companion guide for @native-dates/plugins (zones, loose, legacy-date), @native-dates/polyfill, and authoring custom native-dates plugins. Use whenever code parses non-ISO or slash dates ('11/06/2026', 'Oct 17, 2026', { loose: true, dayFirst }), resolves city names ('Berlin', 'Tokyo') or timezone abbreviations ('EST', 'PT', 'CET', zoneAliases), shims legacy Date.prototype getters (getFullYear, getMonth, getDay), polyfills Temporal for Safari/older browsers, or extends native-dates prototypes. +description: "Companion guide for @native-dates/plugins (zones, loose, legacy-date), @native-dates/polyfill, and authoring custom native-dates prototype plugins. Use whenever code parses non-ISO or slash/dot dates ('11/06/2026', '16.11.2026', 'Oct 17, 2026', { loose: true, dayFirst }), resolves IANA city names ('Berlin', 'Los Angeles') or timezone abbreviations ('EST', 'PT', 'CET', zoneAliases), shims legacy Date.prototype getters (getFullYear, getMonth, getDay), polyfills Temporal on Safari, older browsers, or Node <26, or extends native-dates class prototypes." keywords: ["@native-dates/plugins", "@native-dates/polyfill", "temporal-polyfill", zones, loose, legacy-date, dayFirst, zoneAliases, timezones, getFullYear, getTimezoneOffset, sideEffects, missingPlugin] audience: usage skill: native-dates-plugins @@ -10,164 +10,186 @@ type: skill # Plugins, Loose Parsing, Zone Aliases, and Polyfill for native-dates > **Skill:** `native-dates-plugins` -> **Purpose:** Guide to `@native-dates/plugins/{zones,loose,legacy-date}`, `@native-dates/polyfill`, and custom plugin authoring +> **Purpose:** Guide to `@native-dates/plugins/{zones,loose,legacy-date}`, `@native-dates/polyfill`, and custom prototype plugins -Optional conveniences that add lookup tables, `Date.parse` fallbacks, or legacy shims live in `@native-dates/plugins` so core `native-dates` stays ~14 kB Brotli with zero dependencies. Each plugin is a side-effect subpath module that installs its hooks or prototype methods once at import time, and `@native-dates/polyfill` conditionally loads `temporal-polyfill` only on runtimes missing `globalThis.Temporal`. +Each `@native-dates/plugins/*` subpath mutates `native-dates` hooks or prototypes once process-wide when imported (with no per-instance scoping or unload), and `@native-dates/polyfill` installs `temporal-polyfill` only when `globalThis.Temporal` is absent. -**Golden rule: Import plugins as bare subpaths (`import '@native-dates/plugins/loose'`) at startup with no `.use()` call, and remember `{ loose: true }` returns `null` only for malformed input data while still throwing on invalid caller options like a bad `zone` or `locale`.** +**Golden rule: Import plugin subpaths once at startup without `.use()`, pass `{ loose: true }` per call, and treat `{ loose: true }` as returning `null` for unreadable data while still throwing on bad options.** --- ## What You'd Get Wrong -**1. `@native-dates/plugins` has no root export and no `.use()` or `.extend()` registration.** Plugins self-attach when their subpath is imported; forgetting the import before passing `{ loose: true }`, `dayFirst`, or `zoneAliases` throws `RangeError` with `code: 'missingPlugin'`. +**1. `@native-dates/plugins` has no root barrel and no `.use()` or `.extend()` method.** Importing a subpath (`import '@native-dates/plugins/loose'` or `import { timezones } from '@native-dates/plugins/zones'`) registers it realm-wide and merges its TypeScript types. Using `{ loose: true }`, `dayFirst`, or `zoneAliases` before importing its plugin throws `RangeError` (`code: 'missingPlugin'`). ```js -// ❌ WRONG - no root barrel and no dayjs.extend() / .use() call +// ❌ WRONG - no root export and no dayjs.extend() / .use() registration import { loose, zones } from '@native-dates/plugins'; datetime.extend(loose); -// ✅ RIGHT - bare subpath imports register hooks once process-wide (and merge TypeScript declarations) +// ✅ RIGHT - subpath imports self-register once for the whole JS realm import '@native-dates/plugins/loose'; import '@native-dates/plugins/zones'; -import { date, datetime } from 'native-dates'; +import { datetime } from 'native-dates'; datetime('Nov 16, 2026 9:30am', { zone: 'Berlin', loose: true }); ``` -**2. `{ loose: true }` returns `null` for unreadable input data, NOT for invalid caller configuration.** Passing an unknown `zone` or `locale` alongside `{ loose: true }` still throws `unknownZone` or `unknownLocale` so programmer typos are never masked as empty user input. +**2. Strict core parsing always runs first; `{ loose: true }` is per-call only, defaults `'06/11/2026'` to US month-first (`June 11`), and still throws on bad caller options.** `configure({ loose: true })` throws `unknownSetting`, and `configure({ dayFirst: true })` only affects calls that also pass `{ loose: true }`. Under `{ loose: true }`, `null`, `undefined`, `""`, `NaN`, `'16/11/2026'` (without `dayFirst`), rolled-forward `'Feb 30, 2026'`, and non-English month names in `date()`/`datetime()` all return `null` (`T | null` in TypeScript, never *now*), whereas bad options (`zone: 'Mars/Olympus'`, `locale: '123'`) still throw `unknownZone` or `unknownLocale`. ```js -// ❌ WRONG assumption - expecting { loose: true } to swallow a bad zone option -datetime('2026-11-16', { zone: 'Mars/Olympus', loose: true }); // throws RangeError [unknownZone] - -// ✅ RIGHT - { loose: true } turns malformed input strings/numbers into null (and rejects rolled-forward 'Feb 30') -date('not a date', { loose: true }); // null -date('Feb 30, 2026', { loose: true }); // null (Date.parse rollover into March is caught and rejected) +// ❌ WRONG - omitting { loose: true } after configure({ dayFirst: true }), or assuming French date() works +configure({ dayFirst: true }); +date('16/11/2026'); // RangeError [invalidDate] — { loose: true } was omitted! +date('17 octobre 2026', { loose: true, locale: 'fr' }); // null — date()/datetime() month names are English-only + +// ✅ RIGHT - pass { loose: true } per call; slash, dot, and hyphen numeric strings honor dayFirst +date('16.11.2026', { loose: true }); // CalendarDate(2026-11-16) because dayFirst is configured +date(undefined, { loose: true }); // null (never defaults to today/now) +monthDay('17 octobre', { loose: true, locale: 'fr' }); // MonthDay(10-17) — partials DO match Intl locales ``` -**3. Bare IANA `'EST'`, `'MST'`, and `'HST'` behave differently once `@native-dates/plugins/zones` is imported.** Without the plugin, `Temporal` treats `'EST'` as a legacy fixed `-05:00` zone with no daylight saving time. `@native-dates/plugins/zones` maps `'EST'`, `'EDT'`, `'ET'`, and `'Eastern'` to `'America/New_York'` (`'MST'` -> `'America/Denver'`, `'PST'`/`'PT'` -> `'America/Los_Angeles'`) so summer dates observe DST. Use `'-05:00'` when you genuinely want a fixed year-round offset. +**3. `@native-dates/plugins/zones` maps `'EST'`/`'MST'`/`'HST'` to DST-observing zones and resolves IANA leaf cities, NOT arbitrary world cities.** Without `zones`, `Temporal` treats `'EST'` as fixed `-05:00`; with `zones`, `'EST'`/`'EDT'`/`'ET'` map to `'America/New_York'` (pass `'-05:00'` for a fixed offset). City lookup indexes `Intl.supportedValuesOf('timeZone')` leaf names and tzdb links, so `'Berlin'`, `'Los Angeles'`, and `'Ho Chi Minh'` resolve, while non-IANA cities like `'San Francisco'`, `'Munich'`, or `'Mumbai'` throw `unknownZone` unless mapped via `configure({ zoneAliases })`. -**4. `legacy-date` reads local `Date` getters in `dt.zone`, not the host machine's OS timezone, and throws `immutable` on setters.** Calling `dt.getHours()` or `dt.getDay()` returns the hour and `0`–`6` weekday in `dt.zone` regardless of the server's timezone, while `dt.getMonth()` returns `0`–`11` to match `Date.prototype.getMonth()` (unlike `dt.month`, which stays `1`–`12`). +**4. `legacy-date` attaches only to `DateTime.prototype`, evaluates local `Date` getters in `dt.zone` (not the host OS timezone), and throws `immutable` on setters.** `CalendarDate` and `Time` get no `Date` methods. On `DateTime`, `dt.getHours()` and `dt.getDay()` (`0`–`6`) read in `dt.zone` even on a UTC server, `dt.getMonth()` returns `0`–`11` (`dt.month` stays `1`–`12`), and all `set*`/`setUTC*` mutators throw `RangeError` (`code: 'immutable'`). ```js import '@native-dates/plugins/legacy-date'; import { datetime } from 'native-dates'; const tokyo = datetime('2026-11-16T00:30:00Z', 'Asia/Tokyo'); -tokyo.getHours(); // 9 (09:30 in Tokyo, even on a UTC server) -tokyo.getMonth(); // 10 (0-indexed legacy shim; tokyo.month is still 11) -tokyo.setHours(12); // throws RangeError [immutable] — use tokyo.set('hour', 12) instead +tokyo.getHours(); // 9 (09:30 in Tokyo, regardless of server OS timezone) +tokyo.getMonth(); // 10 (0-indexed; tokyo.month is 11) +tokyo.setHours(12); // RangeError [immutable] — use tokyo.set('hour', 12) ``` -**5. `@native-dates/polyfill` uses top-level `await` on its default entry.** Default `import '@native-dates/polyfill'` dynamically imports `temporal-polyfill` only when `!globalThis.Temporal` so modern browsers download 0 polyfill bytes. In CommonJS or bundler targets that disallow top-level `await`, import `'@native-dates/polyfill/sync'` instead, and list `temporal-polyfill` (`>=0.3.0`) in your app's `dependencies`. +**5. Node `<26` (Node 20/22/24 LTS) and Safari require both `@native-dates/polyfill` AND `"temporal-polyfill": ">=0.3.0"` in your app's `dependencies`.** Bundlers statically resolve `import('temporal-polyfill')`, so omitting `"temporal-polyfill"` from `package.json` breaks builds even when targeting Chrome. Use `'@native-dates/polyfill/sync'` in CommonJS or build targets without top-level `await`. --- ## @native-dates/plugins/zones -Resolves city names, common timezone abbreviations, case/diacritic variations, IANA tzdb link names, and custom `zoneAliases` anywhere a `zone` is accepted (`datetime`, `now`, `today`, `in`, `at`, `configure`). +Resolves IANA leaf cities, tzdb links, timezone abbreviations, and custom `zoneAliases` anywhere a `zone` parameter or `[Zone]` suffix is accepted (`datetime`, `date`, `time`, `now`, `today`, `in`, `at`, `configure`). Named `import { timezones } from '@native-dates/plugins/zones'` registers the plugin automatically without a second bare import. ```js -import '@native-dates/plugins/zones'; import { timezones } from '@native-dates/plugins/zones'; import { configure, datetime } from 'native-dates'; -datetime('2026-11-16T09:30', 'Berlin').zone; // 'Europe/Berlin' -datetime('2026-11-16T09:30', 'são_paulo').zone; // 'America/Sao_Paulo' -datetime('2026-11-16T09:30', 'PT').zone; // 'America/Los_Angeles' +timezones.IST = 'Asia/Jerusalem'; // override default 'Asia/Kolkata' +configure({ zoneAliases: { hq: 'Berlin', sf: 'America/Los_Angeles' } }); // merges & eagerly resolves targets! -configure({ zoneAliases: { hq: 'Europe/Berlin', warehouse: 'America/Chicago' } }); -datetime('2026-11-16T09:30', 'hq').zone; // 'Europe/Berlin' +datetime('2026-11-16T09:30', 'HQ').zone; // 'Europe/Berlin' (case/space/underscore/accent-insensitive) +datetime('2026-11-16T09:30', 'são_paulo').zone; // 'America/Sao_Paulo' ``` -| Resolution layer | Examples | Notes | +| Precedence (1 = highest) | Source & examples | Override / behavior | |---|---|---| -| `configure({ zoneAliases })` | `{ hq: 'Europe/Berlin' }` | Highest precedence; pass `{ hq: null }` to delete one alias or `zoneAliases: null` to clear all | -| Exported `timezones` map | `ET`, `CT`, `MT`, `PT`, `UK`, `CET`, `IST` (`Asia/Kolkata`), `JST`, `AET`, `BRT`, `NZT`, `SGT` | Mutable object (`timezones.IST = 'Asia/Jerusalem'`) for ambiguous regional codes | -| Built-in abbreviations | `EST`/`EDT`/`Eastern`, `CST`/`CDT`, `MST`/`MDT`, `PST`/`PDT`/`Pacific`, `BST`, `CEST`, `GMT`, `Z` | Maps to full DST-observing IANA zones (`GMT` and `Z` -> `'UTC'`) | -| Runtime IANA & city lookup | `'los angeles'`, `'buenos aires'`, `'ho chi minh'`, `'europe/paris'` | Case-, underscore-, and accent-insensitive against `Intl.supportedValuesOf('timeZone')` and `Temporal` | +| 1. `configure({ zoneAliases })` | `{ hq: 'Berlin', sf: 'America/Los_Angeles' }` | Merges across calls; validates/resolves targets eagerly (`unknownZone` if invalid); `{ hq: null }` deletes one key, `zoneAliases: null` clears all | +| 2. Exported `timezones` object | `ET`, `CT`, `MT`, `PT`, `AKT`, `HT`, `AT`, `UK`, `WET`, `CET`, `ECT`, `EET`, `IRST`, `AET`, `ACT`, `AWT`, `NZT`, `BRT`, `IST` (`Asia/Kolkata`), `INST`, `JST`, `SGT` | Mutable map for ambiguous regional codes (`timezones.IST = '...'`) | +| 3. Built-in abbreviations | `EST`/`EDT`/`Eastern`, `CST`/`CDT`/`Central`, `MST`/`MDT`/`Mountain`, `PST`/`PDT`/`Pacific`, `AKST`/`AKDT`/`Alaska`, `HST`/`Hawaii`, `BST`, `CEST`, `KST`, `AEST`/`AEDT`, `NZST`/`NZDT`, `HKT`, `GMT`, `Z` | Maps to DST-observing IANA zones (`GMT` & `Z` -> `'UTC'`); override via `zoneAliases` | +| 4. IANA IDs, leaf cities & tzdb links | `'los angeles'`, `'buenos aires'`, `'ho chi minh'`, `'europe/paris'` | Case/accent/separator-insensitive against `Intl.supportedValuesOf('timeZone')` and `Temporal` `/` links | --- ## @native-dates/plugins/loose -Enables `{ loose: true }` and `dayFirst` on `datetime()`, `date()`, `time()`, `duration()`, `monthDay()`, `dayMonth()`, `yearMonth()`, `monthYear()`, `dateRange()`, `datetimeRange()`, `timeRange()`, and `configure({ dayFirst })`. - -```js -import '@native-dates/plugins/loose'; -import { configure, date, datetime, monthDay, yearMonth } from 'native-dates'; - -date('11/06/2026', { loose: true }); // CalendarDate(2026-11-06) — US month-first default -date('06/11/2026', { loose: true, dayFirst: true }); // CalendarDate(2026-11-06) — European day-first -datetime('Sep 6, 2026 9:30 PM EDT', { loose: true, zone: 'America/New_York' }); -monthDay('17 octobre', { loose: true, locale: 'fr' }); // MonthDay(10-17) -yearMonth('noviembre de 2026', { loose: true, locale: 'es' }); // YearMonth(2026-11) -date('', { loose: true }); // null -``` +When strict core parsing fails and `{ loose: true }` is passed, factories fall back as follows (`T | null` in TypeScript): -| Input / Option | Behavior under `{ loose: true }` | -|---|---| -| Numeric slash/dot/dash `'06/11/2026'` | Month-first by default; set `{ dayFirst: true }` per call or `configure({ dayFirst: true })` globally for `DD/MM/YYYY` | -| Rolled-forward calendar dates (`'Feb 30, 2026'`, `'11/31/2026'`) | Caught and returned as `null` instead of letting `Date.parse` silently roll into the next month | -| Named months in `monthDay` / `yearMonth` | Matches English first (so `'Mar 17'` stays March even under `'fi'`), then `Intl` month names in `{ locale }` or `configure({ locale })` | -| Unreadable strings, `null`, `undefined`, `NaN` | Returns `null` (`TypeScript` return type widens to `T \| null` when `{ loose: true }` is passed) | -| Two-digit ISO `'10-17'` in `dayMonth()` | Always stays month-first (`October 17`) so ISO `toJSON()` strings round-trip, whereas `'17/10'` reads day-first | +- **`datetime()` and `date()` (`Date.parse` fallback):** + - Accepts English month names (`'Oct 17, 2026'`) and numeric slash/dot/hyphen dates (`'11/06/2026'`, `'06.11.2026'`, `'06-11-2026'`, 2-digit years `'11/06/26'` -> `2026`). Without `dayFirst: true`, `'16/11/2026'` returns `null` (never auto-flips `16 > 12`). + - Catches `Date.parse` calendar rollovers (`'Feb 30, 2026'`, `'11/31/2026'` -> `null`), as well as `null`, `undefined`, `""`, `NaN`, `{}` (`-> null`). + - **Zone handling:** Unzoned strings keep their written wall clock in `zone` (defaulting to `configure({ zone })` or system local IANA zone). Inline zone tokens inside strings rely strictly on native `Date.parse` (`Z`, numeric `+02:00`, `GMT`/`UTC`, US `EST`/`EDT`/`CST`/`CDT`/`MST`/`MDT`/`PST`/`PDT`) to fix the instant and convert to `zone` — inline tokens do **not** consult `zones` plugin `timezones` or `zoneAliases` (`'Nov 16, 2026 9am IST'` or `'... HQ'`; pass `{ zone: 'IST' }` as an option instead). +- **`time()`:** Extracts `.toPlainTime()` from any loose date-time string (`time('Nov 16, 2026 5:30 PM', { loose: true })` -> `17:30:00`), or returns `null`. +- **`monthDay()`, `dayMonth()`, `yearMonth()`, `monthYear()`:** Matches English month names first (`'Mar 17'` stays March under `'fi'`), then localized `Intl` month names in `{ locale }` or `configure({ locale })`. Two-digit ISO `'10-17'` with a hyphen stays month-first even in `dayMonth('10-17')`, whereas `'17/10'` reads day-first. +- **`duration()`:** Core already parses `'2h 30m'` and `'90 mins'`; `{ loose: true }` returns `null` on unreadable text, `unknownUnit` (`'5 lightyears'`), `conflictingSigns`, `invalidFraction`, or `NaN`. +- **`dateRange()`, `datetimeRange()`, `timeRange()`:** Forwards `{ loose: true, dayFirst, zone, locale }` to both endpoints and returns `null` if either endpoint is unreadable; valid endpoints with `end < start` on `DateRange`/`DateTimeRange` still throw `invalidRange`. --- ## @native-dates/plugins/legacy-date -Attaches `Date.prototype` read methods onto `DateTime.prototype` for incremental migration where downstream helpers still call `Date` getters directly (note: `.toJSDate()` is already in core without this plugin). +Attaches `Date.prototype` shims to `DateTime.prototype` only (`valueOf()` / `+dt` and `toJSDate()` already exist in core): -- **Zone-aware local getters:** `getFullYear()`, `getMonth()` (`0`–`11`), `getDate()` (`1`–`31`), `getDay()` (`0`–`6`, Sunday = `0`), `getHours()`, `getMinutes()`, `getSeconds()`, `getMilliseconds()`, and `getTimezoneOffset()` (minutes positive west of UTC, matching `Date`) all evaluate in `this.zone`. -- **UTC & string getters:** `getTime()`, `getUTCFullYear()`, `getUTCMonth()`, `getUTCDate()`, `getUTCDay()`, `getUTCHours()`, `getUTCMinutes()`, `getUTCSeconds()`, `getUTCMilliseconds()`, `toISOString()` (fixed `.sssZ`), `toLocaleString(locales?, options?)`, `toLocaleDateString(...)`, `toLocaleTimeString(...)` (defaulting to `this.locale()` and `this.zone`). -- **Mutator guard:** All 15 `set*` / `setUTC*` methods (`setHours`, `setMonth`, `setTime`, ...) throw `RangeError` with `code: 'immutable'`. +- **Shimmed reads (22):** Zone-local `get{FullYear,Month,Date,Day,Hours,Minutes,Seconds,Milliseconds}()` and `getTimezoneOffset()` (minutes positive west of UTC in `this.zone`); UTC `getTime()` and `getUTC*()` (8 methods); `toISOString()` (fixed `.sssZ`); and `toLocale{,Date,Time}String(locales?, opts?)` (defaulting to `this.locale()` and `this.zone`). +- **Not shimmed / blocked:** `toDateString()` and `toUTCString()` are omitted (use `dt.toJSDate().toUTCString()`); all 15 `set*` and `setUTC*` methods throw `RangeError` (`code: 'immutable'`). --- ## @native-dates/polyfill -```js -// Entrypoint of an app supporting Safari or older browsers (install temporal-polyfill >= 0.3.0): -import '@native-dates/polyfill'; -import { now, today } from 'native-dates'; -``` +`native-dates` reads `globalThis.Temporal` lazily at call time; import the polyfill at entrypoint startup before calling factories (with `"temporal-polyfill": ">=0.3.0"` installed): -- **`@native-dates/polyfill` (default):** Checks `if (!globalThis.Temporal)` and runs `await import('temporal-polyfill')`, splitting the polyfill into an on-demand chunk skipped by Chrome, Firefox, Edge, and Node `>=26`. -- **`@native-dates/polyfill/sync`:** Synchronous import of `temporal-polyfill` for CommonJS bundles or build targets without top-level `await`. +| Entrypoint | Mechanism | Target environments | +|---|---|---| +| `import '@native-dates/polyfill'` | `if (!globalThis.Temporal) await import('temporal-polyfill')` | ESM browsers (0 B downloaded on Chrome/Firefox/Edge; dynamic chunk on Safari) & ESM on Node `<26` | +| `import '@native-dates/polyfill/sync'` | Sync `import { Temporal } from 'temporal-polyfill'` + `if (!globalThis.Temporal)` | CommonJS bundles, test setups, or bundler targets disallowing top-level `await` | --- ## Authoring Custom Plugins -1. **Mutate `Class.prototype` purely:** Instances are frozen, so plugin methods return new instances (`this.plus(...)`, `new CalendarDate(...)`) rather than mutating `this`. -2. **Check brands, never `constructor.name`:** Use `IS_DATE_TIME`, `IS_CALENDAR_DATE`, `IS_TIME`, `IS_DURATION`, `IS_MONTH_DAY`, `IS_YEAR_MONTH`, `IS_RANGE`, or `kindOf(value)` from `'native-dates'` so checks survive realms and duplicate bundler copies. -3. **Declare `"sideEffects"` and `"peerDependencies"`:** Mark plugin entry files in `"sideEffects": ["./index.js"]` (never `"sideEffects": false`, or bundlers drop bare `import 'my-plugin'` statements) and put `"native-dates"` in `peerDependencies`. -4. **Augment TypeScript types:** Use `declare module 'native-dates' { interface CalendarDate { ... } }`. +Parser and zone hooks (`native-dates/helpers/*`) are private to `@native-dates/plugins` without semver guarantees. Third-party plugins extend the 9 exported class prototypes (`DateTime`, `CalendarDate`, `Time`, `Duration`, `MonthDay`, `YearMonth`, `DateRange`, `DateTimeRange`, `TimeRange`): + +- **Cross-realm identity:** `kindOf(v)` returns `'datetime' | 'date' | 'time' | 'duration' | 'monthDay' | 'yearMonth' | 'dateRange' | 'datetimeRange' | 'timeRange' | undefined`. Exported `Symbol.for` keys (`IS_DATE_TIME`, `IS_CALENDAR_DATE`, `IS_TIME`, `IS_DURATION`, `IS_MONTH_DAY`, `IS_YEAR_MONTH`, `IS_RANGE`, `IS_DATE_RANGE`, `IS_DATE_TIME_RANGE`, `IS_TIME_RANGE`) are **property keys** (`Boolean(v?.[IS_CALENDAR_DATE])`, never called as functions), alongside predicate functions `isDateTime(v)`, `isCalendarDate(v)`, etc. +- **Immutability & packaging:** Instances are frozen (`this.date`, `this.time`, `this.zone` are getters; `this.locale()` is a 0-arg getter / 1-arg clone method). Return new instances, list entry files in `"sideEffects": ["./index.js"]`, and put `"native-dates"` in `"peerDependencies"`. + +```ts +// my-business-days-plugin/index.ts +import { CalendarDate, DateTime, IS_CALENDAR_DATE, kindOf } from 'native-dates'; + +declare module 'native-dates' { + interface CalendarDate { + nextBusinessDay(): CalendarDate; + } + interface DateTime { + nextBusinessDay(): DateTime; + } +} + +CalendarDate.prototype.nextBusinessDay = function nextBusinessDay() { + const step = this.dayOfWeek === 5 ? 3 : this.dayOfWeek === 6 ? 2 : 1; + return this.plus(step, 'days'); +}; + +DateTime.prototype.nextBusinessDay = function nextBusinessDay() { + return this.date.nextBusinessDay().at(this.time, this.zone).locale(this.locale()); +}; + +export const isSupportedPoint = (v: unknown) => Boolean((v as any)?.[IS_CALENDAR_DATE]) || kindOf(v) === 'datetime'; +``` --- ## Quick Reference +| Untrusted / edge-case situation | Outcome | Idiom | +|---|---|---| +| Untrusted `rawText` AND untrusted `zoneName` | `loose` returns `null` for `rawText`, but throws `unknownZone` on `zoneName` | Wrap in `try/catch` checking `err?.code === 'unknownZone'` | +| Non-IANA city (`'San Francisco'`, `'Mumbai'`) | Throws `unknownZone` | Register `configure({ zoneAliases: { sf: 'America/Los_Angeles', mumbai: 'Asia/Kolkata' } })` | +| Non-US inline zone in string (`'Nov 16 9am IST'`) | `Date.parse` returns `null` (doesn't read `timezones`) | Strip or pass zone separately: `datetime('Nov 16, 2026 9am', { zone: 'IST', loose: true })` | +| `16/11/2026` without `dayFirst: true` | Returns `null` under `{ loose: true }` | Pass `{ loose: true, dayFirst: true }` (or `configure({ dayFirst: true })` + `{ loose: true }`) | +| Fixed `-05:00` year-round after importing `zones` | `'EST'` now observes EDT in summer | Pass explicit offset string `'-05:00'` instead of `'EST'` | + ```js -import '@native-dates/polyfill'; // only when targeting runtimes without native Temporal -import '@native-dates/plugins/zones'; +import '@native-dates/polyfill/sync'; +import { timezones } from '@native-dates/plugins/zones'; import '@native-dates/plugins/loose'; -import '@native-dates/plugins/legacy-date'; -import { configure, date, datetime } from 'native-dates'; - -configure({ - dayFirst: true, - zoneAliases: { office: 'Europe/London' }, -}); +import { configure, datetime } from 'native-dates'; -const parsed = date(userInput, { loose: true }); // CalendarDate | null ('16/11/2026' -> 2026-11-16) -const meeting = datetime('2026-11-16T14:00', 'office'); // zone: 'Europe/London' -meeting.getHours(); // 14 (via legacy-date) +timezones.IST = 'Asia/Jerusalem'; +configure({ dayFirst: true, zoneAliases: { sf: 'America/Los_Angeles' } }); + +export function parseCsvTimestamp(rawText, rawZone) { + try { + return datetime(rawText, { zone: rawZone, loose: true }); // DateTime | null (null if rawText is null/""/invalid) + } catch (err) { + if (err?.code === 'unknownZone') { return null; } + throw err; + } +} ``` -**Golden rule: Import plugins as bare subpaths (`import '@native-dates/plugins/loose'`) at startup with no `.use()` call, and remember `{ loose: true }` returns `null` only for malformed input data while still throwing on invalid caller options like a bad `zone` or `locale`.** +**Golden rule: Import plugin subpaths once at startup without `.use()`, pass `{ loose: true }` per call, and treat `{ loose: true }` as returning `null` for unreadable data while still throwing on bad options.** --- @@ -175,4 +197,4 @@ meeting.getHours(); // 14 (via legacy-date) | Skill | Use when... | |---|---| -| `native-dates` | Core classes (`DateTime`, `CalendarDate`, `Time`, `Duration`, `MonthDay`, `YearMonth`, ranges), DST-safe arithmetic, `format()` presets and tokens, `.locale()`, `weekStart`, `compare()`, and error codes | +| `native-dates` | Core classes (`DateTime`, `CalendarDate`, `Time`, `Duration`, `MonthDay`, `YearMonth`, ranges), DST-safe arithmetic, `round()`, `format()` presets and tokens, `.locale()`, `weekStart`, `compare()`, and error codes | diff --git a/ai/skills/native-dates.md b/ai/skills/native-dates.md index 373e678..48c250c 100644 --- a/ai/skills/native-dates.md +++ b/ai/skills/native-dates.md @@ -1,7 +1,7 @@ --- title: Dates, Times, Zones, Durations, and Ranges with native-dates -description: Core guide for building with native-dates (and @native-dates/core). Use whenever code creates, parses, shifts, rounds, compares, ranges over, or formats dates, clock times, zoned timestamps, durations, billing months, or recurring month-days, handles DST or HTTP Accept-Language locales, or migrates off Date, Moment, Day.js, or raw Temporal. For city/abbreviation zones, { loose: true } parsing, legacy Date getters, or the Safari Temporal polyfill, also load native-dates-plugins. -keywords: [native-dates, "@native-dates/core", datetime, date, time, duration, monthDay, yearMonth, dateRange, datetimeRange, timeRange, today, now, fromNow, weekStart, dayOfWeek, epochSeconds, epochMilliseconds, configure, Temporal, Intl, DST] +description: "Core guide for building with native-dates (and @native-dates/core). Use whenever code creates, parses, shifts, rounds, compares, ranges over, or formats dates, clock times, zoned timestamps, durations, billing months, or recurring month-days, handles DST or HTTP Accept-Language locales, or migrates off Date, Moment, Day.js, date-fns, Luxon, or raw Temporal. For city/abbreviation zones, { loose: true } parsing, legacy Date getters, or the Temporal polyfill on Safari and Node <26, also load native-dates-plugins." +keywords: [native-dates, "@native-dates/core", datetime, date, time, duration, monthDay, yearMonth, dateRange, datetimeRange, timeRange, today, now, dayOfWeek, epochSeconds, epochMilliseconds, configure, Accept-Language, Temporal, Intl, DST] audience: usage skill: native-dates type: skill @@ -12,227 +12,251 @@ type: skill > **Skill:** `native-dates` > **Purpose:** Core mental model, pitfalls, and API reference for `native-dates` (`@native-dates/core`) -`native-dates` wraps the platform's `Temporal` and `Intl` APIs with immutable classes and zero runtime dependencies. Instead of routing every concept through one `Date` object, each kind of value has its own class and factory so invalid operations (adding hours to a calendar date, comparing a date to a zoned timestamp, or mutating a shared instance) fail immediately with a coded error. +`native-dates` (`@native-dates/core` is the identical scoped package) wraps `Temporal` and `Intl` with 9 immutable, `Object.freeze`d classes and zero runtime dependencies. Chrome, Firefox, Edge, and Node `>=26` run it natively; load `native-dates-plugins` when targeting Safari or Node `<26` (`@native-dates/polyfill`), parsing `'11/16/2026'` or informal strings (`{ loose: true }`), resolving `'PST'`/`'Berlin'` zones, or shimming `Date` getters. -**Golden rule: Pick the noun that matches the data (`datetime` for an exact moment in a zone, `date` for a calendar day, `time` for a wall clock, `yearMonth` or `monthDay` for partial dates), chain immutable methods rather than mutating, and pass explicit IANA zones or per-value `.locale()` in server code.** +**Golden rule: Match the class to the data (`datetime` for zoned instants, `date` for calendar days, `time` for clocks), chain immutable methods, and pass explicit IANA zones and per-value `.locale()` in server code.** --- ## What You'd Get Wrong -**1. Trailing `Z` and numeric offsets (`-05:00`) fix the instant, not `.zone`.** Database and JSON timestamps routinely arrive with `Z`. Adopting `'UTC'` as `.zone` would silently disable daylight-saving rules on subsequent `.plus(1, 'day')` or `.startOf('day')` calls. `.zone` comes from the explicit `zone` argument, a bracketed `[Zone]` suffix, `configure({ zone })`, or the runtime's local zone, while `toString()` and `toJSON()` always serialize standard ISO 8601 UTC (`...Z`). +**1. Trailing `Z` and numeric offsets (`-05:00`) fix the instant, not `.zone`.** Database and JSON timestamps arrive with `Z`; adopting `'UTC'` as `.zone` would disable daylight-saving rules on `.plus(1, 'day')` or `.startOf('day')`. `.zone` resolves from the explicit `zone` argument -> bracketed `[Zone]` suffix -> `configure({ zone })` -> system zone, while `toString()` and `toJSON()` always emit UTC `...Z` (core has no `.toISOString()` or `.toISO()`). ```js -// ❌ WRONG - assuming 'Z' sets .zone to 'UTC' +// ❌ WRONG - assuming 'Z' sets .zone to 'UTC', or calling .toISOString() const dt = datetime('2026-03-08T04:30:00Z'); dt.zone; // local or configured zone (NOT 'UTC') -// ✅ RIGHT - pass 'UTC' when you want UTC wall-clock fields, or pass the user's IANA zone for DST-safe math +// ✅ RIGHT - pass 'UTC' for UTC wall fields, or pass the user's IANA zone for DST-safe calendar math const utc = datetime('2026-03-08T04:30:00Z', 'UTC'); const ny = datetime('2026-03-08T04:30:00Z', 'America/New_York').plus(1, 'day'); // crosses spring-forward at local 23:30 ny.toJSON(); // '2026-03-09T03:30:00.000Z' ``` -**2. `month` is `1`–`12` and `dayOfWeek` is ISO `1`–`7` (`7` = Sunday), not `0`-indexed.** `isWeekday()` is `true` Monday–Friday (`1`–`5`) and `false` on weekends (`6`–`7`). In token patterns, `'E'` outputs `'1'`–`'7'` while `'d'` keeps Moment/Day.js's `'0'`–`'6'` (`'0'` = Sunday). +**2. `month` is `1`–`12`, `dayOfWeek` is ISO `1`–`7` (`7` = Sunday), and tokens use Moment/Day.js casing (`YYYY-MM-DD`, never `yyyy-MM-dd`).** `isWeekday()` is `true` Monday–Friday (`1`–`5`). In `format()`, `'yyyy'` throws `unsupportedToken`, lowercase `'dd'` prints the 2-letter weekday (`'Mo'`, not day-of-month `'DD'`), `'E'` prints `'1'`–`'7'`, and `'d'` prints Moment's `'0'`–`'6'` (`'0'` = Sunday). ```js -// ❌ WRONG - JS Date / Moment 0-indexed months or Sunday = 0 on .dayOfWeek +// ❌ WRONG - 0-indexed month/Sunday, or date-fns/Luxon 'yyyy-MM-dd' tokens date(2026, 0, 15); // RangeError [invalidDate] -if (d.dayOfWeek === 0) { /* never true: Sunday is 7 */ } +date('2026-11-16').format('yyyy-MM-dd'); // RangeError [unsupportedToken] ('dd' is narrow weekday 'Mo'!) -// ✅ RIGHT - 1 = January..12 = December, 1 = Monday..7 = Sunday -const d = date(2026, 1, 15); -d.month; // 1 -date('2026-11-15').dayOfWeek; // 7 (Sunday) -date('2026-11-15').format('E'); // '7' (token 'd' prints '0') +// ✅ RIGHT - 1..12 months, 1..7 ISO weekdays, 'YYYY-MM-DD' tokens +const sun = date(2026, 11, 15); +sun.dayOfWeek; // 7 (Sunday) +sun.format('YYYY-MM-DD (E / d)'); // '2026-11-15 (7 / 0)' ``` -**3. Unix timestamp properties require an explicit unit — there is no bare `.epoch` or `.timestamp`.** Shells, Python, SQL, and JWT `exp`/`iat` claims count seconds while `Date.now()` counts milliseconds, so every epoch property names its unit. +**3. Unix timestamps name their unit explicitly.** Neither `.epoch`, `.timestamp`, nor `.unix()` exists. ```js -// ❌ WRONG - undefined! No .epoch or .timestamp property exists +// ❌ WRONG - undefined! const exp = now().epoch; -// ✅ RIGHT - choose epochSeconds (Number, floored), epochMilliseconds (Number), or epochNanoseconds (BigInt) +// ✅ RIGHT - epochSeconds (Number, floored), epochMilliseconds (Number), or epochNanoseconds (BigInt) const jwtExp = now().plus(15, 'minutes').epochSeconds; -const ms = now().epochMilliseconds; // also returned by valueOf() +const ms = now().epochMilliseconds; ``` -**4. `next()` and `previous()` step to weekdays or `MonthDay`s and preserve clock time; `startOfNext()` and `startOfPrevious()` step to unit boundaries at `00:00`.** Passing a unit like `'month'` to `next()` throws `unknownDayOfWeek`, and passing a number like `2` to `startOfNext()` throws `unknownUnit`. +**4. `next()` / `previous()` step strictly to future/past weekdays or `MonthDay`s at the same clock time; `startOfNext()` / `startOfPrevious()` step to unit boundaries at `00:00`.** Calling `next('friday')` on a Friday advances `+7` days (`previous('friday')` steps `-7` days). Passing a unit like `'month'` to `next()` throws `unknownDayOfWeek`, and passing a count like `2` to `startOfNext()` throws `unknownUnit`. ```js // ❌ WRONG - passing a calendar unit to next() -datetime('2026-11-16T09:30', 'UTC').next('month'); // throws [unknownDayOfWeek] +datetime('2026-11-16T09:30', 'UTC').next('month'); // RangeError [unknownDayOfWeek] -// ✅ RIGHT - use next('friday') for same-clock weekday steps, startOfNext('month') for 00:00 unit boundaries -datetime('2026-11-16T09:30', 'UTC').next('friday'); // 2026-11-20T09:30:00Z -datetime('2026-11-16T09:30', 'UTC').startOfNext('month'); // 2026-12-01T00:00:00Z +// ✅ RIGHT - next('friday') keeps 09:30; startOfNext('month') lands on Dec 1 00:00 +datetime('2026-11-16T09:30', 'UTC').next('friday'); // 2026-11-20T09:30:00.000Z +datetime('2026-11-16T09:30', 'UTC').startOfNext('month'); // 2026-12-01T00:00:00.000Z ``` -**5. `DateRange` is closed `[start, end]`, while `DateTimeRange` and `TimeRange` are half-open `[start, end)`.** "Monday to Friday" includes Friday (`5` days), so `checkIn.for(3, 'days')` automatically subtracts 1 day from `end` (`Sep 1` through `Sep 3`). `DateTimeRange` and `TimeRange` exclude `end` so adjacent slots (`09:00`–`10:00`, `10:00`–`11:00`) do not overlap, and `TimeRange` wraps across midnight when `end < start` (`Time.prototype.until()` stays signed within a single `00:00`–`23:59` day). +**5. `DateRange` is closed `[start, end]`; `DateTimeRange` and `TimeRange` are half-open `[start, end)`.** `checkIn.for(3, 'days')` subtracts 1 day from `end` (`'2026-09-01/2026-09-03'` = 3 days). For database `< end` queries, use `dt.range('month')` (`[Nov 1 00:00, Dec 1 00:00)`) rather than `dt.endOf('month')` (inclusive `.999Z`). `TimeRange` wraps midnight when `end < start`, whereas `Time.until()` stays signed within one `00:00`–`23:59` day. ```js -// ❌ WRONG - adding 3 days manually to build a 3-night/3-day DateRange spans 4 inclusive days -const bad = date('2026-09-01').to(date('2026-09-01').plus(3, 'days')); // 4 days! +// ❌ WRONG - manual +3 days spans 4 inclusive dates; endOf('month') misses sub-ms rows between .999Z and Dec 1 +const fourDays = date('2026-09-01').to(date('2026-09-01').plus(3, 'days')); // 4 days! -// ✅ RIGHT - use .for(3, 'days') for a span, or .to() / .through() with the inclusive end date -const stay = date('2026-09-01').for(3, 'days'); // 2026-09-01 through 2026-09-03 (duration: 3 days) -const slot = time('22:00').to('06:00'); // overnight TimeRange (duration: 8 hours) +// ✅ RIGHT - .for(3, 'days') for inclusive dates; .range('month') for half-open [start, end) query bounds +const stay = date('2026-09-01').for(3, 'days'); // '2026-09-01/2026-09-03' (3 days) +const { start, end } = now('UTC').range('month'); // WHERE created_at >= start AND created_at < end +const nightShift = time('22:00').to('06:00'); // wraps midnight (duration: 8 hours) ``` -**6. `Duration` keeps written fields until `.balance()`, totals via `.total(unit)` / `.as(unit)` (never `.in()`), and refuses `days(1).minus(hours(1))`.** There is no `.normalize()` method. Subtracting clock units from calendar days throws `conflictingSigns` because DST days are 23 or 25 hours, and converting/comparing unanchored months or years against days/hours throws `missingAnchor` unless measured with `a.until(b)`. +**6. `Duration` keeps written fields until `.balance()`, totals via `.total(unit)` / `.as(unit)` (never `.in()`), and refuses `days(1).minus(hours(1))`.** There is no `.normalize()`. Mixing opposing signs across calendar days and clock hours throws `conflictingSigns`, and unanchored `months`/`years` throw `missingAnchor` in `.total()` or `compare()` unless anchored via `a.until(b)`. ```js -// ❌ WRONG - .normalize(), .in('hours'), or mixing calendar day and hour signs on a Duration -minutes(90).normalize(); // TypeError: not a function -hours(36).in('days'); // TypeError: not a function +// ❌ WRONG - .normalize(), .in('days'), or days(1).minus(hours(1)) +minutes(90).normalize(); // TypeError days(1).minus(hours(1)); // RangeError [conflictingSigns] -// ✅ RIGHT - use .balance(), .total(unit) / .as(unit), and chain mixed calendar + clock steps on DateTime +// ✅ RIGHT - .balance(), .total(unit), chain mixed units on DateTime, and anchor calendar spans via .until() minutes(90).balance(); // Duration(PT1H30M) -> hours: 1, minutes: 30 hours(36).total('days'); // 1.5 dt.plus(1, 'day').minus(1, 'hour'); // DST-accurate chaining -date('2026-01-15').until('2026-04-15', 'days'); // 90 (anchored via until) +date('2026-01-15').until('2026-04-15', 'days'); // 90 ``` -**7. `.locale()` affects both formatting and default week start (`startOf('week')`), while `weekOfYear` stays ISO Monday.** On multi-user servers, attach `.locale(req.headers['accept-language'])` to values instead of mutating process-wide `configure({ locale })`, and pass `'monday'` explicitly when keying stored weekly buckets. +**7. `.locale(tag)` natively parses HTTP `Accept-Language` headers and sets default `weekStart`, while `0`-arg `.locale()` is a getter.** Calling `x.locale()` with **zero arguments** returns `string | readonly string[] | undefined`; calling `x.locale(header)` with **one argument** always returns a new instance (even when `header` is `undefined` or `'*'`), sorting `;q=` weights, dropping `*` and `q=0`, and converting `'en_US'` to `'en-US'`. Pass `'monday'` to `startOf('week', 'monday')` when week keys must not shift by locale (`weekOfYear` is always ISO Monday). ```js -// ❌ WRONG - mutating global configure() per HTTP request, or assuming startOf('week') is Monday in en-US -configure({ locale: req.headers['accept-language'] }); -const bucket = rowDate.startOf('week').toString(); // Sunday in en-US, Monday in de-DE, Saturday in ar-EG! +// ❌ WRONG - calling 0-arg .locale() expecting a clone, mutating global configure() per request, or unpinned week buckets +configure({ locale: req.headers['accept-language'] }); // leaks across concurrent requests! -// ✅ RIGHT - attach locale per value, and pass firstDay when week keys must not shift by locale -const localized = datetime(row.at, user.zone).locale(req.headers['accept-language']); -const isoWeekKey = localized.date.startOf('week', 'monday').toString(); +// ✅ RIGHT - 1-arg .locale(header) is safe even if header is undefined or 'fr-CH, fr;q=0.9, *;q=0.5' +const local = datetime(row.at, user.zone).locale(req.headers['accept-language']); +const isoWeekKey = local.date.startOf('week', 'monday').toString(); ``` -**8. Core rejects ambiguous inputs and city/abbreviation zones without plugins, and strips error prose in production.** `'11/06/2026'` and `{ loose: true }` require `@native-dates/plugins/loose`, `'Berlin'` and `'PST'` require `@native-dates/plugins/zones`, `compare(date, datetime)` throws `conflictingKinds`, `CalendarDate` / `Time` throw `unsupportedComparison` on `<` or `-`, and `err.message` explanations fold out of production builds — branch on `err.code` and `err.at`, never `err.message` substrings. +**8. `<`, `>`, and `-` work only on `DateTime` and fixed `Duration`; non-instant nouns throw `unsupportedComparison`, there is no `.isValid()`, and production builds strip `err.message` prose.** Compare `CalendarDate`, `Time`, `YearMonth`, and ranges with `.isBefore()`, `.isAfter()`, `.equals()`, or `compare(a, b)` (`compare(date, datetime)` throws `conflictingKinds`), and catch errors by `err.code` and `err.at`. + +```js +// ❌ WRONG - relational operators on CalendarDate/Time, or matching error message text +if (date('2026-01-01') < date('2026-02-01')) {} // RangeError [unsupportedComparison] + +// ✅ RIGHT - .isBefore() / compare(), and structured err.code checks +const earlier = date('2026-01-01').isBefore('2026-02-01'); // true +try { + datetime(input, untrustedZone); +} catch (err) { + if (err?.code === 'unknownZone') { /* handle bad zone at err.at */ } +} +``` --- ## Choosing the Right Noun +All 9 classes, factories, type guards (`isDateTime`, `isCalendarDate`, ...), `Symbol.for` brand keys (`IS_DATE_TIME`, ...), `monthNames`, `weekdayNames`, `dayOfWeek`, `compare`, `earliest`, `latest`, `kindOf`, and `configure` are named runtime and TypeScript exports from `'native-dates'` (`weekStart` is an instance getter and `configure` option, not a standalone function). + | Class | Factories | Represents | Key rule | |---|---|---|---| -| `DateTime` | `datetime(input, zoneOrOpts?)`, `now(zone?)`, `startOfToday(zone?)`, `endOfToday(zone?)` | Exact instant + IANA zone (`Temporal.ZonedDateTime`) | DST-aware; `toString()` / `toJSON()` emit UTC `...Z`; `<` / `valueOf()` use `epochMilliseconds` | -| `CalendarDate` | `date(input, opts?)`, `date(y, m, d)`, `today(zone?)`, `tomorrow(zone?)`, `yesterday(zone?)` | Calendar day (`Temporal.PlainDate`) | Refuses clock units (`hours`) and `<` / `-`; two-arg `date(2026, 11)` throws `missingDay` | -| `Time` | `time(input, zoneOrOpts?)`, `time(h, m, s?)` | Wall-clock time (`Temporal.PlainTime`) | Wraps modulo 24h on `plus`/`minus`; accepts `'9am'`, `'17:30'`, `'9:05:08.428'` | -| `Duration` | `duration(input, unitOrOpts?)`, `years(n)`..`milliseconds(n)` | Span of units (`Temporal.Duration`) | 8 unit helpers (`years`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`); use `duration(n, 'microseconds' \| 'nanoseconds')` for sub-ms | -| `MonthDay` | `monthDay(input, opts?)`, `monthDay(m, d)`, `dayMonth(input, opts?)`, `dayMonth(d, m)` | Recurring month + day (`Temporal.PlainMonthDay`) | No linear order (`equals()`, `fallsOn()` / `isOn()`); Feb 29 falls on Feb 28 in non-leap years | -| `YearMonth` | `yearMonth(input, opts?)`, `yearMonth(y, m)`, `monthYear(input, opts?)`, `monthYear(m, y)` | Billing/calendar month (`Temporal.PlainYearMonth`) | Only `years`, `quarters`, `months` arithmetic; `monthYear('11/26')` adds `YearMonth.century` (`2000`) | -| `DateRange`, `DateTimeRange`, `TimeRange` | `dateRange(s, e?, opts?)`, `datetimeRange(...)`, `timeRange(...)`, `pt.to(end)`, `pt.for(n, unit)`, `pt.range(unit)` | Interval between two points | `DateRange` is `[start, end]` (also `date.through(end)`); `DateTimeRange` & `TimeRange` are `[start, end)` | - -Every instance is `Object.freeze`d on construction with `.text` as its first enumerable own property. Cross between types with `.date`, `.time`, `.monthDay`, `.yearMonth`, `date.at(time?, zone?)`, `time.on(date, zone?)`, `monthDay.in(year)`, `yearMonth.on(day)` (`yearMonth.start` / `.end`), `range.in(zone)`, or `.as('date' | 'time' | 'datetime' | 'monthDay' | 'yearMonth' | 'duration')`. +| `DateTime` | `datetime(input, zoneOrOpts?)`, `now(zone?)`, `startOfToday(zone?)`, `endOfToday(zone?)` | Exact instant + IANA zone (`Temporal.ZonedDateTime`) | `<` / `valueOf()` return `epochMilliseconds`; 0-arg `datetime()` throws `missingDateTime` | +| `CalendarDate` | `date(input, zoneOrOpts?)`, `date(y, m, d)`, `today(zone?)`, `tomorrow(zone?)`, `yesterday(zone?)` | Calendar day (`Temporal.PlainDate`) | Refuses clock units (`unsupportedUnit`); two-arg `date(2026, 11)` throws `missingDay` | +| `Time` | `time(input, zoneOrOpts?)`, `time(h, m, s?)` | Wall-clock time (`Temporal.PlainTime`) | Wraps modulo 24h on `plus`/`minus`; `time(9)` -> `09:00` | +| `Duration` | `duration(input, unitOrOpts?)`, `years(n)`..`milliseconds(n)` | Span of units (`Temporal.Duration`) | 8 unit helpers (`years`..`milliseconds`); use `duration(n, 'microseconds' \| 'nanoseconds')` for sub-ms | +| `MonthDay` | `monthDay(input, zoneOrOpts?)`, `monthDay(m, d)`, `dayMonth(input, zoneOrOpts?)`, `dayMonth(d, m)` | Recurring month + day (`Temporal.PlainMonthDay`) | No linear order (`equals()`, `fallsOn()`); Feb 29 falls on Feb 28 in non-leap years | +| `YearMonth` | `yearMonth(input, zoneOrOpts?)`, `monthYear(input, zoneOrOpts?)`, `yearMonth(y, m)`, `monthYear(m, y)` | Billing/calendar month (`Temporal.PlainYearMonth`) | Only `years`, `quarters`, `months` math; `monthYear('11/26')` adds `YearMonth.century` (`2000`) | +| `DateRange`, `DateTimeRange`, `TimeRange` | `dateRange(s, e?, zoneOrOpts?)`, `datetimeRange(...)`, `timeRange(...)`, `pt.to(end)`, `pt.for(n, u)`, `pt.range(u)` | Interval between two points | `DateRange` is `[start, end]` (`date.through(end)`); `DateTimeRange` & `TimeRange` are `[start, end)` | + +### Cross-Noun Invariants + +- **Unit spellings:** Every `unit` argument accepts singular, plural, or shorthand (`'y'`/`'yr'`, `'q'`/`'qtr'`, `'M'`/`'mo'` for month vs lowercase `'m'`/`'min'` for minute, `'w'`/`'wk'`, `'d'`, `'h'`/`'hr'`, `'s'`/`'sec'`, `'ms'`, `'us'`/`'µs'`, `'ns'`). +- **Options (`zoneOrOpts`):** Point and range factories accept either a bare `zone` string (`'+05:30'`, `'UTC'`, `'America/New_York'`) or `{ zone, locale, loose, dayFirst }` (`duration` accepts a unit string or `{ locale, loose }`; `loose` and `dayFirst` require `@native-dates/plugins/loose`). +- **Serialization & state:** Every noun implements `toString()` & `toJSON()` (canonical ISO wire string: `'start/end'` on ranges, `.sssZ` on `DateTime` expanding to 6/9 digits when µs/ns are nonzero), `.text` (default human format), `String(x)` / `` `${x}` `` (`toString()`), and `.locale()` / `.locale(tag)` (propagated across `.plus()`, `.date`, `.time`, `.in()`, `.to()`). All 6 non-range nouns implement `toTemporal()` (ranges expose `start.toTemporal()` and `end.toTemporal()`). +- **Input coercion:** Binary and composition methods (`equals`, `isBefore`, `isAfter`, `isSame`, `until`, `since`, `from`, `to`, `on`, `at`, `contains`) accept an instance or any valid factory input for that noun (unzoned inputs on `DateTime` methods resolve in `this.zone`). +- **Overflow & DST disambiguation:** Explicit out-of-range fields (`{ month: 2, day: 30 }`) throw `invalid*`, whereas month/year steps (`Jan 31 + 1 month`) and `set` on other fields clamp existing days to month-end (`Feb 28`). Zoned wall-clock construction and transforms use `Temporal`'s `'compatible'` rule: spring-forward gaps (`02:30` -> `03:30`) push forward by the gap length, and fall-back folds (`01:30`) pick the earlier offset. +- **Type conversions:** Cross between nouns via `.date`, `.time`, `.monthDay`, `.yearMonth`, `date.at(time = '00:00', zone?)` (`d.at(undefined, zone)` for midnight in `zone`), `time.on(date, zone?)`, `monthDay.in(year)`, `yearMonth.on(day)` (`yearMonth.start` / `.end`), `range.in(zone)`, or `.as('date' | 'time' | 'datetime' | 'monthDay' | 'yearMonth' | 'duration')`. --- ## DateTime ```js -import { datetime, endOfToday, now, startOfToday } from 'native-dates'; +import { DateTime, datetime, endOfToday, now, startOfToday } from 'native-dates'; const dt = datetime('2026-11-16T09:30', 'America/Los_Angeles'); -const shifted = dt.plus(2, 'days').at('14:00').in('Europe/Berlin'); +const slot = dt.plus(2, 'days').at('14:17').round(15, 'minutes').in('Europe/Berlin'); ``` -- **Accepted inputs:** ISO strings (`'2026-11-16'`, `'2026-11-16T09:30'`, `'2026-11-16T17:30Z'`, `'2026-11-16T09:30-08:00[America/Los_Angeles]'`), year-first `'2026/11/16 9:30'`, epoch milliseconds (`Number`, truncated if fractional), `Date`, `{ year, month, day, hour, ... }`, `CalendarDate`, `DateTime`, or `Temporal.{ZonedDateTime,Instant,PlainDateTime,PlainDate}`. Passing `null`/`undefined` throws `missingDateTime` (use `now()`). -- **Own properties:** `text`, `year`, `month` (`1`–`12`), `day` (`1`–`31`), `dayOfWeek` (`1`–`7`), `hour` (`0`–`23`), `minute`, `second`, `millisecond`, `zone` (IANA ID), `offset` (`'-08:00'`), `epochMilliseconds`. -- **Getters & predicates:** `microsecond`, `nanosecond`, `epochSeconds`, `epochNanoseconds` (`BigInt`), `weekStart`, `quarter` (`1`–`4`), `dayOfYear`, `weekOfYear` (ISO), `daysInMonth`, `daysInYear`, `hoursInDay` (`23`/`24`/`25` across DST), `date`, `time`, `monthDay`, `yearMonth`, `isLeapYear()`, `isWeekday()`, `isWeekend()`, `isPast()`, `isFuture()`, `isToday()`, `isTomorrow()`, `isYesterday()`. -- **Transforms:** `plus(n, unit)` / `add`, `minus(n, unit)` / `subtract` (also accepts `'1h 30m'`, `{ days: 2 }`, or `Duration`), `set(field, value)` / `set({ year, month })` (clamps existing day on month/year change, rejects out-of-range explicit fields), `at(time)` (wall clock in `this.zone`), `in(zone)` (same instant in new zone), `startOf(unit, firstDay?)`, `endOf(unit, firstDay?)` (inclusive last ms/ns — prefer `range(unit)` for `< end` queries), `startOfNext(unitOrWeekday, firstDay?)`, `startOfPrevious(unitOrWeekday, firstDay?)`, `next(weekdayOrMonthDay)`, `previous(weekdayOrMonthDay)`, `round(inc, unit?)`, `floor(inc, unit?)`, `ceil(inc, unit?)`, `locale(tag?)` / `lang`. -- **Comparisons & spans:** `equals(other)`, `isBefore(other)`, `isAfter(other)`, `isSame(other, unit?, firstDay?)`, `until(other, unit?)`, `since(other, unit?)`, `from(other?, locale?)` / `formatRelative`, `fromNow(locale?)`, `to(endOrDuration, unit?)` / `for`, `range(unit, firstDay?)`, `toString()`, `toJSON()`, `toJSDate()`, `toTemporal()`. +- **Inputs:** ISO strings (`'2026-11-16'`, `'2026-11-16T09:30'`, `'2026-11-16T17:30Z'`, `'2026-11-16T09:30-08:00[America/Los_Angeles]'`), `'2026/11/16 9:30'`, epoch ms (`Number`, truncated if fractional), `Date`, `{ year, month, day, hour, ... }`, `CalendarDate`, `DateTime`, or `Temporal.{ZonedDateTime,Instant,PlainDateTime,PlainDate}`. `null`/`undefined` throws `missingDateTime` (use `now(zone?)`). +- **Fields & getters:** `text`, `year`, `month` (`1`–`12`), `day` (`1`–`31`), `dayOfWeek` (`1`–`7`), `hour` (`0`–`23`), `minute`, `second`, `millisecond`, `microsecond`, `nanosecond`, `zone` (IANA ID), `offset` (`'-08:00'`), `epochSeconds` (floored `Number`), `epochMilliseconds` (`Number`), `epochNanoseconds` (`BigInt`), `weekStart`, `quarter` (`1`–`4`), `dayOfYear`, `weekOfYear` (ISO), `daysInMonth`, `daysInYear`, `hoursInDay` (`23`/`24`/`25` across DST), `date`, `time`, `monthDay`, `yearMonth`. +- **Predicates:** `isLeapYear()`, `isWeekday()`, `isWeekend()`, `isPast()`, `isFuture()`, `isToday()`, `isTomorrow()`, `isYesterday()`. +- **Arithmetic & boundaries:** + - `plus(n, unit)` / `add`, `minus(n, unit)` / `subtract` (also `'1h 30m'`, `{ days: 2 }`, or `Duration`), `set(field, value)` / `set({ year, month })`, `at(time)` (wall clock in `this.zone`), `in(zone)` (same instant in new zone). + - `startOf(unit, firstDay?)`, `endOf(unit, firstDay?)` (steps back `1` ms to `.999` for `'year'`..`'millisecond'`, or `1` ns for `'microsecond'`/`'nanosecond'`), `startOfNext(unitOrWeekday, firstDay?)`, `startOfPrevious(unitOrWeekday, firstDay?)`, `next(weekdayOrMonthDay)`, `previous(weekdayOrMonthDay)`. + - `round(unit)` or `round(increment, unit)` (same for `floor` and `ceil`, e.g. `dt.round('hour')` or `dt.round(15, 'minutes')` — pass two arguments for increments > 1, never `'15m'`). +- **Comparisons & measurement:** + - `equals(other)`, `isBefore(other)`, `isAfter(other)`, `isSame(other, unit?, firstDay?)`. + - `until(other, unit?)` / `since(other, unit?)`: without `unit`, returns an anchored `Duration` (`largestUnit: 'day'`); with `unit`, returns an **exact floating-point `Number`** (e.g. `1.5`, not truncated). + - `from(other?, locale?)` / `formatRelative` (`this` relative to `other`: `"in 2 days"` when `this > other`, `"2 days ago"` when `this < other`), `fromNow(locale?)`, `to(endOrDuration, unit?)` / `for`, `range(unit, firstDay?)`, `toJSDate()`. --- ## CalendarDate ```js -import { date, today, tomorrow, yesterday } from 'native-dates'; +import { CalendarDate, date, today, tomorrow, yesterday } from 'native-dates'; const due = today('America/New_York').plus(2, 'weeks').next('friday'); ``` -- **Accepted inputs:** `'2026-11-16'`, `'2026/11/16'`, `'2026.11.16'`, `'2026-1-5'`, `(year, month, day)` integers, `{ year, month, day }`, `DateTime`, `Date`, instant strings (resolved in `zone`), or `Temporal.PlainDate`. Bare single numbers throw `invalidDate` (`datetime(ms).date` or `date(y, m, d)`). -- **Clock guard:** Refuses clock units (`hours`, `minutes`, ...) with `unsupportedUnit`; attach a clock first via `.at('00:00', zone)`. -- **Day-specific methods:** Shares `DateTime`'s calendar properties, `plus`/`minus`, `set`, `startOf`/`endOf`, `startOfNext`/`startOfPrevious`, `next`/`previous`, `isSame`, `until`/`since` (returns `Duration` in days or `Number` when `unit` is passed), `from`/`fromNow`, plus `.through(end)` (alias for `.to(end)`), `.at(time?, zone?)` -> `DateTime`, and `.points(step, unit?, zone?)` / `.split(step, unit?, zone?)` / `.splitBy` across that date's zoned day. +- **Inputs:** `'2026-11-16'`, `'2026/11/16'`, `'2026.11.16'`, `'2026-1-5'`, `(year, month, day)` integers, `{ year, month, day }`, `DateTime`, `Date`, instant strings (resolved in `zone`), or `Temporal.PlainDate`. Single bare numbers throw `invalidDate` (use `datetime(ms).date` or `date(y, m, d)`). +- **Clock guard & methods:** Refuses clock units (`hours`, `minutes`, ...) with `unsupportedUnit`. Shares `DateTime`'s calendar getters, `plus`/`minus`, `set`, `startOf`/`endOf`, `startOfNext`/`startOfPrevious`, `next`/`previous`, `isSame`, `until`/`since` (`Duration` in days, or float `Number` when `unit` is passed), `from(other?, locale?)` / `fromNow(locale?)` (on servers, pass explicit `d.from(today(user.zone), locale)` since `fromNow` reads default `today()`), `.through(end)` (alias for `.to(end)`), `.at(time = '00:00', zone?)` -> `DateTime`, and `.points(step, unit?, zone?)` / `.split(step, unit?, zone?)` / `.splitBy` across that date's zoned day. --- ## Time ```js -import { time } from 'native-dates'; +import { Time, time } from 'native-dates'; -const shiftStart = time('9:30am').plus(45, 'minutes'); // Time(10:15:00) -const scheduled = shiftStart.on('2026-11-16', 'America/Chicago'); // DateTime +const scheduled = time('9:30am').plus(45, 'minutes').round(15, 'minutes').on('2026-11-16', 'America/Chicago'); ``` -- **Accepted inputs:** `'09:30'`, `'9am'`, `'5:30:15 pm'`, `time(9, 30, 0)`, `{ hour, minute }`, `DateTime`, `Date`, instant strings (resolved in `zone`), or `Temporal.PlainTime`. Single bare hour integer is accepted in `time(9)` -> `09:00` (`set` / arithmetic wrap around midnight). -- **Methods:** `plus`/`minus`, `set`, `startOf`/`endOf`, `startOfNext(unit)` / `startOfPrevious(unit)` (clock units only), `round`/`floor`/`ceil`, `equals`/`isBefore`/`isAfter`/`isSame`, `until(other, unit?)` / `since(other, unit?)` (within a single `00:00`–`23:59` day), `to(end, unit?)` / `for`, `on(day, zone?)` -> `DateTime`, `format(spec?, locale?)`, `toString()`. +- **Inputs:** `'09:30'`, `'9am'`, `'5:30:15 pm'`, `time(9, 30, 0)`, `time(9)` (`09:00`), `{ hour, minute }`, `DateTime`, `Date`, instant strings (resolved in `zone`), or `Temporal.PlainTime`. +- **Methods:** `plus`/`minus` and `set` (wrap modulo 24h), `startOf`/`endOf`, `startOfNext(unit)` / `startOfPrevious(unit)` (clock units only), `round(unit)` / `round(inc, unit)` (and `floor`/`ceil`), `equals`/`isBefore`/`isAfter`/`isSame`, `until(other, unit?)` / `since(other, unit?)` (within one `00:00`–`23:59` day, `largestUnit: 'hour'`), `to(end, unit?)` / `for`, `on(day, zone?)` -> `DateTime`. --- ## Duration ```js -import { days, duration, hours, minutes } from 'native-dates'; +import { Duration, days, duration, hours, minutes } from 'native-dates'; const span = duration('2h 45m').plus(30, 'minutes').balance(); // 3 hours, 15 minutes span.total('hours'); // 3.25 ``` -- **Accepted inputs:** ISO 8601 (`'PT1H30M'`, `'-P2D'`), natural phrases (`'1h 30m'`, `'2 weeks, 3 days'`, `'90 mins'`, `'1.5 hours'` -> spills fractional units down to nanoseconds), `(count, unit)`, `{ hours: 1, minutes: 30 }`, or `Temporal.Duration`. -- **Properties & methods:** `text`, `years`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`, `microseconds`, `nanoseconds`, `sign` (`-1 | 0 | 1`), `anchor`, `isZero()`, `isNegative()`, `toFields()`, `plus`/`add`, `minus`/`subtract` (borrows signs automatically across fixed ratios `1y = 12mo` and `1w = 7d`), `times(factor)`, `negated()`, `abs()`, `balance(largestUnit?)`, `round(smallestUnit)`, `total(unit)` / `as(unit)`, `toMilliseconds()` / `valueOf()`, `compare(other)`, `equals(other)`, `format('long' | 'short' | 'narrow' | 'digital', locale?)`. +- **Inputs:** ISO 8601 (`'PT1H30M'`, `'-P2D'`), natural phrases (`'1h 30m'`, `'2 weeks, 3 days'`, `'90 mins'`, `'1.5 hours'` -> spills fractional units to ns), `(count, unit)`, `{ hours: 1, minutes: 30 }`, or `Temporal.Duration`. +- **Fields:** `text` (`'long'` preset), `years`, `months`, `weeks`, `days`, `hours`, `minutes`, `seconds`, `milliseconds`, `microseconds`, `nanoseconds`, `sign` (`-1 | 0 | 1`), `anchor`, `isZero()`, `isNegative()`, `toFields()`. +- **Transforms & totals:** `plus`/`add`, `minus`/`subtract` (borrows signs across fixed ratios `1y = 12mo` and `1w = 7d`), `times(factor)`, `negated()`, `abs()`, `balance(largestUnit?)`, `round(smallestUnit)` (single unit string), `total(unit)` / `as(unit)` (float `Number`), `toMilliseconds()` / `valueOf()`, `compare(other)`, `equals(other)`, `format(style = 'long', locale?)` (`style` in `'long' | 'short' | 'narrow' | 'digital'`; other specs throw `unknownFormat`). --- ## MonthDay and YearMonth ```js -import { dayMonth, monthDay, monthYear, yearMonth } from 'native-dates'; +import { MonthDay, YearMonth, dayMonth, monthDay, monthYear, yearMonth } from 'native-dates'; -const birthday = monthDay('10-17'); // or monthDay(10, 17), dayMonth('17/10') -birthday.in(2027); // CalendarDate(2027-10-17) -birthday.next('2026-11-16'); // CalendarDate(2027-10-17) — strictly after reference date +const leapBday = monthDay('02-29'); +leapBday.fallsOn('2026-02-28'); // true (equals('2026-02-28') is false) +leapBday.next('2026-02-28'); // CalendarDate(2027-02-28) — strictly after reference date -const billing = monthYear('11/26'); // YearMonth(2026-11) -billing.start; // CalendarDate(2026-11-01) -billing.end; // CalendarDate(2026-11-30) +const cardExpiry = monthYear('11/26'); // YearMonth(2026-11) +cardExpiry.format('MM/YY'); // '11/26' ('short' preset prints '11/2026') ``` -- **`MonthDay`:** `month` (`1`–`12`), `day` (`1`–`31`), `in(year)` -> `CalendarDate` (Feb 29 constrains to Feb 28 in non-leap years), `next(fromDay?)` / `after(day)`, `previous(fromDay?)` / `last(fromDay?)` / `before(day)`, `fallsOn(day)` / `isOn(day)` (Feb 29 falls on Feb 28 in non-leap years, whereas `equals()` checks exact `month` & `day` and rejects slash/dot strings as order-ambiguous), `isToday(zone?)`, `isTomorrow(zone?)`, `isYesterday(zone?)`. Note: two-digit `'MM-DD'` with a hyphen always parses month-first even in `dayMonth('10-17')`. -- **`YearMonth`:** `year`, `month`, `quarter`, `daysInMonth`, `daysInYear`, `isLeapYear()`, `start`, `end`, `on(day)` -> `CalendarDate`, `plus`/`minus` (`years`, `quarters`, `months` only), `set`, `contains(day)` / `includes(day)`, `equals`/`isBefore`/`isAfter`/`compare`, `isPast(zone?)`/`isFuture(zone?)`, `until(other, unit?)`/`since(other, unit?)`. `YearMonth` `'short'` preset prints 4-digit years (`'11/2026'`); use `.format('MM/YY')` for 2-digit card expiries. +- **`MonthDay`:** `month` (`1`–`12`), `day` (`1`–`31`), `in(year)` -> `CalendarDate` (Feb 29 -> Feb 28 in non-leap years), `next(fromDay?)` / `after(day)`, `previous(fromDay?)` / `last(fromDay?)` / `before(day)`, `fallsOn(day)` / `isOn(day)` vs exact `equals()` (which rejects slash/dot strings as order-ambiguous), `isToday(zone?)`, `isTomorrow(zone?)`, `isYesterday(zone?)`. Two-digit `'MM-DD'` with a hyphen always parses month-first even in `dayMonth('10-17')`. +- **`YearMonth`:** `year`, `month`, `quarter`, `daysInMonth`, `daysInYear`, `isLeapYear()`, `start`, `end`, `on(day)` -> `CalendarDate`, `plus`/`minus` (`years`, `quarters`, `months` only), `set`, `contains(day)` / `includes(day)`, `equals`/`isBefore`/`isAfter`/`compare`, `isPast(zone?)`/`isFuture(zone?)`, `until(other, unit?)`/`since(other, unit?)` (`largestUnit: 'year'`). --- ## DateRange, DateTimeRange, and TimeRange ```js -import { date, dateRange, datetimeRange, timeRange } from 'native-dates'; +import { DateRange, DateTimeRange, TimeRange, date, dateRange, datetimeRange, timeRange } from 'native-dates'; -const sprint = date('2026-11-02').for(2, 'weeks'); // 2026-11-02 through 2026-11-15 -const daysInSprint = sprint.points('day'); // 14 CalendarDate instances -const weeks = sprint.split(1, 'week'); // [DateRange(Nov 2..Nov 8), DateRange(Nov 9..Nov 15)] +const sprint = date('2026-11-02').for(2, 'weeks'); // '2026-11-02/2026-11-15' +const weeks = sprint.split(1, 'week'); // [DateRange('2026-11-02/2026-11-08'), DateRange('2026-11-09/2026-11-15')] ``` -- **Construction:** `point.to(end)`, `point.for(amount, unit)` / `point.for(duration)`, `date.through(end)`, `point.range(unit, firstDay?)`, or `dateRange` / `datetimeRange` / `timeRange` with `(start, end, options?)` or a single interval string (`'2026-09-01/2026-09-07'`, `'2026-09-01 to 2026-09-07'`, `'09:00-17:00'`). -- **Properties & methods:** `text`, `kind` (`'date' | 'datetime' | 'time'`), `start`, `end`, `duration` (`Duration`), `isEmpty()` (`false` on all `DateRange`s; `start.equals(end)` on `DateTimeRange`/`TimeRange`), `contains(pointOrRange)` / `includes`, `overlaps(otherRange)`, `intersection(otherRange)` (returns range or `null`; throws `unsupportedIntersection` if two overnight `TimeRange`s overlap in two disjoint windows), `equals(other)`, `points(step, unit?)` (`step` > 0, e.g. `'day'`, `'30m'`, `(15, 'minutes')`), `split(step, unit?)` / `splitBy`, `in(zone)` (converts inclusive `DateRange` `[start, end]` to half-open `DateTimeRange` `[start 00:00, (end + 1d) 00:00)` in `zone`; throws `unsupportedZone` on `TimeRange`), `format(spec?, locale?)`, `toString()` (`'start/end'`). +- **Construction:** `point.to(end)`, `point.for(amount, unit)` / `point.for(duration)`, `date.through(end)`, `point.range(unit, firstDay?)`, or `dateRange` / `datetimeRange` / `timeRange` with `(start, end, zoneOrOpts?)` or one interval string (`'2026-09-01/2026-09-07'`, `'2026-09-01 to 2026-09-07'`, `'09:00-17:00'`). +- **Properties, formatting & set ops:** `text`, `kind` (`'date' | 'datetime' | 'time'`), `start`, `end`, `duration` (`Duration`), `isEmpty()` (`false` on `DateRange`; `start.equals(end)` on `DateTimeRange`/`TimeRange`), `contains(pointOrRange)` / `includes`, `overlaps(otherRange)`, `intersection(otherRange)` (range or `null`; throws `unsupportedIntersection` if two overnight `TimeRange`s overlap twice), `equals(other)`, `format(spec?, locale?)` (`Intl` range formatting on presets/options; `'start – end'` on token patterns), `toString()` / `toJSON()` (`'start/end'`). +- **Iteration & zone lift:** `points(step, unit?)` returns an `Array` of points (`step` > 0: `'day'`, `'30m'`, `(15, 'minutes')`), `split(step, unit?)` / `splitBy` returns an `Array` of sub-ranges (clipping any uneven remainder at `end`), and `in(zone)` lifts inclusive `DateRange` `[start, end]` to half-open `DateTimeRange` `[start 00:00, (end + 1d) 00:00)` in `zone` (`unsupportedZone` on `TimeRange`). --- ## format, monthNames, and weekdayNames -`value.format(spec?, locale?)` accepts four kinds of `spec`: +Point, partial, and range `.format(spec?, locale?)` accepts four `spec` forms (`Duration.format` accepts `'long' | 'short' | 'narrow' | 'digital'` only): -1. **Built-in presets:** `'short'`, `'medium'` (default, except `'short'` on `Time`), `'long'`, `'full'`, `'date'`, `'time'`, `'month'`, `'text'`, plus Moment/Day.js localized presets `'LT'`, `'LTS'`, `'L'`, `'l'`, `'LL'`, `'ll'`, `'LLL'`, `'lll'`, `'LLLL'`, `'llll'`. (`Duration.prototype.format` accepts `'long'` default, `'short'`, `'narrow'`, `'digital'`.) -2. **Custom named formats** registered via `configure({ formats: { invoice: 'YYYY-MM-DD' } })` (checked before built-in presets; `value.text` and bare `value.format()` stay on built-in defaults). -3. **`Intl.DateTimeFormat` options objects** (`{ month: 'short', day: 'numeric', weekday: 'short' }`) — fields absent on a noun (such as `hour` on `CalendarDate` or `year` on `Time`) are stripped automatically. -4. **Token patterns** (literal text escaped in `[brackets]`, `'T'` allowed bare; digits and years stay Western ASCII/Gregorian): +1. **Built-in presets:** `'short'`, `'medium'` (default, except `'short'` on `Time`), `'long'`, `'full'`, `'date'`, `'time'`, `'month'`, `'text'`, plus Moment/Day.js localized `'LT'`, `'LTS'`, `'L'`, `'l'`, `'LL'`, `'ll'`, `'LLL'`, `'lll'`, `'LLLL'`, `'llll'`. +2. **Custom named formats** via `configure({ formats: { invoice: 'YYYY-MM-DD' } })` (checked before built-in presets; `.text` and bare `.format()` keep built-in defaults). +3. **`Intl.DateTimeFormat` options** (`{ month: 'short', day: 'numeric', weekday: 'short' }`), automatically stripping fields absent on the noun. +4. **Token patterns** (escape literal words in `[brackets]`, bare `'T'` allowed; digits and years stay Western ASCII/Gregorian): | Tokens | Output | |---|---| | `YYYY`, `YY`, `Q` | 4-digit year, 2-digit year, quarter (`1`–`4`) | -| `M`, `MM`, `MMM`, `MMMM` | Month `1`–`12`, padded `01`–`12`, localized Gregorian short/long name (auto-inflected after day tokens) | +| `M`, `MM`, `MMM`, `MMMM` | Month `1`–`12`, padded `01`–`12`, localized short/long name (inflected after day tokens) | | `D`, `DD`, `Do`, `DDD`, `DDDD` | Day of month, padded, ordinal (`'16th'`, `'6.'`, `'6日'`), day of year, 3-digit day of year | | `E`, `d`, `dd`, `ddd`, `dddd` | ISO weekday `1`–`7` (`7` = Sun), Moment weekday `0`–`6` (`0` = Sun), narrow (`'Mo'`), short, long | | `W`, `WW` | ISO week of year (`1`–`53`), padded | @@ -242,70 +266,70 @@ const weeks = sprint.split(1, 'week'); // [DateRange(Nov 2..Nov 8), DateRange(No | `X`, `x`, `[text]` | Epoch seconds, epoch milliseconds, escaped literal text | - `monthNames(style = 'long' | 'short', locale?)`: 12 Gregorian month names (`0` = Jan..`11` = Dec). -- `weekdayNames(style = 'short' | 'long' | 'narrow', firstDay?, locale?)`: 7 weekday names rotated to start on `firstDay` / `weekStart` / locale's first day (note: `locale` is the **3rd** argument!). +- `weekdayNames(style = 'short' | 'long' | 'narrow', firstDay?, locale?)`: 7 weekday names starting on `firstDay` / `weekStart` / locale's first day (`locale` is the **3rd** argument). --- ## configure, compare, and Guards ```js -import { compare, configure, dayOfWeek, earliest, kindOf, latest } from 'native-dates'; +import { compare, configure, dayOfWeek, earliest, isDateTime, kindOf, latest } from 'native-dates'; configure({ - zone: 'America/New_York', // default IANA zone (null resets to system) - locale: 'en-US', // default locale (null resets to system) - weekStart: 'monday', // 1..7 or day name (null resets to locale-driven) + zone: 'America/New_York', // null resets to system zone + locale: 'en-US', // null resets to system locale + weekStart: 'monday', // 1..7 or weekday name (null resets to locale-driven) formats: { sql: 'YYYY-MM-DD HH:mm:ss' }, // null clears weekdayNames: { lv: { narrow: { fri: 'Pk', sun: 'Sv' } } }, // width in [narrow, short, long] ordinals: { fr: (day) => (day === 1 ? '1er' : day) }, }); ``` -- **`compare(a, b)` / `earliest(...items)` / `latest(...items)`:** Sorts `DateTime`, `CalendarDate`, `Time`, `YearMonth`, `Duration` (in `compare`), or same-kind ranges (accepts a single array or rest args in `earliest`/`latest`). A bare `Number` in first position (`compare(Date.now(), dt)`) is epoch milliseconds; a trailing `Number` after a `Time` (`compare(time('09:00'), 9)`) coerces to an hour. Mixing kinds (`compare(date, datetime)`) throws `conflictingKinds`. -- **`dayOfWeek(input)`:** Converts `'monday'`..`'sunday'`, 3-letter prefixes (`'mon'`), `1`–`7`, or `0` (mapped to `7`) into ISO `1`–`7`. -- **Cross-realm guards & brands:** `kindOf(x)` returns `'datetime' | 'date' | 'time' | 'duration' | 'monthDay' | 'yearMonth' | 'dateRange' | 'datetimeRange' | 'timeRange' | undefined`. Guards `isDateTime`, `isCalendarDate`, `isTime`, `isDuration`, `isMonthDay`, `isYearMonth`, `isDateRange`, `isDateTimeRange`, `isTimeRange` and `instanceof` use `Symbol.for` brands (`IS_DATE_TIME`, etc.) so they work across realms and duplicate bundles. +- **`compare(a, b)` / `earliest(...items)` / `latest(...items)`:** Sorts `DateTime`, `CalendarDate`, `Time`, `YearMonth`, `Duration` (in `compare`), or same-kind ranges (rest args or single array in `earliest`/`latest`; there is no `min`/`max`). A bare `Number` first (`compare(Date.now(), dt)`) is epoch ms; a bare `Number` after a `Time` (`compare(time('09:00'), 9)`) is an hour. +- **`dayOfWeek(input)`:** Maps `'monday'`..`'sunday'`, `'mon'`..`'sun'`, `1`–`7`, or `0` (`7`) to ISO `1`–`7`. +- **Cross-realm guards:** `kindOf(x)` returns `'datetime' | 'date' | 'time' | 'duration' | 'monthDay' | 'yearMonth' | 'dateRange' | 'datetimeRange' | 'timeRange' | undefined`. `isDateTime`, `isCalendarDate`, `isTime`, `isDuration`, `isMonthDay`, `isYearMonth`, `isDateRange`, `isDateTimeRange`, `isTimeRange` and `instanceof` use `Symbol.for` brands across realms and duplicate bundles. --- ## Errors -Every refusal throws `RangeError` or `TypeError` formatted as `dates refused [code] ` with `.code` and `.at` properties: +Nullish factory inputs (`missingDateTime`, `missingDate`, `missingTime`, `missingMonthDay`, `missingYearMonth`) and wrong JS argument types throw `TypeError`; all malformed strings, out-of-range fields, `cannot*`, `unknown*`, `unsupported*`, and `conflicting*` refusals throw `RangeError` (`dates refused [code] ` with `.code` and `.at`): | Error code | Thrown when | |---|---| -| `missingDateTime`, `missingDate`, `missingTime`, `missingMonthDay`, `missingYearMonth`, `missingDay`, `missingPoints`, `missingAnchor`, `missingPlugin` | Required argument, day (`date(2026, 11)`), anchor (`months(2).total('days')`), or plugin (`{ loose: true }` without `@native-dates/plugins/loose`) is missing | -| `invalidDateTime`, `invalidDate`, `invalidTime`, `invalidDuration`, `invalidMonthDay`, `invalidYearMonth`, `invalidRange`, `invalidStep`, `invalidNumber`, `invalidFraction`, `invalidYear`, `invalidDay`, `invalidPoint` | Unparseable syntax, out-of-range calendar field (`Feb 30`), non-positive `points()` step, or `end < start` on `DateRange`/`DateTimeRange` | -| `unknownZone`, `unknownLocale`, `unknownUnit`, `unknownDayOfWeek`, `unknownFormat`, `unknownKind`, `unknownSetting`, `unknownWidth` | Unrecognized IANA zone, BCP 47 tag, unit, weekday, token/preset, `as(kind)` target, or `configure()` key | -| `unsupportedUnit`, `unsupportedToken`, `unsupportedComparison`, `unsupportedZone`, `unsupportedCalendar`, `unsupportedIntersection` | Valid unit/token applied to a noun that lacks it (`hours` on `CalendarDate`), `<` / `-` coercion on non-`DateTime` points, or double-window overnight `TimeRange` intersection | +| `missingDateTime`, `missingDate`, `missingTime`, `missingMonthDay`, `missingYearMonth`, `missingDay`, `missingPoints`, `missingAnchor`, `missingPlugin` | Nullish input, two-arg `date(2026, 11)`, unanchored `months(2).total('days')`, or `{ loose: true }` / `dayFirst` / `zoneAliases` without its plugin | +| `invalidDateTime`, `invalidDate`, `invalidTime`, `invalidDuration`, `invalidMonthDay`, `invalidYearMonth`, `invalidRange`, `invalidStep`, `invalidNumber`, `invalidFraction`, `invalidYear`, `invalidDay`, `invalidPoint` | Malformed string, nonexistent field (`Feb 30`), non-positive `points()` step, or `end < start` on `DateRange`/`DateTimeRange` | +| `cannotAdd`, `cannotSubtract`, `cannotSet`, `cannotRound` | Arithmetic overflow, non-integer `set()` value, or invalid `roundingIncrement` (such as `dt.round(7, 'minutes')`, since `60 % 7 !== 0`) | +| `unknownZone`, `unknownLocale`, `unknownUnit`, `unknownDayOfWeek`, `unknownFormat`, `unknownKind`, `unknownSetting`, `unknownWidth` | Unrecognized IANA zone, malformed BCP 47 tag, unit, weekday, token/preset, `as(kind)` target, or `configure()` key | +| `unsupportedUnit`, `unsupportedToken`, `unsupportedComparison`, `unsupportedZone`, `unsupportedCalendar`, `unsupportedIntersection` | Unit/token absent on noun (`hours` on `CalendarDate`, `'yyyy'`), `<`/`-` on non-`DateTime`, `timeRange.in(zone)`, or double overnight intersection | | `conflictingSigns`, `conflictingKinds`, `conflictingRanges` | `days(1).minus(hours(1))`, `compare(date, datetime)`, or passing a `TimeRange` to `dateRange()` | --- ## Quick Reference -```js -import { date, datetime, days, hours, monthDay, now, time, today, yearMonth } from 'native-dates'; - -// Zoned moment + DST-safe math + UTC wire output -const kickoff = datetime('2026-03-08T04:30:00Z', 'America/New_York').plus(1, 'day').at('09:30'); -kickoff.toJSON(); // '2026-03-09T13:30:00.000Z' -kickoff.epochSeconds; // 1773063000 - -// Calendar day + inclusive range + unit boundary -const billingWindow = today('Europe/Berlin').startOfNext('month').for(1, 'month'); // inclusive DateRange -const eachDay = billingWindow.points('day'); +| Coming from `Date` / Moment / Day.js / Luxon / Temporal | `native-dates` idiom | +|---|---| +| `new Date()` / `dayjs()` / `moment()` / `DateTime.now()` | `now(zone?)` or `today(zone?)` (`0`-arg `datetime()` throws `missingDateTime`) | +| `d.toISOString()` / `dt.toISO()` | `dt.toJSON()` or `dt.toString()` (no `.toISOString()` in core) | +| `d.isValid` / `dayjs(x).isValid()` | Construction throws immediately (or returns `null` with `{ loose: true }` plugin) | +| `moment.tz(x, z)` / `dt.setZone(z)` / `zdt.withTimeZone(z)` | `datetime(x, z)` on parse, `.in(z)` to convert an existing `DateTime` | +| `zdt.with({ hour: 9, minute: 0 })` | `dt.at('09:00')` or `dt.set({ hour: 9, minute: 0 })` | +| `moment.min(a, b)` / `DateTime.max(a, b)` | `earliest(a, b)` / `latest(a, b)` | +| `x.isBetween(a, b)` | `a.to(b).contains(x)` (`[a, b]` on `CalendarDate`, `[a, b)` on `DateTime`/`Time`) | +| `b.diff(a, 'hours', true)` | `a.until(b, 'hours')` (always exact float; `Math.trunc` if integer needed) | -// Server-safe per-request locale + pinned ISO Monday week key -const userTime = datetime(row.createdAt, user.zone).locale(req.headers['accept-language']); -const label = userTime.fromNow(); // localized relative phrase -const weekBucket = userTime.date.startOf('week', 'monday').toString(); +```js +import { compare, date, datetime, earliest, isDateTime, today } from 'native-dates'; -// Anchored calendar span vs fixed duration balancing -const ageDays = date('2026-01-15').until('2026-04-15', 'days'); // 90 -const totalHrs = hours(1).plus(days(2)).total('hours'); // 49 +const start = date('2026-11-01'); +const deadline = earliest(start.plus(2, 'w'), today('Europe/Berlin').next('friday')); +const midnightInBerlin = deadline.at(undefined, 'Europe/Berlin'); // 2026-11-xxT00:00 in Europe/Berlin +const inWindow = start.through(deadline).contains('2026-11-05') && isDateTime(midnightInBerlin); +const ordered = [deadline, start].sort(compare); ``` -**Golden rule: Pick the noun that matches the data (`datetime` for an exact moment in a zone, `date` for a calendar day, `time` for a wall clock, `yearMonth` or `monthDay` for partial dates), chain immutable methods rather than mutating, and pass explicit IANA zones or per-value `.locale()` in server code.** +**Golden rule: Match the class to the data (`datetime` for zoned instants, `date` for calendar days, `time` for clocks), chain immutable methods, and pass explicit IANA zones and per-value `.locale()` in server code.** --- @@ -313,4 +337,4 @@ const totalHrs = hours(1).plus(days(2)).total('hours'); // 49 | Skill | Use when... | |---|---| -| `native-dates-plugins` | Resolving city names (`'Berlin'`) or zone abbreviations (`'PST'`), parsing untrusted/slash strings with `{ loose: true, dayFirst }`, shimming legacy `Date` getters, loading `@native-dates/polyfill` for Safari, or writing a custom plugin | +| `native-dates-plugins` | Resolving IANA city names (`'Berlin'`) or zone abbreviations (`'PST'`), parsing slash/informal strings with `{ loose: true, dayFirst }`, shimming `Date` getters, polyfilling `Temporal` on Safari or Node `<26`, or writing a custom plugin | diff --git a/package.json b/package.json index b62d7ec..a329d5d 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "src", "types", "ai/skills", + "!ai/README.md", "README.md", "LICENSE" ], diff --git a/tools/gates/ai.js b/tools/gates/ai.js index e828cc6..d49ac67 100644 --- a/tools/gates/ai.js +++ b/tools/gates/ai.js @@ -1,8 +1,9 @@ -// validates markdown links, #anchors, GFM tables, unclosed fences, ai/ paths, and AGENTS.md symlinks +// validates YAML frontmatter, markdown links, #anchors, GFM tables, unclosed fences, ai/ paths, and AGENTS.md symlinks import { existsSync, lstatSync, readdirSync, readFileSync, readlinkSync, statSync } from 'node:fs'; import { dirname, relative, resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { parse as parseYaml } from 'yaml'; import { checkDecisions } from './decisions-index.js'; @@ -99,12 +100,24 @@ function countCells(line) { export function checkMarkdownStructure(source) { const lines = source.split('\n'); const findings = []; + let startIndex = 0; + const frontMatch = /^---\n([\s\S]*?)\n---(?:\n|$)/.exec(source); + if (frontMatch) { + startIndex = frontMatch[0].split('\n').length - (frontMatch[0].endsWith('\n') ? 1 : 0); + try { + parseYaml(frontMatch[1]); + } + catch (err) { + findings.push(`L1: invalid YAML frontmatter (${err.message.split('\n')[0]})`); + } + } let fence = null; let fenceLine = 0; let table = null; let previous = ''; lines.forEach((line, index) => { + if (index < startIndex) { return; } const lineNumber = index + 1; const fenceMatch = /^\s*(`{3,}|~{3,})/.exec(line); if (fenceMatch) { diff --git a/tools/gates/ai.test.js b/tools/gates/ai.test.js new file mode 100644 index 0000000..963aef8 --- /dev/null +++ b/tools/gates/ai.test.js @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; + +import { checkMarkdownStructure } from './ai.js'; + +describe('ai gate markdown structure', () => { + it('accepts quoted YAML frontmatter scalars containing colons and braces', () => { + const doc = [ + '---', + 'title: Plugins Guide', + 'description: "Use { loose: true } and configure({ dayFirst: true }) safely."', + 'keywords: ["@native-dates/plugins", loose]', + 'audience: usage', + 'skill: native-dates-plugins', + 'type: skill', + '---', + '', + '# Plugins Guide', + '', + '| Col A | Col B |', + '|---|---|', + '| 1 | 2 |', + '', + ].join('\n'); + + expect(checkMarkdownStructure(doc)).toEqual([]); + }); + + it('flags invalid unquoted YAML mappings in frontmatter', () => { + const broken = [ + '---', + 'title: Plugins Guide', + 'description: Use { loose: true } without quotes', + '---', + '', + '# Plugins Guide', + ].join('\n'); + + const findings = checkMarkdownStructure(broken); + expect(findings).toHaveLength(1); + expect(findings[0]).toMatch(/^L1: invalid YAML frontmatter/); + }); +}); From d781f5c732c0d8e0b027bdce87d211e715a19827 Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 18:06:11 -0500 Subject: [PATCH 3/4] Docs: Clarify Loose Pipeline, Exhaustive Zones, and Guard Exports in Plugins Skill --- ai/skills/native-dates-plugins.md | 63 +++++++++++++++---------------- 1 file changed, 31 insertions(+), 32 deletions(-) diff --git a/ai/skills/native-dates-plugins.md b/ai/skills/native-dates-plugins.md index 928bbd8..eb2117f 100644 --- a/ai/skills/native-dates-plugins.md +++ b/ai/skills/native-dates-plugins.md @@ -12,7 +12,7 @@ type: skill > **Skill:** `native-dates-plugins` > **Purpose:** Guide to `@native-dates/plugins/{zones,loose,legacy-date}`, `@native-dates/polyfill`, and custom prototype plugins -Each `@native-dates/plugins/*` subpath mutates `native-dates` hooks or prototypes once process-wide when imported (with no per-instance scoping or unload), and `@native-dates/polyfill` installs `temporal-polyfill` only when `globalThis.Temporal` is absent. +Each `@native-dates/plugins/*` subpath mutates `native-dates` hooks or prototypes once process-wide when imported (with no per-instance scoping or unload), and `@native-dates/polyfill` installs `temporal-polyfill` only when `globalThis.Temporal` is absent. Point factories (`datetime`, `date`, `time`, `monthDay`, `dayMonth`, `yearMonth`, `monthYear`) take `(input, zoneOrOpts?)`, range factories (`dateRange`, `datetimeRange`, `timeRange`) take `(start, end, zoneOrOpts?)` or `(intervalString, zoneOrOpts?)` where `zoneOrOpts` is a bare `zone` string or `{ zone, locale, loose, dayFirst }`, and `now(zone?)`, `today(zone?)`, `dt.in(zone)`, and `d.at(time?, zone?)` take a bare `zone` string. **Golden rule: Import plugin subpaths once at startup without `.use()`, pass `{ loose: true }` per call, and treat `{ loose: true }` as returning `null` for unreadable data while still throwing on bad options.** @@ -35,7 +35,7 @@ import { datetime } from 'native-dates'; datetime('Nov 16, 2026 9:30am', { zone: 'Berlin', loose: true }); ``` -**2. Strict core parsing always runs first; `{ loose: true }` is per-call only, defaults `'06/11/2026'` to US month-first (`June 11`), and still throws on bad caller options.** `configure({ loose: true })` throws `unknownSetting`, and `configure({ dayFirst: true })` only affects calls that also pass `{ loose: true }`. Under `{ loose: true }`, `null`, `undefined`, `""`, `NaN`, `'16/11/2026'` (without `dayFirst`), rolled-forward `'Feb 30, 2026'`, and non-English month names in `date()`/`datetime()` all return `null` (`T | null` in TypeScript, never *now*), whereas bad options (`zone: 'Mars/Olympus'`, `locale: '123'`) still throw `unknownZone` or `unknownLocale`. +**2. Strict core parsing always runs first; `{ loose: true }` is per-call only, defaults `'06/11/2026'` to US month-first (`June 11`), and still throws on bad caller options.** `configure({ loose: true })` throws `unknownSetting`, and `configure({ dayFirst: true })` only affects calls that also pass `{ loose: true }`. Under `{ loose: true }`, `null`, `undefined`, `""`, `NaN`, `new Date(NaN)`, booleans, `{}` (empty fields), `'16/11/2026'` (without `dayFirst`), rolled-forward `'Feb 30, 2026'`, and non-English month names in `date()`/`datetime()` all return `null` (`T | null` in TypeScript, never *now*), whereas bad options (`zone: 'Mars/Olympus'`, `locale: '123'`) still throw `unknownZone` or `unknownLocale`. ```js // ❌ WRONG - omitting { loose: true } after configure({ dayFirst: true }), or assuming French date() works @@ -49,7 +49,7 @@ date(undefined, { loose: true }); // null (never defaults to today/now) monthDay('17 octobre', { loose: true, locale: 'fr' }); // MonthDay(10-17) — partials DO match Intl locales ``` -**3. `@native-dates/plugins/zones` maps `'EST'`/`'MST'`/`'HST'` to DST-observing zones and resolves IANA leaf cities, NOT arbitrary world cities.** Without `zones`, `Temporal` treats `'EST'` as fixed `-05:00`; with `zones`, `'EST'`/`'EDT'`/`'ET'` map to `'America/New_York'` (pass `'-05:00'` for a fixed offset). City lookup indexes `Intl.supportedValuesOf('timeZone')` leaf names and tzdb links, so `'Berlin'`, `'Los Angeles'`, and `'Ho Chi Minh'` resolve, while non-IANA cities like `'San Francisco'`, `'Munich'`, or `'Mumbai'` throw `unknownZone` unless mapped via `configure({ zoneAliases })`. +**3. `@native-dates/plugins/zones` resolves `zone` parameters and `[Zone]` suffixes — NOT inline tokens inside `loose` strings — and indexes IANA leaf cities rather than all world cities.** With `zones` loaded, `'EST'`/`'MST'`/`'HST'` map to DST-observing `'America/New_York'`/`'America/Denver'`/`'Pacific/Honolulu'` (pass `'-05:00'` for a fixed offset), and IANA leaf cities (`'Berlin'`, `'Los Angeles'`, `'Ho Chi Minh'`) resolve while non-IANA cities (`'San Francisco'`, `'Munich'`, `'Mumbai'`) throw `unknownZone` unless added to `zoneAliases`. Inside loose text (`'Nov 16, 2026 9am IST'` or `'... HQ'`), inline zone tokens hit native `Date.parse` and do **not** consult `zones` — pass `{ zone: 'IST' }` separately. **4. `legacy-date` attaches only to `DateTime.prototype`, evaluates local `Date` getters in `dt.zone` (not the host OS timezone), and throws `immutable` on setters.** `CalendarDate` and `Time` get no `Date` methods. On `DateTime`, `dt.getHours()` and `dt.getDay()` (`0`–`6`) read in `dt.zone` even on a UTC server, `dt.getMonth()` returns `0`–`11` (`dt.month` stays `1`–`12`), and all `set*`/`setUTC*` mutators throw `RangeError` (`code: 'immutable'`). @@ -63,13 +63,13 @@ tokyo.getMonth(); // 10 (0-indexed; tokyo.month is 11) tokyo.setHours(12); // RangeError [immutable] — use tokyo.set('hour', 12) ``` -**5. Node `<26` (Node 20/22/24 LTS) and Safari require both `@native-dates/polyfill` AND `"temporal-polyfill": ">=0.3.0"` in your app's `dependencies`.** Bundlers statically resolve `import('temporal-polyfill')`, so omitting `"temporal-polyfill"` from `package.json` breaks builds even when targeting Chrome. Use `'@native-dates/polyfill/sync'` in CommonJS or build targets without top-level `await`. +**5. Node `<26` (Node 20/22/24 LTS) and Safari require both `@native-dates/polyfill` AND `"temporal-polyfill": ">=0.3.0"` in your app's `dependencies`.** Bundlers statically resolve `import('temporal-polyfill')`, so omitting `"temporal-polyfill"` from `package.json` breaks builds even when targeting Chrome. Use `'@native-dates/polyfill/sync'` in CommonJS, build targets without top-level `await`, or when sibling static imports call `today()`/`now()` at module top level. --- ## @native-dates/plugins/zones -Resolves IANA leaf cities, tzdb links, timezone abbreviations, and custom `zoneAliases` anywhere a `zone` parameter or `[Zone]` suffix is accepted (`datetime`, `date`, `time`, `now`, `today`, `in`, `at`, `configure`). Named `import { timezones } from '@native-dates/plugins/zones'` registers the plugin automatically without a second bare import. +Named `import { timezones } from '@native-dates/plugins/zones'` registers the plugin automatically without a second bare import: ```js import { timezones } from '@native-dates/plugins/zones'; @@ -82,47 +82,47 @@ datetime('2026-11-16T09:30', 'HQ').zone; // 'Europe/Berlin' (case/space/undersco datetime('2026-11-16T09:30', 'são_paulo').zone; // 'America/Sao_Paulo' ``` -| Precedence (1 = highest) | Source & examples | Override / behavior | +| Precedence (1 = highest) | Exhaustive set / lookup source | Override / behavior | |---|---|---| -| 1. `configure({ zoneAliases })` | `{ hq: 'Berlin', sf: 'America/Los_Angeles' }` | Merges across calls; validates/resolves targets eagerly (`unknownZone` if invalid); `{ hq: null }` deletes one key, `zoneAliases: null` clears all | -| 2. Exported `timezones` object | `ET`, `CT`, `MT`, `PT`, `AKT`, `HT`, `AT`, `UK`, `WET`, `CET`, `ECT`, `EET`, `IRST`, `AET`, `ACT`, `AWT`, `NZT`, `BRT`, `IST` (`Asia/Kolkata`), `INST`, `JST`, `SGT` | Mutable map for ambiguous regional codes (`timezones.IST = '...'`) | -| 3. Built-in abbreviations | `EST`/`EDT`/`Eastern`, `CST`/`CDT`/`Central`, `MST`/`MDT`/`Mountain`, `PST`/`PDT`/`Pacific`, `AKST`/`AKDT`/`Alaska`, `HST`/`Hawaii`, `BST`, `CEST`, `KST`, `AEST`/`AEDT`, `NZST`/`NZDT`, `HKT`, `GMT`, `Z` | Maps to DST-observing IANA zones (`GMT` & `Z` -> `'UTC'`); override via `zoneAliases` | -| 4. IANA IDs, leaf cities & tzdb links | `'los angeles'`, `'buenos aires'`, `'ho chi minh'`, `'europe/paris'` | Case/accent/separator-insensitive against `Intl.supportedValuesOf('timeZone')` and `Temporal` `/` links | +| 1. `configure({ zoneAliases })` | App-defined `{ hq: 'Berlin', sf: 'America/Los_Angeles' }` | Merges across calls; validates/resolves targets eagerly (`unknownZone` if invalid); `{ hq: null }` deletes one key, `zoneAliases: null` clears all | +| 2. Exported `timezones` (all 22 keys) | `ET`, `CT`, `MT`, `PT`, `AKT`, `HT`, `AT`, `UK`, `WET`, `CET`, `ECT`, `EET`, `IRST`, `AET`, `ACT`, `AWT`, `NZT`, `BRT`, `IST` (`Asia/Kolkata`), `INST`, `JST`, `SGT` | Mutable map (`timezones.IST = '...'`); unlisted regional codes (`MSK`, `ICT`, `ART`, `EAT`) require `zoneAliases` or IANA IDs | +| 3. Built-in abbreviations (all 30 keys) | `EST`/`EDT`/`Eastern`, `CST`/`CDT`/`Central`, `MST`/`MDT`/`Mountain`, `PST`/`PDT`/`Pacific`, `AKST`/`AKDT`/`Alaska`, `HST`/`Hawaii`, `BST`, `CEST`, `JST`, `KST`, `AEST`/`AEDT`, `NZST`/`NZDT`, `SGT`, `HKT`, `GMT`, `Z` | Maps to DST-observing IANA zones (`GMT` & `Z` -> `'UTC'`); override via `zoneAliases` | +| 4. IANA IDs, leaf cities & tzdb links | Any `Intl.supportedValuesOf('timeZone')` ID/leaf (`'los angeles'`, `'buenos aires'`) or `/` link (`'ho chi minh'`) | Case-, accent-, space-, hyphen-, and underscore-insensitive | --- ## @native-dates/plugins/loose -When strict core parsing fails and `{ loose: true }` is passed, factories fall back as follows (`T | null` in TypeScript): +Every factory tries its strict core parser first (`'2026/11/06'`, `'5:30 PM'`, and `'2h 30m'` already succeed in core, so `dayFirst` never disturbs 4-digit year-first strings). When strict parsing fails and `{ loose: true }` is set (`T | null` in TypeScript): -- **`datetime()` and `date()` (`Date.parse` fallback):** - - Accepts English month names (`'Oct 17, 2026'`) and numeric slash/dot/hyphen dates (`'11/06/2026'`, `'06.11.2026'`, `'06-11-2026'`, 2-digit years `'11/06/26'` -> `2026`). Without `dayFirst: true`, `'16/11/2026'` returns `null` (never auto-flips `16 > 12`). - - Catches `Date.parse` calendar rollovers (`'Feb 30, 2026'`, `'11/31/2026'` -> `null`), as well as `null`, `undefined`, `""`, `NaN`, `{}` (`-> null`). - - **Zone handling:** Unzoned strings keep their written wall clock in `zone` (defaulting to `configure({ zone })` or system local IANA zone). Inline zone tokens inside strings rely strictly on native `Date.parse` (`Z`, numeric `+02:00`, `GMT`/`UTC`, US `EST`/`EDT`/`CST`/`CDT`/`MST`/`MDT`/`PST`/`PDT`) to fix the instant and convert to `zone` — inline tokens do **not** consult `zones` plugin `timezones` or `zoneAliases` (`'Nov 16, 2026 9am IST'` or `'... HQ'`; pass `{ zone: 'IST' }` as an option instead). -- **`time()`:** Extracts `.toPlainTime()` from any loose date-time string (`time('Nov 16, 2026 5:30 PM', { loose: true })` -> `17:30:00`), or returns `null`. +- **`datetime()` and `date()` 3-step pipeline:** + 1. **Leading numeric order:** Strings starting with `1–2` digits + `[./-]` + `1–2` digits + `[./-]` + `2–4` digits (`'11/06/2026'`, `'16.11.2026'`, `'16-11-26'`) normalize to slashes, swapping fields 1 & 2 only when `dayFirst` is enabled. + 2. **Engine `Date.parse` + rollover check:** Parses English month names and numeric dates (engine 2-digit years map `'00`–`'49` -> `2000`–`2049` and `'50`–`'99` -> `1950`–`1999`; yearless `'Oct 17'` defaults to `2001` in V8, so use `monthDay('Oct 17', { loose: true })` for recurring dates), then re-tests day `28` to reject rolled-forward dates (`'Feb 30, 2026'`, `'11/31/2026'` -> `null`). + 3. **Zone & instant placement:** Unzoned strings keep their written wall clock in `zone` (`configure({ zone })` or system local IANA zone). Strings carrying `Z`, numeric `+02:00`, `GMT`/`UTC`, or US `EST`/`EDT`/`CST`/`CDT`/`MST`/`MDT`/`PST`/`PDT` fix that instant and convert to `zone`. +- **`time()`:** Standalone `'5:30 PM'` succeeds in core; `{ loose: true }` also extracts `.toPlainTime()` from full date-time strings (`time('Nov 16, 2026 5:30 PM', { loose: true })` -> `17:30:00`) or returns `null`. - **`monthDay()`, `dayMonth()`, `yearMonth()`, `monthYear()`:** Matches English month names first (`'Mar 17'` stays March under `'fi'`), then localized `Intl` month names in `{ locale }` or `configure({ locale })`. Two-digit ISO `'10-17'` with a hyphen stays month-first even in `dayMonth('10-17')`, whereas `'17/10'` reads day-first. -- **`duration()`:** Core already parses `'2h 30m'` and `'90 mins'`; `{ loose: true }` returns `null` on unreadable text, `unknownUnit` (`'5 lightyears'`), `conflictingSigns`, `invalidFraction`, or `NaN`. +- **`duration()`:** Core parses `'2h 30m'` and `'90 mins'`; `{ loose: true }` returns `null` on unreadable text, `unknownUnit` (`'5 lightyears'`), `conflictingSigns`, `invalidFraction`, or `NaN`. - **`dateRange()`, `datetimeRange()`, `timeRange()`:** Forwards `{ loose: true, dayFirst, zone, locale }` to both endpoints and returns `null` if either endpoint is unreadable; valid endpoints with `end < start` on `DateRange`/`DateTimeRange` still throw `invalidRange`. --- ## @native-dates/plugins/legacy-date -Attaches `Date.prototype` shims to `DateTime.prototype` only (`valueOf()` / `+dt` and `toJSDate()` already exist in core): +Shims `Date.prototype` onto `DateTime.prototype` (`valueOf()` / `+dt` and `toJSDate()` are already in core): -- **Shimmed reads (22):** Zone-local `get{FullYear,Month,Date,Day,Hours,Minutes,Seconds,Milliseconds}()` and `getTimezoneOffset()` (minutes positive west of UTC in `this.zone`); UTC `getTime()` and `getUTC*()` (8 methods); `toISOString()` (fixed `.sssZ`); and `toLocale{,Date,Time}String(locales?, opts?)` (defaulting to `this.locale()` and `this.zone`). -- **Not shimmed / blocked:** `toDateString()` and `toUTCString()` are omitted (use `dt.toJSDate().toUTCString()`); all 15 `set*` and `setUTC*` methods throw `RangeError` (`code: 'immutable'`). +- **22 shimmed reads:** Zone-local `get{FullYear,Month,Date,Day,Hours,Minutes,Seconds,Milliseconds}()` and `getTimezoneOffset()` (positive west of UTC in `this.zone`); UTC `getTime()` and `getUTC*()` (8 methods); `toISOString()` (fixed `.sssZ`); and `toLocale{,Date,Time}String(locales?, opts?)` (defaulting to `this.locale()` and `this.zone`). +- **Omitted / blocked:** `toDateString()` and `toUTCString()` are not shimmed (`dt.toJSDate().toUTCString()`); all 15 `set*`/`setUTC*` methods throw `RangeError` (`code: 'immutable'`). --- ## @native-dates/polyfill -`native-dates` reads `globalThis.Temporal` lazily at call time; import the polyfill at entrypoint startup before calling factories (with `"temporal-polyfill": ">=0.3.0"` installed): +`native-dates` reads `globalThis.Temporal` lazily at call time (`"temporal-polyfill": ">=0.3.0"` required in `dependencies`): -| Entrypoint | Mechanism | Target environments | +| Entrypoint | Mechanism | When to use | |---|---|---| -| `import '@native-dates/polyfill'` | `if (!globalThis.Temporal) await import('temporal-polyfill')` | ESM browsers (0 B downloaded on Chrome/Firefox/Edge; dynamic chunk on Safari) & ESM on Node `<26` | -| `import '@native-dates/polyfill/sync'` | Sync `import { Temporal } from 'temporal-polyfill'` + `if (!globalThis.Temporal)` | CommonJS bundles, test setups, or bundler targets disallowing top-level `await` | +| `import '@native-dates/polyfill'` | `if (!globalThis.Temporal) await import('temporal-polyfill')` | ESM browser entrypoints (0 B downloaded on Chrome/Firefox/Edge; dynamic chunk on Safari) & async ESM on Node `<26` | +| `import '@native-dates/polyfill/sync'` | Sync `import { Temporal } from 'temporal-polyfill'` + `if (!globalThis.Temporal)` | CommonJS, test setups, targets without top-level `await`, or when sibling static imports call `today()`/`now()` during module evaluation | --- @@ -130,7 +130,7 @@ Attaches `Date.prototype` shims to `DateTime.prototype` only (`valueOf()` / `+dt Parser and zone hooks (`native-dates/helpers/*`) are private to `@native-dates/plugins` without semver guarantees. Third-party plugins extend the 9 exported class prototypes (`DateTime`, `CalendarDate`, `Time`, `Duration`, `MonthDay`, `YearMonth`, `DateRange`, `DateTimeRange`, `TimeRange`): -- **Cross-realm identity:** `kindOf(v)` returns `'datetime' | 'date' | 'time' | 'duration' | 'monthDay' | 'yearMonth' | 'dateRange' | 'datetimeRange' | 'timeRange' | undefined`. Exported `Symbol.for` keys (`IS_DATE_TIME`, `IS_CALENDAR_DATE`, `IS_TIME`, `IS_DURATION`, `IS_MONTH_DAY`, `IS_YEAR_MONTH`, `IS_RANGE`, `IS_DATE_RANGE`, `IS_DATE_TIME_RANGE`, `IS_TIME_RANGE`) are **property keys** (`Boolean(v?.[IS_CALENDAR_DATE])`, never called as functions), alongside predicate functions `isDateTime(v)`, `isCalendarDate(v)`, etc. +- **Cross-realm identity:** `kindOf(v)` returns `'datetime' | 'date' | 'time' | 'duration' | 'monthDay' | 'yearMonth' | 'dateRange' | 'datetimeRange' | 'timeRange' | undefined`. Exported predicates are `isDateTime`, `isCalendarDate`, `isTime`, `isDuration`, `isMonthDay`, `isYearMonth`, `isDateRange`, `isDateTimeRange`, and `isTimeRange` (there is no `isRange` function — use `Boolean(v?.[IS_RANGE])`). All 10 `IS_*` exports (`IS_DATE_TIME`, `IS_CALENDAR_DATE`, `IS_TIME`, `IS_DURATION`, `IS_MONTH_DAY`, `IS_YEAR_MONTH`, `IS_RANGE`, `IS_DATE_RANGE`, `IS_DATE_TIME_RANGE`, `IS_TIME_RANGE`) are `Symbol.for` **property keys**, never callable functions. - **Immutability & packaging:** Instances are frozen (`this.date`, `this.time`, `this.zone` are getters; `this.locale()` is a 0-arg getter / 1-arg clone method). Return new instances, list entry files in `"sideEffects": ["./index.js"]`, and put `"native-dates"` in `"peerDependencies"`. ```ts @@ -162,13 +162,12 @@ export const isSupportedPoint = (v: unknown) => Boolean((v as any)?.[IS_CALENDAR ## Quick Reference -| Untrusted / edge-case situation | Outcome | Idiom | +| Cross-plugin / boundary scenario | What happens | Recommended pattern | |---|---|---| -| Untrusted `rawText` AND untrusted `zoneName` | `loose` returns `null` for `rawText`, but throws `unknownZone` on `zoneName` | Wrap in `try/catch` checking `err?.code === 'unknownZone'` | -| Non-IANA city (`'San Francisco'`, `'Mumbai'`) | Throws `unknownZone` | Register `configure({ zoneAliases: { sf: 'America/Los_Angeles', mumbai: 'Asia/Kolkata' } })` | -| Non-US inline zone in string (`'Nov 16 9am IST'`) | `Date.parse` returns `null` (doesn't read `timezones`) | Strip or pass zone separately: `datetime('Nov 16, 2026 9am', { zone: 'IST', loose: true })` | -| `16/11/2026` without `dayFirst: true` | Returns `null` under `{ loose: true }` | Pass `{ loose: true, dayFirst: true }` (or `configure({ dayFirst: true })` + `{ loose: true }`) | -| Fixed `-05:00` year-round after importing `zones` | `'EST'` now observes EDT in summer | Pass explicit offset string `'-05:00'` instead of `'EST'` | +| Both `rawText` and `rawZone` come from untrusted CSV/form input | `loose` turns bad `rawText` into `null`, while bad `rawZone` still throws `unknownZone` | Wrap call in `try/catch` checking `err?.code === 'unknownZone'` | +| Bracketed ISO `'2026-11-16T09:00[Berlin]'` vs loose `'Nov 16, 2026 9am IST'` | `[Berlin]` resolves through `zones`; inline `'IST'` hits `Date.parse` and returns `null` | Pass zone via option: `datetime('Nov 16, 2026 9am', { zone: 'IST', loose: true })` | +| Sibling `import './config.js'` calls `today()` at top level on Node 22 / Safari | Static sibling imports evaluate before default polyfill's top-level `await` settles | Import `'@native-dates/polyfill/sync'` first at entrypoint | +| Yearless `'Oct 17'` vs historical `'05/14/85'` in `date(..., { loose: true })` | Engine `Date.parse` defaults `'Oct 17'` to year `2001`, and maps `'85` -> `1985` (`'00`–`'49` -> `20xx`) | Use `monthDay('Oct 17', { loose: true })` for yearless dates; require 4-digit years past `2049`/`1950` | ```js import '@native-dates/polyfill/sync'; @@ -181,7 +180,7 @@ configure({ dayFirst: true, zoneAliases: { sf: 'America/Los_Angeles' } }); export function parseCsvTimestamp(rawText, rawZone) { try { - return datetime(rawText, { zone: rawZone, loose: true }); // DateTime | null (null if rawText is null/""/invalid) + return datetime(rawText, { zone: rawZone, loose: true }); // DateTime | null } catch (err) { if (err?.code === 'unknownZone') { return null; } throw err; From 2926999c30103269b865138619326f8040badc7b Mon Sep 17 00:00:00 2001 From: Jack Lukic Date: Fri, 20 Nov 2026 18:10:14 -0500 Subject: [PATCH 4/4] Docs: Fix Abbreviation Key Count and Range Loose Guard in Plugins Skill --- ai/skills/native-dates-plugins.md | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/ai/skills/native-dates-plugins.md b/ai/skills/native-dates-plugins.md index eb2117f..3c1591e 100644 --- a/ai/skills/native-dates-plugins.md +++ b/ai/skills/native-dates-plugins.md @@ -12,9 +12,9 @@ type: skill > **Skill:** `native-dates-plugins` > **Purpose:** Guide to `@native-dates/plugins/{zones,loose,legacy-date}`, `@native-dates/polyfill`, and custom prototype plugins -Each `@native-dates/plugins/*` subpath mutates `native-dates` hooks or prototypes once process-wide when imported (with no per-instance scoping or unload), and `@native-dates/polyfill` installs `temporal-polyfill` only when `globalThis.Temporal` is absent. Point factories (`datetime`, `date`, `time`, `monthDay`, `dayMonth`, `yearMonth`, `monthYear`) take `(input, zoneOrOpts?)`, range factories (`dateRange`, `datetimeRange`, `timeRange`) take `(start, end, zoneOrOpts?)` or `(intervalString, zoneOrOpts?)` where `zoneOrOpts` is a bare `zone` string or `{ zone, locale, loose, dayFirst }`, and `now(zone?)`, `today(zone?)`, `dt.in(zone)`, and `d.at(time?, zone?)` take a bare `zone` string. +Each `@native-dates/plugins/*` subpath mutates `native-dates` hooks or prototypes once process-wide when imported (with no per-instance scoping or unload), and `@native-dates/polyfill` installs `temporal-polyfill` only when `globalThis.Temporal` is absent. Point factories (`datetime`, `date`, `time`, `monthDay`, `dayMonth`, `yearMonth`, `monthYear`) take `(input, zoneOrOpts?)`, `duration` takes `(input, unitOrOpts?)`, range factories (`dateRange`, `datetimeRange`, `timeRange`) take `(start, end, zoneOrOpts?)` or `(intervalString, zoneOrOpts?)` where `zoneOrOpts` is a bare `zone` string or `{ zone, locale, loose, dayFirst }`, and `now(zone?)`, `today(zone?)`, `dt.in(zone)`, and `d.at(time?, zone?)` take a bare `zone` string. -**Golden rule: Import plugin subpaths once at startup without `.use()`, pass `{ loose: true }` per call, and treat `{ loose: true }` as returning `null` for unreadable data while still throwing on bad options.** +**Golden rule: Import plugin subpaths once at startup without `.use()`, pass `{ loose: true }` per call, and remember `{ loose: true }` returns `null` for unreadable data while still throwing on bad options (and `invalidRange` when `end < start`).** --- @@ -35,7 +35,7 @@ import { datetime } from 'native-dates'; datetime('Nov 16, 2026 9:30am', { zone: 'Berlin', loose: true }); ``` -**2. Strict core parsing always runs first; `{ loose: true }` is per-call only, defaults `'06/11/2026'` to US month-first (`June 11`), and still throws on bad caller options.** `configure({ loose: true })` throws `unknownSetting`, and `configure({ dayFirst: true })` only affects calls that also pass `{ loose: true }`. Under `{ loose: true }`, `null`, `undefined`, `""`, `NaN`, `new Date(NaN)`, booleans, `{}` (empty fields), `'16/11/2026'` (without `dayFirst`), rolled-forward `'Feb 30, 2026'`, and non-English month names in `date()`/`datetime()` all return `null` (`T | null` in TypeScript, never *now*), whereas bad options (`zone: 'Mars/Olympus'`, `locale: '123'`) still throw `unknownZone` or `unknownLocale`. +**2. Strict core parsing always runs first; `{ loose: true }` is per-call only, defaults `'06/11/2026'` to US month-first (`June 11`), and still throws on bad caller options.** `configure({ loose: true })` throws `unknownSetting`, and `configure({ dayFirst: true })` only affects calls that also pass `{ loose: true }`. Under `{ loose: true }`, `null`, `undefined`, `""`, `NaN`, `new Date(NaN)`, booleans, invalid or empty field objects (`{}`, `{ year: 2026, month: 2, day: 30 }`), `'16/11/2026'` (without `dayFirst`), rolled-forward `'Feb 30, 2026'`, and non-English month names in `date()`/`datetime()` all return `null` (`T | null` in TypeScript, never *now*), whereas bad options (`zone: 'Mars/Olympus'`, `locale: '123'`) and reversed `DateRange`/`DateTimeRange` bounds (`end < start`, `invalidRange`) still throw. ```js // ❌ WRONG - omitting { loose: true } after configure({ dayFirst: true }), or assuming French date() works @@ -84,9 +84,9 @@ datetime('2026-11-16T09:30', 'são_paulo').zone; // 'America/Sao_Paulo' | Precedence (1 = highest) | Exhaustive set / lookup source | Override / behavior | |---|---|---| -| 1. `configure({ zoneAliases })` | App-defined `{ hq: 'Berlin', sf: 'America/Los_Angeles' }` | Merges across calls; validates/resolves targets eagerly (`unknownZone` if invalid); `{ hq: null }` deletes one key, `zoneAliases: null` clears all | +| 1. `configure({ zoneAliases })` | App-defined `{ hq: 'Berlin', sf: 'America/Los_Angeles' }` | Merges across calls and runs before `zone` in `configure({ zoneAliases, zone })`; validates targets eagerly (`unknownZone` if invalid); `{ hq: null }` deletes one key, `zoneAliases: null` clears all | | 2. Exported `timezones` (all 22 keys) | `ET`, `CT`, `MT`, `PT`, `AKT`, `HT`, `AT`, `UK`, `WET`, `CET`, `ECT`, `EET`, `IRST`, `AET`, `ACT`, `AWT`, `NZT`, `BRT`, `IST` (`Asia/Kolkata`), `INST`, `JST`, `SGT` | Mutable map (`timezones.IST = '...'`); unlisted regional codes (`MSK`, `ICT`, `ART`, `EAT`) require `zoneAliases` or IANA IDs | -| 3. Built-in abbreviations (all 30 keys) | `EST`/`EDT`/`Eastern`, `CST`/`CDT`/`Central`, `MST`/`MDT`/`Mountain`, `PST`/`PDT`/`Pacific`, `AKST`/`AKDT`/`Alaska`, `HST`/`Hawaii`, `BST`, `CEST`, `JST`, `KST`, `AEST`/`AEDT`, `NZST`/`NZDT`, `SGT`, `HKT`, `GMT`, `Z` | Maps to DST-observing IANA zones (`GMT` & `Z` -> `'UTC'`); override via `zoneAliases` | +| 3. Built-in abbreviations (all 29 keys) | `EST`/`EDT`/`Eastern`, `CST`/`CDT`/`Central`, `MST`/`MDT`/`Mountain`, `PST`/`PDT`/`Pacific`, `AKST`/`AKDT`/`Alaska`, `HST`/`Hawaii`, `BST`, `CEST`, `JST`, `KST`, `AEST`/`AEDT`, `NZST`/`NZDT`, `SGT`, `HKT`, `GMT`, `Z` | Maps to DST-observing IANA zones (`GMT` & `Z` -> `'UTC'`); override via `zoneAliases` | | 4. IANA IDs, leaf cities & tzdb links | Any `Intl.supportedValuesOf('timeZone')` ID/leaf (`'los angeles'`, `'buenos aires'`) or `/` link (`'ho chi minh'`) | Case-, accent-, space-, hyphen-, and underscore-insensitive | --- @@ -98,9 +98,9 @@ Every factory tries its strict core parser first (`'2026/11/06'`, `'5:30 PM'`, a - **`datetime()` and `date()` 3-step pipeline:** 1. **Leading numeric order:** Strings starting with `1–2` digits + `[./-]` + `1–2` digits + `[./-]` + `2–4` digits (`'11/06/2026'`, `'16.11.2026'`, `'16-11-26'`) normalize to slashes, swapping fields 1 & 2 only when `dayFirst` is enabled. 2. **Engine `Date.parse` + rollover check:** Parses English month names and numeric dates (engine 2-digit years map `'00`–`'49` -> `2000`–`2049` and `'50`–`'99` -> `1950`–`1999`; yearless `'Oct 17'` defaults to `2001` in V8, so use `monthDay('Oct 17', { loose: true })` for recurring dates), then re-tests day `28` to reject rolled-forward dates (`'Feb 30, 2026'`, `'11/31/2026'` -> `null`). - 3. **Zone & instant placement:** Unzoned strings keep their written wall clock in `zone` (`configure({ zone })` or system local IANA zone). Strings carrying `Z`, numeric `+02:00`, `GMT`/`UTC`, or US `EST`/`EDT`/`CST`/`CDT`/`MST`/`MDT`/`PST`/`PDT` fix that instant and convert to `zone`. + 3. **Zone & instant placement:** Unzoned strings keep their written wall clock in `zone` (`configure({ zone })` or system local IANA zone). Strings carrying `Z`, numeric `+02:00`, `GMT`/`UTC`, or US `EST`/`EDT`/`CST`/`CDT`/`MST`/`MDT`/`PST`/`PDT` fix that instant via `Date.parse`'s fixed offsets (`EST` = `-05:00`) and convert to `zone`. - **`time()`:** Standalone `'5:30 PM'` succeeds in core; `{ loose: true }` also extracts `.toPlainTime()` from full date-time strings (`time('Nov 16, 2026 5:30 PM', { loose: true })` -> `17:30:00`) or returns `null`. -- **`monthDay()`, `dayMonth()`, `yearMonth()`, `monthYear()`:** Matches English month names first (`'Mar 17'` stays March under `'fi'`), then localized `Intl` month names in `{ locale }` or `configure({ locale })`. Two-digit ISO `'10-17'` with a hyphen stays month-first even in `dayMonth('10-17')`, whereas `'17/10'` reads day-first. +- **`monthDay()`, `dayMonth()`, `yearMonth()`, `monthYear()`:** Matches English month names first (`'Mar 17'` stays March under `'fi'`), then localized `Intl` month names in `{ locale }` or `configure({ locale })`. `monthDay('16/11', { loose: true, dayFirst: true })` honors `dayFirst`, whereas `dayMonth('16/11')` always reads `/` or `.` day-first and two-digit ISO `'10-17'` with a hyphen stays month-first even in `dayMonth('10-17')`. - **`duration()`:** Core parses `'2h 30m'` and `'90 mins'`; `{ loose: true }` returns `null` on unreadable text, `unknownUnit` (`'5 lightyears'`), `conflictingSigns`, `invalidFraction`, or `NaN`. - **`dateRange()`, `datetimeRange()`, `timeRange()`:** Forwards `{ loose: true, dayFirst, zone, locale }` to both endpoints and returns `null` if either endpoint is unreadable; valid endpoints with `end < start` on `DateRange`/`DateTimeRange` still throw `invalidRange`. @@ -164,31 +164,30 @@ export const isSupportedPoint = (v: unknown) => Boolean((v as any)?.[IS_CALENDAR | Cross-plugin / boundary scenario | What happens | Recommended pattern | |---|---|---| -| Both `rawText` and `rawZone` come from untrusted CSV/form input | `loose` turns bad `rawText` into `null`, while bad `rawZone` still throws `unknownZone` | Wrap call in `try/catch` checking `err?.code === 'unknownZone'` | -| Bracketed ISO `'2026-11-16T09:00[Berlin]'` vs loose `'Nov 16, 2026 9am IST'` | `[Berlin]` resolves through `zones`; inline `'IST'` hits `Date.parse` and returns `null` | Pass zone via option: `datetime('Nov 16, 2026 9am', { zone: 'IST', loose: true })` | +| Untrusted `rawStart`, `rawEnd`, and `rawZone` in `dateRange` | `loose` turns bad strings into `null`, while bad `rawZone` throws `unknownZone` and `end < start` throws `invalidRange` | Catch `err?.code === 'unknownZone' \|\| err?.code === 'invalidRange'` | | Sibling `import './config.js'` calls `today()` at top level on Node 22 / Safari | Static sibling imports evaluate before default polyfill's top-level `await` settles | Import `'@native-dates/polyfill/sync'` first at entrypoint | -| Yearless `'Oct 17'` vs historical `'05/14/85'` in `date(..., { loose: true })` | Engine `Date.parse` defaults `'Oct 17'` to year `2001`, and maps `'85` -> `1985` (`'00`–`'49` -> `20xx`) | Use `monthDay('Oct 17', { loose: true })` for yearless dates; require 4-digit years past `2049`/`1950` | +| Single-call `configure({ zoneAliases: { hq: 'Berlin' }, zone: 'hq' })` | `zoneAliases` merges and resolves before `zone` is set | Safe in one `configure()` call; `{ hq: null }` deletes one alias | ```js import '@native-dates/polyfill/sync'; import { timezones } from '@native-dates/plugins/zones'; import '@native-dates/plugins/loose'; -import { configure, datetime } from 'native-dates'; +import { configure, dateRange } from 'native-dates'; timezones.IST = 'Asia/Jerusalem'; -configure({ dayFirst: true, zoneAliases: { sf: 'America/Los_Angeles' } }); +configure({ dayFirst: true, zoneAliases: { hq: 'Berlin' }, zone: 'hq' }); -export function parseCsvTimestamp(rawText, rawZone) { +export function parseCsvWindow(rawStart, rawEnd, rawZone) { try { - return datetime(rawText, { zone: rawZone, loose: true }); // DateTime | null + return dateRange(rawStart, rawEnd, { zone: rawZone, loose: true }); // DateRange | null } catch (err) { - if (err?.code === 'unknownZone') { return null; } + if (err?.code === 'unknownZone' || err?.code === 'invalidRange') { return null; } throw err; } } ``` -**Golden rule: Import plugin subpaths once at startup without `.use()`, pass `{ loose: true }` per call, and treat `{ loose: true }` as returning `null` for unreadable data while still throwing on bad options.** +**Golden rule: Import plugin subpaths once at startup without `.use()`, pass `{ loose: true }` per call, and remember `{ loose: true }` returns `null` for unreadable data while still throwing on bad options (and `invalidRange` when `end < start`).** ---