@c9up/chronos 0.1.15 → 0.1.17

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.
Files changed (74) hide show
  1. package/README.md +136 -16
  2. package/dist/DateTime.d.ts +209 -8
  3. package/dist/DateTime.d.ts.map +1 -1
  4. package/dist/DateTime.js +815 -116
  5. package/dist/DateTime.js.map +1 -1
  6. package/dist/Duration.d.ts +37 -20
  7. package/dist/Duration.d.ts.map +1 -1
  8. package/dist/Duration.js +287 -120
  9. package/dist/Duration.js.map +1 -1
  10. package/dist/Interval.d.ts +50 -7
  11. package/dist/Interval.d.ts.map +1 -1
  12. package/dist/Interval.js +142 -29
  13. package/dist/Interval.js.map +1 -1
  14. package/dist/atlas.d.ts +11 -15
  15. package/dist/atlas.d.ts.map +1 -1
  16. package/dist/atlas.js +22 -17
  17. package/dist/atlas.js.map +1 -1
  18. package/dist/format.d.ts +47 -0
  19. package/dist/format.d.ts.map +1 -0
  20. package/dist/format.js +387 -0
  21. package/dist/format.js.map +1 -0
  22. package/dist/holidays.d.ts +43 -0
  23. package/dist/holidays.d.ts.map +1 -0
  24. package/dist/holidays.js +102 -0
  25. package/dist/holidays.js.map +1 -0
  26. package/dist/index.d.ts +8 -6
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +4 -3
  29. package/dist/index.js.map +1 -1
  30. package/dist/native/generated.d.ts +11 -2
  31. package/dist/native/generated.d.ts.map +1 -1
  32. package/dist/native.d.ts.map +1 -1
  33. package/dist/native.js +5 -2
  34. package/dist/native.js.map +1 -1
  35. package/dist/parse.d.ts +59 -0
  36. package/dist/parse.d.ts.map +1 -0
  37. package/dist/parse.js +404 -0
  38. package/dist/parse.js.map +1 -0
  39. package/dist/rrule.d.ts +34 -2
  40. package/dist/rrule.d.ts.map +1 -1
  41. package/dist/rrule.js +156 -32
  42. package/dist/rrule.js.map +1 -1
  43. package/index.darwin-arm64.node +0 -0
  44. package/index.darwin-x64.node +0 -0
  45. package/index.linux-arm64-gnu.node +0 -0
  46. package/index.linux-x64-gnu.node +0 -0
  47. package/index.win32-x64-msvc.node +0 -0
  48. package/package.json +2 -3
  49. package/src/DateTime.ts +1089 -124
  50. package/src/Duration.ts +318 -139
  51. package/src/Interval.ts +160 -53
  52. package/src/atlas.ts +23 -17
  53. package/src/format.ts +449 -0
  54. package/src/holidays.ts +161 -0
  55. package/src/index.ts +35 -7
  56. package/src/native/generated.ts +27 -2
  57. package/src/native.ts +7 -3
  58. package/src/parse.ts +559 -0
  59. package/src/rrule.ts +229 -38
  60. package/wasm/chronos_engine_wasm.d.ts +13 -4
  61. package/wasm/chronos_engine_wasm.js +87 -16
  62. package/wasm/chronos_engine_wasm_bg.wasm +0 -0
  63. package/wasm/chronos_engine_wasm_bg.wasm.d.ts +5 -2
  64. package/dist/utils.d.ts +0 -15
  65. package/dist/utils.d.ts.map +0 -1
  66. package/dist/utils.js +0 -17
  67. package/dist/utils.js.map +0 -1
  68. package/scripts/build-napi-types.mjs +0 -69
  69. package/scripts/clean-wasm-pack-meta.mjs +0 -32
  70. package/scripts/copy-napi.mjs +0 -56
  71. package/scripts/generate-napi-types.mjs +0 -156
  72. package/scripts/verify-napi.mjs +0 -46
  73. package/scripts/verify-wasm.mjs +0 -55
  74. package/src/utils.ts +0 -17
@@ -28,6 +28,13 @@ export interface ZonedOutputNapi {
28
28
  zoneName: string;
29
29
  }
