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/.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..3c1591e --- /dev/null +++ b/ai/skills/native-dates-plugins.md @@ -0,0 +1,198 @@ +--- +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 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 +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 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?)`, `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 remember `{ loose: true }` returns `null` for unreadable data while still throwing on bad options (and `invalidRange` when `end < start`).** + +--- + +## What You'd Get Wrong + +**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 export and no dayjs.extend() / .use() registration +import { loose, zones } from '@native-dates/plugins'; +datetime.extend(loose); + +// ✅ RIGHT - subpath imports self-register once for the whole JS realm +import '@native-dates/plugins/loose'; +import '@native-dates/plugins/zones'; +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, 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 +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. `@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'`). + +```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, 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. 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 + +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'; +import { configure, datetime } from 'native-dates'; + +timezones.IST = 'Asia/Jerusalem'; // override default 'Asia/Kolkata' +configure({ zoneAliases: { hq: 'Berlin', sf: 'America/Los_Angeles' } }); // merges & eagerly resolves targets! + +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' +``` + +| Precedence (1 = highest) | Exhaustive set / lookup source | Override / behavior | +|---|---|---| +| 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 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 | + +--- + +## @native-dates/plugins/loose + +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()` 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 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 })`. `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`. + +--- + +## @native-dates/plugins/legacy-date + +Shims `Date.prototype` onto `DateTime.prototype` (`valueOf()` / `+dt` and `toJSDate()` are already in core): + +- **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 (`"temporal-polyfill": ">=0.3.0"` required in `dependencies`): + +| Entrypoint | Mechanism | When to use | +|---|---|---| +| `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 | + +--- + +## Authoring Custom Plugins + +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 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 +// 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 + +| Cross-plugin / boundary scenario | What happens | Recommended pattern | +|---|---|---| +| 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 | +| 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, dateRange } from 'native-dates'; + +timezones.IST = 'Asia/Jerusalem'; +configure({ dayFirst: true, zoneAliases: { hq: 'Berlin' }, zone: 'hq' }); + +export function parseCsvWindow(rawStart, rawEnd, rawZone) { + try { + return dateRange(rawStart, rawEnd, { zone: rawZone, loose: true }); // DateRange | null + } catch (err) { + 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 remember `{ loose: true }` returns `null` for unreadable data while still throwing on bad options (and `invalidRange` when `end < start`).** + +--- + +## Related Skills + +| Skill | Use when... | +|---|---| +| `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 new file mode 100644 index 0000000..48c250c --- /dev/null +++ b/ai/skills/native-dates.md @@ -0,0 +1,340 @@ +--- +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, 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 +--- + +# 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` (`@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: 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 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', or calling .toISOString() +const dt = datetime('2026-03-08T04:30:00Z'); +dt.zone; // local or configured zone (NOT 'UTC') + +// ✅ 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`, `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 - 0-indexed month/Sunday, or date-fns/Luxon 'yyyy-MM-dd' tokens +date(2026, 0, 15); // RangeError [invalidDate] +date('2026-11-16').format('yyyy-MM-dd'); // RangeError [unsupportedToken] ('dd' is narrow weekday 'Mo'!) + +// ✅ 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 timestamps name their unit explicitly.** Neither `.epoch`, `.timestamp`, nor `.unix()` exists. + +```js +// ❌ WRONG - undefined! +const exp = now().epoch; + +// ✅ RIGHT - epochSeconds (Number, floored), epochMilliseconds (Number), or epochNanoseconds (BigInt) +const jwtExp = now().plus(15, 'minutes').epochSeconds; +const ms = now().epochMilliseconds; +``` + +**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'); // RangeError [unknownDayOfWeek] + +// ✅ 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]`; `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 - 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 - .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()`. 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('days'), or days(1).minus(hours(1)) +minutes(90).normalize(); // TypeError +days(1).minus(hours(1)); // RangeError [conflictingSigns] + +// ✅ 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 +``` + +**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 - 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 - 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. `<`, `>`, 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`) | `<` / `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, datetime, endOfToday, now, startOfToday } from 'native-dates'; + +const dt = datetime('2026-11-16T09:30', 'America/Los_Angeles'); +const slot = dt.plus(2, 'days').at('14:17').round(15, 'minutes').in('Europe/Berlin'); +``` + +- **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 { CalendarDate, date, today, tomorrow, yesterday } from 'native-dates'; + +const due = today('America/New_York').plus(2, 'weeks').next('friday'); +``` + +- **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, time } from 'native-dates'; + +const scheduled = time('9:30am').plus(45, 'minutes').round(15, 'minutes').on('2026-11-16', 'America/Chicago'); +``` + +- **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 { 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 +``` + +- **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 { MonthDay, YearMonth, dayMonth, monthDay, monthYear, yearMonth } from 'native-dates'; + +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 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 -> 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 { DateRange, DateTimeRange, TimeRange, date, dateRange, datetimeRange, timeRange } from 'native-dates'; + +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, 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 + +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 `'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 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 | +| `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 starting on `firstDay` / `weekStart` / locale's first day (`locale` is the **3rd** argument). + +--- + +## configure, compare, and Guards + +```js +import { compare, configure, dayOfWeek, earliest, isDateTime, kindOf, latest } from 'native-dates'; + +configure({ + 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 (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 + +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` | 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 + +| 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) | + +```js +import { compare, date, datetime, earliest, isDateTime, today } from 'native-dates'; + +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: 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.** + +--- + +## Related Skills + +| Skill | Use when... | +|---|---| +| `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/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..a329d5d 100644 --- a/package.json +++ b/package.json @@ -23,6 +23,8 @@ "files": [ "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/); + }); +});