temporal-fmt 0.9.2 → 0.9.4
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 +480 -9
- package/dist/calendarUtils.cjs +259 -4
- package/dist/calendarUtils.cjs.map +1 -1
- package/dist/calendarUtils.js +33 -1
- package/dist/chunk-4N3WCGEY.js +183 -0
- package/dist/{chunk-4JWGUR4O.js.map → chunk-4N3WCGEY.js.map} +1 -1
- package/dist/chunk-5UTV5VP6.js +984 -0
- package/dist/chunk-5UTV5VP6.js.map +1 -0
- package/dist/chunk-ACKKWH5Z.js +578 -0
- package/dist/{chunk-2JHEV7ZF.js.map → chunk-ACKKWH5Z.js.map} +1 -1
- package/dist/chunk-EGUUO6LE.js +439 -0
- package/dist/chunk-EGUUO6LE.js.map +1 -0
- package/dist/chunk-FBPHNRVW.js +2939 -0
- package/dist/chunk-FBPHNRVW.js.map +1 -0
- package/dist/chunk-GPB4JHGI.js +65 -0
- package/dist/chunk-GPB4JHGI.js.map +1 -0
- package/dist/chunk-H7YQX25T.js +170 -0
- package/dist/{chunk-J2AQNXF2.js.map → chunk-H7YQX25T.js.map} +1 -1
- package/dist/chunk-HXY2GUUM.js +182 -0
- package/dist/{chunk-EHLRZULM.js.map → chunk-HXY2GUUM.js.map} +1 -1
- package/dist/chunk-L24NPTAJ.js +328 -0
- package/dist/chunk-L24NPTAJ.js.map +1 -0
- package/dist/chunk-M3GDTHMT.js +169 -0
- package/dist/chunk-M3GDTHMT.js.map +1 -0
- package/dist/chunk-MKPDLQKD.js +51 -0
- package/dist/chunk-MKPDLQKD.js.map +1 -0
- package/dist/chunk-TSLPIURC.js +242 -0
- package/dist/{chunk-VQXUMFB2.js.map → chunk-TSLPIURC.js.map} +1 -1
- package/dist/chunk-UOPAV3WX.js +75 -0
- package/dist/chunk-UOPAV3WX.js.map +1 -0
- package/dist/chunk-VNIUIQA4.js +398 -0
- package/dist/chunk-VNIUIQA4.js.map +1 -0
- package/dist/chunk-YEUASGDK.js +9 -0
- package/dist/chunk-YEUASGDK.js.map +1 -0
- package/dist/chunk-ZQZF5EXW.js +29 -0
- package/dist/chunk-ZQZF5EXW.js.map +1 -0
- package/dist/config.d.cts +4 -2
- package/dist/config.d.ts +4 -2
- package/dist/duration.cjs +638 -26
- package/dist/duration.cjs.map +1 -1
- package/dist/duration.js +28 -1
- package/dist/format.cjs +833 -35
- package/dist/format.cjs.map +1 -1
- package/dist/format.js +20 -1
- package/dist/index.cjs +7698 -163
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +108 -24
- package/dist/index.d.ts +108 -24
- package/dist/index.js +1536 -58
- package/dist/index.js.map +1 -1
- package/dist/interval.cjs +5480 -35
- package/dist/interval.cjs.map +1 -1
- package/dist/interval.js +46 -1
- package/dist/localeRegistry.cjs +375 -32
- package/dist/localeRegistry.cjs.map +1 -1
- package/dist/localeRegistry.js +11 -1
- package/dist/modApi.d.cts +131 -0
- package/dist/modApi.d.ts +131 -0
- package/dist/parse.cjs +1797 -70
- package/dist/parse.cjs.map +1 -1
- package/dist/parse.js +20 -1
- package/dist/pattern.d.cts +1 -0
- package/dist/pattern.d.ts +1 -0
- package/dist/recurrence.cjs +452 -20
- package/dist/recurrence.cjs.map +1 -1
- package/dist/recurrence.js +19 -1
- package/dist/relativeTime.cjs +268 -21
- package/dist/relativeTime.cjs.map +1 -1
- package/dist/relativeTime.js +14 -1
- package/dist/runtime.d.cts +201 -0
- package/dist/runtime.d.ts +201 -0
- package/dist/timezone.cjs +387 -20
- package/dist/timezone.cjs.map +1 -1
- package/dist/timezone.js +26 -1
- package/package.json +4 -6
- package/scripts/cli.mjs +27 -5
- package/dist/chunk-2JHEV7ZF.js +0 -7
- package/dist/chunk-3MZLTVP3.js +0 -2
- package/dist/chunk-3MZLTVP3.js.map +0 -1
- package/dist/chunk-4JWGUR4O.js +0 -11
- package/dist/chunk-5U5WJ465.js +0 -36
- package/dist/chunk-5U5WJ465.js.map +0 -1
- package/dist/chunk-C5YESWFT.js +0 -2
- package/dist/chunk-C5YESWFT.js.map +0 -1
- package/dist/chunk-C6ZZ62ET.js +0 -2
- package/dist/chunk-C6ZZ62ET.js.map +0 -1
- package/dist/chunk-EHLRZULM.js +0 -5
- package/dist/chunk-F4RGUDA3.js +0 -2
- package/dist/chunk-F4RGUDA3.js.map +0 -1
- package/dist/chunk-J2AQNXF2.js +0 -2
- package/dist/chunk-NBXF7V5B.js +0 -2
- package/dist/chunk-NBXF7V5B.js.map +0 -1
- package/dist/chunk-R52YOKI3.js +0 -7
- package/dist/chunk-R52YOKI3.js.map +0 -1
- package/dist/chunk-UJR6DHXY.js +0 -2
- package/dist/chunk-UJR6DHXY.js.map +0 -1
- package/dist/chunk-VQXUMFB2.js +0 -21
- package/dist/chunk-XH46JNPK.js +0 -2
- package/dist/chunk-XH46JNPK.js.map +0 -1
- package/dist/chunk-YB6YAG7E.js +0 -35
- package/dist/chunk-YB6YAG7E.js.map +0 -1
- package/dist/chunk-ZGMTY52O.js +0 -2
- package/dist/chunk-ZGMTY52O.js.map +0 -1
package/dist/parse.cjs
CHANGED
|
@@ -1,74 +1,1801 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/parse.ts
|
|
21
|
+
var parse_exports = {};
|
|
22
|
+
__export(parse_exports, {
|
|
23
|
+
compileParser: () => compileParser,
|
|
24
|
+
parse: () => parse,
|
|
25
|
+
parseToParts: () => parseToParts,
|
|
26
|
+
safeParse: () => safeParse,
|
|
27
|
+
tryParse: () => tryParse
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(parse_exports);
|
|
30
|
+
|
|
31
|
+
// src/temporalProvider.ts
|
|
32
|
+
var injectedTemporal;
|
|
33
|
+
var onTemporalChanged = [];
|
|
34
|
+
function subscribeToTemporalChanges(listener) {
|
|
35
|
+
onTemporalChanged.push(listener);
|
|
36
|
+
}
|
|
37
|
+
function resolveTemporal() {
|
|
38
|
+
return injectedTemporal ?? globalThis.Temporal;
|
|
39
|
+
}
|
|
40
|
+
function getTemporal() {
|
|
41
|
+
const temporal = resolveTemporal();
|
|
42
|
+
if (!temporal) {
|
|
43
|
+
throw new Error(
|
|
44
|
+
"temporal-fmt: parse() needs a Temporal implementation to construct its result. Call setTemporal(Temporal) once at startup, or assign one to globalThis.Temporal (native on Node 26+, or a polyfill like temporal-polyfill)."
|
|
45
|
+
);
|
|
46
|
+
}
|
|
47
|
+
return temporal;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// src/errors.ts
|
|
51
|
+
var TemporalFmtError = class extends Error {
|
|
52
|
+
code;
|
|
53
|
+
input;
|
|
54
|
+
format;
|
|
55
|
+
token;
|
|
56
|
+
position;
|
|
57
|
+
expected;
|
|
58
|
+
actual;
|
|
59
|
+
reason;
|
|
60
|
+
constructor(message, fields) {
|
|
61
|
+
super(message);
|
|
62
|
+
this.name = "TemporalFmtError";
|
|
63
|
+
this.code = fields.code;
|
|
64
|
+
this.input = fields.input;
|
|
65
|
+
this.format = fields.format;
|
|
66
|
+
this.token = fields.token;
|
|
67
|
+
this.position = fields.position;
|
|
68
|
+
this.expected = fields.expected;
|
|
69
|
+
this.actual = fields.actual;
|
|
70
|
+
this.reason = fields.reason;
|
|
71
|
+
const capture = Error.captureStackTrace;
|
|
72
|
+
if (typeof capture === "function") {
|
|
73
|
+
capture(this, this.constructor);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
// lets callers just call err.toJSON() for logging. plain Error doesn't
|
|
77
|
+
// serialize its non-enumerable fields on its own, so this picks them
|
|
78
|
+
// up explicitly
|
|
79
|
+
toJSON() {
|
|
80
|
+
return {
|
|
81
|
+
name: this.name,
|
|
82
|
+
message: this.message,
|
|
83
|
+
code: this.code,
|
|
84
|
+
input: this.input,
|
|
85
|
+
format: this.format,
|
|
86
|
+
token: this.token,
|
|
87
|
+
position: this.position,
|
|
88
|
+
expected: this.expected,
|
|
89
|
+
actual: this.actual,
|
|
90
|
+
reason: this.reason
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
var FormatSyntaxError = class extends TemporalFmtError {
|
|
95
|
+
constructor(fields) {
|
|
96
|
+
const { message, ...rest } = fields;
|
|
97
|
+
super(
|
|
98
|
+
message ?? `format string "${fields.format ?? ""}" has a syntax error${fields.reason ? `: ${fields.reason}` : ""}.`,
|
|
99
|
+
{ code: "FORMAT_SYNTAX_ERROR", ...rest }
|
|
100
|
+
);
|
|
101
|
+
this.name = "FormatSyntaxError";
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
var UnknownTokenError = class extends TemporalFmtError {
|
|
105
|
+
constructor(fields) {
|
|
106
|
+
const { message, ...rest } = fields;
|
|
107
|
+
super(
|
|
108
|
+
message ?? `token "${fields.token ?? ""}" is not a recognized temporal-fmt token${fields.format ? ` in format string "${fields.format}"` : ""}.`,
|
|
109
|
+
{ code: "UNKNOWN_TOKEN", ...rest }
|
|
110
|
+
);
|
|
111
|
+
this.name = "UnknownTokenError";
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
var ParseMismatchError = class extends TemporalFmtError {
|
|
115
|
+
constructor(fields) {
|
|
116
|
+
const { message, ...rest } = fields;
|
|
117
|
+
super(
|
|
118
|
+
message ?? `input "${fields.input ?? ""}" does not match format "${fields.format ?? ""}"${fields.reason ? `: ${fields.reason}` : ""}.`,
|
|
119
|
+
{ code: "PARSE_MISMATCH", ...rest }
|
|
120
|
+
);
|
|
121
|
+
this.name = "ParseMismatchError";
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
var InvalidDateError = class extends TemporalFmtError {
|
|
125
|
+
constructor(fields) {
|
|
126
|
+
const { message, ...rest } = fields;
|
|
127
|
+
super(
|
|
128
|
+
message ?? `input "${fields.input ?? ""}" does not describe a valid date${fields.reason ? `: ${fields.reason}` : ""}.`,
|
|
129
|
+
{ code: "INVALID_DATE", ...rest }
|
|
130
|
+
);
|
|
131
|
+
this.name = "InvalidDateError";
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
/* c8 ignore start @preserve -- InvalidTimeError is part of the public
|
|
135
|
+
error-class surface (exported from index.ts, code 'INVALID_TIME') but
|
|
136
|
+
nothing in this package actually constructs one. went and checked
|
|
137
|
+
whether it could get wired in the same way InvalidTimeZoneError just
|
|
138
|
+
was (see parse.ts's zzz-validation loop) — does hour/minute/second have
|
|
139
|
+
a post-match semantic range check the way zone ids do? nope.
|
|
7
140
|
pattern.ts's regex fragments for HH/H/hh/h/mm/m/ss/s already enforce
|
|
8
|
-
their valid ranges at the regex level (e.g. HH is
|
|
9
|
-
which can't match "99"
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
redundant check purely to give this class a body.
|
|
13
|
-
until the library actually
|
|
141
|
+
their valid ranges right at the regex level (e.g. HH is
|
|
142
|
+
'(?:[01]\d|2[0-3])', which literally can't match "99"), so an
|
|
143
|
+
out-of-range time just gets rejected as a plain shape mismatch before
|
|
144
|
+
any semantic check would even run. no live gap to hook this into
|
|
145
|
+
without inventing a redundant check purely to give this class a body.
|
|
146
|
+
leaving it unconstructed until the library actually hits a real
|
|
147
|
+
invalid-time case worth reporting */
|
|
148
|
+
/* c8 ignore stop @preserve */
|
|
149
|
+
var InvalidOffsetError = class extends TemporalFmtError {
|
|
150
|
+
constructor(fields) {
|
|
151
|
+
const { message, ...rest } = fields;
|
|
152
|
+
super(
|
|
153
|
+
message ?? `offset "${fields.actual ?? ""}" is invalid${fields.reason ? `: ${fields.reason}` : ""}.`,
|
|
154
|
+
{ code: "INVALID_OFFSET", ...rest }
|
|
155
|
+
);
|
|
156
|
+
this.name = "InvalidOffsetError";
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
var InvalidTimeZoneError = class extends TemporalFmtError {
|
|
160
|
+
constructor(fields) {
|
|
161
|
+
const { message, ...rest } = fields;
|
|
162
|
+
super(
|
|
163
|
+
message ?? `time zone "${fields.actual ?? ""}" is not a recognized IANA time zone or fixed offset${fields.reason ? `: ${fields.reason}` : ""}.`,
|
|
164
|
+
{ code: "INVALID_TIME_ZONE", ...rest }
|
|
165
|
+
);
|
|
166
|
+
this.name = "InvalidTimeZoneError";
|
|
167
|
+
}
|
|
168
|
+
};
|
|
169
|
+
/* c8 ignore start @preserve -- InvalidCalendarError is part of the
|
|
14
170
|
public error-class surface (exported from index.ts, code
|
|
15
|
-
'INVALID_CALENDAR') but
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
171
|
+
'INVALID_CALENDAR') but same story as InvalidTimeError above — nothing
|
|
172
|
+
in this package constructs one. checked for a wiring opportunity the
|
|
173
|
+
same way: there's no user-supplied calendar identifier anywhere in the
|
|
174
|
+
library that we'd validate against a supported list. resolveCalendar()
|
|
19
175
|
in parse.ts derives the calendar entirely from Intl's own resolution
|
|
20
|
-
of the locale string — it's never handed an arbitrary "calendar"
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
parameter that could be invalid
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
real check rather than an assertion. *//* c8 ignore start @preserve */if(o===-1)throw new N({message:`temporal-fmt: locale produced no "${n}" part while building match vocabulary.`});/* c8 ignore stop @preserve */let a=r[o].value,s=r[o-1],m=r[o+1];return s?.type==="literal"&&!/\s/.test(s.value)&&(a=s.value+a),m?.type==="literal"&&!/\s/.test(m.value)&&(a=a+m.value),a}function ie(e,t,n){let r=new Map;for(let o=0;o<e.length;o++){let a=r.get(e[o]);if(a!==void 0)throw new Error(`temporal-fmt: locale "${n}" renders ${t} index ${a} and ${o} identically ("${e[o]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`);r.set(e[o],o)}}function M(e){let t=C(e);return Le.get(t)}function V(e){he(e);let t=C(e),n=Le.get(t);if(n)return n;let r=W.get(t);if(r)return r;let o=Q(e),a=new Intl.DateTimeFormat(o,{month:"long",timeZone:"UTC"}),s=new Intl.DateTimeFormat(o,{month:"short",timeZone:"UTC"}),m=[],p=[];for(let y=0;y<12;y++){let b=new Date(Date.UTC(2020,y,1));m.push(z(a,b,"month")),p.push(z(s,b,"month"))}ie(m,"MMMM month",e),ie(p,"MMM month",e);let l=new Intl.DateTimeFormat(o,{weekday:"long",timeZone:"UTC"}),c=new Intl.DateTimeFormat(o,{weekday:"short",timeZone:"UTC"}),i=[],d=[];for(let y=0;y<7;y++){let b=new Date(Date.UTC(2024,0,1+y));i.push(z(l,b,"weekday")),d.push(z(c,b,"weekday"))}ie(i,"EEEE weekday",e),ie(d,"EEE weekday",e);let u=new Intl.DateTimeFormat(o,{hour:"numeric",hour12:!0,timeZone:"UTC"}),h=z(u,new Date(Date.UTC(2020,0,1,1)),"dayPeriod"),k=z(u,new Date(Date.UTC(2020,0,1,13)),"dayPeriod"),$=[...new Set([h,k])],O={monthLong:m,monthShort:p,weekdayLong:i,weekdayShort:d,dayPeriod:$};if(W.size>=rt){let y=W.keys().next().value;y!==void 0&&W.delete(y)}return W.set(t,O),O}var ot=[0,31,59,90,120,151,181,212,243,273,304,334];function Pe(e){return e%4===0&&e%100!==0||e%400===0}function j(e){return Pe(e)?366:365}function q(e,t,n){let r=ot[t-1]+n;return t>2&&Pe(e)&&(r+=1),r}var ye=2e3;function at(e){let t=0;if(e>=ye)for(let r=ye;r<e;r++)t+=j(r);else for(let r=e;r<ye;r++)t-=j(r);return((5+t)%7+7)%7+1}function we(e,t,n,r){let a=q(e,t,n)+(4-r),s,m;a<1?(s=e-1,m=a+j(s)):a>j(e)?(s=e+1,m=a-j(e)):(s=e,m=a);let l=1+(4-at(s)+7)%7,c=1+Math.floor((m-l)/7);return{isoYear:s,week:c}}function g(e,t){let n=e<0,r=String(Math.abs(e)).padStart(t,"0");return n?"-"+r:r}g.fraction=function(t,n){let r=t.millisecond*1e6+(t.microsecond??0)*1e3+(t.nanosecond??0);return g(r,9).slice(0,n)};var me="en-US",B=new Map,st=500;function Ie(e,t){let n=JSON.stringify([C(e),t]),r=B.get(n);if(r)return r;if(B.size>=st){let o=B.keys().next().value;o!==void 0&&B.delete(o)}try{r=new Intl.DateTimeFormat(Q(e),t)}catch(o){throw new N({actual:e,reason:o.message})}return B.set(n,r),r}var J;De(()=>{J=void 0});function it(){if(J===void 0){J=!1;try{let e=se();new Intl.DateTimeFormat("en-US",{day:"numeric"}).formatToParts(e.PlainDate.from({year:1970,month:1,day:1})),J=!0}catch{}}return J}function ee(e,t,n,r){let o=e?.calendarId,a={...n,calendar:o&&o!=="iso8601"?o:"gregory"},s=e.toLocaleString;if(typeof s!="function"||s===Object.prototype.toLocaleString)throw new Error(`temporal-fmt: locale-aware part "${r}" needs a value that implements toLocaleString (a real Temporal object). A plain field bag cannot render locale-aware names \u2014 pass a Temporal.PlainDate/PlainDateTime/ZonedDateTime.`);if(!it())try{return s.call(e,Q(t),a)}catch(y){throw y instanceof RangeError?new N({actual:t,reason:y.message}):y}let{toInstant:m,timeZoneId:p}=e,l=typeof m=="function"&&typeof p=="string",c=l?e.toInstant():e,i={...a,...l?{timeZone:p}:{}},u=Ie(t,i).formatToParts(c),h=u.findIndex(y=>y.type===r);if(h===-1)throw new Error(`temporal-fmt: locale "${t}" produced no "${r}" part for this token. This usually means the Temporal object is missing the field the token needs.`);let k=u[h].value,$=u[h-1],O=u[h+1];return $?.type==="literal"&&!/\s/.test($.value)&&(k=$.value+k),O?.type==="literal"&&!/\s/.test(O.value)&&(k=k+O.value),k}function mt(e,t){let n=M(t);if(n)return e<12?n.dayPeriod[0]:n.dayPeriod[1];let r=new Date(Date.UTC(1970,0,1,e)),a=Ie(t,{hour:"numeric",hour12:!0,timeZone:"UTC"}).formatToParts(r).find(s=>s.type==="dayPeriod");if(!a)throw new Error(`temporal-fmt: locale "${t}" produced no "dayPeriod" part for token "a".`);return a.value}function v(e,t,n,r,o,a){return o&&a!==void 0&&a>=0&&a<o.length?o[a]:ee(e,t,n,r)}function Z(e,t){if(e==="+00:00"&&(t==="X"||t==="XX"||t==="XXX"))return"Z";let n=e[0],r=e.slice(1,3),o=e.slice(4,6);switch(t){case"X":case"x":return o==="00"?`${n}${r}`:`${n}${r}${o}`;case"XX":case"xx":return`${n}${r}${o}`;case"XXX":case"xxx":return`${n}${r}:${o}`}}var Fe=[["yyyy",e=>g(e.year,4),"year"],["yy",e=>{if(e.year<0)throw new Error(`temporal-fmt: token "yy" doesn't support negative years (got ${e.year}), since truncating to 2 digits would make it indistinguishable from a positive year. Use "yyyy" instead.`);return g(e.year%100,2)},"year"],["MMMM",(e,t)=>{let n=M(t);return v(e,t,{month:"long"},"month",n?.monthLong,e.month-1)},"month"],["MMM",(e,t)=>{let n=M(t);return v(e,t,{month:"short"},"month",n?.monthShort,e.month-1)},"month"],["MM",e=>g(e.month,2),"month"],["M",e=>String(e.month),"month"],["dd",e=>g(e.day,2),"day"],["d",e=>String(e.day),"day"],["EEEE",(e,t)=>{let n=M(t);return v(e,t,{weekday:"long"},"weekday",n?.weekdayLong,e.dayOfWeek-1)},"dayOfWeek"],["EEE",(e,t)=>{let n=M(t);return v(e,t,{weekday:"short"},"weekday",n?.weekdayShort,e.dayOfWeek-1)},"dayOfWeek"],["HH",e=>g(e.hour,2),"hour"],["H",e=>String(e.hour),"hour"],["hh",e=>g(e.hour%12||12,2),"hour"],["h",e=>String(e.hour%12||12),"hour"],["mm",e=>g(e.minute,2),"minute"],["m",e=>String(e.minute),"minute"],["ss",e=>g(e.second,2),"second"],["s",e=>String(e.second),"second"],["SSSSSSSSS",e=>g.fraction(e,9),"millisecond"],["SSSSSSSS",e=>g.fraction(e,8),"millisecond"],["SSSSSSS",e=>g.fraction(e,7),"millisecond"],["SSSSSS",e=>g.fraction(e,6),"millisecond"],["SSSSS",e=>g.fraction(e,5),"millisecond"],["SSSS",e=>g.fraction(e,4),"millisecond"],["SSS",e=>g.fraction(e,3),"millisecond"],["SS",e=>g.fraction(e,2),"millisecond"],["S",e=>g.fraction(e,1),"millisecond"],["a",(e,t)=>mt(e.hour,t),"hour"],["zzz",e=>e.timeZoneId,"timeZoneId"],["xxx",e=>Z(e.offset,"xxx"),"offset"],["xx",e=>Z(e.offset,"xx"),"offset"],["X",e=>Z(e.offset,"X"),"offset"],["XX",e=>Z(e.offset,"XX"),"offset"],["XXX",e=>Z(e.offset,"XXX"),"offset"],["x",e=>Z(e.offset,"x"),"offset"],["do",e=>{let t=e.day,n=t%10,r=t%100;return r>=11&&r<=13?t+"th":n===1?t+"st":n===2?t+"nd":n===3?t+"rd":t+"th"},"day"],["Q",e=>String(Math.ceil(e.month/3)),"month"],["QQQ",e=>"Q"+Math.ceil(e.month/3),"month"],["ww",e=>{let{week:t}=we(e.year,e.month,e.day,e.dayOfWeek);return g(t,2)},"dayOfWeek"],["RRRR",e=>{let{isoYear:t}=we(e.year,e.month,e.day,e.dayOfWeek);return g(t,4)},"dayOfWeek"],["D",e=>String(q(e.year,e.month,e.day)),"day"],["DD",e=>g(q(e.year,e.month,e.day),2),"day"],["DDD",e=>g(q(e.year,e.month,e.day),3),"day"],["LLLL",(e,t)=>{let n=M(t);return v(e,t,{month:"long"},"month",n?.monthLong,e.month-1)},"month"],["LLL",(e,t)=>{let n=M(t);return v(e,t,{month:"short"},"month",n?.monthShort,e.month-1)},"month"],["cccc",(e,t)=>{let n=M(t);return v(e,t,{weekday:"long"},"weekday",n?.weekdayLong,e.dayOfWeek-1)},"dayOfWeek"],["ccc",(e,t)=>{let n=M(t);return v(e,t,{weekday:"short"},"weekday",n?.weekdayShort,e.dayOfWeek-1)},"dayOfWeek"],["GGGG",(e,t)=>ee(e,t,{era:"long"},"era"),"year"],["G",(e,t)=>ee(e,t,{era:"short"},"era"),"year"],["zzzz",(e,t)=>ee(e,t,{timeZoneName:"longGeneric"},"timeZoneName"),"timeZoneId"],["z",(e,t)=>ee(e,t,{timeZoneName:"short"},"timeZoneName"),"timeZoneId"]];var ct=Fe.map(([e])=>e).sort((e,t)=>t.length-e.length);function ve(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(r==="'"){if(e[n+1]==="'"){Se(t,"'"),n+=2;continue}let a=n+1,s="",m=!1;for(;a<e.length;){if(e[a]==="'"){if(e[a+1]==="'"){s+="'",a+=2;continue}m=!0,a+=1;break}s+=e[a],a+=1}if(!m)throw new S({format:e,message:`temporal-fmt: unterminated quote in format string "${e}"`});Se(t,s),n=a;continue}let o=ct.find(a=>e.startsWith(a,n));if(o){let a=o[o.length-1];if(e[n+o.length]===a){let s=n+o.length;for(;e[s]===a;)s+=1;throw new I({format:e,token:e.slice(n,s),message:`temporal-fmt: "${e.slice(n,s)}" in format string "${e}" isn't a recognized token \u2014 did you mean "${o}"?`})}t.push({kind:"token",value:o}),n+=o.length;continue}Se(t,r),n+=1}return t}function Se(e,t){let n=e[e.length-1];n&&n.kind==="literal"?n.value+=t:e.push({kind:"literal",value:t})}function ut(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function te(e,t=!1){let n=e.map(ut);return t?`(?:${n.map(dt).join("|")})`:`(?:${n.join("|")})`}function dt(e){return e.replace(/[a-zA-Z]/g,t=>`[${t.toLowerCase()}${t.toUpperCase()}]`)}var lt="(?:UTC|[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?|[A-Za-z_]+(?:[+-]\\d{1,2})?(?:\\/[A-Za-z0-9_+-]+)*)",gt={X:"(?:Z|[+-]\\d{2}(?:\\d{2})?)",XX:"(?:Z|[+-]\\d{4})",XXX:"(?:Z|[+-]\\d{2}:\\d{2})",x:"[+-]\\d{2}(?:\\d{2})?",xx:"[+-]\\d{4}",xxx:"[+-]\\d{2}:\\d{2}"};function ft(){return lt}var ce;function pt(){return ce||(ce=new Set(Intl.supportedValuesOf("timeZone")),ce.add("UTC")),ce}var ht=/^[+-]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?$/;function ke(e){return ht.test(e)||pt().has(e)}var yt={yy:"\\d{2}",MM:"(?:0[1-9]|1[0-2])",M:"(?:1[0-2]|[1-9])",dd:"(?:0[1-9]|[12]\\d|3[01])",d:"(?:[12]\\d|3[01]|[1-9])",HH:"(?:[01]\\d|2[0-3])",H:"(?:1\\d|2[0-3]|[0-9])",hh:"(?:0[1-9]|1[0-2])",h:"(?:1[0-2]|[1-9])",mm:"(?:[0-5]\\d)",m:"(?:[1-5]\\d|[0-9])",ss:"(?:[0-5]\\d)",s:"(?:[1-5]\\d|[0-9])",SSSSSSSSS:"\\d{9}",SSSSSSSS:"\\d{8}",SSSSSSS:"\\d{7}",SSSSSS:"\\d{6}",SSSSS:"\\d{5}",SSSS:"\\d{4}",SSS:"\\d{3}",SS:"\\d{2}",S:"\\d",Q:"[1-4]"},wt="Q[1-4]",St=new Set(["do","ww","RRRR","D","DD","DDD","LLLL","LLL","cccc","ccc","GGGG","G","zzzz","z"]),kt="-?\\d{4}",bt="-?\\d{4,}",be=new Set(["yyyy","yy","MM","M","dd","d","HH","H","hh","h","mm","m","ss","s","SSSSSSSSS","SSSSSSSS","SSSSSSS","SSSSSS","SSSSS","SSSS","SSS","SS","S"]);function ue(e,t,n){if(e==="yyyy")return n!==void 0&&be.has(n)?kt:bt;let r=yt[e];if(r)return r;if(e==="QQQ")return wt;if(St.has(e))throw new I({token:e,message:`temporal-fmt: token "${e}" is format-only \u2014 it can't be parsed back into a value. Use a different token in the parse format string (e.g. "d" for "do", "MM" for "ww").`});let o=V(t);switch(e){case"MMMM":return te(o.monthLong);case"MMM":return te(o.monthShort);case"EEEE":return te(o.weekdayLong);case"EEE":return te(o.weekdayShort);case"a":return te(o.dayPeriod,!0);case"zzz":return ft();case"X":case"XX":case"XXX":case"x":case"xx":case"xxx":return gt[e];default:throw new I({token:e,message:`temporal-fmt: unknown token "${e}"`})}}var Ae=new Set(["M","d","H","h","m","s"]),xt={M:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],d:[{digits:1,min:1,max:9},{digits:2,min:10,max:31}],H:[{digits:1,min:0,max:9},{digits:2,min:10,max:23}],h:[{digits:1,min:1,max:9},{digits:2,min:10,max:12}],m:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}],s:[{digits:1,min:0,max:9},{digits:2,min:10,max:59}]};function xe(e,t){let n=new Map;function r(o,a){let s=`${o}:${a}`,m=n.get(s);if(m)return m;if(o===t.length){let i=a===e.length?[[]]:[];return n.set(s,i),i}let p=t[o],l=xt[p];/* c8 ignore start @preserve -- defensive guard, not reachable through
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
176
|
+
of the locale string — it's never handed an arbitrary "calendar" value
|
|
177
|
+
a caller could actually get wrong. no live input to reject here.
|
|
178
|
+
leaving it unconstructed until the library accepts an actual calendar
|
|
179
|
+
parameter that could be invalid */
|
|
180
|
+
/* c8 ignore stop @preserve */
|
|
181
|
+
var AmbiguousInputError = class extends TemporalFmtError {
|
|
182
|
+
constructor(fields) {
|
|
183
|
+
const { message, ...rest } = fields;
|
|
184
|
+
super(
|
|
185
|
+
message ?? `input "${fields.input ?? ""}" is ambiguous${fields.reason ? `: ${fields.reason}` : ""}.`,
|
|
186
|
+
{ code: "AMBIGUOUS_INPUT", ...rest }
|
|
187
|
+
);
|
|
188
|
+
this.name = "AmbiguousInputError";
|
|
189
|
+
}
|
|
190
|
+
};
|
|
191
|
+
var InvalidLocaleError = class extends TemporalFmtError {
|
|
192
|
+
constructor(fields) {
|
|
193
|
+
const { message, ...rest } = fields;
|
|
194
|
+
super(
|
|
195
|
+
message ?? `locale "${fields.actual ?? ""}" is not a valid BCP-47 tag${fields.reason ? `: ${fields.reason}` : ""}.`,
|
|
196
|
+
{ code: "INVALID_LOCALE", ...rest }
|
|
197
|
+
);
|
|
198
|
+
this.name = "InvalidLocaleError";
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
/* c8 ignore start @preserve -- unreachable from the current test suite,
|
|
202
|
+
see rationale above */
|
|
203
|
+
function wrapUntypedError(err, context) {
|
|
204
|
+
const msg = err.message;
|
|
205
|
+
if (/unknown token|isn't a recognized token/.test(msg)) {
|
|
206
|
+
return new UnknownTokenError({ input: context.input, format: context.format, reason: msg });
|
|
207
|
+
}
|
|
208
|
+
if (/ambiguous/i.test(msg)) {
|
|
209
|
+
return new AmbiguousInputError({ input: context.input, format: context.format, reason: msg });
|
|
210
|
+
}
|
|
211
|
+
if (/offset/.test(msg) && /out of range|exceeds|doesn't match the shape/i.test(msg)) {
|
|
212
|
+
return new InvalidOffsetError({ input: context.input, format: context.format, reason: msg });
|
|
213
|
+
}
|
|
214
|
+
if (/no valid pattern matches/i.test(msg)) {
|
|
215
|
+
return new ParseMismatchError({ input: context.input, format: context.format, reason: msg });
|
|
216
|
+
}
|
|
217
|
+
if (/doesn't describe a valid date\/time|incomplete date|weekday token|quarter token/.test(msg)) {
|
|
218
|
+
return new InvalidDateError({ input: context.input, format: context.format, reason: msg });
|
|
219
|
+
}
|
|
220
|
+
const lowerMsg = msg.toLowerCase();
|
|
221
|
+
const mentionsLocale = lowerMsg.includes("locale");
|
|
222
|
+
if (mentionsLocale && (lowerMsg.includes("produced no") || lowerMsg.includes("not a valid")) || lowerMsg.includes("cutoffs must be")) {
|
|
223
|
+
return new InvalidLocaleError({ input: context.input, format: context.format, reason: msg });
|
|
224
|
+
}
|
|
225
|
+
if (/format string exceeds maximum length|input exceeds maximum length|unterminated quote|isn't a recognized token/i.test(msg)) {
|
|
226
|
+
return new FormatSyntaxError({ input: context.input, format: context.format, reason: msg });
|
|
227
|
+
}
|
|
228
|
+
return new ParseMismatchError({ input: context.input, format: context.format, reason: msg });
|
|
229
|
+
}
|
|
230
|
+
/* c8 ignore stop @preserve */
|
|
231
|
+
|
|
232
|
+
// src/localeVocab.ts
|
|
233
|
+
var customVocabs = /* @__PURE__ */ new Map();
|
|
234
|
+
var onVocabChanged = [];
|
|
235
|
+
function subscribeToVocabChanges(listener) {
|
|
236
|
+
onVocabChanged.push(listener);
|
|
237
|
+
}
|
|
238
|
+
function normalizeLocaleTag(locale) {
|
|
239
|
+
return locale.replace(/_/g, "-");
|
|
240
|
+
}
|
|
241
|
+
var canonicalKeyCache = /* @__PURE__ */ new Map();
|
|
242
|
+
var MAX_CANONICAL_KEY_CACHE = 500;
|
|
243
|
+
function canonicalCacheKey(locale) {
|
|
244
|
+
const hit = canonicalKeyCache.get(locale);
|
|
245
|
+
if (hit !== void 0) return hit;
|
|
246
|
+
let key;
|
|
247
|
+
try {
|
|
248
|
+
key = new Intl.Locale(locale.replace(/_/g, "-")).toString().toLowerCase();
|
|
249
|
+
} catch {
|
|
250
|
+
key = locale;
|
|
251
|
+
}
|
|
252
|
+
if (canonicalKeyCache.size >= MAX_CANONICAL_KEY_CACHE) {
|
|
253
|
+
const oldestKey = canonicalKeyCache.keys().next().value;
|
|
254
|
+
if (oldestKey !== void 0) canonicalKeyCache.delete(oldestKey);
|
|
255
|
+
}
|
|
256
|
+
canonicalKeyCache.set(locale, key);
|
|
257
|
+
return key;
|
|
258
|
+
}
|
|
259
|
+
function assertValidLocaleTag(locale) {
|
|
260
|
+
try {
|
|
261
|
+
new Intl.Locale(normalizeLocaleTag(locale));
|
|
262
|
+
} catch {
|
|
263
|
+
throw new InvalidLocaleError({
|
|
264
|
+
actual: locale,
|
|
265
|
+
reason: "not a valid BCP-47 locale tag"
|
|
266
|
+
});
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
var vocabCache = /* @__PURE__ */ new Map();
|
|
270
|
+
var MAX_VOCAB_CACHE_SIZE = 500;
|
|
271
|
+
function partValue(formatter, date, type) {
|
|
272
|
+
const parts = formatter.formatToParts(date);
|
|
273
|
+
const index = parts.findIndex((p) => p.type === type);
|
|
274
|
+
/* c8 ignore start @preserve -- defensive guard against a real but
|
|
275
|
+
unreproducible failure mode: an Intl implementation that omits the
|
|
276
|
+
requested part type entirely for some locale. Checked every locale
|
|
277
|
+
with unusual dayPeriod/weekday/month rendering available in this
|
|
278
|
+
runtime's ICU data (ja-JP, zh-CN, th-TH, he-IL, ar-SA, ko-KR, fa-IR)
|
|
279
|
+
against the exact formatter options getLocaleVocab uses (notably
|
|
280
|
+
hour12: true for the dayPeriod formatter, which is what makes every
|
|
281
|
+
locale here actually emit a dayPeriod part — omitting it is what
|
|
282
|
+
produced a false "gap" during investigation). None omit their part
|
|
283
|
+
on this runtime. A different ICU version or a non-Node Intl
|
|
284
|
+
implementation could plausibly behave differently, so this stays a
|
|
285
|
+
real check rather than an assertion. */
|
|
286
|
+
/* c8 ignore start @preserve */
|
|
287
|
+
if (index === -1) {
|
|
288
|
+
throw new InvalidLocaleError({
|
|
289
|
+
message: `temporal-fmt: locale produced no "${type}" part while building match vocabulary.`
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/* c8 ignore stop @preserve */
|
|
293
|
+
let value = parts[index].value;
|
|
294
|
+
const prev = parts[index - 1];
|
|
295
|
+
const next = parts[index + 1];
|
|
296
|
+
if (prev?.type === "literal" && !/\s/.test(prev.value)) value = prev.value + value;
|
|
297
|
+
if (next?.type === "literal" && !/\s/.test(next.value)) value = value + next.value;
|
|
298
|
+
return value;
|
|
299
|
+
}
|
|
300
|
+
function assertNoCollision(names, label, locale) {
|
|
301
|
+
const seen = /* @__PURE__ */ new Map();
|
|
302
|
+
for (let i = 0; i < names.length; i++) {
|
|
303
|
+
const prior = seen.get(names[i]);
|
|
304
|
+
if (prior !== void 0) {
|
|
305
|
+
throw new Error(
|
|
306
|
+
`temporal-fmt: locale "${locale}" renders ${label} index ${prior} and ${i} identically ("${names[i]}"). parse() can't reliably tell these apart for this locale/token, so this combination isn't supported.`
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
seen.set(names[i], i);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
function getCustomVocab(locale) {
|
|
313
|
+
const cacheKey = canonicalCacheKey(locale);
|
|
314
|
+
return customVocabs.get(cacheKey);
|
|
315
|
+
}
|
|
316
|
+
function getLocaleVocab(locale) {
|
|
317
|
+
assertValidLocaleTag(locale);
|
|
318
|
+
const cacheKey = canonicalCacheKey(locale);
|
|
319
|
+
const custom = customVocabs.get(cacheKey);
|
|
320
|
+
if (custom) {
|
|
321
|
+
return custom;
|
|
322
|
+
}
|
|
323
|
+
const cached = vocabCache.get(cacheKey);
|
|
324
|
+
if (cached) {
|
|
325
|
+
return cached;
|
|
326
|
+
}
|
|
327
|
+
const intlLocale = normalizeLocaleTag(locale);
|
|
328
|
+
const monthLongFmt = new Intl.DateTimeFormat(intlLocale, { month: "long", timeZone: "UTC" });
|
|
329
|
+
const monthShortFmt = new Intl.DateTimeFormat(intlLocale, { month: "short", timeZone: "UTC" });
|
|
330
|
+
const monthLong = [];
|
|
331
|
+
const monthShort = [];
|
|
332
|
+
for (let m = 0; m < 12; m++) {
|
|
333
|
+
const date = new Date(Date.UTC(2020, m, 1));
|
|
334
|
+
monthLong.push(partValue(monthLongFmt, date, "month"));
|
|
335
|
+
monthShort.push(partValue(monthShortFmt, date, "month"));
|
|
336
|
+
}
|
|
337
|
+
assertNoCollision(monthLong, "MMMM month", locale);
|
|
338
|
+
assertNoCollision(monthShort, "MMM month", locale);
|
|
339
|
+
const weekdayLongFmt = new Intl.DateTimeFormat(intlLocale, { weekday: "long", timeZone: "UTC" });
|
|
340
|
+
const weekdayShortFmt = new Intl.DateTimeFormat(intlLocale, { weekday: "short", timeZone: "UTC" });
|
|
341
|
+
const weekdayLong = [];
|
|
342
|
+
const weekdayShort = [];
|
|
343
|
+
for (let d = 0; d < 7; d++) {
|
|
344
|
+
const date = new Date(Date.UTC(2024, 0, 1 + d));
|
|
345
|
+
weekdayLong.push(partValue(weekdayLongFmt, date, "weekday"));
|
|
346
|
+
weekdayShort.push(partValue(weekdayShortFmt, date, "weekday"));
|
|
347
|
+
}
|
|
348
|
+
assertNoCollision(weekdayLong, "EEEE weekday", locale);
|
|
349
|
+
assertNoCollision(weekdayShort, "EEE weekday", locale);
|
|
350
|
+
const dayPeriodFmt = new Intl.DateTimeFormat(intlLocale, { hour: "numeric", hour12: true, timeZone: "UTC" });
|
|
351
|
+
const am = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 1)), "dayPeriod");
|
|
352
|
+
const pm = partValue(dayPeriodFmt, new Date(Date.UTC(2020, 0, 1, 13)), "dayPeriod");
|
|
353
|
+
const dayPeriod = [.../* @__PURE__ */ new Set([am, pm])];
|
|
354
|
+
const vocab = { monthLong, monthShort, weekdayLong, weekdayShort, dayPeriod };
|
|
355
|
+
if (vocabCache.size >= MAX_VOCAB_CACHE_SIZE) {
|
|
356
|
+
const oldestKey = vocabCache.keys().next().value;
|
|
357
|
+
if (oldestKey !== void 0) vocabCache.delete(oldestKey);
|
|
358
|
+
}
|
|
359
|
+
vocabCache.set(cacheKey, vocab);
|
|
360
|
+
return vocab;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// src/isoWeek.ts
|
|
364
|
+
var CUMULATIVE_DAYS_BY_MONTH = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
|
|
365
|
+
function isGregorianLeapYear(year) {
|
|
366
|
+
return year % 4 === 0 && year % 100 !== 0 || year % 400 === 0;
|
|
367
|
+
}
|
|
368
|
+
function daysInYear(year) {
|
|
369
|
+
return isGregorianLeapYear(year) ? 366 : 365;
|
|
370
|
+
}
|
|
371
|
+
function dayOfYear(year, month, day) {
|
|
372
|
+
let doy = CUMULATIVE_DAYS_BY_MONTH[month - 1] + day;
|
|
373
|
+
if (month > 2 && isGregorianLeapYear(year)) doy += 1;
|
|
374
|
+
return doy;
|
|
375
|
+
}
|
|
376
|
+
var REFERENCE_YEAR = 2e3;
|
|
377
|
+
function dayOfWeekOfJan1(year) {
|
|
378
|
+
let offset = 0;
|
|
379
|
+
if (year >= REFERENCE_YEAR) {
|
|
380
|
+
for (let y = REFERENCE_YEAR; y < year; y++) offset += daysInYear(y);
|
|
381
|
+
} else {
|
|
382
|
+
for (let y = year; y < REFERENCE_YEAR; y++) offset -= daysInYear(y);
|
|
383
|
+
}
|
|
384
|
+
const zeroIndexed = ((6 - 1 + offset) % 7 + 7) % 7;
|
|
385
|
+
return zeroIndexed + 1;
|
|
386
|
+
}
|
|
387
|
+
function isoWeekYearAndWeek(year, month, day, dayOfWeek) {
|
|
388
|
+
const doy = dayOfYear(year, month, day);
|
|
389
|
+
const thursdayDoyRelative = doy + (4 - dayOfWeek);
|
|
390
|
+
let isoYear;
|
|
391
|
+
let thursdayDoy;
|
|
392
|
+
if (thursdayDoyRelative < 1) {
|
|
393
|
+
isoYear = year - 1;
|
|
394
|
+
thursdayDoy = thursdayDoyRelative + daysInYear(isoYear);
|
|
395
|
+
} else if (thursdayDoyRelative > daysInYear(year)) {
|
|
396
|
+
isoYear = year + 1;
|
|
397
|
+
thursdayDoy = thursdayDoyRelative - daysInYear(year);
|
|
398
|
+
} else {
|
|
399
|
+
isoYear = year;
|
|
400
|
+
thursdayDoy = thursdayDoyRelative;
|
|
401
|
+
}
|
|
402
|
+
const jan1Dow = dayOfWeekOfJan1(isoYear);
|
|
403
|
+
const firstThursdayDoy = 1 + (4 - jan1Dow + 7) % 7;
|
|
404
|
+
const week = 1 + Math.floor((thursdayDoy - firstThursdayDoy) / 7);
|
|
405
|
+
return { isoYear, week };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
// src/tokens.ts
|
|
409
|
+
function pad(n, len) {
|
|
410
|
+
const negative = n < 0;
|
|
411
|
+
const digits = String(Math.abs(n)).padStart(len, "0");
|
|
412
|
+
return negative ? "-" + digits : digits;
|
|
413
|
+
}
|
|
414
|
+
pad.fraction = function formatFraction(t, width) {
|
|
415
|
+
const nanoOfSecond = t.millisecond * 1e6 + (t.microsecond ?? 0) * 1e3 + (t.nanosecond ?? 0);
|
|
416
|
+
return pad(nanoOfSecond, 9).slice(0, width);
|
|
417
|
+
};
|
|
418
|
+
var DEFAULT_LOCALE = "en-US";
|
|
419
|
+
var formatterCache = /* @__PURE__ */ new Map();
|
|
420
|
+
var MAX_CACHE_SIZE = 500;
|
|
421
|
+
function getFormatter(locale, options) {
|
|
422
|
+
const key = JSON.stringify([canonicalCacheKey(locale), options]);
|
|
423
|
+
let formatter = formatterCache.get(key);
|
|
424
|
+
if (formatter) {
|
|
425
|
+
return formatter;
|
|
426
|
+
}
|
|
427
|
+
if (formatterCache.size >= MAX_CACHE_SIZE) {
|
|
428
|
+
const oldestKey = formatterCache.keys().next().value;
|
|
429
|
+
if (oldestKey !== void 0) formatterCache.delete(oldestKey);
|
|
430
|
+
}
|
|
431
|
+
try {
|
|
432
|
+
formatter = new Intl.DateTimeFormat(normalizeLocaleTag(locale), options);
|
|
433
|
+
} catch (err) {
|
|
434
|
+
throw new InvalidLocaleError({ actual: locale, reason: err.message });
|
|
435
|
+
}
|
|
436
|
+
formatterCache.set(key, formatter);
|
|
437
|
+
return formatter;
|
|
438
|
+
}
|
|
439
|
+
var nativeSupport;
|
|
440
|
+
subscribeToTemporalChanges(() => {
|
|
441
|
+
nativeSupport = void 0;
|
|
442
|
+
});
|
|
443
|
+
function intlSupportsNativeTemporal() {
|
|
444
|
+
if (nativeSupport === void 0) {
|
|
445
|
+
nativeSupport = false;
|
|
446
|
+
try {
|
|
447
|
+
const temporal = getTemporal();
|
|
448
|
+
new Intl.DateTimeFormat("en-US", { day: "numeric" }).formatToParts(temporal.PlainDate.from({ year: 1970, month: 1, day: 1 }));
|
|
449
|
+
nativeSupport = true;
|
|
450
|
+
} catch {
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
return nativeSupport;
|
|
454
|
+
}
|
|
455
|
+
function intlPart(temporal, locale, options, partType) {
|
|
456
|
+
const calendar = temporal?.calendarId;
|
|
457
|
+
const formatterOptions = {
|
|
458
|
+
...options,
|
|
459
|
+
calendar: calendar && calendar !== "iso8601" ? calendar : "gregory"
|
|
460
|
+
};
|
|
461
|
+
const ls = temporal.toLocaleString;
|
|
462
|
+
if (typeof ls !== "function" || ls === Object.prototype.toLocaleString) {
|
|
463
|
+
throw new Error(
|
|
464
|
+
`temporal-fmt: locale-aware part "${partType}" needs a value that implements toLocaleString (a real Temporal object). A plain field bag cannot render locale-aware names \u2014 pass a Temporal.PlainDate/PlainDateTime/ZonedDateTime.`
|
|
465
|
+
);
|
|
466
|
+
}
|
|
467
|
+
if (!intlSupportsNativeTemporal()) {
|
|
468
|
+
try {
|
|
469
|
+
return ls.call(temporal, normalizeLocaleTag(locale), formatterOptions);
|
|
470
|
+
} catch (err) {
|
|
471
|
+
if (err instanceof RangeError) {
|
|
472
|
+
throw new InvalidLocaleError({ actual: locale, reason: err.message });
|
|
473
|
+
}
|
|
474
|
+
throw err;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
const { toInstant, timeZoneId } = temporal;
|
|
478
|
+
const isZoned = typeof toInstant === "function" && typeof timeZoneId === "string";
|
|
479
|
+
const intlSafeTemporal = isZoned ? temporal.toInstant() : temporal;
|
|
480
|
+
const nativeOptions = {
|
|
481
|
+
...formatterOptions,
|
|
482
|
+
...isZoned ? { timeZone: timeZoneId } : {}
|
|
483
|
+
};
|
|
484
|
+
const formatter = getFormatter(locale, nativeOptions);
|
|
485
|
+
const parts = formatter.formatToParts(intlSafeTemporal);
|
|
486
|
+
const index = parts.findIndex((p) => p.type === partType);
|
|
487
|
+
if (index === -1) {
|
|
488
|
+
throw new Error(
|
|
489
|
+
`temporal-fmt: locale "${locale}" produced no "${partType}" part for this token. This usually means the Temporal object is missing the field the token needs.`
|
|
490
|
+
);
|
|
491
|
+
}
|
|
492
|
+
let value = parts[index].value;
|
|
493
|
+
const prev = parts[index - 1];
|
|
494
|
+
const next = parts[index + 1];
|
|
495
|
+
if (prev?.type === "literal" && !/\s/.test(prev.value)) value = prev.value + value;
|
|
496
|
+
if (next?.type === "literal" && !/\s/.test(next.value)) value = value + next.value;
|
|
497
|
+
return value;
|
|
498
|
+
}
|
|
499
|
+
function dayPeriodPart(hour, locale) {
|
|
500
|
+
const custom = getCustomVocab(locale);
|
|
501
|
+
if (custom) {
|
|
502
|
+
return hour < 12 ? custom.dayPeriod[0] : custom.dayPeriod[1];
|
|
503
|
+
}
|
|
504
|
+
const date = new Date(Date.UTC(1970, 0, 1, hour));
|
|
505
|
+
const formatter = getFormatter(locale, { hour: "numeric", hour12: true, timeZone: "UTC" });
|
|
506
|
+
const part = formatter.formatToParts(date).find((p) => p.type === "dayPeriod");
|
|
507
|
+
if (!part) {
|
|
508
|
+
throw new Error(`temporal-fmt: locale "${locale}" produced no "dayPeriod" part for token "a".`);
|
|
509
|
+
}
|
|
510
|
+
return part.value;
|
|
511
|
+
}
|
|
512
|
+
function localeAwareName(temporal, locale, options, partType, customArray, customIndex) {
|
|
513
|
+
if (customArray && customIndex !== void 0 && customIndex >= 0 && customIndex < customArray.length) {
|
|
514
|
+
return customArray[customIndex];
|
|
515
|
+
}
|
|
516
|
+
return intlPart(temporal, locale, options, partType);
|
|
517
|
+
}
|
|
518
|
+
function formatOffset(offset, variant) {
|
|
519
|
+
if (offset === "+00:00" && (variant === "X" || variant === "XX" || variant === "XXX")) {
|
|
520
|
+
return "Z";
|
|
521
|
+
}
|
|
522
|
+
if (offset.length > 6) {
|
|
523
|
+
if (variant === "xxx") {
|
|
524
|
+
return offset;
|
|
525
|
+
}
|
|
526
|
+
throw new Error(
|
|
527
|
+
`temporal-fmt: token "${variant}" cannot represent the offset "${offset}", which has a seconds component. None of the X/XX/XXX/x/xx tokens support offset seconds; use "xxx" instead, which formats the full offset unchanged.`
|
|
528
|
+
);
|
|
529
|
+
}
|
|
530
|
+
const sign = offset[0];
|
|
531
|
+
const hours = offset.slice(1, 3);
|
|
532
|
+
const minutes = offset.slice(4, 6);
|
|
533
|
+
switch (variant) {
|
|
534
|
+
case "X":
|
|
535
|
+
case "x":
|
|
536
|
+
return minutes === "00" ? `${sign}${hours}` : `${sign}${hours}${minutes}`;
|
|
537
|
+
case "XX":
|
|
538
|
+
case "xx":
|
|
539
|
+
return `${sign}${hours}${minutes}`;
|
|
540
|
+
case "XXX":
|
|
541
|
+
case "xxx":
|
|
542
|
+
return `${sign}${hours}:${minutes}`;
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
var TOKENS = [
|
|
546
|
+
["yyyy", (t) => pad(t.year, 4), "year"],
|
|
547
|
+
["yy", (t) => {
|
|
548
|
+
if (t.year < 0) {
|
|
549
|
+
throw new Error(
|
|
550
|
+
`temporal-fmt: token "yy" doesn't support negative years (got ${t.year}), since truncating to 2 digits would make it indistinguishable from a positive year. Use "yyyy" instead.`
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
return pad(t.year % 100, 2);
|
|
554
|
+
}, "year"],
|
|
555
|
+
// Unpadded year — no minimum width, unlike yyyy's fixed 4 digits.
|
|
556
|
+
// pad(n, 0) still does the right thing here: Math.abs(n) with no
|
|
557
|
+
// padStart floor just yields the plain digit string, and the sign
|
|
558
|
+
// handling (split off before padding) already covers negative years,
|
|
559
|
+
// so this doesn't need its own sign branch the way "yy" does.
|
|
560
|
+
["y", (t) => pad(t.year, 0), "year"],
|
|
561
|
+
["MMMM", (t, locale) => {
|
|
562
|
+
const custom = getCustomVocab(locale);
|
|
563
|
+
return localeAwareName(t, locale, { month: "long" }, "month", custom?.monthLong, t.month - 1);
|
|
564
|
+
}, "month"],
|
|
565
|
+
["MMM", (t, locale) => {
|
|
566
|
+
const custom = getCustomVocab(locale);
|
|
567
|
+
return localeAwareName(t, locale, { month: "short" }, "month", custom?.monthShort, t.month - 1);
|
|
568
|
+
}, "month"],
|
|
569
|
+
["MM", (t) => pad(t.month, 2), "month"],
|
|
570
|
+
["M", (t) => String(t.month), "month"],
|
|
571
|
+
["dd", (t) => pad(t.day, 2), "day"],
|
|
572
|
+
["d", (t) => String(t.day), "day"],
|
|
573
|
+
["EEEE", (t, locale) => {
|
|
574
|
+
const custom = getCustomVocab(locale);
|
|
575
|
+
return localeAwareName(t, locale, { weekday: "long" }, "weekday", custom?.weekdayLong, t.dayOfWeek - 1);
|
|
576
|
+
}, "dayOfWeek"],
|
|
577
|
+
["EEE", (t, locale) => {
|
|
578
|
+
const custom = getCustomVocab(locale);
|
|
579
|
+
return localeAwareName(t, locale, { weekday: "short" }, "weekday", custom?.weekdayShort, t.dayOfWeek - 1);
|
|
580
|
+
}, "dayOfWeek"],
|
|
581
|
+
["HH", (t) => pad(t.hour, 2), "hour"],
|
|
582
|
+
["H", (t) => String(t.hour), "hour"],
|
|
583
|
+
["hh", (t) => pad(t.hour % 12 || 12, 2), "hour"],
|
|
584
|
+
["h", (t) => String(t.hour % 12 || 12), "hour"],
|
|
585
|
+
["mm", (t) => pad(t.minute, 2), "minute"],
|
|
586
|
+
["m", (t) => String(t.minute), "minute"],
|
|
587
|
+
["ss", (t) => pad(t.second, 2), "second"],
|
|
588
|
+
["s", (t) => String(t.second), "second"],
|
|
589
|
+
// Fractional-second tokens, S through SSSSSSSSS (1-9 digits). Each token
|
|
590
|
+
// formats a slice of the same underlying nanosecond-of-second value —
|
|
591
|
+
// combining millisecond/microsecond/nanosecond into one 9-digit number
|
|
592
|
+
// and truncating to the token's width — so "SSS" keeps meaning exactly
|
|
593
|
+
// what it always meant (3-digit milliseconds) while wider tokens expose
|
|
594
|
+
// the precision Temporal actually carries. formatFraction below is the
|
|
595
|
+
// shared implementation; see its comment for the truncate-not-round
|
|
596
|
+
// rule and why.
|
|
597
|
+
["SSSSSSSSS", (t) => pad.fraction(t, 9), "millisecond"],
|
|
598
|
+
["SSSSSSSS", (t) => pad.fraction(t, 8), "millisecond"],
|
|
599
|
+
["SSSSSSS", (t) => pad.fraction(t, 7), "millisecond"],
|
|
600
|
+
["SSSSSS", (t) => pad.fraction(t, 6), "millisecond"],
|
|
601
|
+
["SSSSS", (t) => pad.fraction(t, 5), "millisecond"],
|
|
602
|
+
["SSSS", (t) => pad.fraction(t, 4), "millisecond"],
|
|
603
|
+
["SSS", (t) => pad.fraction(t, 3), "millisecond"],
|
|
604
|
+
["SS", (t) => pad.fraction(t, 2), "millisecond"],
|
|
605
|
+
["S", (t) => pad.fraction(t, 1), "millisecond"],
|
|
606
|
+
// dayPeriod text is locale-specific (AM/PM in en-US, م/ص in ar-EG) but
|
|
607
|
+
// still needs .hour on the input to compute which period it is
|
|
608
|
+
["a", (t, locale) => dayPeriodPart(t.hour, locale), "hour"],
|
|
609
|
+
["zzz", (t) => t.timeZoneId, "timeZoneId"],
|
|
610
|
+
// Numeric UTC offset tokens (date-fns/Unicode-LDML family). Only
|
|
611
|
+
// ZonedDateTime carries an offset, so the field check in format() throws
|
|
612
|
+
// the same "requires offset, which this Temporal object doesn't have"
|
|
613
|
+
// error zzz throws on PlainDate/PlainTime/PlainDateTime — same
|
|
614
|
+
// validation path, just a different field name. See formatOffset above
|
|
615
|
+
// for the per-variant width and Z/numeric distinction.
|
|
616
|
+
["xxx", (t) => formatOffset(t.offset, "xxx"), "offset"],
|
|
617
|
+
["xx", (t) => formatOffset(t.offset, "xx"), "offset"],
|
|
618
|
+
["X", (t) => formatOffset(t.offset, "X"), "offset"],
|
|
619
|
+
["XX", (t) => formatOffset(t.offset, "XX"), "offset"],
|
|
620
|
+
["XXX", (t) => formatOffset(t.offset, "XXX"), "offset"],
|
|
621
|
+
["x", (t) => formatOffset(t.offset, "x"), "offset"],
|
|
622
|
+
// Ordinal day (1st, 2nd, 3rd, ... 21st). English suffix rules only —
|
|
623
|
+
// locale-aware ordinals ("2." in de-DE, "2日" in ja-JP) are out of scope,
|
|
624
|
+
// since the rest of this library routes locale-specific names through
|
|
625
|
+
// Intl.DateTimeFormat, and Intl has no part type for ordinals. Format-only:
|
|
626
|
+
// the suffix isn't structurally distinguishable from a literal in a parse
|
|
627
|
+
// context (a "st"/"nd"/"rd"/"th" suffix isn't a digit and would collide
|
|
628
|
+
// with any adjacent literal text), so there's no good way to read it back.
|
|
629
|
+
["do", (t) => {
|
|
630
|
+
const day = t.day;
|
|
631
|
+
const lastDigit = day % 10;
|
|
632
|
+
const lastTwoDigits = day % 100;
|
|
633
|
+
if (lastTwoDigits >= 11 && lastTwoDigits <= 13) {
|
|
634
|
+
return day + "th";
|
|
635
|
+
}
|
|
636
|
+
if (lastDigit === 1) return day + "st";
|
|
637
|
+
if (lastDigit === 2) return day + "nd";
|
|
638
|
+
if (lastDigit === 3) return day + "rd";
|
|
639
|
+
return day + "th";
|
|
640
|
+
}, "day"],
|
|
641
|
+
// Quarter computed from month: 1-3=Q1, 4-6=Q2, 7-9=Q3, 10-12=Q4.
|
|
642
|
+
// `Q` is plain numeric, `QQQ` renders as "Q3" — same convention as
|
|
643
|
+
// date-fns's `Q` and `QQQ` for parity with the most common prior art.
|
|
644
|
+
// Both format and parse; parse() cross-checks Q/QQQ against the parsed
|
|
645
|
+
// month in the same spirit as the EEEE-vs-date cross-check.
|
|
646
|
+
["Q", (t) => String(Math.ceil(t.month / 3)), "month"],
|
|
647
|
+
["QQQ", (t) => "Q" + Math.ceil(t.month / 3), "month"],
|
|
648
|
+
// ISO 8601 week and week-numbering year. Both are format-only — parsing
|
|
649
|
+
// "ww"/"RRRR" back into a real date requires resolving an ISO week + a
|
|
650
|
+
// weekday (or some other disambiguator) to a specific date, which is a
|
|
651
|
+
// different parsing surface than the token-based parse() here. The
|
|
652
|
+
// ISO-week year (RRRR) can differ from the calendar year at the boundary:
|
|
653
|
+
// Dec 29-31 often belong to week 1 of the *next* year; Jan 1-3 often
|
|
654
|
+
// belong to week 52/53 of the *previous* year. See isoWeekYearAndWeek().
|
|
655
|
+
["ww", (t) => {
|
|
656
|
+
const { week } = isoWeekYearAndWeek(t.year, t.month, t.day, t.dayOfWeek);
|
|
657
|
+
return pad(week, 2);
|
|
658
|
+
}, "dayOfWeek"],
|
|
659
|
+
["RRRR", (t) => {
|
|
660
|
+
const { isoYear } = isoWeekYearAndWeek(t.year, t.month, t.day, t.dayOfWeek);
|
|
661
|
+
return pad(isoYear, 4);
|
|
662
|
+
}, "dayOfWeek"],
|
|
663
|
+
// Day of year — number of days since Jan 1 (1-366). Three widths:
|
|
664
|
+
// D — unpadded (1, 2, 366)
|
|
665
|
+
// DD — 2-digit minimum (zero-padded if <100)
|
|
666
|
+
// DDD — 3-digit zero-padded (001, 002, 366)
|
|
667
|
+
// Format-only — parsing day-of-year requires resolving against a year,
|
|
668
|
+
// which is a different shape from the token-based parse() surface.
|
|
669
|
+
// The dayOfYearHelper() in calendarUtils.ts covers the same field for
|
|
670
|
+
// callers who need the numeric value.
|
|
671
|
+
["D", (t) => String(dayOfYear(t.year, t.month, t.day)), "day"],
|
|
672
|
+
["DD", (t) => pad(dayOfYear(t.year, t.month, t.day), 2), "day"],
|
|
673
|
+
["DDD", (t) => pad(dayOfYear(t.year, t.month, t.day), 3), "day"],
|
|
674
|
+
// Stand-alone month — uses Intl's stand-alone form. In most locales
|
|
675
|
+
// (en, fr, de, es) this is identical to MMMM/MMM. In Slavic/Baltic
|
|
676
|
+
// locales (cs, sk, pl, ru) the stand-alone form differs from the
|
|
677
|
+
// format form (nominative vs genitive case). LLLL = long, LLL = short.
|
|
678
|
+
["LLLL", (t, locale) => {
|
|
679
|
+
const custom = getCustomVocab(locale);
|
|
680
|
+
return localeAwareName(t, locale, { month: "long" }, "month", custom?.monthLong, t.month - 1);
|
|
681
|
+
}, "month"],
|
|
682
|
+
["LLL", (t, locale) => {
|
|
683
|
+
const custom = getCustomVocab(locale);
|
|
684
|
+
return localeAwareName(t, locale, { month: "short" }, "month", custom?.monthShort, t.month - 1);
|
|
685
|
+
}, "month"],
|
|
686
|
+
// Stand-alone weekday — same pattern as stand-alone month but for
|
|
687
|
+
// weekday names. cccc = long, ccc = short.
|
|
688
|
+
["cccc", (t, locale) => {
|
|
689
|
+
const custom = getCustomVocab(locale);
|
|
690
|
+
return localeAwareName(t, locale, { weekday: "long" }, "weekday", custom?.weekdayLong, t.dayOfWeek - 1);
|
|
691
|
+
}, "dayOfWeek"],
|
|
692
|
+
["ccc", (t, locale) => {
|
|
693
|
+
const custom = getCustomVocab(locale);
|
|
694
|
+
return localeAwareName(t, locale, { weekday: "short" }, "weekday", custom?.weekdayShort, t.dayOfWeek - 1);
|
|
695
|
+
}, "dayOfWeek"],
|
|
696
|
+
// Era — locale-aware ("AD"/"BC" in en, "ap. J.-C."/"av. J.-C." in fr).
|
|
697
|
+
// GGGG = long, G = short. Format-only.
|
|
698
|
+
["GGGG", (t, locale) => {
|
|
699
|
+
return intlPart(t, locale, { era: "long" }, "era");
|
|
700
|
+
}, "year"],
|
|
701
|
+
["G", (t, locale) => {
|
|
702
|
+
return intlPart(t, locale, { era: "short" }, "era");
|
|
703
|
+
}, "year"],
|
|
704
|
+
// Localized timezone name — uses Intl's longLocalized/short timezone
|
|
705
|
+
// name option. Format-only — these names are locale-dependent and
|
|
706
|
+
// vary by season (EST vs EDT), so parsing them back requires a
|
|
707
|
+
// lookup table that isn't practical to ship.
|
|
708
|
+
["zzzz", (t, locale) => {
|
|
709
|
+
return intlPart(t, locale, { timeZoneName: "longGeneric" }, "timeZoneName");
|
|
710
|
+
}, "timeZoneId"],
|
|
711
|
+
["z", (t, locale) => {
|
|
712
|
+
return intlPart(t, locale, { timeZoneName: "short" }, "timeZoneName");
|
|
713
|
+
}, "timeZoneId"]
|
|
714
|
+
];
|
|
715
|
+
|
|
716
|
+
// src/tokenize.ts
|
|
717
|
+
var SORTED_TOKEN_STRINGS = TOKENS.map(([tok]) => tok).sort((a, b) => b.length - a.length);
|
|
718
|
+
function tokenize(format) {
|
|
719
|
+
const pieces = [];
|
|
720
|
+
let i = 0;
|
|
721
|
+
while (i < format.length) {
|
|
722
|
+
const ch = format[i];
|
|
723
|
+
if (ch === "'") {
|
|
724
|
+
if (format[i + 1] === "'") {
|
|
725
|
+
appendLiteral(pieces, "'");
|
|
726
|
+
i += 2;
|
|
727
|
+
continue;
|
|
728
|
+
}
|
|
729
|
+
let j = i + 1;
|
|
730
|
+
let literal = "";
|
|
731
|
+
let closed = false;
|
|
732
|
+
while (j < format.length) {
|
|
733
|
+
if (format[j] === "'") {
|
|
734
|
+
if (format[j + 1] === "'") {
|
|
735
|
+
literal += "'";
|
|
736
|
+
j += 2;
|
|
737
|
+
continue;
|
|
738
|
+
}
|
|
739
|
+
closed = true;
|
|
740
|
+
j += 1;
|
|
741
|
+
break;
|
|
742
|
+
}
|
|
743
|
+
literal += format[j];
|
|
744
|
+
j += 1;
|
|
745
|
+
}
|
|
746
|
+
if (!closed) {
|
|
747
|
+
throw new FormatSyntaxError({
|
|
748
|
+
format,
|
|
749
|
+
message: `temporal-fmt: unterminated quote in format string "${format}"`
|
|
750
|
+
});
|
|
751
|
+
}
|
|
752
|
+
appendLiteral(pieces, literal);
|
|
753
|
+
i = j;
|
|
754
|
+
continue;
|
|
755
|
+
}
|
|
756
|
+
const match = SORTED_TOKEN_STRINGS.find((tok) => format.startsWith(tok, i));
|
|
757
|
+
if (match) {
|
|
758
|
+
const runChar = match[match.length - 1];
|
|
759
|
+
if (format[i + match.length] === runChar) {
|
|
760
|
+
let end = i + match.length;
|
|
761
|
+
while (format[end] === runChar) end += 1;
|
|
762
|
+
throw new UnknownTokenError({
|
|
763
|
+
format,
|
|
764
|
+
token: format.slice(i, end),
|
|
765
|
+
message: `temporal-fmt: "${format.slice(i, end)}" in format string "${format}" isn't a recognized token \u2014 did you mean "${match}"?`
|
|
766
|
+
});
|
|
767
|
+
}
|
|
768
|
+
pieces.push({ kind: "token", value: match });
|
|
769
|
+
i += match.length;
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
appendLiteral(pieces, ch);
|
|
773
|
+
i += 1;
|
|
774
|
+
}
|
|
775
|
+
return pieces;
|
|
776
|
+
}
|
|
777
|
+
function appendLiteral(pieces, value) {
|
|
778
|
+
const last = pieces[pieces.length - 1];
|
|
779
|
+
if (last && last.kind === "literal") {
|
|
780
|
+
last.value += value;
|
|
781
|
+
} else {
|
|
782
|
+
pieces.push({ kind: "literal", value });
|
|
783
|
+
}
|
|
784
|
+
}
|
|
785
|
+
|
|
786
|
+
// src/pattern.ts
|
|
787
|
+
function escapeRegExp(literal) {
|
|
788
|
+
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
789
|
+
}
|
|
790
|
+
function alternation(values, caseInsensitive = false) {
|
|
791
|
+
const escaped = values.map(escapeRegExp);
|
|
792
|
+
if (!caseInsensitive) return `(?:${escaped.join("|")})`;
|
|
793
|
+
return `(?:${escaped.map(foldCase).join("|")})`;
|
|
794
|
+
}
|
|
795
|
+
function foldCase(value) {
|
|
796
|
+
return value.replace(/[a-zA-Z]/g, (ch) => `[${ch.toLowerCase()}${ch.toUpperCase()}]`);
|
|
797
|
+
}
|
|
798
|
+
var TIME_ZONE_SHAPE = "(?:UTC|[+-]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?|[A-Za-z_]+(?:[+-]\\d{1,2})?(?:\\/[A-Za-z0-9_+-]+)*)";
|
|
799
|
+
var OFFSET_SHAPES = {
|
|
800
|
+
X: "(?:Z|[+-]\\d{2}(?:\\d{2})?)",
|
|
801
|
+
XX: "(?:Z|[+-]\\d{4})",
|
|
802
|
+
XXX: "(?:Z|[+-]\\d{2}:\\d{2})",
|
|
803
|
+
x: "[+-]\\d{2}(?:\\d{2})?",
|
|
804
|
+
xx: "[+-]\\d{4}",
|
|
805
|
+
xxx: "[+-]\\d{2}:\\d{2}"
|
|
806
|
+
};
|
|
807
|
+
function getTimeZoneFragment() {
|
|
808
|
+
return TIME_ZONE_SHAPE;
|
|
809
|
+
}
|
|
810
|
+
var validZoneSet;
|
|
811
|
+
function getValidZoneSet() {
|
|
812
|
+
if (!validZoneSet) {
|
|
813
|
+
validZoneSet = new Set(Intl.supportedValuesOf("timeZone"));
|
|
814
|
+
validZoneSet.add("UTC");
|
|
815
|
+
}
|
|
816
|
+
return validZoneSet;
|
|
817
|
+
}
|
|
818
|
+
var FIXED_OFFSET_RE = /^[+-]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,9})?)?$/;
|
|
819
|
+
function isValidTimeZone(raw) {
|
|
820
|
+
if (FIXED_OFFSET_RE.test(raw) || getValidZoneSet().has(raw)) return true;
|
|
821
|
+
try {
|
|
822
|
+
getTemporal().ZonedDateTime.from({
|
|
823
|
+
year: 2026,
|
|
824
|
+
month: 1,
|
|
825
|
+
day: 1,
|
|
826
|
+
hour: 0,
|
|
827
|
+
minute: 0,
|
|
828
|
+
second: 0,
|
|
829
|
+
timeZone: raw
|
|
830
|
+
});
|
|
831
|
+
return true;
|
|
832
|
+
} catch {
|
|
833
|
+
return false;
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
var NUMERIC_FRAGMENTS = {
|
|
837
|
+
yy: "\\d{2}",
|
|
838
|
+
MM: "(?:0[1-9]|1[0-2])",
|
|
839
|
+
M: "(?:1[0-2]|[1-9])",
|
|
840
|
+
dd: "(?:0[1-9]|[12]\\d|3[01])",
|
|
841
|
+
d: "(?:[12]\\d|3[01]|[1-9])",
|
|
842
|
+
HH: "(?:[01]\\d|2[0-3])",
|
|
843
|
+
H: "(?:1\\d|2[0-3]|[0-9])",
|
|
844
|
+
hh: "(?:0[1-9]|1[0-2])",
|
|
845
|
+
h: "(?:1[0-2]|[1-9])",
|
|
846
|
+
mm: "(?:[0-5]\\d)",
|
|
847
|
+
m: "(?:[1-5]\\d|[0-9])",
|
|
848
|
+
ss: "(?:[0-5]\\d)",
|
|
849
|
+
s: "(?:[1-5]\\d|[0-9])",
|
|
850
|
+
SSSSSSSSS: "\\d{9}",
|
|
851
|
+
SSSSSSSS: "\\d{8}",
|
|
852
|
+
SSSSSSS: "\\d{7}",
|
|
853
|
+
SSSSSS: "\\d{6}",
|
|
854
|
+
SSSSS: "\\d{5}",
|
|
855
|
+
SSSS: "\\d{4}",
|
|
856
|
+
SSS: "\\d{3}",
|
|
857
|
+
SS: "\\d{2}",
|
|
858
|
+
S: "\\d",
|
|
859
|
+
// Q is always a single digit 1-4 (no padding variant, so no width ambiguity
|
|
860
|
+
// with adjacent digit tokens the way M/d/H/m/s have).
|
|
861
|
+
Q: "[1-4]"
|
|
862
|
+
};
|
|
863
|
+
var QQQ_FRAGMENT = "Q[1-4]";
|
|
864
|
+
var FORMAT_ONLY_TOKENS = /* @__PURE__ */ new Set(["do", "ww", "RRRR", "D", "DD", "DDD", "LLLL", "LLL", "cccc", "ccc", "GGGG", "G", "zzzz", "z"]);
|
|
865
|
+
var YYYY_EXACT = "-?\\d{4}";
|
|
866
|
+
var YYYY_EXTENDED = "-?\\d{4,}";
|
|
867
|
+
var Y_FRAGMENT = "-?\\d+";
|
|
868
|
+
var DIGIT_LEADING_TOKENS = /* @__PURE__ */ new Set([
|
|
869
|
+
"yyyy",
|
|
870
|
+
"yy",
|
|
871
|
+
"y",
|
|
872
|
+
"MM",
|
|
873
|
+
"M",
|
|
874
|
+
"dd",
|
|
875
|
+
"d",
|
|
876
|
+
"HH",
|
|
877
|
+
"H",
|
|
878
|
+
"hh",
|
|
879
|
+
"h",
|
|
880
|
+
"mm",
|
|
881
|
+
"m",
|
|
882
|
+
"ss",
|
|
883
|
+
"s",
|
|
884
|
+
"SSSSSSSSS",
|
|
885
|
+
"SSSSSSSS",
|
|
886
|
+
"SSSSSSS",
|
|
887
|
+
"SSSSSS",
|
|
888
|
+
"SSSSS",
|
|
889
|
+
"SSSS",
|
|
890
|
+
"SSS",
|
|
891
|
+
"SS",
|
|
892
|
+
"S"
|
|
893
|
+
]);
|
|
894
|
+
var UNBOUNDED_WIDTH_TOKENS = /* @__PURE__ */ new Set(["y"]);
|
|
895
|
+
function tokenFragment(token, locale, nextToken) {
|
|
896
|
+
if (token === "yyyy") {
|
|
897
|
+
return nextToken !== void 0 && DIGIT_LEADING_TOKENS.has(nextToken) ? YYYY_EXACT : YYYY_EXTENDED;
|
|
898
|
+
}
|
|
899
|
+
if (token === "y") {
|
|
900
|
+
return Y_FRAGMENT;
|
|
901
|
+
}
|
|
902
|
+
const numeric = NUMERIC_FRAGMENTS[token];
|
|
903
|
+
if (numeric) {
|
|
904
|
+
return numeric;
|
|
905
|
+
}
|
|
906
|
+
if (token === "QQQ") {
|
|
907
|
+
return QQQ_FRAGMENT;
|
|
908
|
+
}
|
|
909
|
+
if (FORMAT_ONLY_TOKENS.has(token)) {
|
|
910
|
+
throw new UnknownTokenError({
|
|
911
|
+
token,
|
|
912
|
+
message: `temporal-fmt: token "${token}" is format-only \u2014 it can't be parsed back into a value. Use a different token in the parse format string (e.g. "d" for "do", "MM" for "ww").`
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
const vocab = getLocaleVocab(locale);
|
|
916
|
+
switch (token) {
|
|
917
|
+
case "MMMM":
|
|
918
|
+
return alternation(vocab.monthLong);
|
|
919
|
+
case "MMM":
|
|
920
|
+
return alternation(vocab.monthShort);
|
|
921
|
+
case "EEEE":
|
|
922
|
+
return alternation(vocab.weekdayLong);
|
|
923
|
+
case "EEE":
|
|
924
|
+
return alternation(vocab.weekdayShort);
|
|
925
|
+
// Case-insensitive on purpose: "pm"/"Pm"/"PM" all mean the same thing,
|
|
926
|
+
// and unlike the Md-glue ambiguity elsewhere in this file, there's no
|
|
927
|
+
// second valid reading to guess wrong — so rejecting on case buys no
|
|
928
|
+
// correctness, only friction against real-world data (mixed-case CSV
|
|
929
|
+
// exports, lowercase log timestamps).
|
|
930
|
+
case "a":
|
|
931
|
+
return alternation(vocab.dayPeriod, true);
|
|
932
|
+
case "zzz":
|
|
933
|
+
return getTimeZoneFragment();
|
|
934
|
+
case "X":
|
|
935
|
+
case "XX":
|
|
936
|
+
case "XXX":
|
|
937
|
+
case "x":
|
|
938
|
+
case "xx":
|
|
939
|
+
case "xxx":
|
|
940
|
+
return OFFSET_SHAPES[token];
|
|
941
|
+
/* c8 ignore start @preserve -- defensive guard, not reachable through
|
|
942
|
+
the public API. tokenFragment's only caller (buildCapturingPattern
|
|
943
|
+
in parsePattern.ts) always passes piece.value straight from
|
|
944
|
+
tokenize.ts, which only ever emits strings from tokens.ts's TOKENS
|
|
945
|
+
table. Every token in that table is handled above: the numeric
|
|
946
|
+
ones via NUMERIC_FRAGMENTS, QQQ via QQQ_FRAGMENT, the format-only
|
|
947
|
+
ones via the FORMAT_ONLY_TOKENS check earlier in this function, and
|
|
948
|
+
everything else via one of the switch cases. There's no token
|
|
949
|
+
string that can reach this default without either tokens.ts
|
|
950
|
+
registering something new or tokenize.ts being bypassed, neither of
|
|
951
|
+
which happens on the parse() path. */
|
|
952
|
+
default:
|
|
953
|
+
throw new UnknownTokenError({ token, message: `temporal-fmt: unknown token "${token}"` });
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
var UNPADDED_NUMERIC_TOKENS = /* @__PURE__ */ new Set(["M", "d", "H", "h", "m", "s"]);
|
|
957
|
+
var UNPADDED_NUMERIC_RANGES = {
|
|
958
|
+
M: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 12 }],
|
|
959
|
+
d: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 31 }],
|
|
960
|
+
H: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 23 }],
|
|
961
|
+
h: [{ digits: 1, min: 1, max: 9 }, { digits: 2, min: 10, max: 12 }],
|
|
962
|
+
m: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 59 }],
|
|
963
|
+
s: [{ digits: 1, min: 0, max: 9 }, { digits: 2, min: 10, max: 59 }]
|
|
964
|
+
};
|
|
965
|
+
function enumerateValidSplits(digits, tokens) {
|
|
966
|
+
const memo = /* @__PURE__ */ new Map();
|
|
967
|
+
function solve(tokenIndex, offset) {
|
|
968
|
+
const key = `${tokenIndex}:${offset}`;
|
|
969
|
+
const cached = memo.get(key);
|
|
970
|
+
if (cached) {
|
|
971
|
+
return cached;
|
|
972
|
+
}
|
|
973
|
+
if (tokenIndex === tokens.length) {
|
|
974
|
+
const result = offset === digits.length ? [[]] : [];
|
|
975
|
+
memo.set(key, result);
|
|
976
|
+
return result;
|
|
977
|
+
}
|
|
978
|
+
const token = tokens[tokenIndex];
|
|
979
|
+
const ranges = UNPADDED_NUMERIC_RANGES[token];
|
|
980
|
+
/* c8 ignore start @preserve -- defensive guard, not reachable through
|
|
981
|
+
the public API. enumerateValidSplits's only caller (parse.ts, both
|
|
982
|
+
call sites) passes run.tokens straight from
|
|
983
|
+
pattern.ambiguousRuns, which parsePattern.ts only ever populates
|
|
984
|
+
with tokens already checked against UNPADDED_NUMERIC_TOKENS — the
|
|
985
|
+
exact same key set as UNPADDED_NUMERIC_RANGES. There's no path
|
|
986
|
+
where a token reaches here without having already passed that
|
|
987
|
+
check. */
|
|
988
|
+
if (!ranges) {
|
|
989
|
+
throw new Error(`temporal-fmt: internal error \u2014 "${token}" is not an unpadded numeric token`);
|
|
990
|
+
}
|
|
991
|
+
/* c8 ignore stop @preserve */
|
|
992
|
+
const results = [];
|
|
993
|
+
for (const { digits: width, min, max } of ranges) {
|
|
994
|
+
if (offset + width > digits.length) continue;
|
|
995
|
+
const piece = digits.slice(offset, offset + width);
|
|
996
|
+
if (width === 2 && piece[0] === "0") continue;
|
|
997
|
+
const value = Number(piece);
|
|
998
|
+
if (value < min || value > max) continue;
|
|
999
|
+
for (const restSplit of solve(tokenIndex + 1, offset + width)) {
|
|
1000
|
+
results.push([value, ...restSplit]);
|
|
1001
|
+
if (results.length === 2) break;
|
|
1002
|
+
}
|
|
1003
|
+
if (results.length === 2) break;
|
|
1004
|
+
}
|
|
1005
|
+
memo.set(key, results);
|
|
1006
|
+
return results;
|
|
1007
|
+
}
|
|
1008
|
+
return solve(0, 0);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
// src/parsePattern.ts
|
|
1012
|
+
function escapeRegExp2(literal) {
|
|
1013
|
+
return literal.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
1014
|
+
}
|
|
1015
|
+
var MAX_AMBIGUITY_BITS = 12;
|
|
1016
|
+
function widthChoicesBits(choices) {
|
|
1017
|
+
return Math.ceil(Math.log2(Math.max(choices, 1)));
|
|
1018
|
+
}
|
|
1019
|
+
function isDigitConsumingStart(piece) {
|
|
1020
|
+
if (piece === void 0) return false;
|
|
1021
|
+
if (piece.kind === "literal") return /^[0-9]/.test(piece.value);
|
|
1022
|
+
return DIGIT_LEADING_TOKENS.has(piece.value);
|
|
1023
|
+
}
|
|
1024
|
+
function buildCapturingPattern(pieces, locale) {
|
|
1025
|
+
const groups = [];
|
|
1026
|
+
const ambiguousRuns = [];
|
|
1027
|
+
let source = "";
|
|
1028
|
+
let i = 0;
|
|
1029
|
+
let ambiguityBits = 0;
|
|
1030
|
+
let currentRun = { names: [], tokens: [] };
|
|
1031
|
+
const flushRun = (nextPiece) => {
|
|
1032
|
+
if (currentRun.tokens.length === 1) {
|
|
1033
|
+
const name = currentRun.names[0];
|
|
1034
|
+
const token = currentRun.tokens[0];
|
|
1035
|
+
source += `(?<${name}>${tokenFragment(token, locale)})`;
|
|
1036
|
+
if (isDigitConsumingStart(nextPiece)) ambiguityBits += 1;
|
|
1037
|
+
} else if (currentRun.tokens.length >= 2) {
|
|
1038
|
+
const runName = `r${i++}`;
|
|
1039
|
+
const tokenCount = currentRun.tokens.length;
|
|
1040
|
+
source += `(?<${runName}>\\d{${tokenCount},${tokenCount * 2}})`;
|
|
1041
|
+
ambiguousRuns.push({
|
|
1042
|
+
groupName: runName,
|
|
1043
|
+
groupNames: currentRun.names,
|
|
1044
|
+
tokens: currentRun.tokens
|
|
1045
|
+
});
|
|
1046
|
+
if (isDigitConsumingStart(nextPiece)) {
|
|
1047
|
+
ambiguityBits += widthChoicesBits(tokenCount + 1);
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
currentRun = { names: [], tokens: [] };
|
|
1051
|
+
};
|
|
1052
|
+
for (const [idx, piece] of pieces.entries()) {
|
|
1053
|
+
if (piece.kind === "literal") {
|
|
1054
|
+
flushRun(piece);
|
|
1055
|
+
source += escapeRegExp2(piece.value);
|
|
1056
|
+
continue;
|
|
1057
|
+
}
|
|
1058
|
+
if (UNPADDED_NUMERIC_TOKENS.has(piece.value)) {
|
|
1059
|
+
const name2 = `g${i++}`;
|
|
1060
|
+
groups.push({ name: name2, token: piece.value });
|
|
1061
|
+
currentRun.names.push(name2);
|
|
1062
|
+
currentRun.tokens.push(piece.value);
|
|
1063
|
+
continue;
|
|
1064
|
+
}
|
|
1065
|
+
flushRun(piece);
|
|
1066
|
+
const name = `g${i++}`;
|
|
1067
|
+
groups.push({ name, token: piece.value });
|
|
1068
|
+
const nextPiece = pieces[idx + 1];
|
|
1069
|
+
const nextToken = nextPiece?.kind === "token" ? nextPiece.value : void 0;
|
|
1070
|
+
if (UNBOUNDED_WIDTH_TOKENS.has(piece.value) && isDigitConsumingStart(nextPiece)) {
|
|
1071
|
+
throw new FormatSyntaxError({
|
|
1072
|
+
reason: `token "${piece.value}" has no fixed width \u2014 it can't be placed directly next to another digit-reading token or a literal that starts with a digit, since there's no way to tell where "${piece.value}" ends and the next field begins. Add a non-digit separator (e.g. "-" or " ") after it.`
|
|
1073
|
+
});
|
|
1074
|
+
}
|
|
1075
|
+
if (piece.value === "yyyy" && nextToken === void 0 && isDigitConsumingStart(nextPiece)) {
|
|
1076
|
+
source += `(?<${name}>${tokenFragment(piece.value, locale, "M")})`;
|
|
1077
|
+
} else {
|
|
1078
|
+
source += `(?<${name}>${tokenFragment(piece.value, locale, nextToken)})`;
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
flushRun(void 0);
|
|
1082
|
+
if (ambiguityBits > MAX_AMBIGUITY_BITS) {
|
|
1083
|
+
throw new FormatSyntaxError({
|
|
1084
|
+
reason: `format string has too many variable-width numeric tokens glued to digit-consuming neighbors (ambiguity score ${ambiguityBits} > ${MAX_AMBIGUITY_BITS}). This shape makes the regex engine backtrack exponentially on near-miss input. Add a non-digit separator between these tokens (e.g. "-" or " ") or use their padded forms (MM/dd/HH/mm/ss).`
|
|
1085
|
+
});
|
|
1086
|
+
}
|
|
1087
|
+
return { regex: new RegExp(`^(?:${source})$`, "ud"), groups, ambiguousRuns };
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
// src/constants.ts
|
|
1091
|
+
var MAX_FORMAT_LENGTH = 1e3;
|
|
1092
|
+
var MAX_INPUT_LENGTH = 1e5;
|
|
1093
|
+
|
|
1094
|
+
// src/numbering.ts
|
|
1095
|
+
var SUPPORTED_NUMBERING_SYSTEMS = /* @__PURE__ */ new Set([
|
|
1096
|
+
"latn",
|
|
1097
|
+
"arab",
|
|
1098
|
+
"deva",
|
|
1099
|
+
"beng",
|
|
1100
|
+
"guru",
|
|
1101
|
+
"gujr",
|
|
1102
|
+
"orya",
|
|
1103
|
+
"tamldec",
|
|
1104
|
+
"telu",
|
|
1105
|
+
"knda",
|
|
1106
|
+
"mlym",
|
|
1107
|
+
"fullwide",
|
|
1108
|
+
"hanidec"
|
|
1109
|
+
]);
|
|
1110
|
+
var digitMapCache = /* @__PURE__ */ new Map();
|
|
1111
|
+
function getDigitMap(system) {
|
|
1112
|
+
let map = digitMapCache.get(system);
|
|
1113
|
+
if (map) return map;
|
|
1114
|
+
/* c8 ignore start @preserve -- this branch is dead by construction, not
|
|
1115
|
+
just untested: both callers (convertDigits, convertDigitsToAscii)
|
|
1116
|
+
already bail out early on system === 'latn' before ever calling
|
|
1117
|
+
getDigitMap, so it never actually gets invoked with 'latn'. keeping
|
|
1118
|
+
it anyway as a defensive fallback rather than betting that stays
|
|
1119
|
+
true forever */
|
|
1120
|
+
if (system === "latn") {
|
|
1121
|
+
map = {};
|
|
1122
|
+
for (let i = 0; i < 10; i++) map[String(i)] = String(i);
|
|
1123
|
+
} else {
|
|
1124
|
+
/* c8 ignore stop @preserve */
|
|
1125
|
+
const fmt = new Intl.NumberFormat("en-US-u-nu-" + system, { useGrouping: false });
|
|
1126
|
+
map = {};
|
|
1127
|
+
for (let i = 0; i < 10; i++) {
|
|
1128
|
+
map[String(i)] = fmt.format(i);
|
|
1129
|
+
}
|
|
1130
|
+
}
|
|
1131
|
+
digitMapCache.set(system, map);
|
|
1132
|
+
return map;
|
|
1133
|
+
}
|
|
1134
|
+
function convertDigitsToAscii(s, system) {
|
|
1135
|
+
if (system === "latn") return s;
|
|
1136
|
+
if (!SUPPORTED_NUMBERING_SYSTEMS.has(system)) {
|
|
1137
|
+
throw new InvalidLocaleError({ actual: system, reason: `numbering system "${system}" is not supported.` });
|
|
1138
|
+
}
|
|
1139
|
+
const map = getDigitMap(system);
|
|
1140
|
+
const reverse = {};
|
|
1141
|
+
for (const k of Object.keys(map)) reverse[map[k]] = k;
|
|
1142
|
+
let result = "";
|
|
1143
|
+
for (const ch of s) {
|
|
1144
|
+
result += reverse[ch] ?? ch;
|
|
1145
|
+
}
|
|
1146
|
+
return result;
|
|
1147
|
+
}
|
|
1148
|
+
function applyParseNumbering(s, options) {
|
|
1149
|
+
const system = options.parseNumberingSystem ?? "latn";
|
|
1150
|
+
if (system === "latn") return s;
|
|
1151
|
+
return convertDigitsToAscii(s, system);
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
// src/parse.ts
|
|
1155
|
+
var patternCache = /* @__PURE__ */ new Map();
|
|
1156
|
+
var MAX_CACHE_SIZE2 = 500;
|
|
1157
|
+
subscribeToVocabChanges(() => {
|
|
1158
|
+
patternCache.clear();
|
|
1159
|
+
});
|
|
1160
|
+
function getPattern(formatStr, locale) {
|
|
1161
|
+
const key = JSON.stringify([canonicalCacheKey(locale), formatStr]);
|
|
1162
|
+
let pattern = patternCache.get(key);
|
|
1163
|
+
if (pattern) {
|
|
1164
|
+
return pattern;
|
|
1165
|
+
}
|
|
1166
|
+
if (patternCache.size >= MAX_CACHE_SIZE2) {
|
|
1167
|
+
const oldestKey = patternCache.keys().next().value;
|
|
1168
|
+
if (oldestKey !== void 0) patternCache.delete(oldestKey);
|
|
1169
|
+
}
|
|
1170
|
+
pattern = buildCapturingPattern(tokenize(formatStr), locale);
|
|
1171
|
+
patternCache.set(key, pattern);
|
|
1172
|
+
return pattern;
|
|
1173
|
+
}
|
|
1174
|
+
var calendarCache = /* @__PURE__ */ new Map();
|
|
1175
|
+
var MAX_CALENDAR_CACHE_SIZE = 500;
|
|
1176
|
+
function resolveCalendar(locale) {
|
|
1177
|
+
assertValidLocaleTag(locale);
|
|
1178
|
+
const canonicalLocale = canonicalCacheKey(locale);
|
|
1179
|
+
if (calendarCache.has(canonicalLocale)) {
|
|
1180
|
+
return calendarCache.get(canonicalLocale);
|
|
1181
|
+
}
|
|
1182
|
+
if (calendarCache.size >= MAX_CALENDAR_CACHE_SIZE) {
|
|
1183
|
+
const oldestKey = calendarCache.keys().next().value;
|
|
1184
|
+
if (oldestKey !== void 0) calendarCache.delete(oldestKey);
|
|
1185
|
+
}
|
|
1186
|
+
let calendar;
|
|
1187
|
+
const parts = canonicalLocale.split("-");
|
|
1188
|
+
const extensionIndex = parts.indexOf("u");
|
|
1189
|
+
const calendarKeyIndex = extensionIndex === -1 ? -1 : parts.indexOf("ca", extensionIndex + 1);
|
|
1190
|
+
if (calendarKeyIndex !== -1 && calendarKeyIndex + 1 < parts.length) {
|
|
1191
|
+
const resolved = new Intl.DateTimeFormat(canonicalLocale).resolvedOptions().calendar;
|
|
1192
|
+
calendar = resolved === "gregory" ? void 0 : resolved;
|
|
1193
|
+
}
|
|
1194
|
+
calendarCache.set(canonicalLocale, calendar);
|
|
1195
|
+
return calendar;
|
|
1196
|
+
}
|
|
1197
|
+
function parseOffsetString(raw, token) {
|
|
1198
|
+
if (raw === "Z") {
|
|
1199
|
+
/* c8 ignore start @preserve -- unreachable: lowercase tokens' regex
|
|
1200
|
+
(OFFSET_SHAPES in pattern.ts) has no "Z" alternative at all, so
|
|
1201
|
+
raw === 'Z' can only ever be reached when token is one of the
|
|
1202
|
+
uppercase variants (X/XX/XXX). A lowercase token can't even
|
|
1203
|
+
capture "Z" as `raw` in the first place. */
|
|
1204
|
+
if (token === "x" || token === "xx" || token === "xxx") {
|
|
1205
|
+
throw new Error(
|
|
1206
|
+
`temporal-fmt: offset token "${token}" doesn't accept "Z" \u2014 only the uppercase variants (X/XX/XXX) emit "Z" for UTC. Use "+00:00", "+0000", or "+00" depending on the variant's width.`
|
|
1207
|
+
);
|
|
1208
|
+
}
|
|
1209
|
+
/* c8 ignore stop @preserve */
|
|
1210
|
+
return "+00:00";
|
|
1211
|
+
}
|
|
1212
|
+
const sign = raw[0];
|
|
1213
|
+
/* c8 ignore start @preserve -- unreachable: raw is a regex-captured
|
|
1214
|
+
group from an offset token, and every OFFSET_SHAPES pattern
|
|
1215
|
+
(pattern.ts) is anchored to either "Z" or a leading [+-]. raw's
|
|
1216
|
+
first character can never be anything else by the time it reaches
|
|
1217
|
+
this function. */
|
|
1218
|
+
if (sign !== "+" && sign !== "-") {
|
|
1219
|
+
throw new Error(`temporal-fmt: offset "${raw}" for token "${token}" doesn't start with "+", "-", or "Z".`);
|
|
1220
|
+
}
|
|
1221
|
+
/* c8 ignore stop @preserve */
|
|
1222
|
+
const body = raw.slice(1);
|
|
1223
|
+
let hoursStr;
|
|
1224
|
+
let minutesStr;
|
|
1225
|
+
if (body.length === 2) {
|
|
1226
|
+
/* c8 ignore start @preserve -- unreachable: each offset token's own
|
|
1227
|
+
regex shape in OFFSET_SHAPES (pattern.ts) already gates which
|
|
1228
|
+
body shapes it can capture. Only X and x ever match a 2-digit
|
|
1229
|
+
body — XX/xx/XXX/xxx's regexes can't produce one — so this
|
|
1230
|
+
mismatch can never actually fire through parse(). */
|
|
1231
|
+
if (token !== "X" && token !== "x") {
|
|
1232
|
+
throw new Error(
|
|
1233
|
+
`temporal-fmt: offset token "${token}" can't match "${raw}" \u2014 it requires minutes, but "${raw}" has none.`
|
|
1234
|
+
);
|
|
1235
|
+
}
|
|
1236
|
+
/* c8 ignore stop @preserve */
|
|
1237
|
+
hoursStr = body;
|
|
1238
|
+
minutesStr = "00";
|
|
1239
|
+
} else if (body.length === 4) {
|
|
1240
|
+
/* c8 ignore start @preserve -- unreachable, same reason as the
|
|
1241
|
+
2-digit case above: XXX/xxx's regex requires a colon, so it can
|
|
1242
|
+
never capture a 4-digit no-colon body in the first place. */
|
|
1243
|
+
if (token === "XXX" || token === "xxx") {
|
|
1244
|
+
throw new Error(
|
|
1245
|
+
`temporal-fmt: offset token "${token}" can't match "${raw}" \u2014 it requires a colon between hours and minutes (e.g. "${sign}${body.slice(0, 2)}:${body.slice(2)}").`
|
|
1246
|
+
);
|
|
1247
|
+
}
|
|
1248
|
+
/* c8 ignore stop @preserve */
|
|
1249
|
+
hoursStr = body.slice(0, 2);
|
|
1250
|
+
minutesStr = body.slice(2, 4);
|
|
1251
|
+
} else if (body.length === 5 && body[2] === ":") {
|
|
1252
|
+
/* c8 ignore start @preserve -- unreachable, same reason again: only
|
|
1253
|
+
XXX/xxx's regex can produce a colon-shaped body; X/x/XX/xx never
|
|
1254
|
+
capture one. */
|
|
1255
|
+
if (token !== "XXX" && token !== "xxx") {
|
|
1256
|
+
throw new Error(
|
|
1257
|
+
`temporal-fmt: offset token "${token}" can't match "${raw}" \u2014 it doesn't use a colon (use "${sign}${body.slice(0, 2)}${body.slice(3)}" instead).`
|
|
1258
|
+
);
|
|
1259
|
+
}
|
|
1260
|
+
/* c8 ignore stop @preserve */
|
|
1261
|
+
hoursStr = body.slice(0, 2);
|
|
1262
|
+
minutesStr = body.slice(3, 5);
|
|
1263
|
+
/* c8 ignore start @preserve -- unreachable: every offset token's
|
|
1264
|
+
regex only ever produces a body of length 2, length 4, or length 5
|
|
1265
|
+
with a colon at index 2 (see OFFSET_SHAPES in pattern.ts) — no
|
|
1266
|
+
shape falls outside those three cases, so this else arm can't be
|
|
1267
|
+
taken through parse(). Kept as an exhaustiveness fallback so
|
|
1268
|
+
hoursStr/minutesStr are assigned on every path TypeScript can see. */
|
|
1269
|
+
} else {
|
|
1270
|
+
throw new Error(`temporal-fmt: offset "${raw}" doesn't match the shape token "${token}" accepts.`);
|
|
1271
|
+
}
|
|
1272
|
+
/* c8 ignore stop @preserve */
|
|
1273
|
+
const hours = Number(hoursStr);
|
|
1274
|
+
const minutes = Number(minutesStr);
|
|
1275
|
+
if (hours > 14) {
|
|
1276
|
+
throw new InvalidOffsetError({
|
|
1277
|
+
actual: raw,
|
|
1278
|
+
message: `temporal-fmt: offset hours ${hours} in "${raw}" out of range (max 14 \u2014 Kiritimati, Line Islands is +14:00).`
|
|
1279
|
+
});
|
|
1280
|
+
}
|
|
1281
|
+
if (minutes > 59) {
|
|
1282
|
+
throw new InvalidOffsetError({
|
|
1283
|
+
actual: raw,
|
|
1284
|
+
message: `temporal-fmt: offset minutes ${minutes} in "${raw}" out of range (max 59).`
|
|
1285
|
+
});
|
|
1286
|
+
}
|
|
1287
|
+
if (sign === "+" && hours === 14 && minutes !== 0) {
|
|
1288
|
+
throw new InvalidOffsetError({
|
|
1289
|
+
actual: raw,
|
|
1290
|
+
message: `temporal-fmt: offset "${raw}" exceeds the maximum supported UTC offset of +14:00.`
|
|
1291
|
+
});
|
|
1292
|
+
}
|
|
1293
|
+
if (sign === "-" && hours === 12 && minutes !== 0) {
|
|
1294
|
+
throw new InvalidOffsetError({
|
|
1295
|
+
actual: raw,
|
|
1296
|
+
message: `temporal-fmt: offset "${raw}" exceeds the maximum supported negative UTC offset of -12:00.`
|
|
1297
|
+
});
|
|
1298
|
+
}
|
|
1299
|
+
return `${sign}${hoursStr}:${minutesStr}`;
|
|
1300
|
+
}
|
|
1301
|
+
function assignField(fields, key, value) {
|
|
1302
|
+
fields[key] = value;
|
|
1303
|
+
}
|
|
1304
|
+
function applyGroup(fields, token, raw, locale, formatStr) {
|
|
1305
|
+
const vocab = getLocaleVocab(locale);
|
|
1306
|
+
switch (token) {
|
|
1307
|
+
case "yyyy":
|
|
1308
|
+
case "y":
|
|
1309
|
+
assignField(fields, "year", Number(raw));
|
|
1310
|
+
break;
|
|
1311
|
+
case "yy":
|
|
1312
|
+
assignField(fields, "twoDigitYear", Number(raw));
|
|
1313
|
+
break;
|
|
1314
|
+
case "MM":
|
|
1315
|
+
case "M":
|
|
1316
|
+
assignField(fields, "month", Number(raw));
|
|
1317
|
+
break;
|
|
1318
|
+
case "MMMM":
|
|
1319
|
+
assignField(fields, "month", vocab.monthLong.indexOf(raw) + 1);
|
|
1320
|
+
break;
|
|
1321
|
+
case "MMM":
|
|
1322
|
+
assignField(fields, "month", vocab.monthShort.indexOf(raw) + 1);
|
|
1323
|
+
break;
|
|
1324
|
+
case "dd":
|
|
1325
|
+
case "d":
|
|
1326
|
+
assignField(fields, "day", Number(raw));
|
|
1327
|
+
break;
|
|
1328
|
+
case "EEEE":
|
|
1329
|
+
assignField(fields, "weekdayRaw", raw);
|
|
1330
|
+
assignField(fields, "weekdayExpected", vocab.weekdayLong.indexOf(raw) + 1);
|
|
1331
|
+
break;
|
|
1332
|
+
case "EEE":
|
|
1333
|
+
assignField(fields, "weekdayRaw", raw);
|
|
1334
|
+
assignField(fields, "weekdayExpected", vocab.weekdayShort.indexOf(raw) + 1);
|
|
1335
|
+
break;
|
|
1336
|
+
case "HH":
|
|
1337
|
+
case "H":
|
|
1338
|
+
assignField(fields, "hour", Number(raw));
|
|
1339
|
+
break;
|
|
1340
|
+
case "hh":
|
|
1341
|
+
case "h":
|
|
1342
|
+
assignField(fields, "hour12", Number(raw));
|
|
1343
|
+
break;
|
|
1344
|
+
case "mm":
|
|
1345
|
+
case "m":
|
|
1346
|
+
assignField(fields, "minute", Number(raw));
|
|
1347
|
+
break;
|
|
1348
|
+
case "ss":
|
|
1349
|
+
case "s":
|
|
1350
|
+
assignField(fields, "second", Number(raw));
|
|
1351
|
+
break;
|
|
1352
|
+
case "S":
|
|
1353
|
+
case "SS":
|
|
1354
|
+
case "SSS":
|
|
1355
|
+
case "SSSS":
|
|
1356
|
+
case "SSSSS":
|
|
1357
|
+
case "SSSSSS":
|
|
1358
|
+
case "SSSSSSS":
|
|
1359
|
+
case "SSSSSSSS":
|
|
1360
|
+
case "SSSSSSSSS": {
|
|
1361
|
+
const nanoOfSecond = Number(raw.padEnd(9, "0"));
|
|
1362
|
+
assignField(fields, "millisecond", Math.floor(nanoOfSecond / 1e6));
|
|
1363
|
+
assignField(fields, "microsecond", Math.floor(nanoOfSecond / 1e3) % 1e3);
|
|
1364
|
+
assignField(fields, "nanosecond", nanoOfSecond % 1e3);
|
|
1365
|
+
break;
|
|
1366
|
+
}
|
|
1367
|
+
case "a": {
|
|
1368
|
+
const periodIndex = vocab.dayPeriod.findIndex((p) => p.toLowerCase() === raw.toLowerCase());
|
|
1369
|
+
/* c8 ignore start @preserve -- unreachable: the 'a' token's regex
|
|
1370
|
+
fragment (pattern.ts's alternation() over vocab.dayPeriod) can
|
|
1371
|
+
only ever capture a case-insensitive match of one of
|
|
1372
|
+
vocab.dayPeriod's own entries. Both the regex and this lookup
|
|
1373
|
+
derive their vocab from the same `locale` via getLocaleVocab(),
|
|
1374
|
+
so periodIndex can't come back negative through parse(). */
|
|
1375
|
+
if (periodIndex < 0) throw new Error(`temporal-fmt: unknown day period "${raw}" for locale "${locale}".`);
|
|
1376
|
+
/* c8 ignore stop @preserve */
|
|
1377
|
+
assignField(fields, "dayPeriodRaw", raw);
|
|
1378
|
+
assignField(fields, "isPM", periodIndex === 1);
|
|
1379
|
+
break;
|
|
1380
|
+
}
|
|
1381
|
+
case "zzz":
|
|
1382
|
+
assignField(fields, "timeZoneId", raw);
|
|
1383
|
+
break;
|
|
1384
|
+
case "X":
|
|
1385
|
+
case "XX":
|
|
1386
|
+
case "XXX":
|
|
1387
|
+
case "x":
|
|
1388
|
+
case "xx":
|
|
1389
|
+
case "xxx":
|
|
1390
|
+
assignField(fields, "offsetString", parseOffsetString(raw, token));
|
|
1391
|
+
break;
|
|
1392
|
+
case "Q":
|
|
1393
|
+
assignField(fields, "quarter", Number(raw));
|
|
1394
|
+
break;
|
|
1395
|
+
case "QQQ":
|
|
1396
|
+
assignField(fields, "quarter", Number(raw.slice(1)));
|
|
1397
|
+
break;
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
function pickLenientSplit(splits, tokens) {
|
|
1401
|
+
const dayIndex = tokens.indexOf("d");
|
|
1402
|
+
if (dayIndex !== -1) {
|
|
1403
|
+
const smallDaySplits = splits.filter((s) => s[dayIndex] <= 12);
|
|
1404
|
+
if (smallDaySplits.length > 0) {
|
|
1405
|
+
return smallDaySplits[0];
|
|
1406
|
+
}
|
|
1407
|
+
}
|
|
1408
|
+
return splits[0];
|
|
1409
|
+
}
|
|
1410
|
+
function resolveYear(fields) {
|
|
1411
|
+
if (fields.year !== void 0 && fields.twoDigitYear !== void 0) {
|
|
1412
|
+
throw new FormatSyntaxError({
|
|
1413
|
+
message: 'temporal-fmt: format string mixes a full-year token ("yyyy"/"y") with the two-digit "yy" token.'
|
|
1414
|
+
});
|
|
1415
|
+
}
|
|
1416
|
+
if (fields.year !== void 0) return fields.year;
|
|
1417
|
+
if (fields.twoDigitYear !== void 0) {
|
|
1418
|
+
return fields.twoDigitYear <= 68 ? 2e3 + fields.twoDigitYear : 1900 + fields.twoDigitYear;
|
|
1419
|
+
}
|
|
1420
|
+
return void 0;
|
|
1421
|
+
}
|
|
1422
|
+
function resolveHour(fields, formatStr, locale) {
|
|
1423
|
+
if (fields.hour !== void 0 && fields.hour12 !== void 0) {
|
|
1424
|
+
throw new FormatSyntaxError({
|
|
1425
|
+
format: formatStr,
|
|
1426
|
+
message: `temporal-fmt: format string "${formatStr}" mixes a 24-hour token ("HH"/"H") with a 12-hour token ("hh"/"h").`
|
|
1427
|
+
});
|
|
1428
|
+
}
|
|
1429
|
+
if (fields.hour !== void 0) {
|
|
1430
|
+
if (fields.dayPeriodRaw !== void 0) {
|
|
1431
|
+
throw new FormatSyntaxError({
|
|
1432
|
+
format: formatStr,
|
|
1433
|
+
message: `temporal-fmt: format string "${formatStr}" mixes a 24-hour token ("HH"/"H") with a day-period token ("a"). Both describe the same field; use one or the other, not both.`
|
|
1434
|
+
});
|
|
1435
|
+
}
|
|
1436
|
+
return fields.hour;
|
|
1437
|
+
}
|
|
1438
|
+
if (fields.hour12 !== void 0) {
|
|
1439
|
+
if (fields.isPM === void 0) {
|
|
1440
|
+
throw new FormatSyntaxError({
|
|
1441
|
+
format: formatStr,
|
|
1442
|
+
message: `temporal-fmt: format string "${formatStr}" uses a 12-hour token ("hh"/"h") without an "a" token, so parse() can't tell AM from PM.`
|
|
1443
|
+
});
|
|
1444
|
+
}
|
|
1445
|
+
return fields.hour12 % 12 + (fields.isPM ? 12 : 0);
|
|
1446
|
+
}
|
|
1447
|
+
return void 0;
|
|
1448
|
+
}
|
|
1449
|
+
function parse(formatStr, input, options = {}) {
|
|
1450
|
+
if (formatStr.length > MAX_FORMAT_LENGTH) {
|
|
1451
|
+
throw new FormatSyntaxError({
|
|
1452
|
+
format: formatStr,
|
|
1453
|
+
message: `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`
|
|
1454
|
+
});
|
|
1455
|
+
}
|
|
1456
|
+
if (input.length > MAX_INPUT_LENGTH) {
|
|
1457
|
+
throw new FormatSyntaxError({
|
|
1458
|
+
input,
|
|
1459
|
+
message: `temporal-fmt: input exceeds maximum length of ${MAX_INPUT_LENGTH} characters (got ${input.length}).`
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
if (options.parseNumberingSystem) {
|
|
1463
|
+
input = applyParseNumbering(input, options);
|
|
1464
|
+
}
|
|
1465
|
+
const locale = options.locale ?? DEFAULT_LOCALE;
|
|
1466
|
+
const calendar = resolveCalendar(locale);
|
|
1467
|
+
const pattern = getPattern(formatStr, locale);
|
|
1468
|
+
const match = pattern.regex.exec(input);
|
|
1469
|
+
if (!match) {
|
|
1470
|
+
throw new ParseMismatchError({
|
|
1471
|
+
input,
|
|
1472
|
+
format: formatStr,
|
|
1473
|
+
// reason set explicitly (not just message): parse.test.js's
|
|
1474
|
+
// "safeParse: failure returns { ok: false, error } with a
|
|
1475
|
+
// TemporalFmtError" asserts result.error.reason carries the
|
|
1476
|
+
// underlying detail text, matching what wrapUntypedError used to
|
|
1477
|
+
// populate when this message reached it as a caught plain Error.
|
|
1478
|
+
reason: "no valid pattern matches the format string and input shape",
|
|
1479
|
+
message: `temporal-fmt: no valid pattern matches the format string and input shape`
|
|
1480
|
+
});
|
|
1481
|
+
}
|
|
1482
|
+
if (pattern.groups.length === 0) {
|
|
1483
|
+
throw new ParseMismatchError({
|
|
1484
|
+
format: formatStr,
|
|
1485
|
+
// reason set explicitly: errors.test.js's "format string with no
|
|
1486
|
+
// tokens at all falls through to ParseMismatchError" asserts
|
|
1487
|
+
// error.reason matches /has no tokens/.
|
|
1488
|
+
reason: `format string "${formatStr}" has no tokens \u2014 nothing to parse into a value.`,
|
|
1489
|
+
message: `temporal-fmt: format string "${formatStr}" has no tokens \u2014 nothing to parse into a value.`
|
|
1490
|
+
});
|
|
1491
|
+
}
|
|
1492
|
+
for (const { name, token } of pattern.groups) {
|
|
1493
|
+
if (token === "zzz" && !isValidTimeZone(match.groups[name])) {
|
|
1494
|
+
throw new InvalidTimeZoneError({
|
|
1495
|
+
input,
|
|
1496
|
+
format: formatStr,
|
|
1497
|
+
actual: match.groups[name],
|
|
1498
|
+
reason: "not a recognized IANA time zone identifier"
|
|
1499
|
+
});
|
|
1500
|
+
}
|
|
1501
|
+
}
|
|
1502
|
+
const runValues = /* @__PURE__ */ new Map();
|
|
1503
|
+
for (const run of pattern.ambiguousRuns) {
|
|
1504
|
+
const runDigits = match.groups[run.groupName];
|
|
1505
|
+
const splits = enumerateValidSplits(runDigits, run.tokens);
|
|
1506
|
+
if (splits.length === 0) {
|
|
1507
|
+
throw new ParseMismatchError({
|
|
1508
|
+
input,
|
|
1509
|
+
format: formatStr,
|
|
1510
|
+
reason: "no valid pattern matches the format string and input shape",
|
|
1511
|
+
message: `temporal-fmt: no valid pattern matches the format string and input shape`
|
|
1512
|
+
});
|
|
1513
|
+
}
|
|
1514
|
+
if (splits.length > 1) {
|
|
1515
|
+
if (!options.lenient) {
|
|
1516
|
+
throw new AmbiguousInputError({
|
|
1517
|
+
input,
|
|
1518
|
+
format: formatStr,
|
|
1519
|
+
message: `temporal-fmt: "${runDigits}" in format string "${formatStr}" is ambiguous \u2014 ${splits.length} different ways to read tokens "${run.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). parse() won't guess; add a separator between these tokens, or use their padded form (e.g. "MM" instead of "M") so each one has a fixed width. Pass { lenient: true } to opt into a documented heuristic that picks one.`
|
|
1520
|
+
});
|
|
1521
|
+
}
|
|
1522
|
+
const picked = pickLenientSplit(splits, run.tokens);
|
|
1523
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));
|
|
1524
|
+
} else {
|
|
1525
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0][idx])));
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
const fields = {};
|
|
1529
|
+
for (const { name, token } of pattern.groups) {
|
|
1530
|
+
const raw = runValues.get(name) ?? match.groups[name];
|
|
1531
|
+
applyGroup(fields, token, raw, locale, formatStr);
|
|
1532
|
+
}
|
|
1533
|
+
const year = resolveYear(fields);
|
|
1534
|
+
const hour = resolveHour(fields, formatStr, locale);
|
|
1535
|
+
const { month, day, minute, second, millisecond, microsecond, nanosecond, timeZoneId, offsetString, weekdayExpected, weekdayRaw, quarter } = fields;
|
|
1536
|
+
const hasAnyDatePart = year !== void 0 || month !== void 0 || day !== void 0;
|
|
1537
|
+
const hasFullDate = year !== void 0 && month !== void 0 && day !== void 0;
|
|
1538
|
+
if (hasAnyDatePart && !hasFullDate) {
|
|
1539
|
+
throw new InvalidDateError({
|
|
1540
|
+
format: formatStr,
|
|
1541
|
+
message: `temporal-fmt: format string "${formatStr}" has an incomplete date \u2014 year, month, and day tokens must all be present together.`
|
|
1542
|
+
});
|
|
1543
|
+
}
|
|
1544
|
+
const hasTime = hour !== void 0 || minute !== void 0 || second !== void 0 || millisecond !== void 0;
|
|
1545
|
+
if (timeZoneId !== void 0 && !(hasFullDate && hasTime)) {
|
|
1546
|
+
throw new FormatSyntaxError({
|
|
1547
|
+
format: formatStr,
|
|
1548
|
+
message: `temporal-fmt: format string "${formatStr}" has a "zzz" token but needs a full date and time to build a ZonedDateTime.`
|
|
1549
|
+
});
|
|
1550
|
+
}
|
|
1551
|
+
if (offsetString !== void 0 && !(hasFullDate && hasTime)) {
|
|
1552
|
+
throw new FormatSyntaxError({
|
|
1553
|
+
format: formatStr,
|
|
1554
|
+
message: `temporal-fmt: format string "${formatStr}" has an offset token (X/XX/XXX/x/xx/xxx) but needs a full date and time to build a ZonedDateTime.`
|
|
1555
|
+
});
|
|
1556
|
+
}
|
|
1557
|
+
if (weekdayExpected !== void 0 && !hasFullDate) {
|
|
1558
|
+
throw new FormatSyntaxError({
|
|
1559
|
+
format: formatStr,
|
|
1560
|
+
message: `temporal-fmt: format string "${formatStr}" has a weekday token ("EEEE"/"EEE") but needs a full date to validate it against.`
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1563
|
+
if (!hasFullDate && !hasTime) {
|
|
1564
|
+
throw new FormatSyntaxError({
|
|
1565
|
+
format: formatStr,
|
|
1566
|
+
message: `temporal-fmt: format string "${formatStr}" has no date or time tokens to parse.`
|
|
1567
|
+
});
|
|
1568
|
+
}
|
|
1569
|
+
const temporal = getTemporal();
|
|
1570
|
+
const timeFields = {
|
|
1571
|
+
hour: hour ?? 0,
|
|
1572
|
+
minute: minute ?? 0,
|
|
1573
|
+
second: second ?? 0,
|
|
1574
|
+
millisecond: millisecond ?? 0,
|
|
1575
|
+
microsecond: microsecond ?? 0,
|
|
1576
|
+
nanosecond: nanosecond ?? 0
|
|
1577
|
+
};
|
|
1578
|
+
const calendarField = calendar ? { calendar } : {};
|
|
1579
|
+
const reject = { overflow: "reject" };
|
|
1580
|
+
let result;
|
|
1581
|
+
try {
|
|
1582
|
+
if (timeZoneId !== void 0) {
|
|
1583
|
+
const zoneOptions = { overflow: "reject", offset: "prefer" };
|
|
1584
|
+
result = temporal.ZonedDateTime.from(
|
|
1585
|
+
{
|
|
1586
|
+
year,
|
|
1587
|
+
month,
|
|
1588
|
+
day,
|
|
1589
|
+
...timeFields,
|
|
1590
|
+
...calendarField,
|
|
1591
|
+
timeZone: timeZoneId,
|
|
1592
|
+
...offsetString !== void 0 ? { offset: offsetString } : {}
|
|
1593
|
+
},
|
|
1594
|
+
zoneOptions
|
|
1595
|
+
);
|
|
1596
|
+
if (offsetString !== void 0) {
|
|
1597
|
+
const zdt = result;
|
|
1598
|
+
const wallClockShifted = zdt.hour !== timeFields.hour || zdt.minute !== timeFields.minute || zdt.second !== timeFields.second;
|
|
1599
|
+
if (wallClockShifted) {
|
|
1600
|
+
throw new InvalidDateError({
|
|
1601
|
+
input,
|
|
1602
|
+
format: formatStr,
|
|
1603
|
+
message: `"${timeZoneId}" has no such wall-clock time on this date \u2014 it falls in a DST gap, not an ambiguous or valid instant.`
|
|
1604
|
+
});
|
|
1605
|
+
}
|
|
1606
|
+
const actualOffset = zdt.offset;
|
|
1607
|
+
if (actualOffset !== offsetString) {
|
|
1608
|
+
throw new ParseMismatchError({
|
|
1609
|
+
input,
|
|
1610
|
+
format: formatStr,
|
|
1611
|
+
message: `has both a "zzz" zone (${timeZoneId}) and an offset token (${offsetString}), but the zone's actual offset at this date/time is ${actualOffset}, not ${offsetString}.`
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
} else if (offsetString !== void 0) {
|
|
1616
|
+
throw new ParseMismatchError({
|
|
1617
|
+
input,
|
|
1618
|
+
format: formatStr,
|
|
1619
|
+
message: `format string "${formatStr}" has an offset token but no "zzz" zone token. An offset does not identify a time zone by itself \u2014 add "zzz" to the pattern, or parse into a PlainDateTime/PlainDate/PlainTime if a zone isn't needed.`
|
|
1620
|
+
});
|
|
1621
|
+
} else if (hasFullDate && hasTime) {
|
|
1622
|
+
result = temporal.PlainDateTime.from({ year, month, day, ...timeFields, ...calendarField }, reject);
|
|
1623
|
+
} else if (hasFullDate) {
|
|
1624
|
+
result = temporal.PlainDate.from({ year, month, day, ...calendarField }, reject);
|
|
1625
|
+
} else {
|
|
1626
|
+
result = temporal.PlainTime.from(timeFields, reject);
|
|
1627
|
+
}
|
|
1628
|
+
} catch (err) {
|
|
1629
|
+
throw new InvalidDateError({
|
|
1630
|
+
input,
|
|
1631
|
+
format: formatStr,
|
|
1632
|
+
message: `temporal-fmt: "${input}" doesn't describe a valid date/time for format "${formatStr}": ${err.message}`
|
|
1633
|
+
});
|
|
1634
|
+
}
|
|
1635
|
+
if (weekdayExpected !== void 0) {
|
|
1636
|
+
const actual = result.dayOfWeek;
|
|
1637
|
+
if (actual !== weekdayExpected) {
|
|
1638
|
+
const vocab = getLocaleVocab(locale);
|
|
1639
|
+
throw new InvalidDateError({
|
|
1640
|
+
input,
|
|
1641
|
+
format: formatStr,
|
|
1642
|
+
message: `temporal-fmt: "${weekdayRaw}" doesn't match the actual weekday (${vocab.weekdayLong[actual - 1]}) for the parsed date.`
|
|
1643
|
+
});
|
|
1644
|
+
}
|
|
1645
|
+
}
|
|
1646
|
+
if (quarter !== void 0 && month !== void 0) {
|
|
1647
|
+
const expectedQuarter = Math.ceil(month / 3);
|
|
1648
|
+
if (quarter !== expectedQuarter) {
|
|
1649
|
+
throw new InvalidDateError({
|
|
1650
|
+
format: formatStr,
|
|
1651
|
+
message: `temporal-fmt: format string "${formatStr}" contains a quarter token (Q/QQQ) whose value (Q${quarter}) disagrees with the parsed month's actual quarter \u2014 month ${month} is in Q${expectedQuarter}.`
|
|
1652
|
+
});
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
return result;
|
|
1656
|
+
}
|
|
1657
|
+
function safeParse(formatStr, input, options = {}) {
|
|
1658
|
+
try {
|
|
1659
|
+
return { ok: true, value: parse(formatStr, input, options) };
|
|
1660
|
+
} catch (err) {
|
|
1661
|
+
/* c8 ignore start @preserve */
|
|
1662
|
+
if (err instanceof TemporalFmtError) {
|
|
1663
|
+
return { ok: false, error: err };
|
|
1664
|
+
}
|
|
1665
|
+
return { ok: false, error: wrapUntypedError(err, { input, format: formatStr }) };
|
|
1666
|
+
}
|
|
1667
|
+
/* c8 ignore stop @preserve */
|
|
1668
|
+
}
|
|
1669
|
+
function tryParse(formatStr, input, options = {}) {
|
|
1670
|
+
try {
|
|
1671
|
+
return parse(formatStr, input, options);
|
|
1672
|
+
} catch {
|
|
1673
|
+
return void 0;
|
|
1674
|
+
}
|
|
1675
|
+
}
|
|
1676
|
+
function parseToParts(formatStr, input, options = {}) {
|
|
1677
|
+
if (formatStr.length > MAX_FORMAT_LENGTH) {
|
|
1678
|
+
throw new FormatSyntaxError({
|
|
1679
|
+
format: formatStr,
|
|
1680
|
+
message: `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`
|
|
1681
|
+
});
|
|
1682
|
+
}
|
|
1683
|
+
if (input.length > MAX_INPUT_LENGTH) {
|
|
1684
|
+
throw new FormatSyntaxError({
|
|
1685
|
+
input,
|
|
1686
|
+
message: `temporal-fmt: input exceeds maximum length of ${MAX_INPUT_LENGTH} characters (got ${input.length}).`
|
|
1687
|
+
});
|
|
1688
|
+
}
|
|
1689
|
+
if (options.parseNumberingSystem) {
|
|
1690
|
+
input = applyParseNumbering(input, options);
|
|
1691
|
+
}
|
|
1692
|
+
const locale = options.locale ?? DEFAULT_LOCALE;
|
|
1693
|
+
const pattern = getPattern(formatStr, locale);
|
|
1694
|
+
const match = pattern.regex.exec(input);
|
|
1695
|
+
if (!match) {
|
|
1696
|
+
throw new ParseMismatchError({
|
|
1697
|
+
input,
|
|
1698
|
+
format: formatStr,
|
|
1699
|
+
// reason set explicitly (not just message): parse.test.js's
|
|
1700
|
+
// "safeParse: failure returns { ok: false, error } with a
|
|
1701
|
+
// TemporalFmtError" asserts result.error.reason carries the
|
|
1702
|
+
// underlying detail text, matching what wrapUntypedError used to
|
|
1703
|
+
// populate when this message reached it as a caught plain Error.
|
|
1704
|
+
reason: "no valid pattern matches the format string and input shape",
|
|
1705
|
+
message: `temporal-fmt: no valid pattern matches the format string and input shape`
|
|
1706
|
+
});
|
|
1707
|
+
}
|
|
1708
|
+
if (pattern.groups.length === 0) {
|
|
1709
|
+
throw new ParseMismatchError({
|
|
1710
|
+
format: formatStr,
|
|
1711
|
+
// reason set explicitly: errors.test.js's "format string with no
|
|
1712
|
+
// tokens at all falls through to ParseMismatchError" asserts
|
|
1713
|
+
// error.reason matches /has no tokens/.
|
|
1714
|
+
reason: `format string "${formatStr}" has no tokens \u2014 nothing to parse into a value.`,
|
|
1715
|
+
message: `temporal-fmt: format string "${formatStr}" has no tokens \u2014 nothing to parse into a value.`
|
|
1716
|
+
});
|
|
1717
|
+
}
|
|
1718
|
+
for (const { name, token } of pattern.groups) {
|
|
1719
|
+
if (token === "zzz" && !isValidTimeZone(match.groups[name])) {
|
|
1720
|
+
throw new InvalidTimeZoneError({
|
|
1721
|
+
input,
|
|
1722
|
+
format: formatStr,
|
|
1723
|
+
actual: match.groups[name],
|
|
1724
|
+
reason: "not a recognized IANA time zone identifier"
|
|
1725
|
+
});
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
const runValues = /* @__PURE__ */ new Map();
|
|
1729
|
+
for (const run of pattern.ambiguousRuns) {
|
|
1730
|
+
const runDigits = match.groups[run.groupName];
|
|
1731
|
+
const splits = enumerateValidSplits(runDigits, run.tokens);
|
|
1732
|
+
if (splits.length === 0) {
|
|
1733
|
+
throw new ParseMismatchError({
|
|
1734
|
+
input,
|
|
1735
|
+
format: formatStr,
|
|
1736
|
+
reason: "no valid pattern matches the format string and input shape",
|
|
1737
|
+
message: `temporal-fmt: no valid pattern matches the format string and input shape`
|
|
1738
|
+
});
|
|
1739
|
+
}
|
|
1740
|
+
if (splits.length > 1) {
|
|
1741
|
+
if (!options.lenient) {
|
|
1742
|
+
throw new AmbiguousInputError({
|
|
1743
|
+
input,
|
|
1744
|
+
format: formatStr,
|
|
1745
|
+
message: `temporal-fmt: "${runDigits}" in format string "${formatStr}" is ambiguous \u2014 ${splits.length} different ways to read tokens "${run.tokens.join("")}" (with no separator between them) are all individually valid (e.g. ${JSON.stringify(splits[0])} vs ${JSON.stringify(splits[1])}). parse() won't guess; add a separator between these tokens, or use their padded form (e.g. "MM" instead of "M") so each one has a fixed width. Pass { lenient: true } to opt into a documented heuristic that picks one.`
|
|
1746
|
+
});
|
|
1747
|
+
}
|
|
1748
|
+
const picked = pickLenientSplit(splits, run.tokens);
|
|
1749
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(picked[idx])));
|
|
1750
|
+
} else {
|
|
1751
|
+
run.groupNames.forEach((name, idx) => runValues.set(name, String(splits[0][idx])));
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
const parts = [];
|
|
1755
|
+
const indices = match.indices;
|
|
1756
|
+
const groupIndices = indices?.groups;
|
|
1757
|
+
let consumed = 0;
|
|
1758
|
+
for (const { name, token } of pattern.groups) {
|
|
1759
|
+
const raw = runValues.get(name) ?? match.groups[name];
|
|
1760
|
+
const fromIndices = !runValues.has(name) && groupIndices?.[name];
|
|
1761
|
+
const position = fromIndices ? fromIndices[0] : (match.index ?? 0) + consumed;
|
|
1762
|
+
parts.push({ token, raw, position });
|
|
1763
|
+
consumed += raw.length;
|
|
1764
|
+
}
|
|
1765
|
+
return parts;
|
|
1766
|
+
}
|
|
1767
|
+
function compileParser(formatStr, options = {}) {
|
|
1768
|
+
if (formatStr.length > MAX_FORMAT_LENGTH) {
|
|
1769
|
+
throw new FormatSyntaxError({
|
|
1770
|
+
format: formatStr,
|
|
1771
|
+
message: `temporal-fmt: format string exceeds maximum length of ${MAX_FORMAT_LENGTH} characters (got ${formatStr.length}).`
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
const locale = options.locale ?? DEFAULT_LOCALE;
|
|
1775
|
+
const pattern = getPattern(formatStr, locale);
|
|
1776
|
+
return {
|
|
1777
|
+
formatStr,
|
|
1778
|
+
pattern,
|
|
1779
|
+
parse(input, opts = {}) {
|
|
1780
|
+
return parse(formatStr, input, { locale, ...opts });
|
|
1781
|
+
},
|
|
1782
|
+
safeParse(input, opts = {}) {
|
|
1783
|
+
return safeParse(formatStr, input, { locale, ...opts });
|
|
1784
|
+
},
|
|
1785
|
+
tryParse(input, opts = {}) {
|
|
1786
|
+
return tryParse(formatStr, input, { locale, ...opts });
|
|
1787
|
+
},
|
|
1788
|
+
parseToParts(input, opts = {}) {
|
|
1789
|
+
return parseToParts(formatStr, input, { locale, ...opts });
|
|
1790
|
+
}
|
|
1791
|
+
};
|
|
1792
|
+
}
|
|
1793
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
1794
|
+
0 && (module.exports = {
|
|
1795
|
+
compileParser,
|
|
1796
|
+
parse,
|
|
1797
|
+
parseToParts,
|
|
1798
|
+
safeParse,
|
|
1799
|
+
tryParse
|
|
1800
|
+
});
|
|
74
1801
|
//# sourceMappingURL=parse.cjs.map
|