@c9up/chronos 0.1.16 → 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 (59) hide show
  1. package/README.md +81 -8
  2. package/dist/DateTime.d.ts +64 -4
  3. package/dist/DateTime.d.ts.map +1 -1
  4. package/dist/DateTime.js +314 -32
  5. package/dist/DateTime.js.map +1 -1
  6. package/dist/format.d.ts +10 -0
  7. package/dist/format.d.ts.map +1 -1
  8. package/dist/format.js +5 -5
  9. package/dist/format.js.map +1 -1
  10. package/dist/holidays.d.ts +43 -0
  11. package/dist/holidays.d.ts.map +1 -0
  12. package/dist/holidays.js +102 -0
  13. package/dist/holidays.js.map +1 -0
  14. package/dist/index.d.ts +3 -1
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +1 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/native/generated.d.ts +9 -0
  19. package/dist/native/generated.d.ts.map +1 -1
  20. package/dist/native.d.ts.map +1 -1
  21. package/dist/native.js +3 -0
  22. package/dist/native.js.map +1 -1
  23. package/dist/parse.d.ts +59 -0
  24. package/dist/parse.d.ts.map +1 -0
  25. package/dist/parse.js +404 -0
  26. package/dist/parse.js.map +1 -0
  27. package/dist/rrule.d.ts +10 -2
  28. package/dist/rrule.d.ts.map +1 -1
  29. package/dist/rrule.js +33 -7
  30. package/dist/rrule.js.map +1 -1
  31. package/index.darwin-arm64.node +0 -0
  32. package/index.darwin-x64.node +0 -0
  33. package/index.linux-arm64-gnu.node +0 -0
  34. package/index.linux-x64-gnu.node +0 -0
  35. package/index.win32-x64-msvc.node +0 -0
  36. package/package.json +2 -3
  37. package/src/DateTime.ts +448 -32
  38. package/src/format.ts +6 -6
  39. package/src/holidays.ts +161 -0
  40. package/src/index.ts +18 -0
  41. package/src/native/generated.ts +21 -0
  42. package/src/native.ts +4 -0
  43. package/src/parse.ts +559 -0
  44. package/src/rrule.ts +47 -8
  45. package/wasm/chronos_engine_wasm.d.ts +9 -0
  46. package/wasm/chronos_engine_wasm.js +61 -0
  47. package/wasm/chronos_engine_wasm_bg.wasm +0 -0
  48. package/wasm/chronos_engine_wasm_bg.wasm.d.ts +3 -0
  49. package/dist/utils.d.ts +0 -15
  50. package/dist/utils.d.ts.map +0 -1
  51. package/dist/utils.js +0 -17
  52. package/dist/utils.js.map +0 -1
  53. package/scripts/build-napi-types.mjs +0 -69
  54. package/scripts/clean-wasm-pack-meta.mjs +0 -32
  55. package/scripts/copy-napi.mjs +0 -56
  56. package/scripts/generate-napi-types.mjs +0 -156
  57. package/scripts/verify-napi.mjs +0 -46
  58. package/scripts/verify-wasm.mjs +0 -55
  59. package/src/utils.ts +0 -17
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@c9up/chronos",
3
- "version": "0.1.16",
3
+ "version": "0.1.17",
4
4
  "description": "Chronos — advanced date/time and recurrence engine (TypeScript + Rust N-API)",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,7 +21,6 @@
21
21
  "README.md",
22
22
  "dist",
23
23
  "index.*.node",
24
- "scripts",
25
24
  "src",
26
25
  "wasm"
27
26
  ],
@@ -51,7 +50,7 @@
51
50
  "test": "vitest run",
52
51
  "test:rust": "cargo test",
53
52
  "test:napi": "node scripts/verify-napi.mjs",
54
- "build:wasm": "wasm-pack build --target web crates/chronos-engine-wasm --out-dir ../../wasm && node scripts/clean-wasm-pack-meta.mjs",
53
+ "build:wasm": "node scripts/build-wasm.mjs",
55
54
  "lint": "biome check src/ tests/",
56
55
  "test:coverage": "vitest run --coverage",
57
56
  "typecheck": "tsc --noEmit"
package/src/DateTime.ts CHANGED
@@ -17,7 +17,21 @@ import {
17
17
  } from "./Duration.js";
18
18
  import { formatLuxon } from "./format.js";
