@bevelo/date 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,417 @@
1
+ import { a as fromEpochDay, c as toDate, d as assertValidDate, f as assertValidDateTime, g as utcMilliseconds, i as fromDate, l as toEpochDay, m as hasIntl, p as assertWeekday, r as daysInMonth, s as isValidDate, t as dayOfWeek, u as assertInteger } from "./civil-SGLjw0gL.js";
2
+ // src/arithmetic.ts
3
+ const MIDNIGHT$1 = {
4
+ hour: 0,
5
+ minute: 0,
6
+ second: 0,
7
+ millisecond: 0
8
+ };
9
+ /**
10
+ * Largest day count `eachDay` and `eachDayInRange` will produce.
11
+ *
12
+ * A month or a year of days is a UI question; ten thousand days is already 27
13
+ * years, and anything larger is almost certainly a reversed or corrupted input
14
+ * that would allocate millions of objects. Throwing states the limit instead of
15
+ * silently truncating, which would return a range that looks complete.
16
+ */
17
+ const MAX_RANGE_DAYS = 1e4;
18
+ /**
19
+ * Adds a whole number of days.
20
+ *
21
+ * Works by converting to an epoch day, so month lengths, leap years and year
22
+ * boundaries need no special cases.
23
+ */
24
+ function addDays(date, days) {
25
+ assertInteger(days, "days");
26
+ return fromEpochDay(toEpochDay(date) + days);
27
+ }
28
+ /**
29
+ * Adds a whole number of months, clamping the day to the target month's length.
30
+ *
31
+ * Jan 31 + 1 month is Feb 28 (Feb 29 in a leap year), not Mar 2: the result is
32
+ * "the same day of the next month, or the last day of that month if it is
33
+ * shorter", which is the behaviour a date picker's stepper needs. Rejected
34
+ * alternative: overflow into the next month (what Date.setMonth does), which
35
+ * makes the stepper walk forward when the user asked for one month.
36
+ */
37
+ function addMonths(date, months) {
38
+ assertInteger(months, "months");
39
+ if (!isValidDate(date)) throw new RangeError(`Invalid civil date: ${JSON.stringify(date)}`);
40
+ const total = date.year * 12 + (date.month - 1) + months;
41
+ const year = Math.floor(total / 12);
42
+ const month = total - year * 12 + 1;
43
+ return {
44
+ year,
45
+ month,
46
+ day: Math.min(date.day, daysInMonth(year, month))
47
+ };
48
+ }
49
+ /**
50
+ * Adds a whole number of years, clamping Feb 29 to Feb 28 in non-leap years.
51
+ *
52
+ * Implemented through addMonths so the clamping rule exists once.
53
+ */
54
+ function addYears(date, years) {
55
+ assertInteger(years, "years");
56
+ return addMonths(date, years * 12);
57
+ }
58
+ function startOfDay$1(value) {
59
+ if (isCivilDateTimeLike(value)) {
60
+ assertValidDateTime(value);
61
+ return {
62
+ date: { ...value.date },
63
+ time: { ...MIDNIGHT$1 }
64
+ };
65
+ }
66
+ if (!isValidDate(value)) throw new RangeError(`Invalid civil date: ${JSON.stringify(value)}`);
67
+ return { ...value };
68
+ }
69
+ /** The first day of the month. */
70
+ function startOfMonth(date) {
71
+ if (!isValidDate(date)) throw new RangeError(`Invalid civil date: ${JSON.stringify(date)}`);
72
+ return {
73
+ year: date.year,
74
+ month: date.month,
75
+ day: 1
76
+ };
77
+ }
78
+ /** The last day of the month (28, 29, 30 or 31). */
79
+ function endOfMonth(date) {
80
+ if (!isValidDate(date)) throw new RangeError(`Invalid civil date: ${JSON.stringify(date)}`);
81
+ return {
82
+ year: date.year,
83
+ month: date.month,
84
+ day: daysInMonth(date.year, date.month)
85
+ };
86
+ }
87
+ /**
88
+ * The first day of the week containing `date`.
89
+ *
90
+ * `weekStartsOn` is an explicit input rather than a locale lookup: the locale
91
+ * decides what a calendar displays, and the caller owns that policy.
92
+ */
93
+ function startOfWeek(date, weekStartsOn) {
94
+ assertWeekday(weekStartsOn);
95
+ return addDays(date, -((dayOfWeek(date) - weekStartsOn + 7) % 7));
96
+ }
97
+ /** The last day of the week containing `date` (the day before the next week starts). */
98
+ function endOfWeek(date, weekStartsOn) {
99
+ return addDays(startOfWeek(date, weekStartsOn), 6);
100
+ }
101
+ /** True when both dates name the same calendar day. */
102
+ function isSameDay(a, b) {
103
+ return toEpochDay(a) === toEpochDay(b);
104
+ }
105
+ /** True when both dates are in the same year and month. */
106
+ function isSameMonth(a, b) {
107
+ toEpochDay(a);
108
+ toEpochDay(b);
109
+ return a.year === b.year && a.month === b.month;
110
+ }
111
+ /**
112
+ * Orders two dates: -1 when `a` is earlier, 0 when equal, 1 when later.
113
+ *
114
+ * A comparator rather than a boolean because Array.prototype.sort needs exactly
115
+ * this shape, and callers need the direction.
116
+ */
117
+ function compare(a, b) {
118
+ const left = toEpochDay(a);
119
+ const right = toEpochDay(b);
120
+ if (left < right) return -1;
121
+ return left > right ? 1 : 0;
122
+ }
123
+ function min(firstOrDates, ...rest) {
124
+ return extremum(Array.isArray(firstOrDates) ? firstOrDates : [firstOrDates, ...rest], compare);
125
+ }
126
+ function max(firstOrDates, ...rest) {
127
+ return extremum(Array.isArray(firstOrDates) ? firstOrDates : [firstOrDates, ...rest], (a, b) => compare(b, a));
128
+ }
129
+ function extremum(dates, order) {
130
+ const first = dates[0];
131
+ if (first === void 0) throw new RangeError("min/max need at least one date");
132
+ let best = first;
133
+ for (const candidate of dates) if (order(candidate, best) < 0) best = candidate;
134
+ return { ...best };
135
+ }
136
+ /**
137
+ * Every day from `from` to `to`, inclusive, in ascending order.
138
+ *
139
+ * Returns an empty array when `from` is after `to` (a reversed range is an
140
+ * empty selection, not an error) and throws when the span exceeds
141
+ * MAX_RANGE_DAYS so a bad range cannot allocate without bound.
142
+ */
143
+ function eachDay(from, to) {
144
+ const start = toEpochDay(from);
145
+ const end = toEpochDay(to);
146
+ if (end < start) return [];
147
+ const count = end - start + 1;
148
+ if (count > 1e4) throw new RangeError(`Range of ${count} days exceeds MAX_RANGE_DAYS (${MAX_RANGE_DAYS})`);
149
+ return Array.from({ length: count }, (_, index) => fromEpochDay(start + index));
150
+ }
151
+ /**
152
+ * Days from `from` to `to`: positive when `to` is later, negative when earlier,
153
+ * zero on the same day.
154
+ *
155
+ * Signed because a UI that says "3 days early" needs the direction; the absolute
156
+ * difference is `Math.abs(differenceInDays(a, b))`.
157
+ */
158
+ function differenceInDays(from, to) {
159
+ return toEpochDay(to) - toEpochDay(from);
160
+ }
161
+ function isCivilDateTimeLike(value) {
162
+ return typeof value.time === "object" && value.time !== null;
163
+ }
164
+ // src/timezone.ts
165
+ /** Largest magnitude a JavaScript Date (and therefore Intl) can represent. */
166
+ const MAX_INSTANT = 864e13;
167
+ const MIDNIGHT = {
168
+ hour: 0,
169
+ minute: 0
170
+ };
171
+ /** The default `formatInZone` shape: a readable date and a short time. */
172
+ const DEFAULT_FORMAT = {
173
+ dateStyle: "medium",
174
+ timeStyle: "short"
175
+ };
176
+ /**
177
+ * Zones already accepted by the runtime.
178
+ *
179
+ * Validation costs one formatter construction, which is the expensive half of
180
+ * Intl; a calendar asks about the same one or two zones thousands of times, so
181
+ * positive answers are memoized. Negative answers are not cached: a miss is a
182
+ * programming error, not a hot path.
183
+ */
184
+ const knownZones = /* @__PURE__ */ new Set();
185
+ /**
186
+ * Rejects anything that is not a representation a Date can hold.
187
+ *
188
+ * The check is here rather than left to Intl because Intl's response to a
189
+ * non-finite instant is a bare RangeError from formatToParts, which does not
190
+ * name the argument the caller got wrong.
191
+ */
192
+ function assertInstant(instant) {
193
+ if (typeof instant !== "number" || !Number.isFinite(instant) || Math.abs(instant) > MAX_INSTANT) throw new RangeError("Instant must be a time value within the Date range, received " + String(instant));
194
+ }
195
+ /**
196
+ * Rejects zones the runtime does not know.
197
+ *
198
+ * The zone name is validated once per distinct string, so an invalid zone in a
199
+ * render loop throws the same clear RangeError without rebuilding formatters.
200
+ * Any identifier the runtime accepts is accepted here, including IANA aliases
201
+ * (Asia/Calcutta) and, on runtimes that implement it, a UTC offset string.
202
+ */
203
+ function assertZone(zone) {
204
+ if (typeof zone !== "string" || zone.length === 0) throw new RangeError("Time zone must be a non-empty IANA zone name, received " + String(zone));
205
+ if (knownZones.has(zone)) return;
206
+ if (!hasIntl()) throw new RangeError("Time zone conversion requires Intl.DateTimeFormat");
207
+ try {
208
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
209
+ } catch {
210
+ throw new RangeError("Unknown time zone: " + JSON.stringify(zone));
211
+ }
212
+ knownZones.add(zone);
213
+ }
214
+ function assertWallTime(time) {
215
+ assertInteger(time.hour, "hour");
216
+ if (time.hour < 0 || time.hour > 23) throw new RangeError("hour must be an integer in 0..23, received " + String(time.hour));
217
+ assertInteger(time.minute, "minute");
218
+ if (time.minute < 0 || time.minute > 59) throw new RangeError("minute must be an integer in 0..59, received " + String(time.minute));
219
+ }
220
+ /**
221
+ * The UTC offset of a zone at an instant, in minutes.
222
+ *
223
+ * Computed by asking Intl for the wall clock and subtracting it from the instant:
224
+ * no offset table, no transition list. The offset is positive east of Greenwich,
225
+ * so Asia/Kolkata returns 330 and America/New_York returns -300 in January.
226
+ *
227
+ * Whole minutes are the norm, but the result is not rounded: historical
228
+ * local-mean-time offsets (before standard time was adopted) include seconds, and
229
+ * a function that silently rounded them would be wrong for a century of dates.
230
+ * Fractions of a second in the instant are ignored, because the wall clock is
231
+ * read to the second.
232
+ *
233
+ * @throws RangeError when the instant is not finite or the zone is unknown.
234
+ */
235
+ function offsetAt(instant, zone) {
236
+ assertInstant(instant);
237
+ assertZone(zone);
238
+ if (zone === "UTC" || zone === "Etc/UTC") return 0;
239
+ const parts = zonedParts(instant, zone);
240
+ return (utcMilliseconds({
241
+ date: {
242
+ year: parts.year,
243
+ month: parts.month,
244
+ day: parts.day
245
+ },
246
+ time: {
247
+ hour: parts.hour,
248
+ minute: parts.minute,
249
+ second: parts.second,
250
+ millisecond: 0
251
+ }
252
+ }) - Math.floor(instant / 1e3) * 1e3) / 6e4;
253
+ }
254
+ /**
255
+ * The wall-clock fields of an instant in a zone.
256
+ *
257
+ * Seconds are reported; milliseconds are not, because a calendar never renders
258
+ * them and CivilTime is the only place this package keeps a millisecond field.
259
+ *
260
+ * @throws RangeError when the instant is not finite or the zone is unknown.
261
+ */
262
+ function zonedParts(instant, zone) {
263
+ assertInstant(instant);
264
+ assertZone(zone);
265
+ const { date, time } = fromDate(new Date(instant), zone);
266
+ return {
267
+ year: date.year,
268
+ month: date.month,
269
+ day: date.day,
270
+ hour: time.hour,
271
+ minute: time.minute,
272
+ second: time.second
273
+ };
274
+ }
275
+ /**
276
+ * The civil date in a zone at an instant.
277
+ *
278
+ * This is the answer to "which day is it there?" - the question a calendar
279
+ * header, a "today" button or a reminder schedule asks, and the one a UTC-only
280
+ * answer gets wrong for half the world for part of every day.
281
+ *
282
+ * @throws RangeError when the instant is not finite or the zone is unknown.
283
+ */
284
+ function civilInZone(instant, zone) {
285
+ assertInstant(instant);
286
+ assertZone(zone);
287
+ const { date } = fromDate(new Date(instant), zone);
288
+ return {
289
+ year: date.year,
290
+ month: date.month,
291
+ day: date.day
292
+ };
293
+ }
294
+ /**
295
+ * The instant a wall clock in a zone names.
296
+ *
297
+ * With no time, this is the start of that civil day in that zone. Both DST
298
+ * disambiguations are the package policy, documented on `toDate` and
299
+ * implemented once there:
300
+ *
301
+ * - a nonexistent wall clock (the skipped hour when the clocks spring forward)
302
+ * maps to the instant the clock jumped to, so 2024-03-10 02:30 in New York is
303
+ * the instant whose local clock reads 03:30;
304
+ * - an ambiguous wall clock (the repeated hour when they fall back) maps to the
305
+ * earlier instant, so 2024-11-03 01:30 in New York is the still-daylight one.
306
+ *
307
+ * @throws RangeError when the civil date or the wall time is invalid, or the
308
+ * zone is unknown.
309
+ */
310
+ function instantFor(civil, zone, time) {
311
+ assertZone(zone);
312
+ const wall = time ?? MIDNIGHT;
313
+ assertWallTime(wall);
314
+ assertValidDate(civil);
315
+ return toDate({
316
+ date: {
317
+ year: civil.year,
318
+ month: civil.month,
319
+ day: civil.day
320
+ },
321
+ time: {
322
+ hour: wall.hour,
323
+ minute: wall.minute,
324
+ second: 0,
325
+ millisecond: 0
326
+ }
327
+ }, zone).getTime();
328
+ }
329
+ /**
330
+ * The first instant of the civil day an instant falls in.
331
+ *
332
+ * Normally local midnight, but a zone can start its day inside a DST gap (Chile
333
+ * and Lebanon have both moved the clocks at 00:00), and then the first instant
334
+ * of the day is the moment the clock jumped to - 01:00 local, not a nonexistent
335
+ * 00:00. That follows from `instantFor`'s gap policy rather than being a
336
+ * special case here.
337
+ *
338
+ * ./arithmetic also exports a startOfDay, for civil dates, so a barrel that re-exports both has to alias one of them.
339
+ *
340
+ * @throws RangeError when the instant is not finite or the zone is unknown.
341
+ */
342
+ function startOfDay(instant, zone) {
343
+ assertInstant(instant);
344
+ assertZone(zone);
345
+ return instantFor(civilInZone(instant, zone), zone);
346
+ }
347
+ /**
348
+ * Hours from the start of the civil day an instant falls in to the start of the
349
+ * next one: 24 normally, 23 when the clocks spring forward, 25 when they fall
350
+ * back.
351
+ *
352
+ * Derived from startOfDay on both days rather than from a DST flag, so a zone
353
+ * that shifts by half an hour reports 23.5 or 24.5 and one that shifts by two
354
+ * hours reports 22 or 26. Anything that hardcoded 23/24/25 would silently
355
+ * misreport those zones; Lord Howe Island is the known half-hour case.
356
+ *
357
+ * @throws RangeError when the instant is not finite or the zone is unknown.
358
+ */
359
+ function dayLength(instant, zone) {
360
+ assertInstant(instant);
361
+ assertZone(zone);
362
+ const today = civilInZone(instant, zone);
363
+ return (instantFor(addDays(today, 1), zone) - instantFor(today, zone)) / 36e5;
364
+ }
365
+ /**
366
+ * Formats an instant in a zone, delegating to Intl.DateTimeFormat.
367
+ *
368
+ * The formatter is built per call on purpose: Intl caches locale data itself, and
369
+ * a caller formatting a column of dates should hold its own formatter (formatDate
370
+ * in ./format is the package's cached path). The `zone` argument wins over an
371
+ * explicit `timeZone` in `options`, so there is exactly one place the zone is
372
+ * decided.
373
+ *
374
+ * `locale` is optional and defaults to the runtime locale, as Intl does; the
375
+ * tests pass it explicitly so they do not depend on the host.
376
+ *
377
+ * @throws RangeError when the instant is not finite or the zone is unknown, and
378
+ * TypeError from Intl for an invalid combination of options (dateStyle plus
379
+ * individual fields, for example) - that is Intl's documented contract.
380
+ */
381
+ const formattersCache = /* @__PURE__ */ new Map();
382
+ function formatInZone(instant, zone, options, locale) {
383
+ assertInstant(instant);
384
+ assertZone(zone);
385
+ const optKey = options === void 0 ? "" : JSON.stringify(options);
386
+ const key = `${locale ?? ""}\0${zone}\0${optKey}`;
387
+ let formatter = formattersCache.get(key);
388
+ if (formatter === void 0) {
389
+ formatter = new Intl.DateTimeFormat(locale, {
390
+ ...options ?? DEFAULT_FORMAT,
391
+ timeZone: zone
392
+ });
393
+ if (formattersCache.size >= 128) formattersCache.delete(formattersCache.keys().next().value);
394
+ formattersCache.set(key, formatter);
395
+ }
396
+ return formatter.format(new Date(instant));
397
+ }
398
+ /**
399
+ * The zone identifiers this runtime knows, from Intl.supportedValuesOf("timeZone").
400
+ *
401
+ * Returns an empty list when the runtime has no supportedValuesOf (older engines
402
+ * and minimal Intl builds), because there is no honest partial answer: guessing a
403
+ * list would make a zone picker offer zones the runtime cannot convert. The list
404
+ * is the runtime's, so it omits aliases and "UTC" even though Intl accepts them;
405
+ * callers that need "UTC" in a picker should add it themselves.
406
+ *
407
+ * Not cached: the runtime's list is small and fixed, while a cache would hide a
408
+ * test or a restricted runtime that removes supportedValuesOf.
409
+ */
410
+ function zoneIds() {
411
+ if (!hasIntl()) return [];
412
+ const supportedValuesOf = Reflect.get(Intl, "supportedValuesOf");
413
+ if (typeof supportedValuesOf !== "function") return [];
414
+ const list = supportedValuesOf.call(Intl, "timeZone");
415
+ return Array.isArray(list) ? list.filter((id) => typeof id === "string") : [];
416
+ }
417
+ export { startOfMonth as C, startOfDay$1 as S, endOfWeek as _, offsetAt as a, max as b, zonedParts as c, addMonths as d, addYears as f, endOfMonth as g, eachDay as h, instantFor as i, MAX_RANGE_DAYS as l, differenceInDays as m, dayLength as n, startOfDay as o, compare as p, formatInZone as r, zoneIds as s, civilInZone as t, addDays as u, isSameDay as v, startOfWeek as w, min as x, isSameMonth as y };