30
30
 
31
+ export interface HolidayNapi {
32
+ /** The calendar date, `YYYY-MM-DD`. */
33
+ date: string;
34
+ /** The stable key the application translates. */
35
+ key: string;
36
+ }
37
+
31
38
  export declare function add(iso: string, amount: number, unit: string): string;
32
39
 
33
40
  export declare function diff(aIso: string, bIso: string, unit: string): number;
@@ -76,12 +83,30 @@ export declare function fromLocal(naiveIso: string, zone: string): string;
76
83
 
77
84
  export declare function parseRfc2822(input: string): string;
78
85
 
79
- export declare function parseSql(input: string): string;
86
+ export declare function parseSql(
87
+ input: string,
88
+ zone?: string | undefined | null,
89
+ ): string;
80
90
 
81
91
  export declare function parseHttp(input: string): string;
82
92
 
83
93
  export declare function rruleExpand(
84
- startIso: string,
94
+ startIso: string | undefined | null,
85
95
  rrule: string,
86
96
  limit: number,
97
+ tzid?: string | undefined | null,
87
98
  ): Array<string>;
99
+
100
+ export declare function easterDate(year: number): string;
101
+
102
+ export declare function holidays(
103
+ year: number,
104
+ country: string,
105
+ region?: string | undefined | null,
106
+ ): Array<HolidayNapi>;
107
+
108
+ export declare function isHoliday(
109
+ date: string,
110
+ country: string,
111
+ region?: string | undefined | null,
112
+ ): boolean;
package/src/native.ts CHANGED
@@ -76,11 +76,15 @@ if (isNode) {
76
76
  zoneOffset: (iso, zone) => wasm.zone_offset(iso, zone),
77
77
  fromLocal: (naive, zone) => wasm.from_local(naive, zone),
78
78
  parseRfc2822: (input) => wasm.parse_rfc2822(input),
79
- parseSql: (input) => wasm.parse_sql(input),
79
+ parseSql: (input, zone) => wasm.parse_sql(input, zone),
80
80
  parseHttp: (input) => wasm.parse_http(input),
81
- rruleExpand: (start, rrule, limit) =>
82
- wasm.rrule_expand(start, rrule, limit),
81
+ rruleExpand: (start, rrule, limit, tzid) =>
82
+ wasm.rrule_expand(start, rrule, limit, tzid),
83
83
  calendarParts: (iso) => wasm.calendar_parts(iso),
84
+ easterDate: (year) => wasm.easter_date(year),
85
+ holidays: (year, country, region) => wasm.holidays(year, country, region),
86
+ isHoliday: (date, country, region) =>
87
+ wasm.is_holiday(date, country, region),
84
88
  };
