-
Notifications
You must be signed in to change notification settings - Fork 153
/
ecmascript.mjs
5766 lines (5308 loc) · 201 KB
/
ecmascript.mjs
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
/* global __debug__ */
const ArrayIncludes = Array.prototype.includes;
const ArrayPrototypeMap = Array.prototype.map;
const ArrayPrototypePush = Array.prototype.push;
const ArrayPrototypeSort = Array.prototype.sort;
const ArrayPrototypeFind = Array.prototype.find;
const IntlDateTimeFormat = globalThis.Intl.DateTimeFormat;
const IntlSupportedValuesOf = globalThis.Intl.supportedValuesOf;
const MapCtor = Map;
const MapPrototypeSet = Map.prototype.set;
const MathAbs = Math.abs;
const MathFloor = Math.floor;
const MathMax = Math.max;
const MathMin = Math.min;
const MathSign = Math.sign;
const MathTrunc = Math.trunc;
const NumberIsFinite = Number.isFinite;
const NumberIsNaN = Number.isNaN;
const NumberIsSafeInteger = Number.isSafeInteger;
const NumberMaxSafeInteger = Number.MAX_SAFE_INTEGER;
const ObjectCreate = Object.create;
const ObjectDefineProperty = Object.defineProperty;
const ObjectEntries = Object.entries;
const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
const SetPrototypeHas = Set.prototype.has;
const StringCtor = String;
const StringFromCharCode = String.fromCharCode;
const StringPrototypeCharCodeAt = String.prototype.charCodeAt;
const StringPrototypeMatchAll = String.prototype.matchAll;
const StringPrototypeReplace = String.prototype.replace;
const StringPrototypeSlice = String.prototype.slice;
import bigInt from 'big-integer';
import callBound from 'call-bind/callBound';
import Call from 'es-abstract/2024/Call.js';
import CompletionRecord from 'es-abstract/2024/CompletionRecord.js';
import CreateDataPropertyOrThrow from 'es-abstract/2024/CreateDataPropertyOrThrow.js';
import Get from 'es-abstract/2024/Get.js';
import GetIterator from 'es-abstract/2024/GetIterator.js';
import GetMethod from 'es-abstract/2024/GetMethod.js';
import HasOwnProperty from 'es-abstract/2024/HasOwnProperty.js';
import IsArray from 'es-abstract/2024/IsArray.js';
import IsIntegralNumber from 'es-abstract/2024/IsIntegralNumber.js';
import IsPropertyKey from 'es-abstract/2024/IsPropertyKey.js';
import IteratorClose from 'es-abstract/2024/IteratorClose.js';
import IteratorStep from 'es-abstract/2024/IteratorStep.js';
import IteratorValue from 'es-abstract/2024/IteratorValue.js';
import SameValue from 'es-abstract/2024/SameValue.js';
import ToNumber from 'es-abstract/2024/ToNumber.js';
import ToObject from 'es-abstract/2024/ToObject.js';
import ToPrimitive from 'es-abstract/2024/ToPrimitive.js';
import ToString from 'es-abstract/2024/ToString.js';
import ToZeroPaddedDecimalString from 'es-abstract/2024/ToZeroPaddedDecimalString.js';
import Type from 'es-abstract/2024/Type.js';
import every from 'es-abstract/helpers/every.js';
import forEach from 'es-abstract/helpers/forEach.js';
import OwnPropertyKeys from 'es-abstract/helpers/OwnPropertyKeys.js';
import some from 'es-abstract/helpers/some.js';
import { GetIntrinsic } from './intrinsicclass.mjs';
import { FMAPowerOf10, TruncatingDivModByPowerOf10 } from './math.mjs';
import { CalendarMethodRecord, TimeZoneMethodRecord } from './methodrecord.mjs';
import { TimeDuration } from './timeduration.mjs';
import {
CreateSlots,
GetSlot,
HasSlot,
SetSlot,
EPOCHNANOSECONDS,
TIMEZONE_ID,
CALENDAR_ID,
INSTANT,
ISO_YEAR,
ISO_MONTH,
ISO_DAY,
ISO_HOUR,
ISO_MINUTE,
ISO_SECOND,
ISO_MILLISECOND,
ISO_MICROSECOND,
ISO_NANOSECOND,
DATE_BRAND,
YEAR_MONTH_BRAND,
MONTH_DAY_BRAND,
TIME_ZONE,
CALENDAR,
YEARS,
MONTHS,
WEEKS,
DAYS,
HOURS,
MINUTES,
SECONDS,
MILLISECONDS,
MICROSECONDS,
NANOSECONDS
} from './slots.mjs';
const $TypeError = GetIntrinsic('%TypeError%');
const $isEnumerable = callBound('Object.prototype.propertyIsEnumerable');
const DAY_SECONDS = 86400;
const DAY_NANOS = DAY_SECONDS * 1e9;
// Instant range is 100 million days (inclusive) before or after epoch.
const NS_MIN = bigInt(DAY_NANOS).multiply(-1e8);
const NS_MAX = bigInt(DAY_NANOS).multiply(1e8);
// PlainDateTime range is 24 hours wider (exclusive) than the Instant range on
// both ends, to allow for valid Instant=>PlainDateTime conversion for all
// built-in time zones (whose offsets must have a magnitude less than 24 hours).
const DATETIME_NS_MIN = NS_MIN.subtract(DAY_NANOS).add(bigInt.one);
const DATETIME_NS_MAX = NS_MAX.add(DAY_NANOS).subtract(bigInt.one);
// The pattern of leap years in the ISO 8601 calendar repeats every 400 years.
// The constant below is the number of nanoseconds in 400 years. It is used to
// avoid overflows when dealing with values at the edge legacy Date's range.
const NS_IN_400_YEAR_CYCLE = bigInt(400 * 365 + 97).multiply(DAY_NANOS);
const YEAR_MIN = -271821;
const YEAR_MAX = 275760;
const BEFORE_FIRST_DST = bigInt(-388152).multiply(1e13); // 1847-01-01T00:00:00Z
const BUILTIN_CALENDAR_IDS = [
'iso8601',
'hebrew',
'islamic',
'islamic-umalqura',
'islamic-tbla',
'islamic-civil',
'islamic-rgsa',
'islamicc',
'persian',
'ethiopic',
'ethioaa',
'coptic',
'chinese',
'dangi',
'roc',
'indian',
'buddhist',
'japanese',
'gregory'
];
const ICU_LEGACY_TIME_ZONE_IDS = new Set([
'ACT',
'AET',
'AGT',
'ART',
'AST',
'BET',
'BST',
'CAT',
'CNT',
'CST',
'CTT',
'EAT',
'ECT',
'IET',
'IST',
'JST',
'MIT',
'NET',
'NST',
'PLT',
'PNT',
'PRT',
'PST',
'SST',
'VST'
]);
export function ToIntegerWithTruncation(value) {
const number = ToNumber(value);
if (number === 0) return 0;
if (NumberIsNaN(number) || !NumberIsFinite(number)) {
throw new RangeError('invalid number value');
}
const integer = MathTrunc(number);
if (integer === 0) return 0; // ℝ(value) in spec text; converts -0 to 0
return integer;
}
export function ToPositiveIntegerWithTruncation(value, property) {
const integer = ToIntegerWithTruncation(value);
if (integer <= 0) {
if (property !== undefined) {
throw new RangeError(`property '${property}' cannot be a a number less than one`);
}
throw new RangeError('Cannot convert a number less than one to a positive integer');
}
return integer;
}
export function ToIntegerIfIntegral(value) {
const number = ToNumber(value);
if (!NumberIsFinite(number)) throw new RangeError('infinity is out of range');
if (!IsIntegralNumber(number)) throw new RangeError(`unsupported fractional value ${value}`);
if (number === 0) return 0; // ℝ(value) in spec text; converts -0 to 0
return number;
}
// This convenience function isn't in the spec, but is useful in the polyfill
// for DRY and better error messages.
export function RequireString(value) {
if (Type(value) !== 'String') {
// Use String() to ensure that Symbols won't throw
throw new TypeError(`expected a string, not ${StringCtor(value)}`);
}
return value;
}
// This function is an enum in the spec, but it's helpful to make it a
// function in the polyfill.
function ToPrimitiveAndRequireString(value) {
value = ToPrimitive(value, StringCtor);
return RequireString(value);
}
const BUILTIN_CASTS = new Map([
['year', ToIntegerWithTruncation],
['month', ToPositiveIntegerWithTruncation],
['monthCode', ToPrimitiveAndRequireString],
['day', ToPositiveIntegerWithTruncation],
['hour', ToIntegerWithTruncation],
['minute', ToIntegerWithTruncation],
['second', ToIntegerWithTruncation],
['millisecond', ToIntegerWithTruncation],
['microsecond', ToIntegerWithTruncation],
['nanosecond', ToIntegerWithTruncation],
['years', ToIntegerIfIntegral],
['months', ToIntegerIfIntegral],
['weeks', ToIntegerIfIntegral],
['days', ToIntegerIfIntegral],
['hours', ToIntegerIfIntegral],
['minutes', ToIntegerIfIntegral],
['seconds', ToIntegerIfIntegral],
['milliseconds', ToIntegerIfIntegral],
['microseconds', ToIntegerIfIntegral],
['nanoseconds', ToIntegerIfIntegral],
['offset', ToPrimitiveAndRequireString]
]);
const BUILTIN_DEFAULTS = new Map([
['hour', 0],
['minute', 0],
['second', 0],
['millisecond', 0],
['microsecond', 0],
['nanosecond', 0]
]);
// each item is [plural, singular, category]
const SINGULAR_PLURAL_UNITS = [
['years', 'year', 'date'],
['months', 'month', 'date'],
['weeks', 'week', 'date'],
['days', 'day', 'date'],
['hours', 'hour', 'time'],
['minutes', 'minute', 'time'],
['seconds', 'second', 'time'],
['milliseconds', 'millisecond', 'time'],
['microseconds', 'microsecond', 'time'],
['nanoseconds', 'nanosecond', 'time']
];
const SINGULAR_FOR = new Map(SINGULAR_PLURAL_UNITS);
const PLURAL_FOR = new Map(SINGULAR_PLURAL_UNITS.map(([p, s]) => [s, p]));
const UNITS_DESCENDING = SINGULAR_PLURAL_UNITS.map(([, s]) => s);
const DURATION_FIELDS = [
'days',
'hours',
'microseconds',
'milliseconds',
'minutes',
'months',
'nanoseconds',
'seconds',
'weeks',
'years'
];
import * as PARSE from './regex.mjs';
export {
Call,
CompletionRecord,
GetIterator,
GetMethod,
HasOwnProperty,
IsIntegralNumber,
IteratorClose,
IteratorStep,
IteratorValue,
ToNumber,
ToObject,
ToPrimitive,
ToString,
Type
};
const IntlDateTimeFormatEnUsCache = new Map();
function getIntlDateTimeFormatEnUsForTimeZone(timeZoneIdentifier) {
const lowercaseIdentifier = ASCIILowercase(timeZoneIdentifier);
let instance = IntlDateTimeFormatEnUsCache.get(lowercaseIdentifier);
if (instance === undefined) {
instance = new IntlDateTimeFormat('en-us', {
timeZone: lowercaseIdentifier,
hour12: false,
era: 'short',
year: 'numeric',
month: 'numeric',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
IntlDateTimeFormatEnUsCache.set(lowercaseIdentifier, instance);
}
return instance;
}
// copied from es-abstract/2024/CopyDataProperties.js
// with modifications per Temporal spec/mainadditions.html
export function CopyDataProperties(target, source, excludedKeys, excludedValues) {
if (Type(target) !== 'Object') {
throw new $TypeError('Assertion failed: "target" must be an Object');
}
if (!IsArray(excludedKeys) || !every(excludedKeys, IsPropertyKey)) {
throw new $TypeError('Assertion failed: "excludedKeys" must be a List of Property Keys');
}
if (excludedValues !== undefined && !IsArray(excludedValues)) {
throw new $TypeError('Assertion failed: "excludedValues" must be a List of ECMAScript language values');
}
if (typeof source === 'undefined' || source === null) {
return;
}
var from = ToObject(source);
var keys = OwnPropertyKeys(from);
forEach(keys, function (nextKey) {
var excluded = some(excludedKeys, function (e) {
return SameValue(e, nextKey) === true;
});
if (excluded) return;
var enumerable =
$isEnumerable(from, nextKey) ||
// this is to handle string keys being non-enumerable in older engines
(typeof source === 'string' && nextKey >= 0 && IsIntegralNumber(ToNumber(nextKey)));
if (enumerable) {
var propValue = Get(from, nextKey);
if (excludedValues !== undefined) {
forEach(excludedValues, function (e) {
if (SameValue(e, propValue) === true) {
excluded = true;
}
});
}
if (excluded === false) CreateDataPropertyOrThrow(target, nextKey, propValue);
}
});
}
export function IsTemporalInstant(item) {
return HasSlot(item, EPOCHNANOSECONDS) && !HasSlot(item, TIME_ZONE, CALENDAR);
}
export function IsTemporalTimeZone(item) {
return HasSlot(item, TIMEZONE_ID);
}
export function IsTemporalCalendar(item) {
return HasSlot(item, CALENDAR_ID);
}
export function IsTemporalDuration(item) {
return HasSlot(item, YEARS, MONTHS, DAYS, HOURS, MINUTES, SECONDS, MILLISECONDS, MICROSECONDS, NANOSECONDS);
}
export function IsTemporalDate(item) {
return HasSlot(item, DATE_BRAND);
}
export function IsTemporalTime(item) {
return (
HasSlot(item, ISO_HOUR, ISO_MINUTE, ISO_SECOND, ISO_MILLISECOND, ISO_MICROSECOND, ISO_NANOSECOND) &&
!HasSlot(item, ISO_YEAR, ISO_MONTH, ISO_DAY)
);
}
export function IsTemporalDateTime(item) {
return HasSlot(
item,
ISO_YEAR,
ISO_MONTH,
ISO_DAY,
ISO_HOUR,
ISO_MINUTE,
ISO_SECOND,
ISO_MILLISECOND,
ISO_MICROSECOND,
ISO_NANOSECOND
);
}
export function IsTemporalYearMonth(item) {
return HasSlot(item, YEAR_MONTH_BRAND);
}
export function IsTemporalMonthDay(item) {
return HasSlot(item, MONTH_DAY_BRAND);
}
export function IsTemporalZonedDateTime(item) {
return HasSlot(item, EPOCHNANOSECONDS, TIME_ZONE, CALENDAR);
}
export function RejectTemporalLikeObject(item) {
if (HasSlot(item, CALENDAR) || HasSlot(item, TIME_ZONE)) {
throw new TypeError('with() does not support a calendar or timeZone property');
}
if (IsTemporalTime(item)) {
throw new TypeError('with() does not accept Temporal.PlainTime, use withPlainTime() instead');
}
if (item.calendar !== undefined) {
throw new TypeError('with() does not support a calendar property');
}
if (item.timeZone !== undefined) {
throw new TypeError('with() does not support a timeZone property');
}
}
export function MaybeFormatCalendarAnnotation(calendar, showCalendar) {
if (showCalendar === 'never') return '';
return FormatCalendarAnnotation(ToTemporalCalendarIdentifier(calendar), showCalendar);
}
export function FormatCalendarAnnotation(id, showCalendar) {
if (showCalendar === 'never') return '';
if (showCalendar === 'auto' && id === 'iso8601') return '';
const flag = showCalendar === 'critical' ? '!' : '';
return `[${flag}u-ca=${id}]`;
}
// Not a separate abstract operation in the spec, because it only occurs in one
// place: ParseISODateTime. In the code it's more convenient to split up
// ParseISODateTime for the YYYY-MM, MM-DD, and THH:MM:SS parse goals, so it's
// repeated four times.
function processAnnotations(annotations) {
let calendar;
let calendarWasCritical = false;
for (const [, critical, key, value] of Call(StringPrototypeMatchAll, annotations, [PARSE.annotation])) {
if (key === 'u-ca') {
if (calendar === undefined) {
calendar = value;
calendarWasCritical = critical === '!';
} else if (critical === '!' || calendarWasCritical) {
throw new RangeError(`Invalid annotations in ${annotations}: more than one u-ca present with critical flag`);
}
} else if (critical === '!') {
throw new RangeError(`Unrecognized annotation: !${key}=${value}`);
}
}
return calendar;
}
export function ParseISODateTime(isoString) {
// ZDT is the superset of fields for every other Temporal type
const match = PARSE.zoneddatetime.exec(isoString);
if (!match) throw new RangeError(`invalid ISO 8601 string: ${isoString}`);
let yearString = match[1];
if (yearString[0] === '\u2212') yearString = `-${yearString.slice(1)}`;
if (yearString === '-000000') throw new RangeError(`invalid ISO 8601 string: ${isoString}`);
const year = +yearString;
const month = +(match[2] ?? match[4] ?? 1);
const day = +(match[3] ?? match[5] ?? 1);
const hasTime = match[6] !== undefined;
const hour = +(match[6] ?? 0);
const minute = +(match[7] ?? match[10] ?? 0);
let second = +(match[8] ?? match[11] ?? 0);
if (second === 60) second = 59;
const fraction = (match[9] ?? match[12] ?? '') + '000000000';
const millisecond = +fraction.slice(0, 3);
const microsecond = +fraction.slice(3, 6);
const nanosecond = +fraction.slice(6, 9);
let offset;
let z = false;
if (match[13]) {
offset = undefined;
z = true;
} else if (match[14]) {
offset = match[14];
}
const tzAnnotation = match[15];
const calendar = processAnnotations(match[16]);
RejectDateTime(year, month, day, hour, minute, second, millisecond, microsecond, nanosecond);
return {
year,
month,
day,
hasTime,
hour,
minute,
second,
millisecond,
microsecond,
nanosecond,
tzAnnotation,
offset,
z,
calendar
};
}
export function ParseTemporalInstantString(isoString) {
const result = ParseISODateTime(isoString);
if (!result.z && !result.offset) throw new RangeError('Temporal.Instant requires a time zone offset');
return result;
}
export function ParseTemporalZonedDateTimeString(isoString) {
const result = ParseISODateTime(isoString);
if (!result.tzAnnotation) throw new RangeError('Temporal.ZonedDateTime requires a time zone ID in brackets');
return result;
}
export function ParseTemporalDateTimeString(isoString) {
return ParseISODateTime(isoString);
}
export function ParseTemporalDateString(isoString) {
return ParseISODateTime(isoString);
}
export function ParseTemporalTimeString(isoString) {
const match = PARSE.time.exec(isoString);
let hour, minute, second, millisecond, microsecond, nanosecond;
if (match) {
hour = +(match[1] ?? 0);
minute = +(match[2] ?? match[5] ?? 0);
second = +(match[3] ?? match[6] ?? 0);
if (second === 60) second = 59;
const fraction = (match[4] ?? match[7] ?? '') + '000000000';
millisecond = +fraction.slice(0, 3);
microsecond = +fraction.slice(3, 6);
nanosecond = +fraction.slice(6, 9);
processAnnotations(match[10]); // ignore found calendar
if (match[8]) throw new RangeError('Z designator not supported for PlainTime');
} else {
let z, hasTime;
({ hasTime, hour, minute, second, millisecond, microsecond, nanosecond, z } = ParseISODateTime(isoString));
if (!hasTime) throw new RangeError(`time is missing in string: ${isoString}`);
if (z) throw new RangeError('Z designator not supported for PlainTime');
}
// if it's a date-time string, OK
if (/[tT ][0-9][0-9]/.test(isoString)) {
return { hour, minute, second, millisecond, microsecond, nanosecond };
}
// Reject strings that are ambiguous with PlainMonthDay or PlainYearMonth.
try {
const { month, day } = ParseTemporalMonthDayString(isoString);
RejectISODate(1972, month, day);
} catch {
try {
const { year, month } = ParseTemporalYearMonthString(isoString);
RejectISODate(year, month, 1);
} catch {
return { hour, minute, second, millisecond, microsecond, nanosecond };
}
}
throw new RangeError(`invalid ISO 8601 time-only string ${isoString}; may need a T prefix`);
}
export function ParseTemporalYearMonthString(isoString) {
const match = PARSE.yearmonth.exec(isoString);
let year, month, calendar, referenceISODay;
if (match) {
let yearString = match[1];
if (yearString[0] === '\u2212') yearString = `-${yearString.slice(1)}`;
if (yearString === '-000000') throw new RangeError(`invalid ISO 8601 string: ${isoString}`);
year = +yearString;
month = +match[2];
calendar = processAnnotations(match[3]);
referenceISODay = 1;
if (calendar !== undefined && calendar !== 'iso8601') {
throw new RangeError('YYYY-MM format is only valid with iso8601 calendar');
}
} else {
let z;
({ year, month, calendar, day: referenceISODay, z } = ParseISODateTime(isoString));
if (z) throw new RangeError('Z designator not supported for PlainYearMonth');
}
return { year, month, calendar, referenceISODay };
}
export function ParseTemporalMonthDayString(isoString) {
const match = PARSE.monthday.exec(isoString);
let month, day, calendar, referenceISOYear;
if (match) {
month = +match[1];
day = +match[2];
calendar = processAnnotations(match[3]);
if (calendar !== undefined && calendar !== 'iso8601') {
throw new RangeError('MM-DD format is only valid with iso8601 calendar');
}
} else {
let z;
({ month, day, calendar, year: referenceISOYear, z } = ParseISODateTime(isoString));
if (z) throw new RangeError('Z designator not supported for PlainMonthDay');
}
return { month, day, calendar, referenceISOYear };
}
const TIMEZONE_IDENTIFIER = new RegExp(`^${PARSE.timeZoneID.source}$`, 'i');
const OFFSET_IDENTIFIER = new RegExp(`^${PARSE.offsetIdentifier.source}$`);
function throwBadTimeZoneStringError(timeZoneString) {
// Offset identifiers only support minute precision, but offsets in ISO
// strings support nanosecond precision. If the identifier is invalid but
// it's a valid ISO offset, then it has sub-minute precision. Show a clearer
// error message in that case.
const msg = OFFSET.test(timeZoneString) ? 'Seconds not allowed in offset time zone' : 'Invalid time zone';
throw new RangeError(`${msg}: ${timeZoneString}`);
}
export function ParseTimeZoneIdentifier(identifier) {
if (!TIMEZONE_IDENTIFIER.test(identifier)) {
throwBadTimeZoneStringError(identifier);
}
if (OFFSET_IDENTIFIER.test(identifier)) {
const offsetNanoseconds = ParseDateTimeUTCOffset(identifier);
// The regex limits the input to minutes precision, so we know that the
// division below will result in an integer.
return { offsetMinutes: offsetNanoseconds / 60e9 };
}
return { tzName: identifier };
}
// This operation doesn't exist in the spec, but in the polyfill it's split from
// ParseTemporalTimeZoneString so that parsing can be tested separately from the
// logic of converting parsed values into a named or offset identifier.
export function ParseTemporalTimeZoneStringRaw(timeZoneString) {
if (TIMEZONE_IDENTIFIER.test(timeZoneString)) {
return { tzAnnotation: timeZoneString, offset: undefined, z: false };
}
try {
// Try parsing ISO string instead
const { tzAnnotation, offset, z } = ParseISODateTime(timeZoneString);
if (z || tzAnnotation || offset) {
return { tzAnnotation, offset, z };
}
} catch {
// fall through
}
throwBadTimeZoneStringError(timeZoneString);
}
export function ParseTemporalTimeZoneString(stringIdent) {
const { tzAnnotation, offset, z } = ParseTemporalTimeZoneStringRaw(stringIdent);
if (tzAnnotation) return ParseTimeZoneIdentifier(tzAnnotation);
if (z) return ParseTimeZoneIdentifier('UTC');
if (offset) return ParseTimeZoneIdentifier(offset);
throw new Error('this line should not be reached');
}
export function ParseTemporalDurationString(isoString) {
const match = PARSE.duration.exec(isoString);
if (!match) throw new RangeError(`invalid duration: ${isoString}`);
if (match.slice(2).every((element) => element === undefined)) {
throw new RangeError(`invalid duration: ${isoString}`);
}
const sign = match[1] === '-' || match[1] === '\u2212' ? -1 : 1;
const years = match[2] === undefined ? 0 : ToIntegerWithTruncation(match[2]) * sign;
const months = match[3] === undefined ? 0 : ToIntegerWithTruncation(match[3]) * sign;
const weeks = match[4] === undefined ? 0 : ToIntegerWithTruncation(match[4]) * sign;
const days = match[5] === undefined ? 0 : ToIntegerWithTruncation(match[5]) * sign;
const hours = match[6] === undefined ? 0 : ToIntegerWithTruncation(match[6]) * sign;
let fHours = match[7];
let minutesStr = match[8];
let fMinutes = match[9];
let secondsStr = match[10];
let fSeconds = match[11];
let minutes = 0;
let seconds = 0;
// fractional hours, minutes, or seconds, expressed in whole nanoseconds:
let excessNanoseconds = 0;
if (fHours !== undefined) {
if (minutesStr ?? fMinutes ?? secondsStr ?? fSeconds ?? false) {
throw new RangeError('only the smallest unit can be fractional');
}
excessNanoseconds = ToIntegerWithTruncation((fHours + '000000000').slice(0, 9)) * 3600 * sign;
} else {
minutes = minutesStr === undefined ? 0 : ToIntegerWithTruncation(minutesStr) * sign;
if (fMinutes !== undefined) {
if (secondsStr ?? fSeconds ?? false) {
throw new RangeError('only the smallest unit can be fractional');
}
excessNanoseconds = ToIntegerWithTruncation((fMinutes + '000000000').slice(0, 9)) * 60 * sign;
} else {
seconds = secondsStr === undefined ? 0 : ToIntegerWithTruncation(secondsStr) * sign;
if (fSeconds !== undefined) {
excessNanoseconds = ToIntegerWithTruncation((fSeconds + '000000000').slice(0, 9)) * sign;
}
}
}
const nanoseconds = excessNanoseconds % 1000;
const microseconds = MathTrunc(excessNanoseconds / 1000) % 1000;
const milliseconds = MathTrunc(excessNanoseconds / 1e6) % 1000;
seconds += MathTrunc(excessNanoseconds / 1e9) % 60;
minutes += MathTrunc(excessNanoseconds / 60e9);
RejectDuration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
return { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds };
}
export function RegulateISODate(year, month, day, overflow) {
switch (overflow) {
case 'reject':
RejectISODate(year, month, day);
break;
case 'constrain':
({ year, month, day } = ConstrainISODate(year, month, day));
break;
}
return { year, month, day };
}
export function RegulateTime(hour, minute, second, millisecond, microsecond, nanosecond, overflow) {
switch (overflow) {
case 'reject':
RejectTime(hour, minute, second, millisecond, microsecond, nanosecond);
break;
case 'constrain':
({ hour, minute, second, millisecond, microsecond, nanosecond } = ConstrainTime(
hour,
minute,
second,
millisecond,
microsecond,
nanosecond
));
break;
}
return { hour, minute, second, millisecond, microsecond, nanosecond };
}
export function RegulateISOYearMonth(year, month, overflow) {
const referenceISODay = 1;
switch (overflow) {
case 'reject':
RejectISODate(year, month, referenceISODay);
break;
case 'constrain':
({ year, month } = ConstrainISODate(year, month));
break;
}
return { year, month };
}
export function ToTemporalDurationRecord(item) {
if (Type(item) !== 'Object') {
return ParseTemporalDurationString(RequireString(item));
}
if (IsTemporalDuration(item)) {
return {
years: GetSlot(item, YEARS),
months: GetSlot(item, MONTHS),
weeks: GetSlot(item, WEEKS),
days: GetSlot(item, DAYS),
hours: GetSlot(item, HOURS),
minutes: GetSlot(item, MINUTES),
seconds: GetSlot(item, SECONDS),
milliseconds: GetSlot(item, MILLISECONDS),
microseconds: GetSlot(item, MICROSECONDS),
nanoseconds: GetSlot(item, NANOSECONDS)
};
}
const result = {
years: 0,
months: 0,
weeks: 0,
days: 0,
hours: 0,
minutes: 0,
seconds: 0,
milliseconds: 0,
microseconds: 0,
nanoseconds: 0
};
let partial = ToTemporalPartialDurationRecord(item);
for (let index = 0; index < DURATION_FIELDS.length; index++) {
const property = DURATION_FIELDS[index];
const value = partial[property];
if (value !== undefined) {
result[property] = value;
}
}
let { years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds } = result;
RejectDuration(years, months, weeks, days, hours, minutes, seconds, milliseconds, microseconds, nanoseconds);
return result;
}
export function ToTemporalPartialDurationRecord(temporalDurationLike) {
if (Type(temporalDurationLike) !== 'Object') {
throw new TypeError('invalid duration-like');
}
const result = {
years: undefined,
months: undefined,
weeks: undefined,
days: undefined,
hours: undefined,
minutes: undefined,
seconds: undefined,
milliseconds: undefined,
microseconds: undefined,
nanoseconds: undefined
};
let any = false;
for (let index = 0; index < DURATION_FIELDS.length; index++) {
const property = DURATION_FIELDS[index];
const value = temporalDurationLike[property];
if (value !== undefined) {
any = true;
result[property] = ToIntegerIfIntegral(value);
}
}
if (!any) {
throw new TypeError('invalid duration-like');
}
return result;
}
export function ToLimitedTemporalDuration(item, disallowedProperties) {
let record = ToTemporalDurationRecord(item);
for (const property of disallowedProperties) {
if (record[property] !== 0) {
throw new RangeError(
`Duration field ${property} not supported by Temporal.Instant. Try Temporal.ZonedDateTime instead.`
);
}
}
return record;
}
export function ToTemporalOverflow(options) {
if (options === undefined) return 'constrain';
return GetOption(options, 'overflow', ['constrain', 'reject'], 'constrain');
}
export function ToTemporalDisambiguation(options) {
if (options === undefined) return 'compatible';
return GetOption(options, 'disambiguation', ['compatible', 'earlier', 'later', 'reject'], 'compatible');
}
export function ToTemporalRoundingMode(options, fallback) {
return GetOption(
options,
'roundingMode',
['ceil', 'floor', 'expand', 'trunc', 'halfCeil', 'halfFloor', 'halfExpand', 'halfTrunc', 'halfEven'],
fallback
);
}
export function NegateTemporalRoundingMode(roundingMode) {
switch (roundingMode) {
case 'ceil':
return 'floor';
case 'floor':
return 'ceil';
case 'halfCeil':
return 'halfFloor';
case 'halfFloor':
return 'halfCeil';
default:
return roundingMode;
}
}
export function ToTemporalOffset(options, fallback) {
if (options === undefined) return fallback;
return GetOption(options, 'offset', ['prefer', 'use', 'ignore', 'reject'], fallback);
}
export function ToCalendarNameOption(options) {
return GetOption(options, 'calendarName', ['auto', 'always', 'never', 'critical'], 'auto');
}
export function ToTimeZoneNameOption(options) {
return GetOption(options, 'timeZoneName', ['auto', 'never', 'critical'], 'auto');
}
export function ToShowOffsetOption(options) {
return GetOption(options, 'offset', ['auto', 'never'], 'auto');
}
export function ToTemporalRoundingIncrement(options) {
let increment = options.roundingIncrement;
if (increment === undefined) return 1;
increment = ToNumber(increment);
if (!NumberIsFinite(increment)) {
throw new RangeError('roundingIncrement must be finite');
}
const integerIncrement = MathTrunc(increment);
if (integerIncrement < 1 || integerIncrement > 1e9) {
throw new RangeError(`roundingIncrement must be at least 1 and at most 1e9, not ${increment}`);
}
return integerIncrement;
}
export function ValidateTemporalRoundingIncrement(increment, dividend, inclusive) {
const maximum = inclusive ? dividend : dividend - 1;
if (increment > maximum) {
throw new RangeError(`roundingIncrement must be at least 1 and less than ${maximum}, not ${increment}`);
}
if (dividend % increment !== 0) {
throw new RangeError(`Rounding increment must divide evenly into ${dividend}`);
}
}
export function ToFractionalSecondDigits(normalizedOptions) {
let digitsValue = normalizedOptions.fractionalSecondDigits;
if (digitsValue === undefined) return 'auto';
if (Type(digitsValue) !== 'Number') {
if (ToString(digitsValue) !== 'auto') {
throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${digitsValue}`);
}
return 'auto';
}
const digitCount = MathFloor(digitsValue);
if (!NumberIsFinite(digitCount) || digitCount < 0 || digitCount > 9) {
throw new RangeError(`fractionalSecondDigits must be 'auto' or 0 through 9, not ${digitsValue}`);
}
return digitCount;
}
export function ToSecondsStringPrecisionRecord(smallestUnit, precision) {
switch (smallestUnit) {
case 'minute':
return { precision: 'minute', unit: 'minute', increment: 1 };
case 'second':
return { precision: 0, unit: 'second', increment: 1 };
case 'millisecond':
return { precision: 3, unit: 'millisecond', increment: 1 };
case 'microsecond':
return { precision: 6, unit: 'microsecond', increment: 1 };
case 'nanosecond':
return { precision: 9, unit: 'nanosecond', increment: 1 };
default: // fall through if option not given
}
switch (precision) {
case 'auto':
return { precision, unit: 'nanosecond', increment: 1 };
case 0:
return { precision, unit: 'second', increment: 1 };
case 1:
case 2:
case 3:
return { precision, unit: 'millisecond', increment: 10 ** (3 - precision) };
case 4:
case 5:
case 6:
return { precision, unit: 'microsecond', increment: 10 ** (6 - precision) };
case 7:
case 8:
case 9:
return { precision, unit: 'nanosecond', increment: 10 ** (9 - precision) };
}
}
export const REQUIRED = Symbol('~required~');
export function GetTemporalUnit(options, key, unitGroup, requiredOrDefault, extraValues = []) {
const allowedSingular = [];
for (let index = 0; index < SINGULAR_PLURAL_UNITS.length; index++) {
const unitInfo = SINGULAR_PLURAL_UNITS[index];
const singular = unitInfo[1];
const category = unitInfo[2];
if (unitGroup === 'datetime' || unitGroup === category) {
allowedSingular.push(singular);
}
}
Call(ArrayPrototypePush, allowedSingular, extraValues);
let defaultVal = requiredOrDefault;
if (defaultVal === REQUIRED) {
defaultVal = undefined;
} else if (defaultVal !== undefined) {
allowedSingular.push(defaultVal);
}
const allowedValues = [];
Call(ArrayPrototypePush, allowedValues, allowedSingular);
for (let index = 0; index < allowedSingular.length; index++) {