@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
package/dist/DateTime.js CHANGED
@@ -1,3 +1,4 @@
1
+ var _a;
1
2
  /**
2
3
  * DateTime — immutable UTC datetime value object for the Ream framework.
3
4
  *
@@ -10,8 +11,10 @@
10
11
  *
11
12
  * @implements Epic 36 — Chronos
12
13
  */
14
+ import { Duration, } from "./Duration.js";
15
+ import { formatLuxon } from "./format.js";
13
16
  import { nativeChronos } from "./native.js";
14
- import { normalizeIso } from "./utils.js";
17
+ import { dayOfMs, daysInYearOf, dayToIsoWeek, dayToOrdinal, isoWeekday, isoWeeksInYear, isoWeekToDay, ordinalToDay, parseWithFormat, utcDayMs, } from "./parse.js";
15
18
  // ─── Internal helpers ────────────────────────────────────────
16
19
  const MONTH_NAMES = [
17
20
  "January",
@@ -52,51 +55,388 @@ function daysInMonthOf(year, month) {
52
55
  return daysPerMonthOf(year)[month - 1] ?? 31;
53
56
  }
54
57
  /**
55
- * Refuse a calendar date that does not exist, instead of sliding to the next
56
- * one that does.
57
- *
58
- * `new Date('2026-02-30')` answers 2026-03-02: the overflow semantics are right
59
- * for arithmetic — adding a month to January 31st has to land somewhere — and
60
- * wrong for reading input, where the same slide turns a typo into a fact. The
61
- * inconsistency was the dangerous part: '2026-13-45' threw while '2026-02-30'
62
- * came back as a date, so a caller wrapping this in try/catch had covered the
63
- * loud half and left the half that writes something false to the database.
58
+ * The only strings a `DateTime` reads: ISO 8601 calendar dates, optionally with
59
+ * a time (`T` or, as SQL writes it, a space) and an offset (`Z`, `±HH`,
60
+ * `±HHMM`, `±HH:MM`). Anything else is refused: V8's fallback parser turns
61
+ * `"1"` or `"foo 2026"` into a date, and reads an offset-less time in the
62
+ * HOST zone, so the same text named a different instant on every machine.
63
+ */
64
+ const ISO_8601 = /^(\d{4})-(\d{2})-(\d{2})(?:[Tt ](\d{2}):(\d{2})(?::(\d{2})(?:[.,](\d{1,9}))?)?(?:\s?([Zz])|\s?([+-])(\d{2})(?::?(\d{2}))?)?)?$/;
65
+ /** First and last instants a value may hold: what a four-digit ISO year writes. */
66
+ const MIN_MS = -62_167_219_200_000; // 0000-01-01T00:00:00.000Z
67
+ const MAX_MS = 253_402_300_799_999; // 9999-12-31T23:59:59.999Z
68
+ /**
69
+ * Refuse a wall-clock value that does not exist, instead of sliding to the
70
+ * next one that does.
64
71
  *
65
- * `fromObject` has always refused the same input; this is that check on the
66
- * door that was missing it. Only the written date is examined, never the
67
- * instant it resolves to, so an offset that legitimately moves the UTC day
68
- * ('2026-08-10T23:00:00-05:00' → the 11th) is untouched.
72
+ * `new Date('2026-02-30')` answers 2026-03-02 and `Date.UTC(…, 10, 90)` reads
73
+ * minute 90 as 11:30: the overflow semantics are right for arithmetic — adding
74
+ * a month to January 31st has to land somewhere — and wrong for reading input,
75
+ * where the same slide turns a typo into a fact. Only the written value is
76
+ * examined, never the instant it resolves to, so an offset that legitimately
77
+ * moves the UTC day ('2026-08-10T23:00:00-05:00' → the 11th) is untouched.
69
78
  */
70
- const CALENDAR_DATE = /^(\d{4})-(\d{2})-(\d{2})(?=$|[T ])/;
71
- function assertCalendarDateExists(raw) {
72
- const match = CALENDAR_DATE.exec(raw);
73
- // Anything else — RFC 2822, a bare year, a basic-format string — is left to
74
- // `Date`, which already refuses what it cannot read.
75
- if (!match)
76
- return;
77
- const year = Number(match[1]);
78
- const month = Number(match[2]);
79
- const day = Number(match[3]);
80
- if (month < 1 || month > 12) {
81
- throw new Error(`Invalid date '${raw}': there is no month ${month}.`);
79
+ function assertWallClock(c, raw) {
80
+ const integer = (unit, value, min, max) => {
81
+ if (!Number.isInteger(value) || value < min || value > max) {
82
+ throw new RangeError(`Invalid date '${raw}': ${unit} ${String(value)} is out of range (${min}-${max}).`);
83
+ }
84
+ };
85
+ integer("year", c.year, 0, 9999);
86
+ if (!Number.isInteger(c.month) || c.month < 1 || c.month > 12) {
87
+ throw new RangeError(`Invalid date '${raw}': there is no month ${String(c.month)}.`);
88
+ }
89
+ const lastDay = daysInMonthOf(c.year, c.month);
90
+ if (!Number.isInteger(c.day) || c.day < 1 || c.day > lastDay) {
91
+ throw new RangeError(`Invalid date '${raw}': ${MONTH_NAMES[c.month - 1]} ${c.year} has ${lastDay} days, so there is no day ${String(c.day)}.`);
92
+ }
93
+ integer("hour", c.hour, 0, 23);
94
+ integer("minute", c.minute, 0, 59);
95
+ integer("second", c.second, 0, 59);
96
+ integer("millisecond", c.millisecond, 0, 999);
97
+ }
98
+ /** Epoch milliseconds of a UTC wall clock; years 0-99 stay literal (Date.UTC maps them to 19xx). */
99
+ function utcMs(c) {
100
+ const d = new Date(0);
101
+ d.setUTCFullYear(c.year, c.month - 1, c.day);
102
+ d.setUTCHours(c.hour, c.minute, c.second, c.millisecond);
103
+ return d.getTime();
104
+ }
105
+ const pad = (n, width = 2) => String(n).padStart(width, "0");
106
+ /** Epoch milliseconds of a wall clock read in `zone`. */
107
+ function wallClockMs(c, zone) {
108
+ if (zone === "UTC")
109
+ return utcMs(c);
110
+ const naive = `${pad(c.year, 4)}-${pad(c.month)}-${pad(c.day)}T${pad(c.hour)}:${pad(c.minute)}:${pad(c.second)}`;
111
+ return Date.parse(nativeChronos().fromLocal(naive, zone)) + c.millisecond;
112
+ }
113
+ /** The canonical UTC ISO string of an instant, refusing what chronos cannot hold. */
114
+ function isoOfMs(ms, input) {
115
+ if (!Number.isFinite(ms))
116
+ throw new RangeError(`Invalid date ${input()}`);
117
+ if (ms < MIN_MS || ms > MAX_MS) {
118
+ throw new RangeError(`Date ${input()} is out of range: years are limited to 0000-9999.`);
119
+ }
120
+ return new Date(ms).toISOString();
121
+ }
122
+ /**
123
+ * Fill the units a `fromFormat` text left out, as Luxon's `fromObject` does:
124
+ * the units larger than the largest one written come from `now`, the smaller
125
+ * ones take their minimum. A text naming a week (`kkkk`, `W`) or only a
126
+ * weekday is read on the ISO week calendar, one naming an ordinal (`o`) on the
127
+ * ordinal calendar. Every unit is range-checked; hour 24 is accepted at
128
+ * 24:00:00.000 and is midnight of the next day, as Luxon reads it.
129
+ */
130
+ function resolveParsedFields(f, now, raw) {
131
+ const hasOrdinal = f.ordinal !== undefined;
132
+ const hasMonthDay = f.month !== undefined || f.day !== undefined;
133
+ const hasGregorian = f.year !== undefined || hasMonthDay;
134
+ const weekDefined = f.weekYear !== undefined || f.weekNumber !== undefined;
135
+ if ((hasGregorian || hasOrdinal) && weekDefined) {
136
+ throw new Error("Can't mix weekYear/weekNumber units with year/month/day or ordinals");
137
+ }
138
+ if (hasMonthDay && hasOrdinal) {
139
+ throw new Error("Can't mix ordinal dates with month/day");
140
+ }
141
+ let found = false;
142
+ const take = (given, current, min) => {
143
+ if (given !== undefined) {
144
+ found = true;
145
+ return given;
146
+ }
147
+ return found ? min : current;
148
+ };
149
+ const range = (unit, value, min, max) => {
150
+ if (!Number.isInteger(value) || value < min || value > max) {
151
+ throw new RangeError(`Invalid date '${raw}': ${unit} ${String(value)} is out of range (${min}-${max}).`);
152
+ }
153
+ };
154
+ const nowDay = {
155
+ year: now.year,
156
+ month: now.month,
157
+ day: now.day,
158
+ };
159
+ let day;
160
+ if (weekDefined || (f.weekday !== undefined && !hasGregorian)) {
161
+ const nowWeek = dayToIsoWeek(nowDay);
162
+ const weekYear = take(f.weekYear, nowWeek.weekYear, 1);
163
+ const weekNumber = take(f.weekNumber, nowWeek.weekNumber, 1);
164
+ const weekday = take(f.weekday, nowWeek.weekday, 1);
165
+ range("weekYear", weekYear, 0, 9999);
166
+ range("weekNumber", weekNumber, 1, isoWeeksInYear(weekYear));
167
+ range("weekday", weekday, 1, 7);
168
+ day = isoWeekToDay(weekYear, weekNumber, weekday);
169
+ }
170
+ else if (hasOrdinal) {
171
+ const year = take(f.year, now.year, 1);
172
+ const ordinal = take(f.ordinal, dayToOrdinal(nowDay), 1);
173
+ range("year", year, 0, 9999);
174
+ range("ordinal", ordinal, 1, daysInYearOf(year));
175
+ day = ordinalToDay(year, ordinal);
82
176
  }
83
- const lastDay = daysInMonthOf(year, month);
84
- if (day < 1 || day > lastDay) {
85
- throw new Error(`Invalid date '${raw}': ${MONTH_NAMES[month - 1]} ${year} has ${lastDay} days, so there is no day ${day}.`);
177
+ else {
178
+ day = {
179
+ year: take(f.year, now.year, 1),
180
+ month: take(f.month, now.month, 1),
181
+ day: take(f.day, now.day, 1),
182
+ };
86
183
  }
184
+ const clock = {
185
+ ...day,
186
+ hour: take(f.hour, now.hour, 0),
187
+ minute: take(f.minute, now.minute, 0),
188
+ second: take(f.second, now.second, 0),
189
+ millisecond: take(f.millisecond, now.millisecond, 0),
190
+ };
191
+ const endOfDay = clock.hour === 24 &&
192
+ clock.minute === 0 &&
193
+ clock.second === 0 &&
194
+ clock.millisecond === 0;
195
+ assertWallClock(endOfDay ? { ...clock, hour: 0 } : clock, raw);
196
+ const out = endOfDay
197
+ ? {
198
+ ...clock,
199
+ ...dayOfMs(utcDayMs(clock.year, clock.month, clock.day + 1)),
200
+ hour: 0,
201
+ }
202
+ : clock;
203
+ assertWallClock(out, raw);
204
+ if (f.weekday !== undefined &&
205
+ hasGregorian &&
206
+ isoWeekday(out) !== f.weekday) {
207
+ throw new RangeError(`Invalid date '${raw}': weekday ${f.weekday} does not fall on ${pad(out.year, 4)}-${pad(out.month)}-${pad(out.day)}.`);
208
+ }
209
+ return out;
87
210
  }
88
- function toIso(value) {
211
+ /** Now as a wall clock in `zone`, or at a fixed `offset` (minutes) when the text gave one. */
212
+ function nowWallClock(zone, offset) {
213
+ if (offset === undefined) {
214
+ const { year, month, day, hour, minute, second, millisecond } = DateTime.now(zone).calendar;
215
+ return { year, month, day, hour, minute, second, millisecond };
216
+ }
217
+ const d = new Date(Date.now() + offset * 60_000);
218
+ return {
219
+ year: d.getUTCFullYear(),
220
+ month: d.getUTCMonth() + 1,
221
+ day: d.getUTCDate(),
222
+ hour: d.getUTCHours(),
223
+ minute: d.getUTCMinutes(),
224
+ second: d.getUTCSeconds(),
225
+ millisecond: d.getUTCMilliseconds(),
226
+ };
227
+ }
228
+ /**
229
+ * The instant of a parsed wall clock. An offset alone fixes it. A zone and an
230
+ * offset together: the offset settles the hour a zone repeats when its clocks
231
+ * go back, as long as the zone has that offset then; otherwise the zone wins.
232
+ */
233
+ function instantOfParsed(c, parsed, wallZone) {
234
+ if (parsed.offset !== undefined) {
235
+ const atOffset = utcMs(c) - parsed.offset * 60_000;
236
+ if (parsed.zone === undefined)
237
+ return atOffset;
238
+ const zoneOffset = parsed.zone === "UTC"
239
+ ? 0
240
+ : nativeChronos().zoneOffset(isoOfMs(atOffset, () => `'${parsed.zone}'`), parsed.zone);
241
+ if (zoneOffset === parsed.offset)
242
+ return atOffset;
243
+ }
244
+ return wallClockMs(c, wallZone);
245
+ }
246
+ /** Read an ISO 8601 string; an offset-less one is a wall clock in `zone`. */
247
+ function parseIso(raw, zone) {
248
+ const m = ISO_8601.exec(raw);
249
+ if (!m) {
250
+ throw new RangeError(`Invalid date '${raw}': expected ISO 8601 (YYYY-MM-DD, optionally with THH:mm[:ss[.SSS]] and an offset).`);
251
+ }
252
+ const c = {
253
+ year: Number(m[1]),
254
+ month: Number(m[2]),
255
+ day: Number(m[3]),
256
+ hour: Number(m[4] ?? 0),
257
+ minute: Number(m[5] ?? 0),
258
+ second: Number(m[6] ?? 0),
259
+ millisecond: Math.floor(Number(`0.${m[7] ?? "0"}`) * 1000),
260
+ };
261
+ assertWallClock(c, raw);
262
+ let ms;
263
+ if (m[8] !== undefined) {
264
+ ms = utcMs(c);
265
+ }
266
+ else if (m[9] !== undefined) {
267
+ const hours = Number(m[10]);
268
+ const minutes = Number(m[11] ?? 0);
269
+ if (hours > 23 || minutes > 59) {
270
+ throw new RangeError(`Invalid date '${raw}': the offset is out of range.`);
271
+ }
272
+ const sign = m[9] === "-" ? -1 : 1;
273
+ ms = utcMs(c) - sign * (hours * 60 + minutes) * 60_000;
274
+ }
275
+ else {
276
+ ms = wallClockMs(c, zone);
277
+ }
278
+ return isoOfMs(ms, () => `'${raw}'`);
279
+ }
280
+ function toIso(value, zone = "UTC") {
89
281
  if (value instanceof DateTime)
90
282
  return value.toISO();
91
- if (value instanceof Date)
92
- return normalizeIso(value.toISOString());
93
- if (typeof value === "string")
94
- assertCalendarDateExists(value);
95
- return normalizeIso(new Date(value).toISOString());
283
+ if (value instanceof Date) {
284
+ return isoOfMs(value.getTime(), () => "(JS Date)");
285
+ }
286
+ if (typeof value !== "string") {
287
+ throw new TypeError(`Invalid date input: expected a string, a Date or a DateTime, got ${typeof value}`);
288
+ }
289
+ return parseIso(value, zone);
96
290
  }
97
291
  function toMs(value) {
98
292
  return new Date(toIso(value)).getTime();
99
293
  }
294
+ const CASUAL_UNIT_MS = {
295
+ second: 1_000,
296
+ minute: 60_000,
297
+ hour: 3_600_000,
298
+ day: 86_400_000,
299
+ week: 604_800_000,
300
+ month: 30 * 86_400_000,
301
+ year: 365 * 86_400_000,
302
+ };
303
+ /** Milliseconds in one unit on Luxon's casual matrix; throws on an unknown unit. */
304
+ function casualUnitMs(unit) {
305
+ const singular = unit.endsWith("s") ? unit.slice(0, -1) : unit;
306
+ const ms = Object.hasOwn(CASUAL_UNIT_MS, singular)
307
+ ? CASUAL_UNIT_MS[singular]
308
+ : undefined;
309
+ if (ms === undefined)
310
+ throw new Error(`Unsupported unit: ${unit}`);
311
+ return ms;
312
+ }
313
+ const DIFF_ORDER = [
314
+ "years",
315
+ "months",
316
+ "weeks",
317
+ "days",
318
+ "hours",
319
+ "minutes",
320
+ "seconds",
321
+ "milliseconds",
322
+ ];
323
+ const CALENDAR_UNITS = new Set([
324
+ "years",
325
+ "months",
326
+ "weeks",
327
+ "days",
328
+ ]);
329
+ const RELATIVE_UNITS = [
330
+ "years",
331
+ "months",
332
+ "weeks",
333
+ "days",
334
+ "hours",
335
+ "minutes",
336
+ "seconds",
337
+ ];
338
+ const TO_RELATIVE_UNITS = [
339
+ "years",
340
+ "months",
341
+ "days",
342
+ "hours",
343
+ "minutes",
344
+ "seconds",
345
+ ];
346
+ const TO_RELATIVE_CALENDAR_UNITS = [
347
+ "years",
348
+ "months",
349
+ "days",
350
+ ];
351
+ const BOUND_OF = {
352
+ years: "year",
353
+ months: "month",
354
+ weeks: "week",
355
+ days: "day",
356
+ hours: "hour",
357
+ minutes: "minute",
358
+ seconds: "second",
359
+ };
360
+ function relativeUnitOf(unit) {
361
+ const plural = typeof unit === "string" && !unit.endsWith("s") ? `${unit}s` : unit;
362
+ const found = RELATIVE_UNITS.find((u) => u === plural);
363
+ if (found === undefined) {
364
+ throw new RangeError(`Unsupported relative unit: ${String(unit)}`);
365
+ }
366
+ return found;
367
+ }
368
+ /** Round to `digits` decimals the way the reference library's `roundTo` does. */
369
+ function roundTo(value, digits, rounding) {
370
+ const factor = 10 ** digits;
371
+ switch (rounding) {
372
+ case "expand":
373
+ return value > 0
374
+ ? Math.ceil(value * factor) / factor
375
+ : Math.floor(value * factor) / factor;
376
+ case "trunc":
377
+ return Math.trunc(value * factor) / factor;
378
+ case "round":
379
+ return Math.round(value * factor) / factor;
380
+ case "floor":
381
+ return Math.floor(value * factor) / factor;
382
+ case "ceil":
383
+ return Math.ceil(value * factor) / factor;
384
+ default:
385
+ throw new RangeError(`Value rounding ${String(rounding)} is out of range`);
386
+ }
387
+ }
388
+ /**
389
+ * The reference library's `diffRelative`: count `end - start` in the first
390
+ * unit (largest first) that reaches 1, or in the one unit asked for.
391
+ * `calendary` counts calendar boundaries crossed (yesterday is 1 day back at
392
+ * 23:59 as at 00:01) and rounds to the nearest; otherwise the count is the
393
+ * calendar-aware diff, truncated unless `rounding` says otherwise.
394
+ */
395
+ function diffRelative(start, end, opts) {
396
+ const round = opts.round ?? true;
397
+ const rounding = opts.rounding ?? "trunc";
398
+ // NAMED DEVIATION: the reference library prints English (en, en-US) from a
399
+ // hand-written table and every other locale through Intl. Every locale goes
400
+ // through Intl here, so en-US gets CLDR's own short and narrow forms
401
+ // ("2d ago" in narrow, where the table prints "2 days ago"); the long style,
402
+ // the default, reads the same.
403
+ const intlOptions = {
404
+ numeric: opts.numeric,
405
+ style: opts.style ?? "long",
406
+ };
407
+ if (opts.numberingSystem !== undefined) {
408
+ intlOptions.numberingSystem = opts.numberingSystem;
409
+ }
410
+ const formatter = new Intl.RelativeTimeFormat(opts.locale ?? end.locale, intlOptions);
411
+ const format = (count, unit) => formatter.format(roundTo(count, round || opts.calendary ? 0 : 2, opts.calendary ? "round" : rounding), unit);
412
+ const differ = (unit) => {
413
+ if (opts.calendary) {
414
+ const bound = BOUND_OF[unit];
415
+ if (end.hasSame(start, bound))
416
+ return 0;
417
+ return end.startOf(bound).diff(start.startOf(bound), unit).as(unit);
418
+ }
419
+ return end.diff(start, unit).as(unit);
420
+ };
421
+ if (opts.unit !== undefined)
422
+ return format(differ(opts.unit), opts.unit);
423
+ for (const unit of opts.units) {
424
+ const count = differ(unit);
425
+ if (Math.abs(count) >= 1)
426
+ return format(count, unit);
427
+ }
428
+ const last = opts.units.at(-1);
429
+ if (last === undefined)
430
+ throw new RangeError("No unit to count in");
431
+ return format(start.toMillis() > end.toMillis() ? -0 : 0, last);
432
+ }
433
+ function durationUnitOf(unit) {
434
+ const plural = unit.endsWith("s") ? unit : `${unit}s`;
435
+ const found = DIFF_ORDER.find((u) => u === plural);
436
+ if (found === undefined)
437
+ throw new RangeError(`Unsupported unit: ${unit}`);
438
+ return found;
439
+ }
100
440
  function isCalendarUnit(unit) {
101
441
  return (unit === "day" || unit === "week" || unit === "month" || unit === "year");
102
442
  }
@@ -250,55 +590,182 @@ function rangesOverlap(a, b, opt = {}) {
250
590
  ? Math.max(na.start, nb.start) <= Math.min(na.end, nb.end)
251
591
  : Math.max(na.start, nb.start) < Math.min(na.end, nb.end);
252
592
  }
593
+ // ─── Zone validation ─────────────────────────────────────────
594
+ /**
595
+ * Zones the engine has already accepted, exactly as it names them.
596
+ *
597
+ * Every derived value (`plus`, `startOf`, …) is built through the constructor
598
+ * with the zone of the value it came from, so without this each one would pay
599
+ * a native call to re-validate a zone that was checked on the way in. Only a
600
+ * name equal to the engine's canonical spelling is remembered: the set is then
601
+ * bounded by the tz database, whatever spellings a caller sends.
602
+ */
603
+ const acceptedZones = new Set(["UTC"]);
604
+ /**
605
+ * Throw on a zone the tz database does not know — the one check behind every
606
+ * entry that takes a zone (`new DateTime(input, zone)`, `DateTime.now(zone)`,
607
+ * `setZone`), so all three refuse the same names with the same message.
608
+ */
609
+ function assertZone(zone) {
610
+ if (acceptedZones.has(zone))
611
+ return;
612
+ const canonical = nativeChronos().validateTimezone(zone);
613
+ if (canonical === zone)
614
+ acceptedZones.add(zone);
615
+ }
253
616
  // ─── DateTime class ──────────────────────────────────────────
254
617
  export class DateTime {
255
618
  #iso;
256
619
  #zone;
620
+ /** Locale for names in `toFormat` and for `toLocaleString`; en-US unless set. */
621
+ #locale = "en-US";
622
+ /**
623
+ * @throws on a zone the tz database does not know. An unknown zone used to
624
+ * be stored as given and break later, on the first offset or format.
625
+ */
257
626
  constructor(input = new Date(), zone = "UTC") {
258
- this.#iso = toIso(input);
627
+ assertZone(zone);
628
+ this.#iso = toIso(input, zone);
259
629
  this.#zone = zone;
260
630
  }
261
631
  static from(input) {
262
- if (input instanceof DateTime)
263
- return new DateTime(input.#iso, input.#zone);
264
- return new DateTime(toIso(input));
632
+ if (input instanceof _a)
633
+ return input.#derive(input.#iso);
634
+ return new _a(toIso(input));
635
+ }
636
+ /** A value derived from this one: same zone (unless given) and locale. */
637
+ #derive(input, zone = this.#zone) {
638
+ const out = new _a(input, zone);
639
+ out.#locale = this.#locale;
640
+ return out;
641
+ }
642
+ /** Now, or the given wall clock, in the host's zone (Luxon's `DateTime.local`). */
643
+ static local(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, millisecond = 0) {
644
+ const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
645
+ if (year === undefined)
646
+ return _a.now(zone);
647
+ return _a.fromObject({ year, month, day, hour, minute, second, millisecond }, { zone });
648
+ }
649
+ /** Now, or the given wall clock, in UTC (Luxon's `DateTime.utc`). */
650
+ static utc(year, month = 1, day = 1, hour = 0, minute = 0, second = 0, millisecond = 0) {
651
+ if (year === undefined)
652
+ return _a.now();
653
+ return _a.fromObject({
654
+ year,
655
+ month,
656
+ day,
657
+ hour,
658
+ minute,
659
+ second,
660
+ millisecond,
661
+ });
265
662
  }
266
663
  static now(zone) {
267
- return new DateTime(new Date(), zone ?? "UTC");
664
+ return new _a(new Date(), zone ?? "UTC");
268
665
  }
269
666
  static fromMillis(ms) {
270
- return new DateTime(new Date(ms));
667
+ if (typeof ms !== "number") {
668
+ throw new TypeError(`fromMillis expects a number, got ${typeof ms}`);
669
+ }
670
+ return new _a(new Date(ms));
271
671
  }
272
672
  static fromSeconds(seconds) {
273
- return new DateTime(new Date(seconds * 1000));
673
+ // Same guard as fromMillis: `seconds * 1000` would turn "12" into 12 s
674
+ // and null into the epoch.
675
+ if (typeof seconds !== "number") {
676
+ throw new TypeError(`fromSeconds expects a number, got ${seconds === null ? "null" : typeof seconds}`);
677
+ }
678
+ return new _a(new Date(seconds * 1000));
274
679
  }
275
680
  static fromUnix(seconds) {
276
- return DateTime.fromSeconds(seconds);
681
+ return _a.fromSeconds(seconds);
277
682
  }
278
683
  static fromJSDate(date) {
279
684
  if (!Number.isFinite(date.getTime()))
280
685
  throw new Error("Invalid Date");
281
- return new DateTime(date);
282
- }
283
- static fromObject(obj) {
284
- if (obj.month < 1 || obj.month > 12)
285
- throw new Error(`Invalid month: ${obj.month}`);
286
- if (obj.day < 1 || obj.day > 31)
287
- throw new Error(`Invalid day: ${obj.day}`);
288
- const d = new Date(Date.UTC(obj.year, obj.month - 1, obj.day, obj.hour ?? 0, obj.minute ?? 0, obj.second ?? 0, obj.ms ?? 0));
289
- if (d.getUTCMonth() !== obj.month - 1 || d.getUTCDate() !== obj.day) {
290
- throw new Error(`Invalid date object: ${JSON.stringify(obj)}`);
291
- }
292
- return new DateTime(d);
686
+ return new _a(date);
687
+ }
688
+ /**
689
+ * Read an ISO 8601 string. An offset-less one is a wall clock in
690
+ * `options.zone` (UTC by default), and the result is in that zone.
691
+ */
692
+ static fromISO(text, options = {}) {
693
+ return new _a(text, options.zone ?? "UTC");
694
+ }
695
+ /**
696
+ * Build from calendar fields, read as a wall clock in `options.zone` (UTC by
697
+ * default). Every field is checked: an integer within its range (minute
698
+ * 0-59, …), and a year read literally (50 is year 0050, not 1950).
699
+ */
700
+ static fromObject(obj, options = {}) {
701
+ const zone = options.zone ?? "UTC";
702
+ assertZone(zone);
703
+ const c = {
704
+ year: obj.year,
705
+ month: obj.month,
706
+ day: obj.day,
707
+ hour: obj.hour ?? 0,
708
+ minute: obj.minute ?? 0,
709
+ second: obj.second ?? 0,
710
+ millisecond: obj.millisecond ?? obj.ms ?? 0,
711
+ };
712
+ assertWallClock(c, JSON.stringify(obj));
713
+ return new _a(isoOfMs(wallClockMs(c, zone), () => JSON.stringify(obj)), zone);
293
714
  }
294
715
  static fromRFC2822(input) {
295
- return new DateTime(nativeChronos().parseRfc2822(input));
716
+ return new _a(nativeChronos().parseRfc2822(input));
296
717
  }
297
- static fromSQL(input) {
298
- return new DateTime(nativeChronos().parseSql(input));
718
+ /**
719
+ * Read a SQL literal: `YYYY-MM-DD`, or `YYYY-MM-DD HH:mm[:ss[.fff]]` with an
720
+ * optional offset (`+00`, `+02:00` — PostgreSQL's `timestamptz` text) or
721
+ * IANA zone. Without one, the value is a wall clock in `options.zone` (UTC
722
+ * by default), and the result is in that zone.
723
+ */
724
+ static fromSQL(input, options = {}) {
725
+ const zone = options.zone ?? "UTC";
726
+ assertZone(zone);
727
+ return new _a(nativeChronos().parseSql(input, zone === "UTC" ? undefined : zone), zone);
299
728
  }
300
729
  static fromHTTP(input) {
301
- return new DateTime(nativeChronos().parseHttp(input));
730
+ return new _a(nativeChronos().parseHttp(input));
731
+ }
732
+ /**
733
+ * Read `text` written with Luxon's format tokens (`dd/MM/yyyy HH:mm`,
734
+ * `dd LLL yyyy 'at' h:mm a`, `kkkk-'W'WW-c`, macros such as `D` or `f`), as
735
+ * Luxon's `fromFormat`. Units the format leaves out are filled as Luxon
736
+ * fills them: larger ones from now, smaller ones with their minimum
737
+ * (`HH:mm` is today at that time, `MMMM` the 1st of that month this year).
738
+ *
739
+ * The wall clock is read in the zone the text names (`z`), else at the
740
+ * offset it writes (`Z`, `ZZ`, `ZZZ`), else in `options.zone` (UTC by
741
+ * default); the result is in `options.zone`. Names are matched in
742
+ * `options.locale` (en-US by default), which the result keeps.
743
+ *
744
+ * Two deviations, named: text that does not match the format, or names a
745
+ * date that does not exist, throws instead of returning an invalid value
746
+ * (chronos has no invalid DateTime); and there is no `setZone` option, since
747
+ * a chronos zone is an IANA name and an offset alone names none.
748
+ */
749
+ static fromFormat(text, format, options = {}) {
750
+ if (typeof text !== "string" || typeof format !== "string") {
751
+ throw new TypeError("fromFormat requires an input string and a format");
752
+ }
753
+ const zone = options.zone ?? "UTC";
754
+ assertZone(zone);
755
+ const locale = options.locale ?? "en-US";
756
+ const parsed = parseWithFormat(text, format, locale);
757
+ if (parsed === null ||
758
+ (Object.keys(parsed.fields).length === 0 && parsed.zone === undefined)) {
759
+ throw new RangeError(`Invalid date '${text}': it does not match the format '${format}'.`);
760
+ }
761
+ if (parsed.zone !== undefined)
762
+ assertZone(parsed.zone);
763
+ const wallZone = parsed.zone ?? zone;
764
+ const clock = resolveParsedFields(parsed.fields, nowWallClock(wallZone, parsed.offset), text);
765
+ const ms = instantOfParsed(clock, parsed, wallZone);
766
+ const out = new _a(isoOfMs(ms, () => `'${text}'`), zone);
767
+ out.#locale = locale;
768
+ return out;
302
769
  }
303
770
  // ─── Timezone ───────────────────────────────────────────
304
771
  get zoneName() {
@@ -309,38 +776,192 @@ export class DateTime {
309
776
  return 0;
310
777
  return nativeChronos().zoneOffset(this.#iso, this.#zone);
311
778
  }
312
- setZone(zone) {
313
- nativeChronos().validateTimezone(zone);
314
- return new DateTime(this.#iso, zone);
779
+ /**
780
+ * The same instant in another zone, or — with `keepLocalTime` — the same
781
+ * wall clock in another zone (a different instant), as Luxon's `setZone`.
782
+ */
783
+ setZone(zone, options = {}) {
784
+ assertZone(zone);
785
+ if (!options.keepLocalTime)
786
+ return this.#derive(this.#iso, zone);
787
+ return this.#derive(new Date(wallClockMs(this.calendar, zone)), zone);
315
788
  }
316
789
  toUTC() {
317
- return new DateTime(this.#iso, "UTC");
790
+ return this.#derive(this.#iso, "UTC");
791
+ }
792
+ get locale() {
793
+ return this.#locale;
794
+ }
795
+ /** A copy whose names (`toFormat`) and `toLocaleString` default use `locale`. */
796
+ setLocale(locale) {
797
+ const [canonical] = Intl.getCanonicalLocales(locale);
798
+ if (canonical === undefined)
799
+ throw new RangeError(`Invalid locale: ${locale}`);
800
+ const out = this.#derive(this.#iso);
801
+ out.#locale = canonical;
802
+ return out;
803
+ }
804
+ /** Always true: chronos refuses invalid input instead of building an invalid value. */
805
+ get isValid() {
806
+ return true;
807
+ }
808
+ /**
809
+ * A copy with some calendar fields replaced, read on this value's wall
810
+ * clock (Luxon's `set`). Changing the month keeps the day within it unless
811
+ * the day is given too.
812
+ *
813
+ * @throws RangeError on a field out of range.
814
+ */
815
+ set(values) {
816
+ const c = this.calendar;
817
+ const mixed = {
818
+ year: values.year ?? c.year,
819
+ month: values.month ?? c.month,
820
+ day: values.day ?? c.day,
821
+ hour: values.hour ?? c.hour,
822
+ minute: values.minute ?? c.minute,
823
+ second: values.second ?? c.second,
824
+ millisecond: values.millisecond ?? c.millisecond,
825
+ };
826
+ if (values.day === undefined &&
827
+ Number.isInteger(mixed.month) &&
828
+ mixed.month >= 1 &&
829
+ mixed.month <= 12) {
830
+ mixed.day = Math.min(mixed.day, daysInMonthOf(mixed.year, mixed.month));
831
+ }
832
+ assertWallClock(mixed, JSON.stringify(values));
833
+ return this.#derive(new Date(wallClockMs(mixed, this.#zone)));
318
834
  }
319
835
  toZonedISO() {
320
836
  if (this.#zone === "UTC")
321
837
  return this.#iso;
322
838
  return nativeChronos().toZone(this.#iso, this.#zone).iso;
323
839
  }
324
- // ─── Arithmetic ─────────────────────────────────────────
325
- plus(amount, unit) {
840
+ plus(amountOrDuration, unit) {
841
+ if (typeof amountOrDuration === "object" && amountOrDuration !== null) {
842
+ return this.#plusDuration(amountOrDuration instanceof Duration
843
+ ? amountOrDuration
844
+ : Duration.fromObject(amountOrDuration));
845
+ }
846
+ if (unit === undefined) {
847
+ throw new TypeError("plus(amount, unit) needs a unit");
848
+ }
849
+ return this.#plusUnit(amountOrDuration, unit);
850
+ }
851
+ #plusDuration(duration) {
852
+ const v = duration.toObject();
853
+ const months = Math.trunc(v.years) * 12 + Math.trunc(v.months);
854
+ const days = Math.trunc(v.weeks) * 7 + Math.trunc(v.days);
855
+ const elapsed = Duration.fromObject({
856
+ years: v.years - Math.trunc(v.years),
857
+ months: v.months - Math.trunc(v.months),
858
+ weeks: v.weeks - Math.trunc(v.weeks),
859
+ days: v.days - Math.trunc(v.days),
860
+ hours: v.hours,
861
+ minutes: v.minutes,
862
+ seconds: v.seconds,
863
+ milliseconds: v.milliseconds,
864
+ }).as("milliseconds");
865
+ let out = this.#plusUnit(months, "month");
866
+ if (days !== 0)
867
+ out = out.#plusUnit(days, "day");
868
+ if (elapsed === 0)
869
+ return out;
870
+ return this.#derive(new Date(out.toMillis() + Math.round(elapsed)));
871
+ }
872
+ #plusUnit(amount, unit) {
873
+ if (typeof amount !== "number" || !Number.isFinite(amount)) {
874
+ throw new RangeError(`Invalid unit value ${String(amount)}: plus/minus take a finite number`);
875
+ }
876
+ const unitMs = casualUnitMs(unit);
877
+ const whole = Math.trunc(amount);
878
+ if (!Number.isSafeInteger(whole)) {
879
+ throw new RangeError(`plus(${amount}, '${unit}') is out of range: years are limited to 0000-9999`);
880
+ }
326
881
  const n = nativeChronos();
327
- const out = this.#zone !== "UTC" && isCalendarUnit(unit)
328
- ? n.addInZone(this.#iso, amount, unit, this.#zone)
329
- : n.add(this.#iso, amount, unit);
330
- return new DateTime(out, this.#zone);
882
+ const shifted = whole === 0
883
+ ? this.#iso
884
+ : this.#zone !== "UTC" && isCalendarUnit(unit)
885
+ ? n.addInZone(this.#iso, whole, unit, this.#zone)
886
+ : n.add(this.#iso, whole, unit);
887
+ const fraction = amount - whole;
888
+ if (fraction === 0)
889
+ return this.#derive(shifted);
890
+ return this.#derive(new Date(Date.parse(shifted) + Math.round(fraction * unitMs)));
331
891
  }
332
- minus(amount, unit) {
333
- return this.plus(-amount, unit);
892
+ minus(amountOrDuration, unit) {
893
+ if (typeof amountOrDuration === "object" && amountOrDuration !== null) {
894
+ const duration = amountOrDuration instanceof Duration
895
+ ? amountOrDuration
896
+ : Duration.fromObject(amountOrDuration);
897
+ return this.#plusDuration(duration.negate());
898
+ }
899
+ if (unit === undefined) {
900
+ throw new TypeError("minus(amount, unit) needs a unit");
901
+ }
902
+ // Checked before negating: `-"1"` would turn a string into a number.
903
+ if (typeof amountOrDuration !== "number") {
904
+ throw new RangeError(`Invalid unit value ${String(amountOrDuration)}: plus/minus take a finite number`);
905
+ }
906
+ return this.#plusUnit(-amountOrDuration, unit);
334
907
  }
335
- diff(other, unit) {
908
+ /**
909
+ * `this - other` as a Duration in the given unit(s), as Luxon's `diff`:
910
+ * calendar units are counted on this value's calendar (a day across a DST
911
+ * change is one day), the lowest unit keeps its fraction, and clock units
912
+ * take what is left. `.as(unit)` reads it as a number.
913
+ */
914
+ diff(other, unit = "milliseconds") {
915
+ const units = (Array.isArray(unit) ? unit : [unit]).map(durationUnitOf);
916
+ const ordered = DIFF_ORDER.filter((u) => units.includes(u));
917
+ if (ordered.length === 0)
918
+ throw new RangeError("diff needs a unit");
919
+ const o = _a.from(other).setZone(this.#zone);
920
+ const thisIsLater = this.toMillis() >= o.toMillis();
921
+ const earlier = thisIsLater ? o : this;
922
+ const later = thisIsLater ? this : o;
923
+ const calendar = ordered.filter((u) => CALENDAR_UNITS.has(u));
924
+ const clock = ordered.filter((u) => !CALENDAR_UNITS.has(u));
925
+ const results = {};
926
+ let cursor = earlier;
927
+ for (const u of calendar) {
928
+ results[u] = Math.trunc(later.#diffNumber(cursor, u));
929
+ cursor = earlier.plus(results);
930
+ }
931
+ let out;
932
+ const lowest = calendar.at(-1);
933
+ if (clock.length === 0 && lowest !== undefined) {
934
+ results[lowest] =
935
+ (results[lowest] ?? 0) + later.#diffNumber(cursor, lowest);
936
+ out = Duration.fromObject(results);
937
+ }
938
+ else {
939
+ out = Duration.fromMillis(later.toMillis() - cursor.toMillis())
940
+ .shiftTo(...clock)
941
+ .plus(results);
942
+ }
943
+ return thisIsLater ? out : out.negate();
944
+ }
945
+ /** `this - other` in one unit, as a fractional number (calendar-aware). */
946
+ #diffNumber(other, unit) {
336
947
  const n = nativeChronos();
337
- const otherIso = toIso(other);
338
- return this.#zone !== "UTC" && (unit === "month" || unit === "year")
339
- ? n.diffInZone(this.#iso, otherIso, unit, this.#zone)
340
- : n.diff(this.#iso, otherIso, unit);
948
+ const singular = unit.slice(0, -1);
949
+ return CALENDAR_UNITS.has(unit)
950
+ ? n.diffInZone(this.#iso, other.#iso, singular, this.#zone)
951
+ : n.diff(this.#iso, other.#iso, unit);
341
952
  }
342
953
  // ─── Comparison ─────────────────────────────────────────
954
+ /**
955
+ * Same instant — and, against another DateTime, same zone and locale, as
956
+ * Luxon's `equals`. Compare `toMillis()` (or use `<`, `>`) for the instant
957
+ * alone.
958
+ */
343
959
  equals(other) {
960
+ if (other instanceof _a) {
961
+ return (this.#iso === other.#iso &&
962
+ this.#zone === other.#zone &&
963
+ this.#locale === other.#locale);
964
+ }
344
965
  return this.#iso === toIso(other);
345
966
  }
346
967
  isBefore(other) {
@@ -349,8 +970,10 @@ export class DateTime {
349
970
  isAfter(other) {
350
971
  return toMs(this) > toMs(other);
351
972
  }
973
+ /** Whether `other` falls in the same `unit` as this value, on this value's calendar. */
352
974
  hasSame(other, unit) {
353
- return (this.startOf(unit).toISO() === DateTime.from(other).startOf(unit).toISO());
975
+ const o = _a.from(other).setZone(this.#zone);
976
+ return this.startOf(unit).toMillis() === o.startOf(unit).toMillis();
354
977
  }
355
978
  isSameDay(other) {
356
979
  return this.hasSame(other, "day");
@@ -366,85 +989,160 @@ export class DateTime {
366
989
  */
367
990
  startOf(unit) {
368
991
  const n = nativeChronos();
369
- return new DateTime(this.#zone === "UTC"
992
+ return this.#derive(this.#zone === "UTC"
370
993
  ? n.startOf(this.#iso, unit)
371
- : n.startOfInZone(this.#iso, unit, this.#zone), this.#zone);
994
+ : n.startOfInZone(this.#iso, unit, this.#zone));
372
995
  }
373
996
  /** The last instant of `unit` — see {@link startOf} on the shared routine. */
374
997
  endOf(unit) {
375
998
  const n = nativeChronos();
376
- return new DateTime(this.#zone === "UTC"
999
+ return this.#derive(this.#zone === "UTC"
377
1000
  ? n.endOf(this.#iso, unit)
378
- : n.endOfInZone(this.#iso, unit, this.#zone), this.#zone);
1001
+ : n.endOfInZone(this.#iso, unit, this.#zone));
379
1002
  }
380
1003
  // ─── Range ──────────────────────────────────────────────
381
1004
  isWithin(range, options = {}) {
382
1005
  return rangeContains(range, { start: this.#iso, end: this.#iso }, options);
383
1006
  }
384
1007
  // ─── Formatting ─────────────────────────────────────────
1008
+ /**
1009
+ * Format with chronos's moment-style tokens (`YYYY`, `YY`, `MM`, `DD`,
1010
+ * `HH`, `mm`, `ss`, `Z`; `[text]` is literal) on this value's wall clock.
1011
+ * Luxon's tokens (`yyyy`, `dd`, `LLL`, …) are {@link toFormat}.
1012
+ */
385
1013
  format(pattern = "YYYY-MM-DD HH:mm:ss") {
386
1014
  if (this.#zone !== "UTC") {
387
1015
  return formatFromIsoString(nativeChronos().toZone(this.#iso, this.#zone).iso, pattern);
388
1016
  }
389
1017
  return nativeChronos().format(this.#iso, pattern);
390
1018
  }
1019
+ /**
1020
+ * Format with Luxon's tokens (`yyyy-MM-dd HH:mm`, `dd LLL yyyy`, `EEEE`,
1021
+ * `ZZ`, macros such as `DD` or `t`; `'quoted'` text is literal), on this
1022
+ * value's wall clock. {@link format} keeps chronos's moment-style tokens.
1023
+ */
1024
+ toFormat(pattern) {
1025
+ return this.#luxonFormat(pattern, false);
1026
+ }
1027
+ /** `allowZ`: a UTC value writes its offset as `Z` (ISO and SQL output). */
1028
+ #luxonFormat(pattern, allowZ = true) {
1029
+ return formatLuxon(pattern, {
1030
+ parts: this.calendar,
1031
+ ts: this.toMillis(),
1032
+ offset: this.offset,
1033
+ zone: this.#zone,
1034
+ locale: this.#locale,
1035
+ allowZ: allowZ && this.#zone === "UTC",
1036
+ });
1037
+ }
391
1038
  toDate() {
392
1039
  return new Date(this.#iso);
393
1040
  }
394
- toISO() {
395
- return this.#iso;
1041
+ /**
1042
+ * ISO 8601 on this value's wall clock, as Luxon's `toISO`: `…Z` in UTC,
1043
+ * the local offset (`2026-08-10T12:00:00.000+02:00`) in any other zone —
1044
+ * the same instant either way.
1045
+ */
1046
+ toISO(options = {}) {
1047
+ const plain = options.suppressMilliseconds !== true && options.includeOffset !== false;
1048
+ if (this.#zone === "UTC" && plain)
1049
+ return this.#iso;
1050
+ return this.#luxonFormat(`yyyy-MM-dd'T'${this.#timeFormat(options)}`);
1051
+ }
1052
+ #timeFormat(options) {
1053
+ const ms = options.suppressMilliseconds === true && this.millisecond === 0
1054
+ ? ""
1055
+ : ".SSS";
1056
+ return `HH:mm:ss${ms}${options.includeOffset === false ? "" : "ZZ"}`;
1057
+ }
1058
+ /** `yyyy-MM-dd` on this value's calendar. */
1059
+ toISODate() {
1060
+ return this.#luxonFormat("yyyy-MM-dd");
1061
+ }
1062
+ /** `HH:mm:ss.SSS` plus the offset, on this value's wall clock. */
1063
+ toISOTime(options = {}) {
1064
+ return this.#luxonFormat(this.#timeFormat(options));
1065
+ }
1066
+ /** `yyyy-MM-dd`, as SQL writes a date. */
1067
+ toSQLDate() {
1068
+ return this.toISODate();
1069
+ }
1070
+ /** `HH:mm:ss.SSS +02:00` (`Z` in UTC), as Luxon's `toSQLTime`. */
1071
+ toSQLTime(options = {}) {
1072
+ return this.#luxonFormat(options.includeOffset === false ? "HH:mm:ss.SSS" : "HH:mm:ss.SSS ZZ");
1073
+ }
1074
+ /** `yyyy-MM-dd HH:mm:ss.SSS +02:00`, as Luxon's `toSQL`. */
1075
+ toSQL(options = {}) {
1076
+ return `${this.toSQLDate()} ${this.toSQLTime(options)}`;
396
1077
  }
397
1078
  toString() {
398
- return this.#iso;
1079
+ return this.toISO();
399
1080
  }
400
1081
  toJSON() {
401
- return this.#iso;
1082
+ return this.toISO();
402
1083
  }
403
1084
  toMillis() {
404
1085
  return new Date(this.#iso).getTime();
405
1086
  }
1087
+ /** Epoch milliseconds, so `a < b` and `a - b` work as with Luxon. */
1088
+ valueOf() {
1089
+ return this.toMillis();
1090
+ }
406
1091
  toSeconds() {
407
1092
  return Math.floor(this.toMillis() / 1000);
408
1093
  }
409
1094
  toLocaleString(locale, options) {
410
- return new Intl.DateTimeFormat(locale, {
411
- ...(this.#zone !== "UTC" ? { timeZone: this.#zone } : {}),
1095
+ // The value's own zone, UTC included: without it Intl falls back to the
1096
+ // host's zone and the same value prints differently per machine.
1097
+ return new Intl.DateTimeFormat(locale ?? this.#locale, {
1098
+ timeZone: this.#zone,
412
1099
  ...options,
413
1100
  }).format(this.toDate());
414
1101
  }
415
- toRelative(options) {
416
- const base = options?.base ? DateTime.from(options.base) : new DateTime();
417
- const diffMs = this.toMillis() - base.toMillis();
418
- const abs = Math.abs(diffMs);
1102
+ /**
1103
+ * This value relative to `base` (now by default), as Luxon's `toRelative`:
1104
+ * "in 1 day", "48 hours ago". The count is the calendar-aware diff in the
1105
+ * largest unit that reaches 1, truncated toward zero, always as a number
1106
+ * ("1 day ago", never "yesterday": that is {@link toRelativeCalendar}).
1107
+ * Formatted in this value's locale unless `locale` is given.
1108
+ *
1109
+ * NAMED DEVIATION: no `quarters` unit, as chronos's Duration has none.
1110
+ */
1111
+ toRelative(options = {}) {
1112
+ const base = options.base === undefined
1113
+ ? _a.now(this.#zone)
1114
+ : _a.from(options.base);
1115
+ const padding = options.padding
1116
+ ? this.toMillis() < base.toMillis()
1117
+ ? -options.padding
1118
+ : options.padding
1119
+ : 0;
1120
+ let units = TO_RELATIVE_UNITS;
419
1121
  let unit;
420
- let value;
421
- if (abs < 60_000) {
422
- unit = "second";
423
- value = Math.round(diffMs / 1000);
1122
+ if (Array.isArray(options.unit)) {
1123
+ units = options.unit.map(relativeUnitOf);
424
1124
  }
425
- else if (abs < 3_600_000) {
426
- unit = "minute";
427
- value = Math.round(diffMs / 60_000);
1125
+ else if (options.unit !== undefined) {
1126
+ unit = relativeUnitOf(options.unit);
428
1127
  }
429
- else if (abs < 86_400_000) {
430
- unit = "hour";
431
- value = Math.round(diffMs / 3_600_000);
432
- }
433
- else if (abs < 2_592_000_000) {
434
- unit = "day";
435
- value = Math.round(diffMs / 86_400_000);
436
- }
437
- else if (abs < 31_536_000_000) {
438
- unit = "month";
439
- value = Math.round(diffMs / 2_592_000_000);
440
- }
441
- else {
442
- unit = "year";
443
- value = Math.round(diffMs / 31_536_000_000);
444
- }
445
- return new Intl.RelativeTimeFormat(options?.locale, {
1128
+ return diffRelative(base, padding === 0 ? this : this.plus({ milliseconds: padding }), { ...options, numeric: "always", units, unit, calendary: false });
1129
+ }
1130
+ /**
1131
+ * This value relative to `base`'s calendar, as Luxon's
1132
+ * `toRelativeCalendar`: "yesterday", "next month", "3 days ago". Counts the
1133
+ * calendar boundaries crossed in years, months, then days, or in `unit`.
1134
+ */
1135
+ toRelativeCalendar(options = {}) {
1136
+ const base = options.base === undefined
1137
+ ? _a.now(this.#zone)
1138
+ : _a.from(options.base);
1139
+ return diffRelative(base, this, {
1140
+ ...options,
446
1141
  numeric: "auto",
447
- }).format(value, unit);
1142
+ units: TO_RELATIVE_CALENDAR_UNITS,
1143
+ unit: options.unit === undefined ? undefined : relativeUnitOf(options.unit),
1144
+ calendary: true,
1145
+ });
448
1146
  }
449
1147
  // ─── Calendar accessors ─────────────────────────────────
450
1148
  get calendar() {
@@ -499,6 +1197,7 @@ export class DateTime {
499
1197
  return this.calendar.millisecond;
500
1198
  }
501
1199
  }
1200
+ _a = DateTime;
502
1201
  // ─── Standalone range helpers ────────────────────────────────
503
1202
  export function inRange(input, range, options = {}) {
504
1203
  return DateTime.from(input).isWithin(range, options);