temporal-fmt 0.8.96 → 0.8.98
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -3
- package/dist/{chunk-QG4FJRJI.js → chunk-2R46FDWW.js} +2 -2
- package/dist/{chunk-AVR7G7JI.js → chunk-3RLYULUQ.js} +15 -1
- package/dist/chunk-3RLYULUQ.js.map +1 -0
- package/dist/{chunk-VL4LY2SF.js → chunk-EA34SFOW.js} +2 -2
- package/dist/{chunk-MT3IRF4V.js → chunk-EIJRFICK.js} +2 -2
- package/dist/chunk-EIJRFICK.js.map +1 -0
- package/dist/{chunk-PH4UNLZE.js → chunk-G7ADZLSD.js} +49 -14
- package/dist/chunk-G7ADZLSD.js.map +1 -0
- package/dist/{chunk-XPCESY6Z.js → chunk-PVJXJPHQ.js} +4 -4
- package/dist/{chunk-MMLNAIXW.js → chunk-WVMHS4OX.js} +2 -2
- package/dist/{chunk-MMLNAIXW.js.map → chunk-WVMHS4OX.js.map} +1 -1
- package/dist/{chunk-RP7T3IKD.js → chunk-X64UUZ7M.js} +3 -3
- package/dist/{chunk-XZ67GHW3.js → chunk-XIKLQMF7.js} +2 -2
- package/dist/{chunk-OHPQPOQ3.js → chunk-XUQBJHG2.js} +10 -2
- package/dist/chunk-XUQBJHG2.js.map +1 -0
- package/dist/codemod.d.cts +33 -0
- package/dist/codemod.d.ts +33 -0
- package/dist/duration.cjs.map +1 -1
- package/dist/duration.js +2 -2
- package/dist/format.cjs.map +1 -1
- package/dist/format.js +4 -4
- package/dist/ideData.d.cts +1 -1
- package/dist/ideData.d.ts +1 -1
- package/dist/index.cjs +286 -32
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +224 -29
- package/dist/index.js.map +1 -1
- package/dist/interval.cjs.map +1 -1
- package/dist/interval.js +5 -5
- package/dist/localeRegistry.cjs +22 -0
- package/dist/localeRegistry.cjs.map +1 -1
- package/dist/localeRegistry.js +2 -2
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.js +4 -4
- package/dist/recurrence.cjs +48 -13
- package/dist/recurrence.cjs.map +1 -1
- package/dist/recurrence.js +1 -1
- package/dist/relativeTime.js +3 -3
- package/package.json +9 -4
- package/scripts/cli.mjs +195 -111
- package/dist/chunk-AVR7G7JI.js.map +0 -1
- package/dist/chunk-MT3IRF4V.js.map +0 -1
- package/dist/chunk-OHPQPOQ3.js.map +0 -1
- package/dist/chunk-PH4UNLZE.js.map +0 -1
- /package/dist/{chunk-QG4FJRJI.js.map → chunk-2R46FDWW.js.map} +0 -0
- /package/dist/{chunk-VL4LY2SF.js.map → chunk-EA34SFOW.js.map} +0 -0
- /package/dist/{chunk-XPCESY6Z.js.map → chunk-PVJXJPHQ.js.map} +0 -0
- /package/dist/{chunk-RP7T3IKD.js.map → chunk-X64UUZ7M.js.map} +0 -0
- /package/dist/{chunk-XZ67GHW3.js.map → chunk-XIKLQMF7.js.map} +0 -0
package/README.md
CHANGED
|
@@ -834,7 +834,7 @@ A handful of functions exist specifically to feed editor tooling — autocomplet
|
|
|
834
834
|
|
|
835
835
|
## CLI
|
|
836
836
|
|
|
837
|
-
The CLI ships in this package (`scripts/cli.mjs`) and reads/writes stdin/stdout. Run it via `npm run cli` inside a checkout of this repo, or `node scripts/cli.mjs` directly:
|
|
837
|
+
The CLI ships in this package (`scripts/cli.mjs`) and reads/writes stdin/stdout. Run it via `npm run cli` inside a checkout of this repo, or `node scripts/cli.mjs` directly. Called with a subcommand it runs once and exits, same as any Unix tool — fine for scripts and CI:
|
|
838
838
|
|
|
839
839
|
```sh
|
|
840
840
|
temporal-fmt format "2026-08-04T15:45:30" "yyyy-MM-dd HH:mm:ss"
|
|
@@ -852,7 +852,23 @@ temporal-fmt translate dayjs "YYYY-MM-DD HH:mm:ss"
|
|
|
852
852
|
| `validate <format-string>` | Prints `valid` or `invalid`. |
|
|
853
853
|
| `translate <source-lib> <format-string>` | Translates a Day.js or date-fns format string to `temporal-fmt` tokens. |
|
|
854
854
|
|
|
855
|
-
|
|
855
|
+
`translate` is implemented in-repo (`src/codemod.ts`) against the same token tables the IDE tooling data uses — no external package, no runtime dependency beyond this library itself. It throws on tokens with no `temporal-fmt` equivalent (`Do`/`P`/etc. — see the [migration table](#token-mapping)) rather than guessing.
|
|
856
|
+
|
|
857
|
+
### Interactive mode
|
|
858
|
+
|
|
859
|
+
Run `temporal-fmt` with no arguments to start a REPL:
|
|
860
|
+
|
|
861
|
+
```
|
|
862
|
+
$ temporal-fmt
|
|
863
|
+
temporal-fmt interactive mode. Type a subcommand, "help", or "exit".
|
|
864
|
+
temporal-fmt> format
|
|
865
|
+
ISO input: 2026-08-04T15:45:30
|
|
866
|
+
Format string: yyyy-MM-dd HH:mm:ss
|
|
867
|
+
2026-08-04 15:45:30
|
|
868
|
+
temporal-fmt> exit
|
|
869
|
+
```
|
|
870
|
+
|
|
871
|
+
Type a subcommand with all its arguments inline (`validate yyyy-MM-dd`) or just the subcommand name — the REPL prompts for whatever's missing, one field at a time. Errors print and the session keeps going; `exit`, `quit`, or Ctrl+D ends it. This is the same subcommand logic as one-shot mode, just wrapped in a loop that asks instead of exiting on a missing argument — one-shot stays there for scripting, and doesn't touch the REPL machinery.
|
|
856
872
|
|
|
857
873
|
## Subpath imports
|
|
858
874
|
|
|
@@ -977,7 +993,7 @@ Migrate file by file, dropping the wrapper once nothing calls the old path anymo
|
|
|
977
993
|
Neither of these ships as part of this repository — separate packages, install them on their own:
|
|
978
994
|
|
|
979
995
|
- [`eslint-plugin-temporal-fmt`](https://www.npmjs.com/package/eslint-plugin-temporal-fmt) — lints format strings for common mistakes (e.g. `hh` without `a`). This is what backs the `analyzeFormat(formatStr).warnings` check mentioned in [Introspection and the analyzer](#introspection-and-the-analyzer) — same underlying metadata, surfaced as a lint diagnostic instead of a runtime call.
|
|
980
|
-
- [`temporal-fmt-codemod`](https://
|
|
996
|
+
- [`temporal-fmt-codemod`](https://github.com/DirazCoder/temporal-fmt-codemod) — a jscodeshift AST codemod that rewrites `dayjs(x).format(...)`/date-fns `format(...)` *call sites* across a codebase, not just format-string literals. A different job from the CLI's `translate` subcommand (see [CLI](#cli)), which only translates a format string you hand it and doesn't touch call sites; use this instead if you're migrating an entire codebase and want the calls themselves rewritten.
|
|
981
997
|
|
|
982
998
|
## Testing
|
|
983
999
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
DEFAULT_LOCALE
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-XIKLQMF7.js";
|
|
4
4
|
import {
|
|
5
5
|
differenceInDays
|
|
6
6
|
} from "./chunk-WZC43XGU.js";
|
|
@@ -54,4 +54,4 @@ export {
|
|
|
54
54
|
formatRelative,
|
|
55
55
|
formatRelativeToNow
|
|
56
56
|
};
|
|
57
|
-
//# sourceMappingURL=chunk-
|
|
57
|
+
//# sourceMappingURL=chunk-2R46FDWW.js.map
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// src/localeVocab.ts
|
|
2
2
|
var customVocabs = /* @__PURE__ */ new Map();
|
|
3
|
+
var MAX_CUSTOM_VOCABS = 500;
|
|
4
|
+
var MAX_LOCALE_TAG_LENGTH = 256;
|
|
5
|
+
var MAX_VOCAB_ENTRY_LENGTH = 256;
|
|
3
6
|
function assertValidVocab(vocab, locale) {
|
|
4
7
|
const required = [
|
|
5
8
|
{ key: "monthLong", length: 12, label: "long month names" },
|
|
@@ -31,6 +34,11 @@ function assertValidVocab(vocab, locale) {
|
|
|
31
34
|
`temporal-fmt: registerLocaleVocab for locale "${locale}": "${key}[${i}]" must be a non-empty string, got ${String(entry)}.`
|
|
32
35
|
);
|
|
33
36
|
}
|
|
37
|
+
if (entry.length > MAX_VOCAB_ENTRY_LENGTH) {
|
|
38
|
+
throw new RangeError(
|
|
39
|
+
`temporal-fmt: registerLocaleVocab for locale "${locale}": "${key}[${i}]" is too long (maximum ${MAX_VOCAB_ENTRY_LENGTH} characters).`
|
|
40
|
+
);
|
|
41
|
+
}
|
|
34
42
|
});
|
|
35
43
|
}
|
|
36
44
|
assertNoCollision(vocab.monthLong, "MMMM month", locale);
|
|
@@ -47,8 +55,14 @@ function registerLocaleVocab(locale, vocab) {
|
|
|
47
55
|
if (typeof locale !== "string" || locale.length === 0) {
|
|
48
56
|
throw new Error(`temporal-fmt: registerLocaleVocab requires a non-empty locale string, got ${String(locale)}.`);
|
|
49
57
|
}
|
|
58
|
+
if (locale.length > MAX_LOCALE_TAG_LENGTH) {
|
|
59
|
+
throw new RangeError(`temporal-fmt: registerLocaleVocab locale is too long (maximum ${MAX_LOCALE_TAG_LENGTH} characters).`);
|
|
60
|
+
}
|
|
50
61
|
assertValidVocab(vocab, locale);
|
|
51
62
|
const cacheKey = canonicalCacheKey(locale);
|
|
63
|
+
if (!customVocabs.has(cacheKey) && customVocabs.size >= MAX_CUSTOM_VOCABS) {
|
|
64
|
+
throw new RangeError(`temporal-fmt: registerLocaleVocab reached the ${MAX_CUSTOM_VOCABS}-locale limit.`);
|
|
65
|
+
}
|
|
52
66
|
customVocabs.set(cacheKey, {
|
|
53
67
|
monthLong: [...vocab.monthLong],
|
|
54
68
|
monthShort: [...vocab.monthShort],
|
|
@@ -161,4 +175,4 @@ export {
|
|
|
161
175
|
getCustomVocab,
|
|
162
176
|
getLocaleVocab
|
|
163
177
|
};
|
|
164
|
-
//# sourceMappingURL=chunk-
|
|
178
|
+
//# sourceMappingURL=chunk-3RLYULUQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/localeVocab.ts"],"sourcesContent":["// Name lists for the locale-aware tokens (MMMM, MMM, EEEE, EEE, a). Each\n// list is small and fixed (12 months, 7 weekdays, 2 day periods), so we\n// generate the real Intl strings for a locale once and cache them.\n\nexport interface LocaleVocab {\n monthLong: string[]; // index 0 = January\n monthShort: string[];\n weekdayLong: string[]; // index 0 = Monday, per Temporal's dayOfWeek numbering\n weekdayShort: string[];\n dayPeriod: string[]; // typically [AM-ish, PM-ish], deduped\n}\n\n// Custom vocabs registered by callers for locales Intl doesn't cover well\n// (e.g. a 13-month Hebrew leap year, where Intl's 12-month vocabulary\n// silently loses a whole month). Keyed by canonical cache key so the\n// same locale string spelling variants fold together — same convention\n// as the Intl-derived vocab cache above.\nconst customVocabs = new Map<string, LocaleVocab>();\nconst MAX_CUSTOM_VOCABS = 500;\nconst MAX_LOCALE_TAG_LENGTH = 256;\nconst MAX_VOCAB_ENTRY_LENGTH = 256;\n\nfunction assertValidVocab(vocab: Partial<LocaleVocab>, locale: string): void {\n // Strict shape validation at registration time, not lazily on first\n // use — the README's promise is that a malformed registration throws\n // descriptively here, rather than failing later inside format()/parse()\n // with a confusing \"no month part\" or wrong-month error the caller\n // can't trace back to the bad registration.\n const required: Array<{ key: keyof LocaleVocab; length: number; label: string }> = [\n { key: 'monthLong', length: 12, label: 'long month names' },\n { key: 'monthShort', length: 12, label: 'short month names' },\n { key: 'weekdayLong', length: 7, label: 'long weekday names' },\n { key: 'weekdayShort', length: 7, label: 'short weekday names' },\n { key: 'dayPeriod', length: 2, label: 'day period markers (AM/PM-equivalent)' },\n ];\n\n for (const { key, length, label } of required) {\n const value = vocab[key];\n if (value === undefined) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\" is missing required field \"${key}\" (${label}).`\n );\n }\n if (!Array.isArray(value)) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}\" must be an array, got ${typeof value}.`\n );\n }\n if (value.length !== length) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}\" must have exactly ${length} entries (got ${value.length}) — ${label}.`\n );\n }\n value.forEach((entry, i) => {\n if (typeof entry !== 'string' || entry.length === 0) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}[${i}]\" must be a non-empty string, got ${String(entry)}.`\n );\n }\n if (entry.length > MAX_VOCAB_ENTRY_LENGTH) {\n throw new RangeError(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": \"${key}[${i}]\" is too long (maximum ${MAX_VOCAB_ENTRY_LENGTH} characters).`\n );\n }\n });\n }\n\n // Reuse the same collision check the Intl-derived path uses — a\n // duplicate month name is just as ambiguous when supplied by a caller\n // as when produced by Intl.\n assertNoCollision(vocab.monthLong!, 'MMMM month', locale);\n assertNoCollision(vocab.monthShort!, 'MMM month', locale);\n assertNoCollision(vocab.weekdayLong!, 'EEEE weekday', locale);\n assertNoCollision(vocab.weekdayShort!, 'EEE weekday', locale);\n\n // dayPeriod entries must differ from each other, or parse()'s\n // isPM check (raw === vocab.dayPeriod[1]) can never return true and\n // every 12-hour parse silently resolves to AM. The Intl-derived path\n // dedupes a same-AM/PM collision to length 1, but a caller passing\n // both entries identical is a real bug to surface — not something to\n // dedupe around.\n if (vocab.dayPeriod![0] === vocab.dayPeriod![1]) {\n throw new Error(\n `temporal-fmt: registerLocaleVocab for locale \"${locale}\": dayPeriod entries must differ ` +\n `(both are \"${vocab.dayPeriod![0]}\"); otherwise parse() can't tell AM from PM.`\n );\n }\n}\n\n/**\n * Supply a custom month/weekday/day-period vocabulary for a locale key,\n * overriding the Intl-derived vocab this library would otherwise build\n * for that key. Useful for locales Intl doesn't cover well — the README's\n * known-limitations section calls out the Hebrew leap-month gap as a\n * specific case this addresses.\n *\n * Throws descriptively on malformed input (wrong array lengths, empty\n * strings, duplicate entries, missing fields) rather than failing later\n * during format/parse.\n *\n * Registered vocab takes precedence over the Intl-derived vocab for that\n * locale key, including for already-cached entries — registering\n * invalidates the prior cache entry for that locale so the next call\n * picks up the new vocab.\n *\n * @example\n * registerLocaleVocab('en-u-ca-hebrew-leap', {\n * monthLong: ['Nisan','Iyar','Sivan','Tammuz','Av','Elul','Tishrei','Marcheshvan','Kislev','Tevet','Shevat','Adar I','Adar II'],\n * monthShort: ['Nis','Iyy','Siv','Tam','Av','Elu','Tish','Chesh','Kis','Tev','Shv','Ad1','Ad2'],\n * weekdayLong: ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday'],\n * weekdayShort: ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'],\n * dayPeriod: ['AM','PM'],\n * });\n */\nexport function registerLocaleVocab(locale: string, vocab: Partial<LocaleVocab>): void {\n if (typeof locale !== 'string' || locale.length === 0) {\n throw new Error(`temporal-fmt: registerLocaleVocab requires a non-empty locale string, got ${String(locale)}.`);\n }\n if (locale.length > MAX_LOCALE_TAG_LENGTH) {\n throw new RangeError(`temporal-fmt: registerLocaleVocab locale is too long (maximum ${MAX_LOCALE_TAG_LENGTH} characters).`);\n }\n assertValidVocab(vocab, locale);\n\n const cacheKey = canonicalCacheKey(locale);\n if (!customVocabs.has(cacheKey) && customVocabs.size >= MAX_CUSTOM_VOCABS) {\n throw new RangeError(`temporal-fmt: registerLocaleVocab reached the ${MAX_CUSTOM_VOCABS}-locale limit.`);\n }\n customVocabs.set(cacheKey, {\n monthLong: [...vocab.monthLong!],\n monthShort: [...vocab.monthShort!],\n weekdayLong: [...vocab.weekdayLong!],\n weekdayShort: [...vocab.weekdayShort!],\n dayPeriod: [...vocab.dayPeriod!],\n });\n // Invalidate the Intl-derived cache entry so any prior format/parse\n // result cached for this locale is rebuilt against the new vocab. Not\n // strictly necessary (getLocaleVocab checks customVocabs first), but\n // cheap and keeps the two caches from drifting out of sync.\n vocabCache.delete(cacheKey);\n}\n\n// Every locale-keyed cache in this library (this one, formatterCache in\n// tokens.ts, patternCache/calendarCache in parse.ts) used to key on the\n// exact locale string a caller passed in. Intl treats spelling variants of\n// the same locale as equivalent ('en-US' / 'en-us' / 'en_US' all resolve\n// the same way), but a plain string-keyed Map doesn't — so callers mixing\n// spellings for what's really one locale would silently fragment across\n// separate cache entries instead of sharing one, making the bounded\n// eviction limits (MAX_*_CACHE_SIZE) less effective than they look. This\n// doesn't change any cache's *correctness* (each entry is still built from\n// -- and valid for -- whatever locale string produced it), only how many\n// distinct entries equivalent spellings end up costing. Falls back to the\n// original string on a malformed/unrecognized tag rather than throwing —\n// cache-key normalization shouldn't be where a bad locale first surfaces\n// as an error; whatever actually calls `new Intl.DateTimeFormat(locale)`\n// downstream is the right place for that.\nexport function canonicalCacheKey(locale: string): string {\n try {\n // Intl.Locale requires BCP-47 hyphens and rejects underscore-separated\n // tags like 'en_US' outright (RangeError), rather than normalizing\n // them — so without this replace, that spelling would just fall\n // through to the catch below and never fold with 'en-US'.\n return new Intl.Locale(locale.replace(/_/g, '-')).toString().toLowerCase();\n } catch {\n return locale;\n }\n}\n\nconst vocabCache = new Map<string, LocaleVocab>();\nconst MAX_VOCAB_CACHE_SIZE = 500;\n\n// Some locales (ja-JP) split a field across two parts — month \"8\" plus a\n// counter suffix \"月\" as a separate sibling \"literal\" — while format()'s\n// tokens go through toLocaleString(), which concatenates everything into\n// \"8月\". Reading only the type-tagged part used to drop that suffix, so\n// this locale's vocab never matched what format() actually produced.\n// Only merges *adjacent* literals, not the whole string, since the\n// dayPeriod/weekday formatters below carry an extra hour part that a\n// join-everything approach would wrongly absorb.\nfunction partValue(formatter: Intl.DateTimeFormat, date: Date, type: Intl.DateTimeFormatPartTypes): string {\n const parts = formatter.formatToParts(date);\n const index = parts.findIndex((p) => p.type === type);\n /* c8 ignore start @preserve -- defensive guard against a real but\n unreproducible failure mode: an Intl implementation that omits the\n requested part type entirely for some locale. Checked every locale\n with unusual dayPeriod/weekday/month rendering available in this\n runtime's ICU data (ja-JP, zh-CN, th-TH, he-IL, ar-SA, ko-KR, fa-IR)\n against the exact formatter options getLocaleVocab uses (notably\n hour12: true for the dayPeriod formatter, which is what makes every\n locale here actually emit a dayPeriod part — omitting it is what\n produced a false \"gap\" during investigation). None omit their part\n on this runtime. A different ICU version or a non-Node Intl\n implementation could plausibly behave differently, so this stays a\n real check rather than an assertion. */\n /* c8 ignore start @preserve */\n if (index === -1) {\n throw new Error(`temporal-fmt: locale produced no \"${type}\" part while building match vocabulary.`);\n }\n /* c8 ignore stop @preserve */\n let value = parts[index]!.value;\n const prev = parts[index - 1];\n const next = parts[index + 1];\n // skip whitespace literals (the separator before \"AM\") — only a\n // no-space suffix like ja-JP's \"月\" should get folded in\n if (prev?.type === 'literal' && !/\\s/.test(prev.value)) value = prev.value + value;\n if (next?.type === 'literal' && !/\\s/.test(next.value)) value = value + next.value;\n return value;\n}\n\n// Two entries rendering identically means parse()'s reverse lookup\n// (indexOf) can never tell them apart. Weekday collisions already surface\n// via parse()'s dayOfWeek cross-check, but with a confusing same-string\n// error; months have no equivalent cross-check, so a collision there would\n// otherwise resolve silently to the wrong month. Catching both here, once\n// at build time, gives one clear error instead.\nfunction assertNoCollision(names: string[], label: string, locale: string): void {\n const seen = new Map<string, number>();\n for (let i = 0; i < names.length; i++) {\n const prior = seen.get(names[i]!);\n if (prior !== undefined) {\n throw new Error(\n `temporal-fmt: locale \"${locale}\" renders ${label} index ${prior} and ${i} identically ` +\n `(\"${names[i]}\"). parse() can't reliably tell these apart for this locale/token, so this ` +\n `combination isn't supported.`\n );\n }\n seen.set(names[i]!, i);\n }\n}\n\n// Exposed for tokens.ts: when a custom vocab is registered for this\n// locale, format()'s locale-aware tokens (MMMM/MMM/EEEE/EEE/a) read\n// straight from the registered array instead of going through\n// Intl.DateTimeFormat. Without this override, format() would silently\n// keep producing Intl's strings while parse() matched against the\n// registered vocab — the two would round-trip-fail.\nexport function getCustomVocab(locale: string): LocaleVocab | undefined {\n const cacheKey = canonicalCacheKey(locale);\n return customVocabs.get(cacheKey);\n}\n\nexport function getLocaleVocab(locale: string): LocaleVocab {\n const cacheKey = canonicalCacheKey(locale);\n // Registered vocabs take precedence over the Intl-derived one — this\n // is the override mechanism registerLocaleVocab() promises. Checking\n // here, before the Intl cache lookup, means a registration that\n // happens *after* the first Intl-derived vocab was built still takes\n // effect on the next call.\n const custom = customVocabs.get(cacheKey);\n if (custom) {\n return custom;\n }\n const cached = vocabCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n const monthLongFmt = new Intl.DateTimeFormat(locale, { month: 'long', timeZone: 'UTC' });\n const monthShortFmt = new Intl.DateTimeFormat(locale, { month: 'short', timeZone: 'UTC' });\n const monthLong: string[] = [];\n const monthShort: string[] = [];\n for (let m = 0; m < 12; m++) {\n const date = new Date(Date.UTC(2020, m, 1));\n monthLong.push(partValue(monthLongFmt, date, 'month'));\n monthShort.push(partValue(monthShortFmt, date, 'month'));\n }\n assertNoCollision(monthLong, 'MMMM month', locale);\n assertNoCollision(monthShort, 'MMM month', locale);\n\n const weekdayLongFmt = new Intl.DateTimeFormat(locale, { weekday: 'long', timeZone: 'UTC' });\n const weekdayShortFmt = new Intl.DateTimeFormat(locale, { weekday: 'short', timeZone: 'UTC' });\n const weekdayLong: string[] = [];\n const weekdayShort: string[] = [];\n // 2024-01-01 is a Monday (UTC) — walk 7 days from there for weekday names\n for (let d = 0; d < 7; d++) {\n const date = new Date(Date.UTC(2024, 0, 1 + d));\n weekdayLong.push(partValue(weekdayLongFmt, date, 'weekday'));\n weekdayShort.push(partValue(weekdayShortFmt, date, 'weekday'));\n }\n // redundant with parse()'s dayOfWeek cross-check, but gives a clearer error\n assertNoCollision(weekdayLong, 'EEEE weekday', locale);\n assertNoCollision(weekdayShort, 'EEE weekday', locale);\n\n const dayPeriodFmt = new Intl.DateTimeFormat(locale, { hour: 'numeric', hour12: true, timeZone: 'UTC' });\n const am = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 1)), 'dayPeriod');\n const pm = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 13)), 'dayPeriod');\n const dayPeriod = [...new Set([am, pm])];\n\n const vocab: LocaleVocab = { monthLong, monthShort, weekdayLong, weekdayShort, dayPeriod };\n if (vocabCache.size >= MAX_VOCAB_CACHE_SIZE) {\n const oldestKey = vocabCache.keys().next().value;\n if (oldestKey !== undefined) vocabCache.delete(oldestKey);\n }\n vocabCache.set(cacheKey, vocab);\n return vocab;\n}"],"mappings":";AAiBA,IAAM,eAAe,oBAAI,IAAyB;AACl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K,eAAe,QAAQ,EAAE,MAAM,WAAW,QAAQ,MAAM,UAAU,MAAM,CAAC;AACvG,QAAM,KAAK,UAAU,cAAc,IAAI,KAAK,KAAK,IAAI,MAAM,GAAG,GAAG,CAAC,CAAC,GAAG,WAAW;AACjF,QAAM,KAAK,UAAU,cAAc,IAAI,KAAK,KAAK,IAAI,MAAM,GAAG,GAAG,EAAE,CAAC,GAAG,WAAW;AAClF,QAAM,YAAY,CAAC,GAAG,oBAAI,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC;AAEvC,QAAM,QAAqB,EAAE,WAAW,YAAY,aAAa,cAAc,UAAU;AACzF,MAAI,WAAW,QAAQ,sBAAsB;AAC3C,UAAM,YAAY,WAAW,KAAK,EAAE,KAAK,EAAE;AAC3C,QAAI,cAAc,OAAW,YAAW,OAAO,SAAS;AAAA,EAC1D;AACA,aAAW,IAAI,UAAU,KAAK;AAC9B,SAAO;AACT;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
TOKENS
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-XIKLQMF7.js";
|
|
4
4
|
import {
|
|
5
5
|
InvalidLocaleError
|
|
6
6
|
} from "./chunk-USONQ7MV.js";
|
|
@@ -159,4 +159,4 @@ export {
|
|
|
159
159
|
applyNumbering,
|
|
160
160
|
applyParseNumbering
|
|
161
161
|
};
|
|
162
|
-
//# sourceMappingURL=chunk-
|
|
162
|
+
//# sourceMappingURL=chunk-EA34SFOW.js.map
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
} from "./chunk-USONQ7MV.js";
|
|
8
8
|
import {
|
|
9
9
|
canonicalCacheKey
|
|
10
|
-
} from "./chunk-
|
|
10
|
+
} from "./chunk-3RLYULUQ.js";
|
|
11
11
|
import {
|
|
12
12
|
asDateFieldView
|
|
13
13
|
} from "./chunk-7LAIYTPE.js";
|
|
@@ -601,4 +601,4 @@ export {
|
|
|
601
601
|
addDuration,
|
|
602
602
|
subtractDuration
|
|
603
603
|
};
|
|
604
|
-
//# sourceMappingURL=chunk-
|
|
604
|
+
//# sourceMappingURL=chunk-EIJRFICK.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/rounding.ts","../src/formatDuration.ts","../src/duration.ts"],"sourcesContent":["// Rounding helpers (plan section N). Pure functions over field bags,\n// same convention as arithmetic.ts/calendarUtils.ts.\n\nimport { asDateFieldView, type DateFieldView } from './calendarUtils.js';\n\ntype RoundingUnit = 'day' | 'hour' | 'minute' | 'second' | 'millisecond';\ntype RoundingMode = 'nearest' | 'floor' | 'ceil' | 'trunc';\n\ninterface DateTimeFieldView extends DateFieldView {\n hour?: number;\n minute?: number;\n second?: number;\n millisecond?: number;\n}\n\n// Ms-per-unit table. Used by round() to convert a field bag to ms,\n// apply the rounding mode, and convert back. Mirrors how add() in\n// arithmetic.ts handles sub-day arithmetic.\nconst MS_PER_UNIT: Record<RoundingUnit, number> = {\n day: 86_400_000,\n hour: 3_600_000,\n minute: 60_000,\n second: 1_000,\n millisecond: 1,\n};\n\nfunction applyMode(ms: number, mode: RoundingMode, increment: number): number {\n // All four modes operate on absolute value then re-apply the sign,\n // so negative values round symmetrically (floor of -1.5 → -2, not -1).\n // Matches Math.round semantics for 'nearest' and Temporal's rounding\n // for the other three.\n const sign = ms < 0 ? -1 : 1;\n const abs = Math.abs(ms);\n const stepped = abs / increment;\n let rounded: number;\n switch (mode) {\n case 'nearest': rounded = Math.round(stepped); break;\n case 'floor': rounded = Math.floor(stepped); break;\n case 'ceil': rounded = Math.ceil(stepped); break;\n case 'trunc': rounded = Math.trunc(stepped); break;\n }\n return sign * rounded * increment;\n}\n\nfunction toMs(v: DateTimeFieldView): number {\n // Returns ms-since-(Howard Hinnant epoch). Used internally — the\n // absolute value is meaningful only relative to the same epoch used\n // by fromMs.\n const y = v.year!, m = v.month!, d = v.day!;\n const y2 = m <= 2 ? y - 1 : y;\n const era = Math.floor((y2 >= 0 ? y2 : y2 - 399) / 400);\n const yoe = y2 - era * 400;\n const m2 = m > 2 ? m - 3 : m + 9;\n const doy = Math.floor((153 * m2 + 2) / 5) + d - 1;\n const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;\n const days = era * 146097 + doe - 719468;\n return days * MS_PER_UNIT.day\n + (v.hour ?? 0) * MS_PER_UNIT.hour\n + (v.minute ?? 0) * MS_PER_UNIT.minute\n + (v.second ?? 0) * MS_PER_UNIT.second\n + (v.millisecond ?? 0);\n}\n\nfunction fromMs(ms: number, base: DateTimeFieldView): DateTimeFieldView {\n // Convert absolute ms (on the same epoch as toMs) back to a field bag.\n // Walks the Howard Hinnant days_from_civil inverse inline.\n const MS_PER_DAY = MS_PER_UNIT.day;\n const totalDays = Math.floor(ms / MS_PER_DAY);\n let withinDay = ms - totalDays * MS_PER_DAY; // ms since midnight\n // Defensive floating-point guard: given totalDays = Math.floor(ms /\n // MS_PER_DAY), withinDay = ms - totalDays * MS_PER_DAY is\n // mathematically guaranteed non-negative (that's what Math.floor\n // division gives you), verified against extreme values including\n // Number.MIN_SAFE_INTEGER and sub-ms fractional noise near day\n // boundaries. Kept in case a future change to how ms is computed\n // upstream breaks that guarantee.\n /* c8 ignore next */\n if (withinDay < 0) withinDay += MS_PER_DAY;\n const hour = Math.floor(withinDay / MS_PER_UNIT.hour);\n const minute = Math.floor((withinDay % MS_PER_UNIT.hour) / MS_PER_UNIT.minute);\n const second = Math.floor((withinDay % MS_PER_UNIT.minute) / MS_PER_UNIT.second);\n const millisecond = withinDay % MS_PER_UNIT.second;\n // Convert totalDays back to year/month/day via Howard Hinnant's\n // civil_from_days. Same algorithm as arithmetic.ts's shiftDays.\n const z = totalDays + 719468;\n const era = Math.floor((z >= 0 ? z : z - 146096) / 146097);\n const doe = z - era * 146097;\n const yoe = Math.floor((doe - Math.floor(doe / 1460) + Math.floor(doe / 36524) - Math.floor(doe / 146096)) / 365);\n const y2 = yoe + era * 400;\n const doy = doe - (365 * yoe + Math.floor(yoe / 4) - Math.floor(yoe / 100));\n const mp = Math.floor((5 * doy + 2) / 153);\n const d = doy - Math.floor((153 * mp + 2) / 5) + 1;\n const m = mp < 10 ? mp + 3 : mp - 9;\n const year = m <= 2 ? y2 + 1 : y2;\n return { ...base, year, month: m, day: d, hour, minute, second, millisecond };\n}\n\nfunction shiftDays(v: DateTimeFieldView, days: number): DateTimeFieldView {\n const y = v.year!, m = v.month!, d = v.day!;\n const y2 = m <= 2 ? y - 1 : y;\n const era = Math.floor((y2 >= 0 ? y2 : y2 - 399) / 400);\n const yoe = y2 - era * 400;\n const m2 = m > 2 ? m - 3 : m + 9;\n const doy = Math.floor((153 * m2 + 2) / 5) + d - 1;\n const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy;\n const totalDays = era * 146097 + doe - 719468 + days;\n const z = totalDays + 719468;\n const era2 = Math.floor((z >= 0 ? z : z - 146096) / 146097);\n const doe2 = z - era2 * 146097;\n const yoe2 = Math.floor((doe2 - Math.floor(doe2 / 1460) + Math.floor(doe2 / 36524) - Math.floor(doe2 / 146096)) / 365);\n const y2out = yoe2 + era2 * 400;\n const doy2 = doe2 - (365 * yoe2 + Math.floor(yoe2 / 4) - Math.floor(yoe2 / 100));\n const mp = Math.floor((5 * doy2 + 2) / 153);\n const d2 = doy2 - Math.floor((153 * mp + 2) / 5) + 1;\n const m2out = mp < 10 ? mp + 3 : mp - 9;\n const yOut = m2out <= 2 ? y2out + 1 : y2out;\n return { ...v, year: yOut, month: m2out, day: d2 };\n}\n\nexport interface RoundOptions {\n unit: RoundingUnit;\n mode?: RoundingMode;\n roundingIncrement?: number;\n}\n\nexport function round(value: unknown, options: RoundOptions): DateTimeFieldView {\n const base = asDateFieldView(value) as DateTimeFieldView;\n const mode = options.mode ?? 'nearest';\n const increment = (options.roundingIncrement ?? 1) * MS_PER_UNIT[options.unit];\n if (increment <= 0) {\n throw new Error(`temporal-fmt: round() requires a positive roundingIncrement (got ${options.roundingIncrement}).`);\n }\n const ms = toMs(base);\n const rounded = applyMode(ms, mode, increment);\n return fromMs(rounded, base);\n}\n\nexport function floor(value: unknown, unit: RoundingUnit, roundingIncrement: number = 1): DateTimeFieldView {\n return round(value, { unit, mode: 'floor', roundingIncrement });\n}\n\nexport function ceil(value: unknown, unit: RoundingUnit, roundingIncrement: number = 1): DateTimeFieldView {\n return round(value, { unit, mode: 'ceil', roundingIncrement });\n}\n\nexport function truncate(value: unknown, unit: RoundingUnit, roundingIncrement: number = 1): DateTimeFieldView {\n return round(value, { unit, mode: 'trunc', roundingIncrement });\n}\n\n// Duration rounding. Takes a duration field bag and rounds it to the\n// requested unit. Operates on the duration's own fields (years/months\n// for calendar-bound units, days/hours/minutes/seconds/ms/µs/ns for\n// absolute units). Mirrors Temporal.Duration.prototype.round's surface\n// — but operates on plain field bags rather than real Temporal.Duration\n// instances, same convention as the rest of this module set.\nexport interface DurationFields {\n years?: number;\n months?: number;\n weeks?: number;\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n microseconds?: number;\n nanoseconds?: number;\n}\n\ntype DurationUnit = 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' | 'microseconds' | 'nanoseconds';\n\nconst DURATION_UNIT_TO_NS: Record<DurationUnit, bigint> = {\n years: 0n, // calendar-bound, can't convert without relativeTo\n months: 0n, // same\n weeks: 0n, // same\n days: 86_400n * 1_000_000_000n,\n hours: 3_600n * 1_000_000_000n,\n minutes: 60n * 1_000_000_000n,\n seconds: 1_000_000_000n,\n milliseconds: 1_000_000n,\n microseconds: 1_000n,\n nanoseconds: 1n,\n};\n\n// Absolute units (days and below) can be rounded without a relativeTo\n// because their length is fixed in nanoseconds. Calendar-bound units\n// (years/months/weeks) can't — would need a Temporal.Duration round()\n// call with a relativeTo. This helper throws if the caller tries to\n// round to/from a calendar-bound unit, rather than silently producing\n// a wrong result.\nfunction isCalendarBound(unit: DurationUnit): boolean {\n return unit === 'years' || unit === 'months' || unit === 'weeks';\n}\n\nexport function roundDuration(duration: DurationFields, options: {\n unit: DurationUnit;\n mode?: RoundingMode;\n roundingIncrement?: number;\n}): DurationFields {\n const mode = options.mode ?? 'nearest';\n const increment = BigInt(options.roundingIncrement ?? 1);\n if (increment <= 0n) {\n throw new Error(`temporal-fmt: roundDuration() requires a positive roundingIncrement (got ${options.roundingIncrement}).`);\n }\n if (isCalendarBound(options.unit)) {\n throw new Error(\n `temporal-fmt: roundDuration() to \"${options.unit}\" requires a Temporal.Duration with a relativeTo — ` +\n `this helper operates on plain field bags without calendar context. Use Temporal.Duration.prototype.round() directly.`\n );\n }\n\n // Sum all absolute-unit contributions into total nanoseconds.\n let totalNs = 0n;\n for (const u of ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'] as DurationUnit[]) {\n const v = duration[u] ?? 0;\n totalNs += BigInt(v) * DURATION_UNIT_TO_NS[u];\n }\n\n // Apply rounding on the absolute value, preserving sign (same as round()).\n const stepNs = increment * DURATION_UNIT_TO_NS[options.unit];\n const sign = totalNs < 0n ? -1n : 1n;\n const abs = totalNs < 0n ? -totalNs : totalNs;\n const stepped = abs / stepNs;\n const remainder = abs % stepNs;\n let rounded: bigint;\n switch (mode) {\n case 'nearest':\n // Banker's rounding would be the Temporal spec, but Math.round-style\n // half-up is what callers typically expect from a \"round\" function.\n // Going with half-up to match round() above and avoid surprising anyone\n // who reads the output.\n rounded = remainder * 2n >= stepNs ? stepped + 1n : stepped;\n break;\n case 'floor': rounded = stepped; break;\n case 'ceil': rounded = remainder > 0n ? stepped + 1n : stepped; break;\n case 'trunc': rounded = stepped; break;\n }\n const newTotalNs = sign * rounded * stepNs;\n\n // Distribute back into the largest unit ≤ the requested unit. This\n // produces a balanced duration (e.g. rounding 90s to minutes gives\n // 1m30s in the minute field, not 90s).\n const result: DurationFields = { ...duration };\n let remaining = newTotalNs;\n // Clear all absolute units, then re-populate from largest to smallest.\n for (const u of ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'] as DurationUnit[]) {\n if (u === options.unit || isLargerUnit(u, options.unit) || u === options.unit) {\n // Keep calendar-bound units as-is; clear absolute units smaller\n // than the rounding target so the balanced output is clean.\n }\n result[u] = 0;\n }\n // Re-populate from the rounding unit downward (largest absolute unit\n // ≤ the target), so the result has all its value concentrated at the\n // target unit and below.\n const unitsInOrder: DurationUnit[] = ['days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'];\n const startIdx = unitsInOrder.indexOf(options.unit);\n // Include days in the distribution if days is below or equal to the target.\n // Otherwise leave days untouched (caller's days value stays).\n for (let i = 0; i <= startIdx; i++) {\n const u = unitsInOrder[i]!;\n const unitNs = DURATION_UNIT_TO_NS[u];\n // Dead by construction: unitsInOrder only lists days/hours/minutes/\n // seconds/milliseconds/microseconds/nanoseconds, none of which are\n // 0n in DURATION_UNIT_TO_NS (only years/months/weeks are, and those\n // never appear in this array). Kept in case unitsInOrder grows to\n // include a calendar-bound unit later.\n /* c8 ignore next */\n if (unitNs === 0n) continue;\n const count = remaining / unitNs;\n remaining -= count * unitNs;\n if (count !== 0n) {\n result[u] = Number(count);\n }\n }\n return result;\n}\n\nfunction isLargerUnit(_a: DurationUnit, _b: DurationUnit): boolean {\n // Helper kept for clarity above — currently unused because the\n // distribution loop handles ordering explicitly via unitsInOrder.\n return false;\n}","import { type FormatOptions } from './tokens.js';\nimport { tokenize } from './tokenize.js';\nimport { MAX_FORMAT_LENGTH } from './constants.js';\nimport { canonicalCacheKey } from './localeVocab.js';\n\n// A Temporal.Duration doesn't sit on a calendar — it has no year/month/day\n// position the way a PlainDate does — so the date/time token set in\n// tokens.ts doesn't apply. This is a separate token table for the same\n// reason parseRelative() lives in its own module: a different surface\n// deserves its own grammar, not a bolt-on to the existing one.\n//\n// Token design: each unit has three forms, in increasing verbosity.\n// `y` — numeric value, no unit text (\"2\")\n// `yy` — short unit suffix, plural-aware (\"2y\", or \"1y\" — see below)\n// `yyy` — full unit word, plural-aware (\"2 years\", \"1 year\")\n// Same for months (`o`/`oo`/`ooo` — `o` not `M` because the duration's\n// own field name in Temporal is \"months\" and the long-form output should\n// read \"month\"/\"months\", but the *token* letter is arbitrary; `o` is\n// chosen so it doesn't visually collide with `m` (minutes) or `M`\n// (months in date format) when a reader skims both tables side by side).\n//\n// Locale-aware rendering: when a `locale` is passed, the short/long\n// forms delegate to `Intl.NumberFormat` with `style: 'unit'`. That gives\n// us pluralization, native unit names, and the locale's preferred\n// spacing for free, matching the same \"delegate to Intl\" approach\n// `formatDistance` already uses. Without a `locale`, the original\n// English-only hardcoded table is used so existing default output stays\n// byte-identical — this is an additive locale option, not a rewrite of\n// the default rendering path.\n\ntype UnitKey = 'years' | 'months' | 'weeks' | 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds';\n\ninterface UnitForms {\n // singular and plural suffixes for the long form (e.g. \"year\", \"years\")\n longSingular: string;\n longPlural: string;\n // singular and plural suffixes for the short form (e.g. \"yr\", \"yrs\")\n shortSingular: string;\n shortPlural: string;\n // the property on Temporal.Duration to read for this unit\n field: UnitKey;\n // Intl.NumberFormat unit identifier (used only on the locale-aware path).\n // Confirmed against the current Intl spec — including `millisecond`, which\n // is in fact supported by every engine we target (Node 20+, modern ICU).\n // The task brief flagged this as a possible gap; empirically it isn't.\n intlUnit: string;\n}\n\nconst DURATION_UNITS: Record<string, UnitForms> = {\n y: { longSingular: 'year', longPlural: 'years', shortSingular: 'yr', shortPlural: 'yrs', field: 'years', intlUnit: 'year' },\n o: { longSingular: 'month', longPlural: 'months', shortSingular: 'mo', shortPlural: 'mos', field: 'months', intlUnit: 'month' },\n w: { longSingular: 'week', longPlural: 'weeks', shortSingular: 'wk', shortPlural: 'wks', field: 'weeks', intlUnit: 'week' },\n d: { longSingular: 'day', longPlural: 'days', shortSingular: 'd', shortPlural: 'd', field: 'days', intlUnit: 'day' },\n h: { longSingular: 'hour', longPlural: 'hours', shortSingular: 'h', shortPlural: 'h', field: 'hours', intlUnit: 'hour' },\n m: { longSingular: 'minute', longPlural: 'minutes', shortSingular: 'm', shortPlural: 'm', field: 'minutes', intlUnit: 'minute' },\n s: { longSingular: 'second', longPlural: 'seconds', shortSingular: 's', shortPlural: 's', field: 'seconds', intlUnit: 'second' },\n S: { longSingular: 'millisecond', longPlural: 'milliseconds', shortSingular: 'ms', shortPlural: 'ms', field: 'milliseconds', intlUnit: 'millisecond' },\n};\n\n// Token strings this module recognizes, longest-first for the greedy\n// tokenizer. tokenize() in tokenize.ts already does longest-first via\n// SORTED_TOKEN_STRINGS, but it operates on the *date/time* TOKENS table —\n// not this one. Rather than teach tokenize() about two tables, this\n// module uses its own equivalent scan over DURATION_UNITS keys.\nconst DURATION_TOKEN_STRINGS = Object.keys(DURATION_UNITS)\n .flatMap((single) => [single + single + single, single + single, single])\n .sort((a, b) => b.length - a.length);\n\ntype Piece =\n | { kind: 'token'; value: string; unit: string; form: 'numeric' | 'short' | 'long' }\n | { kind: 'literal'; value: string };\n\n// Same greedy-match shape as tokenize() in tokenize.ts, but with this\n// module's own token set. Quoted-literal handling is identical so the\n// same documented escaping rules carry over: 'at' is a literal, '' is a\n// literal quote.\nfunction tokenizeDuration(format: string): Piece[] {\n const pieces: Piece[] = [];\n let i = 0;\n while (i < format.length) {\n const ch = format[i];\n if (ch === \"'\") {\n if (format[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < format.length) {\n if (format[j] === \"'\") {\n if (format[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += format[j];\n j += 1;\n }\n if (!closed) {\n throw new Error(`temporal-fmt: unterminated quote in duration format string \"${format}\"`);\n }\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n const match = DURATION_TOKEN_STRINGS.find((tok) => format.startsWith(tok, i));\n if (match) {\n // single letter = numeric, double = short, triple = long\n const unit = match[0]!;\n const form = match.length === 1 ? 'numeric' : match.length === 2 ? 'short' : 'long';\n pieces.push({ kind: 'token', value: match, unit, form });\n i += match.length;\n continue;\n }\n appendLiteral(pieces, ch);\n i += 1;\n }\n return pieces;\n}\n\nfunction appendLiteral(pieces: Piece[], value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n}\n\n// Reads a unit value off the duration in a way that works for both real\n// Temporal.Duration objects and field bags ({ hours: 2, minutes: 30 }).\n// Temporal.Duration values are numbers, possibly negative for\n// backwards durations; a field bag the caller passes might leave fields\n// off entirely (undefined → treated as 0 for this unit).\nfunction readUnit(duration: Record<string, unknown>, field: UnitKey): number {\n const value = duration[field];\n if (value === undefined || value === null) return 0;\n if (typeof value === 'number' && Number.isFinite(value)) return value;\n // Temporal.Duration values are always numbers, but a hand-built field\n // bag could end up with a string here. Coerce; throw on garbage rather\n // than silently formatting NaN.\n const coerced = Number(value);\n if (!Number.isFinite(coerced)) {\n throw new Error(\n `temporal-fmt: duration field \"${field}\" is not a finite number (got ${String(value)}).`\n );\n }\n return coerced;\n}\n\n// Intl.NumberFormat is expensive to construct, and a typical duration\n// render walks 2-4 units — so a tight loop on the same (locale, unit,\n// display) triple would otherwise rebuild the formatter for every token\n// of every row. Cache by canonical-locale + unit + display, same\n// eviction shape as the other locale-keyed caches in this library\n// (formatterCache in tokens.ts, rtfCache in formatDistance.ts).\nconst unitFormatterCache = new Map<string, Intl.NumberFormat>();\nconst MAX_UNIT_FORMATTER_CACHE_SIZE = 200;\n\nfunction getUnitFormatter(locale: string, intlUnit: string, unitDisplay: 'short' | 'long'): Intl.NumberFormat {\n const key = `${canonicalCacheKey(locale)}|${intlUnit}|${unitDisplay}`;\n const cached = unitFormatterCache.get(key);\n if (cached) return cached;\n if (unitFormatterCache.size >= MAX_UNIT_FORMATTER_CACHE_SIZE) {\n const oldestKey = unitFormatterCache.keys().next().value;\n if (oldestKey !== undefined) unitFormatterCache.delete(oldestKey);\n }\n const formatter = new Intl.NumberFormat(locale, {\n style: 'unit',\n unit: intlUnit,\n unitDisplay,\n });\n unitFormatterCache.set(key, formatter);\n return formatter;\n}\n\nexport interface DurationFormatOptions extends FormatOptions {\n /**\n * When true, units whose value is zero are still emitted in the output\n * (e.g. \"0 hours, 30 minutes\" instead of \"30 minutes\"). Default is\n * false: zero-value units are omitted, matching how date-fns's\n * formatDuration works and how most callers rendering a duration to\n * a human would want it.\n */\n showZeroValues?: boolean;\n}\n\n/**\n * Format a Temporal.Duration (or a plain field bag { years, months, ...\n * }) using a duration-specific token string. Token grammar is documented\n * in the README under \"Duration formatting\" — it does NOT reuse the\n * date/time token table, since a duration has no calendar position.\n *\n * Zero-value units are omitted by default; pass { showZeroValues: true }\n * to force them to appear.\n *\n * Unit-name localization: without a `locale`, output is the original\n * English hardcoded singular/plural forms (byte-identical to previous\n * versions). With a `locale`, the short/long forms delegate to\n * `Intl.NumberFormat`'s `style: 'unit'` — same approach `formatDistance`\n * already uses for `Intl.RelativeTimeFormat`. Numeric-only tokens\n * (`y`, `o`, `w`, ...) are not affected by `locale`; they remain ASCII\n * digits, matching the rest of this library's \"numbers stay Western\"\n * convention.\n *\n * @example\n * formatDuration(Temporal.Duration.from({ years: 2, months: 1 }), 'yyy ooo')\n * // \"2 years 1 month\"\n * formatDuration({ hours: 2, minutes: 30 }, 'hhh mmm', { locale: 'fr-FR' })\n * // \"2 heures 30 minutes\"\n */\nexport function formatDuration(\n duration: Record<string, unknown>,\n formatStr: string,\n options: DurationFormatOptions = {},\n): string {\n if (formatStr.length > MAX_FORMAT_LENGTH) {\n throw new Error(\n `temporal-fmt: duration format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters ` +\n `(got ${formatStr.length}).`\n );\n }\n\n const showZeroes = options.showZeroValues === true;\n // Undefined locale → keep the original hardcoded English path so\n // existing default output is byte-identical. Any locale string passed\n // (including 'en-US') takes the Intl.NumberFormat path — so an\n // explicit `locale: 'en-US'` will produce Intl's spacing/word choices\n // rather than the hand-rolled English table. That's intentional: the\n // locale-aware path delegates to Intl, the default path doesn't.\n const locale = options.locale;\n const useIntl = locale !== undefined;\n\n const pieces = tokenizeDuration(formatStr);\n let result = '';\n\n for (const piece of pieces) {\n if (piece.kind === 'literal') {\n result += piece.value;\n continue;\n }\n\n const unit = DURATION_UNITS[piece.unit];\n // Dead by construction: piece.unit always comes from match[0] where\n // match is a member of DURATION_TOKEN_STRINGS, itself built\n // exhaustively from DURATION_UNITS' own keys — so this lookup can\n // never miss. Kept in case tokenizeDuration's token construction\n // ever diverges from DURATION_UNITS.\n /* c8 ignore start */\n if (!unit) {\n throw new Error(`temporal-fmt: unknown duration token \"${piece.value}\"`);\n }\n /* c8 ignore stop */\n\n const value = readUnit(duration, unit.field);\n if (value === 0 && !showZeroes) {\n // Omit zero-value units entirely. The token's contribution to the\n // output is empty — but this can leave a dangling separator literal\n // (e.g. \"2 hours, \" with nothing after). Callers who want clean\n // output should structure their format string to not put a\n // separator after a unit that might be zero, or use showZeroValues.\n continue;\n }\n\n if (piece.form === 'numeric') {\n result += String(value);\n continue;\n }\n\n if (useIntl) {\n // Intl.NumberFormat handles pluralization, native unit names, and\n // locale-appropriate spacing all in one call — no point replicating\n // that here. We pass the value as-is so negative durations\n // (`-1 hour`) round-trip the sign the way Intl expects.\n const unitDisplay = piece.form === 'short' ? 'short' : 'long';\n const formatter = getUnitFormatter(locale!, unit.intlUnit, unitDisplay);\n result += formatter.format(value);\n continue;\n }\n\n // Default-path English. Plural rule based on absolute value matches\n // what Intl does for unit style on en-US — only |value| === 1 is\n // singular, including for negatives like \"-1 hour\" (which is what\n // Intl produces for en-US too).\n if (piece.form === 'short') {\n result += value + (value === 1 || value === -1 ? unit.shortSingular : unit.shortPlural);\n } else {\n result += value + ' ' + (value === 1 || value === -1 ? unit.longSingular : unit.longPlural);\n }\n }\n\n return result;\n}","// Duration extensions (plan section I). The existing formatDuration()\n// in formatDuration.ts stays as-is; this module adds the rest of the\n// duration surface: parseDuration, parseISODuration, formatISODuration,\n// formatDurationToParts, balanceDuration, roundDuration (re-exported\n// from rounding.ts), totalDuration, compareDuration, addDuration,\n// subtractDuration.\n//\n// All operate on plain field bags ({ years, months, weeks, days, hours,\n// minutes, seconds, milliseconds, microseconds, nanoseconds }) rather\n// than Temporal.Duration instances — same convention as the rest of\n// this module set, so callers can use these without committing to a\n// Temporal implementation. addDuration/subtractDuration produce a new\n// field bag; totalDuration produces a number; compareDuration produces\n// -1/0/1.\n\nimport { roundDuration, type DurationFields } from './rounding.js';\nimport { getTemporal } from './temporalProvider.js';\nimport { formatDuration } from './formatDuration.js';\nimport { InvalidDurationError, FormatSyntaxError } from './errors.js';\n\n// Re-export roundDuration here so callers can import everything duration-\n// related from one place.\nexport { roundDuration };\nexport type { DurationFields };\n\n// Mirrors formatToParts in format.ts. Returns the same piece list\n// formatDuration() would consume, but split into parts instead of\n// joined. Useful for callers building custom UIs (one DOM node per\n// unit) or doing their own unit suppression logic.\n\nimport type { Piece } from './tokenize.js';\n\nexport interface DurationPart {\n type: 'literal' | 'token';\n value: string;\n token?: string;\n}\n\n// Delegates to formatDuration() by formatting once with each piece\n// in isolation, then splitting. Simpler than duplicating the\n// formatting logic — at the cost of running the formatter multiple\n// times. For typical durations (2-4 units) this is fine.\nexport function formatDurationToParts(\n duration: Record<string, unknown>,\n formatStr: string,\n options: Parameters<typeof formatDuration>[2] = {},\n): DurationPart[] {\n // Format the whole thing once to get the joined output, then walk\n // the formatStr's tokens and slice the output by each token's\n // rendered width. This works because formatDuration() emits each\n // token's value verbatim with literals in between — there's no\n // locale-dependent reordering.\n const full = formatDuration(duration, formatStr, options);\n // Re-tokenize the format string to know what tokens are present.\n // (formatDuration has its own tokenizer; we don't re-implement it\n // here. Instead, we scan the format string for token runs the same\n // way its tokenizer does.)\n const tokens = tokenizeDurationFormat(formatStr);\n const parts: DurationPart[] = [];\n let pos = 0;\n for (const tok of tokens) {\n if (tok.kind === 'literal') {\n // Find the literal text in `full` starting at `pos`. It should\n // be there verbatim.\n const lit = tok.value;\n if (full.slice(pos, pos + lit.length) === lit) {\n parts.push({ type: 'literal', value: lit });\n pos += lit.length;\n /* c8 ignore start @preserve -- unreachable given current formatDuration(): every\n literal is appended to `full` unconditionally regardless of adjacent\n zero-value tokens, and pos tracking never desyncs from the true\n literal position (verified via adversarial testing: duplicate\n literals, skipped tokens before/after, ambiguous text — all still\n found via indexOf as expected). Kept as a guard against a future\n formatDuration() change that conditionally drops literals. */\n } else {\n // Literal missing from output (e.g. zero-value unit was\n // skipped). Don't emit a part for it.\n }\n /* c8 ignore stop @preserve */\n } else {\n // Token: find the next non-literal chunk of `full` starting at\n // `pos`. Use the next literal piece (if any) as the bound.\n const nextLiteralStart = findNextLiteralStart(tokens, tok, full, pos);\n const value = full.slice(pos, nextLiteralStart);\n parts.push({ type: 'token', value, token: tok.value });\n pos = nextLiteralStart;\n }\n }\n return parts;\n}\n\n// Minimal tokenizer for the duration format string. Reuses the same\n// quoted-literal and greedy-match logic as tokenize.ts.\nfunction tokenizeDurationFormat(formatStr: string): Array<Piece & { unit?: string }> {\n const DURATION_TOKEN_STRINGS = ['y', 'o', 'w', 'd', 'h', 'm', 's', 'S']\n .flatMap((single) => [single + single + single, single + single, single])\n .sort((a, b) => b.length - a.length);\n const pieces: Array<Piece & { unit?: string }> = [];\n let i = 0;\n while (i < formatStr.length) {\n const ch = formatStr[i];\n if (ch === \"'\") {\n if (formatStr[i + 1] === \"'\") {\n appendLiteral(pieces, \"'\");\n i += 2;\n continue;\n }\n let j = i + 1;\n let literal = '';\n let closed = false;\n while (j < formatStr.length) {\n if (formatStr[j] === \"'\") {\n if (formatStr[j + 1] === \"'\") {\n literal += \"'\";\n j += 2;\n continue;\n }\n closed = true;\n j += 1;\n break;\n }\n literal += formatStr[j]!;\n j += 1;\n }\n if (!closed) throw new FormatSyntaxError({ format: formatStr, reason: 'unterminated quote' });\n appendLiteral(pieces, literal);\n i = j;\n continue;\n }\n const match = DURATION_TOKEN_STRINGS.find((tok) => formatStr.startsWith(tok, i));\n if (match) {\n pieces.push({ kind: 'token', value: match, unit: match[0] });\n i += match.length;\n continue;\n }\n appendLiteral(pieces, ch);\n i += 1;\n }\n return pieces;\n}\n\nfunction appendLiteral(pieces: Array<Piece & { unit?: string }>, value: string): void {\n const last = pieces[pieces.length - 1];\n if (last && last.kind === 'literal') {\n last.value += value;\n } else {\n pieces.push({ kind: 'literal', value });\n }\n}\n\nfunction findNextLiteralStart(\n tokens: Array<Piece & { unit?: string }>,\n _currentTok: Piece & { unit?: string },\n full: string,\n pos: number,\n): number {\n // Find the position in `full` where the next literal after the\n // current token starts. For now, just return the end of `full` —\n // formatDurationToParts is best-effort for the common case where\n // tokens are separated by literals, and degrades gracefully when\n // they aren't.\n // A more precise implementation would walk the tokens array from\n // the current position and use the next literal piece's text to\n // find the boundary in `full`. Doing it correctly requires handling\n // zero-value unit suppression, which is why this helper exists.\n // For now, we use the next literal piece's value as a search anchor.\n const idx = tokens.indexOf(_currentTok);\n for (let j = idx + 1; j < tokens.length; j++) {\n const t = tokens[j]!;\n if (t.kind === 'literal') {\n const found = full.indexOf(t.value, pos);\n if (found >= 0) return found;\n }\n }\n return full.length;\n}\n\n// ISO 8601 duration format: P[n]Y[n]M[n]W[n]DT[n]H[n]M[n]S\n// e.g. \"P3Y6M4DT12H30M5S\", \"PT1H30M\", \"P1W\", \"P0D\".\n// Parsed into a DurationFields bag.\nexport function parseISODuration(input: string): DurationFields {\n // Loose grammar: P [years Y] [months M] [weeks W] [days D] [T [hours H] [minutes M] [seconds S]]\n // Weeks is an ISO 8601-2 extension; widely supported.\n const re = /^P(?:(?:(\\d+(?:\\.\\d+)?)Y)?(?:(\\d+(?:\\.\\d+)?)M)?(?:(\\d+(?:\\.\\d+)?)W)?(?:(\\d+(?:\\.\\d+)?)D)?)?(?:T(?:(\\d+(?:\\.\\d+)?)H)?(?:(\\d+(?:\\.\\d+)?)M)?(?:(\\d+(?:\\.\\d+)?)S)?)?$/;\n const m = re.exec(input);\n if (!m) {\n throw new InvalidDurationError({ input, reason: 'does not match ISO 8601 duration grammar (P[n]Y[n]M[n]W[n]DT[n]H[n]M[n]S)' });\n }\n // All-zero / empty: P0D is valid ISO for zero duration.\n if (m.slice(1).every((g) => g === undefined)) {\n throw new InvalidDurationError({ input, reason: 'duration has no fields (use \"P0D\" for zero duration)' });\n }\n const toNum = (s: string | undefined): number => s === undefined ? 0 : Number(s);\n return {\n years: toNum(m[1]),\n months: toNum(m[2]),\n weeks: toNum(m[3]),\n days: toNum(m[4]),\n hours: toNum(m[5]),\n minutes: toNum(m[6]),\n seconds: toNum(m[7]),\n };\n}\n\nexport function formatISODuration(duration: DurationFields): string {\n const parts: string[] = ['P'];\n const years = duration.years ?? 0;\n const months = duration.months ?? 0;\n const weeks = duration.weeks ?? 0;\n const days = duration.days ?? 0;\n const hours = duration.hours ?? 0;\n const minutes = duration.minutes ?? 0;\n const seconds = duration.seconds ?? 0;\n if (years) parts.push(`${years}Y`);\n if (months) parts.push(`${months}M`);\n if (weeks) parts.push(`${weeks}W`);\n if (days) parts.push(`${days}D`);\n if (hours || minutes || seconds) {\n parts.push('T');\n if (hours) parts.push(`${hours}H`);\n if (minutes) parts.push(`${minutes}M`);\n if (seconds) parts.push(`${seconds}S`);\n }\n // parts is just ['P'] when every field is zero -- ISO has no empty\n // duration, so fall back to P0D.\n if (parts.length === 1) parts.push('0D');\n return parts.join('');\n}\n\n// Parses a duration-format string (the tokenized format formatDuration\n// accepts) into a DurationFields bag. Inverse of formatDuration().\nexport function parseDuration(input: string, formatStr: string, options: { locale?: string } = {}): DurationFields {\n // Build a capturing regex from the format string. Each token\n // captures a number; literals are matched literally.\n const tokens = tokenizeDurationFormat(formatStr);\n const fields: DurationFields = {};\n const groupSpecs: Array<{ unit: keyof DurationFields; form: 'numeric' | 'short' | 'long' }> = [];\n let regex = '';\n for (const tok of tokens) {\n if (tok.kind === 'literal') {\n regex += tok.value.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n } else {\n const unit = tok.unit!;\n const form = tok.value.length === 1 ? 'numeric' : tok.value.length === 2 ? 'short' : 'long';\n // Map token letter to DurationFields key.\n /* c8 ignore start @preserve -- the final `: null` branch, and the\n `if (key === null)` throw it feeds, are both unreachable: tok.unit\n is always one of the 8 letters in DURATION_TOKEN_STRINGS (the same\n source set this ternary checks against), so `null` can't be\n produced by any token the tokenizer emits. Kept as a guard against\n a future letter being added to one set without the other. */\n const key: keyof DurationFields | null = (\n unit === 'y' ? 'years'\n : unit === 'o' ? 'months'\n : unit === 'w' ? 'weeks'\n : unit === 'd' ? 'days'\n : unit === 'h' ? 'hours'\n : unit === 'm' ? 'minutes'\n : unit === 's' ? 'seconds'\n : unit === 'S' ? 'milliseconds'\n : null\n );\n if (key === null) {\n throw new FormatSyntaxError({ format: formatStr, token: tok.value, reason: 'unknown duration token' });\n }\n /* c8 ignore stop @preserve */\n // Numeric form: capture digits (and optional sign).\n // Short/long form: capture digits followed by optional unit text.\n // We'll handle unit-text stripping after the match.\n if (form === 'numeric') {\n regex += '(-?\\\\d+)';\n } else {\n // Short form like \"2y\" or \"2yrs\"; long form like \"2 years\" or \"2 year\".\n // Capture the number; unit text is matched but not captured.\n regex += '(\\\\d+)\\\\s*\\\\w*';\n }\n groupSpecs.push({ unit: key, form });\n }\n }\n const re = new RegExp(`^${regex}$`, 'u');\n const m = re.exec(input);\n if (!m) {\n throw new FormatSyntaxError({ input, format: formatStr, reason: 'does not match duration format' });\n }\n groupSpecs.forEach((spec, i) => {\n const raw = m[i + 1]!;\n const value = Number(raw);\n if (!Number.isFinite(value)) {\n throw new InvalidDurationError({ input, reason: `token for ${spec.unit} matched \"${raw}\" but isn't a finite number` });\n }\n fields[spec.unit] = value;\n });\n return fields;\n}\n\n// Balances a duration's absolute fields (days/hours/minutes/seconds/ms/µs/ns)\n// so each carries its natural range and excess carries into the next\n// larger unit. Doesn't touch calendar-bound fields (years/months/weeks)\n// since those need a relativeTo to balance correctly.\nexport function balanceDuration(duration: DurationFields): DurationFields {\n const NS_PER: Array<[keyof DurationFields, bigint]> = [\n ['days', 86_400n * 1_000_000_000n],\n ['hours', 3_600n * 1_000_000_000n],\n ['minutes', 60n * 1_000_000_000n],\n ['seconds', 1_000_000_000n],\n ['milliseconds', 1_000_000n],\n ['microseconds', 1_000n],\n ['nanoseconds', 1n],\n ];\n // Sum everything from days down to ns.\n let totalNs = 0n;\n for (const [k, nsPer] of NS_PER) {\n const v = duration[k];\n if (typeof v === 'number') totalNs += BigInt(v) * nsPer;\n }\n // Re-distribute.\n const result: DurationFields = { ...duration };\n let remaining = totalNs;\n for (const [k, nsPer] of NS_PER) {\n const count = remaining / nsPer;\n remaining -= count * nsPer;\n result[k] = Number(count);\n }\n return result;\n}\n\n// Sums all absolute fields into a single number expressed in the\n// requested unit. Throws for calendar-bound target units (years/months/\n// weeks) since those need a relativeTo.\nexport function totalDuration(duration: DurationFields, unit: 'days' | 'hours' | 'minutes' | 'seconds' | 'milliseconds' | 'microseconds' | 'nanoseconds'): number {\n const NS_PER: Record<string, bigint> = {\n days: 86_400n * 1_000_000_000n,\n hours: 3_600n * 1_000_000_000n,\n minutes: 60n * 1_000_000_000n,\n seconds: 1_000_000_000n,\n milliseconds: 1_000_000n,\n microseconds: 1_000n,\n nanoseconds: 1n,\n };\n let totalNs = 0n;\n for (const k of Object.keys(NS_PER) as Array<keyof typeof NS_PER>) {\n const v = duration[k as keyof DurationFields];\n if (typeof v === 'number') totalNs += BigInt(v) * NS_PER[k]!;\n }\n const divisor = NS_PER[unit];\n if (!divisor) {\n throw new InvalidDurationError({ reason: `totalDuration() does not support unit \"${unit}\" (calendar-bound units need a relativeTo)` });\n }\n return Number(totalNs) / Number(divisor);\n}\n\n// Compares two durations by their total absolute length. Returns -1/0/1.\nexport function compareDuration(a: DurationFields, b: DurationFields): number {\n const aNs = totalDurationNs(a);\n const bNs = totalDurationNs(b);\n if (aNs < bNs) return -1;\n if (aNs > bNs) return 1;\n return 0;\n}\n\nfunction totalDurationNs(d: DurationFields): bigint {\n const NS_PER: Record<string, bigint> = {\n days: 86_400n * 1_000_000_000n,\n hours: 3_600n * 1_000_000_000n,\n minutes: 60n * 1_000_000_000n,\n seconds: 1_000_000_000n,\n milliseconds: 1_000_000n,\n microseconds: 1_000n,\n nanoseconds: 1n,\n };\n let total = 0n;\n for (const k of Object.keys(NS_PER)) {\n const v = d[k as keyof DurationFields];\n if (typeof v === 'number') total += BigInt(v) * NS_PER[k]!;\n }\n return total;\n}\n\n// Adds two durations field-by-field. Doesn't balance — call\n// balanceDuration() afterwards if you want a balanced result.\nexport function addDuration(a: DurationFields, b: DurationFields): DurationFields {\n const keys: Array<keyof DurationFields> = ['years', 'months', 'weeks', 'days', 'hours', 'minutes', 'seconds', 'milliseconds', 'microseconds', 'nanoseconds'];\n const result: DurationFields = {};\n for (const k of keys) {\n result[k] = (a[k] ?? 0) + (b[k] ?? 0);\n }\n return result;\n}\n\nexport function subtractDuration(a: DurationFields, b: DurationFields): DurationFields {\n return addDuration(a, negateDuration(b));\n}\n\nfunction negateDuration(d: DurationFields): DurationFields {\n const result: DurationFields = {};\n for (const k of Object.keys(d) as Array<keyof DurationFields>) {\n result[k] = -(d[k] ?? 0);\n }\n return result;\n}\n\n// Suppress unused-import warning. getTemporal is used by fromUnix*\n// helpers in serialization.ts, not here — but keeping the import\n// around ensures this module is consistent with the rest of the\n// library's pattern of importing temporalProvider for any code path\n// that might construct a Temporal value.\nvoid getTemporal;\n"],"mappings":";;;;;;;;;;;;;;;AAkBA,IAAM,cAA4C;AAAA,EAChD,KAAK;AAAA,EACL,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,QAAQ;AAAA,EACR,aAAa;AACf;AAEA,SAAS,UAAU,IAAY,MAAoB,WAA2B;AAK5E,QAAM,OAAO,KAAK,IAAI,KAAK;AAC3B,QAAM,MAAM,KAAK,IAAI,EAAE;AACvB,QAAM,UAAU,MA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,gBAAgB,gBAAgB,aAAa;AAC3J,QAAM,SAAyB,CAAC;AAChC,aAAW,KAAK,MAAM;AACpB,WAAO,CAAC,KAAK,EAAE,CAAC,KAAK,MAAM,EAAE,CAAC,KAAK;AAAA,EACrC;AACA,SAAO;AACT;AAEO,SAAS,iBAAiB,GAAmB,GAAmC;AACrF,SAAO,YAAY,GAAG,eAAe,CAAC,CAAC;AACzC;AAEA,SAAS,eAAe,GAAmC;AACzD,QAAM,SAAyB,CAAC;AAChC,aAAW,KAAK,OAAO,KAAK,CAAC,GAAkC;AAC7D,WAAO,CAAC,IAAI,EAAE,EAAE,CAAC,KAAK;AAAA,EACxB;AACA,SAAO;AACT;","names":["DURATION_TOKEN_STRINGS","appendLiteral"]}
|
|
@@ -10,7 +10,7 @@ function recurrence(start, rule) {
|
|
|
10
10
|
let current = start;
|
|
11
11
|
let count = 0;
|
|
12
12
|
const history = [];
|
|
13
|
-
const
|
|
13
|
+
const MAX_HISTORY = 1e4;
|
|
14
14
|
let atEnd = false;
|
|
15
15
|
let atStart = true;
|
|
16
16
|
function matches(value) {
|
|
@@ -31,6 +31,10 @@ function recurrence(start, rule) {
|
|
|
31
31
|
const unit = rule.frequency === "secondly" ? "seconds" : rule.frequency === "minutely" ? "minutes" : rule.frequency === "hourly" ? "hours" : rule.frequency === "daily" ? "days" : rule.frequency === "weekly" ? "weeks" : rule.frequency === "monthly" ? "months" : "years";
|
|
32
32
|
return add(value, steps * rule.interval, unit);
|
|
33
33
|
}
|
|
34
|
+
function recordHistory(value) {
|
|
35
|
+
history.push(value);
|
|
36
|
+
if (history.length > MAX_HISTORY) history.shift();
|
|
37
|
+
}
|
|
34
38
|
function nextMatch(value) {
|
|
35
39
|
let candidate = value;
|
|
36
40
|
let safetyCounter = 0;
|
|
@@ -60,7 +64,7 @@ function recurrence(start, rule) {
|
|
|
60
64
|
atEnd = true;
|
|
61
65
|
return { value: void 0, done: true };
|
|
62
66
|
}
|
|
63
|
-
|
|
67
|
+
recordHistory(current);
|
|
64
68
|
return { value: current, done: false };
|
|
65
69
|
}
|
|
66
70
|
const advanced2 = nextMatch(current);
|
|
@@ -68,7 +72,7 @@ function recurrence(start, rule) {
|
|
|
68
72
|
current = advanced2.value;
|
|
69
73
|
count++;
|
|
70
74
|
if (rule.count !== void 0 && count >= rule.count) atEnd = true;
|
|
71
|
-
|
|
75
|
+
recordHistory(current);
|
|
72
76
|
return { value: current, done: false };
|
|
73
77
|
}
|
|
74
78
|
const advanced = nextMatch(current);
|
|
@@ -76,13 +80,12 @@ function recurrence(start, rule) {
|
|
|
76
80
|
current = advanced.value;
|
|
77
81
|
count++;
|
|
78
82
|
if (rule.count !== void 0 && count >= rule.count) atEnd = true;
|
|
79
|
-
|
|
83
|
+
recordHistory(current);
|
|
80
84
|
return { value: current, done: false };
|
|
81
85
|
},
|
|
82
86
|
previous() {
|
|
83
87
|
if (history.length === 0) return { value: void 0, done: true };
|
|
84
88
|
const v = history.pop();
|
|
85
|
-
future.push(v);
|
|
86
89
|
return { value: v, done: false };
|
|
87
90
|
}
|
|
88
91
|
};
|
|
@@ -117,6 +120,15 @@ function between(start, rule, rangeStart, rangeEnd) {
|
|
|
117
120
|
function parseRRule(input) {
|
|
118
121
|
const parts = input.trim().toUpperCase().replace(/^RRULE:/, "").split(";");
|
|
119
122
|
const rule = { frequency: "daily", interval: 1 };
|
|
123
|
+
const frequencies = /* @__PURE__ */ new Set([
|
|
124
|
+
"SECONDLY",
|
|
125
|
+
"MINUTELY",
|
|
126
|
+
"HOURLY",
|
|
127
|
+
"DAILY",
|
|
128
|
+
"WEEKLY",
|
|
129
|
+
"MONTHLY",
|
|
130
|
+
"YEARLY"
|
|
131
|
+
]);
|
|
120
132
|
for (const part of parts) {
|
|
121
133
|
if (!part) continue;
|
|
122
134
|
const eq = part.indexOf("=");
|
|
@@ -125,14 +137,27 @@ function parseRRule(input) {
|
|
|
125
137
|
const value = part.slice(eq + 1);
|
|
126
138
|
switch (key) {
|
|
127
139
|
case "FREQ":
|
|
140
|
+
if (!frequencies.has(value)) {
|
|
141
|
+
throw new RangeError(`temporal-fmt: unsupported RRULE frequency "${value}".`);
|
|
142
|
+
}
|
|
128
143
|
rule.frequency = value.toLowerCase();
|
|
129
144
|
break;
|
|
130
|
-
case "INTERVAL":
|
|
131
|
-
|
|
145
|
+
case "INTERVAL": {
|
|
146
|
+
const interval = Number(value);
|
|
147
|
+
if (!Number.isSafeInteger(interval) || interval < 1) {
|
|
148
|
+
throw new RangeError(`temporal-fmt: RRULE INTERVAL must be a positive safe integer (got "${value}").`);
|
|
149
|
+
}
|
|
150
|
+
rule.interval = interval;
|
|
132
151
|
break;
|
|
133
|
-
|
|
134
|
-
|
|
152
|
+
}
|
|
153
|
+
case "COUNT": {
|
|
154
|
+
const count = Number(value);
|
|
155
|
+
if (!Number.isSafeInteger(count) || count < 1) {
|
|
156
|
+
throw new RangeError(`temporal-fmt: RRULE COUNT must be a positive safe integer (got "${value}").`);
|
|
157
|
+
}
|
|
158
|
+
rule.count = count;
|
|
135
159
|
break;
|
|
160
|
+
}
|
|
136
161
|
case "UNTIL":
|
|
137
162
|
rule.until = value;
|
|
138
163
|
break;
|
|
@@ -145,12 +170,22 @@ function parseRRule(input) {
|
|
|
145
170
|
return map[wd] ?? 0;
|
|
146
171
|
});
|
|
147
172
|
break;
|
|
148
|
-
case "BYMONTHDAY":
|
|
149
|
-
|
|
173
|
+
case "BYMONTHDAY": {
|
|
174
|
+
const values = value.split(",").map(Number);
|
|
175
|
+
if (values.some((day) => !Number.isInteger(day) || day === 0 || day < -31 || day > 31)) {
|
|
176
|
+
throw new RangeError(`temporal-fmt: RRULE BYMONTHDAY contains an out-of-range value.`);
|
|
177
|
+
}
|
|
178
|
+
rule.byMonthDay = values;
|
|
150
179
|
break;
|
|
151
|
-
|
|
152
|
-
|
|
180
|
+
}
|
|
181
|
+
case "BYMONTH": {
|
|
182
|
+
const values = value.split(",").map(Number);
|
|
183
|
+
if (values.some((month) => !Number.isInteger(month) || month < 1 || month > 12)) {
|
|
184
|
+
throw new RangeError(`temporal-fmt: RRULE BYMONTH contains an out-of-range value.`);
|
|
185
|
+
}
|
|
186
|
+
rule.byMonth = values;
|
|
153
187
|
break;
|
|
188
|
+
}
|
|
154
189
|
}
|
|
155
190
|
}
|
|
156
191
|
return rule;
|
|
@@ -177,4 +212,4 @@ export {
|
|
|
177
212
|
parseRRule,
|
|
178
213
|
formatRRule
|
|
179
214
|
};
|
|
180
|
-
//# sourceMappingURL=chunk-
|
|
215
|
+
//# sourceMappingURL=chunk-G7ADZLSD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/recurrence.ts"],"sourcesContent":["// Recurrence engine (plan section T). Deterministic RRULE-like\n// recurrence without pulling in a runtime dependency. Supports\n// secondly/minutely/hourly/daily/weekly/monthly/yearly frequencies,\n// interval, count, until, weekdays, monthDays, positional rules,\n// exclusions, inclusions.\n//\n// RRULE interop: parseRRule() / formatRRule() convert to/from the\n// standard iCalendar RRULE string format (RFC 5545). Implemented\n// without depending on a RRULE library — the grammar is small enough\n// to handle inline.\n\nimport { add } from './arithmetic.js';\nimport { compare } from './comparison.js';\n\nexport type RecurrenceFrequency = 'secondly' | 'minutely' | 'hourly' | 'daily' | 'weekly' | 'monthly' | 'yearly';\n\nexport interface RecurrenceRule {\n frequency: RecurrenceFrequency;\n interval: number; // default 1\n count?: number; // max occurrences\n until?: unknown; // Temporal value — recurrence ends before this\n // For weekly: ISO weekdays to include (1=Mon..7=Sun). Empty = all.\n byWeekday?: number[];\n // For monthly/yearly: days of month to include (1-31, or negative\n // for end-of-month: -1 = last day).\n byMonthDay?: number[];\n // For yearly: months to include (1-12).\n byMonth?: number[];\n // For weekly: which week of the year (1-53).\n byWeek?: number[];\n // Exclusions: dates to skip even if they match the rule.\n exDates?: unknown[];\n // Inclusions: dates to add even if they don't match the rule.\n rDates?: unknown[];\n}\n\nexport interface RecurrenceIterator {\n next(): { value: unknown; done: boolean } | { value: undefined; done: true };\n previous(): { value: unknown; done: boolean } | { value: undefined; done: true };\n}\n\n// Creates a recurrence iterator starting from `start`. The first call\n// to next() returns `start` itself (if it matches the rule); subsequent\n// calls return the next matching occurrence.\nexport function recurrence(start: unknown, rule: RecurrenceRule): RecurrenceIterator {\n let current: unknown = start;\n let count = 0;\n // Track past values for previous() — keeps a ring buffer of the last\n // N occurrences so previous() can walk back without recomputing.\n const history: unknown[] = [];\n const MAX_HISTORY = 10_000;\n let atEnd = false;\n let atStart = true;\n\n function matches(value: unknown): boolean {\n const v = value as { dayOfWeek?: number; day?: number; month?: number; year?: number; hour?: number; minute?: number; second?: number };\n if (rule.byWeekday && rule.byWeekday.length > 0) {\n if (!rule.byWeekday.includes(v.dayOfWeek ?? 0)) return false;\n }\n if (rule.byMonthDay && rule.byMonthDay.length > 0) {\n if (!rule.byMonthDay.includes(v.day ?? 0)) return false;\n }\n if (rule.byMonth && rule.byMonth.length > 0) {\n if (!rule.byMonth.includes(v.month ?? 0)) return false;\n }\n if (rule.exDates && rule.exDates.some((d) => compare(d, value) === 0)) return false;\n return true;\n }\n\n function advance(value: unknown, steps: number): unknown {\n // Add `steps` * interval units to `value`.\n const unit = rule.frequency === 'secondly' ? 'seconds'\n : rule.frequency === 'minutely' ? 'minutes'\n : rule.frequency === 'hourly' ? 'hours'\n : rule.frequency === 'daily' ? 'days'\n : rule.frequency === 'weekly' ? 'weeks'\n : rule.frequency === 'monthly' ? 'months'\n : 'years';\n return add(value, steps * rule.interval, unit as Parameters<typeof add>[2]);\n }\n\n function recordHistory(value: unknown): void {\n history.push(value);\n if (history.length > MAX_HISTORY) history.shift();\n }\n\n function nextMatch(value: unknown): { value: unknown; found: boolean } {\n // Advance one step at a time until we find a match. For\n // byWeekday/byMonthDay rules this can skip multiple steps.\n let candidate = value;\n let safetyCounter = 0;\n do {\n candidate = advance(candidate, 1);\n safetyCounter++;\n if (safetyCounter > 1000) {\n // Defensive — if the rule is so restrictive no match exists\n // within 1000 steps, give up rather than spin forever. The\n // caller must treat this as \"no more occurrences\", not as a\n // real match — returning the unmatched candidate here used to\n // get handed back to next()'s caller as if it were valid.\n atEnd = true;\n return { value: candidate, found: false };\n }\n if (rule.until && compare(candidate, rule.until) > 0) {\n atEnd = true;\n return { value: candidate, found: false };\n }\n } while (!matches(candidate));\n return { value: candidate, found: true };\n }\n\n return {\n next() {\n if (atEnd) return { value: undefined, done: true };\n if (atStart) {\n atStart = false;\n if (matches(current)) {\n count++;\n if (rule.count !== undefined && count >= rule.count) atEnd = true;\n if (rule.until && compare(current, rule.until) > 0) {\n atEnd = true;\n return { value: undefined, done: true };\n }\n // Include rDates that match the current value.\n recordHistory(current);\n return { value: current, done: false };\n }\n // If start doesn't match, advance to first match.\n const advanced = nextMatch(current);\n if (!advanced.found) return { value: undefined, done: true };\n current = advanced.value;\n count++;\n if (rule.count !== undefined && count >= rule.count) atEnd = true;\n recordHistory(current);\n return { value: current, done: false };\n }\n const advanced = nextMatch(current);\n if (!advanced.found) return { value: undefined, done: true };\n current = advanced.value;\n count++;\n if (rule.count !== undefined && count >= rule.count) atEnd = true;\n recordHistory(current);\n return { value: current, done: false };\n },\n previous() {\n if (history.length === 0) return { value: undefined, done: true };\n const v = history.pop()!;\n return { value: v, done: false };\n },\n };\n}\n\n// Take N occurrences from a recurrence iterator.\nexport function take(iter: RecurrenceIterator, n: number): unknown[] {\n const result: unknown[] = [];\n for (let i = 0; i < n; i++) {\n const r = iter.next();\n if (r.done) break;\n result.push(r.value);\n }\n return result;\n}\n\n// Skip N occurrences from a recurrence iterator.\nexport function skip(iter: RecurrenceIterator, n: number): unknown[] {\n for (let i = 0; i < n; i++) {\n const r = iter.next();\n if (r.done) break;\n }\n return take(iter, Number.MAX_SAFE_INTEGER);\n}\n\n// All occurrences between two dates (inclusive of start, exclusive of end).\nexport function between(start: unknown, rule: RecurrenceRule, rangeStart: unknown, rangeEnd: unknown): unknown[] {\n const iter = recurrence(start, rule);\n const result: unknown[] = [];\n while (true) {\n const r = iter.next();\n if (r.done) break;\n if (compare(r.value, rangeEnd) >= 0) break;\n if (compare(r.value, rangeStart) >= 0) result.push(r.value);\n }\n return result;\n}\n\n// Parses an RRULE string like \"FREQ=DAILY;INTERVAL=2;COUNT=5\" into a\n// RecurrenceRule. Doesn't support every RRULE feature (BYSETPOS,\n// BYHOUR, BYMINUTE, BYSECOND are parsed but not enforced by the\n// recurrence iterator above), but covers the common cases.\nexport function parseRRule(input: string): RecurrenceRule {\n const parts = input.trim().toUpperCase().replace(/^RRULE:/, '').split(';');\n const rule: RecurrenceRule = { frequency: 'daily', interval: 1 };\n const frequencies: ReadonlySet<string> = new Set([\n 'SECONDLY', 'MINUTELY', 'HOURLY', 'DAILY', 'WEEKLY', 'MONTHLY', 'YEARLY',\n ]);\n for (const part of parts) {\n if (!part) continue;\n const eq = part.indexOf('=');\n if (eq < 0) continue;\n const key = part.slice(0, eq);\n const value = part.slice(eq + 1);\n switch (key) {\n case 'FREQ':\n if (!frequencies.has(value)) {\n throw new RangeError(`temporal-fmt: unsupported RRULE frequency \"${value}\".`);\n }\n rule.frequency = value.toLowerCase() as RecurrenceFrequency;\n break;\n case 'INTERVAL': {\n const interval = Number(value);\n if (!Number.isSafeInteger(interval) || interval < 1) {\n throw new RangeError(`temporal-fmt: RRULE INTERVAL must be a positive safe integer (got \"${value}\").`);\n }\n rule.interval = interval;\n break;\n }\n case 'COUNT': {\n const count = Number(value);\n if (!Number.isSafeInteger(count) || count < 1) {\n throw new RangeError(`temporal-fmt: RRULE COUNT must be a positive safe integer (got \"${value}\").`);\n }\n rule.count = count;\n break;\n }\n case 'UNTIL':\n rule.until = value;\n break;\n case 'BYDAY':\n rule.byWeekday = value.split(',').map((d) => {\n const m = d.match(/^([+-]?\\d)?([A-Z]{2})$/);\n if (!m) return 0;\n const wd = m[2];\n const map: Record<string, number> = { MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6, SU: 7 };\n return map[wd!] ?? 0;\n });\n break;\n case 'BYMONTHDAY': {\n const values = value.split(',').map(Number);\n if (values.some((day) => !Number.isInteger(day) || day === 0 || day < -31 || day > 31)) {\n throw new RangeError(`temporal-fmt: RRULE BYMONTHDAY contains an out-of-range value.`);\n }\n rule.byMonthDay = values;\n break;\n }\n case 'BYMONTH': {\n const values = value.split(',').map(Number);\n if (values.some((month) => !Number.isInteger(month) || month < 1 || month > 12)) {\n throw new RangeError(`temporal-fmt: RRULE BYMONTH contains an out-of-range value.`);\n }\n rule.byMonth = values;\n break;\n }\n }\n }\n return rule;\n}\n\nexport function formatRRule(rule: RecurrenceRule): string {\n const parts: string[] = [`FREQ=${rule.frequency.toUpperCase()}`];\n if (rule.interval !== 1) parts.push(`INTERVAL=${rule.interval}`);\n if (rule.count !== undefined) parts.push(`COUNT=${rule.count}`);\n if (rule.until !== undefined) parts.push(`UNTIL=${String(rule.until)}`);\n if (rule.byWeekday && rule.byWeekday.length > 0) {\n const map: Record<number, string> = { 1: 'MO', 2: 'TU', 3: 'WE', 4: 'TH', 5: 'FR', 6: 'SA', 7: 'SU' };\n parts.push(`BYDAY=${rule.byWeekday.map((d) => map[d]).join(',')}`);\n }\n if (rule.byMonthDay && rule.byMonthDay.length > 0) parts.push(`BYMONTHDAY=${rule.byMonthDay.join(',')}`);\n if (rule.byMonth && rule.byMonth.length > 0) parts.push(`BYMONTH=${rule.byMonth.join(',')}`);\n return parts.join(';');\n}"],"mappings":";;;;;;;;AA4CO,SAAS,WAAW,OAAgB,MAA0C;AACnF,MAAI,UAAmB;AACvB,MAAI,QAAQ;AAGZ,QAAM,UAAqB,CAAC;AAC5B,QAAM,cAAc;AACpB,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,WAAS,QAAQ,OAAyB;AACxC,UAAM,IAAI;AACV,QAAI,KAAK,aAAa,KAAK,UAAU,SAAS,GAAG;AAC/C,UAAI,CAAC,KAAK,UAAU,SAAS,EAAE,aAAa,CAAC,EAAG,QAAO;AAAA,IACzD;AACA,QAAI,KAAK,cAAc,KAAK,WAAW,SAA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AU;AACf;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,YAAY,MAA8B;AACxD,QAAM,QAAkB,CAAC,QAAQ,KAAK,UAAU,YAAY,CAAC,EAAE;AAC/D,MAAI,KAAK,aAAa,EAAG,OAAM,KAAK,YAAY,KAAK,QAAQ,EAAE;AAC/D,MAAI,KAAK,UAAU,OAAW,OAAM,KAAK,SAAS,KAAK,KAAK,EAAE;AAC9D,MAAI,KAAK,UAAU,OAAW,OAAM,KAAK,SAAS,OAAO,KAAK,KAAK,CAAC,EAAE;AACtE,MAAI,KAAK,aAAa,KAAK,UAAU,SAAS,GAAG;AAC/C,UAAM,MAA8B,EAAE,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,KAAK;AACpG,UAAM,KAAK,SAAS,KAAK,UAAU,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,EAAE;AAAA,EACnE;AACA,MAAI,KAAK,cAAc,KAAK,WAAW,SAAS,EAAG,OAAM,KAAK,cAAc,KAAK,WAAW,KAAK,GAAG,CAAC,EAAE;AACvG,MAAI,KAAK,WAAW,KAAK,QAAQ,SAAS,EAAG,OAAM,KAAK,WAAW,KAAK,QAAQ,KAAK,GAAG,CAAC,EAAE;AAC3F,SAAO,MAAM,KAAK,GAAG;AACvB;","names":["advanced"]}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import {
|
|
2
2
|
applyParseNumbering,
|
|
3
3
|
tokenize
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-EA34SFOW.js";
|
|
5
5
|
import {
|
|
6
6
|
DEFAULT_LOCALE
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-XIKLQMF7.js";
|
|
8
8
|
import {
|
|
9
9
|
MAX_FORMAT_LENGTH,
|
|
10
10
|
MAX_INPUT_LENGTH
|
|
@@ -20,7 +20,7 @@ import {
|
|
|
20
20
|
import {
|
|
21
21
|
canonicalCacheKey,
|
|
22
22
|
getLocaleVocab
|
|
23
|
-
} from "./chunk-
|
|
23
|
+
} from "./chunk-3RLYULUQ.js";
|
|
24
24
|
|
|
25
25
|
// src/pattern.ts
|
|
26
26
|
function escapeRegExp(literal) {
|
|
@@ -824,4 +824,4 @@ export {
|
|
|
824
824
|
parseToParts,
|
|
825
825
|
compileParser
|
|
826
826
|
};
|
|
827
|
-
//# sourceMappingURL=chunk-
|
|
827
|
+
//# sourceMappingURL=chunk-PVJXJPHQ.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
format,
|
|
3
3
|
formatToParts
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-X64UUZ7M.js";
|
|
5
5
|
import {
|
|
6
6
|
compare
|
|
7
7
|
} from "./chunk-OGVBMURH.js";
|
|
@@ -193,4 +193,4 @@ export {
|
|
|
193
193
|
formatRange,
|
|
194
194
|
formatRangeToParts
|
|
195
195
|
};
|
|
196
|
-
//# sourceMappingURL=chunk-
|
|
196
|
+
//# sourceMappingURL=chunk-WVMHS4OX.js.map
|