19
19
  import { nativeChronos } from "./native.js";
20
- import { normalizeIso } from "./utils.js";
20
+ import {
21
+ type CalendarDay,
22
+ dayOfMs,
23
+ daysInYearOf,
24
+ dayToIsoWeek,
25
+ dayToOrdinal,
26
+ isoWeekday,
27
+ isoWeeksInYear,
28
+ isoWeekToDay,
29
+ ordinalToDay,
30
+ type ParsedFields,
31
+ type ParsedText,
32
+ parseWithFormat,
33
+ utcDayMs,
34
+ } from "./parse.js";
21
35
 
22
36
  export type DateUnit =
23
37
  | "second"
@@ -204,6 +218,151 @@ function isoOfMs(ms: number, input: () => string): string {
204
218
  return new Date(ms).toISOString();
205
219
  }
206
220
 
221
+ /**
222
+ * Fill the units a `fromFormat` text left out, as Luxon's `fromObject` does:
223
+ * the units larger than the largest one written come from `now`, the smaller
224
+ * ones take their minimum. A text naming a week (`kkkk`, `W`) or only a
225
+ * weekday is read on the ISO week calendar, one naming an ordinal (`o`) on the
226
+ * ordinal calendar. Every unit is range-checked; hour 24 is accepted at
227
+ * 24:00:00.000 and is midnight of the next day, as Luxon reads it.
228
+ */
229
+ function resolveParsedFields(
230
+ f: ParsedFields,
231
+ now: WallClock,
232
+ raw: string,
233
+ ): WallClock {
234
+ const hasOrdinal = f.ordinal !== undefined;
235
+ const hasMonthDay = f.month !== undefined || f.day !== undefined;
236
+ const hasGregorian = f.year !== undefined || hasMonthDay;
237
+ const weekDefined = f.weekYear !== undefined || f.weekNumber !== undefined;
238
+ if ((hasGregorian || hasOrdinal) && weekDefined) {
239
+ throw new Error(
240
+ "Can't mix weekYear/weekNumber units with year/month/day or ordinals",
241
+ );
242
+ }
243
+ if (hasMonthDay && hasOrdinal) {
244
+ throw new Error("Can't mix ordinal dates with month/day");
245
+ }
246
+ let found = false;
247
+ const take = (given: number | undefined, current: number, min: number) => {
248
+ if (given !== undefined) {
249
+ found = true;
250
+ return given;
251
+ }
252
+ return found ? min : current;
253
+ };
254
+ const range = (unit: string, value: number, min: number, max: number) => {
255
+ if (!Number.isInteger(value) || value < min || value > max) {
256
+ throw new RangeError(
257
+ `Invalid date '${raw}': ${unit} ${String(value)} is out of range (${min}-${max}).`,
258
+ );
259
+ }
260
+ };
261
+ const nowDay: CalendarDay = {
262
+ year: now.year,
263
+ month: now.month,
264
+ day: now.day,
265
+ };
266
+ let day: CalendarDay;
267
+ if (weekDefined || (f.weekday !== undefined && !hasGregorian)) {
268
+ const nowWeek = dayToIsoWeek(nowDay);
269
+ const weekYear = take(f.weekYear, nowWeek.weekYear, 1);
270
+ const weekNumber = take(f.weekNumber, nowWeek.weekNumber, 1);
271
+ const weekday = take(f.weekday, nowWeek.weekday, 1);
272
+ range("weekYear", weekYear, 0, 9999);
273
+ range("weekNumber", weekNumber, 1, isoWeeksInYear(weekYear));
274
+ range("weekday", weekday, 1, 7);
275
+ day = isoWeekToDay(weekYear, weekNumber, weekday);
276
+ } else if (hasOrdinal) {
277
+ const year = take(f.year, now.year, 1);
278
+ const ordinal = take(f.ordinal, dayToOrdinal(nowDay), 1);
279
+ range("year", year, 0, 9999);
280
+ range("ordinal", ordinal, 1, daysInYearOf(year));
281
+ day = ordinalToDay(year, ordinal);
282
+ } else {
283
+ day = {
284
+ year: take(f.year, now.year, 1),
285
+ month: take(f.month, now.month, 1),
286
+ day: take(f.day, now.day, 1),
287
+ };
288
+ }
289
+ const clock: WallClock = {
290
+ ...day,
291
+ hour: take(f.hour, now.hour, 0),
292
+ minute: take(f.minute, now.minute, 0),
293
+ second: take(f.second, now.second, 0),
294
+ millisecond: take(f.millisecond, now.millisecond, 0),
295
+ };
296
+ const endOfDay =
297
+ clock.hour === 24 &&
298
+ clock.minute === 0 &&
299
+ clock.second === 0 &&
300
+ clock.millisecond === 0;
301
+ assertWallClock(endOfDay ? { ...clock, hour: 0 } : clock, raw);
302
+ const out = endOfDay
303
+ ? {
304
+ ...clock,
305
+ ...dayOfMs(utcDayMs(clock.year, clock.month, clock.day + 1)),
306
+ hour: 0,
307
+ }
308
+ : clock;
309
+ assertWallClock(out, raw);
310
+ if (
311
+ f.weekday !== undefined &&
312
+ hasGregorian &&
313
+ isoWeekday(out) !== f.weekday
314
+ ) {
315
+ throw new RangeError(
316
+ `Invalid date '${raw}': weekday ${f.weekday} does not fall on ${pad(out.year, 4)}-${pad(out.month)}-${pad(out.day)}.`,
317
+ );
318
+ }
319
+ return out;
320
+ }
321
+
322
+ /** Now as a wall clock in `zone`, or at a fixed `offset` (minutes) when the text gave one. */
323
+ function nowWallClock(zone: string, offset: number | undefined): WallClock {
324
+ if (offset === undefined) {
325
+ const { year, month, day, hour, minute, second, millisecond } =
326
+ DateTime.now(zone).calendar;
327
+ return { year, month, day, hour, minute, second, millisecond };
328
+ }
329
+ const d = new Date(Date.now() + offset * 60_000);
330
+ return {
331
+ year: d.getUTCFullYear(),
332
+ month: d.getUTCMonth() + 1,
333
+ day: d.getUTCDate(),
334
+ hour: d.getUTCHours(),
335
+ minute: d.getUTCMinutes(),
336
+ second: d.getUTCSeconds(),
337
+ millisecond: d.getUTCMilliseconds(),
338
+ };
339
+ }
340
+
341
+ /**
342
+ * The instant of a parsed wall clock. An offset alone fixes it. A zone and an
343
+ * offset together: the offset settles the hour a zone repeats when its clocks
344
+ * go back, as long as the zone has that offset then; otherwise the zone wins.
345
+ */
346
+ function instantOfParsed(
347
+ c: WallClock,
348
+ parsed: ParsedText,
349
+ wallZone: string,
350
+ ): number {
351
+ if (parsed.offset !== undefined) {
352
+ const atOffset = utcMs(c) - parsed.offset * 60_000;
353
+ if (parsed.zone === undefined) return atOffset;
354
+ const zoneOffset =
355
+ parsed.zone === "UTC"
356
+ ? 0
357
+ : nativeChronos().zoneOffset(
358
+ isoOfMs(atOffset, () => `'${parsed.zone}'`),
359
+ parsed.zone,
360
+ );
361
+ if (zoneOffset === parsed.offset) return atOffset;
362
+ }
363
+ return wallClockMs(c, wallZone);
364
+ }
365
+
207
366
  /** Read an ISO 8601 string; an offset-less one is a wall clock in `zone`. */
