-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2419 lines (2294 loc) · 80 KB
/
Copy pathindex.js
File metadata and controls
2419 lines (2294 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const nopeRedis = require('./nope-redis');
const {
parseWithTimezone,
getTimezoneOffset,
absFloor,
duration,
padZero,
checkTimezone,
getTimezoneInfo,
convertToTimezone,
getAvailableTimezones,
isDST,
getTimezoneAbbreviation,
dateTimeFormat,
converter,
isValidMonth,
tryParseTextDate,
num2,
num4,
getOrdinal,
getCompiledTemplate,
getDayOfWeek,
getDayOfYear,
getIsoWeekInfo,
getLocaleWeekInfo,
getTimezoneLongName,
format_validators,
validateDynamicTemplate,
} = require('./functions');
const {
cached_dateTimeFormat,
format_types,
timeInMilliseconds,
format_types_regex,
global_config,
format_types_regex_cache,
formatter_cache,
format_part_types,
format_derived_flags,
systemTimezone,
} = require('./constants');
nopeRedis.config({ defaultTtl: 1300 });
// Hoisted 'dddd' sentinel so the static isValid fast path is a single identity compare
// instead of a property load on every call (the detection ladder calls isValid per rung).
const TEMPLATE_DDDD = format_types.dddd;
// Mirrors nope-redis service status. When caching is disabled (the default), we skip all
// cache reads/writes so no cache-key string, Date clone, or Promise is allocated on the hot path.
let cachingEnabled = false;
// Shared frozen per-instance config: most instances never call config()/tz()/fromNow(), so the
// constructor assigns this sentinel instead of allocating a fresh { rtf: {} } per instance.
// Readers behave exactly as with a fresh object (every property is undefined); the few methods
// that write per-instance config go through ownTempConfig() first (copy-on-write).
const EMPTY_RTF = Object.freeze({});
const EMPTY_TEMP_CONFIG = Object.freeze({ timezone: undefined, locale: undefined, weekStartDay: undefined, rtf: EMPTY_RTF });
/**
* Copy-on-write escape from the shared temp_config sentinel; call before any temp_config write.
*
* @param {KkDate} kkDate
* @returns {object} the instance's own (writable) temp_config
*/
function ownTempConfig(kkDate) {
if (kkDate.temp_config === EMPTY_TEMP_CONFIG) {
kkDate.temp_config = { timezone: undefined, locale: undefined, weekStartDay: undefined, rtf: {} };
}
return kkDate.temp_config;
}
// True only while the global timezone differs from the system timezone — the single case where
// the constructor's parseWithTimezone() call can change the date. Kept in sync by config() and
// setTimezone() so the constructor can skip that call entirely in the default configuration.
let timezone_shift_enabled = global_config.timezone !== systemTimezone;
/**
* Builds a local-time Date from already-split numeric date parts using the numeric Date
* constructor, which skips the engine's (much slower) string date parser.
*
* Guarded on a 4-digit year: the parse regexes' `(|17|18|19|20|21)\d\d` empty-alternative also
* matches 2-digit years, for which the numeric constructor maps to 19xx and would accept inputs
* that the legacy string form rejects. 2-digit years fall back to the exact legacy string so
* behavior is preserved.
*
* @param {string} year
* @param {string} month - 1-based month
* @param {string} day
* @returns {Date}
*/
function fastLocalDate(year, month, day) {
if (year.length === 4) {
return new Date(+year, +month - 1, +day, 0, 0, 0, 0);
}
return new Date(`${year}-${month}-${day} 00:00:00`);
}
/**
* Two ASCII digits at offset i as an int. Only called on strings whose shape was already
* confirmed by a template validator, so no digit re-checking is needed.
*
* @param {string} s
* @param {number} i
* @returns {number}
*/
function cc2(s, i) {
return (s.charCodeAt(i) - 48) * 10 + (s.charCodeAt(i + 1) - 48);
}
/**
* Four ASCII digits at offset i as an int (validated shapes only).
*
* @param {string} s
* @param {number} i
* @returns {number}
*/
function cc4(s, i) {
return cc2(s, i) * 100 + cc2(s, i + 2);
}
/**
* Like {@link fastLocalDate} but with a time component. `timePart` is the raw "HH:mm[:ss]" slice;
* seconds default to 0 when absent. Same 4-digit-year guard and legacy fallback.
*
* @param {string} year
* @param {string} month - 1-based month
* @param {string} day
* @param {string} timePart - "HH:mm" or "HH:mm:ss"
* @returns {Date}
*/
function fastLocalDateTime(year, month, day, timePart) {
if (year.length === 4) {
const [h, mi, s] = timePart.split(':');
return new Date(+year, +month - 1, +day, +h, +mi || 0, +s || 0, 0);
}
return new Date(`${year}-${month}-${day}T${timePart}`);
}
/**
* @class KkDate
* @description A utility class for date parsing, validation, and formatting.
* Accepts various input types (string, Date, KkDate) and supports multiple date formats
* like "YYYY-MM-DD" or "YYYY-DD-MM".
*/
// ---------------------------------------------------------------------------
// Constructor auto-detection
//
// String inputs are routed by (length, separator charCode) so each input runs at most a
// couple of template validators instead of walking a long rung ladder. The validators are
// the same `format_validators` the ladder used — acceptance is unchanged — and every shape
// the fast paths decline falls through to `parseTextLegacy`, which keeps the original
// regex rung chain and the native `new Date(string)` fallback verbatim.
// ---------------------------------------------------------------------------
// Cached "today" fields for time-of-day inputs. Valid while Date.now() lies inside
// [today_from, today_until); both boundaries come from real local Date construction, so the
// window stays exact across DST transitions (23/25-hour days).
let today_year = 0;
let today_month = 0;
let today_day = 0;
let today_from = 1;
let today_until = 0;
function refreshToday(nowMs) {
const now = new Date(nowMs);
today_year = now.getFullYear();
today_month = now.getMonth();
today_day = now.getDate();
today_from = new Date(today_year, today_month, today_day, 0, 0, 0, 0).getTime();
today_until = new Date(today_year, today_month, today_day + 1, 0, 0, 0, 0).getTime();
}
/**
* Parses bare time-of-day strings onto today's date in a single charCode pass (no split()).
* Acceptance is bit-identical to the legacy validator/regex set:
* 24-hour "HH:mm[:ss[.SSS]]" with hours 00-29 (24+ rolls into the next day),
* 12-hour "hh:mm[:ss[.SSS]] AM|PM" with hours 01-12 (uppercase meridiem only).
* Everything else returns false and must keep falling through — e.g. "12:30:60" reaches the
* native parser, which reads ":60" as a 2-digit year (locked legacy behavior).
*
* detected_format quirks are load-bearing (tests and timezone reinterpretation key off them):
* zero seconds report 'HH:mm' ("14:30:00", "02:30 PM" and "02:30:00 PM" all detect as
* 'HH:mm'), and ".000" milliseconds do not count as a .SSS match.
*
* @param {KkDate} kk
* @param {string} s - string with ":" at index 2 and length <= 15
* @param {number} len
* @returns {boolean}
*/
function parseTimeOnly(kk, s, len) {
let hours = num2(s, 0);
const minutes = num2(s, 3);
if (hours < 0 || minutes < 0 || minutes > 59) {
return false;
}
let seconds = 0;
let hasSeconds = false;
let milliseconds = 0;
let end = 5; // index just past "HH:mm"
if (len >= 8 && s.charCodeAt(5) === 58) {
seconds = num2(s, 6);
if (seconds < 0 || seconds > 59) {
return false;
}
hasSeconds = true;
end = 8;
if (len >= 12 && s.charCodeAt(8) === 46) {
const msHi = num2(s, 9);
const msLo = s.charCodeAt(11) - 48;
if (msHi < 0 || msLo < 0 || msLo > 9) {
return false;
}
milliseconds = msHi * 10 + msLo;
end = 12;
}
}
let isTwelveHour = false;
if (end !== len) {
// Only a literal " AM"/" PM" tail may remain (12-hour forms).
if (len !== end + 3 || s.charCodeAt(end) !== 32 || s.charCodeAt(end + 2) !== 77 || hours < 1 || hours > 12) {
return false;
}
const meridiem = s.charCodeAt(end + 1);
if (meridiem === 65) {
if (hours === 12) {
hours = 0;
}
} else if (meridiem === 80) {
if (hours !== 12) {
hours += 12;
}
} else {
return false;
}
isTwelveHour = true;
} else if (hours > 29) {
return false;
}
const nowMs = Date.now();
if (nowMs < today_from || nowMs >= today_until) {
refreshToday(nowMs);
}
// Hours 24-29 spill into the following day through the day argument — the same
// normalization the legacy setDate() + setHours() pair produced.
const extraDay = hours >= 24 ? 1 : 0;
kk.date = new Date(today_year, today_month, today_day + extraDay, hours - extraDay * 24, minutes, seconds, milliseconds);
if (milliseconds !== 0) {
kk.detected_format = isTwelveHour ? format_types['hh:mm:ss.SSS'] : format_types['HH:mm:ss.SSS'];
} else if (hasSeconds && seconds !== 0) {
kk.detected_format = isTwelveHour ? format_types['hh:mm:ss'] : format_types['HH:mm:ss'];
} else {
kk.detected_format = format_types['HH:mm'];
}
return true;
}
/**
* Exact-shape ISO parser built straight from charCodes:
* len 19 "YYYY-MM-DDTHH:mm:ss" → local time (utc = false)
* len 20 "YYYY-MM-DDTHH:mm:ssZ" → UTC
* len 24 "YYYY-MM-DDTHH:mm:ss.SSSZ" → UTC
* Day overflow rolls exactly like the native parser; the shapes where native semantics
* differ from the numeric constructors (month 13, hour 24, year < 100 two-digit mapping)
* return false so the caller's native `new Date(string)` keeps producing the locked result.
*
* @param {KkDate} kk
* @param {string} s
* @param {number} len - 19, 20 or 24 (already checked by the caller)
* @param {boolean} utc
* @returns {boolean}
*/
function parseIsoExact(kk, s, len, utc) {
if (s.charCodeAt(13) !== 58 || s.charCodeAt(16) !== 58) {
return false;
}
const year = num4(s, 0);
const month = num2(s, 5);
const day = num2(s, 8);
const hours = num2(s, 11);
const minutes = num2(s, 14);
const seconds = num2(s, 17);
if (
year < 100 ||
month < 1 ||
month > 12 ||
day < 1 ||
day > 31 ||
hours < 0 ||
hours > 23 ||
minutes < 0 ||
minutes > 59 ||
seconds < 0 ||
seconds > 59
) {
return false;
}
let milliseconds = 0;
if (len === 24) {
if (s.charCodeAt(19) !== 46) {
return false;
}
const msHi = num2(s, 20);
const msLo = s.charCodeAt(22) - 48;
if (msHi < 0 || msLo < 0 || msLo > 9) {
return false;
}
milliseconds = msHi * 10 + msLo;
}
kk.date = utc
? new Date(Date.UTC(year, month - 1, day, hours, minutes, seconds, milliseconds))
: new Date(year, month - 1, day, hours, minutes, seconds, milliseconds);
return true;
}
/**
* Claims a full-year "YYYY(sep)MM(sep)DD HH:mm[:ss]" input from fixed charCode offsets.
* Only called after the template's validator accepted the string, so fields are digits and
* hours are 00-29; hours 24-29 spill into the next day (legacy overflow result).
*/
function claimYmdDateTime(kk, s, template, withSeconds) {
const hours = cc2(s, 11);
const day = cc2(s, 8);
const extraDay = hours >= 24 ? 1 : 0;
kk.date = new Date(cc4(s, 0), cc2(s, 5) - 1, day + extraDay, hours - extraDay * 24, cc2(s, 14), withSeconds ? cc2(s, 17) : 0, 0);
kk.detected_format = format_types[template];
return true;
}
/** Mirror of claimYmdDateTime for "DD(sep)MM(sep)YYYY HH:mm[:ss]" layouts. */
function claimDmyDateTime(kk, s, template, withSeconds) {
const hours = cc2(s, 11);
const day = cc2(s, 0);
const extraDay = hours >= 24 ? 1 : 0;
kk.date = new Date(cc4(s, 6), cc2(s, 3) - 1, day + extraDay, hours - extraDay * 24, cc2(s, 14), withSeconds ? cc2(s, 17) : 0, 0);
kk.detected_format = format_types[template];
return true;
}
/**
* Legacy construction for the rare 2-digit-year datetime shapes ("15-01-24 14:30", ...).
* The exact split()-based pipeline is preserved — including the string round-trips — because
* V8's string parser defines their (locked, often Invalid) results.
*/
function claimShortYearDateTime(kk, s, template, sep, dayFirst, withSeconds) {
const [datePart, timePart] = s.split(' ');
const dateParts = datePart.split(sep);
const year = dayFirst ? dateParts[2] : dateParts[0];
const month = dateParts[1];
const day = dayFirst ? dateParts[0] : dateParts[2];
const timeParts = timePart.split(':').map(Number);
const hours = timeParts[0];
if (hours >= 24) {
const extraDays = Math.floor(hours / 24);
const dateObj = fastLocalDate(year, month, day);
dateObj.setDate(dateObj.getDate() + extraDays);
const newDay = String(dateObj.getDate()).padStart(2, '0');
const newMonth = String(dateObj.getMonth() + 1).padStart(2, '0');
const newYear = dateObj.getFullYear();
const hoursText = (hours % 24).toString().padStart(2, '0');
const minutesText = timeParts[1].toString().padStart(2, '0');
kk.date = withSeconds
? new Date(`${newYear}-${newMonth}-${newDay}T${hoursText}:${minutesText}:${timeParts[2].toString().padStart(2, '0')}`)
: new Date(`${newYear}-${newMonth}-${newDay}T${hoursText}:${minutesText}`);
} else {
kk.date = fastLocalDateTime(year, month, day, timePart);
}
kk.detected_format = format_types[template];
return true;
}
/**
* Numeric date shapes ("-" / "." separated and compact digits), dispatched by length and
* separator position. Branch order inside each length class preserves the legacy ladder's
* claim precedence for overlapping shapes (dot DD.MM.YY before dot YY.MM.DD, dash YY-MM-DD
* before dash DD-MM-YY, ...).
*
* @param {KkDate} kk
* @param {string} s
* @param {number} len
* @param {number} probe2 - charCodeAt(2)
* @param {number} probe4 - charCodeAt(4)
* @returns {boolean}
*/
function parseNumericDate(kk, s, len, probe2, probe4) {
switch (len) {
case 19: {
if (probe2 === 46 && isValid(s, format_types['DD.MM.YYYY HH:mm:ss'])) {
return claimDmyDateTime(kk, s, 'DD.MM.YYYY HH:mm:ss', true);
}
if (probe4 === 45 && isValid(s, format_types['YYYY-MM-DD HH:mm:ss'])) {
return claimYmdDateTime(kk, s, 'YYYY-MM-DD HH:mm:ss', true);
}
if (probe4 === 46 && isValid(s, format_types['YYYY.MM.DD HH:mm:ss'])) {
return claimYmdDateTime(kk, s, 'YYYY.MM.DD HH:mm:ss', true);
}
if (probe2 === 45 && isValid(s, format_types['DD-MM-YYYY HH:mm:ss'])) {
return claimDmyDateTime(kk, s, 'DD-MM-YYYY HH:mm:ss', true);
}
return false;
}
case 16: {
if (probe2 === 46 && isValid(s, format_types['DD.MM.YYYY HH:mm'])) {
return claimDmyDateTime(kk, s, 'DD.MM.YYYY HH:mm', false);
}
if (probe4 === 45 && isValid(s, format_types['YYYY-MM-DD HH:mm'])) {
return claimYmdDateTime(kk, s, 'YYYY-MM-DD HH:mm', false);
}
if (probe4 === 46 && isValid(s, format_types['YYYY.MM.DD HH:mm'])) {
return claimYmdDateTime(kk, s, 'YYYY.MM.DD HH:mm', false);
}
if (probe2 === 45 && isValid(s, format_types['DD-MM-YYYY HH:mm'])) {
return claimDmyDateTime(kk, s, 'DD-MM-YYYY HH:mm', false);
}
return false;
}
case 10: {
if (probe2 === 46 && isValid(s, format_types['DD.MM.YYYY'])) {
kk.date = new Date(cc4(s, 6), cc2(s, 3) - 1, cc2(s, 0), 0, 0, 0, 0);
kk.detected_format = format_types['DD.MM.YYYY'];
return true;
}
if (probe2 === 45 && isValid(s, format_types['DD-MM-YYYY'])) {
kk.date = new Date(cc4(s, 6), cc2(s, 3) - 1, cc2(s, 0), 0, 0, 0, 0);
kk.detected_format = format_types['DD-MM-YYYY'];
return true;
}
if (probe4 === 45 && isValid(s, format_types['YYYY-DD-MM'])) {
kk.date = new Date(cc4(s, 0), cc2(s, 8) - 1, cc2(s, 5), 0, 0, 0, 0);
kk.detected_format = format_types['YYYY-DD-MM'];
return true;
}
// New rung: date-only "YYYY.MM.DD" previously fell through to the native parser with
// the same resulting instant; out-of-range shapes still do (e.g. "2300.01.15").
if (probe4 === 46 && isValid(s, format_types['YYYY.MM.DD'])) {
kk.date = new Date(cc4(s, 0), cc2(s, 5) - 1, cc2(s, 8), 0, 0, 0, 0);
kk.detected_format = format_types['YYYY.MM.DD'];
return true;
}
return false;
}
case 7: {
if (probe4 === 45 && isValid(s, format_types['YYYY-MM'])) {
kk.date = new Date(cc4(s, 0), cc2(s, 5) - 1, 1, 0, 0, 0, 0);
kk.detected_format = format_types['YYYY-MM'];
return true;
}
return false;
}
case 17: {
// 2-digit-year datetime shapes share separator positions; ladder order decides.
if (probe2 === 46) {
if (isValid(s, format_types['DD.MM.YYYY HH:mm:ss'])) {
return claimShortYearDateTime(kk, s, 'DD.MM.YYYY HH:mm:ss', '.', true, true);
}
if (isValid(s, format_types['YYYY.MM.DD HH:mm:ss'])) {
return claimShortYearDateTime(kk, s, 'YYYY.MM.DD HH:mm:ss', '.', false, true);
}
} else if (probe2 === 45) {
if (isValid(s, format_types['YYYY-MM-DD HH:mm:ss'])) {
return claimShortYearDateTime(kk, s, 'YYYY-MM-DD HH:mm:ss', '-', false, true);
}
if (isValid(s, format_types['DD-MM-YYYY HH:mm:ss'])) {
return claimShortYearDateTime(kk, s, 'DD-MM-YYYY HH:mm:ss', '-', true, true);
}
}
return false;
}
case 14: {
if (probe2 === 46) {
if (isValid(s, format_types['DD.MM.YYYY HH:mm'])) {
return claimShortYearDateTime(kk, s, 'DD.MM.YYYY HH:mm', '.', true, false);
}
if (isValid(s, format_types['YYYY.MM.DD HH:mm'])) {
return claimShortYearDateTime(kk, s, 'YYYY.MM.DD HH:mm', '.', false, false);
}
return false;
}
if (probe2 === 45) {
if (isValid(s, format_types['YYYY-MM-DD HH:mm'])) {
return claimShortYearDateTime(kk, s, 'YYYY-MM-DD HH:mm', '-', false, false);
}
if (isValid(s, format_types['DD-MM-YYYY HH:mm'])) {
return claimShortYearDateTime(kk, s, 'DD-MM-YYYY HH:mm', '-', true, false);
}
return false;
}
if (isValid(s, format_types['YYYYMMDDHHmmss'])) {
kk.date = new Date(cc4(s, 0), cc2(s, 4) - 1, cc2(s, 6), cc2(s, 8), cc2(s, 10), cc2(s, 12), 0);
kk.detected_format = format_types['YYYYMMDDHHmmss'];
return true;
}
return false;
}
case 12: {
if (isValid(s, format_types['YYYYMMDDHHmmss'])) {
// Legacy body verbatim: fixed substrings produce a truncated string for
// 12-char inputs, whose (Invalid) native-parse result is locked.
const year = s.substring(0, 4);
const month = s.substring(4, 6);
const day = s.substring(6, 8);
const hour = s.substring(8, 10);
const minute = s.substring(10, 12);
const second = s.substring(12, 14);
kk.date = new Date(`${year}-${month}-${day} ${hour}:${minute}:${second}`);
kk.detected_format = format_types['YYYYMMDDHHmmss'];
return true;
}
return false;
}
case 8: {
if (probe2 === 46 && isValid(s, format_types['DD.MM.YYYY'])) {
const [day, month, year] = s.split('.');
kk.date = fastLocalDate(year, month, day);
kk.detected_format = format_types['DD.MM.YYYY'];
return true;
}
if (probe2 === 45 && isValid(s, format_types['DD-MM-YYYY'])) {
const [day, month, year] = s.split('-');
kk.date = fastLocalDate(year, month, day);
kk.detected_format = format_types['DD-MM-YYYY'];
return true;
}
if (probe2 !== 46 && probe2 !== 45 && isValid(s, format_types['YYYYMMDD'])) {
kk.date = new Date(cc4(s, 0), cc2(s, 4) - 1, cc2(s, 6), 0, 0, 0, 0);
kk.detected_format = format_types['YYYYMMDD'];
return true;
}
return false;
}
case 6: {
if (isValid(s, format_types['YYYYMMDD'])) {
// Legacy body verbatim for the short compact form (locked Invalid result).
const year = String(s.substring(0, 4), 10);
const month = String(s.substring(4, 6), 10);
const day = String(s.substring(6, 8), 10);
kk.date = new Date(`${year}-${month}-${day} 00:00:00`);
kk.detected_format = format_types['YYYYMMDD'];
return true;
}
return false;
}
default:
return false;
}
}
/**
* Legacy text-format regex chain — the cold fallback for every string the fast paths decline
* (2-digit-year text forms, tab-separated ordinals, embedded 'Do' matches, unknown month
* names, ...), ending in the native `new Date(string)` parser. Bodies are the original rung
* bodies, verbatim: their string round-trip construction defines the locked results.
*
* @param {KkDate} kk
* @param {string} date
* @param {boolean} has_space
* @returns {boolean} always true (kk.date is always assigned, possibly an Invalid Date)
*/
function parseTextLegacy(kk, date, has_space) {
if (has_space && isValid(date, format_types['DD MMMM YYYY'])) {
const parts = date.split(' ');
const day = parseInt(parts[0], 10).toString();
const month = isValidMonth(parts[1]);
const year = parts[2];
kk.date = new Date(`${year}-${month}-${day.padStart(2, '0')} 00:00:00`); // Ensure day is padded for Date constructor
kk.detected_format = format_types['DD MMMM YYYY'];
} else if (has_space && isValid(date, format_types['DD MMMM dddd'])) {
const currentYear = new Date().getFullYear();
const parts = date.split(' '); // e.g., ['01', 'January', 'Monday']
const day = parts[0];
const month = isValidMonth(parts[1]);
kk.date = new Date(`${currentYear}-${month}-${day} 00:00:00`);
kk.detected_format = format_types['DD MMMM dddd'];
} else if (has_space && isValid(date, format_types['D MMMM YYYY'])) {
const parts = date.split(' '); // e.g., ['1', 'January', '2024'] or ['01', 'January', '2024']
const day = parts[0];
const year = parts[2];
const month = isValidMonth(parts[1]);
kk.date = new Date(`${year}-${month}-${day.padStart(2, '0')} 00:00:00`); // Ensure day is padded for Date constructor
kk.detected_format = format_types['D MMMM YYYY'];
} else if (has_space && isValid(date, format_types['YYYY MMM DD'])) {
const parts = date.split(' ');
const year = parts[0];
const month = isValidMonth(parts[1]);
const day = parts[2];
kk.date = new Date(`${year}-${month}-${day.padStart(2, '0')} 00:00:00`); // Ensure day is padded for Date constructor
kk.detected_format = format_types['YYYY MMM DD'];
} else if (isValid(date, format_types['Do MMM YYYY'])) {
const parts = date.split(' ');
const day = parseInt(parts[0], 10).toString();
const month = isValidMonth(parts[1]);
const year = parts[2];
kk.date = new Date(`${year}-${month}-${day.padStart(2, '0')} 00:00:00`); // Ensure day is padded for Date constructor
kk.detected_format = format_types['Do MMM YYYY'];
} else if (has_space && isValid(date, format_types['DD MMMM dddd, YYYY'])) {
const parts = date.split(' ');
const day = parseInt(parts[0], 10).toString();
const month = isValidMonth(parts[1]);
const year = parts[3];
kk.date = new Date(`${year}-${month}-${day.padStart(2, '0')} 00:00:00`); // Ensure day is padded for Date constructor
kk.detected_format = format_types['DD MMMM dddd, YYYY'];
} else if (has_space && isValid(date, format_types['dddd, DD MMMM YYYY'])) {
const parts = date.split(' ');
const day = parseInt(parts[1], 10).toString();
const month = isValidMonth(parts[2]);
const year = parts[3];
kk.date = new Date(`${year}-${month}-${day.padStart(2, '0')} 00:00:00`); // Ensure day is padded for Date constructor
kk.detected_format = format_types['dddd, DD MMMM YYYY'];
} else if (has_space && isValid(date, format_types['DD MMMM'])) {
const currentYear = new Date().getFullYear();
const parts = date.split(' ');
const day = parts[0];
const month = isValidMonth(parts[1]);
kk.date = new Date(`${currentYear}-${month}-${day.padStart(2, '0')} 00:00:00`);
kk.detected_format = format_types['DD MMMM'];
} else {
kk.date = new Date(`${date}`);
}
return true;
}
/**
* Offset source for the manipulation methods' offset dance (add/set/get/startOf/endOf/diff).
* When the effective timezone IS the system timezone — the default configuration, since the
* global timezone initializes to it — the native getTimezoneOffset() yields the identical
* value with no Intl formatToParts call and no cache-key string allocation. The two sources
* only diverge for pre-1901 sub-minute LMT instants, far outside the supported input range.
*
* @param {string} timezone - effective target timezone (always truthy at call sites)
* @param {Date} date
* @returns {number} offset in milliseconds
*/
function offsetForCalc(timezone, date) {
if (timezone === systemTimezone) {
return -date.getTimezoneOffset() * 60000;
}
return getTimezoneOffset(timezone, date);
}
/**
* Auto-detects and parses a string input, assigning kk.date and kk.detected_format.
*
* @param {KkDate} kk
* @param {string} date
* @returns {boolean} the constructor's is_can_cache flag (auto-detected YYYY-MM-DD is not
* cached; every other claim — including the native fallback — is; legacy behavior)
*/
function parseStringInput(kk, date) {
const len = date.length;
const probe2 = date.charCodeAt(2);
const probe4 = date.charCodeAt(4);
// Hottest shape first; also claims the lenient 2-digit-year "YY-MM-DD" (legacy precedence).
if ((probe2 === 45 || probe4 === 45) && isValid(date, format_types['YYYY-MM-DD'])) {
if (len === 10) {
kk.date = new Date(cc4(date, 0), cc2(date, 5) - 1, cc2(date, 8), 0, 0, 0, 0);
} else {
const [year, month, day] = date.split('-');
kk.date = fastLocalDate(year, month, day);
}
kk.detected_format = 'YYYY-MM-DD';
return false;
}
if (probe2 === 58 && len <= 15 && parseTimeOnly(kk, date, len)) {
return true;
}
if (date.charCodeAt(len - 1) === 90 && date.indexOf('T') !== -1) {
// UTC ISO strings; the exact 20/24-char shapes skip the native string parser.
if (!((len === 20 || len === 24) && parseIsoExact(kk, date, len, true))) {
kk.date = new Date(date);
}
kk.detected_format = 'ISO8601';
return true;
}
if (probe4 === 45 && date.charCodeAt(7) === 45 && date.charCodeAt(10) === 84) {
// ISO datetime without a Z/offset suffix, matched precisely by shape "____-__-__T…"
// (dashes at index 4 & 7, 'T' at 10) so weekday-name inputs like "Tuesday, …" are not
// caught. detected_format stays null, matching the legacy behavior of this shape.
if (!(len === 19 && parseIsoExact(kk, date, len, false))) {
kk.date = new Date(date);
}
return true;
}
if (parseNumericDate(kk, date, len, probe2, probe4)) {
return true;
}
const has_space = date.indexOf(' ') !== -1;
if (has_space && tryParseTextDate(kk, date)) {
return true;
}
return parseTextLegacy(kk, date, has_space);
}
class KkDate {
/**
* Constructs a KkDate instance with the given input and format.
*
* @param {string|Date|KkDate|number} date - The input value. Can be:
* - a date string (e.g. "2024-01-15", "15.01.2024"),
* - a native Date object,
* - another KkDate instance,
* - a numeric Unix timestamp (≤10 digits treated as seconds, >10 digits as milliseconds).
*
* @param {string} [date_format] - Optional format hint for parsing the date string.
* Supported formats include: `"YYYY-MM-DD"`, `"DD.MM.YYYY"`, `"YYYY-MM-DD HH:mm:ss"`, etc.
*/
constructor(...params) {
let is_can_cache = true;
let cached = false;
this.detected_format = null;
this.temp_config = EMPTY_TEMP_CONFIG;
// Formatter config-signature cache slot (-1 = not computed yet); see formatSig().
this._fmt_sig = -1;
this._fmt_sig_v = -1;
if (params.length === 0) {
this.date = new Date();
this.detected_format = 'now';
} else {
const date = params[0];
let forced_format_founded = false;
if (cachingEnabled) {
cached = nopeRedis.getItem(date instanceof Date || Number.isInteger(date) ? null : `${date}`);
}
if (typeof params[1] === 'string' && !cached) {
if (!format_types_regex[params[1]]) {
throw new Error(`Unsupported Format! ${params[1]} !`);
}
if (!format_types_regex[params[1]].test(params[0])) {
throw new Error(`Invalid format ! ${format_types[params[1]]} !`);
}
if (params[1] === format_types['YYYY-DD-MM']) {
is_can_cache = true;
const [year, day, month] = date.split('-');
this.date = fastLocalDate(year, month, day);
forced_format_founded = true;
this.detected_format = 'YYYY-DD-MM';
} else if (params[1] === format_types['YYYY-MM-DD']) {
is_can_cache = true;
if (typeof date === 'string' && date.length === 10) {
this.date = new Date(cc4(date, 0), cc2(date, 5) - 1, cc2(date, 8), 0, 0, 0, 0);
} else {
const [year, month, day] = date.split('-');
this.date = fastLocalDate(year, month, day);
}
forced_format_founded = true;
this.detected_format = 'YYYY-MM-DD';
} else if (params[1] === format_types['mm:ss']) {
// Time-only value on today's date, like the bare time formats below. Not cached:
// the cache key is the raw input, and e.g. '03:45' means 03h45 when auto-detected
// but 3m45s here — sharing one key would poison the other interpretation.
is_can_cache = false;
const time_str = typeof date === 'string' ? date : `${date}`;
const d = new Date();
d.setHours(0, cc2(time_str, 0), cc2(time_str, 3), 0);
this.date = d;
forced_format_founded = true;
this.detected_format = format_types['mm:ss'];
}
}
if (!forced_format_founded && !cached) {
is_can_cache = false;
if (typeof date === 'string') {
is_can_cache = parseStringInput(this, date);
} else if (Number.isInteger(date)) {
const stringed_date_length = `${date}`.length;
if (stringed_date_length <= 10) {
// Unix timestamp (seconds) - always create as UTC
this.date = new Date(date * 1000);
} else {
// JavaScript timestamp (milliseconds) - always create as UTC
this.date = new Date(date);
}
this.detected_format = 'Xx';
} else if (date instanceof KkDate) {
// Clone from another KkDate - preserve the exact time
this.date = new Date(date.date.getTime());
this.detected_format = 'kkDate';
} else if (date instanceof Date) {
// Clone from Date object - preserve the exact time
this.date = new Date(date.getTime());
this.detected_format = 'now';
} else {
// Exotic inputs (null, floats, plain objects): parse their string coercion —
// the legacy ladder validated the same coercion before running its bodies, and
// non-parseable values still end at the native Invalid Date throw below.
is_can_cache = parseStringInput(this, `${date}`);
}
}
if (is_can_cache && cached) {
// Restore detected_format alongside the instant: it drives timezone
// reinterpretation and UTC formatting, so a hit must behave like the parse it cached.
this.date = new Date(cached.t);
this.detected_format = cached.f;
} else {
// Inline isInvalid(): this.date is always a Date here, so the helper's
// try/catch adds nothing. The thrown error must stay byte-identical.
if (!this.date || Number.isNaN(this.date.getTime())) {
throw new Error('Invalid Date');
}
if (is_can_cache && cachingEnabled) {
nopeRedis.setItemSync(`${date}`, { t: this.date.getTime(), f: this.detected_format });
}
}
}
// parseWithTimezone() can only change the date while the global timezone differs from
// the system timezone (a fresh instance never has temp_config.timezone) — skip it otherwise.
if (timezone_shift_enabled) {
this.date = parseWithTimezone(this);
}
}
/**
* returns native Date getTime value
*
* @returns {number|Error}
*/
getTime() {
isInvalid(this.date);
return this.date.getTime();
}
/**
* Optimized helper to get timestamp from various input types
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {number}
*/
_getTimestamp(date) {
if (isKkDate(date) || date instanceof Date) {
return date.getTime();
}
if (Number.isInteger(date)) {
// Same seconds-vs-milliseconds rule as the constructor: up to 10 digits = Unix seconds
return `${date}`.length <= 10 ? date * 1000 : date;
}
// Only create KkDate instance for string inputs
return new KkDate(date).getTime();
}
/**
* isBefore
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isBefore(date) {
return this.getTime() < this._getTimestamp(date);
}
/**
* isSameOrBefore
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isSameOrBefore(date) {
return this.getTime() <= this._getTimestamp(date);
}
/**
* isAfter
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isAfter(date) {
return this.getTime() > this._getTimestamp(date);
}
/**
* isSameOrAfter
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isSameOrAfter(date) {
return this.getTime() >= this._getTimestamp(date);
}
/**
* isSame
*
* @param {string|Date|KkDate} date - date/datetime/time
* @returns {boolean|Error}
*/
isSame(date) {
return this.getTime() === this._getTimestamp(date);
}
/**
* isBetween
*
* @param {string|Date|KkDate} start - start date/datetime/time
* @param {string|Date|KkDate} end - end date/datetime/time
* @param {'seconds'|'minutes'|'hours'|'days'|'months'|'years'} [unit='milliseconds']
* @returns {boolean|Error}
*/
isBetween(start, end, unit = 'milliseconds') {
const starts = isKkDate(start) ? start.getTime() : new KkDate(start).getTime();
const ends = isKkDate(end) ? end.getTime() : new KkDate(end).getTime();
const date_time = this.date.getTime();
if (unit === 'milliseconds') {
return date_time >= starts && date_time <= ends;
}
if (!timeInMilliseconds[unit]) {
throw new Error('Invalid unit type. Must be one of: milliseconds, seconds, minutes, hours, days, weeks, months, years');
}
const startUnit = Math.floor(starts / timeInMilliseconds[unit]);
const endUnit = Math.floor(ends / timeInMilliseconds[unit]);
const dateUnit = Math.floor(date_time / timeInMilliseconds[unit]);
return dateUnit >= startUnit && dateUnit <= endUnit;
}
/**
* returns string of date
*
* @returns {string|Error}
*/
toString() {
isInvalid(this.date);
return this.date.toString();
}
/**
* The toDateString() method of Date instances returns a string representing the date portion of this date interpreted in the local timezone.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toDateString
* @returns {string|Error}
*/
toDateString() {
isInvalid(this.date);
return this.date.toDateString();
}
/**
* The toISOString() method of Date instances returns a string representing this date in the date time string format, a simplified format based on ISO 8601, which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively). The timezone is always UTC, as denoted by the suffix Z.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString
*
* @returns {string|Error}
*/
toISOString() {
isInvalid(this.date);
return this.date.toISOString();
}
/**
* The toJSON() method of Date instances returns a string representing this date in the same ISO format as toISOString().
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toJSON
*
* @returns {Object|Error}
*/
toJSON() {
isInvalid(this.date);
return this.date.toJSON();
}
/**
* The toUTCString() method of Date instances returns a string representing this date in the RFC 7231 format, with negative years allowed. The timezone is always UTC. toGMTString() is an alias of this method.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toUTCString
*
* @returns {string|Error}
*/
toUTCString() {
isInvalid(this.date);
return this.date.toUTCString();
}
/**
* The locale and options parameters customize the behavior of the function and let applications specify the language whose formatting conventions should be used.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString
*
* @param {object} options
* @returns {string|Error}
*/
toLocaleDateString(options) {
isInvalid(this.date);
if (!this.temp_config) {
this.temp_config = {
locale: global_config.locale || 'en-en',
rtf: {},
};
}
return this.date.toLocaleDateString(this.temp_config.locale, options);
}
/**
* The toLocaleString() method of Date instances returns a string with a language-sensitive representation of this date in the local timezone. In implementations with Intl.DateTimeFormat API support, this method simply calls Intl.DateTimeFormat.
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleString
*
* @param {object} options
* @returns {string|Error}
*/
toLocaleString(options) {
isInvalid(this.date);
if (!this.temp_config) {
this.temp_config = {
locale: global_config.locale || 'en-en',