neramjs 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.
package/dist/neram.js ADDED
@@ -0,0 +1,910 @@
1
+ var _a;
2
+ import { daysInMonth, dayOfYear, isLeapYear, weekOfYear, weeksInYear } from './calendar.js';
3
+ import { Duration, duration, isDuration } from './duration.js';
4
+ import { formatDate } from './format.js';
5
+ import { clean, intlSettings } from './intl.js';
6
+ import { canonicalLocale, localeData, publicLocaleData } from './locale.js';
7
+ import { parseFormat, parseString } from './parse.js';
8
+ import { formatRelative, pickUnit } from './relative.js';
9
+ import { FIXED_MS, MS_DAY, MS_WEEK, normalizeUnit } from './units.js';
10
+ import { formatOffset, guessZone, isFixedZone, normalizeZone, offsetAt, wallFromEpoch, wallToEpoch, wallToUtcMs, } from './zone.js';
11
+ const config = { locale: 'en', zone: 'local', normalizeSpaces: true };
12
+ const intlCache = new Map();
13
+ // ---------------------------------------------------------------------------
14
+ // Neram
15
+ // ---------------------------------------------------------------------------
16
+ export class Neram {
17
+ #ms;
18
+ #zone;
19
+ #locale;
20
+ #weekStart;
21
+ #wallCache;
22
+ #offCache;
23
+ /** @internal Use `neram()` instead. */
24
+ constructor(ms, zone, locale, weekStart) {
25
+ this.#ms = Number.isFinite(ms) && Math.abs(ms) <= 8.64e15 ? ms : NaN;
26
+ this.#zone = zone;
27
+ this.#locale = locale;
28
+ this.#weekStart = weekStart;
29
+ }
30
+ #make(ms, zone = this.#zone, locale = this.#locale, weekStart = this.#weekStart) {
31
+ return new _a(ms, zone, locale, weekStart);
32
+ }
33
+ #offset() {
34
+ return (this.#offCache ??= this.isValid() ? offsetAt(this.#ms, this.#zone) : NaN);
35
+ }
36
+ #wall() {
37
+ if (!this.#wallCache) {
38
+ this.#wallCache = this.isValid()
39
+ ? wallFromEpoch(this.#ms, this.#offset())
40
+ : { y: NaN, M: NaN, D: NaN, h: NaN, m: NaN, s: NaN, ms: NaN, dow: NaN };
41
+ }
42
+ return this.#wallCache;
43
+ }
44
+ #fromWall(w) {
45
+ return this.#make(wallToEpoch(w, this.#zone));
46
+ }
47
+ #weekStartDay() {
48
+ return this.#weekStart ?? config.weekStart ?? localeData(this.#locale).week.firstDay;
49
+ }
50
+ #addMonths(n) {
51
+ const w = this.#wall();
52
+ const total = w.y * 12 + w.M + roundCalendar(n);
53
+ const y = Math.floor(total / 12);
54
+ const M = total - y * 12;
55
+ return this.#fromWall({ ...w, y, M, D: Math.min(w.D, daysInMonth(y, M)) });
56
+ }
57
+ #addDays(n) {
58
+ const w = this.#wall();
59
+ return this.#fromWall({ ...w, D: w.D + roundCalendar(n) });
60
+ }
61
+ #intl(opts, locale = this.#locale) {
62
+ if (!this.isValid())
63
+ return 'Invalid Date';
64
+ const fixed = isFixedZone(this.#zone);
65
+ const timeZone = this.#zone === 'local' ? undefined : fixed ? 'UTC' : this.#zone;
66
+ const key = `${locale}|${timeZone}|${JSON.stringify(opts)}`;
67
+ let f = intlCache.get(key);
68
+ if (!f) {
69
+ f = new Intl.DateTimeFormat(locale, { ...opts, timeZone });
70
+ intlCache.set(key, f);
71
+ }
72
+ const out = clean(f.format(fixed ? this.#ms + this.#offset() * 60000 : this.#ms));
73
+ return fixed && opts.timeZoneName ? out.replace(/UTC|GMT/, `GMT${formatOffset(this.#offset())}`) : out;
74
+ }
75
+ // -- validity & identity ---------------------------------------------------
76
+ isValid() {
77
+ return !Number.isNaN(this.#ms);
78
+ }
79
+ clone() {
80
+ return this;
81
+ }
82
+ // -- getters / setters -----------------------------------------------------
83
+ get(unit) {
84
+ const w = this.#wall();
85
+ switch (normalizeUnit(unit)) {
86
+ case 'year': return w.y;
87
+ case 'quarter': return Math.floor(w.M / 3) + 1;
88
+ case 'month': return w.M;
89
+ case 'week': return this.week();
90
+ case 'isoWeek': return this.isoWeek();
91
+ case 'date': return w.D;
92
+ case 'day': return w.dow;
93
+ case 'hour': return w.h;
94
+ case 'minute': return w.m;
95
+ case 'second': return w.s;
96
+ default: return w.ms;
97
+ }
98
+ }
99
+ set(unitOrValues, value) {
100
+ if (!this.isValid())
101
+ return this;
102
+ if (typeof unitOrValues === 'object') {
103
+ let r = this;
104
+ const order = ['year', 'month', 'date', 'day', 'hour', 'minute', 'second', 'millisecond'];
105
+ for (const k of order) {
106
+ const v = unitOrValues[k];
107
+ if (v !== undefined)
108
+ r = r.set(k, v);
109
+ }
110
+ return r;
111
+ }
112
+ const v = value;
113
+ const w = { ...this.#wall() };
114
+ switch (normalizeUnit(unitOrValues)) {
115
+ case 'year':
116
+ return this.#fromWall({ ...w, y: v, D: Math.min(w.D, daysInMonth(v, w.M)) });
117
+ case 'quarter':
118
+ return this.#addMonths((v - (Math.floor(w.M / 3) + 1)) * 3);
119
+ case 'month': {
120
+ const y = w.y + Math.floor(v / 12);
121
+ const M = ((v % 12) + 12) % 12;
122
+ return this.#fromWall({ ...w, y, M, D: Math.min(w.D, daysInMonth(y, M)) });
123
+ }
124
+ case 'week': return this.#addDays((v - this.week()) * 7);
125
+ case 'isoWeek': return this.#addDays((v - this.isoWeek()) * 7);
126
+ case 'date': return this.#fromWall({ ...w, D: v });
127
+ case 'day': return this.#addDays(v - w.dow);
128
+ case 'hour': return this.#fromWall({ ...w, h: v });
129
+ case 'minute': return this.#fromWall({ ...w, m: v });
130
+ case 'second': return this.#fromWall({ ...w, s: v });
131
+ default: return this.#fromWall({ ...w, ms: v });
132
+ }
133
+ }
134
+ year(v) { return v === undefined ? this.get('year') : this.set('year', v); }
135
+ month(v) { return v === undefined ? this.get('month') : this.set('month', v); }
136
+ date(v) { return v === undefined ? this.get('date') : this.set('date', v); }
137
+ day(v) { return v === undefined ? this.get('day') : this.set('day', v); }
138
+ hour(v) { return v === undefined ? this.get('hour') : this.set('hour', v); }
139
+ minute(v) { return v === undefined ? this.get('minute') : this.set('minute', v); }
140
+ second(v) { return v === undefined ? this.get('second') : this.set('second', v); }
141
+ millisecond(v) { return v === undefined ? this.get('millisecond') : this.set('millisecond', v); }
142
+ quarter(v) { return v === undefined ? this.get('quarter') : this.set('quarter', v); }
143
+ dayOfYear(v) {
144
+ const w = this.#wall();
145
+ const doy = dayOfYear(w.y, w.M, w.D);
146
+ return v === undefined ? doy : this.#addDays(v - doy);
147
+ }
148
+ isoWeekday(v) {
149
+ const iso = this.#wall().dow || 7;
150
+ return v === undefined ? iso : this.#addDays(v - iso);
151
+ }
152
+ weekday(v) {
153
+ const wd = (this.#wall().dow - this.#weekStartDay() + 7) % 7;
154
+ return v === undefined ? wd : this.#addDays(v - wd);
155
+ }
156
+ /** Locale week of the year (uses the locale's first day and minimal-days rule). */
157
+ week() {
158
+ const w = this.#wall();
159
+ return weekOfYear(w.y, w.M, w.D, this.#weekStartDay(), localeData(this.#locale).week.minimalDays).week;
160
+ }
161
+ weekYear() {
162
+ const w = this.#wall();
163
+ return weekOfYear(w.y, w.M, w.D, this.#weekStartDay(), localeData(this.#locale).week.minimalDays).year;
164
+ }
165
+ /** ISO 8601 week number, 1-53. */
166
+ isoWeek() {
167
+ const w = this.#wall();
168
+ return weekOfYear(w.y, w.M, w.D, 1, 4).week;
169
+ }
170
+ isoWeekYear() {
171
+ const w = this.#wall();
172
+ return weekOfYear(w.y, w.M, w.D, 1, 4).year;
173
+ }
174
+ isoWeeksInYear() {
175
+ return weeksInYear(this.year(), 1, 4);
176
+ }
177
+ daysInMonth() {
178
+ const w = this.#wall();
179
+ return daysInMonth(w.y, w.M);
180
+ }
181
+ isLeapYear() {
182
+ return isLeapYear(this.year());
183
+ }
184
+ add(amount, unit) {
185
+ if (!this.isValid())
186
+ return this;
187
+ if (typeof amount !== 'number') {
188
+ const dur = isDuration(amount) ? amount : duration(amount);
189
+ if (!dur.isValid())
190
+ return this.#make(NaN);
191
+ const o = dur.toObject();
192
+ let r = this;
193
+ if (o.years || o.months)
194
+ r = r.#addMonths(o.years * 12 + o.months);
195
+ if (o.weeks || o.days)
196
+ r = r.#addDays(o.weeks * 7 + o.days);
197
+ const exact = o.hours * 3600000 + o.minutes * 60000 + o.seconds * 1000 + o.milliseconds;
198
+ return exact ? r.#make(r.#ms + exact) : r;
199
+ }
200
+ const u = normalizeUnit(unit ?? 'millisecond');
201
+ switch (u) {
202
+ case 'year': return this.#addMonths(amount * 12);
203
+ case 'quarter': return this.#addMonths(amount * 3);
204
+ case 'month': return this.#addMonths(amount);
205
+ case 'week':
206
+ case 'isoWeek': return this.#addDays(amount * 7);
207
+ case 'day':
208
+ case 'date': return this.#addDays(amount);
209
+ default: return this.#make(this.#ms + amount * (FIXED_MS[u] ?? 1));
210
+ }
211
+ }
212
+ subtract(amount, unit) {
213
+ if (typeof amount === 'number')
214
+ return this.add(-amount, unit);
215
+ return this.add((isDuration(amount) ? amount : duration(amount)).negate());
216
+ }
217
+ startOf(unit) {
218
+ if (!this.isValid())
219
+ return this;
220
+ const u = normalizeUnit(unit);
221
+ const w = { ...this.#wall() };
222
+ const midnight = { h: 0, m: 0, s: 0, ms: 0 };
223
+ switch (u) {
224
+ case 'year': return this.#fromWall({ ...w, ...midnight, M: 0, D: 1 });
225
+ case 'quarter': return this.#fromWall({ ...w, ...midnight, M: Math.floor(w.M / 3) * 3, D: 1 });
226
+ case 'month': return this.#fromWall({ ...w, ...midnight, D: 1 });
227
+ case 'week': return this.#fromWall({ ...w, ...midnight, D: w.D - ((w.dow - this.#weekStartDay() + 7) % 7) });
228
+ case 'isoWeek': return this.#fromWall({ ...w, ...midnight, D: w.D - ((w.dow + 6) % 7) });
229
+ case 'day':
230
+ case 'date': return this.#fromWall({ ...w, ...midnight });
231
+ // Sub-day units: trim elapsed time so repeated DST hours stay on the right side.
232
+ case 'hour': return this.#make(this.#ms - (w.m * 60000 + w.s * 1000 + w.ms));
233
+ case 'minute': return this.#make(this.#ms - (w.s * 1000 + w.ms));
234
+ case 'second': return this.#make(this.#ms - w.ms);
235
+ default: return this;
236
+ }
237
+ }
238
+ endOf(unit) {
239
+ const u = normalizeUnit(unit);
240
+ if (u === 'millisecond')
241
+ return this;
242
+ return this.startOf(u).add(1, u === 'date' ? 'day' : u).subtract(1, 'millisecond');
243
+ }
244
+ /** Round to the nearest unit boundary: neram('10:40').round('hour') → 11:00. */
245
+ round(unit) {
246
+ if (!this.isValid())
247
+ return this;
248
+ const u = normalizeUnit(unit);
249
+ const start = this.startOf(u);
250
+ const next = start.add(1, u === 'date' ? 'day' : u);
251
+ return this.#ms - start.#ms < next.#ms - this.#ms ? start : next;
252
+ }
253
+ /** Keep the date inside [min, max]. */
254
+ clamp(min, max) {
255
+ const lo = this.#coerce(min);
256
+ const hi = this.#coerce(max);
257
+ if (this.#ms < lo.#ms)
258
+ return lo.tz(this.#zone);
259
+ if (this.#ms > hi.#ms)
260
+ return hi.tz(this.#zone);
261
+ return this;
262
+ }
263
+ // -- zones -----------------------------------------------------------------
264
+ /**
265
+ * The same instant in another zone, or (keepLocalTime) the same wall time in another zone.
266
+ * neram('2026-12-04T09:00Z').tz('Asia/Kolkata').format('HH:mm') → "14:30"
267
+ */
268
+ tz(zone, keepLocalTime = false) {
269
+ const z = normalizeZone(zone);
270
+ if (!this.isValid())
271
+ return this.#make(NaN, z);
272
+ if (keepLocalTime)
273
+ return this.#make(wallToEpoch(this.#wall(), z), z);
274
+ return this.#make(this.#ms, z);
275
+ }
276
+ utc(keepLocalTime = false) {
277
+ return this.tz('UTC', keepLocalTime);
278
+ }
279
+ local(keepLocalTime = false) {
280
+ return this.tz('local', keepLocalTime);
281
+ }
282
+ /** The IANA name (or "UTC" / "+05:30") of this instance's zone. */
283
+ timezone() {
284
+ return this.#zone === 'local' ? guessZone() : this.#zone;
285
+ }
286
+ isUTC() {
287
+ return this.#zone === 'UTC';
288
+ }
289
+ isLocal() {
290
+ return this.#zone === 'local';
291
+ }
292
+ utcOffset(offset, keepLocalTime = false) {
293
+ if (offset === undefined)
294
+ return this.#offset();
295
+ let mins;
296
+ if (typeof offset === 'string') {
297
+ mins = normalizeZone(offset) === 'UTC' ? 0 : Number.NaN;
298
+ const m = /^([+-])(\d{2}):?(\d{2})$/.exec(offset);
299
+ if (m)
300
+ mins = (m[1] === '-' ? -1 : 1) * (Number(m[2]) * 60 + Number(m[3]));
301
+ }
302
+ else {
303
+ mins = Math.abs(offset) < 16 ? offset * 60 : offset;
304
+ }
305
+ if (Number.isNaN(mins))
306
+ throw new RangeError(`neram: invalid offset "${offset}"`);
307
+ return this.tz(mins === 0 ? 'UTC' : formatOffset(mins), keepLocalTime);
308
+ }
309
+ /** True when daylight-saving time is in effect in this instance's zone. */
310
+ isDST() {
311
+ if (!this.isValid())
312
+ return false;
313
+ const y = this.year();
314
+ const jan = offsetAt(Date.UTC(y, 0, 1), this.#zone);
315
+ const jul = offsetAt(Date.UTC(y, 6, 1), this.#zone);
316
+ return jan !== jul && this.#offset() === Math.max(jan, jul);
317
+ }
318
+ // -- locale ----------------------------------------------------------------
319
+ /** Month and weekday names and week rules for this value's locale. Day.js-compatible. */
320
+ localeData() {
321
+ return publicLocaleData(this.#locale);
322
+ }
323
+ locale(locale) {
324
+ if (locale === undefined)
325
+ return this.#locale;
326
+ return this.#make(this.#ms, this.#zone, canonicalLocale(locale));
327
+ }
328
+ weekStart(day) {
329
+ if (day === undefined)
330
+ return this.#weekStartDay();
331
+ return this.#make(this.#ms, this.#zone, this.#locale, day);
332
+ }
333
+ // -- display ---------------------------------------------------------------
334
+ /**
335
+ * Format with Day.js tokens, plus:
336
+ * W/WW ISO week · GGGG ISO week-year · E ISO weekday · Qo ordinal quarter
337
+ * z/zzz zone name · S…SSSSSSSSS fraction · L LL LLL LLLL LT LTS (via Intl)
338
+ */
339
+ format(fmt = 'YYYY-MM-DDTHH:mm:ssZ') {
340
+ if (!this.isValid())
341
+ return 'Invalid Date';
342
+ return formatDate({
343
+ wall: this.#wall(),
344
+ ms: this.#ms,
345
+ offset: this.#offset(),
346
+ locale: this.#locale,
347
+ weekStart: this.#weekStartDay(),
348
+ intl: (o) => this.#intl(o),
349
+ }, fmt);
350
+ }
351
+ /** Format with Intl options: neram().toLocaleString({ dateStyle: 'full' }, 'ta') */
352
+ toLocaleString(opts = { dateStyle: 'medium', timeStyle: 'medium' }, locale) {
353
+ return this.#intl(opts, locale ? canonicalLocale(locale) : this.#locale);
354
+ }
355
+ /** "in 3 hours", "yesterday", "2 months ago" — relative to another date. */
356
+ from(other, opts = {}) {
357
+ if (!this.isValid())
358
+ return 'Invalid Date';
359
+ const that = this.#coerce(other);
360
+ if (!that.isValid())
361
+ return 'Invalid Date';
362
+ const ms = this.#ms - that.#ms;
363
+ const { value, unit } = pickUnit(ms, this.diff(that, 'month', true));
364
+ return formatRelative(value, unit, opts.locale ?? this.#locale, opts);
365
+ }
366
+ fromNow(opts = {}) {
367
+ return this.from(this.#make(Date.now()), opts);
368
+ }
369
+ to(other, opts = {}) {
370
+ if (!this.isValid())
371
+ return 'Invalid Date';
372
+ return this.#coerce(other).locale(this.#locale).from(this, opts);
373
+ }
374
+ toNow(opts = {}) {
375
+ return this.to(this.#make(Date.now()), opts);
376
+ }
377
+ /** "Today at 3:00 PM", "Tomorrow at 9:00 AM", "Last Friday at …", or a date. */
378
+ calendar(reference, opts = {}) {
379
+ if (!this.isValid())
380
+ return 'Invalid Date';
381
+ const ref = (reference === undefined ? this.#make(Date.now()) : this.#coerce(reference)).tz(this.#zone);
382
+ const days = this.startOf('day').diff(ref.startOf('day'), 'day');
383
+ const en = this.#locale.toLowerCase().startsWith('en');
384
+ const at = en ? ' at ' : ' ';
385
+ const time = this.format('LT');
386
+ const cap = (s) => s.charAt(0).toLocaleUpperCase(this.#locale) + s.slice(1);
387
+ if (Math.abs(days) <= 1)
388
+ return cap(formatRelative(days, 'day', this.#locale)) + at + time;
389
+ const wd = localeData(this.#locale).weekdays[this.day()];
390
+ if (days > 1 && days < 7)
391
+ return cap(wd) + at + time;
392
+ if (days < -1 && days > -7)
393
+ return (en ? `Last ${wd}` : cap(wd)) + at + time;
394
+ return this.format(opts.sameElse ?? 'L');
395
+ }
396
+ // -- comparison ------------------------------------------------------------
397
+ #coerce(input) {
398
+ return input instanceof _a ? input : neram(input, { zone: this.#zone, locale: this.#locale });
399
+ }
400
+ /**
401
+ * Difference in a unit, truncated toward zero unless `float`.
402
+ * Months and years are calendar-aware; days and weeks count local calendar days (DST-safe).
403
+ */
404
+ diff(other, unit = 'millisecond', float = false) {
405
+ const that = this.#coerce(other);
406
+ if (!this.isValid() || !that.isValid())
407
+ return NaN;
408
+ const u = normalizeUnit(unit);
409
+ const wallDelta = this.#ms + this.#offset() * 60000 - (that.#ms + that.#offset() * 60000);
410
+ let r;
411
+ switch (u) {
412
+ case 'year':
413
+ r = monthDiff(this, that) / 12;
414
+ break;
415
+ case 'quarter':
416
+ r = monthDiff(this, that) / 3;
417
+ break;
418
+ case 'month':
419
+ r = monthDiff(this, that);
420
+ break;
421
+ case 'week':
422
+ case 'isoWeek':
423
+ r = wallDelta / MS_WEEK;
424
+ break;
425
+ case 'day':
426
+ case 'date':
427
+ r = wallDelta / MS_DAY;
428
+ break;
429
+ default: r = (this.#ms - that.#ms) / (FIXED_MS[u] ?? 1);
430
+ }
431
+ return float ? r : Math.trunc(r) || 0;
432
+ }
433
+ /** Whole Duration between two dates, calendar-correct: 1 year 2 months 3 days … */
434
+ durationTo(other) {
435
+ const that = this.#coerce(other);
436
+ if (!this.isValid() || !that.isValid())
437
+ return duration(NaN);
438
+ const sign = that.#ms < this.#ms ? -1 : 1;
439
+ let [a, b] = sign > 0 ? [this, that] : [that, this];
440
+ const months = Math.trunc(monthDiff(b, a));
441
+ a = a.add(months, 'month');
442
+ const days = Math.trunc(b.diff(a, 'day'));
443
+ a = a.add(days, 'day');
444
+ const rest = b.#ms - a.#ms;
445
+ return duration({ months: sign * months, days: sign * days, milliseconds: sign * rest }).normalize();
446
+ }
447
+ isBefore(other, unit) {
448
+ const that = this.#coerce(other);
449
+ return unit ? this.endOf(unit).#ms < that.#ms : this.#ms < that.#ms;
450
+ }
451
+ isAfter(other, unit) {
452
+ const that = this.#coerce(other);
453
+ return unit ? this.startOf(unit).#ms > that.#ms : this.#ms > that.#ms;
454
+ }
455
+ isSame(other, unit) {
456
+ const that = this.#coerce(other);
457
+ if (!unit)
458
+ return this.#ms === that.#ms;
459
+ return this.startOf(unit).#ms <= that.#ms && that.#ms <= this.endOf(unit).#ms;
460
+ }
461
+ isSameOrBefore(other, unit) {
462
+ return this.isSame(other, unit) || this.isBefore(other, unit);
463
+ }
464
+ isSameOrAfter(other, unit) {
465
+ return this.isSame(other, unit) || this.isAfter(other, unit);
466
+ }
467
+ isBetween(a, b, unit, inclusivity = '()') {
468
+ const [lo, hi] = [this.#coerce(a), this.#coerce(b)].sort((x, y) => x.#ms - y.#ms);
469
+ const left = inclusivity[0] === '[' ? this.isSameOrAfter(lo, unit) : this.isAfter(lo, unit);
470
+ const right = inclusivity[1] === ']' ? this.isSameOrBefore(hi, unit) : this.isBefore(hi, unit);
471
+ return left && right;
472
+ }
473
+ isToday() {
474
+ return this.isSame(this.#make(Date.now()), 'day');
475
+ }
476
+ isTomorrow() {
477
+ return this.isSame(this.#make(Date.now()).add(1, 'day'), 'day');
478
+ }
479
+ isYesterday() {
480
+ return this.isSame(this.#make(Date.now()).subtract(1, 'day'), 'day');
481
+ }
482
+ isPast() {
483
+ return this.#ms < Date.now();
484
+ }
485
+ isFuture() {
486
+ return this.#ms > Date.now();
487
+ }
488
+ // -- business days ---------------------------------------------------------
489
+ isWeekend(weekend) {
490
+ return (weekend === undefined ? localeData(this.#locale).week.weekend : checkWeekend(weekend)).includes(this.day());
491
+ }
492
+ isBusinessDay(opts = {}) {
493
+ if (this.isWeekend(opts.weekend))
494
+ return false;
495
+ if (!opts.holidays?.length)
496
+ return true;
497
+ return !this.#holidaySet(opts).has(this.format('YYYY-MM-DD'));
498
+ }
499
+ /** Step over weekends and holidays. Negative n goes backwards. */
500
+ addBusinessDays(n, opts = {}) {
501
+ if (!Number.isInteger(n))
502
+ throw new RangeError(`neram: business days must be a whole number, got ${n}`);
503
+ if (opts.weekend !== undefined)
504
+ checkWeekend(opts.weekend);
505
+ const set = this.#holidaySet(opts);
506
+ if (!this.isValid())
507
+ return this;
508
+ const step = n < 0 ? -1 : 1;
509
+ let left = Math.abs(n);
510
+ let r = this;
511
+ while (left > 0) {
512
+ r = r.#addDays(step);
513
+ if (!r.isWeekend(opts.weekend) && !set.has(r.format('YYYY-MM-DD')))
514
+ left--;
515
+ }
516
+ return r;
517
+ }
518
+ subtractBusinessDays(n, opts = {}) {
519
+ return this.addBusinessDays(-n, opts);
520
+ }
521
+ /** Business days from this date (exclusive) to `other` (inclusive); negative if earlier. */
522
+ businessDaysUntil(other, opts = {}) {
523
+ if (opts.weekend !== undefined)
524
+ checkWeekend(opts.weekend);
525
+ const target = this.#coerce(other);
526
+ if (!this.isValid() || !target.isValid())
527
+ return NaN;
528
+ const that = target.tz(this.#zone).startOf('day');
529
+ let cur = this.startOf('day');
530
+ const step = that.#ms < cur.#ms ? -1 : 1;
531
+ const set = this.#holidaySet(opts);
532
+ let count = 0;
533
+ while (step > 0 ? cur.#ms < that.#ms : cur.#ms > that.#ms) {
534
+ cur = cur.#addDays(step);
535
+ if (!cur.isWeekend(opts.weekend) && !set.has(cur.format('YYYY-MM-DD')))
536
+ count += step;
537
+ }
538
+ return count;
539
+ }
540
+ #holidaySet(opts) {
541
+ return new Set((opts.holidays ?? []).map((h) => {
542
+ const d = this.#coerce(h);
543
+ if (!d.isValid())
544
+ throw new RangeError(`neram: invalid holiday ${JSON.stringify(h)}`);
545
+ return d.tz(this.#zone).format('YYYY-MM-DD');
546
+ }));
547
+ }
548
+ // -- conversion ------------------------------------------------------------
549
+ valueOf() {
550
+ return this.#ms;
551
+ }
552
+ /** Seconds since the epoch. */
553
+ unix() {
554
+ return Math.floor(this.#ms / 1000);
555
+ }
556
+ toDate() {
557
+ return new Date(this.#ms);
558
+ }
559
+ toISOString() {
560
+ return new Date(this.#ms).toISOString();
561
+ }
562
+ /**
563
+ * RFC 9557 / Temporal string with the zone kept:
564
+ * "2026-12-04T14:30:00+05:30[Asia/Kolkata]"
565
+ */
566
+ toZonedISOString() {
567
+ if (!this.isValid())
568
+ return 'Invalid Date';
569
+ const frac = this.#wall().ms ? '.SSS' : '';
570
+ return `${this.format(`YYYY-MM-DDTHH:mm:ss${frac}Z`)}[${this.timezone()}]`;
571
+ }
572
+ /** A Temporal.ZonedDateTime, where the runtime has Temporal. */
573
+ toTemporal() {
574
+ const T = globalThis.Temporal;
575
+ if (!T)
576
+ throw new Error('neram: Temporal is not available in this runtime');
577
+ return T.ZonedDateTime.from(this.toZonedISOString());
578
+ }
579
+ toJSON() {
580
+ return this.isValid() ? this.toISOString() : null;
581
+ }
582
+ toString() {
583
+ return this.isValid() ? new Date(this.#ms).toUTCString() : 'Invalid Date';
584
+ }
585
+ toObject() {
586
+ const w = this.#wall();
587
+ return { year: w.y, month: w.M, date: w.D, hour: w.h, minute: w.m, second: w.s, millisecond: w.ms };
588
+ }
589
+ toArray() {
590
+ const w = this.#wall();
591
+ return [w.y, w.M, w.D, w.h, w.m, w.s, w.ms];
592
+ }
593
+ [Symbol.toPrimitive](hint) {
594
+ return hint === 'number' ? this.#ms : this.toString();
595
+ }
596
+ get [Symbol.toStringTag]() {
597
+ return 'Neram';
598
+ }
599
+ }
600
+ _a = Neram;
601
+ function monthDiff(a, b) {
602
+ // Day.js algorithm: whole months, then the fraction of the month in progress.
603
+ if (a.date() < b.date())
604
+ return -monthDiff(b, a);
605
+ const whole = (b.year() - a.year()) * 12 + (b.month() - a.month());
606
+ const anchor = a.add(whole, 'month').valueOf();
607
+ const behind = b.valueOf() - anchor < 0;
608
+ const anchor2 = a.add(whole + (behind ? -1 : 1), 'month').valueOf();
609
+ return -(whole + (b.valueOf() - anchor) / (behind ? anchor - anchor2 : anchor2 - anchor)) || 0;
610
+ }
611
+ // ---------------------------------------------------------------------------
612
+ // Factory
613
+ // ---------------------------------------------------------------------------
614
+ function resolve(parsed, zone, zoneGiven) {
615
+ if (parsed.kind === 'epoch')
616
+ return { ms: parsed.ms, zone };
617
+ let z = zone;
618
+ if (parsed.zone && !zoneGiven)
619
+ z = normalizeZone(parsed.zone);
620
+ if (parsed.offset !== undefined)
621
+ return { ms: wallToUtcMs(parsed.wall) - parsed.offset * 60000, zone: z };
622
+ return { ms: wallToEpoch(parsed.wall, z), zone: z };
623
+ }
624
+ function isEpochLike(x) {
625
+ return typeof x === 'object' && x !== null && typeof x.epochMilliseconds === 'number';
626
+ }
627
+ /**
628
+ * Create a date.
629
+ * neram() now
630
+ * neram('2026-12-04') local midnight
631
+ * neram('2026-12-04T10:00+05:30') exact instant
632
+ * neram('2026-12-04T10:00[Asia/Tokyo]') RFC 9557 — wall time in that zone
633
+ * neram('04/12/2026', 'DD/MM/YYYY') custom format
634
+ * neram('04/12/2026', 'DD/MM/YYYY', true) strict
635
+ * neram({ year: 2026, month: 11, date: 4 }) fields
636
+ * neram(Temporal.Now.instant()) Temporal interop
637
+ */
638
+ function create(input, formatOrOpts, localeOrStrict, strict) {
639
+ let opts = {};
640
+ if (typeof formatOrOpts === 'string' || Array.isArray(formatOrOpts))
641
+ opts.format = formatOrOpts;
642
+ else if (formatOrOpts)
643
+ opts = { ...formatOrOpts };
644
+ if (typeof localeOrStrict === 'boolean')
645
+ opts.strict = localeOrStrict;
646
+ else if (typeof localeOrStrict === 'string')
647
+ opts.locale = localeOrStrict;
648
+ if (typeof strict === 'boolean')
649
+ opts.strict = strict;
650
+ const locale = opts.locale ? canonicalLocale(opts.locale) : config.locale;
651
+ const zoneGiven = opts.utc === true || opts.zone !== undefined;
652
+ let zone = normalizeZone(opts.utc ? 'UTC' : (opts.zone ?? config.zone));
653
+ const ws = opts.weekStart;
654
+ if (input instanceof Neram) {
655
+ let r = input;
656
+ if (zoneGiven)
657
+ r = r.tz(zone);
658
+ if (opts.locale)
659
+ r = r.locale(locale);
660
+ if (ws !== undefined)
661
+ r = r.weekStart(ws);
662
+ return r;
663
+ }
664
+ let ms;
665
+ if (input === undefined)
666
+ ms = Date.now();
667
+ else if (input === null)
668
+ ms = NaN;
669
+ else if (input instanceof Date)
670
+ ms = input.getTime();
671
+ else if (typeof input === 'number')
672
+ ms = input;
673
+ else if (typeof input === 'string') {
674
+ const formats = opts.format === undefined ? undefined : Array.isArray(opts.format) ? opts.format : [opts.format];
675
+ if (!formats) {
676
+ ;
677
+ ({ ms, zone } = resolve(parseString(input), zone, zoneGiven));
678
+ }
679
+ else {
680
+ ms = NaN;
681
+ for (const f of formats) {
682
+ const r = resolve(parseFormat(input, f, locale), zone, zoneGiven);
683
+ if (Number.isNaN(r.ms))
684
+ continue;
685
+ if (opts.strict && new Neram(r.ms, r.zone, locale, ws).format(f) !== input.trim())
686
+ continue;
687
+ ({ ms, zone } = r);
688
+ break;
689
+ }
690
+ }
691
+ }
692
+ else if (Array.isArray(input)) {
693
+ const [y = new Date().getFullYear(), M = 0, D = 1, h = 0, m = 0, s = 0, mss = 0] = input;
694
+ const w = { y, M, D, h, m, s, ms: mss };
695
+ ms = input.length >= 1 && input.length <= 7 && isValidWall(w) ? wallToEpoch(w, zone) : NaN;
696
+ }
697
+ else if (isEpochLike(input)) {
698
+ ms = input.epochMilliseconds;
699
+ if (input.timeZoneId && !zoneGiven)
700
+ zone = normalizeZone(input.timeZoneId);
701
+ }
702
+ else if (typeof input === 'object') {
703
+ const o = objectFields(input);
704
+ const w = o && {
705
+ y: o.year ?? new Date().getFullYear(),
706
+ M: o.month ?? 0,
707
+ D: o.date ?? 1,
708
+ h: o.hour ?? 0,
709
+ m: o.minute ?? 0,
710
+ s: o.second ?? 0,
711
+ ms: o.millisecond ?? 0,
712
+ };
713
+ ms = w && isValidWall(w) ? wallToEpoch(w, zone) : NaN;
714
+ }
715
+ else {
716
+ ms = NaN;
717
+ }
718
+ return new Neram(ms, zone, locale, ws);
719
+ }
720
+ /** Round half away from zero, so add(1.5, 'month') and subtract(1.5, 'month') mirror each other. */
721
+ function roundCalendar(n) {
722
+ return n < 0 ? -Math.round(-n) : Math.round(n);
723
+ }
724
+ function checkWeekend(weekend) {
725
+ if (!Array.isArray(weekend) || weekend.some((d) => !Number.isInteger(d) || d < 0 || d > 6)) {
726
+ throw new RangeError(`neram: weekend must list weekday numbers 0-6 (0 = Sunday), got ${JSON.stringify(weekend)}`);
727
+ }
728
+ if (new Set(weekend).size === 7)
729
+ throw new RangeError('neram: weekend cannot include every day of the week');
730
+ return weekend;
731
+ }
732
+ const OBJECT_KEYS = {
733
+ year: 'year', years: 'year', y: 'year',
734
+ month: 'month', months: 'month', M: 'month',
735
+ date: 'date', dates: 'date', D: 'date', d: 'date', day: 'date', days: 'date',
736
+ hour: 'hour', hours: 'hour', h: 'hour',
737
+ minute: 'minute', minutes: 'minute', m: 'minute',
738
+ second: 'second', seconds: 'second', s: 'second',
739
+ millisecond: 'millisecond', milliseconds: 'millisecond', ms: 'millisecond',
740
+ };
741
+ /** Fields of a date object, or undefined when it has no known field, an unknown field or a non-number. */
742
+ function objectFields(input) {
743
+ const out = {};
744
+ let any = false;
745
+ for (const [k, v] of Object.entries(input)) {
746
+ if (v === undefined)
747
+ continue;
748
+ const key = OBJECT_KEYS[k];
749
+ if (!key || typeof v !== 'number' || out[key] !== undefined)
750
+ return undefined;
751
+ out[key] = v;
752
+ any = true;
753
+ }
754
+ return any ? out : undefined;
755
+ }
756
+ /** True when every field is a whole number inside its range (no rolling Feb 30 into March). */
757
+ function isValidWall(w) {
758
+ const ints = [w.y, w.M, w.D, w.h, w.m, w.s, w.ms];
759
+ if (!ints.every(Number.isInteger))
760
+ return false;
761
+ return (w.M >= 0 && w.M <= 11 && w.D >= 1 && w.D <= daysInMonth(w.y, w.M) &&
762
+ w.h >= 0 && w.h <= 23 && w.m >= 0 && w.m <= 59 && w.s >= 0 && w.s <= 59 && w.ms >= 0 && w.ms <= 999);
763
+ }
764
+ const installed = new Set();
765
+ function toNerams(args) {
766
+ return (args.length === 1 && Array.isArray(args[0]) && !(typeof args[0][0] === 'number') ? args[0] : args)
767
+ .map((a) => create(a))
768
+ .filter((d) => d.isValid());
769
+ }
770
+ export const neram = Object.assign(create, {
771
+ /** Parse in UTC: neram.utc('2026-12-04 10:00') */
772
+ utc(input, format, strict) {
773
+ return create(input, { format, strict, utc: true });
774
+ },
775
+ /** Parse a wall time in a zone, or convert an instant to it: neram.tz('2026-03-08 02:30', 'America/New_York') */
776
+ tz(input, zone, format) {
777
+ return create(input, { format, zone });
778
+ },
779
+ /** From seconds since the epoch. */
780
+ unix(seconds) {
781
+ return create(seconds * 1000);
782
+ },
783
+ now() {
784
+ return create();
785
+ },
786
+ duration,
787
+ isDuration,
788
+ Duration,
789
+ Neram,
790
+ isNeram(x) {
791
+ return x instanceof Neram;
792
+ },
793
+ min(...dates) {
794
+ const list = toNerams(dates);
795
+ return list.length ? list.reduce((a, b) => (b.valueOf() < a.valueOf() ? b : a)) : null;
796
+ },
797
+ max(...dates) {
798
+ const list = toNerams(dates);
799
+ return list.length ? list.reduce((a, b) => (b.valueOf() > a.valueOf() ? b : a)) : null;
800
+ },
801
+ /** Sorted copy, earliest first. */
802
+ sort(dates) {
803
+ return dates.map((d) => create(d)).sort((a, b) => a.valueOf() - b.valueOf());
804
+ },
805
+ /**
806
+ * Every date from start to end (inclusive) in steps:
807
+ * neram.range('2026-12-01', '2026-12-07') — 7 days
808
+ * neram.range(start, end, { unit: 'week', step: 2 })
809
+ */
810
+ range(start, end, opts = {}) {
811
+ const unit = normalizeUnit(opts.unit ?? 'day');
812
+ const size = opts.step ?? 1;
813
+ if (typeof size !== 'number' || !Number.isFinite(size) || size <= 0) {
814
+ throw new RangeError(`neram: range step must be a positive number, got ${String(size)}`);
815
+ }
816
+ if (!(unit in FIXED_MS) && !Number.isInteger(size)) {
817
+ throw new RangeError(`neram: range step must be a whole number of ${unit}s, got ${size}`);
818
+ }
819
+ const limit = opts.limit ?? 100000;
820
+ if (!Number.isInteger(limit) || limit < 0)
821
+ throw new RangeError(`neram: range limit must be a whole number, got ${limit}`);
822
+ const a = create(start);
823
+ const b = create(end);
824
+ if (!a.isValid() || !b.isValid())
825
+ return [];
826
+ const step = size * (b.valueOf() < a.valueOf() ? -1 : 1);
827
+ const out = [];
828
+ for (let i = 0;; i++) {
829
+ const cur = a.add(step * i, unit);
830
+ const past = step > 0 ? cur.valueOf() > b.valueOf() : cur.valueOf() < b.valueOf();
831
+ if (past || (opts.exclusive && cur.valueOf() === b.valueOf()))
832
+ break;
833
+ if (out.length === limit) {
834
+ throw new RangeError(`neram: range has more than ${limit} dates; use a larger step or pass { limit }`);
835
+ }
836
+ out.push(cur);
837
+ }
838
+ return out;
839
+ },
840
+ /** Get or set the default locale for new instances. */
841
+ locale(locale) {
842
+ if (locale !== undefined)
843
+ config.locale = canonicalLocale(locale);
844
+ return config.locale;
845
+ },
846
+ /** Month and weekday names and week rules for a locale (the default locale if omitted). Day.js-compatible. */
847
+ localeData(locale) {
848
+ return publicLocaleData(locale ? canonicalLocale(locale) : config.locale);
849
+ },
850
+ /**
851
+ * Versions and features of this runtime's date data. Log it on the server and in the browser:
852
+ * if icu/cldr/tzdata or the zone differ, localized text or future DST changes may differ too.
853
+ */
854
+ environment() {
855
+ const v = globalThis.process?.versions ?? {};
856
+ const I = Intl;
857
+ let unitFormat = true;
858
+ try {
859
+ new Intl.NumberFormat('en', { style: 'unit', unit: 'hour' });
860
+ }
861
+ catch {
862
+ unitFormat = false;
863
+ }
864
+ return {
865
+ zone: guessZone(),
866
+ defaultZone: config.zone === 'local' ? guessZone() : config.zone,
867
+ locale: config.locale,
868
+ runtimeLocale: new Intl.DateTimeFormat().resolvedOptions().locale,
869
+ icu: v.icu,
870
+ cldr: v.cldr,
871
+ tzdata: v.tz,
872
+ features: {
873
+ relativeTimeFormat: typeof I.RelativeTimeFormat === 'function',
874
+ listFormat: typeof I.ListFormat === 'function',
875
+ durationFormat: typeof I.DurationFormat === 'function',
876
+ supportedValuesOf: typeof I.supportedValuesOf === 'function',
877
+ unitFormat,
878
+ },
879
+ };
880
+ },
881
+ /** The runtime's IANA time zone. */
882
+ guess() {
883
+ return guessZone();
884
+ },
885
+ /** Every IANA zone the runtime knows (where Intl.supportedValuesOf exists). */
886
+ zones() {
887
+ const sv = Intl.supportedValuesOf;
888
+ return sv ? sv('timeZone') : [];
889
+ },
890
+ /** Set defaults: neram.config({ locale: 'ta', zone: 'Asia/Kolkata', weekStart: 1 }) */
891
+ config(next = {}) {
892
+ if (next.locale !== undefined)
893
+ config.locale = canonicalLocale(next.locale);
894
+ if (next.zone !== undefined)
895
+ config.zone = normalizeZone(next.zone);
896
+ if ('weekStart' in next)
897
+ config.weekStart = next.weekStart;
898
+ if (next.normalizeSpaces !== undefined)
899
+ intlSettings.normalizeSpaces = config.normalizeSpaces = next.normalizeSpaces;
900
+ return { ...config };
901
+ },
902
+ /** Day.js-style plugins: (option, NeramClass, neram) => void. Installed once. */
903
+ extend(plugin, option) {
904
+ if (!installed.has(plugin)) {
905
+ plugin(option, Neram, neram);
906
+ installed.add(plugin);
907
+ }
908
+ return neram;
909
+ },
910
+ });