@vielzeug/tempo 1.0.6 → 2.0.0
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 +18 -43
- package/dist/_convert.cjs +1 -1
- package/dist/_convert.cjs.map +1 -1
- package/dist/_convert.d.ts +9 -43
- package/dist/_convert.d.ts.map +1 -1
- package/dist/_convert.js +12 -10
- package/dist/_convert.js.map +1 -1
- package/dist/_floor.cjs +1 -1
- package/dist/_floor.cjs.map +1 -1
- package/dist/_floor.d.ts +3 -7
- package/dist/_floor.d.ts.map +1 -1
- package/dist/_floor.js +1 -4
- package/dist/_floor.js.map +1 -1
- package/dist/_tz.cjs +1 -1
- package/dist/_tz.cjs.map +1 -1
- package/dist/_tz.d.ts +4 -11
- package/dist/_tz.d.ts.map +1 -1
- package/dist/_tz.js +8 -16
- package/dist/_tz.js.map +1 -1
- package/dist/boundary.cjs +1 -1
- package/dist/boundary.cjs.map +1 -1
- package/dist/boundary.d.ts +0 -21
- package/dist/boundary.d.ts.map +1 -1
- package/dist/boundary.js +2 -2
- package/dist/boundary.js.map +1 -1
- package/dist/classify.cjs +1 -1
- package/dist/classify.cjs.map +1 -1
- package/dist/classify.d.ts +3 -45
- package/dist/classify.d.ts.map +1 -1
- package/dist/classify.js +33 -31
- package/dist/classify.js.map +1 -1
- package/dist/compare.cjs +1 -1
- package/dist/compare.cjs.map +1 -1
- package/dist/compare.d.ts +6 -70
- package/dist/compare.d.ts.map +1 -1
- package/dist/compare.js +31 -45
- package/dist/compare.js.map +1 -1
- package/dist/core.cjs +1 -1
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.ts +21 -131
- package/dist/core.d.ts.map +1 -1
- package/dist/core.js +30 -73
- package/dist/core.js.map +1 -1
- package/dist/format.cjs +1 -1
- package/dist/format.cjs.map +1 -1
- package/dist/format.d.ts +17 -17
- package/dist/format.d.ts.map +1 -1
- package/dist/format.js +10 -10
- package/dist/format.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +5 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -9
- package/dist/range.cjs +1 -1
- package/dist/range.cjs.map +1 -1
- package/dist/range.d.ts +3 -57
- package/dist/range.d.ts.map +1 -1
- package/dist/range.js +9 -20
- package/dist/range.js.map +1 -1
- package/dist/tempo.cjs +1 -1
- package/dist/tempo.cjs.map +1 -1
- package/dist/tempo.iife.js +1 -1
- package/dist/tempo.iife.js.map +1 -1
- package/dist/tempo.js +1 -1
- package/dist/tempo.js.map +1 -1
- package/dist/types.d.ts +34 -36
- package/dist/types.d.ts.map +1 -1
- package/package.json +1 -1
package/dist/core.d.ts
CHANGED
|
@@ -1,136 +1,26 @@
|
|
|
1
1
|
import { Temporal } from '@js-temporal/polyfill';
|
|
2
|
-
import type {
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
* @example
|
|
20
|
-
* ```ts
|
|
21
|
-
* timeDiff(nowInstant()) // { unit: 'millisecond', value: 0 } (compared to now)
|
|
22
|
-
* expires(nowInstant(), { expired: { days: 0 }, safe: { years: 100 } }) // 'safe'
|
|
23
|
-
* ```
|
|
24
|
-
*/
|
|
2
|
+
import type { DifferenceInput, ShiftOptions, TimeInput } from './types';
|
|
3
|
+
/** Parse intentionally requires an explicit result kind: time strings are ambiguous at system boundaries. */
|
|
4
|
+
export declare function parse(input: string, options: {
|
|
5
|
+
as: 'zonedDateTime';
|
|
6
|
+
}): Temporal.ZonedDateTime;
|
|
7
|
+
export declare function parse(input: string, options: {
|
|
8
|
+
as: 'instant';
|
|
9
|
+
}): Temporal.Instant;
|
|
10
|
+
export declare function parse(input: string, options: {
|
|
11
|
+
as: 'plainDateTime';
|
|
12
|
+
}): Temporal.PlainDateTime;
|
|
13
|
+
export declare function parse(input: string, options: {
|
|
14
|
+
as: 'plainDate';
|
|
15
|
+
}): Temporal.PlainDate;
|
|
16
|
+
export declare function now(options: {
|
|
17
|
+
timeZone: string;
|
|
18
|
+
}): Temporal.ZonedDateTime;
|
|
25
19
|
export declare function nowInstant(): Temporal.Instant;
|
|
26
|
-
/**
|
|
27
|
-
* Parses a full ISO 8601 zoned date-time string into a `ZonedDateTime`.
|
|
28
|
-
* Use this instead of `Temporal.ZonedDateTime.from()` to avoid importing Temporal directly.
|
|
29
|
-
*
|
|
30
|
-
* @example
|
|
31
|
-
* ```ts
|
|
32
|
-
* parseZoned('2026-03-21T11:00:00+01:00[Europe/Berlin]')
|
|
33
|
-
* parseZoned('2026-03-21T00:00:00[UTC]')
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
export declare function parseZoned(input: string): Temporal.ZonedDateTime;
|
|
37
|
-
/**
|
|
38
|
-
* Parses an ISO 8601 date-only string into a timezone-free `PlainDate`.
|
|
39
|
-
* Use this instead of `Temporal.PlainDate.from()` to avoid importing Temporal directly.
|
|
40
|
-
*
|
|
41
|
-
* @example
|
|
42
|
-
* ```ts
|
|
43
|
-
* parsePlainDate('2026-03-21') // 2026-03-21
|
|
44
|
-
* ```
|
|
45
|
-
*/
|
|
46
|
-
export declare function parsePlainDate(input: string): Temporal.PlainDate;
|
|
47
|
-
/**
|
|
48
|
-
* Parses an ISO 8601 string into a timezone-free `PlainDateTime` (wall-clock time).
|
|
49
|
-
* Use {@link toInstant} or {@link inTz} to attach a timezone when needed.
|
|
50
|
-
*
|
|
51
|
-
* @example
|
|
52
|
-
* ```ts
|
|
53
|
-
* parsePlainDateTime('2026-03-21') // 2026-03-21T00:00:00
|
|
54
|
-
* parsePlainDateTime('2026-03-21T10:15:30') // 2026-03-21T10:15:30
|
|
55
|
-
* ```
|
|
56
|
-
*/
|
|
57
|
-
export declare function parsePlainDateTime(input: string): Temporal.PlainDateTime;
|
|
58
|
-
/**
|
|
59
|
-
* Parses an ISO 8601 UTC string into an absolute `Instant`.
|
|
60
|
-
*
|
|
61
|
-
* @example
|
|
62
|
-
* ```ts
|
|
63
|
-
* parseInstant('2026-03-21T10:15:30Z')
|
|
64
|
-
* ```
|
|
65
|
-
*/
|
|
66
|
-
export declare function parseInstant(input: string): Temporal.Instant;
|
|
67
|
-
/**
|
|
68
|
-
* DST-safe date arithmetic. Adds `duration` to `input` and returns the result as a
|
|
69
|
-
* `ZonedDateTime`. Handles spring-forward and fall-back correctly.
|
|
70
|
-
*
|
|
71
|
-
* **Always returns a `ZonedDateTime`** — even when the input is an `Instant`.
|
|
72
|
-
* Call `.toInstant()` on the result if you need an `Instant` back.
|
|
73
|
-
* Requires `options.tz` when input is an `Instant`, `PlainDate`, or `PlainDateTime`.
|
|
74
|
-
*
|
|
75
|
-
* @example
|
|
76
|
-
* ```ts
|
|
77
|
-
* shift(parseZoned('2026-03-08T01:30:00-05:00[America/New_York]'), { hours: 1 })
|
|
78
|
-
* // 2026-03-08T03:30:00-04:00[America/New_York] (skipped the missing hour)
|
|
79
|
-
*
|
|
80
|
-
* // Instant input — tz required, result is ZonedDateTime
|
|
81
|
-
* shift(parseInstant('2026-03-21T10:00:00Z'), { hours: 2 }, { tz: 'UTC' }).toInstant()
|
|
82
|
-
* ```
|
|
83
|
-
*/
|
|
84
20
|
export declare function shift(input: Temporal.ZonedDateTime, duration: Temporal.DurationLike, options?: ShiftOptions): Temporal.ZonedDateTime;
|
|
85
|
-
export declare function shift(input:
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
* When both inputs are `Instant` and no calendar unit is requested, the fast
|
|
90
|
-
* path skips timezone conversion. Calendar units (`day`, `week`, `month`, `year`)
|
|
91
|
-
* always require a timezone — pass `options.tz` or use `ZonedDateTime` inputs.
|
|
92
|
-
* `options.prefer` (DST disambiguation) is only meaningful for `PlainDateTime` inputs.
|
|
93
|
-
*
|
|
94
|
-
* @example
|
|
95
|
-
* ```ts
|
|
96
|
-
* difference(
|
|
97
|
-
* parseZoned('2026-03-08T00:00:00-05:00[America/New_York]'),
|
|
98
|
-
* parseZoned('2026-03-09T00:00:00-04:00[America/New_York]'),
|
|
99
|
-
* { largestUnit: 'hour' },
|
|
100
|
-
* ).hours // 23 (DST spring-forward day)
|
|
101
|
-
* ```
|
|
102
|
-
*/
|
|
103
|
-
export declare function difference(start: TimeInput, end: TimeInput, options?: DifferenceOptions): Temporal.Duration;
|
|
104
|
-
/**
|
|
105
|
-
* Type guard that checks whether `value` is a valid `TimeInput`.
|
|
106
|
-
*
|
|
107
|
-
* @example
|
|
108
|
-
* ```ts
|
|
109
|
-
* isValid(parseInstant('2026-03-21T10:00:00Z')) // true
|
|
110
|
-
* isValid('2026-03-21') // false
|
|
111
|
-
* ```
|
|
112
|
-
*/
|
|
21
|
+
export declare function shift(input: Exclude<TimeInput, Temporal.ZonedDateTime>, duration: Temporal.DurationLike, options: ShiftOptions & {
|
|
22
|
+
timeZone: string;
|
|
23
|
+
}): Temporal.ZonedDateTime;
|
|
24
|
+
export declare function difference(input: DifferenceInput): Temporal.Duration;
|
|
113
25
|
export declare function isValid(value: unknown): value is TimeInput;
|
|
114
|
-
/**
|
|
115
|
-
* Parses any ISO 8601 string into the most specific `TimeInput` type possible.
|
|
116
|
-
* Tries ZonedDateTime → Instant → PlainDateTime → PlainDate in order.
|
|
117
|
-
* Throws a descriptive `TypeError` if none match.
|
|
118
|
-
*
|
|
119
|
-
* Pass `as` to request a specific return type (throws if the string cannot be parsed as that type):
|
|
120
|
-
*
|
|
121
|
-
* @example
|
|
122
|
-
* ```ts
|
|
123
|
-
* parse('2026-03-21T11:00:00+01:00[Europe/Berlin]') // TimeInput (auto-detect)
|
|
124
|
-
* parse('2026-03-21T11:00:00+01:00[Europe/Berlin]', 'zoned') // Temporal.ZonedDateTime
|
|
125
|
-
* parse('2026-03-21T10:00:00Z', 'instant') // Temporal.Instant
|
|
126
|
-
* parse('2026-03-21T10:00:00', 'plain-datetime') // Temporal.PlainDateTime
|
|
127
|
-
* parse('2026-03-21', 'plain-date') // Temporal.PlainDate
|
|
128
|
-
* ```
|
|
129
|
-
*/
|
|
130
|
-
export declare function parse(input: string, as: 'zoned'): Temporal.ZonedDateTime;
|
|
131
|
-
export declare function parse(input: string, as: 'instant'): Temporal.Instant;
|
|
132
|
-
export declare function parse(input: string, as: 'plain-datetime'): Temporal.PlainDateTime;
|
|
133
|
-
export declare function parse(input: string, as: 'plain-date'): Temporal.PlainDate;
|
|
134
|
-
export declare function parse(input: string, as?: ParseAs): TimeInput;
|
|
135
|
-
export {};
|
|
136
26
|
//# sourceMappingURL=core.d.ts.map
|
package/dist/core.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjD,OAAO,KAAK,EAAgB,
|
|
1
|
+
{"version":3,"file":"core.d.ts","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjD,OAAO,KAAK,EAAgB,eAAe,EAAW,YAAY,EAAE,SAAS,EAAE,MAAM,SAAS,CAAC;AAM/F,6GAA6G;AAC7G,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE;IAAE,EAAE,EAAE,eAAe,CAAA;CAAE,GAAG,QAAQ,CAAC,aAAa,CAAC;AAC/F,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE;IAAE,EAAE,EAAE,SAAS,CAAA;CAAE,GAAG,QAAQ,CAAC,OAAO,CAAC;AACnF,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE;IAAE,EAAE,EAAE,eAAe,CAAA;CAAE,GAAG,QAAQ,CAAC,aAAa,CAAC;AAC/F,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE;IAAE,EAAE,EAAE,WAAW,CAAA;CAAE,GAAG,QAAQ,CAAC,SAAS,CAAC;AAevF,wBAAgB,GAAG,CAAC,OAAO,EAAE;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,GAAG,QAAQ,CAAC,aAAa,CAEzE;AAED,wBAAgB,UAAU,IAAI,QAAQ,CAAC,OAAO,CAE7C;AAED,wBAAgB,KAAK,CACnB,KAAK,EAAE,QAAQ,CAAC,aAAa,EAC7B,QAAQ,EAAE,QAAQ,CAAC,YAAY,EAC/B,OAAO,CAAC,EAAE,YAAY,GACrB,QAAQ,CAAC,aAAa,CAAC;AAC1B,wBAAgB,KAAK,CACnB,KAAK,EAAE,OAAO,CAAC,SAAS,EAAE,QAAQ,CAAC,aAAa,CAAC,EACjD,QAAQ,EAAE,QAAQ,CAAC,YAAY,EAC/B,OAAO,EAAE,YAAY,GAAG;IAAE,QAAQ,EAAE,MAAM,CAAA;CAAE,GAC3C,QAAQ,CAAC,aAAa,CAAC;AAW1B,wBAAgB,UAAU,CAAC,KAAK,EAAE,eAAe,GAAG,QAAQ,CAAC,QAAQ,CAepE;AAED,wBAAgB,OAAO,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,SAAS,CAO1D"}
|
package/dist/core.js
CHANGED
|
@@ -1,89 +1,46 @@
|
|
|
1
1
|
import { fail as e } from "./errors.js";
|
|
2
|
-
import { CALENDAR_UNITS as t, inferSharedTimeZone as n, inferTimeZone as r } from "./_tz.js";
|
|
3
|
-
import { toZoned as
|
|
4
|
-
import { Temporal as
|
|
2
|
+
import { CALENDAR_UNITS as t, inferSharedTimeZone as n, inferTimeZone as r, validateTimeZone as i } from "./_tz.js";
|
|
3
|
+
import { toZoned as a } from "./_convert.js";
|
|
4
|
+
import { Temporal as o } from "@js-temporal/polyfill";
|
|
5
5
|
//#region src/core.ts
|
|
6
|
-
function
|
|
7
|
-
return a.Now.zonedDateTimeISO(e);
|
|
8
|
-
}
|
|
9
|
-
function s() {
|
|
10
|
-
return a.Now.instant();
|
|
11
|
-
}
|
|
12
|
-
function c(t) {
|
|
13
|
-
try {
|
|
14
|
-
return a.ZonedDateTime.from(t);
|
|
15
|
-
} catch {
|
|
16
|
-
e(`Invalid zoned date-time string: "${t}". Expected an ISO 8601 string with offset and timezone (e.g. 2026-03-21T10:00:00+01:00[Europe/Berlin]).`);
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
function l(t) {
|
|
6
|
+
function s(t, n) {
|
|
20
7
|
try {
|
|
21
|
-
return
|
|
8
|
+
return n.as === "zonedDateTime" ? o.ZonedDateTime.from(t) : n.as === "instant" ? o.Instant.from(t) : n.as === "plainDateTime" ? o.PlainDateTime.from(t) : o.PlainDate.from(t);
|
|
22
9
|
} catch {
|
|
23
|
-
e(`Invalid
|
|
10
|
+
e(`Invalid ${n.as} ISO 8601 string: "${t}".`);
|
|
24
11
|
}
|
|
25
12
|
}
|
|
26
|
-
function
|
|
27
|
-
|
|
28
|
-
return a.PlainDateTime.from(t);
|
|
29
|
-
} catch {
|
|
30
|
-
e(`Invalid date/time string: "${t}". Expected an ISO 8601 date or date-time string (e.g. YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss).`);
|
|
31
|
-
}
|
|
13
|
+
function c(e) {
|
|
14
|
+
return o.Now.zonedDateTimeISO(i(e.timeZone));
|
|
32
15
|
}
|
|
33
|
-
function
|
|
34
|
-
|
|
35
|
-
return a.Instant.from(t);
|
|
36
|
-
} catch {
|
|
37
|
-
e(`Invalid instant string: "${t}". Expected an ISO 8601 UTC string (e.g. YYYY-MM-DDTHH:mm:ssZ).`);
|
|
38
|
-
}
|
|
16
|
+
function l() {
|
|
17
|
+
return o.Now.instant();
|
|
39
18
|
}
|
|
40
|
-
function
|
|
41
|
-
let
|
|
42
|
-
return
|
|
43
|
-
|
|
44
|
-
|
|
19
|
+
function u(e, t, n = {}) {
|
|
20
|
+
let i = r(e, n);
|
|
21
|
+
return a(e, {
|
|
22
|
+
disambiguation: n.disambiguation,
|
|
23
|
+
timeZone: i
|
|
45
24
|
}).add(t);
|
|
46
25
|
}
|
|
47
|
-
function
|
|
48
|
-
let {
|
|
49
|
-
largestUnit:
|
|
50
|
-
roundingIncrement:
|
|
51
|
-
roundingMode:
|
|
52
|
-
smallestUnit:
|
|
26
|
+
function d(e) {
|
|
27
|
+
let { end: r, largestUnit: i, roundingIncrement: s, roundingMode: c, smallestUnit: l, start: u } = e, d = {
|
|
28
|
+
largestUnit: i,
|
|
29
|
+
roundingIncrement: s,
|
|
30
|
+
roundingMode: c,
|
|
31
|
+
smallestUnit: l
|
|
53
32
|
};
|
|
54
|
-
if (!(
|
|
55
|
-
let
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
prefer: c,
|
|
61
|
-
tz: p
|
|
62
|
-
}), f);
|
|
63
|
-
}
|
|
64
|
-
function m(e) {
|
|
65
|
-
return e instanceof a.Instant || e instanceof a.ZonedDateTime || e instanceof a.PlainDateTime || e instanceof a.PlainDate;
|
|
33
|
+
if (!(i !== void 0 && t.has(i) || l !== void 0 && t.has(l)) && u instanceof o.Instant && r instanceof o.Instant) return r.since(u, d);
|
|
34
|
+
let f = n([u, r], e), p = {
|
|
35
|
+
disambiguation: e.disambiguation,
|
|
36
|
+
timeZone: f
|
|
37
|
+
};
|
|
38
|
+
return a(r, p).since(a(u, p), d);
|
|
66
39
|
}
|
|
67
|
-
function
|
|
68
|
-
|
|
69
|
-
if (n === "instant") return d(t);
|
|
70
|
-
if (n === "plain-datetime") return u(t);
|
|
71
|
-
if (n === "plain-date") return l(t);
|
|
72
|
-
try {
|
|
73
|
-
return a.ZonedDateTime.from(t);
|
|
74
|
-
} catch {}
|
|
75
|
-
try {
|
|
76
|
-
return a.Instant.from(t);
|
|
77
|
-
} catch {}
|
|
78
|
-
if (t.includes("T")) try {
|
|
79
|
-
return a.PlainDateTime.from(t);
|
|
80
|
-
} catch {}
|
|
81
|
-
else try {
|
|
82
|
-
return a.PlainDate.from(t);
|
|
83
|
-
} catch {}
|
|
84
|
-
e(`Unable to parse date/time string: "${t}". Expected ISO 8601 ZonedDateTime, Instant, PlainDateTime, or PlainDate.`);
|
|
40
|
+
function f(e) {
|
|
41
|
+
return e instanceof o.Instant || e instanceof o.ZonedDateTime || e instanceof o.PlainDateTime || e instanceof o.PlainDate;
|
|
85
42
|
}
|
|
86
43
|
//#endregion
|
|
87
|
-
export {
|
|
44
|
+
export { d as difference, f as isValid, c as now, l as nowInstant, s as parse, u as shift };
|
|
88
45
|
|
|
89
46
|
//# sourceMappingURL=core.js.map
|
package/dist/core.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"core.js","names":[],"sources":["../src/core.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\n\nimport type { CalendarUnit, DifferenceOptions, ParseAs, ShiftOptions, TimeInput } from './types';\n\nimport { toInstant, toZoned } from './_convert';\nimport { CALENDAR_UNITS, inferSharedTimeZone, inferTimeZone } from './_tz';\nimport { fail } from './errors';\n\ntype TimeOptionsWithTz = { tz: string };\n\n/**\n * Returns the current date and time in the given timezone.\n *\n * @example\n * ```ts\n * now('America/New_York').hour; // current hour in New York\n * ```\n */\nexport function now(tz: string): Temporal.ZonedDateTime {\n return Temporal.Now.zonedDateTimeISO(tz);\n}\n\n/**\n * Returns the current absolute instant (UTC point in time).\n * Use this instead of `Temporal.Now.instant()` to avoid importing Temporal directly.\n *\n * @example\n * ```ts\n * timeDiff(nowInstant()) // { unit: 'millisecond', value: 0 } (compared to now)\n * expires(nowInstant(), { expired: { days: 0 }, safe: { years: 100 } }) // 'safe'\n * ```\n */\nexport function nowInstant(): Temporal.Instant {\n return Temporal.Now.instant();\n}\n\n/**\n * Parses a full ISO 8601 zoned date-time string into a `ZonedDateTime`.\n * Use this instead of `Temporal.ZonedDateTime.from()` to avoid importing Temporal directly.\n *\n * @example\n * ```ts\n * parseZoned('2026-03-21T11:00:00+01:00[Europe/Berlin]')\n * parseZoned('2026-03-21T00:00:00[UTC]')\n * ```\n */\nexport function parseZoned(input: string): Temporal.ZonedDateTime {\n try {\n return Temporal.ZonedDateTime.from(input);\n } catch {\n fail(\n `Invalid zoned date-time string: \"${input}\". Expected an ISO 8601 string with offset and timezone (e.g. 2026-03-21T10:00:00+01:00[Europe/Berlin]).`,\n );\n }\n}\n\n/**\n * Parses an ISO 8601 date-only string into a timezone-free `PlainDate`.\n * Use this instead of `Temporal.PlainDate.from()` to avoid importing Temporal directly.\n *\n * @example\n * ```ts\n * parsePlainDate('2026-03-21') // 2026-03-21\n * ```\n */\nexport function parsePlainDate(input: string): Temporal.PlainDate {\n try {\n return Temporal.PlainDate.from(input);\n } catch {\n fail(`Invalid plain date string: \"${input}\". Expected an ISO 8601 date string (e.g. YYYY-MM-DD).`);\n }\n}\n\n/**\n * Parses an ISO 8601 string into a timezone-free `PlainDateTime` (wall-clock time).\n * Use {@link toInstant} or {@link inTz} to attach a timezone when needed.\n *\n * @example\n * ```ts\n * parsePlainDateTime('2026-03-21') // 2026-03-21T00:00:00\n * parsePlainDateTime('2026-03-21T10:15:30') // 2026-03-21T10:15:30\n * ```\n */\nexport function parsePlainDateTime(input: string): Temporal.PlainDateTime {\n try {\n return Temporal.PlainDateTime.from(input);\n } catch {\n fail(\n `Invalid date/time string: \"${input}\". Expected an ISO 8601 date or date-time string (e.g. YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss).`,\n );\n }\n}\n\n/**\n * Parses an ISO 8601 UTC string into an absolute `Instant`.\n *\n * @example\n * ```ts\n * parseInstant('2026-03-21T10:15:30Z')\n * ```\n */\nexport function parseInstant(input: string): Temporal.Instant {\n try {\n return Temporal.Instant.from(input);\n } catch {\n fail(`Invalid instant string: \"${input}\". Expected an ISO 8601 UTC string (e.g. YYYY-MM-DDTHH:mm:ssZ).`);\n }\n}\n\n/**\n * DST-safe date arithmetic. Adds `duration` to `input` and returns the result as a\n * `ZonedDateTime`. Handles spring-forward and fall-back correctly.\n *\n * **Always returns a `ZonedDateTime`** — even when the input is an `Instant`.\n * Call `.toInstant()` on the result if you need an `Instant` back.\n * Requires `options.tz` when input is an `Instant`, `PlainDate`, or `PlainDateTime`.\n *\n * @example\n * ```ts\n * shift(parseZoned('2026-03-08T01:30:00-05:00[America/New_York]'), { hours: 1 })\n * // 2026-03-08T03:30:00-04:00[America/New_York] (skipped the missing hour)\n *\n * // Instant input — tz required, result is ZonedDateTime\n * shift(parseInstant('2026-03-21T10:00:00Z'), { hours: 2 }, { tz: 'UTC' }).toInstant()\n * ```\n */\nexport function shift(\n input: Temporal.ZonedDateTime,\n duration: Temporal.DurationLike,\n options?: ShiftOptions,\n): Temporal.ZonedDateTime;\nexport function shift(\n input: Temporal.Instant | Temporal.PlainDate | Temporal.PlainDateTime,\n duration: Temporal.DurationLike,\n options: ShiftOptions & TimeOptionsWithTz,\n): Temporal.ZonedDateTime;\nexport function shift(\n input: TimeInput,\n duration: Temporal.DurationLike,\n options: ShiftOptions = {},\n): Temporal.ZonedDateTime {\n const tz = inferTimeZone(input, options);\n\n return toZoned(input, { prefer: options.prefer, tz }).add(duration);\n}\n\n/**\n * Returns the calendar-aware duration between `start` and `end`.\n *\n * When both inputs are `Instant` and no calendar unit is requested, the fast\n * path skips timezone conversion. Calendar units (`day`, `week`, `month`, `year`)\n * always require a timezone — pass `options.tz` or use `ZonedDateTime` inputs.\n * `options.prefer` (DST disambiguation) is only meaningful for `PlainDateTime` inputs.\n *\n * @example\n * ```ts\n * difference(\n * parseZoned('2026-03-08T00:00:00-05:00[America/New_York]'),\n * parseZoned('2026-03-09T00:00:00-04:00[America/New_York]'),\n * { largestUnit: 'hour' },\n * ).hours // 23 (DST spring-forward day)\n * ```\n */\nexport function difference(start: TimeInput, end: TimeInput, options: DifferenceOptions = {}): Temporal.Duration {\n const { largestUnit, prefer, roundingIncrement, roundingMode, smallestUnit } = options;\n const roundingOptions = { largestUnit, roundingIncrement, roundingMode, smallestUnit };\n\n const needsCalendar =\n (largestUnit !== undefined && CALENDAR_UNITS.has(largestUnit as CalendarUnit)) ||\n (smallestUnit !== undefined && CALENDAR_UNITS.has(smallestUnit as CalendarUnit));\n\n if (!needsCalendar && start instanceof Temporal.Instant && end instanceof Temporal.Instant) {\n return end.since(start, roundingOptions as Temporal.DifferenceOptions<Temporal.TimeUnit>);\n }\n\n const tz = inferSharedTimeZone([start, end], options);\n\n return toZoned(end, { prefer, tz }).since(toZoned(start, { prefer, tz }), roundingOptions);\n}\n\n/**\n * Type guard that checks whether `value` is a valid `TimeInput`.\n *\n * @example\n * ```ts\n * isValid(parseInstant('2026-03-21T10:00:00Z')) // true\n * isValid('2026-03-21') // false\n * ```\n */\nexport function isValid(value: unknown): value is TimeInput {\n return (\n value instanceof Temporal.Instant ||\n value instanceof Temporal.ZonedDateTime ||\n value instanceof Temporal.PlainDateTime ||\n value instanceof Temporal.PlainDate\n );\n}\n\n/**\n * Parses any ISO 8601 string into the most specific `TimeInput` type possible.\n * Tries ZonedDateTime → Instant → PlainDateTime → PlainDate in order.\n * Throws a descriptive `TypeError` if none match.\n *\n * Pass `as` to request a specific return type (throws if the string cannot be parsed as that type):\n *\n * @example\n * ```ts\n * parse('2026-03-21T11:00:00+01:00[Europe/Berlin]') // TimeInput (auto-detect)\n * parse('2026-03-21T11:00:00+01:00[Europe/Berlin]', 'zoned') // Temporal.ZonedDateTime\n * parse('2026-03-21T10:00:00Z', 'instant') // Temporal.Instant\n * parse('2026-03-21T10:00:00', 'plain-datetime') // Temporal.PlainDateTime\n * parse('2026-03-21', 'plain-date') // Temporal.PlainDate\n * ```\n */\nexport function parse(input: string, as: 'zoned'): Temporal.ZonedDateTime;\nexport function parse(input: string, as: 'instant'): Temporal.Instant;\nexport function parse(input: string, as: 'plain-datetime'): Temporal.PlainDateTime;\nexport function parse(input: string, as: 'plain-date'): Temporal.PlainDate;\nexport function parse(input: string, as?: ParseAs): TimeInput;\nexport function parse(input: string, as?: ParseAs): TimeInput {\n if (as === 'zoned') return parseZoned(input);\n\n if (as === 'instant') return parseInstant(input);\n\n if (as === 'plain-datetime') return parsePlainDateTime(input);\n\n if (as === 'plain-date') return parsePlainDate(input);\n\n try {\n return Temporal.ZonedDateTime.from(input);\n } catch {\n /* try next format */\n }\n\n try {\n return Temporal.Instant.from(input);\n } catch {\n /* try next format */\n }\n\n // Try PlainDateTime before PlainDate — a date-only string (no 'T') will also\n // be accepted by PlainDateTime.from(), producing midnight, so we check the\n // string to pick the most specific type.\n if (input.includes('T')) {\n try {\n return Temporal.PlainDateTime.from(input);\n } catch {\n /* fall through to error */\n }\n } else {\n try {\n return Temporal.PlainDate.from(input);\n } catch {\n /* fall through to error */\n }\n }\n\n fail(\n `Unable to parse date/time string: \"${input}\". Expected ISO 8601 ZonedDateTime, Instant, PlainDateTime, or PlainDate.`,\n );\n}\n"],"mappings":";;;;;AAkBA,SAAgB,EAAI,GAAoC;CACtD,OAAO,EAAS,IAAI,iBAAiB,CAAE;AACzC;AAYA,SAAgB,IAA+B;CAC7C,OAAO,EAAS,IAAI,QAAQ;AAC9B;AAYA,SAAgB,EAAW,GAAuC;CAChE,IAAI;EACF,OAAO,EAAS,cAAc,KAAK,CAAK;CAC1C,QAAQ;EACN,EACE,oCAAoC,EAAM,yGAC5C;CACF;AACF;AAWA,SAAgB,EAAe,GAAmC;CAChE,IAAI;EACF,OAAO,EAAS,UAAU,KAAK,CAAK;CACtC,QAAQ;EACN,EAAK,+BAA+B,EAAM,uDAAuD;CACnG;AACF;AAYA,SAAgB,EAAmB,GAAuC;CACxE,IAAI;EACF,OAAO,EAAS,cAAc,KAAK,CAAK;CAC1C,QAAQ;EACN,EACE,8BAA8B,EAAM,2FACtC;CACF;AACF;AAUA,SAAgB,EAAa,GAAiC;CAC5D,IAAI;EACF,OAAO,EAAS,QAAQ,KAAK,CAAK;CACpC,QAAQ;EACN,EAAK,4BAA4B,EAAM,gEAAgE;CACzG;AACF;AA6B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AK,CAAK;CAC1C,QAAQ,CAER;MAEA,IAAI;EACF,OAAO,EAAS,UAAU,KAAK,CAAK;CACtC,QAAQ,CAER;CAGF,EACE,sCAAsC,EAAM,0EAC9C;AACF"}
|
|
1
|
+
{"version":3,"file":"core.js","names":[],"sources":["../src/core.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\n\nimport type { CalendarUnit, DifferenceInput, ParseAs, ShiftOptions, TimeInput } from './types';\n\nimport { toZoned } from './_convert';\nimport { CALENDAR_UNITS, inferSharedTimeZone, inferTimeZone, validateTimeZone } from './_tz';\nimport { fail } from './errors';\n\n/** Parse intentionally requires an explicit result kind: time strings are ambiguous at system boundaries. */\nexport function parse(input: string, options: { as: 'zonedDateTime' }): Temporal.ZonedDateTime;\nexport function parse(input: string, options: { as: 'instant' }): Temporal.Instant;\nexport function parse(input: string, options: { as: 'plainDateTime' }): Temporal.PlainDateTime;\nexport function parse(input: string, options: { as: 'plainDate' }): Temporal.PlainDate;\nexport function parse(input: string, options: { as: ParseAs }): TimeInput {\n try {\n if (options.as === 'zonedDateTime') return Temporal.ZonedDateTime.from(input);\n\n if (options.as === 'instant') return Temporal.Instant.from(input);\n\n if (options.as === 'plainDateTime') return Temporal.PlainDateTime.from(input);\n\n return Temporal.PlainDate.from(input);\n } catch {\n fail(`Invalid ${options.as} ISO 8601 string: \"${input}\".`);\n }\n}\n\nexport function now(options: { timeZone: string }): Temporal.ZonedDateTime {\n return Temporal.Now.zonedDateTimeISO(validateTimeZone(options.timeZone));\n}\n\nexport function nowInstant(): Temporal.Instant {\n return Temporal.Now.instant();\n}\n\nexport function shift(\n input: Temporal.ZonedDateTime,\n duration: Temporal.DurationLike,\n options?: ShiftOptions,\n): Temporal.ZonedDateTime;\nexport function shift(\n input: Exclude<TimeInput, Temporal.ZonedDateTime>,\n duration: Temporal.DurationLike,\n options: ShiftOptions & { timeZone: string },\n): Temporal.ZonedDateTime;\nexport function shift(\n input: TimeInput,\n duration: Temporal.DurationLike,\n options: ShiftOptions = {},\n): Temporal.ZonedDateTime {\n const timeZone = inferTimeZone(input, options);\n\n return toZoned(input, { disambiguation: options.disambiguation, timeZone }).add(duration);\n}\n\nexport function difference(input: DifferenceInput): Temporal.Duration {\n const { end, largestUnit, roundingIncrement, roundingMode, smallestUnit, start } = input;\n const rounding = { largestUnit, roundingIncrement, roundingMode, smallestUnit };\n const needsCalendar =\n (largestUnit !== undefined && CALENDAR_UNITS.has(largestUnit as CalendarUnit)) ||\n (smallestUnit !== undefined && CALENDAR_UNITS.has(smallestUnit as CalendarUnit));\n\n if (!needsCalendar && start instanceof Temporal.Instant && end instanceof Temporal.Instant) {\n return end.since(start, rounding as Temporal.DifferenceOptions<Temporal.TimeUnit>);\n }\n\n const timeZone = inferSharedTimeZone([start, end], input);\n const options = { disambiguation: input.disambiguation, timeZone };\n\n return toZoned(end, options).since(toZoned(start, options), rounding);\n}\n\nexport function isValid(value: unknown): value is TimeInput {\n return (\n value instanceof Temporal.Instant ||\n value instanceof Temporal.ZonedDateTime ||\n value instanceof Temporal.PlainDateTime ||\n value instanceof Temporal.PlainDate\n );\n}\n"],"mappings":";;;;;AAaA,SAAgB,EAAM,GAAe,GAAqC;CACxE,IAAI;EAOF,OANI,EAAQ,OAAO,kBAAwB,EAAS,cAAc,KAAK,CAAK,IAExE,EAAQ,OAAO,YAAkB,EAAS,QAAQ,KAAK,CAAK,IAE5D,EAAQ,OAAO,kBAAwB,EAAS,cAAc,KAAK,CAAK,IAErE,EAAS,UAAU,KAAK,CAAK;CACtC,QAAQ;EACN,EAAK,WAAW,EAAQ,GAAG,qBAAqB,EAAM,GAAG;CAC3D;AACF;AAEA,SAAgB,EAAI,GAAuD;CACzE,OAAO,EAAS,IAAI,iBAAiB,EAAiB,EAAQ,QAAQ,CAAC;AACzE;AAEA,SAAgB,IAA+B;CAC7C,OAAO,EAAS,IAAI,QAAQ;AAC9B;AAYA,SAAgB,EACd,GACA,GACA,IAAwB,CAAC,GACD;CACxB,IAAM,IAAW,EAAc,GAAO,CAAO;CAE7C,OAAO,EAAQ,GAAO;EAAE,gBAAgB,EAAQ;EAAgB;CAAS,CAAC,CAAC,CAAC,IAAI,CAAQ;AAC1F;AAEA,SAAgB,EAAW,GAA2C;CACpE,IAAM,EAAE,QAAK,gBAAa,sBAAmB,iBAAc,iBAAc,aAAU,GAC7E,IAAW;EAAE;EAAa;EAAmB;EAAc;CAAa;CAK9E,IAAI,EAHD,MAAgB,KAAA,KAAa,EAAe,IAAI,CAA2B,KAC3E,MAAiB,KAAA,KAAa,EAAe,IAAI,CAA4B,MAE1D,aAAiB,EAAS,WAAW,aAAe,EAAS,SACjF,OAAO,EAAI,MAAM,GAAO,CAAyD;CAGnF,IAAM,IAAW,EAAoB,CAAC,GAAO,CAAG,GAAG,CAAK,GAClD,IAAU;EAAE,gBAAgB,EAAM;EAAgB;CAAS;CAEjE,OAAO,EAAQ,GAAK,CAAO,CAAC,CAAC,MAAM,EAAQ,GAAO,CAAO,GAAG,CAAQ;AACtE;AAEA,SAAgB,EAAQ,GAAoC;CAC1D,OACE,aAAiB,EAAS,WAC1B,aAAiB,EAAS,iBAC1B,aAAiB,EAAS,iBAC1B,aAAiB,EAAS;AAE9B"}
|
package/dist/format.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
const e=require("./errors.cjs"),t=require("./_tz.cjs"),n=require("./_convert.cjs");let r=require("@js-temporal/polyfill");var i=128;function a(e,t,n){let r=e.get(t);if(r!==void 0)return r;if(e.size>=i){let t=e.keys().next().value;t!==void 0&&e.delete(t)}let a=n();return e.set(t,a),a}var o=new Map,s=new Map,c=new Map,l={"date-only":{dateStyle:`short`},long:{dateStyle:`full`,timeStyle:`long`},medium:{dateStyle:`medium`,timeStyle:`short`},short:{dateStyle:`short`,timeStyle:`short`},"time-only":{timeStyle:`short`}};function u(e){return JSON.stringify(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,String(t)]))}function d(e,t){let n=e.
|
|
1
|
+
const e=require("./errors.cjs"),t=require("./_tz.cjs"),n=require("./_convert.cjs");let r=require("@js-temporal/polyfill");var i=128;function a(e,t,n){let r=e.get(t);if(r!==void 0)return r;if(e.size>=i){let t=e.keys().next().value;t!==void 0&&e.delete(t)}let a=n();return e.set(t,a),a}var o=new Map,s=new Map,c=new Map,l={"date-only":{dateStyle:`short`},long:{dateStyle:`full`,timeStyle:`long`},medium:{dateStyle:`medium`,timeStyle:`short`},short:{dateStyle:`short`,timeStyle:`short`},"time-only":{timeStyle:`short`}};function u(e){return JSON.stringify(Object.entries(e).filter(([,e])=>e!==void 0).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>[e,String(t)]))}function d(e,t){let n=e.timeZone??t,r=e.locale;if(e.intl!==void 0)return a(o,`${String(r??``)}|intl|${n??``}|${u(e.intl)}`,()=>{let t=n===void 0?e.intl:{...e.intl,timeZone:n};return new Intl.DateTimeFormat(r,t)});let i=e.pattern??`medium`;return a(o,`${String(r??``)}|${i}|${n??``}`,()=>new Intl.DateTimeFormat(r,{...l[i],timeZone:n}))}function f(e){return a(s,`${String(e.locale??``)}|${e.numeric??`auto`}|${e.style??`long`}`,()=>new Intl.RelativeTimeFormat(e.locale,{numeric:e.numeric??`auto`,style:e.style??`long`}))}function p(e){let t=Intl;return t.DurationFormat?a(c,`${String(e.locale??``)}|${e.style??``}`,()=>new t.DurationFormat(e.locale,{style:e.style})):null}var m=60,h=3600,g=86400,_=604800,v=2629800,y=31557600,b=[{scale:1,thresholdToPromote:m,unit:`second`},{scale:m,thresholdToPromote:h/m,unit:`minute`},{scale:h,thresholdToPromote:g/h,unit:`hour`},{scale:g,thresholdToPromote:_/g,unit:`day`},{scale:_,thresholdToPromote:v/_,unit:`week`},{scale:v,thresholdToPromote:12,unit:`month`},{scale:y,thresholdToPromote:1/0,unit:`year`}];function x(t){Number.isFinite(t)||e.fail(`formatRelative received a non-finite time difference.`);let n=Math.round(t);for(let{scale:e,thresholdToPromote:t,unit:r}of b){let i=Math.round(n/e);if(Math.abs(i)<t)return{unit:r,value:i}}return{unit:`year`,value:Math.round(n/y)}}var S=[`years`,`months`,`weeks`,`days`,`hours`,`minutes`,`seconds`,`milliseconds`,`microseconds`,`nanoseconds`];function C(e){let t=[];for(let n of S){let r=Math.abs(e[n]);r!==0&&t.push(`${r} ${r===1?n.slice(0,-1):n}`)}return t.length===0?`0 seconds`:t.join(`, `)}function w(t,n,i,a){if(i.timeZone)return i.timeZone;let o=t instanceof r.Temporal.ZonedDateTime?t.timeZoneId:void 0,s=n instanceof r.Temporal.ZonedDateTime?n.timeZoneId:void 0;return o&&s&&o!==s&&e.fail(`${a} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`),o??s}function T(e,t={}){let i=t.timeZone??(e instanceof r.Temporal.ZonedDateTime?e.timeZoneId:void 0);return d(t,i).format(new Date(n.toInstant(e,{timeZone:i}).epochMilliseconds))}function E(e,t,r={}){let i=w(e,t,r,`formatRange`);return d(r,i).formatRange(new Date(n.toInstant(e,{timeZone:i}).epochMilliseconds),new Date(n.toInstant(t,{timeZone:i}).epochMilliseconds))}function D(e,t,r={}){let i=w(e,t,r,`formatRangeParts`);return d(r,i).formatRangeToParts(new Date(n.toInstant(e,{timeZone:i}).epochMilliseconds),new Date(n.toInstant(t,{timeZone:i}).epochMilliseconds))}function O(e,t={}){return n.toInstant(e,t).toString()}function k(e,r={}){let i=t.inferTimeZone(e,r);return n.toZoned(e,{timeZone:i}).toString()}function A(e,t={}){let n=e instanceof r.Temporal.Instant?e:e.toInstant(),i=t.base?t.base instanceof r.Temporal.Instant?t.base:t.base.toInstant():r.Temporal.Now.instant(),{unit:a,value:o}=x((n.epochMilliseconds-i.epochMilliseconds)/1e3);return f(t).format(o,a)}function j(t){try{return r.Temporal.Duration.from(t)}catch{e.fail(`Invalid duration input: "${String(t)}". Expected an ISO 8601 duration string or Temporal.DurationLike.`)}}function M(e,t={}){let n=j(e),r=p(t);return r?r.format(n):C(n)}function N(e,t={}){let i=t.timeZone??(e instanceof r.Temporal.ZonedDateTime?e.timeZoneId:void 0);return d(t,i).formatToParts(new Date(n.toInstant(e,{timeZone:i}).epochMilliseconds))}function P(e,t={}){let{unit:n,value:r}=e;return`${t.locale?new Intl.NumberFormat(t.locale).format(r):String(r)} ${r===1?n:`${n}s`}`}exports.format=T,exports.formatDuration=M,exports.formatInstant=O,exports.formatParts=N,exports.formatRange=E,exports.formatRangeParts=D,exports.formatRelative=A,exports.formatZoned=k,exports.humanize=P,exports.parseDuration=j;
|
|
2
2
|
//# sourceMappingURL=format.cjs.map
|
package/dist/format.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\n\nimport type {\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n RelativeFormatOptions,\n RelativeTimeInput,\n TimeDiffResult,\n TimeInput,\n TimeOptions,\n} from './types';\n\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { fail } from './errors';\n\n// ─── Formatter types ──────────────────────────────────────────────────────────\n\ntype DurationFormatter = { format(value: Temporal.Duration): string };\ntype DurationFormatterConstructor = new (\n locales?: Intl.LocalesArgument,\n options?: { style?: 'digital' | 'long' | 'narrow' | 'short' },\n) => DurationFormatter;\n\n// ─── Formatter caches ─────────────────────────────────────────────────────────\n\nconst FORMATTER_CACHE_MAX = 128;\n\nfunction cappedGetOrCreate<V>(cache: Map<string, V>, key: string, factory: () => V): V {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n if (cache.size >= FORMATTER_CACHE_MAX) {\n const oldest = cache.keys().next().value;\n\n if (oldest !== undefined) cache.delete(oldest);\n }\n\n const value = factory();\n\n cache.set(key, value);\n\n return value;\n}\n\nconst DATE_TIME_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();\nconst RELATIVE_TIME_FORMATTER_CACHE = new Map<string, Intl.RelativeTimeFormat>();\nconst DURATION_FORMATTER_CACHE = new Map<string, DurationFormatter>();\n\n// ─── Format presets ───────────────────────────────────────────────────────────\n\nconst FORMAT_PRESETS: Record<FormatPattern, Intl.DateTimeFormatOptions> = {\n 'date-only': { dateStyle: 'short' },\n long: { dateStyle: 'full', timeStyle: 'long' },\n medium: { dateStyle: 'medium', timeStyle: 'short' },\n short: { dateStyle: 'short', timeStyle: 'short' },\n 'time-only': { timeStyle: 'short' },\n};\n\n// ─── Formatter factory helpers ────────────────────────────────────────────────\n\nfunction serializeIntlOptions(options: Intl.DateTimeFormatOptions): string {\n return JSON.stringify(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .sort(([l], [r]) => l.localeCompare(r))\n .map(([key, value]) => [key, String(value)]),\n );\n}\n\nfunction makeFormatter(options: FormatOptions, fallbackTz?: string): Intl.DateTimeFormat {\n const tz = options.tz ?? fallbackTz;\n const locale = options.locale;\n\n if (options.intl !== undefined) {\n const cacheKey = `${String(locale ?? '')}|intl|${tz ?? ''}|${serializeIntlOptions(options.intl)}`;\n\n return cappedGetOrCreate(DATE_TIME_FORMATTER_CACHE, cacheKey, () => {\n const intlOptions = tz !== undefined ? { ...options.intl, timeZone: tz } : options.intl;\n\n return new Intl.DateTimeFormat(locale, intlOptions);\n });\n }\n\n const pattern = options.pattern ?? 'medium';\n const cacheKey = `${String(locale ?? '')}|${pattern}|${tz ?? ''}`;\n\n return cappedGetOrCreate(\n DATE_TIME_FORMATTER_CACHE,\n cacheKey,\n () => new Intl.DateTimeFormat(locale, { ...FORMAT_PRESETS[pattern], timeZone: tz }),\n );\n}\n\nfunction getRelativeFormatter(options: {\n locale?: Intl.LocalesArgument;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n}): Intl.RelativeTimeFormat {\n const cacheKey = `${String(options.locale ?? '')}|${options.numeric ?? 'auto'}|${options.style ?? 'long'}`;\n\n return cappedGetOrCreate(\n RELATIVE_TIME_FORMATTER_CACHE,\n cacheKey,\n () =>\n new Intl.RelativeTimeFormat(options.locale, {\n numeric: options.numeric ?? 'auto',\n style: options.style ?? 'long',\n }),\n );\n}\n\nfunction getDurationFormatter(options: {\n locale?: Intl.LocalesArgument;\n style?: 'digital' | 'long' | 'narrow' | 'short';\n}): DurationFormatter | null {\n const IntlWithDurationFormat = Intl as typeof Intl & { DurationFormat?: DurationFormatterConstructor };\n\n if (!IntlWithDurationFormat.DurationFormat) return null;\n\n const cacheKey = `${String(options.locale ?? '')}|${options.style ?? ''}`;\n\n return cappedGetOrCreate(\n DURATION_FORMATTER_CACHE,\n cacheKey,\n () => new IntlWithDurationFormat.DurationFormat!(options.locale, { style: options.style }),\n );\n}\n\n// ─── Time scale constants ─────────────────────────────────────────────────────\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3_600;\nconst SECONDS_PER_DAY = 86_400;\nconst SECONDS_PER_WEEK = 604_800;\nconst SECONDS_PER_MONTH = 2_629_800; // ≈ 30.4375 days × 86400\nconst SECONDS_PER_YEAR = 31_557_600; // 365.25 days × 86400\n\n// ─── Relative time helpers ────────────────────────────────────────────────────\n\nconst RELATIVE_UNITS: ReadonlyArray<{ scale: number; thresholdToPromote: number; unit: Intl.RelativeTimeFormatUnit }> =\n [\n { scale: 1, thresholdToPromote: SECONDS_PER_MINUTE, unit: 'second' },\n { scale: SECONDS_PER_MINUTE, thresholdToPromote: SECONDS_PER_HOUR / SECONDS_PER_MINUTE, unit: 'minute' },\n { scale: SECONDS_PER_HOUR, thresholdToPromote: SECONDS_PER_DAY / SECONDS_PER_HOUR, unit: 'hour' },\n { scale: SECONDS_PER_DAY, thresholdToPromote: SECONDS_PER_WEEK / SECONDS_PER_DAY, unit: 'day' },\n { scale: SECONDS_PER_WEEK, thresholdToPromote: SECONDS_PER_MONTH / SECONDS_PER_WEEK, unit: 'week' },\n { scale: SECONDS_PER_MONTH, thresholdToPromote: 12, unit: 'month' },\n { scale: SECONDS_PER_YEAR, thresholdToPromote: Number.POSITIVE_INFINITY, unit: 'year' },\n ];\n\nfunction toRelativeUnit(seconds: number): { unit: Intl.RelativeTimeFormatUnit; value: number } {\n if (!Number.isFinite(seconds)) fail('formatRelative received a non-finite time difference.');\n\n const roundedSeconds = Math.round(seconds);\n\n for (const { scale, thresholdToPromote, unit } of RELATIVE_UNITS) {\n const value = Math.round(roundedSeconds / scale);\n\n if (Math.abs(value) < thresholdToPromote) return { unit, value };\n }\n\n return { unit: 'year', value: Math.round(roundedSeconds / SECONDS_PER_YEAR) };\n}\n\n// ─── Duration fallback renderer ───────────────────────────────────────────────\n\n// All English duration unit names follow the same pluralization rule: singular = plural.slice(0, -1)\nconst DURATION_UNITS = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n] as const satisfies ReadonlyArray<keyof Temporal.Duration>;\n\n// English-only fallback; runs only when Intl.DurationFormat is unavailable in the runtime.\nfunction buildDurationFallback(duration: Temporal.Duration): string {\n const parts: string[] = [];\n\n for (const unit of DURATION_UNITS) {\n const value = Math.abs(duration[unit] as number);\n\n if (value !== 0) parts.push(`${value} ${value === 1 ? unit.slice(0, -1) : unit}`);\n }\n\n return parts.length === 0 ? '0 seconds' : parts.join(', ');\n}\n\n// ─── Private helpers ──────────────────────────────────────────────────────────\n\n/**\n * Resolves a shared display timezone for two-input range functions.\n * Throws when both inputs are `ZonedDateTime` with different zones and no `options.tz` override.\n */\nfunction resolveRangeTz(start: TimeInput, end: TimeInput, options: FormatOptions, caller: string): string | undefined {\n if (options.tz) return options.tz;\n\n const startTz = start instanceof Temporal.ZonedDateTime ? start.timeZoneId : undefined;\n const endTz = end instanceof Temporal.ZonedDateTime ? end.timeZoneId : undefined;\n\n if (startTz && endTz && startTz !== endTz) {\n fail(`${caller} received ZonedDateTime inputs with different time zones. Pass options.tz explicitly.`);\n }\n\n return startTz ?? endTz;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Formats `input` using `Intl.DateTimeFormat`. Defaults to `pattern: 'medium'`.\n *\n * Pass `intl` for full `Intl.DateTimeFormatOptions` control (mutually exclusive with `pattern`).\n * The timezone is inferred from a `ZonedDateTime` input or from `options.tz`.\n *\n * @example\n * ```ts\n * format(parseInstant('2026-03-21T10:15:30Z'), { locale: 'en-GB', pattern: 'short', tz: 'UTC' })\n * // '21/03/2026, 10:15'\n * ```\n */\nexport function format(input: TimeInput, options: FormatOptions = {}): string {\n const tz = options.tz ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, tz).format(new Date(toInstant(input, { tz }).epochMilliseconds));\n}\n\n/**\n * Formats a time span between `start` and `end` using `Intl.DateTimeFormat.formatRange`.\n *\n * @example\n * ```ts\n * formatRange(start, end, { locale: 'en-GB', pattern: 'short', tz: 'UTC' })\n * // '21/03/2026, 10:00 – 12:00'\n * ```\n */\nexport function formatRange(start: TimeInput, end: TimeInput, options: FormatOptions = {}): string {\n const tz = resolveRangeTz(start, end, options, 'formatRange');\n const formatter = makeFormatter(options, tz);\n\n return formatter.formatRange(\n new Date(toInstant(start, { tz }).epochMilliseconds),\n new Date(toInstant(end, { tz }).epochMilliseconds),\n );\n}\n\n/**\n * Returns the raw `Intl.DateTimeRangeFormatPart[]` array for a time span, enabling\n * fine-grained rendering of range start, end, and shared parts separately.\n *\n * @example\n * ```ts\n * formatRangeParts(start, end, { locale: 'en-US', pattern: 'short', tz: 'UTC' })\n * // [{ type: 'month', value: '3', source: 'startRange' }, ...]\n * ```\n */\nexport function formatRangeParts(\n start: TimeInput,\n end: TimeInput,\n options: FormatOptions = {},\n): ReturnType<Intl.DateTimeFormat['formatRangeToParts']> {\n const tz = resolveRangeTz(start, end, options, 'formatRangeParts');\n const formatter = makeFormatter(options, tz);\n\n return formatter.formatRangeToParts(\n new Date(toInstant(start, { tz }).epochMilliseconds),\n new Date(toInstant(end, { tz }).epochMilliseconds),\n );\n}\n\n/**\n * Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).\n * Requires `options.tz` when input is a `PlainDate` or `PlainDateTime`.\n *\n * @example\n * ```ts\n * formatInstant(parseZoned('2026-03-21T11:15:30+01:00[Europe/Berlin]'))\n * // '2026-03-21T10:15:30Z'\n * ```\n */\nexport function formatInstant(input: TimeInput, options: TimeOptions = {}): string {\n return toInstant(input, options).toString();\n}\n\n/**\n * Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).\n *\n * @param options.tz - Required when `input` is a `PlainDate` or `PlainDateTime`.\n * Inferred automatically from a `ZonedDateTime` or `Instant` input.\n *\n * @throws {TempoError} When `input` is a `PlainDate` or `PlainDateTime` and `options.tz` is omitted.\n *\n * @example\n * ```ts\n * formatZoned(parseInstant('2026-03-21T10:15:30Z'), { tz: 'Europe/Berlin' })\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]'\n *\n * formatZoned(parseZoned('2026-03-21T11:15:30+01:00[Europe/Berlin]'))\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (tz inferred)\n * ```\n */\nexport function formatZoned(input: TimeInput, options: TimeOptions = {}): string {\n const tz = inferTimeZone(input, options);\n\n return toZoned(input, { tz }).toString();\n}\n\n/**\n * Formats `input` relative to `options.base` (defaults to now) using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```ts\n * formatRelative(parseInstant('2026-03-21T12:00:00Z'), {\n * base: parseInstant('2026-03-21T10:00:00Z'),\n * locale: 'en-US',\n * numeric: 'always',\n * })\n * // 'in 2 hours'\n * ```\n */\nexport function formatRelative(input: RelativeTimeInput, options: RelativeFormatOptions = {}): string {\n const target = input instanceof Temporal.Instant ? input : input.toInstant();\n const base = options.base\n ? options.base instanceof Temporal.Instant\n ? options.base\n : options.base.toInstant()\n : Temporal.Now.instant();\n const differenceInSeconds = (target.epochMilliseconds - base.epochMilliseconds) / 1000;\n const { unit, value } = toRelativeUnit(differenceInSeconds);\n\n return getRelativeFormatter(options).format(value, unit);\n}\n\n/**\n * Parses an ISO duration string or `Temporal.DurationLike` into a `Temporal.Duration`.\n *\n * @example\n * ```ts\n * parseDuration('PT2H30M').toString() // 'PT2H30M'\n * parseDuration({ hours: 2, minutes: 30 }).toString() // 'PT2H30M'\n * ```\n */\nexport function parseDuration(input: string | Temporal.DurationLike): Temporal.Duration {\n try {\n return Temporal.Duration.from(input);\n } catch {\n fail(`Invalid duration input: \"${String(input)}\". Expected an ISO 8601 duration string or Temporal.DurationLike.`);\n }\n}\n\n/**\n * Formats a duration using `Intl.DurationFormat` when available, falling back to\n * a human-readable plain-English string.\n *\n * @example\n * ```ts\n * formatDuration('PT2H30M', { locale: 'en-US', style: 'long' })\n * // '2 hours, 30 minutes'\n * ```\n */\nexport function formatDuration(input: string | Temporal.DurationLike, options: DurationFormatOptions = {}): string {\n const duration = parseDuration(input);\n const formatter = getDurationFormatter(options);\n\n if (formatter) return formatter.format(duration);\n\n return buildDurationFallback(duration);\n}\n\n/**\n * Returns the raw `Intl.DateTimeFormatPart[]` array for `input`, enabling\n * custom rendering where individual parts (year, month, day, etc.) need\n * to be styled or composed differently.\n *\n * @example\n * ```ts\n * formatParts(parseInstant('2026-03-21T10:15:30Z'), { pattern: 'medium', tz: 'UTC' })\n * // [{ type: 'month', value: 'Mar' }, { type: 'literal', value: ' ' }, ...]\n * ```\n */\nexport function formatParts(input: TimeInput, options: FormatOptions = {}): Intl.DateTimeFormatPart[] {\n const tz = options.tz ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, tz).formatToParts(new Date(toInstant(input, { tz }).epochMilliseconds));\n}\n\n/**\n * Converts a `TimeDiffResult` to a human-readable string.\n * Uses the singular unit name when value is 1, plural (unit + 's') otherwise.\n *\n * Pass `options.locale` to localize the numeric part via `Intl.NumberFormat`.\n * Unit names remain English — for fully localized output use {@link formatRelative}\n * or {@link formatDuration} instead.\n *\n * @example\n * ```ts\n * humanize({ unit: 'day', value: 1 }) // '1 day'\n * humanize({ unit: 'day', value: 3 }) // '3 days'\n * humanize({ unit: 'day', value: 3 }, { locale: 'ar' }) // '٣ days'\n * humanize({ unit: 'millisecond', value: 0 }) // '0 milliseconds'\n * ```\n */\nexport function humanize(diff: TimeDiffResult, options: { locale?: Intl.LocalesArgument } = {}): string {\n const { unit, value } = diff;\n const formatted = options.locale ? new Intl.NumberFormat(options.locale).format(value) : String(value);\n\n return `${formatted} ${value === 1 ? unit : `${unit}s`}`;\n}\n"],"mappings":"0HA2BA,IAAM,EAAsB,IAE5B,SAAS,EAAqB,EAAuB,EAAa,EAAqB,CACrF,IAAM,EAAS,EAAM,IAAI,CAAG,EAE5B,GAAI,IAAW,IAAA,GAAW,OAAO,EAEjC,GAAI,EAAM,MAAQ,EAAqB,CACrC,IAAM,EAAS,EAAM,KAAK,CAAC,CAAC,KAAK,CAAC,CAAC,MAE/B,IAAW,IAAA,IAAW,EAAM,OAAO,CAAM,CAC/C,CAEA,IAAM,EAAQ,EAAQ,EAItB,OAFA,EAAM,IAAI,EAAK,CAAK,EAEb,CACT,CAEA,IAAM,EAA4B,IAAI,IAChC,EAAgC,IAAI,IACpC,EAA2B,IAAI,IAI/B,EAAoE,CACxE,YAAa,CAAE,UAAW,OAAQ,EAClC,KAAM,CAAE,UAAW,OAAQ,UAAW,MAAO,EAC7C,OAAQ,CAAE,UAAW,SAAU,UAAW,OAAQ,EAClD,MAAO,CAAE,UAAW,QAAS,UAAW,OAAQ,EAChD,YAAa,CAAE,UAAW,OAAQ,CACpC,EAIA,SAAS,EAAqB,EAA6C,CACzE,OAAO,KAAK,UACV,OAAO,QAAQ,CAAO,CAAC,CACpB,QAAQ,EAAG,KAAW,IAAU,IAAA,EAAS,CAAC,CAC1C,MAAM,CAAC,GAAI,CAAC,KAAO,EAAE,cAAc,CAAC,CAAC,CAAC,CACtC,KAAK,CAAC,EAAK,KAAW,CAAC,EAAK,OAAO,CAAK,C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"format.cjs","names":[],"sources":["../src/format.ts"],"sourcesContent":["import { Temporal } from '@js-temporal/polyfill';\n\nimport type {\n DurationFormatOptions,\n FormatOptions,\n FormatPattern,\n RelativeFormatOptions,\n RelativeTimeInput,\n TimeDiffResult,\n TimeInput,\n TimeZoneOptions,\n} from './types';\n\nimport { toInstant, toZoned } from './_convert';\nimport { inferTimeZone } from './_tz';\nimport { fail } from './errors';\n\n// ─── Formatter types ──────────────────────────────────────────────────────────\n\ntype DurationFormatter = { format(value: Temporal.Duration): string };\ntype DurationFormatterConstructor = new (\n locales?: Intl.LocalesArgument,\n options?: { style?: 'digital' | 'long' | 'narrow' | 'short' },\n) => DurationFormatter;\n\n// ─── Formatter caches ─────────────────────────────────────────────────────────\n\nconst FORMATTER_CACHE_MAX = 128;\n\nfunction cappedGetOrCreate<V>(cache: Map<string, V>, key: string, factory: () => V): V {\n const cached = cache.get(key);\n\n if (cached !== undefined) return cached;\n\n if (cache.size >= FORMATTER_CACHE_MAX) {\n const oldest = cache.keys().next().value;\n\n if (oldest !== undefined) cache.delete(oldest);\n }\n\n const value = factory();\n\n cache.set(key, value);\n\n return value;\n}\n\nconst DATE_TIME_FORMATTER_CACHE = new Map<string, Intl.DateTimeFormat>();\nconst RELATIVE_TIME_FORMATTER_CACHE = new Map<string, Intl.RelativeTimeFormat>();\nconst DURATION_FORMATTER_CACHE = new Map<string, DurationFormatter>();\n\n// ─── Format presets ───────────────────────────────────────────────────────────\n\nconst FORMAT_PRESETS: Record<FormatPattern, Intl.DateTimeFormatOptions> = {\n 'date-only': { dateStyle: 'short' },\n long: { dateStyle: 'full', timeStyle: 'long' },\n medium: { dateStyle: 'medium', timeStyle: 'short' },\n short: { dateStyle: 'short', timeStyle: 'short' },\n 'time-only': { timeStyle: 'short' },\n};\n\n// ─── Formatter factory helpers ────────────────────────────────────────────────\n\nfunction serializeIntlOptions(options: Intl.DateTimeFormatOptions): string {\n return JSON.stringify(\n Object.entries(options)\n .filter(([, value]) => value !== undefined)\n .sort(([l], [r]) => l.localeCompare(r))\n .map(([key, value]) => [key, String(value)]),\n );\n}\n\nfunction makeFormatter(options: FormatOptions, fallbackTz?: string): Intl.DateTimeFormat {\n const timeZone = options.timeZone ?? fallbackTz;\n const locale = options.locale;\n\n if (options.intl !== undefined) {\n const cacheKey = `${String(locale ?? '')}|intl|${timeZone ?? ''}|${serializeIntlOptions(options.intl)}`;\n\n return cappedGetOrCreate(DATE_TIME_FORMATTER_CACHE, cacheKey, () => {\n const intlOptions = timeZone !== undefined ? { ...options.intl, timeZone: timeZone } : options.intl;\n\n return new Intl.DateTimeFormat(locale, intlOptions);\n });\n }\n\n const pattern = options.pattern ?? 'medium';\n const cacheKey = `${String(locale ?? '')}|${pattern}|${timeZone ?? ''}`;\n\n return cappedGetOrCreate(\n DATE_TIME_FORMATTER_CACHE,\n cacheKey,\n () => new Intl.DateTimeFormat(locale, { ...FORMAT_PRESETS[pattern], timeZone: timeZone }),\n );\n}\n\nfunction getRelativeFormatter(options: {\n locale?: Intl.LocalesArgument;\n numeric?: Intl.RelativeTimeFormatNumeric;\n style?: Intl.RelativeTimeFormatStyle;\n}): Intl.RelativeTimeFormat {\n const cacheKey = `${String(options.locale ?? '')}|${options.numeric ?? 'auto'}|${options.style ?? 'long'}`;\n\n return cappedGetOrCreate(\n RELATIVE_TIME_FORMATTER_CACHE,\n cacheKey,\n () =>\n new Intl.RelativeTimeFormat(options.locale, {\n numeric: options.numeric ?? 'auto',\n style: options.style ?? 'long',\n }),\n );\n}\n\nfunction getDurationFormatter(options: {\n locale?: Intl.LocalesArgument;\n style?: 'digital' | 'long' | 'narrow' | 'short';\n}): DurationFormatter | null {\n const IntlWithDurationFormat = Intl as typeof Intl & { DurationFormat?: DurationFormatterConstructor };\n\n if (!IntlWithDurationFormat.DurationFormat) return null;\n\n const cacheKey = `${String(options.locale ?? '')}|${options.style ?? ''}`;\n\n return cappedGetOrCreate(\n DURATION_FORMATTER_CACHE,\n cacheKey,\n () => new IntlWithDurationFormat.DurationFormat!(options.locale, { style: options.style }),\n );\n}\n\n// ─── Time scale constants ─────────────────────────────────────────────────────\n\nconst SECONDS_PER_MINUTE = 60;\nconst SECONDS_PER_HOUR = 3_600;\nconst SECONDS_PER_DAY = 86_400;\nconst SECONDS_PER_WEEK = 604_800;\nconst SECONDS_PER_MONTH = 2_629_800; // ≈ 30.4375 days × 86400\nconst SECONDS_PER_YEAR = 31_557_600; // 365.25 days × 86400\n\n// ─── Relative time helpers ────────────────────────────────────────────────────\n\nconst RELATIVE_UNITS: ReadonlyArray<{ scale: number; thresholdToPromote: number; unit: Intl.RelativeTimeFormatUnit }> =\n [\n { scale: 1, thresholdToPromote: SECONDS_PER_MINUTE, unit: 'second' },\n { scale: SECONDS_PER_MINUTE, thresholdToPromote: SECONDS_PER_HOUR / SECONDS_PER_MINUTE, unit: 'minute' },\n { scale: SECONDS_PER_HOUR, thresholdToPromote: SECONDS_PER_DAY / SECONDS_PER_HOUR, unit: 'hour' },\n { scale: SECONDS_PER_DAY, thresholdToPromote: SECONDS_PER_WEEK / SECONDS_PER_DAY, unit: 'day' },\n { scale: SECONDS_PER_WEEK, thresholdToPromote: SECONDS_PER_MONTH / SECONDS_PER_WEEK, unit: 'week' },\n { scale: SECONDS_PER_MONTH, thresholdToPromote: 12, unit: 'month' },\n { scale: SECONDS_PER_YEAR, thresholdToPromote: Number.POSITIVE_INFINITY, unit: 'year' },\n ];\n\nfunction toRelativeUnit(seconds: number): { unit: Intl.RelativeTimeFormatUnit; value: number } {\n if (!Number.isFinite(seconds)) fail('formatRelative received a non-finite time difference.');\n\n const roundedSeconds = Math.round(seconds);\n\n for (const { scale, thresholdToPromote, unit } of RELATIVE_UNITS) {\n const value = Math.round(roundedSeconds / scale);\n\n if (Math.abs(value) < thresholdToPromote) return { unit, value };\n }\n\n return { unit: 'year', value: Math.round(roundedSeconds / SECONDS_PER_YEAR) };\n}\n\n// ─── Duration fallback renderer ───────────────────────────────────────────────\n\n// All English duration unit names follow the same pluralization rule: singular = plural.slice(0, -1)\nconst DURATION_UNITS = [\n 'years',\n 'months',\n 'weeks',\n 'days',\n 'hours',\n 'minutes',\n 'seconds',\n 'milliseconds',\n 'microseconds',\n 'nanoseconds',\n] as const satisfies ReadonlyArray<keyof Temporal.Duration>;\n\n// English-only fallback; runs only when Intl.DurationFormat is unavailable in the runtime.\nfunction buildDurationFallback(duration: Temporal.Duration): string {\n const parts: string[] = [];\n\n for (const unit of DURATION_UNITS) {\n const value = Math.abs(duration[unit] as number);\n\n if (value !== 0) parts.push(`${value} ${value === 1 ? unit.slice(0, -1) : unit}`);\n }\n\n return parts.length === 0 ? '0 seconds' : parts.join(', ');\n}\n\n// ─── Private helpers ──────────────────────────────────────────────────────────\n\n/**\n * Resolves a shared display timezone for two-input range functions.\n * Throws when both inputs are `ZonedDateTime` with different zones and no `options.timeZone` override.\n */\nfunction resolveRangeTz(start: TimeInput, end: TimeInput, options: FormatOptions, caller: string): string | undefined {\n if (options.timeZone) return options.timeZone;\n\n const startTz = start instanceof Temporal.ZonedDateTime ? start.timeZoneId : undefined;\n const endTz = end instanceof Temporal.ZonedDateTime ? end.timeZoneId : undefined;\n\n if (startTz && endTz && startTz !== endTz) {\n fail(`${caller} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`);\n }\n\n return startTz ?? endTz;\n}\n\n// ─── Public API ───────────────────────────────────────────────────────────────\n\n/**\n * Formats `input` using `Intl.DateTimeFormat`. Defaults to `pattern: 'medium'`.\n *\n * Pass `intl` for full `Intl.DateTimeFormatOptions` control (mutually exclusive with `pattern`).\n * The timezone is inferred from a `ZonedDateTime` input or from `options.timeZone`.\n *\n * @example\n * ```ts\n * format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:15'\n * ```\n */\nexport function format(input: TimeInput, options: FormatOptions = {}): string {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).format(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Formats a time span between `start` and `end` using `Intl.DateTimeFormat.formatRange`.\n *\n * @example\n * ```ts\n * formatRange(start, end, { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })\n * // '21/03/2026, 10:00 – 12:00'\n * ```\n */\nexport function formatRange(start: TimeInput, end: TimeInput, options: FormatOptions = {}): string {\n const timeZone = resolveRangeTz(start, end, options, 'formatRange');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRange(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Returns the raw `Intl.DateTimeRangeFormatPart[]` array for a time span, enabling\n * fine-grained rendering of range start, end, and shared parts separately.\n *\n * @example\n * ```ts\n * formatRangeParts(start, end, { locale: 'en-US', pattern: 'short', timeZone: 'UTC' })\n * // [{ type: 'month', value: '3', source: 'startRange' }, ...]\n * ```\n */\nexport function formatRangeParts(\n start: TimeInput,\n end: TimeInput,\n options: FormatOptions = {},\n): ReturnType<Intl.DateTimeFormat['formatRangeToParts']> {\n const timeZone = resolveRangeTz(start, end, options, 'formatRangeParts');\n const formatter = makeFormatter(options, timeZone);\n\n return formatter.formatRangeToParts(\n new Date(toInstant(start, { timeZone }).epochMilliseconds),\n new Date(toInstant(end, { timeZone }).epochMilliseconds),\n );\n}\n\n/**\n * Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).\n * Requires `options.timeZone` when input is a `PlainDate` or `PlainDateTime`.\n *\n * @example\n * ```ts\n * formatInstant(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T10:15:30Z'\n * ```\n */\nexport function formatInstant(input: TimeInput, options: TimeZoneOptions = {}): string {\n return toInstant(input, options).toString();\n}\n\n/**\n * Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).\n *\n * @param options.timeZone - Required when `input` is a `PlainDate` or `PlainDateTime`.\n * Inferred automatically from a `ZonedDateTime` or `Instant` input.\n *\n * @throws {TempoError} When `input` is a `PlainDate` or `PlainDateTime` and `options.timeZone` is omitted.\n *\n * @example\n * ```ts\n * formatZoned(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { timeZone: 'Europe/Berlin' })\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]'\n *\n * formatZoned(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))\n * // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (timeZone inferred)\n * ```\n */\nexport function formatZoned(input: TimeInput, options: TimeZoneOptions = {}): string {\n const timeZone = inferTimeZone(input, options);\n\n return toZoned(input, { timeZone }).toString();\n}\n\n/**\n * Formats `input` relative to `options.base` (defaults to now) using `Intl.RelativeTimeFormat`.\n *\n * @example\n * ```ts\n * formatRelative(parse('2026-03-21T12:00:00Z', { as: 'instant' }), {\n * base: parse('2026-03-21T10:00:00Z', { as: 'instant' }),\n * locale: 'en-US',\n * numeric: 'always',\n * })\n * // 'in 2 hours'\n * ```\n */\nexport function formatRelative(input: RelativeTimeInput, options: RelativeFormatOptions = {}): string {\n const target = input instanceof Temporal.Instant ? input : input.toInstant();\n const base = options.base\n ? options.base instanceof Temporal.Instant\n ? options.base\n : options.base.toInstant()\n : Temporal.Now.instant();\n const differenceInSeconds = (target.epochMilliseconds - base.epochMilliseconds) / 1000;\n const { unit, value } = toRelativeUnit(differenceInSeconds);\n\n return getRelativeFormatter(options).format(value, unit);\n}\n\n/**\n * Parses an ISO duration string or `Temporal.DurationLike` into a `Temporal.Duration`.\n *\n * @example\n * ```ts\n * parseDuration('PT2H30M').toString() // 'PT2H30M'\n * parseDuration({ hours: 2, minutes: 30 }).toString() // 'PT2H30M'\n * ```\n */\nexport function parseDuration(input: string | Temporal.DurationLike): Temporal.Duration {\n try {\n return Temporal.Duration.from(input);\n } catch {\n fail(`Invalid duration input: \"${String(input)}\". Expected an ISO 8601 duration string or Temporal.DurationLike.`);\n }\n}\n\n/**\n * Formats a duration using `Intl.DurationFormat` when available, falling back to\n * a human-readable plain-English string.\n *\n * @example\n * ```ts\n * formatDuration('PT2H30M', { locale: 'en-US', style: 'long' })\n * // '2 hours, 30 minutes'\n * ```\n */\nexport function formatDuration(input: string | Temporal.DurationLike, options: DurationFormatOptions = {}): string {\n const duration = parseDuration(input);\n const formatter = getDurationFormatter(options);\n\n if (formatter) return formatter.format(duration);\n\n return buildDurationFallback(duration);\n}\n\n/**\n * Returns the raw `Intl.DateTimeFormatPart[]` array for `input`, enabling\n * custom rendering where individual parts (year, month, day, etc.) need\n * to be styled or composed differently.\n *\n * @example\n * ```ts\n * formatParts(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { pattern: 'medium', timeZone: 'UTC' })\n * // [{ type: 'month', value: 'Mar' }, { type: 'literal', value: ' ' }, ...]\n * ```\n */\nexport function formatParts(input: TimeInput, options: FormatOptions = {}): Intl.DateTimeFormatPart[] {\n const timeZone = options.timeZone ?? (input instanceof Temporal.ZonedDateTime ? input.timeZoneId : undefined);\n\n return makeFormatter(options, timeZone).formatToParts(new Date(toInstant(input, { timeZone }).epochMilliseconds));\n}\n\n/**\n * Converts a `TimeDiffResult` to a human-readable string.\n * Uses the singular unit name when value is 1, plural (unit + 's') otherwise.\n *\n * Pass `options.locale` to localize the numeric part via `Intl.NumberFormat`.\n * Unit names remain English — for fully localized output use {@link formatRelative}\n * or {@link formatDuration} instead.\n *\n * @example\n * ```ts\n * humanize({ unit: 'day', value: 1 }) // '1 day'\n * humanize({ unit: 'day', value: 3 }) // '3 days'\n * humanize({ unit: 'day', value: 3 }, { locale: 'ar' }) // '٣ days'\n * humanize({ unit: 'millisecond', value: 0 }) // '0 milliseconds'\n * ```\n */\nexport function humanize(diff: TimeDiffResult, options: { locale?: Intl.LocalesArgument } = {}): string {\n const { unit, value } = diff;\n const formatted = options.locale ? new Intl.N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AE,OAAM,SAAU,GADK,EAAO,kBAAoB,EAAK,mBAAqB,GACxB,EAE1D,OAAO,EAAqB,CAAO,CAAC,CAAC,OAAO,EAAO,CAAI,CACzD,CAWA,SAAgB,EAAc,EAA0D,CACtF,GAAI,CACF,OAAO,EAAA,SAAS,SAAS,KAAK,CAAK,CACrC,MAAQ,CACN,EAAA,KAAK,4BAA4B,OAAO,CAAK,EAAE,kEAAkE,CACnH,CACF,CAYA,SAAgB,EAAe,EAAuC,EAAiC,CAAC,EAAW,CACjH,IAAM,EAAW,EAAc,CAAK,EAC9B,EAAY,EAAqB,CAAO,EAI9C,OAFI,EAAkB,EAAU,OAAO,CAAQ,EAExC,EAAsB,CAAQ,CACvC,CAaA,SAAgB,EAAY,EAAkB,EAAyB,CAAC,EAA8B,CACpG,IAAM,EAAW,EAAQ,WAAa,aAAiB,EAAA,SAAS,cAAgB,EAAM,WAAa,IAAA,IAEnG,OAAO,EAAc,EAAS,CAAQ,CAAC,CAAC,cAAc,IAAI,KAAK,EAAA,UAAU,EAAO,CAAE,UAAS,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAClH,CAkBA,SAAgB,EAAS,EAAsB,EAA6C,CAAC,EAAW,CACtG,GAAM,CAAE,OAAM,SAAU,EAGxB,MAAO,GAFW,EAAQ,OAAS,IAAI,KAAK,aAAa,EAAQ,MAAM,CAAC,CAAC,OAAO,CAAK,EAAI,OAAO,CAAK,EAEjF,GAAG,IAAU,EAAI,EAAO,GAAG,EAAK,IACtD"}
|
package/dist/format.d.ts
CHANGED
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { Temporal } from '@js-temporal/polyfill';
|
|
2
|
-
import type { DurationFormatOptions, FormatOptions, RelativeFormatOptions, RelativeTimeInput, TimeDiffResult, TimeInput,
|
|
2
|
+
import type { DurationFormatOptions, FormatOptions, RelativeFormatOptions, RelativeTimeInput, TimeDiffResult, TimeInput, TimeZoneOptions } from './types';
|
|
3
3
|
/**
|
|
4
4
|
* Formats `input` using `Intl.DateTimeFormat`. Defaults to `pattern: 'medium'`.
|
|
5
5
|
*
|
|
6
6
|
* Pass `intl` for full `Intl.DateTimeFormatOptions` control (mutually exclusive with `pattern`).
|
|
7
|
-
* The timezone is inferred from a `ZonedDateTime` input or from `options.
|
|
7
|
+
* The timezone is inferred from a `ZonedDateTime` input or from `options.timeZone`.
|
|
8
8
|
*
|
|
9
9
|
* @example
|
|
10
10
|
* ```ts
|
|
11
|
-
* format(
|
|
11
|
+
* format(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })
|
|
12
12
|
* // '21/03/2026, 10:15'
|
|
13
13
|
* ```
|
|
14
14
|
*/
|
|
@@ -18,7 +18,7 @@ export declare function format(input: TimeInput, options?: FormatOptions): strin
|
|
|
18
18
|
*
|
|
19
19
|
* @example
|
|
20
20
|
* ```ts
|
|
21
|
-
* formatRange(start, end, { locale: 'en-GB', pattern: 'short',
|
|
21
|
+
* formatRange(start, end, { locale: 'en-GB', pattern: 'short', timeZone: 'UTC' })
|
|
22
22
|
* // '21/03/2026, 10:00 – 12:00'
|
|
23
23
|
* ```
|
|
24
24
|
*/
|
|
@@ -29,47 +29,47 @@ export declare function formatRange(start: TimeInput, end: TimeInput, options?:
|
|
|
29
29
|
*
|
|
30
30
|
* @example
|
|
31
31
|
* ```ts
|
|
32
|
-
* formatRangeParts(start, end, { locale: 'en-US', pattern: 'short',
|
|
32
|
+
* formatRangeParts(start, end, { locale: 'en-US', pattern: 'short', timeZone: 'UTC' })
|
|
33
33
|
* // [{ type: 'month', value: '3', source: 'startRange' }, ...]
|
|
34
34
|
* ```
|
|
35
35
|
*/
|
|
36
36
|
export declare function formatRangeParts(start: TimeInput, end: TimeInput, options?: FormatOptions): ReturnType<Intl.DateTimeFormat['formatRangeToParts']>;
|
|
37
37
|
/**
|
|
38
38
|
* Serializes `input` to a UTC ISO 8601 instant string (`2026-03-21T10:15:30Z`).
|
|
39
|
-
* Requires `options.
|
|
39
|
+
* Requires `options.timeZone` when input is a `PlainDate` or `PlainDateTime`.
|
|
40
40
|
*
|
|
41
41
|
* @example
|
|
42
42
|
* ```ts
|
|
43
|
-
* formatInstant(
|
|
43
|
+
* formatInstant(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))
|
|
44
44
|
* // '2026-03-21T10:15:30Z'
|
|
45
45
|
* ```
|
|
46
46
|
*/
|
|
47
|
-
export declare function formatInstant(input: TimeInput, options?:
|
|
47
|
+
export declare function formatInstant(input: TimeInput, options?: TimeZoneOptions): string;
|
|
48
48
|
/**
|
|
49
49
|
* Serializes `input` to a zoned ISO 8601 string (`2026-03-21T11:15:30+01:00[Europe/Berlin]`).
|
|
50
50
|
*
|
|
51
|
-
* @param options.
|
|
51
|
+
* @param options.timeZone - Required when `input` is a `PlainDate` or `PlainDateTime`.
|
|
52
52
|
* Inferred automatically from a `ZonedDateTime` or `Instant` input.
|
|
53
53
|
*
|
|
54
|
-
* @throws {TempoError} When `input` is a `PlainDate` or `PlainDateTime` and `options.
|
|
54
|
+
* @throws {TempoError} When `input` is a `PlainDate` or `PlainDateTime` and `options.timeZone` is omitted.
|
|
55
55
|
*
|
|
56
56
|
* @example
|
|
57
57
|
* ```ts
|
|
58
|
-
* formatZoned(
|
|
58
|
+
* formatZoned(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { timeZone: 'Europe/Berlin' })
|
|
59
59
|
* // '2026-03-21T11:15:30+01:00[Europe/Berlin]'
|
|
60
60
|
*
|
|
61
|
-
* formatZoned(
|
|
62
|
-
* // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (
|
|
61
|
+
* formatZoned(parse('2026-03-21T11:15:30+01:00[Europe/Berlin]', { as: 'zonedDateTime' }))
|
|
62
|
+
* // '2026-03-21T11:15:30+01:00[Europe/Berlin]' (timeZone inferred)
|
|
63
63
|
* ```
|
|
64
64
|
*/
|
|
65
|
-
export declare function formatZoned(input: TimeInput, options?:
|
|
65
|
+
export declare function formatZoned(input: TimeInput, options?: TimeZoneOptions): string;
|
|
66
66
|
/**
|
|
67
67
|
* Formats `input` relative to `options.base` (defaults to now) using `Intl.RelativeTimeFormat`.
|
|
68
68
|
*
|
|
69
69
|
* @example
|
|
70
70
|
* ```ts
|
|
71
|
-
* formatRelative(
|
|
72
|
-
* base:
|
|
71
|
+
* formatRelative(parse('2026-03-21T12:00:00Z', { as: 'instant' }), {
|
|
72
|
+
* base: parse('2026-03-21T10:00:00Z', { as: 'instant' }),
|
|
73
73
|
* locale: 'en-US',
|
|
74
74
|
* numeric: 'always',
|
|
75
75
|
* })
|
|
@@ -105,7 +105,7 @@ export declare function formatDuration(input: string | Temporal.DurationLike, op
|
|
|
105
105
|
*
|
|
106
106
|
* @example
|
|
107
107
|
* ```ts
|
|
108
|
-
* formatParts(
|
|
108
|
+
* formatParts(parse('2026-03-21T10:15:30Z', { as: 'instant' }), { pattern: 'medium', timeZone: 'UTC' })
|
|
109
109
|
* // [{ type: 'month', value: 'Mar' }, { type: 'literal', value: ' ' }, ...]
|
|
110
110
|
* ```
|
|
111
111
|
*/
|
package/dist/format.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjD,OAAO,KAAK,EACV,qBAAqB,EACrB,aAAa,EAEb,qBAAqB,EACrB,iBAAiB,EACjB,cAAc,EACd,SAAS,EACT,
|
|
1
|
+
{"version":3,"file":"format.d.ts","sourceRoot":"","sources":["../src/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AAEjD,OAAO,KAAK,EACV,qBAAqB,EACrB,aAAa,EAEb,qBAAqB,EACrB,iBAAiB,EACjB,cAAc,EACd,SAAS,EACT,eAAe,EAChB,MAAM,SAAS,CAAC;AA8MjB;;;;;;;;;;;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AM,CAAC,EAAE,IAAI,CAAC,eAAe,CAAA;CAAO,GAAG,MAAM,CAKtG"}
|
package/dist/format.js
CHANGED
|
@@ -34,7 +34,7 @@ function d(e) {
|
|
|
34
34
|
return JSON.stringify(Object.entries(e).filter(([, e]) => e !== void 0).sort(([e], [t]) => e.localeCompare(t)).map(([e, t]) => [e, String(t)]));
|
|
35
35
|
}
|
|
36
36
|
function f(e, t) {
|
|
37
|
-
let n = e.
|
|
37
|
+
let n = e.timeZone ?? t, r = e.locale;
|
|
38
38
|
if (e.intl !== void 0) return o(s, `${String(r ?? "")}|intl|${n ?? ""}|${d(e.intl)}`, () => {
|
|
39
39
|
let t = n === void 0 ? e.intl : {
|
|
40
40
|
...e.intl,
|
|
@@ -131,28 +131,28 @@ function w(e) {
|
|
|
131
131
|
return t.length === 0 ? "0 seconds" : t.join(", ");
|
|
132
132
|
}
|
|
133
133
|
function T(t, n, r, a) {
|
|
134
|
-
if (r.
|
|
134
|
+
if (r.timeZone) return r.timeZone;
|
|
135
135
|
let o = t instanceof i.ZonedDateTime ? t.timeZoneId : void 0, s = n instanceof i.ZonedDateTime ? n.timeZoneId : void 0;
|
|
136
|
-
return o && s && o !== s && e(`${a} received ZonedDateTime inputs with different time zones. Pass options.
|
|
136
|
+
return o && s && o !== s && e(`${a} received ZonedDateTime inputs with different time zones. Pass options.timeZone explicitly.`), o ?? s;
|
|
137
137
|
}
|
|
138
138
|
function E(e, t = {}) {
|
|
139
|
-
let r = t.
|
|
140
|
-
return f(t, r).format(new Date(n(e, {
|
|
139
|
+
let r = t.timeZone ?? (e instanceof i.ZonedDateTime ? e.timeZoneId : void 0);
|
|
140
|
+
return f(t, r).format(new Date(n(e, { timeZone: r }).epochMilliseconds));
|
|
141
141
|
}
|
|
142
142
|
function D(e, t, r = {}) {
|
|
143
143
|
let i = T(e, t, r, "formatRange");
|
|
144
|
-
return f(r, i).formatRange(new Date(n(e, {
|
|
144
|
+
return f(r, i).formatRange(new Date(n(e, { timeZone: i }).epochMilliseconds), new Date(n(t, { timeZone: i }).epochMilliseconds));
|
|
145
145
|
}
|
|
146
146
|
function O(e, t, r = {}) {
|
|
147
147
|
let i = T(e, t, r, "formatRangeParts");
|
|
148
|
-
return f(r, i).formatRangeToParts(new Date(n(e, {
|
|
148
|
+
return f(r, i).formatRangeToParts(new Date(n(e, { timeZone: i }).epochMilliseconds), new Date(n(t, { timeZone: i }).epochMilliseconds));
|
|
149
149
|
}
|
|
150
150
|
function k(e, t = {}) {
|
|
151
151
|
return n(e, t).toString();
|
|
152
152
|
}
|
|
153
153
|
function A(e, n = {}) {
|
|
154
154
|
let i = t(e, n);
|
|
155
|
-
return r(e, {
|
|
155
|
+
return r(e, { timeZone: i }).toString();
|
|
156
156
|
}
|
|
157
157
|
function j(e, t = {}) {
|
|
158
158
|
let n = e instanceof i.Instant ? e : e.toInstant(), r = t.base ? t.base instanceof i.Instant ? t.base : t.base.toInstant() : i.Now.instant(), { unit: a, value: o } = S((n.epochMilliseconds - r.epochMilliseconds) / 1e3);
|
|
@@ -170,8 +170,8 @@ function N(e, t = {}) {
|
|
|
170
170
|
return r ? r.format(n) : w(n);
|
|
171
171
|
}
|
|
172
172
|
function P(e, t = {}) {
|
|
173
|
-
let r = t.
|
|
174
|
-
return f(t, r).formatToParts(new Date(n(e, {
|
|
173
|
+
let r = t.timeZone ?? (e instanceof i.ZonedDateTime ? e.timeZoneId : void 0);
|
|
174
|
+
return f(t, r).formatToParts(new Date(n(e, { timeZone: r }).epochMilliseconds));
|
|
175
175
|
}
|
|
176
176
|
function F(e, t = {}) {
|
|
177
177
|
let { unit: n, value: r } = e;
|