85
89
  } catch (e) {
86
90
  loadError = e;
package/src/parse.ts ADDED
@@ -0,0 +1,559 @@
1
+ /**
2
+ * `DateTime.fromFormat` — read a string written with Luxon's format tokens
3
+ * (`dd/MM/yyyy`, `dd LLL yyyy 'at' h:mm a`, `kkkk-'W'WW-c`, macros such as
4
+ * `D` or `f`), the way Luxon's token parser does: the format becomes one
5
+ * anchored, case-insensitive regular expression, names are matched against the
6
+ * locale's lists, and the matched units are resolved as Luxon's `fromObject`
7
+ * resolves them (larger units missing → now, smaller ones → their minimum).
8
+ *
9
+ * Digits are Latin only, as `toFormat` writes them. English names come from
10
+ * the same lists `toFormat` prints for every `en` locale, so a value formatted
11
+ * with chronos reads back.
12
+ */
13
+
14
+ import {
15
+ isEnglish,
16
+ MACROS,
17
+ MONTHS_LONG,
18
+ parseFormat,
19
+ type Token,
20
+ WEEKDAYS_LONG,
21
+ } from "./format.js";
22
+
23
+ /** The units a format can name, before the missing ones are filled in. */
24
+ export interface ParsedFields {
25
+ year?: number;
26
+ month?: number;
27
+ day?: number;
28
+ ordinal?: number;
29
+ weekYear?: number;
30
+ weekNumber?: number;
31
+ weekday?: number;
32
+ hour?: number;
33
+ minute?: number;
34
+ second?: number;
35
+ millisecond?: number;
36
+ }
37
+
38
+ export interface ParsedText {
39
+ fields: ParsedFields;
40
+ /** IANA zone named by the `z` token. */
41
+ zone?: string;
42
+ /** UTC offset in minutes, from `Z`, `ZZ` or `ZZZ`. */
43
+ offset?: number;
44
+ }
45
+
46
+ interface Unit {
47
+ token: Token;
48
+ regex: string;
49
+ /** Capture groups inside `regex`. */
50
+ groups: number;
51
+ literal: boolean;
52
+ deser: (match: readonly string[]) => number | string;
53
+ }
54
+
55
+ type NameLength = "short" | "long";
56
+
57
+ interface NameLists {
58
+ months(length: NameLength, format: boolean): readonly string[];
59
+ weekdays(length: NameLength, format: boolean): readonly string[];
60
+ meridiems(): readonly string[];
61
+ eras(length: NameLength): readonly string[];
62
+ }
63
+
64
+ const ENGLISH_ERAS: Readonly<Record<NameLength, readonly string[]>> = {
65
+ short: ["BC", "AD"],
66
+ long: ["Before Christ", "Anno Domini"],
67
+ };
68
+
69
+ function intlPart(
70
+ locale: string,
71
+ options: Intl.DateTimeFormatOptions,
72
+ ms: number,
73
+ type: Intl.DateTimeFormatPartTypes,
74
+ ): string {
75
+ const parts = new Intl.DateTimeFormat(locale, {
76
+ ...options,
77
+ timeZone: "UTC",
78
+ }).formatToParts(new Date(ms));
79
+ return parts.find((p) => p.type === type)?.value ?? "";
80
+ }
81
+
82
+ /** The dates Luxon reads its lists from: 2009 for months, the week of 2016-11-14 for weekdays. */
83
+ function nameLists(locale: string): NameLists {
84
+ if (isEnglish(locale)) {
85
+ const cut = (name: string, length: NameLength) =>
86
+ length === "long" ? name : name.slice(0, 3);
87
+ return {
88
+ months: (length) => MONTHS_LONG.map((m) => cut(m, length)),
89
+ weekdays: (length) => WEEKDAYS_LONG.map((d) => cut(d, length)),
90
+ meridiems: () => ["AM", "PM"],
91
+ eras: (length) => ENGLISH_ERAS[length],
92
+ };
93
+ }
94
+ return {
95
+ months: (length, format) =>
96
+ Array.from({ length: 12 }, (_, i) =>
97
+ intlPart(
98
+ locale,
99
+ format ? { month: length, day: "numeric" } : { month: length },
100
+ Date.UTC(2009, i, 1),
101
+ "month",
102
+ ),
103
+ ),
104
+ weekdays: (length, format) =>
105
+ Array.from({ length: 7 }, (_, i) =>
106
+ intlPart(
107
+ locale,
108
+ format
109
+ ? {
110
+ weekday: length,
111
+ year: "numeric",
112
+ month: "long",
113
+ day: "numeric",
114
+ }
115
+ : { weekday: length },
116
+ Date.UTC(2016, 10, 14 + i),
117
+ "weekday",
118
+ ),
119
+ ),
120
+ meridiems: () =>
121
+ [9, 19].map((hour) =>
122
+ intlPart(
123
+ locale,
124
+ { hour: "numeric", hourCycle: "h12" },
125
+ Date.UTC(2016, 10, 13, hour),
126
+ "dayPeriod",
127
+ ),
128
+ ),
129
+ eras: (length) =>
130
+ [Date.UTC(-40, 0, 1), Date.UTC(2017, 0, 1)].map((ms) =>
131
+ intlPart(locale, { era: length }, ms, "era"),
132
+ ),
133
+ };
134
+ }
135
+
136
+ function escapeRegex(text: string): string {
137
+ return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
138
+ }
139
+
140
+ /** A name in a list: its dots optional, a space and a no-break space alike. */
141
+ function listEntryRegex(name: string): string {
142
+ return name
143
+ .split(".")
144
+ .map((piece) => escapeRegex(piece).replace(/\\ |\\ /g, "[  ]"))
145
+ .join("\\.?");
146
+ }
147
+
148
+ function stripInsensitivities(name: string): string {
149
+ return name.replace(/\./g, "").replace(/[  ]/g, " ").toLowerCase();
150
+ }
151
+
152
+ function oneOf(
153
+ token: Token,
154
+ names: readonly string[],
155
+ startIndex: number,
156
+ ): Unit {
157
+ return {
158
+ token,
159
+ regex: names.map(listEntryRegex).join("|"),
160
+ groups: 0,
161
+ literal: false,
162
+ deser: ([text = ""]) =>
163
+ names.findIndex(
164
+ (name) => stripInsensitivities(name) === stripInsensitivities(text),
165
+ ) + startIndex,
166
+ };
167
+ }
168
+
169
+ function intUnit(
170
+ token: Token,
171
+ regex: string,
172
+ post: (value: number) => number = (value) => value,
173
+ ): Unit {
174
+ return {
175
+ token,
176
+ regex,
177
+ groups: 0,
178
+ literal: false,
179
+ deser: ([text = ""]) => post(Number.parseInt(text, 10)),
180
+ };
181
+ }
182
+
183
+ function simple(token: Token, regex: string): Unit {
184
+ return {
185
+ token,
186
+ regex,
187
+ groups: 0,
188
+ literal: false,
189
+ deser: ([text = ""]) => text,
190
+ };
191
+ }
192
+
193
+ /** Minutes of `+02:00` / `-5` / `+0530`; `-0:30` keeps its sign. */
194
+ function signedOffset(hours: string, minutes: string | undefined): number {
195
+ const h = Number.parseInt(hours, 10);
196
+ const m = Number.parseInt(minutes ?? "0", 10) || 0;
197
+ return h * 60 + (hours.startsWith("-") ? -m : m);
198
+ }
199
+
200
+ function offsetUnit(token: Token, regex: string): Unit {
201
+ return {
202
+ token,
203
+ regex,
204
+ groups: 2,
205
+ literal: false,
206
+ deser: ([, hours = "0", minutes]) => signedOffset(hours, minutes),
207
+ };
208
+ }
209
+
210
+ /** Luxon's cut-off: `yy` above 60 is the 1900s, the rest the 2000s. */
211
+ function untruncateYear(year: number): number {
212
+ if (year > 99) return year;
213
+ return year > 60 ? 1900 + year : 2000 + year;
214
+ }
215
+
216
+ function unitForToken(token: Token, names: NameLists): Unit {
217
+ const literal: Unit = {
218
+ token,
219
+ regex: escapeRegex(token.val),
220
+ groups: 0,
221
+ literal: true,
222
+ deser: ([text = ""]) => text,
223
+ };
224
+ if (token.literal) return literal;
225
+ switch (token.val) {
226
+ case "G":
227
+ return oneOf(token, names.eras("short"), 0);
228
+ case "GG":
229
+ return oneOf(token, names.eras("long"), 0);
230
+ case "y":
231
+ return intUnit(token, "\\d{1,6}");
232
+ case "yy":
233
+ return intUnit(token, "\\d{2,4}", untruncateYear);
234
+ case "yyyy":
235
+ return intUnit(token, "\\d{4}");
236
+ case "yyyyy":
237
+ return intUnit(token, "\\d{4,6}");
238
+ case "yyyyyy":
239
+ return intUnit(token, "\\d{6}");
240
+ case "M":
241
+ case "L":
242
+ case "d":
243
+ case "H":
244
+ case "h":
245
+ case "m":
246
+ case "s":
247
+ case "q":
248
+ case "W":
249
+ return intUnit(token, "\\d{1,2}");
250
+ case "MM":
251
+ case "LL":
252
+ case "dd":
253
+ case "HH":
254
+ case "hh":
255
+ case "mm":
256
+ case "ss":
257
+ case "qq":
258
+ case "WW":
259
+ return intUnit(token, "\\d{2}");
260
+ case "MMM":
261
+ return oneOf(token, names.months("short", true), 1);
262
+ case "MMMM":
263
+ return oneOf(token, names.months("long", true), 1);
264
+ case "LLL":
265
+ return oneOf(token, names.months("short", false), 1);
266
+ case "LLLL":
267
+ return oneOf(token, names.months("long", false), 1);
268
+ case "o":
269
+ case "S":
270
+ return intUnit(token, "\\d{1,3}");
271
+ case "ooo":
272
+ case "SSS":
273
+ return intUnit(token, "\\d{3}");
274
+ case "u":
275
+ return simple(token, "\\d{1,9}");
276
+ case "uu":
277
+ return simple(token, "\\d{1,2}");
278
+ case "uuu":
279
+ return intUnit(token, "\\d");
280
+ case "a":
281
+ return oneOf(token, names.meridiems(), 0);
282
+ case "kkkk":
283
+ return intUnit(token, "\\d{4}");
284
+ case "kk":
285
+ return intUnit(token, "\\d{2,4}", untruncateYear);
286
+ case "E":
287
+ case "c":
288
+ return intUnit(token, "\\d");
289
+ case "EEE":
290
+ return oneOf(token, names.weekdays("short", false), 1);
291
+ case "EEEE":
292
+ return oneOf(token, names.weekdays("long", false), 1);
293
+ case "ccc":
294
+ return oneOf(token, names.weekdays("short", true), 1);
295
+ case "cccc":
296
+ return oneOf(token, names.weekdays("long", true), 1);
297
+ case "Z":
298
+ case "ZZ":
299
+ return offsetUnit(token, "([+-]\\d{1,2})(?::(\\d{2}))?");
300
+ case "ZZZ":
301
+ return offsetUnit(token, "([+-]\\d{1,2})(\\d{2})?");
302
+ case "z":
303
+ return simple(token, "[a-z_+-/]{1,256}?");
304
+ // Where a macro expanded into white space: one blank, newlines excepted.
305
+ case " ":
306
+ return simple(token, "[^\\S\\n\\r]");
307
+ default:
308
+ return literal;
309
+ }
310
+ }
311
+
312
+ function pick(
313
+ table: Readonly<Record<string, string>>,
314
+ style: string | undefined,
315
+ ): Token | undefined {
316
+ if (style === undefined || !Object.hasOwn(table, style)) return undefined;
317
+ const val = table[style];
318
+ return val === undefined ? undefined : { literal: false, val };
319
+ }
320
+
321
+ /** One part of a macro's Intl rendering, as the token that reads it back. */
322
+ function tokenForPart(
323
+ part: Intl.DateTimeFormatPart,
324
+ options: Intl.DateTimeFormatOptions,
325
+ resolved: Intl.ResolvedDateTimeFormatOptions,
326
+ ): Token | undefined {
327
+ switch (part.type) {
328
+ case "literal": {
329
+ const isSpace = /^\s+$/.test(part.value);
330
+ return { literal: !isSpace, val: isSpace ? " " : part.value };
331
+ }
332
+ case "year":
333
+ return pick({ "2-digit": "yy", numeric: "yyyyy" }, options.year);
334
+ case "month":
335
+ return pick(
336
+ { numeric: "M", "2-digit": "MM", short: "MMM", long: "MMMM" },
337
+ options.month,
338
+ );
339
+ case "day":
340
+ return pick({ numeric: "d", "2-digit": "dd" }, options.day);
341
+ case "weekday":
342
+ return pick({ short: "EEE", long: "EEEE" }, options.weekday);
343
+ case "dayPeriod":
344
+ return { literal: false, val: "a" };
345
+ case "hour": {
346
+ const twelve =
347
+ options.hour12 ??
348
+ (options.hourCycle === undefined
349
+ ? resolved.hour12 === true
350
+ : options.hourCycle === "h11" || options.hourCycle === "h12");
351
+ return pick(
352
+ twelve
353
+ ? { numeric: "h", "2-digit": "hh" }
354
+ : { numeric: "H", "2-digit": "HH" },
355
+ options.hour,
356
+ );
357
+ }
358
+ case "minute":
359
+ return pick({ numeric: "m", "2-digit": "mm" }, options.minute);
360
+ case "second":
361
+ return pick({ numeric: "s", "2-digit": "ss" }, options.second);
362
+ case "timeZoneName":
363
+ return pick({ long: "ZZZZZ", short: "ZZZ" }, options.timeZoneName);
364
+ default:
365
+ return undefined;
366
+ }
367
+ }
368
+
369
+ /** A macro token (`D`, `f`, `T`…) as the tokens of its rendering in `locale`. */
370
+ function expandMacro(token: Token, locale: string): Token[] {
371
+ const options =
372
+ !token.literal && Object.hasOwn(MACROS, token.val)
373
+ ? MACROS[token.val]
374
+ : undefined;
375
+ if (options === undefined) return [token];
376
+ const dtf = new Intl.DateTimeFormat(locale, { ...options, timeZone: "UTC" });
377
+ const resolved = dtf.resolvedOptions();
378
+ const tokens: Token[] = [];
379
+ for (const part of dtf.formatToParts(new Date(1555555555555))) {
380
+ const expanded = tokenForPart(part, options, resolved);
381
+ if (expanded === undefined) return [token];
382
+ tokens.push(expanded);
383
+ }
384
+ return tokens;
385
+ }
386
+
387
+ /** Fraction digits as milliseconds: `5` → 500, `42` → 420. */
388
+ function parseMillis(fraction: string): number {
389
+ return Math.floor(Number.parseFloat(`0.${fraction}`) * 1000);
390
+ }
391
+
392
+ const FIELD_OF_KEY: Readonly<Record<string, keyof ParsedFields>> = {
393
+ S: "millisecond",
394
+ s: "second",
395
+ m: "minute",
396
+ h: "hour",
397
+ H: "hour",
398
+ d: "day",
399
+ o: "ordinal",
400
+ L: "month",
401
+ M: "month",
402
+ y: "year",
403
+ E: "weekday",
404
+ c: "weekday",
405
+ W: "weekNumber",
406
+ k: "weekYear",
407
+ };
408
+
409
+ /**
410
+ * Match `text` against `format`. `null` when it does not match; throws when the
411
+ * format names a meridiem together with a 24-hour hour.
412
+ */
413
+ export function parseWithFormat(
414
+ text: string,
415
+ format: string,
416
+ locale: string,
417
+ ): ParsedText | null {
418
+ const names = nameLists(locale);
419
+ const tokens = parseFormat(format).flatMap((t) => expandMacro(t, locale));
420
+ const units = tokens.map((t) => unitForToken(t, names));
421
+ const regex = new RegExp(
422
+ `^${units.map((u) => `(${u.regex})`).join("")}$`,
423
+ "i",
424
+ );
425
+ const match = regex.exec(text);
426
+ if (match === null) return null;
427
+
428
+ // Keyed by the token's letter, the last one written winning, as Luxon does.
429
+ const matches = new Map<string, number | string>();
430
+ let index = 1;
431
+ for (const unit of units) {
432
+ const groups = unit.groups + 1;
433
+ const key = unit.token.val[0];
434
+ if (!unit.literal && key !== undefined) {
435
+ matches.set(key, unit.deser(match.slice(index, index + groups)));
436
+ }
437
+ index += groups;
438
+ }
439
+ if (matches.has("a") && matches.has("H")) {
440
+ throw new Error("Can't include meridiem when specifying 24-hour format");
441
+ }
442
+ const num = (key: string): number | undefined => {
443
+ const value = matches.get(key);
444
+ return typeof value === "number" ? value : undefined;
445
+ };
446
+
447
+ const out: ParsedText = { fields: {} };
448
+ const zone = matches.get("z");
449
+ if (typeof zone === "string") out.zone = zone;
450
+ const offset = num("Z");
451
+ if (offset !== undefined) out.offset = offset;
452
+
453
+ const quarter = num("q");
454
+ if (quarter !== undefined) matches.set("M", (quarter - 1) * 3 + 1);
455
+ const hour12 = num("h");
456
+ const meridiem = num("a");
457
+ if (hour12 !== undefined) {
458
+ if (hour12 < 12 && meridiem === 1) matches.set("h", hour12 + 12);
459
+ else if (hour12 === 12 && meridiem === 0) matches.set("h", 0);
460
+ }
461
+ const year = num("y");
462
+ if (num("G") === 0 && year) matches.set("y", -year);
463
+ const fraction = matches.get("u");
464
+ if (fraction !== undefined) matches.set("S", parseMillis(String(fraction)));
465
+
466
+ for (const [key, value] of matches) {
467
+ const field = Object.hasOwn(FIELD_OF_KEY, key)
468
+ ? FIELD_OF_KEY[key]
469
+ : undefined;
470
+ if (field !== undefined && typeof value === "number") {
471
+ out.fields[field] = value;
472
+ }
473
+ }
474
+ return out;
475
+ }
476
+
477
+ // ─── Calendar conversions (ISO weeks, ordinal days) ──────────
478
+
479
+ const DAY_MS = 86_400_000;
480
+
481
+ export interface CalendarDay {
482
+ year: number;
483
+ month: number;
484
+ day: number;
485
+ }
486
+
487
+ /** Epoch milliseconds of a UTC midnight; years 0-99 stay literal. */
488
+ export function utcDayMs(year: number, month: number, day: number): number {
489
+ const d = new Date(0);
490
+ d.setUTCFullYear(year, month - 1, day);
491
+ return d.getTime();
492
+ }
493
+
494
+ export function dayOfMs(ms: number): CalendarDay {
495
+ const d = new Date(ms);
496
+ return {
497
+ year: d.getUTCFullYear(),
498
+ month: d.getUTCMonth() + 1,
499
+ day: d.getUTCDate(),
500
+ };
501
+ }
502
+
503
+ /** ISO weekday, 1 = Monday. */
504
+ export function isoWeekday(day: CalendarDay): number {
505
+ const js = new Date(utcDayMs(day.year, day.month, day.day)).getUTCDay();
506
+ return js === 0 ? 7 : js;
507
+ }
508
+
509
+ /** Monday of ISO week 1: the week holding January 4th. */
510
+ function firstIsoMonday(weekYear: number): number {
511
+ const jan4 = { year: weekYear, month: 1, day: 4 };
512
+ return utcDayMs(weekYear, 1, 4) - (isoWeekday(jan4) - 1) * DAY_MS;
513
+ }
514
+
515
+ export function isoWeeksInYear(weekYear: number): number {
516
+ return Math.round(
517
+ (firstIsoMonday(weekYear + 1) - firstIsoMonday(weekYear)) / (7 * DAY_MS),
518
+ );
519
+ }
520
+
521
+ export function daysInYearOf(year: number): number {
522
+ return Math.round((utcDayMs(year + 1, 1, 1) - utcDayMs(year, 1, 1)) / DAY_MS);
523
+ }
524
+
525
+ export function isoWeekToDay(
526
+ weekYear: number,
527
+ weekNumber: number,
528
+ weekday: number,
529
+ ): CalendarDay {
530
+ return dayOfMs(
531
+ firstIsoMonday(weekYear) + ((weekNumber - 1) * 7 + weekday - 1) * DAY_MS,
532
+ );
533
+ }
534
+
535
+ export function dayToIsoWeek(day: CalendarDay): {
536
+ weekYear: number;
537
+ weekNumber: number;
538
+ weekday: number;
539
+ } {
540
+ const ms = utcDayMs(day.year, day.month, day.day);
541
+ let weekYear = day.year + 1;
542
+ while (firstIsoMonday(weekYear) > ms) weekYear -= 1;
543
+ return {
544
+ weekYear,
545
+ weekNumber: Math.floor((ms - firstIsoMonday(weekYear)) / (7 * DAY_MS)) + 1,
546
+ weekday: isoWeekday(day),
547
+ };
548
+ }
549
+
550
+ export function ordinalToDay(year: number, ordinal: number): CalendarDay {
551
+ return dayOfMs(utcDayMs(year, 1, 1) + (ordinal - 1) * DAY_MS);
552
+ }
553
+
554
+ export function dayToOrdinal(day: CalendarDay): number {
555
+ const start = utcDayMs(day.year, 1, 1);
556
+ return (
557
+ Math.round((utcDayMs(day.year, day.month, day.day) - start) / DAY_MS) + 1
558
+ );
559
+ }