@bevelo/date 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,328 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_civil = require("./civil-QU5EukOm.cjs");
3
+ // src/pattern.ts
4
+ const ISO_LAYOUT = {
5
+ order: [
6
+ "year",
7
+ "month",
8
+ "day"
9
+ ],
10
+ before: [
11
+ "",
12
+ "-",
13
+ "-"
14
+ ],
15
+ after: ""
16
+ };
17
+ /** 2001-02-03, chosen so year, month and day are three different values. */
18
+ const PROBE = new Date(Date.UTC(2001, 1, 3));
19
+ /** A four-digit year, the ISO form that needs no locale to read. */
20
+ const ISO_DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
21
+ const layouts = /* @__PURE__ */ new Map();
22
+ /**
23
+ * The order in which a locale writes a numeric date.
24
+ *
25
+ * Derived from `Intl.DateTimeFormat(locale).formatToParts` on a fixed probe
26
+ * date, never from a table: the formatter knows about locales the package has
27
+ * never heard of. Falls back to ISO order (year, month, day) when Intl is
28
+ * unavailable or rejects the tag, because that is the one order a reader cannot
29
+ * misread.
30
+ *
31
+ * @example dateOrder("en-US") // ["month", "day", "year"]
32
+ */
33
+ function dateOrder(locale) {
34
+ return layoutFor(locale).order;
35
+ }
36
+ /**
37
+ * Reads a date typed in the locale's own order.
38
+ *
39
+ * Tolerant where a person is tolerant: surrounding whitespace, any run of
40
+ * non-digits as a separator (`-`, `/`, `.`, a space, the right-to-left marks an
41
+ * Arabic formatter inserts), and one- or two-digit month and day. It is not a
42
+ * general date parser: a month name or a time makes the input invalid, because
43
+ * guessing there is how a calendar picks the wrong day.
44
+ *
45
+ * A two-digit year is windowed the way a paper form is: 00-49 is 2000-2049 and
46
+ * 50-99 is 1950-1999. The window is fixed rather than relative to a clock, so
47
+ * the same text parses to the same date in a test, on a server and next year.
48
+ * A four-digit ISO date (`2024-02-03`) is accepted in every locale before the
49
+ * locale order is applied, because it cannot be misread.
50
+ *
51
+ * Returns undefined for anything invalid — an impossible date, a leap day in a
52
+ * non-leap year, too few or too many fields, a one- or three-digit year — and
53
+ * never throws: this runs on every keystroke of a date input.
54
+ */
55
+ function parseDateInput(text, locale) {
56
+ if (typeof text !== "string") return;
57
+ const value = text.trim();
58
+ if (value === "") return;
59
+ const iso = parseIso(value);
60
+ if (iso !== void 0) return iso;
61
+ const tokens = value.split(/\D+/).filter((token) => token !== "");
62
+ if (tokens.length !== 3) return;
63
+ const layout = layoutFor(locale);
64
+ const fields = {};
65
+ for (const [index, field] of layout.order.entries()) {
66
+ const token = tokens[index] ?? "";
67
+ const number = field === "year" ? parseYearToken(token) : parseDayOrMonth(token);
68
+ if (number === void 0) return;
69
+ fields[field] = number;
70
+ }
71
+ const candidate = {
72
+ year: fields.year,
73
+ month: fields.month,
74
+ day: fields.day
75
+ };
76
+ return require_civil.isValidDate(candidate) ? candidate : void 0;
77
+ }
78
+ /**
79
+ * Writes a date in the locale's own order, zero-padded to the width a date input
80
+ * expects: two digits for month and day, four for the year.
81
+ *
82
+ * The output is the string `parseDateInput` reads back for every year this
83
+ * format can name (0 through 9999), so a controlled input can format state and
84
+ * parse what the user typed with the same pair of functions.
85
+ *
86
+ * Returns undefined for an invalid civil date and for a year outside 0..9999,
87
+ * which the four-digit field cannot express. Falls back to ISO when Intl is
88
+ * unavailable, matching the rest of the package.
89
+ */
90
+ function formatDateInput(date, locale) {
91
+ if (!require_civil.isValidDate(date) || date.year < 0 || date.year > 9999) return;
92
+ const { order, before, after } = layoutFor(locale);
93
+ const field = (name) => name === "year" ? require_civil.pad(date.year, 4) : require_civil.pad(name === "month" ? date.month : date.day, 2);
94
+ return before[0] + field(order[0]) + before[1] + field(order[1]) + before[2] + field(order[2]) + after;
95
+ }
96
+ /** The layout for a locale, probed once and cached; a bad tag caches the ISO fallback. */
97
+ function layoutFor(locale) {
98
+ const cached = layouts.get(locale);
99
+ if (cached !== void 0) return cached;
100
+ let layout = ISO_LAYOUT;
101
+ if (require_civil.hasIntl()) try {
102
+ layout = readLayout(new Intl.DateTimeFormat(locale, {
103
+ year: "numeric",
104
+ month: "2-digit",
105
+ day: "2-digit",
106
+ calendar: "gregory",
107
+ numberingSystem: "latn",
108
+ timeZone: "UTC"
109
+ }).formatToParts(PROBE)) ?? ISO_LAYOUT;
110
+ } catch {
111
+ layout = ISO_LAYOUT;
112
+ }
113
+ layouts.set(locale, layout);
114
+ return layout;
115
+ }
116
+ /** Reads the field order and the literals around them out of a formatter's parts. */
117
+ function readLayout(parts) {
118
+ const order = [];
119
+ const before = [];
120
+ let literal = "";
121
+ for (const part of parts) if (part.type === "year" || part.type === "month" || part.type === "day") {
122
+ order.push(part.type);
123
+ before.push(literal);
124
+ literal = "";
125
+ } else literal += part.value;
126
+ if (order.length !== 3) return;
127
+ return {
128
+ order,
129
+ before,
130
+ after: literal
131
+ };
132
+ }
133
+ /** A four-digit year as written, or a windowed two-digit one. */
134
+ function parseYearToken(token) {
135
+ if (/^\d{4}$/.test(token)) return Number(token);
136
+ if (!/^\d{2}$/.test(token)) return;
137
+ const short = Number(token);
138
+ return short <= 49 ? 2e3 + short : 1900 + short;
139
+ }
140
+ /** A month or day as written: one or two digits, no sign, no padding requirement. */
141
+ function parseDayOrMonth(token) {
142
+ return /^\d{1,2}$/.test(token) ? Number(token) : void 0;
143
+ }
144
+ /** The ISO form, tried first in every locale because it is unambiguous. */
145
+ function parseIso(value) {
146
+ const match = ISO_DATE.exec(value);
147
+ if (match === null) return;
148
+ const candidate = {
149
+ year: Number(match[1]),
150
+ month: Number(match[2]),
151
+ day: Number(match[3])
152
+ };
153
+ return require_civil.isValidDate(candidate) ? candidate : void 0;
154
+ }
155
+ const DIRECTION_MARKS = /[‎‏؜]/g;
156
+ /**
157
+ * Reads a date a person typed or pasted into a date field.
158
+ *
159
+ * Wider than `parseDateInput`: besides the locale's numeric order with any
160
+ * separator, it reads digits alone ("10202026"), a month by name or by an
161
+ * unambiguous start of three letters ("dec 3", "3 December 2026"), weekday
162
+ * names beside the date, and a date with no year, which takes the year of
163
+ * `referenceDate`. A two-digit year lands in the hundred years that end
164
+ * twenty years after that year.
165
+ *
166
+ * Returns undefined for anything that is not one real date. Never throws.
167
+ */
168
+ function parseTypedDate(text, locale, options = {}) {
169
+ if (typeof text !== "string") return;
170
+ const value = text.replace(DIRECTION_MARKS, "").trim();
171
+ if (value === "") return;
172
+ const iso = parseIso(value);
173
+ if (iso !== void 0) return iso;
174
+ const referenceYear = options.referenceDate?.year ?? (/* @__PURE__ */ new Date()).getFullYear();
175
+ const words = wordsFor(locale);
176
+ const numbers = [];
177
+ let namedMonth;
178
+ for (const token of value.toLocaleLowerCase(locale).match(/\d+|[\p{L}\p{M}]+/gu) ?? []) {
179
+ if (/^\d+$/.test(token)) {
180
+ numbers.push(token);
181
+ continue;
182
+ }
183
+ const month = monthFromName(token, words.months);
184
+ if (month !== void 0 && namedMonth === void 0) namedMonth = month;
185
+ else if (!words.other.has(token)) return;
186
+ }
187
+ const order = layoutFor(locale).order;
188
+ const fields = {};
189
+ if (namedMonth !== void 0) {
190
+ if (numbers.length === 0 || numbers.length > 2) return;
191
+ fields.month = String(namedMonth);
192
+ (numbers.length === 1 ? ["day"] : words.namedOrder.filter((field) => field !== "month")).forEach((field, index) => fields[field] = numbers[index] ?? "");
193
+ } else if (numbers.length === 1) {
194
+ const digits = numbers[0] ?? "";
195
+ if (digits.length !== 8 && digits.length !== 6) return;
196
+ let offset = 0;
197
+ for (const field of order) {
198
+ const length = field === "year" ? digits.length - 4 : 2;
199
+ fields[field] = digits.slice(offset, offset += length);
200
+ }
201
+ } else if (numbers.length === 2 || numbers.length === 3) (numbers.length === 3 ? order : order.filter((field) => field !== "year")).forEach((field, index) => fields[field] = numbers[index] ?? "");
202
+ else return;
203
+ const candidate = {
204
+ year: fields.year === void 0 ? referenceYear : typedYear(fields.year, referenceYear),
205
+ month: Number(fields.month),
206
+ day: Number(fields.day)
207
+ };
208
+ return require_civil.isValidDate(candidate) ? candidate : void 0;
209
+ }
210
+ /**
211
+ * The format a locale's numeric date is typed in, as a placeholder: "MM/DD/YYYY"
212
+ * in American English, "TT.MM.JJJJ" in German. Each field repeats the first
213
+ * letter of its name in the locale when the script has capitals, else the
214
+ * English letter.
215
+ */
216
+ function datePlaceholder(locale) {
217
+ const cached = placeholders.get(locale);
218
+ if (cached !== void 0) return cached;
219
+ const { order, before, after } = layoutFor(locale);
220
+ const letters = fieldLetters(locale);
221
+ const field = (name) => letters[name].repeat(name === "year" ? 4 : 2);
222
+ const placeholder = (before[0] + field(order[0]) + before[1] + field(order[1]) + before[2] + field(order[2]) + after).replace(DIRECTION_MARKS, "");
223
+ placeholders.set(locale, placeholder);
224
+ return placeholder;
225
+ }
226
+ const placeholders = /* @__PURE__ */ new Map();
227
+ const ENGLISH_LETTERS = {
228
+ year: "Y",
229
+ month: "M",
230
+ day: "D"
231
+ };
232
+ function fieldLetters(locale) {
233
+ if (!require_civil.hasIntl() || typeof Intl.DisplayNames !== "function") return ENGLISH_LETTERS;
234
+ try {
235
+ const names = new Intl.DisplayNames(locale, { type: "dateTimeField" });
236
+ const letter = (field) => {
237
+ const first = names.of(field)?.[0]?.toLocaleUpperCase(locale);
238
+ return first !== void 0 && first !== first.toLocaleLowerCase(locale) ? first : ENGLISH_LETTERS[field];
239
+ };
240
+ return {
241
+ year: letter("year"),
242
+ month: letter("month"),
243
+ day: letter("day")
244
+ };
245
+ } catch {
246
+ return ENGLISH_LETTERS;
247
+ }
248
+ }
249
+ function typedYear(token, referenceYear) {
250
+ const year = Number(token);
251
+ if (token.length !== 2) return year;
252
+ const century = Math.floor((referenceYear + 20) / 100) * 100;
253
+ return century + year > referenceYear + 20 ? century - 100 + year : century + year;
254
+ }
255
+ const dateWords = /* @__PURE__ */ new Map();
256
+ function wordsFor(locale) {
257
+ const cached = dateWords.get(locale);
258
+ if (cached !== void 0) return cached;
259
+ const months = /* @__PURE__ */ new Map();
260
+ const other = /* @__PURE__ */ new Set();
261
+ let namedOrder = [
262
+ "month",
263
+ "day",
264
+ "year"
265
+ ];
266
+ const addWords = (text) => {
267
+ for (const word of text.toLocaleLowerCase(locale).match(/[\p{L}\p{M}]+/gu) ?? []) other.add(word);
268
+ };
269
+ if (require_civil.hasIntl()) for (const tag of [locale, "en-US"]) try {
270
+ for (const width of ["long", "short"]) {
271
+ const standalone = new Intl.DateTimeFormat(tag, {
272
+ month: width,
273
+ timeZone: "UTC"
274
+ });
275
+ const inDate = new Intl.DateTimeFormat(tag, {
276
+ month: width,
277
+ day: "numeric",
278
+ timeZone: "UTC"
279
+ });
280
+ const weekday = new Intl.DateTimeFormat(tag, {
281
+ weekday: width,
282
+ timeZone: "UTC"
283
+ });
284
+ for (let index = 0; index < 12; index++) {
285
+ const at = Date.UTC(2001, index, 16);
286
+ const name = inDate.formatToParts(at).find((part) => part.type === "month")?.value ?? "";
287
+ for (const text of [standalone.format(at), name]) {
288
+ const key = text.toLocaleLowerCase(locale).replace(/\.$/, "");
289
+ if (/\p{L}/u.test(key) && !months.has(key)) months.set(key, index + 1);
290
+ }
291
+ }
292
+ for (let index = 0; index < 7; index++) addWords(weekday.format(Date.UTC(2001, 0, 7 + index)));
293
+ }
294
+ const named = new Intl.DateTimeFormat(tag, {
295
+ year: "numeric",
296
+ month: "long",
297
+ day: "numeric",
298
+ weekday: "long",
299
+ timeZone: "UTC"
300
+ }).formatToParts(PROBE);
301
+ if (tag === locale) namedOrder = named.map((part) => part.type).filter((type) => type === "year" || type === "month" || type === "day");
302
+ for (const part of named) if (part.type === "literal") addWords(part.value);
303
+ } catch {}
304
+ const words = {
305
+ months,
306
+ other,
307
+ namedOrder
308
+ };
309
+ dateWords.set(locale, words);
310
+ return words;
311
+ }
312
+ /** The month a word names: a whole name, or the start of exactly one month's names, three letters or more. */
313
+ function monthFromName(word, months) {
314
+ const exact = months.get(word);
315
+ if (exact !== void 0) return exact;
316
+ if (word.length < 3) return;
317
+ let found;
318
+ for (const [name, month] of months) if (name.startsWith(word)) {
319
+ if (found !== void 0 && found !== month) return;
320
+ found = month;
321
+ }
322
+ return found;
323
+ }
324
+ exports.dateOrder = dateOrder;
325
+ exports.datePlaceholder = datePlaceholder;
326
+ exports.formatDateInput = formatDateInput;
327
+ exports.parseDateInput = parseDateInput;
328
+ exports.parseTypedDate = parseTypedDate;
@@ -0,0 +1,75 @@
1
+ import { t as CivilDate } from "./civil-GPupvlwZ.cjs";
2
+ /** The three fields a numeric date is made of, in the order a locale writes them. */
3
+ export type DateField = "year" | "month" | "day";
4
+ /** A locale's numeric field order: en-US is month/day/year, ja-JP is year/month/day. */
5
+ export type DateOrder = readonly [DateField, DateField, DateField];
6
+ /**
7
+ * The order in which a locale writes a numeric date.
8
+ *
9
+ * Derived from `Intl.DateTimeFormat(locale).formatToParts` on a fixed probe
10
+ * date, never from a table: the formatter knows about locales the package has
11
+ * never heard of. Falls back to ISO order (year, month, day) when Intl is
12
+ * unavailable or rejects the tag, because that is the one order a reader cannot
13
+ * misread.
14
+ *
15
+ * @example dateOrder("en-US") // ["month", "day", "year"]
16
+ */
17
+ export declare function dateOrder(locale: string): DateOrder;
18
+ /**
19
+ * Reads a date typed in the locale's own order.
20
+ *
21
+ * Tolerant where a person is tolerant: surrounding whitespace, any run of
22
+ * non-digits as a separator (`-`, `/`, `.`, a space, the right-to-left marks an
23
+ * Arabic formatter inserts), and one- or two-digit month and day. It is not a
24
+ * general date parser: a month name or a time makes the input invalid, because
25
+ * guessing there is how a calendar picks the wrong day.
26
+ *
27
+ * A two-digit year is windowed the way a paper form is: 00-49 is 2000-2049 and
28
+ * 50-99 is 1950-1999. The window is fixed rather than relative to a clock, so
29
+ * the same text parses to the same date in a test, on a server and next year.
30
+ * A four-digit ISO date (`2024-02-03`) is accepted in every locale before the
31
+ * locale order is applied, because it cannot be misread.
32
+ *
33
+ * Returns undefined for anything invalid — an impossible date, a leap day in a
34
+ * non-leap year, too few or too many fields, a one- or three-digit year — and
35
+ * never throws: this runs on every keystroke of a date input.
36
+ */
37
+ export declare function parseDateInput(text: string, locale: string): CivilDate | undefined;
38
+ /**
39
+ * Writes a date in the locale's own order, zero-padded to the width a date input
40
+ * expects: two digits for month and day, four for the year.
41
+ *
42
+ * The output is the string `parseDateInput` reads back for every year this
43
+ * format can name (0 through 9999), so a controlled input can format state and
44
+ * parse what the user typed with the same pair of functions.
45
+ *
46
+ * Returns undefined for an invalid civil date and for a year outside 0..9999,
47
+ * which the four-digit field cannot express. Falls back to ISO when Intl is
48
+ * unavailable, matching the rest of the package.
49
+ */
50
+ export declare function formatDateInput(date: CivilDate, locale: string): string | undefined;
51
+ /** Options for `parseTypedDate`. */
52
+ export type ParseTypedDateOptions = {
53
+ /** The date whose year a date typed without one takes. Defaults to the clock's year. */
54
+ readonly referenceDate?: CivilDate | undefined;
55
+ };
56
+ /**
57
+ * Reads a date a person typed or pasted into a date field.
58
+ *
59
+ * Wider than `parseDateInput`: besides the locale's numeric order with any
60
+ * separator, it reads digits alone ("10202026"), a month by name or by an
61
+ * unambiguous start of three letters ("dec 3", "3 December 2026"), weekday
62
+ * names beside the date, and a date with no year, which takes the year of
63
+ * `referenceDate`. A two-digit year lands in the hundred years that end
64
+ * twenty years after that year.
65
+ *
66
+ * Returns undefined for anything that is not one real date. Never throws.
67
+ */
68
+ export declare function parseTypedDate(text: string, locale: string, options?: ParseTypedDateOptions): CivilDate | undefined;
69
+ /**
70
+ * The format a locale's numeric date is typed in, as a placeholder: "MM/DD/YYYY"
71
+ * in American English, "TT.MM.JJJJ" in German. Each field repeats the first
72
+ * letter of its name in the locale when the script has capitals, else the
73
+ * English letter.
74
+ */
75
+ export declare function datePlaceholder(locale: string): string;
@@ -0,0 +1,75 @@
1
+ import { t as CivilDate } from "./civil-GPupvlwZ.js";
2
+ /** The three fields a numeric date is made of, in the order a locale writes them. */
3
+ export type DateField = "year" | "month" | "day";
4
+ /** A locale's numeric field order: en-US is month/day/year, ja-JP is year/month/day. */
5
+ export type DateOrder = readonly [DateField, DateField, DateField];
6
+ /**
7
+ * The order in which a locale writes a numeric date.
8
+ *
9
+ * Derived from `Intl.DateTimeFormat(locale).formatToParts` on a fixed probe
10
+ * date, never from a table: the formatter knows about locales the package has
11
+ * never heard of. Falls back to ISO order (year, month, day) when Intl is
12
+ * unavailable or rejects the tag, because that is the one order a reader cannot
13
+ * misread.
14
+ *
15
+ * @example dateOrder("en-US") // ["month", "day", "year"]
16
+ */
17
+ export declare function dateOrder(locale: string): DateOrder;
18
+ /**
19
+ * Reads a date typed in the locale's own order.
20
+ *
21
+ * Tolerant where a person is tolerant: surrounding whitespace, any run of
22
+ * non-digits as a separator (`-`, `/`, `.`, a space, the right-to-left marks an
23
+ * Arabic formatter inserts), and one- or two-digit month and day. It is not a
24
+ * general date parser: a month name or a time makes the input invalid, because
25
+ * guessing there is how a calendar picks the wrong day.
26
+ *
27
+ * A two-digit year is windowed the way a paper form is: 00-49 is 2000-2049 and
28
+ * 50-99 is 1950-1999. The window is fixed rather than relative to a clock, so
29
+ * the same text parses to the same date in a test, on a server and next year.
30
+ * A four-digit ISO date (`2024-02-03`) is accepted in every locale before the
31
+ * locale order is applied, because it cannot be misread.
32
+ *
33
+ * Returns undefined for anything invalid — an impossible date, a leap day in a
34
+ * non-leap year, too few or too many fields, a one- or three-digit year — and
35
+ * never throws: this runs on every keystroke of a date input.
36
+ */
37
+ export declare function parseDateInput(text: string, locale: string): CivilDate | undefined;
38
+ /**
39
+ * Writes a date in the locale's own order, zero-padded to the width a date input
40
+ * expects: two digits for month and day, four for the year.
41
+ *
42
+ * The output is the string `parseDateInput` reads back for every year this
43
+ * format can name (0 through 9999), so a controlled input can format state and
44
+ * parse what the user typed with the same pair of functions.
45
+ *
46
+ * Returns undefined for an invalid civil date and for a year outside 0..9999,
47
+ * which the four-digit field cannot express. Falls back to ISO when Intl is
48
+ * unavailable, matching the rest of the package.
49
+ */
50
+ export declare function formatDateInput(date: CivilDate, locale: string): string | undefined;
51
+ /** Options for `parseTypedDate`. */
52
+ export type ParseTypedDateOptions = {
53
+ /** The date whose year a date typed without one takes. Defaults to the clock's year. */
54
+ readonly referenceDate?: CivilDate | undefined;
55
+ };
56
+ /**
57
+ * Reads a date a person typed or pasted into a date field.
58
+ *
59
+ * Wider than `parseDateInput`: besides the locale's numeric order with any
60
+ * separator, it reads digits alone ("10202026"), a month by name or by an
61
+ * unambiguous start of three letters ("dec 3", "3 December 2026"), weekday
62
+ * names beside the date, and a date with no year, which takes the year of
63
+ * `referenceDate`. A two-digit year lands in the hundred years that end
64
+ * twenty years after that year.
65
+ *
66
+ * Returns undefined for anything that is not one real date. Never throws.
67
+ */
68
+ export declare function parseTypedDate(text: string, locale: string, options?: ParseTypedDateOptions): CivilDate | undefined;
69
+ /**
70
+ * The format a locale's numeric date is typed in, as a placeholder: "MM/DD/YYYY"
71
+ * in American English, "TT.MM.JJJJ" in German. Each field repeats the first
72
+ * letter of its name in the locale when the script has capitals, else the
73
+ * English letter.
74
+ */
75
+ export declare function datePlaceholder(locale: string): string;