@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,461 @@
1
+ // src/internal.ts
2
+ /** A day in milliseconds. Only the Date boundary and formatting need it. */
3
+ const MS_PER_DAY = 864e5;
4
+ /** Proleptic Gregorian leap rule, valid for negative years too. */
5
+ function isLeapYearNumber(year) {
6
+ return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
7
+ }
8
+ /** Length of a month; the caller has already checked that month is 1..12. */
9
+ function monthLength(year, month) {
10
+ if (month === 2) return isLeapYearNumber(year) ? 29 : 28;
11
+ if (month === 4 || month === 6 || month === 9 || month === 11) return 30;
12
+ return 31;
13
+ }
14
+ /**
15
+ * The guard behind `isValidDate`. It takes `unknown` so a caller can sit on a
16
+ * boundary where the value is not typed yet.
17
+ */
18
+ function isCivilDate(value) {
19
+ if (typeof value !== "object" || value === null) return false;
20
+ const { year, month, day } = value;
21
+ if (typeof year !== "number" || typeof month !== "number" || typeof day !== "number") return false;
22
+ if (!Number.isSafeInteger(year) || !Number.isInteger(month) || !Number.isInteger(day)) return false;
23
+ if (month < 1 || month > 12) return false;
24
+ return day >= 1 && day <= monthLength(year, month);
25
+ }
26
+ /** Shorthand for the common case: the caller already has a CivilDate. */
27
+ function assertValidDate(value) {
28
+ if (!isCivilDate(value)) throw new RangeError(`Invalid civil date: ${describe(value)}`);
29
+ }
30
+ /** A time of day is four integers; leap seconds (60) are deliberately invalid. */
31
+ function isCivilTime(value) {
32
+ if (typeof value !== "object" || value === null) return false;
33
+ const { hour, minute, second, millisecond } = value;
34
+ if (typeof hour !== "number" || typeof minute !== "number" || typeof second !== "number" || typeof millisecond !== "number") return false;
35
+ return Number.isInteger(hour) && hour >= 0 && hour <= 23 && Number.isInteger(minute) && minute >= 0 && minute <= 59 && Number.isInteger(second) && second >= 0 && second <= 59 && Number.isInteger(millisecond) && millisecond >= 0 && millisecond <= 999;
36
+ }
37
+ /** A civil date-time is a valid date plus a valid time; both halves are checked. */
38
+ function isCivilDateTime(value) {
39
+ if (typeof value !== "object" || value === null) return false;
40
+ const candidate = value;
41
+ return isCivilDate(candidate.date) && isCivilTime(candidate.time);
42
+ }
43
+ function assertValidDateTime(value) {
44
+ if (!isCivilDateTime(value)) throw new RangeError(`Invalid civil date-time: ${describe(value)}`);
45
+ }
46
+ /** Integers only. Rounding is not done here: a fractional day is a caller bug. */
47
+ function assertInteger(value, name) {
48
+ if (!Number.isInteger(value)) throw new RangeError(`${name} must be an integer, received ${String(value)}`);
49
+ }
50
+ /** Weekday indexes are 0 (Sunday) through 6 (Saturday). */
51
+ function assertWeekday(value) {
52
+ if (!Number.isInteger(value) || value < 0 || value > 6) throw new RangeError(`weekStartsOn must be 0..6, received ${String(value)}`);
53
+ }
54
+ /** True when this runtime can format dates; the format module degrades without it. */
55
+ function hasIntl() {
56
+ return typeof Intl !== "undefined" && typeof Intl.DateTimeFormat === "function";
57
+ }
58
+ /**
59
+ * Milliseconds since the epoch of a civil date-time read as if it were UTC.
60
+ *
61
+ * Date.UTC maps years 0..99 to 1900..1999, so the fields are applied to an
62
+ * existing epoch date with `setUTCFullYear` instead of being passed to the
63
+ * constructor. This is the primitive both the Intl conversion and the ISO
64
+ * formatter build on.
65
+ */
66
+ function utcMilliseconds(value) {
67
+ const date = /* @__PURE__ */ new Date(0);
68
+ date.setUTCFullYear(value.date.year, value.date.month - 1, value.date.day);
69
+ date.setUTCHours(value.time.hour, value.time.minute, value.time.second, value.time.millisecond);
70
+ return date.getTime();
71
+ }
72
+ /** Left-pads a non-negative integer; ISO formatting uses widths 2, 3 and 4. */
73
+ function pad(value, width) {
74
+ return String(value).padStart(width, "0");
75
+ }
76
+ function describe(value) {
77
+ if (typeof value === "object" && value !== null) try {
78
+ return JSON.stringify(value);
79
+ } catch {
80
+ return Object.prototype.toString.call(value);
81
+ }
82
+ return String(value);
83
+ }
84
+ // src/civil.ts
85
+ const MIDNIGHT = {
86
+ hour: 0,
87
+ minute: 0,
88
+ second: 0,
89
+ millisecond: 0
90
+ };
91
+ /**
92
+ * The number of whole days from 1970-01-01 to `date`; negative before the
93
+ * epoch.
94
+ *
95
+ * Howard Hinnant's `days_from_civil`: shift January/February to the end of the
96
+ * previous year so the leap day is the last day of the shifted year, then count
97
+ * whole 400-year eras (146097 days, an exact cycle of the Gregorian calendar).
98
+ * Using Math.floor instead of C++ integer truncation is what makes it work for
99
+ * negative years; a truncating version drifts by one day before year 0.
100
+ *
101
+ * @throws RangeError when `date` is not a valid civil date.
102
+ */
103
+ function toEpochDay(date) {
104
+ assertValidDate(date);
105
+ let year = date.year;
106
+ const { month, day } = date;
107
+ year -= month <= 2 ? 1 : 0;
108
+ const era = Math.floor(year / 400);
109
+ const yearOfEra = year - era * 400;
110
+ const dayOfYearIndex = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1;
111
+ const dayOfEra = yearOfEra * 365 + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100) + dayOfYearIndex;
112
+ return era * 146097 + dayOfEra - 719468;
113
+ }
114
+ /**
115
+ * The inverse of `toEpochDay`.
116
+ *
117
+ * Hinnant's `civil_from_days`. Correct for every day the civil calendar can
118
+ * name, including pre-1970 and far-future dates that a Date object cannot hold.
119
+ *
120
+ * @throws RangeError when `day` is not a safe integer.
121
+ */
122
+ function fromEpochDay(day) {
123
+ if (!Number.isSafeInteger(day)) throw new RangeError(`Epoch day must be a safe integer, received ${String(day)}`);
124
+ const shifted = day + 719468;
125
+ const era = Math.floor(shifted / 146097);
126
+ const dayOfEra = shifted - era * 146097;
127
+ const yearOfEra = Math.floor((dayOfEra - Math.floor(dayOfEra / 1460) + Math.floor(dayOfEra / 36524) - Math.floor(dayOfEra / 146096)) / 365);
128
+ const year = yearOfEra + era * 400;
129
+ const dayOfYearIndex = dayOfEra - (365 * yearOfEra + Math.floor(yearOfEra / 4) - Math.floor(yearOfEra / 100));
130
+ const monthIndex = Math.floor((5 * dayOfYearIndex + 2) / 153);
131
+ const dayOfMonth = dayOfYearIndex - Math.floor((153 * monthIndex + 2) / 5) + 1;
132
+ const month = monthIndex + (monthIndex < 10 ? 3 : -9);
133
+ return {
134
+ year: year + (month <= 2 ? 1 : 0),
135
+ month,
136
+ day: dayOfMonth
137
+ };
138
+ }
139
+ /**
140
+ * Narrows an unknown value to a CivilDate.
141
+ *
142
+ * The guard is the package boundary: a component reading `<input type="date">`
143
+ * or a JSON payload can validate before handing the value to arithmetic.
144
+ */
145
+ function isValidDate(value) {
146
+ return isCivilDate(value);
147
+ }
148
+ /**
149
+ * Number of days in a month.
150
+ *
151
+ * @throws RangeError when `year` is not an integer or `month` is not 1..12.
152
+ */
153
+ function daysInMonth(year, month) {
154
+ assertInteger(year, "year");
155
+ if (!Number.isInteger(month) || month < 1 || month > 12) throw new RangeError(`month must be an integer in 1..12, received ${String(month)}`);
156
+ return monthLength(year, month);
157
+ }
158
+ /**
159
+ * Proleptic Gregorian leap year.
160
+ *
161
+ * @throws RangeError when `year` is not an integer.
162
+ */
163
+ function isLeapYear(year) {
164
+ assertInteger(year, "year");
165
+ return isLeapYearNumber(year);
166
+ }
167
+ /**
168
+ * Weekday of a date, 0 (Sunday) through 6 (Saturday).
169
+ *
170
+ * 1970-01-01 was a Thursday (4), which is the only anchor this needs; adding
171
+ * `% 7` twice keeps the result non-negative for pre-epoch dates.
172
+ */
173
+ function dayOfWeek(date) {
174
+ return ((toEpochDay(date) + 4) % 7 + 7) % 7;
175
+ }
176
+ /** One-based day of the year: January 1 is 1, December 31 is 365 or 366. */
177
+ function dayOfYear(date) {
178
+ const yearStart = toEpochDay({
179
+ year: date.year,
180
+ month: 1,
181
+ day: 1
182
+ });
183
+ return toEpochDay(date) - yearStart + 1;
184
+ }
185
+ /**
186
+ * Reads the civil date and time of a JavaScript Date.
187
+ *
188
+ * With no `timeZone`, the host local zone is used (what a date picker in that
189
+ * zone means by "today"). With a zone, Intl is asked for the wall clock in that
190
+ * zone, which is DST-correct and needs no offset bookkeeping.
191
+ *
192
+ * @throws RangeError when the Date is invalid, when the timezone is unknown,
193
+ * or when a timezone is requested in a runtime without Intl.
194
+ */
195
+ function fromDate(date, timeZone) {
196
+ if (!(date instanceof Date) || Number.isNaN(date.getTime())) throw new RangeError("fromDate expects a valid Date");
197
+ if (timeZone === void 0) return {
198
+ date: {
199
+ year: date.getFullYear(),
200
+ month: date.getMonth() + 1,
201
+ day: date.getDate()
202
+ },
203
+ time: {
204
+ hour: date.getHours(),
205
+ minute: date.getMinutes(),
206
+ second: date.getSeconds(),
207
+ millisecond: date.getMilliseconds()
208
+ }
209
+ };
210
+ return zonedParts(date, timeZone);
211
+ }
212
+ function toDate(value, timeZone) {
213
+ const civil = "time" in value ? value : {
214
+ date: value,
215
+ time: { ...MIDNIGHT }
216
+ };
217
+ assertValidDateTime(civil);
218
+ const instant = timeZone === void 0 ? localInstant(civil) : zonedInstant(civil, timeZone);
219
+ if (!(instant instanceof Date) || Number.isNaN(instant.getTime())) throw new RangeError(`Civil date-time cannot be represented as a Date: ${String(value)}`);
220
+ return instant;
221
+ }
222
+ /** Local-zone construction; setFullYear avoids the constructor's 0..99 -> 19xx mapping. */
223
+ function localInstant(civil) {
224
+ const instant = /* @__PURE__ */ new Date(0);
225
+ instant.setFullYear(civil.date.year, civil.date.month - 1, civil.date.day);
226
+ instant.setHours(civil.time.hour, civil.time.minute, civil.time.second, civil.time.millisecond);
227
+ return instant;
228
+ }
229
+ const zoneDayOffsets = /* @__PURE__ */ new Map();
230
+ const isUtcZone = (timeZone) => timeZone === "UTC" || timeZone === "Etc/UTC";
231
+ function zonedInstant(civil, timeZone) {
232
+ const target = utcMilliseconds(civil);
233
+ if (isUtcZone(timeZone)) return new Date(target);
234
+ const utcDay = Math.floor(target / MS_PER_DAY);
235
+ const cachedOffset = zoneDayOffsets.get(timeZone)?.get(utcDay);
236
+ if (cachedOffset !== void 0) return new Date(target - cachedOffset);
237
+ const offsets = /* @__PURE__ */ new Set();
238
+ for (const deltaDays of [
239
+ -2,
240
+ 0,
241
+ 2
242
+ ]) offsets.add(offsetAt(target + deltaDays * MS_PER_DAY, timeZone));
243
+ const candidates = [...offsets].map((offset) => target - offset);
244
+ const matching = candidates.filter((candidate) => sameWallClock(zonedParts(new Date(candidate), timeZone), civil));
245
+ const chosen = matching.length > 0 ? Math.min(...matching) : Math.max(...candidates);
246
+ if (offsets.size === 1 && matching.length === 1) {
247
+ const off = target - chosen;
248
+ const dayStart = utcDay * MS_PER_DAY;
249
+ if (offsetAt(dayStart - 1728e5, timeZone) === off && offsetAt(dayStart, timeZone) === off && offsetAt(dayStart + 2592e5, timeZone) === off) {
250
+ let map = zoneDayOffsets.get(timeZone);
251
+ if (!map) zoneDayOffsets.set(timeZone, map = /* @__PURE__ */ new Map());
252
+ else if (map.size >= 128) map.delete(map.keys().next().value);
253
+ map.set(utcDay, off);
254
+ }
255
+ }
256
+ return new Date(chosen);
257
+ }
258
+ /** Milliseconds the zone is ahead of UTC at that instant. */
259
+ function offsetAt(instant, timeZone) {
260
+ const parts = zonedParts(new Date(instant), timeZone);
261
+ return utcMilliseconds({
262
+ date: parts.date,
263
+ time: {
264
+ ...parts.time,
265
+ millisecond: 0
266
+ }
267
+ }) - Math.floor(instant / 1e3) * 1e3;
268
+ }
269
+ function sameWallClock(a, b) {
270
+ return a.date.year === b.date.year && a.date.month === b.date.month && a.date.day === b.date.day && a.time.hour === b.time.hour && a.time.minute === b.time.minute && a.time.second === b.time.second && a.time.millisecond === b.time.millisecond;
271
+ }
272
+ /**
273
+ * The formatter is cached per zone because formatToParts is the only DST-correct
274
+ * way to read a wall clock, and constructing the formatter is the expensive part
275
+ * of that call. The locale is pinned to Gregorian/Latin digits so the parsed
276
+ * values are numbers regardless of the host locale.
277
+ */
278
+ const zoneFormatters = /* @__PURE__ */ new Map();
279
+ function zoneFormatter(timeZone) {
280
+ const cached = zoneFormatters.get(timeZone);
281
+ if (cached !== void 0) return cached;
282
+ const formatter = new Intl.DateTimeFormat("en-US-u-ca-gregory-nu-latn", {
283
+ timeZone,
284
+ year: "numeric",
285
+ month: "2-digit",
286
+ day: "2-digit",
287
+ hour: "2-digit",
288
+ minute: "2-digit",
289
+ second: "2-digit",
290
+ hourCycle: "h23",
291
+ era: "short"
292
+ });
293
+ zoneFormatters.set(timeZone, formatter);
294
+ return formatter;
295
+ }
296
+ /** The wall clock in a zone, as civil parts. */
297
+ function zonedParts(date, timeZone) {
298
+ if (!hasIntl()) throw new RangeError("Time zone conversion requires Intl.DateTimeFormat");
299
+ if (isUtcZone(timeZone)) return {
300
+ date: {
301
+ year: date.getUTCFullYear(),
302
+ month: date.getUTCMonth() + 1,
303
+ day: date.getUTCDate()
304
+ },
305
+ time: {
306
+ hour: date.getUTCHours(),
307
+ minute: date.getUTCMinutes(),
308
+ second: date.getUTCSeconds(),
309
+ millisecond: date.getUTCMilliseconds()
310
+ }
311
+ };
312
+ const parts = zoneFormatter(timeZone).formatToParts(date);
313
+ let year = 0;
314
+ let month = 0;
315
+ let day = 0;
316
+ let hour = 0;
317
+ let minute = 0;
318
+ let second = 0;
319
+ let isBc = false;
320
+ let seenMask = 0;
321
+ for (let i = 0; i < parts.length; i += 1) {
322
+ const part = parts[i];
323
+ switch (part.type) {
324
+ case "year":
325
+ year = Number(part.value);
326
+ seenMask |= 1;
327
+ break;
328
+ case "month":
329
+ month = Number(part.value);
330
+ seenMask |= 2;
331
+ break;
332
+ case "day":
333
+ day = Number(part.value);
334
+ seenMask |= 4;
335
+ break;
336
+ case "hour":
337
+ hour = Number(part.value);
338
+ seenMask |= 8;
339
+ break;
340
+ case "minute":
341
+ minute = Number(part.value);
342
+ seenMask |= 16;
343
+ break;
344
+ case "second":
345
+ second = Number(part.value);
346
+ seenMask |= 32;
347
+ break;
348
+ case "era": isBc = part.value.startsWith("B");
349
+ }
350
+ }
351
+ if (seenMask !== 63) throw new RangeError(`Intl did not report the parts of a date in ${timeZone}`);
352
+ return {
353
+ date: {
354
+ year: isBc ? 1 - year : year,
355
+ month,
356
+ day
357
+ },
358
+ time: {
359
+ hour,
360
+ minute,
361
+ second,
362
+ millisecond: date.getMilliseconds()
363
+ }
364
+ };
365
+ }
366
+ Object.defineProperty(exports, "assertInteger", {
367
+ enumerable: true,
368
+ get: function() {
369
+ return assertInteger;
370
+ }
371
+ });
372
+ Object.defineProperty(exports, "assertValidDate", {
373
+ enumerable: true,
374
+ get: function() {
375
+ return assertValidDate;
376
+ }
377
+ });
378
+ Object.defineProperty(exports, "assertValidDateTime", {
379
+ enumerable: true,
380
+ get: function() {
381
+ return assertValidDateTime;
382
+ }
383
+ });
384
+ Object.defineProperty(exports, "assertWeekday", {
385
+ enumerable: true,
386
+ get: function() {
387
+ return assertWeekday;
388
+ }
389
+ });
390
+ Object.defineProperty(exports, "dayOfWeek", {
391
+ enumerable: true,
392
+ get: function() {
393
+ return dayOfWeek;
394
+ }
395
+ });
396
+ Object.defineProperty(exports, "dayOfYear", {
397
+ enumerable: true,
398
+ get: function() {
399
+ return dayOfYear;
400
+ }
401
+ });
402
+ Object.defineProperty(exports, "daysInMonth", {
403
+ enumerable: true,
404
+ get: function() {
405
+ return daysInMonth;
406
+ }
407
+ });
408
+ Object.defineProperty(exports, "fromDate", {
409
+ enumerable: true,
410
+ get: function() {
411
+ return fromDate;
412
+ }
413
+ });
414
+ Object.defineProperty(exports, "fromEpochDay", {
415
+ enumerable: true,
416
+ get: function() {
417
+ return fromEpochDay;
418
+ }
419
+ });
420
+ Object.defineProperty(exports, "hasIntl", {
421
+ enumerable: true,
422
+ get: function() {
423
+ return hasIntl;
424
+ }
425
+ });
426
+ Object.defineProperty(exports, "isLeapYear", {
427
+ enumerable: true,
428
+ get: function() {
429
+ return isLeapYear;
430
+ }
431
+ });
432
+ Object.defineProperty(exports, "isValidDate", {
433
+ enumerable: true,
434
+ get: function() {
435
+ return isValidDate;
436
+ }
437
+ });
438
+ Object.defineProperty(exports, "pad", {
439
+ enumerable: true,
440
+ get: function() {
441
+ return pad;
442
+ }
443
+ });
444
+ Object.defineProperty(exports, "toDate", {
445
+ enumerable: true,
446
+ get: function() {
447
+ return toDate;
448
+ }
449
+ });
450
+ Object.defineProperty(exports, "toEpochDay", {
451
+ enumerable: true,
452
+ get: function() {
453
+ return toEpochDay;
454
+ }
455
+ });
456
+ Object.defineProperty(exports, "utcMilliseconds", {
457
+ enumerable: true,
458
+ get: function() {
459
+ return utcMilliseconds;
460
+ }
461
+ });