208
367
  function parseIso(raw: string, zone: string): string {
209
368
  const m = ISO_8601.exec(raw);
@@ -244,14 +403,14 @@ function parseIso(raw: string, zone: string): string {
244
403
  function toIso(value: DateInput, zone = "UTC"): string {
245
404
  if (value instanceof DateTime) return value.toISO();
246
405
  if (value instanceof Date) {
247
- return normalizeIso(isoOfMs(value.getTime(), () => "(JS Date)"));
406
+ return isoOfMs(value.getTime(), () => "(JS Date)");
248
407
  }
249
408
  if (typeof value !== "string") {
250
409
  throw new TypeError(
251
410
  `Invalid date input: expected a string, a Date or a DateTime, got ${typeof value}`,
252
411
  );
253
412
  }
254
- return normalizeIso(parseIso(value, zone));
413
+ return parseIso(value, zone);
255
414
  }
256
415
 
257
416
  function toMs(value: DateInput): number {
@@ -295,6 +454,183 @@ const CALENDAR_UNITS: ReadonlySet<DurationUnit> = new Set([
295
454
  "days",
296
455
  ]);
297
456
 
457
+ /** A unit `toRelative` and `toRelativeCalendar` can count in. */
458
+ export type RelativeUnit =
459
+ | "years"
460
+ | "months"
461
+ | "weeks"
462
+ | "days"
463
+ | "hours"
464
+ | "minutes"
465
+ | "seconds";
466
+ export type RelativeUnitLike =
467
+ | RelativeUnit
468
+ | "year"
469
+ | "month"
470
+ | "week"
471
+ | "day"
472
+ | "hour"
473
+ | "minute"
474
+ | "second";
475
+ export type RelativeRounding = "trunc" | "expand" | "round" | "floor" | "ceil";
476
+
477
+ interface RelativeFormatOptions {
478
+ /** Compared against; now, in this value's zone, by default. */
479
+ base?: DateInput;
480
+ /** Overrides this value's locale. */
481
+ locale?: Intl.LocalesArgument;
482
+ style?: Intl.RelativeTimeFormatStyle;
483
+ /** Reaches the formatter; the engine may not honour it. */
484
+ numberingSystem?: string;
485
+ }
486
+
487
+ export interface ToRelativeOptions extends RelativeFormatOptions {
488
+ /** One unit, or the units to pick the largest non-zero one from. */
489
+ unit?: RelativeUnitLike | readonly RelativeUnitLike[];
490
+ /** Round the count (default), or keep two decimals. */
491
+ round?: boolean;
492
+ /** How the count is rounded; toward zero by default. */
493
+ rounding?: RelativeRounding;
494
+ /** Milliseconds added away from the base before counting. */
495
+ padding?: number;
496
+ }
497
+
498
+ export interface ToRelativeCalendarOptions extends RelativeFormatOptions {
499
+ unit?: RelativeUnitLike;
500
+ }
501
+
502
+ const RELATIVE_UNITS: readonly RelativeUnit[] = [
503
+ "years",
504
+ "months",
505
+ "weeks",
506
+ "days",
507
+ "hours",
508
+ "minutes",
509
+ "seconds",
510
+ ];
511
+ const TO_RELATIVE_UNITS: readonly RelativeUnit[] = [
512
+ "years",
513
+ "months",
514
+ "days",
515
+ "hours",
516
+ "minutes",
517
+ "seconds",
518
+ ];
519
+ const TO_RELATIVE_CALENDAR_UNITS: readonly RelativeUnit[] = [
520
+ "years",
521
+ "months",
522
+ "days",
523
+ ];
524
+ const BOUND_OF: Readonly<Record<RelativeUnit, BoundUnit>> = {
525
+ years: "year",
526
+ months: "month",
527
+ weeks: "week",
528
+ days: "day",
529
+ hours: "hour",
530
+ minutes: "minute",
531
+ seconds: "second",
532
+ };
533
+
534
+ function relativeUnitOf(unit: unknown): RelativeUnit {
535
+ const plural =
536
+ typeof unit === "string" && !unit.endsWith("s") ? `${unit}s` : unit;
537
+ const found = RELATIVE_UNITS.find((u) => u === plural);
538
+ if (found === undefined) {
539
+ throw new RangeError(`Unsupported relative unit: ${String(unit)}`);
540
+ }
541
+ return found;
542
+ }
543
+
544
+ /** Round to `digits` decimals the way the reference library's `roundTo` does. */
545
+ function roundTo(value: number, digits: number, rounding: unknown): number {
546
+ const factor = 10 ** digits;
547
+ switch (rounding) {
548
+ case "expand":
549
+ return value > 0
550
+ ? Math.ceil(value * factor) / factor
551
+ : Math.floor(value * factor) / factor;
552
+ case "trunc":
553
+ return Math.trunc(value * factor) / factor;
554
+ case "round":
555
+ return Math.round(value * factor) / factor;
556
+ case "floor":
557
+ return Math.floor(value * factor) / factor;
558
+ case "ceil":
559
+ return Math.ceil(value * factor) / factor;
560
+ default:
561
+ throw new RangeError(
562
+ `Value rounding ${String(rounding)} is out of range`,
563
+ );
564
+ }
565
+ }
566
+
567
+ /**
568
+ * The reference library's `diffRelative`: count `end - start` in the first
569
+ * unit (largest first) that reaches 1, or in the one unit asked for.
570
+ * `calendary` counts calendar boundaries crossed (yesterday is 1 day back at
571
+ * 23:59 as at 00:01) and rounds to the nearest; otherwise the count is the
572
+ * calendar-aware diff, truncated unless `rounding` says otherwise.
573
+ */
574
+ function diffRelative(
575
+ start: DateTime,
576
+ end: DateTime,
577
+ opts: RelativeFormatOptions & {
578
+ units: readonly RelativeUnit[];
579
+ unit: RelativeUnit | undefined;
580
+ calendary: boolean;
581
+ numeric: "always" | "auto";
582
+ round?: boolean;
583
+ rounding?: RelativeRounding;
584
+ },
585
+ ): string {
586
+ const round = opts.round ?? true;
587
+ const rounding = opts.rounding ?? "trunc";
588
+ // NAMED DEVIATION: the reference library prints English (en, en-US) from a
589
+ // hand-written table and every other locale through Intl. Every locale goes
590
+ // through Intl here, so en-US gets CLDR's own short and narrow forms
591
+ // ("2d ago" in narrow, where the table prints "2 days ago"); the long style,
592
+ // the default, reads the same.
593
+ const intlOptions: Intl.RelativeTimeFormatOptions & {
594
+ numberingSystem?: string;
595
+ } = {
596
+ numeric: opts.numeric,
597
+ style: opts.style ?? "long",
598
+ };
599
+ if (opts.numberingSystem !== undefined) {
600
+ intlOptions.numberingSystem = opts.numberingSystem;
601
+ }
602
+ const formatter = new Intl.RelativeTimeFormat(
603
+ opts.locale ?? end.locale,
604
+ intlOptions,
605
+ );
606
+ const format = (count: number, unit: RelativeUnit): string =>
607
+ formatter.format(
608
+ roundTo(
609
+ count,
610
+ round || opts.calendary ? 0 : 2,
611
+ opts.calendary ? "round" : rounding,
612
+ ),
613
+ unit,
614
+ );
615
+ const differ = (unit: RelativeUnit): number => {
616
+ if (opts.calendary) {
617
+ const bound = BOUND_OF[unit];
618
+ if (end.hasSame(start, bound)) return 0;
619
+ return end.startOf(bound).diff(start.startOf(bound), unit).as(unit);
620
+ }
621
+ return end.diff(start, unit).as(unit);
622
+ };
623
+
624
+ if (opts.unit !== undefined) return format(differ(opts.unit), opts.unit);
625
+ for (const unit of opts.units) {
626
+ const count = differ(unit);
627
+ if (Math.abs(count) >= 1) return format(count, unit);
628
+ }
629
+ const last = opts.units.at(-1);
630
+ if (last === undefined) throw new RangeError("No unit to count in");
631
+ return format(start.toMillis() > end.toMillis() ? -0 : 0, last);
632
+ }
633
+
298
634
  function durationUnitOf(unit: string): DurationUnit {
299
635
  const plural = unit.endsWith("s") ? unit : `${unit}s`;
300
636
  const found = DIFF_ORDER.find((u) => u === plural);
@@ -579,6 +915,13 @@ export class DateTime {
579
915
  return new DateTime(new Date(ms));
580
916
  }
581
917
  static fromSeconds(seconds: number): DateTime {
918
+ // Same guard as fromMillis: `seconds * 1000` would turn "12" into 12 s
919
+ // and null into the epoch.
920
+ if (typeof seconds !== "number") {
921
+ throw new TypeError(
922
+ `fromSeconds expects a number, got ${seconds === null ? "null" : typeof seconds}`,
923
+ );
924
+ }
582
925
  return new DateTime(new Date(seconds * 1000));
583
926
  }
584
927
  static fromUnix(seconds: number): DateTime {
@@ -653,6 +996,59 @@ export class DateTime {
653
996
  return new DateTime(nativeChronos().parseHttp(input));
654
997
  }
655
998
 
999
+ /**
1000
+ * Read `text` written with Luxon's format tokens (`dd/MM/yyyy HH:mm`,
1001
+ * `dd LLL yyyy 'at' h:mm a`, `kkkk-'W'WW-c`, macros such as `D` or `f`), as
1002
+ * Luxon's `fromFormat`. Units the format leaves out are filled as Luxon
1003
+ * fills them: larger ones from now, smaller ones with their minimum
1004
+ * (`HH:mm` is today at that time, `MMMM` the 1st of that month this year).
1005
+ *
1006
+ * The wall clock is read in the zone the text names (`z`), else at the
1007
+ * offset it writes (`Z`, `ZZ`, `ZZZ`), else in `options.zone` (UTC by
1008
+ * default); the result is in `options.zone`. Names are matched in
1009
+ * `options.locale` (en-US by default), which the result keeps.
1010
+ *
1011
+ * Two deviations, named: text that does not match the format, or names a
1012
+ * date that does not exist, throws instead of returning an invalid value
1013
+ * (chronos has no invalid DateTime); and there is no `setZone` option, since
1014
+ * a chronos zone is an IANA name and an offset alone names none.
1015
+ */
1016
+ static fromFormat(
1017
+ text: string,
1018
+ format: string,
1019
+ options: { zone?: string; locale?: string } = {},
1020
+ ): DateTime {
1021
+ if (typeof text !== "string" || typeof format !== "string") {
1022
+ throw new TypeError("fromFormat requires an input string and a format");
1023
+ }
1024
+ const zone = options.zone ?? "UTC";
1025
+ assertZone(zone);
1026
+ const locale = options.locale ?? "en-US";
1027
+ const parsed = parseWithFormat(text, format, locale);
1028
+ if (
1029
+ parsed === null ||
1030
+ (Object.keys(parsed.fields).length === 0 && parsed.zone === undefined)
1031
+ ) {
1032
+ throw new RangeError(
1033
+ `Invalid date '${text}': it does not match the format '${format}'.`,
1034
+ );
1035
+ }
1036
+ if (parsed.zone !== undefined) assertZone(parsed.zone);
1037
+ const wallZone = parsed.zone ?? zone;
1038
+ const clock = resolveParsedFields(
1039
+ parsed.fields,
1040
+ nowWallClock(wallZone, parsed.offset),
1041
+ text,
1042
+ );
1043
+ const ms = instantOfParsed(clock, parsed, wallZone);
1044
+ const out = new DateTime(
1045
+ isoOfMs(ms, () => `'${text}'`),
1046
+ zone,
1047
+ );
1048
+ out.#locale = locale;
1049
+ return out;
1050
+ }
1051
+
656
1052
  // ─── Timezone ───────────────────────────────────────────
657
1053
 
658
1054
  get zoneName(): string {
@@ -1092,37 +1488,57 @@ export class DateTime {
1092
1488
  }).format(this.toDate());
1093
1489
  }
1094
1490
 
1095
- toRelative(options?: {
1096
- base?: DateInput;
1097
- locale?: Intl.LocalesArgument;
1098
- }): string {
1099
- const base = options?.base ? DateTime.from(options.base) : new DateTime();
1100
- const diffMs = this.toMillis() - base.toMillis();
1101
- const abs = Math.abs(diffMs);
1102
- let unit: Intl.RelativeTimeFormatUnit;
1103
- let value: number;
1104
- if (abs < 60_000) {
1105
- unit = "second";
1106
- value = Math.round(diffMs / 1000);
1107
- } else if (abs < 3_600_000) {
1108
- unit = "minute";
1109
- value = Math.round(diffMs / 60_000);
1110
- } else if (abs < 86_400_000) {
1111
- unit = "hour";
1112
- value = Math.round(diffMs / 3_600_000);
1113
- } else if (abs < 2_592_000_000) {
1114
- unit = "day";
1115
- value = Math.round(diffMs / 86_400_000);
1116
- } else if (abs < 31_536_000_000) {
1117
- unit = "month";
1118
- value = Math.round(diffMs / 2_592_000_000);
1119
- } else {
1120
- unit = "year";
1121
- value = Math.round(diffMs / 31_536_000_000);
1491
+ /**
1492
+ * This value relative to `base` (now by default), as Luxon's `toRelative`:
1493
+ * "in 1 day", "48 hours ago". The count is the calendar-aware diff in the
1494
+ * largest unit that reaches 1, truncated toward zero, always as a number
1495
+ * ("1 day ago", never "yesterday": that is {@link toRelativeCalendar}).
1496
+ * Formatted in this value's locale unless `locale` is given.
1497
+ *
1498
+ * NAMED DEVIATION: no `quarters` unit, as chronos's Duration has none.
1499
+ */
1500
+ toRelative(options: ToRelativeOptions = {}): string {
1501
+ const base =
1502
+ options.base === undefined
1503
+ ? DateTime.now(this.#zone)
1504
+ : DateTime.from(options.base);
1505
+ const padding = options.padding
1506
+ ? this.toMillis() < base.toMillis()
1507
+ ? -options.padding
1508
+ : options.padding
1509
+ : 0;
1510
+ let units = TO_RELATIVE_UNITS;
1511
+ let unit: RelativeUnit | undefined;
1512
+ if (Array.isArray(options.unit)) {
1513
+ units = options.unit.map(relativeUnitOf);
1514
+ } else if (options.unit !== undefined) {
1515
+ unit = relativeUnitOf(options.unit);
1122
1516
  }
1123
- return new Intl.RelativeTimeFormat(options?.locale, {
1517
+ return diffRelative(
1518
+ base,
1519
+ padding === 0 ? this : this.plus({ milliseconds: padding }),
1520
+ { ...options, numeric: "always", units, unit, calendary: false },
1521
+ );
1522
+ }
1523
+
1524
+ /**
1525
+ * This value relative to `base`'s calendar, as Luxon's
1526
+ * `toRelativeCalendar`: "yesterday", "next month", "3 days ago". Counts the
1527
+ * calendar boundaries crossed in years, months, then days, or in `unit`.
1528
+ */
1529
+ toRelativeCalendar(options: ToRelativeCalendarOptions = {}): string {
1530
+ const base =
1531
+ options.base === undefined
1532
+ ? DateTime.now(this.#zone)
1533
+ : DateTime.from(options.base);
1534
+ return diffRelative(base, this, {
1535
+ ...options,
1124
1536
  numeric: "auto",
1125
- }).format(value, unit);
1537
+ units: TO_RELATIVE_CALENDAR_UNITS,
1538
+ unit:
1539
+ options.unit === undefined ? undefined : relativeUnitOf(options.unit),
1540
+ calendary: true,
1541
+ });
1126
1542
  }
1127
1543
 
1128
1544
  // ─── Calendar accessors ─────────────────────────────────
package/src/format.ts CHANGED
@@ -36,7 +36,7 @@ export interface FormatContext {
36
36
  allowZ?: boolean;
37
37
  }
38
38
 
39
- const MONTHS_LONG = [
39
+ export const MONTHS_LONG = [
40
40
  "January",
41
41
  "February",
42
42
  "March",
@@ -50,7 +50,7 @@ const MONTHS_LONG = [
50
50
  "November",
51
51
  "December",
52
52
  ];
53
- const WEEKDAYS_LONG = [
53
+ export const WEEKDAYS_LONG = [
54
54
  "Monday",
55
55
  "Tuesday",
56
56
  "Wednesday",
@@ -62,7 +62,7 @@ const WEEKDAYS_LONG = [
62
62
 
63
63
  type NameLength = "short" | "long" | "narrow";
64
64
 
65
- const MACROS: Readonly<Record<string, Intl.DateTimeFormatOptions>> = {
65
+ export const MACROS: Readonly<Record<string, Intl.DateTimeFormatOptions>> = {
66
66
  D: { year: "numeric", month: "numeric", day: "numeric" },
67
67
  DD: { year: "numeric", month: "short", day: "numeric" },
68
68
  DDD: { year: "numeric", month: "long", day: "numeric" },
@@ -170,13 +170,13 @@ const MACROS: Readonly<Record<string, Intl.DateTimeFormatOptions>> = {
170
170
  },
171
171
  };
172
172
 
173
- interface Token {
173
+ export interface Token {
174
174
  literal: boolean;
175
175
  val: string;
176
176
  }
177
177
 
178
178
  /** Luxon's `Formatter.parseFormat`: runs of one letter are a token, `'…'` is literal. */
179
- function parseFormat(fmt: string): Token[] {
179
+ export function parseFormat(fmt: string): Token[] {
180
180
  let current: string | null = null;
181
181
  let currentFull = "";
182
182
  let bracketed = false;
@@ -238,7 +238,7 @@ function formatOffset(
238
238
  }
239
239
  }
240
240
 
241
- function isEnglish(locale: string): boolean {
241
+ export function isEnglish(locale: string): boolean {
242
242
  return /^en(?:-|$)/i.test(locale);
243
243
  }
244
244