@aemforms/af-formatters 0.22.25 → 0.22.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,958 @@
1
+ 'use strict';
2
+
3
+ /*************************************************************************
4
+ * ADOBE CONFIDENTIAL
5
+ * ___________________
6
+ *
7
+ * Copyright 2022 Adobe
8
+ * All Rights Reserved.
9
+ *
10
+ * NOTICE: All information contained herein is, and remains
11
+ * the property of Adobe and its suppliers, if any. The intellectual
12
+ * and technical concepts contained herein are proprietary to Adobe
13
+ * and its suppliers and are protected by all applicable intellectual
14
+ * property laws, including trade secret and copyright laws.
15
+ * Dissemination of this information or reproduction of this material
16
+ * is strictly forbidden unless prior written permission is obtained
17
+ * from Adobe.
18
+ **************************************************************************/
19
+ /**
20
+ * https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
21
+ * Credit: https://git.corp.adobe.com/dc/dfl/blob/master/src/patterns/parseDateTimeSkeleton.js
22
+ * Created a separate library to be used elsewhere as well.
23
+ */
24
+ const DATE_TIME_REGEX =
25
+ // eslint-disable-next-line max-len
26
+ /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvV]{1,5}|[zZOvVxX]{1,3}|S{1,3}|'(?:[^']|'')*')|[^a-zA-Z']+/g;
27
+
28
+ const ShorthandStyles$1 = ["full", "long", "medium", "short"];
29
+
30
+ function getSkeleton(skeleton, language) {
31
+ if (ShorthandStyles$1.find(type => skeleton.includes(type))) {
32
+ const parsed = parseDateStyle(skeleton, language);
33
+ const result = [];
34
+ const symbols = {
35
+ month : 'M',
36
+ year : 'Y',
37
+ day : 'd'
38
+ };
39
+ parsed.forEach(([type, option, length]) => {
40
+ if (type in symbols) {
41
+ result.push(Array(length).fill(symbols[type]).join(''));
42
+ } else if (type === 'literal') {
43
+ result.push(option);
44
+ }
45
+ });
46
+ return result.join('');
47
+ }
48
+ return skeleton;
49
+ }
50
+
51
+ /**
52
+ *
53
+ * @param skeleton shorthand style for the date concatenated with shorthand style of time. The
54
+ * Shorthand style for both date and time is one of ['full', 'long', 'medium', 'short'].
55
+ * @param language {string} language to parse the date shorthand style
56
+ * @returns {[*,string][]}
57
+ */
58
+ function parseDateStyle(skeleton, language) {
59
+ const options = {};
60
+ // the skeleton could have two keywords -- one for date, one for time
61
+ const styles = skeleton.split(/\s/).filter(s => s.length);
62
+ options.dateStyle = styles[0];
63
+ if (styles.length > 1) options.timeStyle = styles[1];
64
+
65
+ const testDate = new Date(2000, 2, 1, 2, 3, 4);
66
+ const parts = new Intl.DateTimeFormat(language, options).formatToParts(testDate);
67
+ // oddly, the formatted month name can be different from the standalone month name
68
+ const formattedMarch = parts.find(p => p.type === 'month').value;
69
+ const longMarch = new Intl.DateTimeFormat(language, {month: 'long'}).formatToParts(testDate)[0].value;
70
+ const shortMarch = new Intl.DateTimeFormat(language, {month: 'short'}).formatToParts(testDate)[0].value;
71
+ const result = [];
72
+ parts.forEach(({type, value}) => {
73
+ let option;
74
+ if (type === 'month') {
75
+ option = {
76
+ [formattedMarch]: skeleton === 'medium' ? 'short' : 'long',
77
+ [longMarch]: 'long',
78
+ [shortMarch]: 'short',
79
+ '03': '2-digit',
80
+ '3': 'numeric'
81
+ }[value];
82
+ }
83
+ if (type === 'year') option = {'2000': 'numeric', '00': '2-digit'}[value];
84
+ if (['day', 'hour', 'minute', 'second'].includes(type)) option = value.length === 2 ? '2-digit' : 'numeric';
85
+ if (type === 'literal') option = value;
86
+ if (type === 'dayPeriod') option = 'short';
87
+ result.push([type, option, value.length]);
88
+ });
89
+ return result;
90
+ }
91
+
92
+ /**
93
+ * Parse Date time skeleton into Intl.DateTimeFormatOptions parts
94
+ * Ref: https://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
95
+ */
96
+ function parseDateTimeSkeleton(skeleton, language) {
97
+ if (ShorthandStyles$1.find(type => skeleton.includes(type))) {
98
+ return parseDateStyle(skeleton, language);
99
+ }
100
+ const result = [];
101
+ skeleton.replace(DATE_TIME_REGEX, match => {
102
+ const len = match.length;
103
+ switch (match[0]) {
104
+ // Era
105
+ case 'G':
106
+ result.push(['era', len === 4 ? 'long' : len === 5 ? 'narrow' : 'short', len]);
107
+ break;
108
+ // Year
109
+ case 'y':
110
+ result.push(['year', len === 2 ? '2-digit' : 'numeric', len]);
111
+ break;
112
+ case 'Y':
113
+ case 'u':
114
+ case 'U':
115
+ case 'r':
116
+ throw new RangeError(
117
+ '`Y/u/U/r` (year) patterns are not supported, use `y` instead'
118
+ );
119
+ // Quarter
120
+ case 'q':
121
+ case 'Q':
122
+ throw new RangeError('`q/Q` (quarter) patterns are not supported');
123
+ // Month
124
+ case 'M':
125
+ case 'L':
126
+ result.push(['month', ['numeric', '2-digit', 'short', 'long', 'narrow'][len - 1], len]);
127
+ break;
128
+ // Week
129
+ case 'w':
130
+ case 'W':
131
+ throw new RangeError('`w/W` (week) patterns are not supported');
132
+ case 'd':
133
+ result.push(['day', ['numeric', '2-digit'][len - 1], len]);
134
+ break;
135
+ case 'D':
136
+ case 'F':
137
+ case 'g':
138
+ throw new RangeError(
139
+ '`D/F/g` (day) patterns are not supported, use `d` instead'
140
+ );
141
+ // Weekday
142
+ case 'E':
143
+ result.push(['weekday', ['short', 'short', 'short', 'long', 'narrow', 'narrow'][len - 1], len]);
144
+ break;
145
+ case 'e':
146
+ if (len < 4) {
147
+ throw new RangeError('`e..eee` (weekday) patterns are not supported');
148
+ }
149
+ result.push(['weekday', ['short', 'long', 'narrow', 'short'][len - 4], len]);
150
+ break;
151
+ case 'c':
152
+ if (len < 3 || len > 5) {
153
+ throw new RangeError('`c, cc, cccccc` (weekday) patterns are not supported');
154
+ }
155
+ result.push(['weekday', ['short', 'long', 'narrow', 'short'][len - 3], len]);
156
+ break;
157
+ // Period
158
+ case 'a': // AM, PM
159
+ result.push(['hour12', true, 1]);
160
+ break;
161
+ case 'b': // am, pm, noon, midnight
162
+ case 'B': // flexible day periods
163
+ throw new RangeError(
164
+ '`b/B` (period) patterns are not supported, use `a` instead'
165
+ );
166
+ // Hour
167
+ case 'h':
168
+ result.push(['hourCycle', 'h12']);
169
+ result.push(['hour', ['numeric', '2-digit'][len - 1], len]);
170
+ break;
171
+ case 'H':
172
+ result.push(['hourCycle', 'h23', 1]);
173
+ result.push(['hour', ['numeric', '2-digit'][len - 1], len]);
174
+ break;
175
+ case 'K':
176
+ result.push(['hourCycle', 'h11', 1]);
177
+ result.push(['hour', ['numeric', '2-digit'][len - 1], len]);
178
+ break;
179
+ case 'k':
180
+ result.push(['hourCycle', 'h24', 1]);
181
+ result.push(['hour', ['numeric', '2-digit'][len - 1], len]);
182
+ break;
183
+ case 'j':
184
+ case 'J':
185
+ case 'C':
186
+ throw new RangeError(
187
+ '`j/J/C` (hour) patterns are not supported, use `h/H/K/k` instead'
188
+ );
189
+ // Minute
190
+ case 'm':
191
+ result.push(['minute', ['numeric', '2-digit'][len - 1], len]);
192
+ break;
193
+ // Second
194
+ case 's':
195
+ result.push(['second', ['numeric', '2-digit'][len - 1], len]);
196
+ break;
197
+ case 'S':
198
+ result.push(['fractionalSecondDigits', len, len]);
199
+ break;
200
+ case 'A':
201
+ throw new RangeError(
202
+ '`S/A` (millisecond) patterns are not supported, use `s` instead'
203
+ );
204
+ // Zone
205
+ case 'O': // timeZone GMT-8 or GMT-08:00
206
+ result.push(['timeZoneName', len < 4 ? 'shortOffset' : 'longOffset', len]);
207
+ result.push(['x-timeZoneName', len < 4 ? 'O' : 'OOOO', len]);
208
+ break;
209
+ case 'X': // 1, 2, 3, 4: The ISO8601 varios formats
210
+ case 'x': // 1, 2, 3, 4: The ISO8601 varios formats
211
+ case 'Z': // 1..3, 4, 5: The ISO8601 varios formats
212
+ // Z, ZZ, ZZZ should produce -0800
213
+ // ZZZZ should produce GMT-08:00
214
+ // ZZZZZ should produce -8:00 or -07:52:58
215
+ result.push(['timeZoneName', 'longOffset', 1]);
216
+ result.push(['x-timeZoneName', match, 1]);
217
+ break;
218
+ case 'z': // 1..3, 4: specific non-location format
219
+ case 'v': // 1, 4: generic non-location format
220
+ case 'V': // 1, 2, 3, 4: time zone ID or city
221
+ throw new RangeError(
222
+ 'z/v/V` (timeZone) patterns are not supported, use `X/x/Z/O` instead'
223
+ );
224
+ case '\'':
225
+ result.push(['literal', match.slice(1, -1).replace(/''/g, '\''), -1]);
226
+ break;
227
+ default:
228
+ result.push(['literal', match, -1]);
229
+ }
230
+ return '';
231
+ });
232
+ return result;
233
+ }
234
+
235
+ /*************************************************************************
236
+ * ADOBE CONFIDENTIAL
237
+ * ___________________
238
+ *
239
+ * Copyright 2022 Adobe
240
+ * All Rights Reserved.
241
+ *
242
+ * NOTICE: All information contained herein is, and remains
243
+ * the property of Adobe and its suppliers, if any. The intellectual
244
+ * and technical concepts contained herein are proprietary to Adobe
245
+ * and its suppliers and are protected by all applicable intellectual
246
+ * property laws, including trade secret and copyright laws.
247
+ * Dissemination of this information or reproduction of this material
248
+ * is strictly forbidden unless prior written permission is obtained
249
+ * from Adobe.
250
+ **************************************************************************/
251
+
252
+ // get the localized month names resulting from a given pattern
253
+ const twelveMonths = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11].map(m => new Date(2000, m, 1));
254
+
255
+ /**
256
+ * returns the name of all the months for a given locale and given Date Format Settings
257
+ * @param locale {string}
258
+ * @param options {string} instance of Intl.DateTimeFormatOptions
259
+ */
260
+ function monthNames(locale, options) {
261
+ return twelveMonths.map(month => {
262
+ const parts = new Intl.DateTimeFormat(locale, options).formatToParts(month);
263
+ const m = parts.find(p => p.type === 'month');
264
+ return m && m.value;
265
+ });
266
+ }
267
+
268
+ /**
269
+ * return an array of digits used by a given locale
270
+ * @param locale {string}
271
+ */
272
+ function digitChars(locale) {
273
+ return new Intl.NumberFormat(locale, {style:'decimal', useGrouping:false})
274
+ .format(9876543210)
275
+ .split('')
276
+ .reverse();
277
+ }
278
+
279
+ /**
280
+ * returns the calendar name used in a given locale
281
+ * @param locale {string}
282
+ */
283
+ function calendarName(locale) {
284
+ const parts = new Intl.DateTimeFormat(locale, {era:'short'}).formatToParts(new Date());
285
+ const era = parts.find(p => p.type === 'era')?.value;
286
+ return era === 'هـ' ? 'islamic' : 'gregory';
287
+ }
288
+
289
+ /**
290
+ * returns the representation of the time of day for a given language
291
+ * @param language {string}
292
+ */
293
+ function getDayPeriod(language) {
294
+ const morning = new Date(2000, 1, 1, 1, 1, 1);
295
+ const afternoon = new Date(2000, 1, 1, 16, 1, 1);
296
+ const df = new Intl.DateTimeFormat(language, {dateStyle: 'full', timeStyle: 'full'});
297
+ const am = df.formatToParts(morning).find(p => p.type === 'dayPeriod');
298
+ const pm = df.formatToParts(afternoon).find(p => p.type === 'dayPeriod');
299
+ if (!am || !pm) return null;
300
+ return {
301
+ regex: `(${am.value}|${pm.value})`,
302
+ fn: (period, obj) => obj.hour += (period === pm.value) ? 12 : 0
303
+ };
304
+ }
305
+
306
+ /**
307
+ * get the offset in MS, given a date and timezone
308
+ * @param dateObj {Date}
309
+ * @param timeZone {string}
310
+ */
311
+ function offsetMS(dateObj, timeZone) {
312
+ let tzOffset;
313
+ try {
314
+ tzOffset = new Intl.DateTimeFormat('en-US', {timeZone, timeZoneName: 'longOffset'}).format(dateObj);
315
+ } catch(e) {
316
+ return offsetMSFallback(dateObj, timeZone);
317
+ }
318
+ const offset = /GMT([+\-−])?(\d{1,2}):?(\d{0,2})?/.exec(tzOffset);
319
+ if (!offset) return 0;
320
+ const [sign, hours, minutes] = offset.slice(1);
321
+ const nHours = isNaN(parseInt(hours)) ? 0 : parseInt(hours);
322
+ const nMinutes = isNaN(parseInt(minutes)) ? 0 : parseInt(minutes);
323
+ const result = ((nHours * 60) + nMinutes) * 60 * 1000;
324
+ return sign === '-' ? - result : result;
325
+ }
326
+
327
+ function getTimezoneOffsetFrom(otherTimezone) {
328
+ var date = new Date();
329
+ function objFromStr(str) {
330
+ var array = str.replace(":", " ").split(" ");
331
+ return {
332
+ day: parseInt(array[0]),
333
+ hour: parseInt(array[1]),
334
+ minute: parseInt(array[2])
335
+ };
336
+ }
337
+ var str = date.toLocaleString('en-US', { timeZone: otherTimezone, day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23' });
338
+ var other = objFromStr(str);
339
+ str = date.toLocaleString('en-US', { day: 'numeric', hour: 'numeric', minute: 'numeric', hourCycle: 'h23' });
340
+ var myLocale = objFromStr(str);
341
+ var otherOffset = (other.day * 24 * 60) + (other.hour * 60) + (other.minute); // utc date + otherTimezoneDifference
342
+ var myLocaleOffset = (myLocale.day * 24 * 60) + (myLocale.hour * 60) + (myLocale.minute); // utc date + myTimeZoneDifference
343
+ // (utc date + otherZoneDifference) - (utc date + myZoneDifference) - (-1 * myTimeZoneDifference)
344
+ return otherOffset - myLocaleOffset - date.getTimezoneOffset();
345
+ }
346
+
347
+ function offsetMSFallback(dateObj, timezone) {
348
+ //const defaultOffset = dateObj.getTimezoneOffset();
349
+ const timezoneOffset = getTimezoneOffsetFrom(timezone);
350
+ return timezoneOffset * 60 * 1000;
351
+ }
352
+
353
+ /**
354
+ * adjust from the default JavaScript timezone to the default timezone
355
+ * @param dateObj {Date}
356
+ * @param timeZone {string}
357
+ */
358
+ function adjustTimeZone(dateObj, timeZone) {
359
+ if (dateObj === null) return null;
360
+ // const defaultOffset = new Intl.DateTimeFormat('en-US', { timeZoneName: 'longOffset'}).format(dateObj);
361
+ let baseDate = dateObj.getTime() - dateObj.getTimezoneOffset() * 60 * 1000;
362
+ const offset = offsetMS(dateObj, timeZone);
363
+ offsetMSFallback(dateObj, timeZone);
364
+ baseDate += - offset;
365
+
366
+
367
+ // get the offset for the default JS environment
368
+ // return days since the epoch
369
+ return new Date(baseDate);
370
+ }
371
+
372
+ /**
373
+ * in some cases, DateTimeFormat doesn't respect the 'numeric' vs. '2-digit' setting
374
+ * for time values. The function corrects that
375
+ * @param formattedParts instance of Intl.DateTimeFormatPart[]
376
+ * @param parsed
377
+ */
378
+ function fixDigits(formattedParts, parsed) {
379
+ ['hour', 'minute', 'second'].forEach(type => {
380
+ const defn = formattedParts.find(f => f.type === type);
381
+ if (!defn) return;
382
+ const fmt = parsed.find(pair => pair[0] === type)[1];
383
+ if (fmt === '2-digit' && defn.value.length === 1) defn.value = `0${defn.value}`;
384
+ if (fmt === 'numeric' && defn.value.length === 2 && defn.value.charAt(0) === '0') defn.value = defn.value.slice(1);
385
+ });
386
+ }
387
+
388
+ function fixYear(formattedParts, parsed) {
389
+ // two digit years are handled differently in DateTimeFormat. 00 becomes 1900
390
+ // providing a two digit year 0010 gets formatted to 10 and when parsed becomes 1910
391
+ // Hence we need to pad the year with 0 as required by the skeleton and mentioned in
392
+ // unicode. https://www.unicode.org/reports/tr35/tr35-dates.html#dfst-year
393
+ const defn = formattedParts.find(f => f.type === 'year');
394
+ if (!defn) return;
395
+ // eslint-disable-next-line no-unused-vars
396
+ const chars = parsed.find(pair => pair[0] === 'year')[2];
397
+ while(defn.value.length < chars) {
398
+ defn.value = `0${defn.value}`;
399
+ }
400
+ }
401
+
402
+ /**
403
+ *
404
+ * @param dateValue {Date}
405
+ * @param language {string}
406
+ * @param skeleton {string}
407
+ * @param timeZone {string}
408
+ * @returns {T}
409
+ */
410
+ function formatDateToParts(dateValue, language, skeleton, timeZone) {
411
+ // DateTimeFormat renames some of the options in its formatted output
412
+ //@ts-ignore
413
+ const mappings = key => ({
414
+ hour12: 'dayPeriod',
415
+ fractionalSecondDigits: 'fractionalSecond',
416
+ })[key] || key;
417
+
418
+ // produces an array of name/value pairs of skeleton parts
419
+ const allParameters = parseDateTimeSkeleton(skeleton, language);
420
+ allParameters.push(['timeZone', timeZone]);
421
+
422
+ const parsed = allParameters.filter(p => !p[0].startsWith('x-'));
423
+ const nonStandard = allParameters.filter(p => p[0].startsWith('x-'));
424
+ // reduce to a set of options that can be used to format
425
+ const options = Object.fromEntries(parsed);
426
+ delete options.literal;
427
+
428
+ const df = new Intl.DateTimeFormat(language, options);
429
+ // formattedParts will have all the pieces we need for our date -- but not in the correct order
430
+ const formattedParts = df.formatToParts(dateValue);
431
+
432
+ fixDigits(formattedParts, allParameters);
433
+ fixYear(formattedParts, parsed);
434
+ // iterate through the original parsed components and use its ordering and literals,
435
+ // and add the formatted pieces
436
+ return parsed.reduce((result, cur) => {
437
+ if (cur[0] === 'literal') result.push(cur);
438
+ else {
439
+ const v = formattedParts.find(p => p.type === mappings(cur[0]));
440
+ if (v && v.type === 'timeZoneName') {
441
+ const tz = nonStandard.find(p => p[0] === 'x-timeZoneName')[1];
442
+ const category = tz[0];
443
+ if (category === 'Z') {
444
+ if (tz.length < 4) {
445
+ // handle 'Z', 'ZZ', 'ZZZ' Time Zone: ISO8601 basic hms? / RFC 822
446
+ v.value = v.value.replace(/(GMT|:)/g, '');
447
+ if (v.value === '') v.value = '+0000';
448
+ } else if (tz.length === 5) {
449
+ // 'ZZZZZ' Time Zone: ISO8601 extended hms?
450
+ if (v.value === 'GMT') v.value = 'Z';
451
+ else v.value = v.value.replace(/GMT/, '');
452
+ }
453
+ }
454
+ if (category === 'X' || category === 'x') {
455
+ if (tz.length === 1) {
456
+ // 'X' ISO8601 basic hm?, with Z for 0
457
+ // -08, +0530, Z
458
+ // 'x' ISO8601 basic hm?, without Z for 0
459
+ v.value = v.value.replace(/(GMT|:(00)?)/g, '');
460
+ }
461
+ if (tz.length === 2) {
462
+ // 'XX' ISO8601 basic hm, with Z
463
+ // -0800, Z
464
+ // 'xx' ISO8601 basic hm, without Z
465
+ v.value = v.value.replace(/(GMT|:)/g, '');
466
+ }
467
+ if (tz.length === 3) {
468
+ // 'XXX' ISO8601 extended hm, with Z
469
+ // -08:00, Z
470
+ // 'xxx' ISO8601 extended hm, without Z
471
+ v.value = v.value.replace(/GMT/g, '');
472
+ }
473
+ if (category === 'X' && v.value === '') v.value = 'Z';
474
+ } else if (tz === 'O') {
475
+ // eliminate 'GMT', leading and trailing zeros
476
+ v.value = v.value.replace(/GMT/g, '').replace(/0(\d+):/, '$1:').replace(/:00/, '');
477
+ if (v.value === '') v.value = '+0';
478
+ }
479
+ }
480
+ if (v) result.push([v.type, v.value]);
481
+ }
482
+ return result;
483
+ }, []);
484
+ }
485
+
486
+ /**
487
+ *
488
+ * @param dateValue {Date}
489
+ * @param language {string}
490
+ * @param skeleton {string}
491
+ * @param timeZone {string}
492
+ */
493
+ function formatDate(dateValue, language, skeleton, timeZone) {
494
+ if (ShorthandStyles$1.find(type => skeleton.includes(type))) {
495
+ const options = {timeZone};
496
+ // the skeleton could have two keywords -- one for date, one for time
497
+ const parts = skeleton.split(/\s/).filter(s => s.length);
498
+ if (ShorthandStyles$1.indexOf(parts[0]) > -1) {
499
+ options.dateStyle = parts[0];
500
+ }
501
+ if (parts.length > 1 && ShorthandStyles$1.indexOf(parts[1]) > -1) {
502
+ options.timeStyle = parts[1];
503
+ }
504
+ return new Intl.DateTimeFormat(language, options).format(dateValue);
505
+ }
506
+ const parts = formatDateToParts(dateValue, language, skeleton, timeZone);
507
+ return parts.map(p => p[1]).join('');
508
+ }
509
+
510
+ /**
511
+ *
512
+ * @param dateString {string}
513
+ * @param language {string}
514
+ * @param skeleton {string}
515
+ * @param timeZone {string}
516
+ */
517
+ function parseDate(dateString, language, skeleton, timeZone, bUseUTC = false) {
518
+ // start by getting all the localized parts of a date/time picture:
519
+ // digits, calendar name
520
+ const lookups = [];
521
+ const regexParts = [];
522
+ const calendar = calendarName(language);
523
+ const digits = digitChars(language);
524
+ const twoDigit = `([${digits[0]}-${digits[9]}]{1,2})`;
525
+ const threeDigit = `([${digits[0]}-${digits[9]}]{1,3})`;
526
+ const fourDigit = `([${digits[0]}-${digits[9]}]{1,4})`;
527
+ let hourCycle = 'h12';
528
+ let _bUseUTC = bUseUTC;
529
+ let _setFullYear = false;
530
+ // functions to process the results of the regex match
531
+ const isSeparator = str => str.length === 1 && ':-/.'.includes(str);
532
+ const monthNumber = str => getNumber(str) - 1;
533
+ const getNumber = str => str.split('').reduce((total, digit) => (total * 10) + digits.indexOf(digit), 0);
534
+ const yearNumber = templateDigits => str => {
535
+ let year = getNumber(str);
536
+ //todo: align with AF
537
+ year = year < 100 && templateDigits === 2 ? year + 2000 : year;
538
+ if (calendar === 'islamic') year = Math.ceil(year * 0.97 + 622);
539
+ if (templateDigits > 2 && year < 100) {
540
+ _setFullYear = true;
541
+ }
542
+ return year;
543
+ };
544
+ const monthLookup = list => month => list.indexOf(month);
545
+
546
+ const parsed = parseDateTimeSkeleton(skeleton, language);
547
+ const months = monthNames(language, Object.fromEntries(parsed));
548
+ // build up a regex expression that identifies each option in the skeleton
549
+ // We build two parallel structures:
550
+ // 1. the regex expression that will extract parts of the date/time
551
+ // 2. a lookup array that will convert the matched results into date/time values
552
+ parsed.forEach(([option, value, len]) => {
553
+ // use a generic regex pattern for all single-character separator literals.
554
+ // Then we'll be forgiving when it comes to separators: / vs - vs : etc
555
+ if (option === 'literal') {
556
+ if (isSeparator(value)) regexParts.push(`[^${digits[0]}-${digits[9]}]`);
557
+ else regexParts.push(value);
558
+
559
+ } else if (option === 'month' && ['numeric', '2-digit'].includes(value)) {
560
+ regexParts.push(twoDigit);
561
+ lookups.push(['month', monthNumber]);
562
+
563
+ } else if (option === 'month' && ['formatted', 'long', 'short', 'narrow'].includes(value)) {
564
+ regexParts.push(`(${months.join('|')})`);
565
+ lookups.push(['month', monthLookup(months)]);
566
+
567
+ } else if (['day', 'minute', 'second'].includes(option)) {
568
+ if (option === 'minute' || option === 'second') {
569
+ _bUseUTC = false;
570
+ }
571
+ regexParts.push(twoDigit);
572
+ lookups.push([option, getNumber]);
573
+
574
+ } else if (option === 'fractionalSecondDigits') {
575
+ _bUseUTC = false;
576
+ regexParts.push(threeDigit);
577
+ lookups.push([option, (v, obj) => obj.fractionalSecondDigits + getNumber(v)]);
578
+
579
+ } else if (option === 'hour') {
580
+ _bUseUTC = false;
581
+ regexParts.push(twoDigit);
582
+ lookups.push([option, (v, obj) => obj.hour + getNumber(v)]);
583
+ } else if (option === 'year') {
584
+ regexParts.push('numeric' === value ? fourDigit : twoDigit);
585
+ lookups.push(['year', yearNumber(len)]);
586
+ } else if (option === 'dayPeriod') {
587
+ _bUseUTC = false;
588
+ const dayPeriod = getDayPeriod(language);
589
+ if (dayPeriod) {
590
+ regexParts.push(dayPeriod.regex);
591
+ lookups.push(['hour', dayPeriod.fn]);
592
+ }
593
+ // Any other part that we don't need, we'll just add a non-greedy consumption
594
+ } else if (option === 'hourCycle') {
595
+ _bUseUTC = false;
596
+ hourCycle = value;
597
+ } else if (option === 'x-timeZoneName') {
598
+ _bUseUTC = false;
599
+ // we handle only the GMT offset picture
600
+ regexParts.push('(?:GMT|UTC|Z)?([+\\-−0-9]{0,3}:?[0-9]{0,2})');
601
+ lookups.push([option, (v, obj) => {
602
+ _bUseUTC = true;
603
+ // v could be undefined if we're on GMT time
604
+ if (!v) return;
605
+ // replace the unicode minus, then extract hours [and minutes]
606
+ const timeParts = v.replace(/−/, '-').match(/([+\-\d]{2,3}):?(\d{0,2})/);
607
+ const hours = timeParts[1] * 1;
608
+ obj.hour -= hours;
609
+ const mins = timeParts.length > 2 ? timeParts[2] * 1 : 0;
610
+ obj.minute -= (hours < 0) ? - mins : mins;
611
+ }]);
612
+ } else if (option !== 'timeZoneName') {
613
+ _bUseUTC = false;
614
+ regexParts.push('.+?');
615
+ }
616
+
617
+ return regexParts;
618
+ }, []);
619
+ const regex = new RegExp(regexParts.join(''));
620
+ const match = dateString.match(regex);
621
+ if (match === null) return dateString;
622
+
623
+ // now loop through all the matched pieces and build up an object we'll use to create a Date object
624
+ const dateObj = {year: 1972, month: 0, day: 1, hour: 0, minute: 0, second: 0, fractionalSecondDigits: 0};
625
+ match.slice(1).forEach((m, index) => {
626
+ const [element, func] = lookups[index];
627
+ dateObj[element] = func(m, dateObj);
628
+ });
629
+ if (hourCycle === 'h24' && dateObj.hour === 24) dateObj.hour = 0;
630
+ if (hourCycle === 'h12' && dateObj.hour === 12) dateObj.hour = 0;
631
+ if (_bUseUTC) {
632
+ const utcDate = new Date(Date.UTC(
633
+ dateObj.year,
634
+ dateObj.month,
635
+ dateObj.day,
636
+ dateObj.hour,
637
+ dateObj.minute,
638
+ dateObj.second,
639
+ dateObj.fractionalSecondDigits,
640
+ ));
641
+ if (_setFullYear) {
642
+ utcDate.setUTCFullYear(dateObj.year);
643
+ }
644
+ return utcDate;
645
+ }
646
+ const jsDate = new Date(
647
+ dateObj.year,
648
+ dateObj.month,
649
+ dateObj.day,
650
+ dateObj.hour,
651
+ dateObj.minute,
652
+ dateObj.second,
653
+ dateObj.fractionalSecondDigits,
654
+ );
655
+ if (_setFullYear) {
656
+ jsDate.setFullYear(dateObj.year);
657
+ }
658
+ return timeZone == null ? jsDate : adjustTimeZone(jsDate, timeZone);
659
+ }
660
+
661
+ const currencies = {
662
+ 'da-DK': 'DKK',
663
+ 'de-DE': 'EUR',
664
+ 'en-US': 'USD',
665
+ 'en-GB': 'GBP',
666
+ 'es-ES': 'EUR',
667
+ 'fi-FI': 'EUR',
668
+ 'fr-FR': 'EUR',
669
+ 'it-IT': 'EUR',
670
+ 'ja-JP': 'JPY',
671
+ 'nb-NO': 'NOK',
672
+ 'nl-NL': 'EUR',
673
+ 'pt-BR': 'BRL',
674
+ 'sv-SE': 'SEK',
675
+ 'zh-CN': 'CNY',
676
+ 'zh-TW': 'TWD',
677
+ 'ko-KR': 'KRW',
678
+ 'cs-CZ': 'CZK',
679
+ 'pl-PL': 'PLN',
680
+ 'ru-RU': 'RUB',
681
+ 'tr-TR': 'TRY'
682
+ };
683
+
684
+ const locales = Object.keys(currencies);
685
+
686
+ const getCurrency = function (locale) {
687
+ if (locales.indexOf(locale) > -1) {
688
+ return currencies[locale]
689
+ } else {
690
+ const matchingLocale = locales.find(x => x.startsWith(locale));
691
+ if (matchingLocale) {
692
+ return currencies[matchingLocale]
693
+ }
694
+ }
695
+ return ''
696
+ };
697
+
698
+ const NUMBER_REGEX =
699
+ // eslint-disable-next-line max-len
700
+ /(?:[#]+|[@]+(?:#+)?|[0]+|[,]|[.]|[-]|[+]|[%]|[¤]{1,4}(?:\/([a-zA-Z]{3}))?|[;]|[K]{1,2}|E{1,2}[+]?|'(?:[^']|'')*')|[^a-zA-Z']+/g;
701
+ const supportedUnits = ['acre', 'bit', 'byte', 'celsius', 'centimeter', 'day',
702
+ 'degree', 'fahrenheit', 'fluid-ounce', 'foot', 'gallon', 'gigabit',
703
+ 'gigabyte', 'gram', 'hectare', 'hour', 'inch', 'kilobit', 'kilobyte',
704
+ 'kilogram', 'kilometer', 'liter', 'megabit', 'megabyte', 'meter', 'mile',
705
+ 'mile-scandinavian', 'milliliter', 'millimeter', 'millisecond', 'minute', 'month',
706
+ 'ounce', 'percent', 'petabyte', 'pound', 'second', 'stone', 'terabit', 'terabyte', 'week', 'yard', 'year'].join('|');
707
+ const ShorthandStyles = [/^currency(?:\/([a-zA-Z]{3}))?$/, /^decimal$/, /^integer$/, /^percent$/, new RegExp(`^unit\/(${supportedUnits})$`)];
708
+
709
+
710
+ function parseNumberSkeleton(skeleton, language) {
711
+ const options = {};
712
+ const order = [];
713
+ let match, index;
714
+ for (index = 0; index < ShorthandStyles.length && match == null; index++) {
715
+ match = ShorthandStyles[index].exec(skeleton);
716
+ }
717
+ if (match) {
718
+ switch(index) {
719
+ case 1:
720
+ options.style = 'currency';
721
+ options.currencyDisplay = 'narrowSymbol';
722
+ if (match[1]) {
723
+ options.currency = match[1];
724
+ } else {
725
+ options.currency = getCurrency(language);
726
+ }
727
+ break;
728
+ case 2:
729
+ new Intl.NumberFormat(language, {}).resolvedOptions();
730
+ options.minimumFractionDigits = options.minimumFractionDigits || 2;
731
+ break;
732
+ case 3:
733
+ options.minimumFractionDigits = 0;
734
+ options.maximumFractionDigits = 0;
735
+ break;
736
+ case 4:
737
+ options.style = 'percent';
738
+ break;
739
+ case 5:
740
+ options.style = "unit";
741
+ options.unitDisplay = "long";
742
+ options.unit = match[1];
743
+ break;
744
+ }
745
+ return {
746
+ options,
747
+ order
748
+ }
749
+ }
750
+ options.useGrouping = false;
751
+ options.minimumIntegerDigits = 1;
752
+ options.maximumFractionDigits = 0;
753
+ options.minimumFractionDigits = 0;
754
+ skeleton.replace(NUMBER_REGEX, (match, offset) => {
755
+ const len = match.length;
756
+ switch(match[0]) {
757
+ case '#':
758
+ order.push(['digit', len]);
759
+ if (options?.decimal === true) {
760
+ options.maximumFractionDigits = options.minimumFractionDigits + len;
761
+ }
762
+ break;
763
+ case '@':
764
+ if (options?.minimumSignificantDigits) {
765
+ throw "@ symbol should occur together"
766
+ }
767
+ order.push(['@', len]);
768
+ options.minimumSignificantDigits = len;
769
+ const hashes = match.match(/#+/) || "";
770
+ options.maximumSignificantDigits = len + hashes.length;
771
+ order.push(['digit', hashes.length]);
772
+ break;
773
+ case ',':
774
+ if (options?.decimal === true) {
775
+ throw "grouping character not supporting for fractions"
776
+ }
777
+ order.push(['group', 1]);
778
+ options.useGrouping = 'auto';
779
+ break;
780
+ case '.':
781
+ if (options?.decimal) {
782
+ console.error("only one decimal symbol is allowed");
783
+ } else {
784
+ order.push(['decimal', 1]);
785
+ options.decimal = true;
786
+ }
787
+ break;
788
+ case '0':
789
+ order.push('0', len);
790
+ if(options.minimumSignificantDigits || options.maximumSignificantDigits) {
791
+ throw "0 is not supported with @"
792
+ }
793
+ if (options?.decimal === true) {
794
+ options.minimumFractionDigits = len;
795
+ } else {
796
+ options.minimumIntegerDigits = len;
797
+ }
798
+ break;
799
+ case '-':
800
+ if (offset !== 0) {
801
+ console.error("sign display is always in the beginning");
802
+ }
803
+ options.signDisplay = 'negative';
804
+ order.push(['signDisplay', 1, '-']);
805
+ break;
806
+ case '+':
807
+ if (offset !== 0 && order[order.length - 1][0] === 'E') {
808
+ console.error("sign display is always in the beginning");
809
+ }
810
+ if (offset === 0) {
811
+ options.signDisplay = 'always';
812
+ }
813
+ order.push(['signDisplay', 1, '+']);
814
+ break;
815
+ case '¤':
816
+ if (offset !== 0 && offset !== skeleton.length - 1) {
817
+ console.error("currency display should be either in the beginning or at the end");
818
+ }
819
+ options.style = 'currency';
820
+ options.currencyDisplay = ['symbol', 'code', 'name', 'narrowSymbol'][len -1];
821
+ options.currency = getCurrency(language);
822
+ order.push(['currency', len]);
823
+ break;
824
+ case '%':
825
+ if (offset !== 0 && offset !== skeleton.length - 1) {
826
+ console.error("percent display should be either in the beginning or at the end");
827
+ }
828
+ order.push(['%', 1]);
829
+ options.style = 'percent';
830
+ break;
831
+ case 'E':
832
+ order.push(['E', len]);
833
+ options.style = ['scientific','engineering'](len - 1);
834
+ break;
835
+ default:
836
+ console.error("unknown chars" + match);
837
+ }
838
+ });
839
+ return {
840
+ options,
841
+ order
842
+ };
843
+ }
844
+
845
+ function formatNumber(numberValue, language, skeletn) {
846
+ if (!skeletn) return numberValue
847
+ language = language || "en";
848
+ const {options, order} = parseNumberSkeleton(skeletn, language);
849
+ return new Intl.NumberFormat(language, options).format(numberValue);
850
+ }
851
+
852
+ function getMetaInfo(language, skel) {
853
+ const parts = {};
854
+ // gather digits and radix symbol
855
+ let options = new Intl.NumberFormat(language, {style:'decimal', useGrouping:false}).formatToParts(9876543210.1);
856
+ parts.digits = options.find(p => p.type === 'integer').value.split('').reverse();
857
+ parts.decimal = options.find(p => p.type === 'decimal').value;
858
+
859
+ // extract type values from the parts
860
+ const gather = type => {
861
+ const find = options.find(p => p.type === type);
862
+ if (find) parts[type] = find.value;
863
+ };
864
+ // now gather the localized parts that correspond to the provided skeleton.
865
+ const parsed = parseNumberSkeleton(skel);
866
+ const nf = new Intl.NumberFormat(language, parsed);
867
+ options = nf.formatToParts(-987654321);
868
+ gather('group');
869
+ gather('minusSign');
870
+ gather('percentSign');
871
+ // it's possible to have multiple currency representations in a single value
872
+ parts.currency = options.filter(p => p.type === 'currency').map(p => p.value);
873
+ // collect all literals. Most likely a literal is an accounting bracket
874
+ parts.literal = options.filter(p => p.type === 'literal').map(p => p.value);
875
+ options = nf.formatToParts(987654321);
876
+ gather('plusSign');
877
+ gather('exponentSeparator');
878
+ gather('unit');
879
+ return parts;
880
+ }
881
+
882
+ function parseNumber(numberString, language, skel) {
883
+ try {
884
+ // factor will be updated to reflect: negative, percent, exponent etc.
885
+ let factor = 1;
886
+ let number = numberString;
887
+ const meta = getMetaInfo(language, skel);
888
+ if (meta.group) number = number.replaceAll(meta.group, '');
889
+ number = number.replace(meta.decimal, '.');
890
+ if (meta.unit) number = number.replaceAll(meta.unit, '');
891
+ if (meta.minusSign && number.includes(meta.minusSign)) {
892
+ number = number.replace(meta.minusSign, '');
893
+ factor *= -1;
894
+ }
895
+ if (meta.percentSign && number.includes(meta.percentSign)) {
896
+ factor = factor/100;
897
+ number = number.replace(meta.percentSign, '');
898
+ }
899
+ meta.currency.forEach(currency => number = number.replace(currency, ''));
900
+ meta.literal.forEach(literal => {
901
+ if (number.includes(literal)) {
902
+ if (literal === '(') factor = factor * -1;
903
+ number = number.replace(literal, '');
904
+ }
905
+ });
906
+ if (meta.plusSign) number = number.replace(meta.plusSign, '');
907
+ if (meta.exponentSeparator) {
908
+ let e;
909
+ [number, e] = number.split(meta.exponentSeparator);
910
+ factor = factor * Math.pow(10, e);
911
+ }
912
+ const result = factor * number;
913
+ return isNaN(result) ? numberString : result;
914
+ } catch (e) {
915
+ console.dir(e);
916
+ return numberString;
917
+ }
918
+ }
919
+
920
+ const getCategory = function (skeleton) {
921
+ const chkCategory = skeleton?.match(/^(?:(num|date)\|)?(.+)/);
922
+ return [chkCategory?.[1], chkCategory?.[2]]
923
+ };
924
+
925
+ const format = function (value, locale, skeleton, timezone) {
926
+ const [category, skelton] = getCategory(skeleton);
927
+ switch (category) {
928
+ case 'date':
929
+ if (!(value instanceof Date)) {
930
+ value = new Date(value);
931
+ }
932
+ return formatDate(value, locale, skelton, timezone)
933
+ case 'num':
934
+ return formatNumber(value, locale, skelton)
935
+ default:
936
+ throw `unable to deduce the format. The skeleton should be date|<format> for date formats and num|<format> for numbers`
937
+ }
938
+ };
939
+
940
+ const parse = function (value, locale, skeleton, timezone) {
941
+ const [category, skelton] = getCategory(skeleton);
942
+ switch (category) {
943
+ case 'date':
944
+ return parseDate(value, locale, skelton, timezone)
945
+ case 'number':
946
+ return parseNumber(value, locale, skelton)
947
+ default:
948
+ throw `unable to deduce the format. The skeleton should be date|<format> for date formats and num|<format> for numbers`
949
+ }
950
+ };
951
+
952
+ exports.format = format;
953
+ exports.formatDate = formatDate;
954
+ exports.formatNumber = formatNumber;
955
+ exports.parse = parse;
956
+ exports.parseDate = parseDate;
957
+ exports.parseDateSkeleton = getSkeleton;
958
+ exports.parseNumber = parseNumber;