@justifi/webcomponents 0.0.9 → 0.0.11

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.
@@ -2,9 +2,83 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- const paymentsList = require('./payments-list-d2dfcef1.js');
6
5
  const index = require('./index-68222998.js');
7
6
 
7
+ const BankAccountForm = class {
8
+ constructor(hostRef) {
9
+ index.registerInstance(this, hostRef);
10
+ this.bankAccountFormReady = index.createEvent(this, "bankAccountFormReady", 7);
11
+ this.bankAccountFormChange = index.createEvent(this, "bankAccountFormChange", 7);
12
+ this.bankAccountFormBlur = index.createEvent(this, "bankAccountFormBlur", 7);
13
+ this.bankAccountFormTokenize = index.createEvent(this, "bankAccountFormTokenize", 7);
14
+ this.iframeOrigin = undefined;
15
+ }
16
+ readyHandler(event) {
17
+ this.bankAccountFormReady.emit(event);
18
+ }
19
+ changeHandler(event) {
20
+ this.bankAccountFormChange.emit(event);
21
+ }
22
+ blurHandler(event) {
23
+ this.bankAccountFormBlur.emit(event);
24
+ }
25
+ tokenizeHandler(event) {
26
+ this.bankAccountFormTokenize.emit(event);
27
+ }
28
+ async tokenize(...args) {
29
+ if (!this.childRef) {
30
+ throw new Error('Cannot call tokenize');
31
+ }
32
+ return this.childRef.tokenize(...args);
33
+ }
34
+ render() {
35
+ return (index.h("justifi-payment-method-form", { ref: el => {
36
+ if (el) {
37
+ this.childRef = el;
38
+ }
39
+ }, "iframe-origin": this.iframeOrigin || 'https://js.justifi.ai/bank-account', "payment-method-form-ready": this.bankAccountFormReady, "payment-method-form-change": this.bankAccountFormChange, "payment-method-form-blur": this.bankAccountFormBlur, "payment-method-form-tokenize": this.bankAccountFormTokenize }));
40
+ }
41
+ };
42
+
43
+ const cardFormCss = "justifi-card-form iframe{height:55px}";
44
+
45
+ const CardForm = class {
46
+ constructor(hostRef) {
47
+ index.registerInstance(this, hostRef);
48
+ this.cardFormReady = index.createEvent(this, "cardFormReady", 7);
49
+ this.cardFormChange = index.createEvent(this, "cardFormChange", 7);
50
+ this.cardFormBlur = index.createEvent(this, "cardFormBlur", 7);
51
+ this.cardFormTokenize = index.createEvent(this, "cardFormTokenize", 7);
52
+ this.iframeOrigin = undefined;
53
+ }
54
+ readyHandler(event) {
55
+ this.cardFormReady.emit(event);
56
+ }
57
+ changeHandler(event) {
58
+ this.cardFormChange.emit(event);
59
+ }
60
+ blurHandler(event) {
61
+ this.cardFormBlur.emit(event);
62
+ }
63
+ tokenizeHandler(event) {
64
+ this.cardFormTokenize.emit(event);
65
+ }
66
+ async tokenize(...args) {
67
+ if (!this.childRef) {
68
+ throw new Error('Cannot call tokenize');
69
+ }
70
+ return this.childRef.tokenize(...args);
71
+ }
72
+ render() {
73
+ return (index.h("justifi-payment-method-form", { ref: el => {
74
+ if (el) {
75
+ this.childRef = el;
76
+ }
77
+ }, "iframe-origin": this.iframeOrigin || 'https://js.justifi.ai/card', "payment-method-form-ready": this.cardFormReady, "payment-method-form-change": this.cardFormChange, "payment-method-form-blur": this.cardFormBlur, "payment-method-form-tokenize": this.cardFormTokenize }));
78
+ }
79
+ };
80
+ CardForm.style = cardFormCss;
81
+
8
82
  const paymentMethodFormCss = ":host{display:block}justifi-payment-method-form iframe{border:none;width:100%}";
9
83
 
10
84
  var DispatchedEventTypes;
@@ -74,7 +148,4235 @@ const PaymentMethodForm = class {
74
148
  };
75
149
  PaymentMethodForm.style = paymentMethodFormCss;
76
150
 
77
- exports.justifi_bank_account_form = paymentsList.BankAccountForm;
78
- exports.justifi_card_form = paymentsList.CardForm;
79
- exports.justifi_payments_list = paymentsList.PaymentsList;
151
+ // Unique ID creation requires a high quality random # generator. In the browser we therefore
152
+ // require the crypto API and do not support built-in fallback to lower quality random number
153
+ // generators (like Math.random()).
154
+ let getRandomValues;
155
+ const rnds8 = new Uint8Array(16);
156
+ function rng() {
157
+ // lazy load so that environments that need to polyfill have a chance to do so
158
+ if (!getRandomValues) {
159
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
160
+ getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
161
+
162
+ if (!getRandomValues) {
163
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
164
+ }
165
+ }
166
+
167
+ return getRandomValues(rnds8);
168
+ }
169
+
170
+ /**
171
+ * Convert array of 16 byte values to UUID string format of the form:
172
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
173
+ */
174
+
175
+ const byteToHex = [];
176
+
177
+ for (let i = 0; i < 256; ++i) {
178
+ byteToHex.push((i + 0x100).toString(16).slice(1));
179
+ }
180
+
181
+ function unsafeStringify(arr, offset = 0) {
182
+ // Note: Be careful editing this code! It's been tuned for performance
183
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
184
+ return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
185
+ }
186
+
187
+ const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
188
+ const native = {
189
+ randomUUID
190
+ };
191
+
192
+ function v4(options, buf, offset) {
193
+ if (native.randomUUID && !buf && !options) {
194
+ return native.randomUUID();
195
+ }
196
+
197
+ options = options || {};
198
+ const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
199
+
200
+ rnds[6] = rnds[6] & 0x0f | 0x40;
201
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
202
+
203
+ if (buf) {
204
+ offset = offset || 0;
205
+
206
+ for (let i = 0; i < 16; ++i) {
207
+ buf[offset + i] = rnds[i];
208
+ }
209
+
210
+ return buf;
211
+ }
212
+
213
+ return unsafeStringify(rnds);
214
+ }
215
+
216
+ const Api = (authToken) => {
217
+ const apiOrigin = 'http://localhost:3000';
218
+ async function getAuthorizationHeader() {
219
+ return {
220
+ Authorization: `Bearer ${authToken}`,
221
+ 'Idempotency-Key': v4(),
222
+ 'Content-Type': 'application/json'
223
+ };
224
+ }
225
+ async function makeRequest(endpoint, method, params, body, signal) {
226
+ const url = `${apiOrigin}/v1/${endpoint}`;
227
+ const requestUrl = params ? `${url}?${new URLSearchParams(params)}` : url;
228
+ const response = await fetch(requestUrl, {
229
+ method: method,
230
+ headers: await getAuthorizationHeader(),
231
+ body: body,
232
+ signal: signal
233
+ });
234
+ if (response) {
235
+ return response.status === 204 ? {} : response.json();
236
+ }
237
+ handleError(requestUrl);
238
+ }
239
+ async function get(endpoint, params, signal) {
240
+ return makeRequest(endpoint, 'GET', params, null, signal);
241
+ }
242
+ async function post(endpoint, body, params, signal) {
243
+ return makeRequest(endpoint, 'POST', params, body, signal);
244
+ }
245
+ async function patch(endpoint, body, params, signal) {
246
+ return makeRequest(endpoint, 'PATCH', params, body, signal);
247
+ }
248
+ async function destroy(endpoint, params, signal) {
249
+ return makeRequest(endpoint, 'DELETE', params, null, signal);
250
+ }
251
+ return { get, post, patch, destroy };
252
+ };
253
+ function handleError(requestUrl) {
254
+ console.error(`Error fetching from ${requestUrl}`);
255
+ }
256
+
257
+ var CaptureStrategy;
258
+ (function (CaptureStrategy) {
259
+ CaptureStrategy["automatic"] = "automatic";
260
+ CaptureStrategy["manual"] = "manual";
261
+ })(CaptureStrategy || (CaptureStrategy = {}));
262
+ var PaymentMethodTypes;
263
+ (function (PaymentMethodTypes) {
264
+ PaymentMethodTypes["card"] = "card";
265
+ PaymentMethodTypes["bankAccount"] = "bank_account";
266
+ })(PaymentMethodTypes || (PaymentMethodTypes = {}));
267
+ var PaymentStatuses;
268
+ (function (PaymentStatuses) {
269
+ PaymentStatuses["pending"] = "pending";
270
+ PaymentStatuses["authorized"] = "authorized";
271
+ PaymentStatuses["succeeded"] = "succeeded";
272
+ PaymentStatuses["failed"] = "failed";
273
+ PaymentStatuses["disputed"] = "disputed";
274
+ PaymentStatuses["fully_refunded"] = "fully_refunded";
275
+ PaymentStatuses["partially_refunded"] = "partially_refunded";
276
+ })(PaymentStatuses || (PaymentStatuses = {}));
277
+ var PaymentDisputedStatuses;
278
+ (function (PaymentDisputedStatuses) {
279
+ // if a dispute is 'won', we don't show a dispute status, just general status
280
+ PaymentDisputedStatuses["lost"] = "lost";
281
+ PaymentDisputedStatuses["open"] = "open";
282
+ })(PaymentDisputedStatuses || (PaymentDisputedStatuses = {}));
283
+ class Payment {
284
+ constructor(payment) {
285
+ this.id = payment.id;
286
+ this.account_id = payment.account_id;
287
+ this.amount = payment.amount;
288
+ this.amount_disputed = payment.amount_disputed;
289
+ this.amount_refundable = payment.amount_refundable;
290
+ this.amount_refunded = payment.amount_refunded;
291
+ this.balance = payment.balance;
292
+ this.captured = payment.captured;
293
+ this.capture_strategy = payment.capture_strategy;
294
+ this.currency = payment.currency;
295
+ this.description = payment.description;
296
+ this.disputed = payment.disputed;
297
+ this.disputes = payment.disputes;
298
+ this.error_code = payment.error_code;
299
+ this.error_description = payment.error_description;
300
+ this.fee_amount = payment.fee_amount;
301
+ this.is_test = payment.is_test;
302
+ this.metadata = payment.metadata;
303
+ this.payment_method = payment.payment_method;
304
+ this.payment_intent_id = payment.payment_intent_id;
305
+ this.refunded = payment.refunded;
306
+ this.status = payment.status;
307
+ this.created_at = payment.created_at;
308
+ this.updated_at = payment.updated_at;
309
+ }
310
+ get disputedStatus() {
311
+ const lost = this.disputes.some((dispute) => dispute.status === PaymentDisputedStatuses.lost);
312
+ // if a dispute is 'won', we don't show a dispute status, just general status
313
+ if (!this.disputed) {
314
+ return null;
315
+ }
316
+ else if (lost) {
317
+ return PaymentDisputedStatuses.lost;
318
+ }
319
+ else {
320
+ return PaymentDisputedStatuses.open;
321
+ }
322
+ }
323
+ }
324
+
325
+ function toInteger(dirtyNumber) {
326
+ if (dirtyNumber === null || dirtyNumber === true || dirtyNumber === false) {
327
+ return NaN;
328
+ }
329
+
330
+ var number = Number(dirtyNumber);
331
+
332
+ if (isNaN(number)) {
333
+ return number;
334
+ }
335
+
336
+ return number < 0 ? Math.ceil(number) : Math.floor(number);
337
+ }
338
+
339
+ function requiredArgs(required, args) {
340
+ if (args.length < required) {
341
+ throw new TypeError(required + ' argument' + (required > 1 ? 's' : '') + ' required, but only ' + args.length + ' present');
342
+ }
343
+ }
344
+
345
+ function _typeof$2(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$2 = function _typeof(obj) { return typeof obj; }; } else { _typeof$2 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$2(obj); }
346
+ /**
347
+ * @name toDate
348
+ * @category Common Helpers
349
+ * @summary Convert the given argument to an instance of Date.
350
+ *
351
+ * @description
352
+ * Convert the given argument to an instance of Date.
353
+ *
354
+ * If the argument is an instance of Date, the function returns its clone.
355
+ *
356
+ * If the argument is a number, it is treated as a timestamp.
357
+ *
358
+ * If the argument is none of the above, the function returns Invalid Date.
359
+ *
360
+ * **Note**: *all* Date arguments passed to any *date-fns* function is processed by `toDate`.
361
+ *
362
+ * @param {Date|Number} argument - the value to convert
363
+ * @returns {Date} the parsed date in the local time zone
364
+ * @throws {TypeError} 1 argument required
365
+ *
366
+ * @example
367
+ * // Clone the date:
368
+ * const result = toDate(new Date(2014, 1, 11, 11, 30, 30))
369
+ * //=> Tue Feb 11 2014 11:30:30
370
+ *
371
+ * @example
372
+ * // Convert the timestamp to date:
373
+ * const result = toDate(1392098430000)
374
+ * //=> Tue Feb 11 2014 11:30:30
375
+ */
376
+
377
+ function toDate(argument) {
378
+ requiredArgs(1, arguments);
379
+ var argStr = Object.prototype.toString.call(argument); // Clone the date
380
+
381
+ if (argument instanceof Date || _typeof$2(argument) === 'object' && argStr === '[object Date]') {
382
+ // Prevent the date to lose the milliseconds when passed to new Date() in IE10
383
+ return new Date(argument.getTime());
384
+ } else if (typeof argument === 'number' || argStr === '[object Number]') {
385
+ return new Date(argument);
386
+ } else {
387
+ if ((typeof argument === 'string' || argStr === '[object String]') && typeof console !== 'undefined') {
388
+ // eslint-disable-next-line no-console
389
+ console.warn("Starting with v2.0.0-beta.1 date-fns doesn't accept strings as date arguments. Please use `parseISO` to parse strings. See: https://github.com/date-fns/date-fns/blob/master/docs/upgradeGuide.md#string-arguments"); // eslint-disable-next-line no-console
390
+
391
+ console.warn(new Error().stack);
392
+ }
393
+
394
+ return new Date(NaN);
395
+ }
396
+ }
397
+
398
+ /**
399
+ * @name addMilliseconds
400
+ * @category Millisecond Helpers
401
+ * @summary Add the specified number of milliseconds to the given date.
402
+ *
403
+ * @description
404
+ * Add the specified number of milliseconds to the given date.
405
+ *
406
+ * @param {Date|Number} date - the date to be changed
407
+ * @param {Number} amount - the amount of milliseconds to be added. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
408
+ * @returns {Date} the new date with the milliseconds added
409
+ * @throws {TypeError} 2 arguments required
410
+ *
411
+ * @example
412
+ * // Add 750 milliseconds to 10 July 2014 12:45:30.000:
413
+ * const result = addMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
414
+ * //=> Thu Jul 10 2014 12:45:30.750
415
+ */
416
+
417
+ function addMilliseconds(dirtyDate, dirtyAmount) {
418
+ requiredArgs(2, arguments);
419
+ var timestamp = toDate(dirtyDate).getTime();
420
+ var amount = toInteger(dirtyAmount);
421
+ return new Date(timestamp + amount);
422
+ }
423
+
424
+ var defaultOptions = {};
425
+ function getDefaultOptions() {
426
+ return defaultOptions;
427
+ }
428
+
429
+ /**
430
+ * Google Chrome as of 67.0.3396.87 introduced timezones with offset that includes seconds.
431
+ * They usually appear for dates that denote time before the timezones were introduced
432
+ * (e.g. for 'Europe/Prague' timezone the offset is GMT+00:57:44 before 1 October 1891
433
+ * and GMT+01:00:00 after that date)
434
+ *
435
+ * Date#getTimezoneOffset returns the offset in minutes and would return 57 for the example above,
436
+ * which would lead to incorrect calculations.
437
+ *
438
+ * This function returns the timezone offset in milliseconds that takes seconds in account.
439
+ */
440
+ function getTimezoneOffsetInMilliseconds(date) {
441
+ var utcDate = new Date(Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
442
+ utcDate.setUTCFullYear(date.getFullYear());
443
+ return date.getTime() - utcDate.getTime();
444
+ }
445
+
446
+ function _typeof$1(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof$1 = function _typeof(obj) { return typeof obj; }; } else { _typeof$1 = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof$1(obj); }
447
+ /**
448
+ * @name isDate
449
+ * @category Common Helpers
450
+ * @summary Is the given value a date?
451
+ *
452
+ * @description
453
+ * Returns true if the given value is an instance of Date. The function works for dates transferred across iframes.
454
+ *
455
+ * @param {*} value - the value to check
456
+ * @returns {boolean} true if the given value is a date
457
+ * @throws {TypeError} 1 arguments required
458
+ *
459
+ * @example
460
+ * // For a valid date:
461
+ * const result = isDate(new Date())
462
+ * //=> true
463
+ *
464
+ * @example
465
+ * // For an invalid date:
466
+ * const result = isDate(new Date(NaN))
467
+ * //=> true
468
+ *
469
+ * @example
470
+ * // For some value:
471
+ * const result = isDate('2014-02-31')
472
+ * //=> false
473
+ *
474
+ * @example
475
+ * // For an object:
476
+ * const result = isDate({})
477
+ * //=> false
478
+ */
479
+
480
+ function isDate(value) {
481
+ requiredArgs(1, arguments);
482
+ return value instanceof Date || _typeof$1(value) === 'object' && Object.prototype.toString.call(value) === '[object Date]';
483
+ }
484
+
485
+ /**
486
+ * @name isValid
487
+ * @category Common Helpers
488
+ * @summary Is the given date valid?
489
+ *
490
+ * @description
491
+ * Returns false if argument is Invalid Date and true otherwise.
492
+ * Argument is converted to Date using `toDate`. See [toDate]{@link https://date-fns.org/docs/toDate}
493
+ * Invalid Date is a Date, whose time value is NaN.
494
+ *
495
+ * Time value of Date: http://es5.github.io/#x15.9.1.1
496
+ *
497
+ * @param {*} date - the date to check
498
+ * @returns {Boolean} the date is valid
499
+ * @throws {TypeError} 1 argument required
500
+ *
501
+ * @example
502
+ * // For the valid date:
503
+ * const result = isValid(new Date(2014, 1, 31))
504
+ * //=> true
505
+ *
506
+ * @example
507
+ * // For the value, convertable into a date:
508
+ * const result = isValid(1393804800000)
509
+ * //=> true
510
+ *
511
+ * @example
512
+ * // For the invalid date:
513
+ * const result = isValid(new Date(''))
514
+ * //=> false
515
+ */
516
+
517
+ function isValid(dirtyDate) {
518
+ requiredArgs(1, arguments);
519
+
520
+ if (!isDate(dirtyDate) && typeof dirtyDate !== 'number') {
521
+ return false;
522
+ }
523
+
524
+ var date = toDate(dirtyDate);
525
+ return !isNaN(Number(date));
526
+ }
527
+
528
+ /**
529
+ * @name subMilliseconds
530
+ * @category Millisecond Helpers
531
+ * @summary Subtract the specified number of milliseconds from the given date.
532
+ *
533
+ * @description
534
+ * Subtract the specified number of milliseconds from the given date.
535
+ *
536
+ * @param {Date|Number} date - the date to be changed
537
+ * @param {Number} amount - the amount of milliseconds to be subtracted. Positive decimals will be rounded using `Math.floor`, decimals less than zero will be rounded using `Math.ceil`.
538
+ * @returns {Date} the new date with the milliseconds subtracted
539
+ * @throws {TypeError} 2 arguments required
540
+ *
541
+ * @example
542
+ * // Subtract 750 milliseconds from 10 July 2014 12:45:30.000:
543
+ * const result = subMilliseconds(new Date(2014, 6, 10, 12, 45, 30, 0), 750)
544
+ * //=> Thu Jul 10 2014 12:45:29.250
545
+ */
546
+
547
+ function subMilliseconds(dirtyDate, dirtyAmount) {
548
+ requiredArgs(2, arguments);
549
+ var amount = toInteger(dirtyAmount);
550
+ return addMilliseconds(dirtyDate, -amount);
551
+ }
552
+
553
+ var MILLISECONDS_IN_DAY = 86400000;
554
+ function getUTCDayOfYear(dirtyDate) {
555
+ requiredArgs(1, arguments);
556
+ var date = toDate(dirtyDate);
557
+ var timestamp = date.getTime();
558
+ date.setUTCMonth(0, 1);
559
+ date.setUTCHours(0, 0, 0, 0);
560
+ var startOfYearTimestamp = date.getTime();
561
+ var difference = timestamp - startOfYearTimestamp;
562
+ return Math.floor(difference / MILLISECONDS_IN_DAY) + 1;
563
+ }
564
+
565
+ function startOfUTCISOWeek(dirtyDate) {
566
+ requiredArgs(1, arguments);
567
+ var weekStartsOn = 1;
568
+ var date = toDate(dirtyDate);
569
+ var day = date.getUTCDay();
570
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
571
+ date.setUTCDate(date.getUTCDate() - diff);
572
+ date.setUTCHours(0, 0, 0, 0);
573
+ return date;
574
+ }
575
+
576
+ function getUTCISOWeekYear(dirtyDate) {
577
+ requiredArgs(1, arguments);
578
+ var date = toDate(dirtyDate);
579
+ var year = date.getUTCFullYear();
580
+ var fourthOfJanuaryOfNextYear = new Date(0);
581
+ fourthOfJanuaryOfNextYear.setUTCFullYear(year + 1, 0, 4);
582
+ fourthOfJanuaryOfNextYear.setUTCHours(0, 0, 0, 0);
583
+ var startOfNextYear = startOfUTCISOWeek(fourthOfJanuaryOfNextYear);
584
+ var fourthOfJanuaryOfThisYear = new Date(0);
585
+ fourthOfJanuaryOfThisYear.setUTCFullYear(year, 0, 4);
586
+ fourthOfJanuaryOfThisYear.setUTCHours(0, 0, 0, 0);
587
+ var startOfThisYear = startOfUTCISOWeek(fourthOfJanuaryOfThisYear);
588
+
589
+ if (date.getTime() >= startOfNextYear.getTime()) {
590
+ return year + 1;
591
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
592
+ return year;
593
+ } else {
594
+ return year - 1;
595
+ }
596
+ }
597
+
598
+ function startOfUTCISOWeekYear(dirtyDate) {
599
+ requiredArgs(1, arguments);
600
+ var year = getUTCISOWeekYear(dirtyDate);
601
+ var fourthOfJanuary = new Date(0);
602
+ fourthOfJanuary.setUTCFullYear(year, 0, 4);
603
+ fourthOfJanuary.setUTCHours(0, 0, 0, 0);
604
+ var date = startOfUTCISOWeek(fourthOfJanuary);
605
+ return date;
606
+ }
607
+
608
+ var MILLISECONDS_IN_WEEK$1 = 604800000;
609
+ function getUTCISOWeek(dirtyDate) {
610
+ requiredArgs(1, arguments);
611
+ var date = toDate(dirtyDate);
612
+ var diff = startOfUTCISOWeek(date).getTime() - startOfUTCISOWeekYear(date).getTime(); // Round the number of days to the nearest integer
613
+ // because the number of milliseconds in a week is not constant
614
+ // (e.g. it's different in the week of the daylight saving time clock shift)
615
+
616
+ return Math.round(diff / MILLISECONDS_IN_WEEK$1) + 1;
617
+ }
618
+
619
+ function startOfUTCWeek(dirtyDate, options) {
620
+ var _ref, _ref2, _ref3, _options$weekStartsOn, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
621
+
622
+ requiredArgs(1, arguments);
623
+ var defaultOptions = getDefaultOptions();
624
+ var weekStartsOn = toInteger((_ref = (_ref2 = (_ref3 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.weekStartsOn) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.weekStartsOn) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.weekStartsOn) !== null && _ref !== void 0 ? _ref : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
625
+
626
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
627
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
628
+ }
629
+
630
+ var date = toDate(dirtyDate);
631
+ var day = date.getUTCDay();
632
+ var diff = (day < weekStartsOn ? 7 : 0) + day - weekStartsOn;
633
+ date.setUTCDate(date.getUTCDate() - diff);
634
+ date.setUTCHours(0, 0, 0, 0);
635
+ return date;
636
+ }
637
+
638
+ function getUTCWeekYear(dirtyDate, options) {
639
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
640
+
641
+ requiredArgs(1, arguments);
642
+ var date = toDate(dirtyDate);
643
+ var year = date.getUTCFullYear();
644
+ var defaultOptions = getDefaultOptions();
645
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
646
+
647
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
648
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
649
+ }
650
+
651
+ var firstWeekOfNextYear = new Date(0);
652
+ firstWeekOfNextYear.setUTCFullYear(year + 1, 0, firstWeekContainsDate);
653
+ firstWeekOfNextYear.setUTCHours(0, 0, 0, 0);
654
+ var startOfNextYear = startOfUTCWeek(firstWeekOfNextYear, options);
655
+ var firstWeekOfThisYear = new Date(0);
656
+ firstWeekOfThisYear.setUTCFullYear(year, 0, firstWeekContainsDate);
657
+ firstWeekOfThisYear.setUTCHours(0, 0, 0, 0);
658
+ var startOfThisYear = startOfUTCWeek(firstWeekOfThisYear, options);
659
+
660
+ if (date.getTime() >= startOfNextYear.getTime()) {
661
+ return year + 1;
662
+ } else if (date.getTime() >= startOfThisYear.getTime()) {
663
+ return year;
664
+ } else {
665
+ return year - 1;
666
+ }
667
+ }
668
+
669
+ function startOfUTCWeekYear(dirtyDate, options) {
670
+ var _ref, _ref2, _ref3, _options$firstWeekCon, _options$locale, _options$locale$optio, _defaultOptions$local, _defaultOptions$local2;
671
+
672
+ requiredArgs(1, arguments);
673
+ var defaultOptions = getDefaultOptions();
674
+ var firstWeekContainsDate = toInteger((_ref = (_ref2 = (_ref3 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale = options.locale) === null || _options$locale === void 0 ? void 0 : (_options$locale$optio = _options$locale.options) === null || _options$locale$optio === void 0 ? void 0 : _options$locale$optio.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : defaultOptions.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref !== void 0 ? _ref : 1);
675
+ var year = getUTCWeekYear(dirtyDate, options);
676
+ var firstWeek = new Date(0);
677
+ firstWeek.setUTCFullYear(year, 0, firstWeekContainsDate);
678
+ firstWeek.setUTCHours(0, 0, 0, 0);
679
+ var date = startOfUTCWeek(firstWeek, options);
680
+ return date;
681
+ }
682
+
683
+ var MILLISECONDS_IN_WEEK = 604800000;
684
+ function getUTCWeek(dirtyDate, options) {
685
+ requiredArgs(1, arguments);
686
+ var date = toDate(dirtyDate);
687
+ var diff = startOfUTCWeek(date, options).getTime() - startOfUTCWeekYear(date, options).getTime(); // Round the number of days to the nearest integer
688
+ // because the number of milliseconds in a week is not constant
689
+ // (e.g. it's different in the week of the daylight saving time clock shift)
690
+
691
+ return Math.round(diff / MILLISECONDS_IN_WEEK) + 1;
692
+ }
693
+
694
+ function addLeadingZeros(number, targetLength) {
695
+ var sign = number < 0 ? '-' : '';
696
+ var output = Math.abs(number).toString();
697
+
698
+ while (output.length < targetLength) {
699
+ output = '0' + output;
700
+ }
701
+
702
+ return sign + output;
703
+ }
704
+
705
+ /*
706
+ * | | Unit | | Unit |
707
+ * |-----|--------------------------------|-----|--------------------------------|
708
+ * | a | AM, PM | A* | |
709
+ * | d | Day of month | D | |
710
+ * | h | Hour [1-12] | H | Hour [0-23] |
711
+ * | m | Minute | M | Month |
712
+ * | s | Second | S | Fraction of second |
713
+ * | y | Year (abs) | Y | |
714
+ *
715
+ * Letters marked by * are not implemented but reserved by Unicode standard.
716
+ */
717
+
718
+ var formatters$1 = {
719
+ // Year
720
+ y: function y(date, token) {
721
+ // From http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_tokens
722
+ // | Year | y | yy | yyy | yyyy | yyyyy |
723
+ // |----------|-------|----|-------|-------|-------|
724
+ // | AD 1 | 1 | 01 | 001 | 0001 | 00001 |
725
+ // | AD 12 | 12 | 12 | 012 | 0012 | 00012 |
726
+ // | AD 123 | 123 | 23 | 123 | 0123 | 00123 |
727
+ // | AD 1234 | 1234 | 34 | 1234 | 1234 | 01234 |
728
+ // | AD 12345 | 12345 | 45 | 12345 | 12345 | 12345 |
729
+ var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
730
+
731
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
732
+ return addLeadingZeros(token === 'yy' ? year % 100 : year, token.length);
733
+ },
734
+ // Month
735
+ M: function M(date, token) {
736
+ var month = date.getUTCMonth();
737
+ return token === 'M' ? String(month + 1) : addLeadingZeros(month + 1, 2);
738
+ },
739
+ // Day of the month
740
+ d: function d(date, token) {
741
+ return addLeadingZeros(date.getUTCDate(), token.length);
742
+ },
743
+ // AM or PM
744
+ a: function a(date, token) {
745
+ var dayPeriodEnumValue = date.getUTCHours() / 12 >= 1 ? 'pm' : 'am';
746
+
747
+ switch (token) {
748
+ case 'a':
749
+ case 'aa':
750
+ return dayPeriodEnumValue.toUpperCase();
751
+
752
+ case 'aaa':
753
+ return dayPeriodEnumValue;
754
+
755
+ case 'aaaaa':
756
+ return dayPeriodEnumValue[0];
757
+
758
+ case 'aaaa':
759
+ default:
760
+ return dayPeriodEnumValue === 'am' ? 'a.m.' : 'p.m.';
761
+ }
762
+ },
763
+ // Hour [1-12]
764
+ h: function h(date, token) {
765
+ return addLeadingZeros(date.getUTCHours() % 12 || 12, token.length);
766
+ },
767
+ // Hour [0-23]
768
+ H: function H(date, token) {
769
+ return addLeadingZeros(date.getUTCHours(), token.length);
770
+ },
771
+ // Minute
772
+ m: function m(date, token) {
773
+ return addLeadingZeros(date.getUTCMinutes(), token.length);
774
+ },
775
+ // Second
776
+ s: function s(date, token) {
777
+ return addLeadingZeros(date.getUTCSeconds(), token.length);
778
+ },
779
+ // Fraction of second
780
+ S: function S(date, token) {
781
+ var numberOfDigits = token.length;
782
+ var milliseconds = date.getUTCMilliseconds();
783
+ var fractionalSeconds = Math.floor(milliseconds * Math.pow(10, numberOfDigits - 3));
784
+ return addLeadingZeros(fractionalSeconds, token.length);
785
+ }
786
+ };
787
+
788
+ var dayPeriodEnum = {
789
+ am: 'am',
790
+ pm: 'pm',
791
+ midnight: 'midnight',
792
+ noon: 'noon',
793
+ morning: 'morning',
794
+ afternoon: 'afternoon',
795
+ evening: 'evening',
796
+ night: 'night'
797
+ };
798
+
799
+ /*
800
+ * | | Unit | | Unit |
801
+ * |-----|--------------------------------|-----|--------------------------------|
802
+ * | a | AM, PM | A* | Milliseconds in day |
803
+ * | b | AM, PM, noon, midnight | B | Flexible day period |
804
+ * | c | Stand-alone local day of week | C* | Localized hour w/ day period |
805
+ * | d | Day of month | D | Day of year |
806
+ * | e | Local day of week | E | Day of week |
807
+ * | f | | F* | Day of week in month |
808
+ * | g* | Modified Julian day | G | Era |
809
+ * | h | Hour [1-12] | H | Hour [0-23] |
810
+ * | i! | ISO day of week | I! | ISO week of year |
811
+ * | j* | Localized hour w/ day period | J* | Localized hour w/o day period |
812
+ * | k | Hour [1-24] | K | Hour [0-11] |
813
+ * | l* | (deprecated) | L | Stand-alone month |
814
+ * | m | Minute | M | Month |
815
+ * | n | | N | |
816
+ * | o! | Ordinal number modifier | O | Timezone (GMT) |
817
+ * | p! | Long localized time | P! | Long localized date |
818
+ * | q | Stand-alone quarter | Q | Quarter |
819
+ * | r* | Related Gregorian year | R! | ISO week-numbering year |
820
+ * | s | Second | S | Fraction of second |
821
+ * | t! | Seconds timestamp | T! | Milliseconds timestamp |
822
+ * | u | Extended year | U* | Cyclic year |
823
+ * | v* | Timezone (generic non-locat.) | V* | Timezone (location) |
824
+ * | w | Local week of year | W* | Week of month |
825
+ * | x | Timezone (ISO-8601 w/o Z) | X | Timezone (ISO-8601) |
826
+ * | y | Year (abs) | Y | Local week-numbering year |
827
+ * | z | Timezone (specific non-locat.) | Z* | Timezone (aliases) |
828
+ *
829
+ * Letters marked by * are not implemented but reserved by Unicode standard.
830
+ *
831
+ * Letters marked by ! are non-standard, but implemented by date-fns:
832
+ * - `o` modifies the previous token to turn it into an ordinal (see `format` docs)
833
+ * - `i` is ISO day of week. For `i` and `ii` is returns numeric ISO week days,
834
+ * i.e. 7 for Sunday, 1 for Monday, etc.
835
+ * - `I` is ISO week of year, as opposed to `w` which is local week of year.
836
+ * - `R` is ISO week-numbering year, as opposed to `Y` which is local week-numbering year.
837
+ * `R` is supposed to be used in conjunction with `I` and `i`
838
+ * for universal ISO week-numbering date, whereas
839
+ * `Y` is supposed to be used in conjunction with `w` and `e`
840
+ * for week-numbering date specific to the locale.
841
+ * - `P` is long localized date format
842
+ * - `p` is long localized time format
843
+ */
844
+ var formatters = {
845
+ // Era
846
+ G: function G(date, token, localize) {
847
+ var era = date.getUTCFullYear() > 0 ? 1 : 0;
848
+
849
+ switch (token) {
850
+ // AD, BC
851
+ case 'G':
852
+ case 'GG':
853
+ case 'GGG':
854
+ return localize.era(era, {
855
+ width: 'abbreviated'
856
+ });
857
+ // A, B
858
+
859
+ case 'GGGGG':
860
+ return localize.era(era, {
861
+ width: 'narrow'
862
+ });
863
+ // Anno Domini, Before Christ
864
+
865
+ case 'GGGG':
866
+ default:
867
+ return localize.era(era, {
868
+ width: 'wide'
869
+ });
870
+ }
871
+ },
872
+ // Year
873
+ y: function y(date, token, localize) {
874
+ // Ordinal number
875
+ if (token === 'yo') {
876
+ var signedYear = date.getUTCFullYear(); // Returns 1 for 1 BC (which is year 0 in JavaScript)
877
+
878
+ var year = signedYear > 0 ? signedYear : 1 - signedYear;
879
+ return localize.ordinalNumber(year, {
880
+ unit: 'year'
881
+ });
882
+ }
883
+
884
+ return formatters$1.y(date, token);
885
+ },
886
+ // Local week-numbering year
887
+ Y: function Y(date, token, localize, options) {
888
+ var signedWeekYear = getUTCWeekYear(date, options); // Returns 1 for 1 BC (which is year 0 in JavaScript)
889
+
890
+ var weekYear = signedWeekYear > 0 ? signedWeekYear : 1 - signedWeekYear; // Two digit year
891
+
892
+ if (token === 'YY') {
893
+ var twoDigitYear = weekYear % 100;
894
+ return addLeadingZeros(twoDigitYear, 2);
895
+ } // Ordinal number
896
+
897
+
898
+ if (token === 'Yo') {
899
+ return localize.ordinalNumber(weekYear, {
900
+ unit: 'year'
901
+ });
902
+ } // Padding
903
+
904
+
905
+ return addLeadingZeros(weekYear, token.length);
906
+ },
907
+ // ISO week-numbering year
908
+ R: function R(date, token) {
909
+ var isoWeekYear = getUTCISOWeekYear(date); // Padding
910
+
911
+ return addLeadingZeros(isoWeekYear, token.length);
912
+ },
913
+ // Extended year. This is a single number designating the year of this calendar system.
914
+ // The main difference between `y` and `u` localizers are B.C. years:
915
+ // | Year | `y` | `u` |
916
+ // |------|-----|-----|
917
+ // | AC 1 | 1 | 1 |
918
+ // | BC 1 | 1 | 0 |
919
+ // | BC 2 | 2 | -1 |
920
+ // Also `yy` always returns the last two digits of a year,
921
+ // while `uu` pads single digit years to 2 characters and returns other years unchanged.
922
+ u: function u(date, token) {
923
+ var year = date.getUTCFullYear();
924
+ return addLeadingZeros(year, token.length);
925
+ },
926
+ // Quarter
927
+ Q: function Q(date, token, localize) {
928
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
929
+
930
+ switch (token) {
931
+ // 1, 2, 3, 4
932
+ case 'Q':
933
+ return String(quarter);
934
+ // 01, 02, 03, 04
935
+
936
+ case 'QQ':
937
+ return addLeadingZeros(quarter, 2);
938
+ // 1st, 2nd, 3rd, 4th
939
+
940
+ case 'Qo':
941
+ return localize.ordinalNumber(quarter, {
942
+ unit: 'quarter'
943
+ });
944
+ // Q1, Q2, Q3, Q4
945
+
946
+ case 'QQQ':
947
+ return localize.quarter(quarter, {
948
+ width: 'abbreviated',
949
+ context: 'formatting'
950
+ });
951
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
952
+
953
+ case 'QQQQQ':
954
+ return localize.quarter(quarter, {
955
+ width: 'narrow',
956
+ context: 'formatting'
957
+ });
958
+ // 1st quarter, 2nd quarter, ...
959
+
960
+ case 'QQQQ':
961
+ default:
962
+ return localize.quarter(quarter, {
963
+ width: 'wide',
964
+ context: 'formatting'
965
+ });
966
+ }
967
+ },
968
+ // Stand-alone quarter
969
+ q: function q(date, token, localize) {
970
+ var quarter = Math.ceil((date.getUTCMonth() + 1) / 3);
971
+
972
+ switch (token) {
973
+ // 1, 2, 3, 4
974
+ case 'q':
975
+ return String(quarter);
976
+ // 01, 02, 03, 04
977
+
978
+ case 'qq':
979
+ return addLeadingZeros(quarter, 2);
980
+ // 1st, 2nd, 3rd, 4th
981
+
982
+ case 'qo':
983
+ return localize.ordinalNumber(quarter, {
984
+ unit: 'quarter'
985
+ });
986
+ // Q1, Q2, Q3, Q4
987
+
988
+ case 'qqq':
989
+ return localize.quarter(quarter, {
990
+ width: 'abbreviated',
991
+ context: 'standalone'
992
+ });
993
+ // 1, 2, 3, 4 (narrow quarter; could be not numerical)
994
+
995
+ case 'qqqqq':
996
+ return localize.quarter(quarter, {
997
+ width: 'narrow',
998
+ context: 'standalone'
999
+ });
1000
+ // 1st quarter, 2nd quarter, ...
1001
+
1002
+ case 'qqqq':
1003
+ default:
1004
+ return localize.quarter(quarter, {
1005
+ width: 'wide',
1006
+ context: 'standalone'
1007
+ });
1008
+ }
1009
+ },
1010
+ // Month
1011
+ M: function M(date, token, localize) {
1012
+ var month = date.getUTCMonth();
1013
+
1014
+ switch (token) {
1015
+ case 'M':
1016
+ case 'MM':
1017
+ return formatters$1.M(date, token);
1018
+ // 1st, 2nd, ..., 12th
1019
+
1020
+ case 'Mo':
1021
+ return localize.ordinalNumber(month + 1, {
1022
+ unit: 'month'
1023
+ });
1024
+ // Jan, Feb, ..., Dec
1025
+
1026
+ case 'MMM':
1027
+ return localize.month(month, {
1028
+ width: 'abbreviated',
1029
+ context: 'formatting'
1030
+ });
1031
+ // J, F, ..., D
1032
+
1033
+ case 'MMMMM':
1034
+ return localize.month(month, {
1035
+ width: 'narrow',
1036
+ context: 'formatting'
1037
+ });
1038
+ // January, February, ..., December
1039
+
1040
+ case 'MMMM':
1041
+ default:
1042
+ return localize.month(month, {
1043
+ width: 'wide',
1044
+ context: 'formatting'
1045
+ });
1046
+ }
1047
+ },
1048
+ // Stand-alone month
1049
+ L: function L(date, token, localize) {
1050
+ var month = date.getUTCMonth();
1051
+
1052
+ switch (token) {
1053
+ // 1, 2, ..., 12
1054
+ case 'L':
1055
+ return String(month + 1);
1056
+ // 01, 02, ..., 12
1057
+
1058
+ case 'LL':
1059
+ return addLeadingZeros(month + 1, 2);
1060
+ // 1st, 2nd, ..., 12th
1061
+
1062
+ case 'Lo':
1063
+ return localize.ordinalNumber(month + 1, {
1064
+ unit: 'month'
1065
+ });
1066
+ // Jan, Feb, ..., Dec
1067
+
1068
+ case 'LLL':
1069
+ return localize.month(month, {
1070
+ width: 'abbreviated',
1071
+ context: 'standalone'
1072
+ });
1073
+ // J, F, ..., D
1074
+
1075
+ case 'LLLLL':
1076
+ return localize.month(month, {
1077
+ width: 'narrow',
1078
+ context: 'standalone'
1079
+ });
1080
+ // January, February, ..., December
1081
+
1082
+ case 'LLLL':
1083
+ default:
1084
+ return localize.month(month, {
1085
+ width: 'wide',
1086
+ context: 'standalone'
1087
+ });
1088
+ }
1089
+ },
1090
+ // Local week of year
1091
+ w: function w(date, token, localize, options) {
1092
+ var week = getUTCWeek(date, options);
1093
+
1094
+ if (token === 'wo') {
1095
+ return localize.ordinalNumber(week, {
1096
+ unit: 'week'
1097
+ });
1098
+ }
1099
+
1100
+ return addLeadingZeros(week, token.length);
1101
+ },
1102
+ // ISO week of year
1103
+ I: function I(date, token, localize) {
1104
+ var isoWeek = getUTCISOWeek(date);
1105
+
1106
+ if (token === 'Io') {
1107
+ return localize.ordinalNumber(isoWeek, {
1108
+ unit: 'week'
1109
+ });
1110
+ }
1111
+
1112
+ return addLeadingZeros(isoWeek, token.length);
1113
+ },
1114
+ // Day of the month
1115
+ d: function d(date, token, localize) {
1116
+ if (token === 'do') {
1117
+ return localize.ordinalNumber(date.getUTCDate(), {
1118
+ unit: 'date'
1119
+ });
1120
+ }
1121
+
1122
+ return formatters$1.d(date, token);
1123
+ },
1124
+ // Day of year
1125
+ D: function D(date, token, localize) {
1126
+ var dayOfYear = getUTCDayOfYear(date);
1127
+
1128
+ if (token === 'Do') {
1129
+ return localize.ordinalNumber(dayOfYear, {
1130
+ unit: 'dayOfYear'
1131
+ });
1132
+ }
1133
+
1134
+ return addLeadingZeros(dayOfYear, token.length);
1135
+ },
1136
+ // Day of week
1137
+ E: function E(date, token, localize) {
1138
+ var dayOfWeek = date.getUTCDay();
1139
+
1140
+ switch (token) {
1141
+ // Tue
1142
+ case 'E':
1143
+ case 'EE':
1144
+ case 'EEE':
1145
+ return localize.day(dayOfWeek, {
1146
+ width: 'abbreviated',
1147
+ context: 'formatting'
1148
+ });
1149
+ // T
1150
+
1151
+ case 'EEEEE':
1152
+ return localize.day(dayOfWeek, {
1153
+ width: 'narrow',
1154
+ context: 'formatting'
1155
+ });
1156
+ // Tu
1157
+
1158
+ case 'EEEEEE':
1159
+ return localize.day(dayOfWeek, {
1160
+ width: 'short',
1161
+ context: 'formatting'
1162
+ });
1163
+ // Tuesday
1164
+
1165
+ case 'EEEE':
1166
+ default:
1167
+ return localize.day(dayOfWeek, {
1168
+ width: 'wide',
1169
+ context: 'formatting'
1170
+ });
1171
+ }
1172
+ },
1173
+ // Local day of week
1174
+ e: function e(date, token, localize, options) {
1175
+ var dayOfWeek = date.getUTCDay();
1176
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
1177
+
1178
+ switch (token) {
1179
+ // Numerical value (Nth day of week with current locale or weekStartsOn)
1180
+ case 'e':
1181
+ return String(localDayOfWeek);
1182
+ // Padded numerical value
1183
+
1184
+ case 'ee':
1185
+ return addLeadingZeros(localDayOfWeek, 2);
1186
+ // 1st, 2nd, ..., 7th
1187
+
1188
+ case 'eo':
1189
+ return localize.ordinalNumber(localDayOfWeek, {
1190
+ unit: 'day'
1191
+ });
1192
+
1193
+ case 'eee':
1194
+ return localize.day(dayOfWeek, {
1195
+ width: 'abbreviated',
1196
+ context: 'formatting'
1197
+ });
1198
+ // T
1199
+
1200
+ case 'eeeee':
1201
+ return localize.day(dayOfWeek, {
1202
+ width: 'narrow',
1203
+ context: 'formatting'
1204
+ });
1205
+ // Tu
1206
+
1207
+ case 'eeeeee':
1208
+ return localize.day(dayOfWeek, {
1209
+ width: 'short',
1210
+ context: 'formatting'
1211
+ });
1212
+ // Tuesday
1213
+
1214
+ case 'eeee':
1215
+ default:
1216
+ return localize.day(dayOfWeek, {
1217
+ width: 'wide',
1218
+ context: 'formatting'
1219
+ });
1220
+ }
1221
+ },
1222
+ // Stand-alone local day of week
1223
+ c: function c(date, token, localize, options) {
1224
+ var dayOfWeek = date.getUTCDay();
1225
+ var localDayOfWeek = (dayOfWeek - options.weekStartsOn + 8) % 7 || 7;
1226
+
1227
+ switch (token) {
1228
+ // Numerical value (same as in `e`)
1229
+ case 'c':
1230
+ return String(localDayOfWeek);
1231
+ // Padded numerical value
1232
+
1233
+ case 'cc':
1234
+ return addLeadingZeros(localDayOfWeek, token.length);
1235
+ // 1st, 2nd, ..., 7th
1236
+
1237
+ case 'co':
1238
+ return localize.ordinalNumber(localDayOfWeek, {
1239
+ unit: 'day'
1240
+ });
1241
+
1242
+ case 'ccc':
1243
+ return localize.day(dayOfWeek, {
1244
+ width: 'abbreviated',
1245
+ context: 'standalone'
1246
+ });
1247
+ // T
1248
+
1249
+ case 'ccccc':
1250
+ return localize.day(dayOfWeek, {
1251
+ width: 'narrow',
1252
+ context: 'standalone'
1253
+ });
1254
+ // Tu
1255
+
1256
+ case 'cccccc':
1257
+ return localize.day(dayOfWeek, {
1258
+ width: 'short',
1259
+ context: 'standalone'
1260
+ });
1261
+ // Tuesday
1262
+
1263
+ case 'cccc':
1264
+ default:
1265
+ return localize.day(dayOfWeek, {
1266
+ width: 'wide',
1267
+ context: 'standalone'
1268
+ });
1269
+ }
1270
+ },
1271
+ // ISO day of week
1272
+ i: function i(date, token, localize) {
1273
+ var dayOfWeek = date.getUTCDay();
1274
+ var isoDayOfWeek = dayOfWeek === 0 ? 7 : dayOfWeek;
1275
+
1276
+ switch (token) {
1277
+ // 2
1278
+ case 'i':
1279
+ return String(isoDayOfWeek);
1280
+ // 02
1281
+
1282
+ case 'ii':
1283
+ return addLeadingZeros(isoDayOfWeek, token.length);
1284
+ // 2nd
1285
+
1286
+ case 'io':
1287
+ return localize.ordinalNumber(isoDayOfWeek, {
1288
+ unit: 'day'
1289
+ });
1290
+ // Tue
1291
+
1292
+ case 'iii':
1293
+ return localize.day(dayOfWeek, {
1294
+ width: 'abbreviated',
1295
+ context: 'formatting'
1296
+ });
1297
+ // T
1298
+
1299
+ case 'iiiii':
1300
+ return localize.day(dayOfWeek, {
1301
+ width: 'narrow',
1302
+ context: 'formatting'
1303
+ });
1304
+ // Tu
1305
+
1306
+ case 'iiiiii':
1307
+ return localize.day(dayOfWeek, {
1308
+ width: 'short',
1309
+ context: 'formatting'
1310
+ });
1311
+ // Tuesday
1312
+
1313
+ case 'iiii':
1314
+ default:
1315
+ return localize.day(dayOfWeek, {
1316
+ width: 'wide',
1317
+ context: 'formatting'
1318
+ });
1319
+ }
1320
+ },
1321
+ // AM or PM
1322
+ a: function a(date, token, localize) {
1323
+ var hours = date.getUTCHours();
1324
+ var dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
1325
+
1326
+ switch (token) {
1327
+ case 'a':
1328
+ case 'aa':
1329
+ return localize.dayPeriod(dayPeriodEnumValue, {
1330
+ width: 'abbreviated',
1331
+ context: 'formatting'
1332
+ });
1333
+
1334
+ case 'aaa':
1335
+ return localize.dayPeriod(dayPeriodEnumValue, {
1336
+ width: 'abbreviated',
1337
+ context: 'formatting'
1338
+ }).toLowerCase();
1339
+
1340
+ case 'aaaaa':
1341
+ return localize.dayPeriod(dayPeriodEnumValue, {
1342
+ width: 'narrow',
1343
+ context: 'formatting'
1344
+ });
1345
+
1346
+ case 'aaaa':
1347
+ default:
1348
+ return localize.dayPeriod(dayPeriodEnumValue, {
1349
+ width: 'wide',
1350
+ context: 'formatting'
1351
+ });
1352
+ }
1353
+ },
1354
+ // AM, PM, midnight, noon
1355
+ b: function b(date, token, localize) {
1356
+ var hours = date.getUTCHours();
1357
+ var dayPeriodEnumValue;
1358
+
1359
+ if (hours === 12) {
1360
+ dayPeriodEnumValue = dayPeriodEnum.noon;
1361
+ } else if (hours === 0) {
1362
+ dayPeriodEnumValue = dayPeriodEnum.midnight;
1363
+ } else {
1364
+ dayPeriodEnumValue = hours / 12 >= 1 ? 'pm' : 'am';
1365
+ }
1366
+
1367
+ switch (token) {
1368
+ case 'b':
1369
+ case 'bb':
1370
+ return localize.dayPeriod(dayPeriodEnumValue, {
1371
+ width: 'abbreviated',
1372
+ context: 'formatting'
1373
+ });
1374
+
1375
+ case 'bbb':
1376
+ return localize.dayPeriod(dayPeriodEnumValue, {
1377
+ width: 'abbreviated',
1378
+ context: 'formatting'
1379
+ }).toLowerCase();
1380
+
1381
+ case 'bbbbb':
1382
+ return localize.dayPeriod(dayPeriodEnumValue, {
1383
+ width: 'narrow',
1384
+ context: 'formatting'
1385
+ });
1386
+
1387
+ case 'bbbb':
1388
+ default:
1389
+ return localize.dayPeriod(dayPeriodEnumValue, {
1390
+ width: 'wide',
1391
+ context: 'formatting'
1392
+ });
1393
+ }
1394
+ },
1395
+ // in the morning, in the afternoon, in the evening, at night
1396
+ B: function B(date, token, localize) {
1397
+ var hours = date.getUTCHours();
1398
+ var dayPeriodEnumValue;
1399
+
1400
+ if (hours >= 17) {
1401
+ dayPeriodEnumValue = dayPeriodEnum.evening;
1402
+ } else if (hours >= 12) {
1403
+ dayPeriodEnumValue = dayPeriodEnum.afternoon;
1404
+ } else if (hours >= 4) {
1405
+ dayPeriodEnumValue = dayPeriodEnum.morning;
1406
+ } else {
1407
+ dayPeriodEnumValue = dayPeriodEnum.night;
1408
+ }
1409
+
1410
+ switch (token) {
1411
+ case 'B':
1412
+ case 'BB':
1413
+ case 'BBB':
1414
+ return localize.dayPeriod(dayPeriodEnumValue, {
1415
+ width: 'abbreviated',
1416
+ context: 'formatting'
1417
+ });
1418
+
1419
+ case 'BBBBB':
1420
+ return localize.dayPeriod(dayPeriodEnumValue, {
1421
+ width: 'narrow',
1422
+ context: 'formatting'
1423
+ });
1424
+
1425
+ case 'BBBB':
1426
+ default:
1427
+ return localize.dayPeriod(dayPeriodEnumValue, {
1428
+ width: 'wide',
1429
+ context: 'formatting'
1430
+ });
1431
+ }
1432
+ },
1433
+ // Hour [1-12]
1434
+ h: function h(date, token, localize) {
1435
+ if (token === 'ho') {
1436
+ var hours = date.getUTCHours() % 12;
1437
+ if (hours === 0) hours = 12;
1438
+ return localize.ordinalNumber(hours, {
1439
+ unit: 'hour'
1440
+ });
1441
+ }
1442
+
1443
+ return formatters$1.h(date, token);
1444
+ },
1445
+ // Hour [0-23]
1446
+ H: function H(date, token, localize) {
1447
+ if (token === 'Ho') {
1448
+ return localize.ordinalNumber(date.getUTCHours(), {
1449
+ unit: 'hour'
1450
+ });
1451
+ }
1452
+
1453
+ return formatters$1.H(date, token);
1454
+ },
1455
+ // Hour [0-11]
1456
+ K: function K(date, token, localize) {
1457
+ var hours = date.getUTCHours() % 12;
1458
+
1459
+ if (token === 'Ko') {
1460
+ return localize.ordinalNumber(hours, {
1461
+ unit: 'hour'
1462
+ });
1463
+ }
1464
+
1465
+ return addLeadingZeros(hours, token.length);
1466
+ },
1467
+ // Hour [1-24]
1468
+ k: function k(date, token, localize) {
1469
+ var hours = date.getUTCHours();
1470
+ if (hours === 0) hours = 24;
1471
+
1472
+ if (token === 'ko') {
1473
+ return localize.ordinalNumber(hours, {
1474
+ unit: 'hour'
1475
+ });
1476
+ }
1477
+
1478
+ return addLeadingZeros(hours, token.length);
1479
+ },
1480
+ // Minute
1481
+ m: function m(date, token, localize) {
1482
+ if (token === 'mo') {
1483
+ return localize.ordinalNumber(date.getUTCMinutes(), {
1484
+ unit: 'minute'
1485
+ });
1486
+ }
1487
+
1488
+ return formatters$1.m(date, token);
1489
+ },
1490
+ // Second
1491
+ s: function s(date, token, localize) {
1492
+ if (token === 'so') {
1493
+ return localize.ordinalNumber(date.getUTCSeconds(), {
1494
+ unit: 'second'
1495
+ });
1496
+ }
1497
+
1498
+ return formatters$1.s(date, token);
1499
+ },
1500
+ // Fraction of second
1501
+ S: function S(date, token) {
1502
+ return formatters$1.S(date, token);
1503
+ },
1504
+ // Timezone (ISO-8601. If offset is 0, output is always `'Z'`)
1505
+ X: function X(date, token, _localize, options) {
1506
+ var originalDate = options._originalDate || date;
1507
+ var timezoneOffset = originalDate.getTimezoneOffset();
1508
+
1509
+ if (timezoneOffset === 0) {
1510
+ return 'Z';
1511
+ }
1512
+
1513
+ switch (token) {
1514
+ // Hours and optional minutes
1515
+ case 'X':
1516
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1517
+ // Hours, minutes and optional seconds without `:` delimiter
1518
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1519
+ // so this token always has the same output as `XX`
1520
+
1521
+ case 'XXXX':
1522
+ case 'XX':
1523
+ // Hours and minutes without `:` delimiter
1524
+ return formatTimezone(timezoneOffset);
1525
+ // Hours, minutes and optional seconds with `:` delimiter
1526
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1527
+ // so this token always has the same output as `XXX`
1528
+
1529
+ case 'XXXXX':
1530
+ case 'XXX': // Hours and minutes with `:` delimiter
1531
+
1532
+ default:
1533
+ return formatTimezone(timezoneOffset, ':');
1534
+ }
1535
+ },
1536
+ // Timezone (ISO-8601. If offset is 0, output is `'+00:00'` or equivalent)
1537
+ x: function x(date, token, _localize, options) {
1538
+ var originalDate = options._originalDate || date;
1539
+ var timezoneOffset = originalDate.getTimezoneOffset();
1540
+
1541
+ switch (token) {
1542
+ // Hours and optional minutes
1543
+ case 'x':
1544
+ return formatTimezoneWithOptionalMinutes(timezoneOffset);
1545
+ // Hours, minutes and optional seconds without `:` delimiter
1546
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1547
+ // so this token always has the same output as `xx`
1548
+
1549
+ case 'xxxx':
1550
+ case 'xx':
1551
+ // Hours and minutes without `:` delimiter
1552
+ return formatTimezone(timezoneOffset);
1553
+ // Hours, minutes and optional seconds with `:` delimiter
1554
+ // Note: neither ISO-8601 nor JavaScript supports seconds in timezone offsets
1555
+ // so this token always has the same output as `xxx`
1556
+
1557
+ case 'xxxxx':
1558
+ case 'xxx': // Hours and minutes with `:` delimiter
1559
+
1560
+ default:
1561
+ return formatTimezone(timezoneOffset, ':');
1562
+ }
1563
+ },
1564
+ // Timezone (GMT)
1565
+ O: function O(date, token, _localize, options) {
1566
+ var originalDate = options._originalDate || date;
1567
+ var timezoneOffset = originalDate.getTimezoneOffset();
1568
+
1569
+ switch (token) {
1570
+ // Short
1571
+ case 'O':
1572
+ case 'OO':
1573
+ case 'OOO':
1574
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1575
+ // Long
1576
+
1577
+ case 'OOOO':
1578
+ default:
1579
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1580
+ }
1581
+ },
1582
+ // Timezone (specific non-location)
1583
+ z: function z(date, token, _localize, options) {
1584
+ var originalDate = options._originalDate || date;
1585
+ var timezoneOffset = originalDate.getTimezoneOffset();
1586
+
1587
+ switch (token) {
1588
+ // Short
1589
+ case 'z':
1590
+ case 'zz':
1591
+ case 'zzz':
1592
+ return 'GMT' + formatTimezoneShort(timezoneOffset, ':');
1593
+ // Long
1594
+
1595
+ case 'zzzz':
1596
+ default:
1597
+ return 'GMT' + formatTimezone(timezoneOffset, ':');
1598
+ }
1599
+ },
1600
+ // Seconds timestamp
1601
+ t: function t(date, token, _localize, options) {
1602
+ var originalDate = options._originalDate || date;
1603
+ var timestamp = Math.floor(originalDate.getTime() / 1000);
1604
+ return addLeadingZeros(timestamp, token.length);
1605
+ },
1606
+ // Milliseconds timestamp
1607
+ T: function T(date, token, _localize, options) {
1608
+ var originalDate = options._originalDate || date;
1609
+ var timestamp = originalDate.getTime();
1610
+ return addLeadingZeros(timestamp, token.length);
1611
+ }
1612
+ };
1613
+
1614
+ function formatTimezoneShort(offset, dirtyDelimiter) {
1615
+ var sign = offset > 0 ? '-' : '+';
1616
+ var absOffset = Math.abs(offset);
1617
+ var hours = Math.floor(absOffset / 60);
1618
+ var minutes = absOffset % 60;
1619
+
1620
+ if (minutes === 0) {
1621
+ return sign + String(hours);
1622
+ }
1623
+
1624
+ var delimiter = dirtyDelimiter || '';
1625
+ return sign + String(hours) + delimiter + addLeadingZeros(minutes, 2);
1626
+ }
1627
+
1628
+ function formatTimezoneWithOptionalMinutes(offset, dirtyDelimiter) {
1629
+ if (offset % 60 === 0) {
1630
+ var sign = offset > 0 ? '-' : '+';
1631
+ return sign + addLeadingZeros(Math.abs(offset) / 60, 2);
1632
+ }
1633
+
1634
+ return formatTimezone(offset, dirtyDelimiter);
1635
+ }
1636
+
1637
+ function formatTimezone(offset, dirtyDelimiter) {
1638
+ var delimiter = dirtyDelimiter || '';
1639
+ var sign = offset > 0 ? '-' : '+';
1640
+ var absOffset = Math.abs(offset);
1641
+ var hours = addLeadingZeros(Math.floor(absOffset / 60), 2);
1642
+ var minutes = addLeadingZeros(absOffset % 60, 2);
1643
+ return sign + hours + delimiter + minutes;
1644
+ }
1645
+
1646
+ var dateLongFormatter = function dateLongFormatter(pattern, formatLong) {
1647
+ switch (pattern) {
1648
+ case 'P':
1649
+ return formatLong.date({
1650
+ width: 'short'
1651
+ });
1652
+
1653
+ case 'PP':
1654
+ return formatLong.date({
1655
+ width: 'medium'
1656
+ });
1657
+
1658
+ case 'PPP':
1659
+ return formatLong.date({
1660
+ width: 'long'
1661
+ });
1662
+
1663
+ case 'PPPP':
1664
+ default:
1665
+ return formatLong.date({
1666
+ width: 'full'
1667
+ });
1668
+ }
1669
+ };
1670
+
1671
+ var timeLongFormatter = function timeLongFormatter(pattern, formatLong) {
1672
+ switch (pattern) {
1673
+ case 'p':
1674
+ return formatLong.time({
1675
+ width: 'short'
1676
+ });
1677
+
1678
+ case 'pp':
1679
+ return formatLong.time({
1680
+ width: 'medium'
1681
+ });
1682
+
1683
+ case 'ppp':
1684
+ return formatLong.time({
1685
+ width: 'long'
1686
+ });
1687
+
1688
+ case 'pppp':
1689
+ default:
1690
+ return formatLong.time({
1691
+ width: 'full'
1692
+ });
1693
+ }
1694
+ };
1695
+
1696
+ var dateTimeLongFormatter = function dateTimeLongFormatter(pattern, formatLong) {
1697
+ var matchResult = pattern.match(/(P+)(p+)?/) || [];
1698
+ var datePattern = matchResult[1];
1699
+ var timePattern = matchResult[2];
1700
+
1701
+ if (!timePattern) {
1702
+ return dateLongFormatter(pattern, formatLong);
1703
+ }
1704
+
1705
+ var dateTimeFormat;
1706
+
1707
+ switch (datePattern) {
1708
+ case 'P':
1709
+ dateTimeFormat = formatLong.dateTime({
1710
+ width: 'short'
1711
+ });
1712
+ break;
1713
+
1714
+ case 'PP':
1715
+ dateTimeFormat = formatLong.dateTime({
1716
+ width: 'medium'
1717
+ });
1718
+ break;
1719
+
1720
+ case 'PPP':
1721
+ dateTimeFormat = formatLong.dateTime({
1722
+ width: 'long'
1723
+ });
1724
+ break;
1725
+
1726
+ case 'PPPP':
1727
+ default:
1728
+ dateTimeFormat = formatLong.dateTime({
1729
+ width: 'full'
1730
+ });
1731
+ break;
1732
+ }
1733
+
1734
+ return dateTimeFormat.replace('{{date}}', dateLongFormatter(datePattern, formatLong)).replace('{{time}}', timeLongFormatter(timePattern, formatLong));
1735
+ };
1736
+
1737
+ var longFormatters = {
1738
+ p: timeLongFormatter,
1739
+ P: dateTimeLongFormatter
1740
+ };
1741
+
1742
+ var protectedDayOfYearTokens = ['D', 'DD'];
1743
+ var protectedWeekYearTokens = ['YY', 'YYYY'];
1744
+ function isProtectedDayOfYearToken(token) {
1745
+ return protectedDayOfYearTokens.indexOf(token) !== -1;
1746
+ }
1747
+ function isProtectedWeekYearToken(token) {
1748
+ return protectedWeekYearTokens.indexOf(token) !== -1;
1749
+ }
1750
+ function throwProtectedError(token, format, input) {
1751
+ if (token === 'YYYY') {
1752
+ throw new RangeError("Use `yyyy` instead of `YYYY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1753
+ } else if (token === 'YY') {
1754
+ throw new RangeError("Use `yy` instead of `YY` (in `".concat(format, "`) for formatting years to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1755
+ } else if (token === 'D') {
1756
+ throw new RangeError("Use `d` instead of `D` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1757
+ } else if (token === 'DD') {
1758
+ throw new RangeError("Use `dd` instead of `DD` (in `".concat(format, "`) for formatting days of the month to the input `").concat(input, "`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md"));
1759
+ }
1760
+ }
1761
+
1762
+ var formatDistanceLocale = {
1763
+ lessThanXSeconds: {
1764
+ one: 'less than a second',
1765
+ other: 'less than {{count}} seconds'
1766
+ },
1767
+ xSeconds: {
1768
+ one: '1 second',
1769
+ other: '{{count}} seconds'
1770
+ },
1771
+ halfAMinute: 'half a minute',
1772
+ lessThanXMinutes: {
1773
+ one: 'less than a minute',
1774
+ other: 'less than {{count}} minutes'
1775
+ },
1776
+ xMinutes: {
1777
+ one: '1 minute',
1778
+ other: '{{count}} minutes'
1779
+ },
1780
+ aboutXHours: {
1781
+ one: 'about 1 hour',
1782
+ other: 'about {{count}} hours'
1783
+ },
1784
+ xHours: {
1785
+ one: '1 hour',
1786
+ other: '{{count}} hours'
1787
+ },
1788
+ xDays: {
1789
+ one: '1 day',
1790
+ other: '{{count}} days'
1791
+ },
1792
+ aboutXWeeks: {
1793
+ one: 'about 1 week',
1794
+ other: 'about {{count}} weeks'
1795
+ },
1796
+ xWeeks: {
1797
+ one: '1 week',
1798
+ other: '{{count}} weeks'
1799
+ },
1800
+ aboutXMonths: {
1801
+ one: 'about 1 month',
1802
+ other: 'about {{count}} months'
1803
+ },
1804
+ xMonths: {
1805
+ one: '1 month',
1806
+ other: '{{count}} months'
1807
+ },
1808
+ aboutXYears: {
1809
+ one: 'about 1 year',
1810
+ other: 'about {{count}} years'
1811
+ },
1812
+ xYears: {
1813
+ one: '1 year',
1814
+ other: '{{count}} years'
1815
+ },
1816
+ overXYears: {
1817
+ one: 'over 1 year',
1818
+ other: 'over {{count}} years'
1819
+ },
1820
+ almostXYears: {
1821
+ one: 'almost 1 year',
1822
+ other: 'almost {{count}} years'
1823
+ }
1824
+ };
1825
+
1826
+ var formatDistance = function formatDistance(token, count, options) {
1827
+ var result;
1828
+ var tokenValue = formatDistanceLocale[token];
1829
+
1830
+ if (typeof tokenValue === 'string') {
1831
+ result = tokenValue;
1832
+ } else if (count === 1) {
1833
+ result = tokenValue.one;
1834
+ } else {
1835
+ result = tokenValue.other.replace('{{count}}', count.toString());
1836
+ }
1837
+
1838
+ if (options !== null && options !== void 0 && options.addSuffix) {
1839
+ if (options.comparison && options.comparison > 0) {
1840
+ return 'in ' + result;
1841
+ } else {
1842
+ return result + ' ago';
1843
+ }
1844
+ }
1845
+
1846
+ return result;
1847
+ };
1848
+
1849
+ function buildFormatLongFn(args) {
1850
+ return function () {
1851
+ var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
1852
+ // TODO: Remove String()
1853
+ var width = options.width ? String(options.width) : args.defaultWidth;
1854
+ var format = args.formats[width] || args.formats[args.defaultWidth];
1855
+ return format;
1856
+ };
1857
+ }
1858
+
1859
+ var dateFormats = {
1860
+ full: 'EEEE, MMMM do, y',
1861
+ long: 'MMMM do, y',
1862
+ medium: 'MMM d, y',
1863
+ short: 'MM/dd/yyyy'
1864
+ };
1865
+ var timeFormats = {
1866
+ full: 'h:mm:ss a zzzz',
1867
+ long: 'h:mm:ss a z',
1868
+ medium: 'h:mm:ss a',
1869
+ short: 'h:mm a'
1870
+ };
1871
+ var dateTimeFormats = {
1872
+ full: "{{date}} 'at' {{time}}",
1873
+ long: "{{date}} 'at' {{time}}",
1874
+ medium: '{{date}}, {{time}}',
1875
+ short: '{{date}}, {{time}}'
1876
+ };
1877
+ var formatLong = {
1878
+ date: buildFormatLongFn({
1879
+ formats: dateFormats,
1880
+ defaultWidth: 'full'
1881
+ }),
1882
+ time: buildFormatLongFn({
1883
+ formats: timeFormats,
1884
+ defaultWidth: 'full'
1885
+ }),
1886
+ dateTime: buildFormatLongFn({
1887
+ formats: dateTimeFormats,
1888
+ defaultWidth: 'full'
1889
+ })
1890
+ };
1891
+
1892
+ var formatRelativeLocale = {
1893
+ lastWeek: "'last' eeee 'at' p",
1894
+ yesterday: "'yesterday at' p",
1895
+ today: "'today at' p",
1896
+ tomorrow: "'tomorrow at' p",
1897
+ nextWeek: "eeee 'at' p",
1898
+ other: 'P'
1899
+ };
1900
+
1901
+ var formatRelative = function formatRelative(token, _date, _baseDate, _options) {
1902
+ return formatRelativeLocale[token];
1903
+ };
1904
+
1905
+ function buildLocalizeFn(args) {
1906
+ return function (dirtyIndex, options) {
1907
+ var context = options !== null && options !== void 0 && options.context ? String(options.context) : 'standalone';
1908
+ var valuesArray;
1909
+
1910
+ if (context === 'formatting' && args.formattingValues) {
1911
+ var defaultWidth = args.defaultFormattingWidth || args.defaultWidth;
1912
+ var width = options !== null && options !== void 0 && options.width ? String(options.width) : defaultWidth;
1913
+ valuesArray = args.formattingValues[width] || args.formattingValues[defaultWidth];
1914
+ } else {
1915
+ var _defaultWidth = args.defaultWidth;
1916
+
1917
+ var _width = options !== null && options !== void 0 && options.width ? String(options.width) : args.defaultWidth;
1918
+
1919
+ valuesArray = args.values[_width] || args.values[_defaultWidth];
1920
+ }
1921
+
1922
+ var index = args.argumentCallback ? args.argumentCallback(dirtyIndex) : dirtyIndex; // @ts-ignore: For some reason TypeScript just don't want to match it, no matter how hard we try. I challenge you to try to remove it!
1923
+
1924
+ return valuesArray[index];
1925
+ };
1926
+ }
1927
+
1928
+ var eraValues = {
1929
+ narrow: ['B', 'A'],
1930
+ abbreviated: ['BC', 'AD'],
1931
+ wide: ['Before Christ', 'Anno Domini']
1932
+ };
1933
+ var quarterValues = {
1934
+ narrow: ['1', '2', '3', '4'],
1935
+ abbreviated: ['Q1', 'Q2', 'Q3', 'Q4'],
1936
+ wide: ['1st quarter', '2nd quarter', '3rd quarter', '4th quarter']
1937
+ }; // Note: in English, the names of days of the week and months are capitalized.
1938
+ // If you are making a new locale based on this one, check if the same is true for the language you're working on.
1939
+ // Generally, formatted dates should look like they are in the middle of a sentence,
1940
+ // e.g. in Spanish language the weekdays and months should be in the lowercase.
1941
+
1942
+ var monthValues = {
1943
+ narrow: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
1944
+ abbreviated: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
1945
+ wide: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
1946
+ };
1947
+ var dayValues = {
1948
+ narrow: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
1949
+ short: ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'],
1950
+ abbreviated: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
1951
+ wide: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
1952
+ };
1953
+ var dayPeriodValues = {
1954
+ narrow: {
1955
+ am: 'a',
1956
+ pm: 'p',
1957
+ midnight: 'mi',
1958
+ noon: 'n',
1959
+ morning: 'morning',
1960
+ afternoon: 'afternoon',
1961
+ evening: 'evening',
1962
+ night: 'night'
1963
+ },
1964
+ abbreviated: {
1965
+ am: 'AM',
1966
+ pm: 'PM',
1967
+ midnight: 'midnight',
1968
+ noon: 'noon',
1969
+ morning: 'morning',
1970
+ afternoon: 'afternoon',
1971
+ evening: 'evening',
1972
+ night: 'night'
1973
+ },
1974
+ wide: {
1975
+ am: 'a.m.',
1976
+ pm: 'p.m.',
1977
+ midnight: 'midnight',
1978
+ noon: 'noon',
1979
+ morning: 'morning',
1980
+ afternoon: 'afternoon',
1981
+ evening: 'evening',
1982
+ night: 'night'
1983
+ }
1984
+ };
1985
+ var formattingDayPeriodValues = {
1986
+ narrow: {
1987
+ am: 'a',
1988
+ pm: 'p',
1989
+ midnight: 'mi',
1990
+ noon: 'n',
1991
+ morning: 'in the morning',
1992
+ afternoon: 'in the afternoon',
1993
+ evening: 'in the evening',
1994
+ night: 'at night'
1995
+ },
1996
+ abbreviated: {
1997
+ am: 'AM',
1998
+ pm: 'PM',
1999
+ midnight: 'midnight',
2000
+ noon: 'noon',
2001
+ morning: 'in the morning',
2002
+ afternoon: 'in the afternoon',
2003
+ evening: 'in the evening',
2004
+ night: 'at night'
2005
+ },
2006
+ wide: {
2007
+ am: 'a.m.',
2008
+ pm: 'p.m.',
2009
+ midnight: 'midnight',
2010
+ noon: 'noon',
2011
+ morning: 'in the morning',
2012
+ afternoon: 'in the afternoon',
2013
+ evening: 'in the evening',
2014
+ night: 'at night'
2015
+ }
2016
+ };
2017
+
2018
+ var ordinalNumber = function ordinalNumber(dirtyNumber, _options) {
2019
+ var number = Number(dirtyNumber); // If ordinal numbers depend on context, for example,
2020
+ // if they are different for different grammatical genders,
2021
+ // use `options.unit`.
2022
+ //
2023
+ // `unit` can be 'year', 'quarter', 'month', 'week', 'date', 'dayOfYear',
2024
+ // 'day', 'hour', 'minute', 'second'.
2025
+
2026
+ var rem100 = number % 100;
2027
+
2028
+ if (rem100 > 20 || rem100 < 10) {
2029
+ switch (rem100 % 10) {
2030
+ case 1:
2031
+ return number + 'st';
2032
+
2033
+ case 2:
2034
+ return number + 'nd';
2035
+
2036
+ case 3:
2037
+ return number + 'rd';
2038
+ }
2039
+ }
2040
+
2041
+ return number + 'th';
2042
+ };
2043
+
2044
+ var localize = {
2045
+ ordinalNumber: ordinalNumber,
2046
+ era: buildLocalizeFn({
2047
+ values: eraValues,
2048
+ defaultWidth: 'wide'
2049
+ }),
2050
+ quarter: buildLocalizeFn({
2051
+ values: quarterValues,
2052
+ defaultWidth: 'wide',
2053
+ argumentCallback: function argumentCallback(quarter) {
2054
+ return quarter - 1;
2055
+ }
2056
+ }),
2057
+ month: buildLocalizeFn({
2058
+ values: monthValues,
2059
+ defaultWidth: 'wide'
2060
+ }),
2061
+ day: buildLocalizeFn({
2062
+ values: dayValues,
2063
+ defaultWidth: 'wide'
2064
+ }),
2065
+ dayPeriod: buildLocalizeFn({
2066
+ values: dayPeriodValues,
2067
+ defaultWidth: 'wide',
2068
+ formattingValues: formattingDayPeriodValues,
2069
+ defaultFormattingWidth: 'wide'
2070
+ })
2071
+ };
2072
+
2073
+ function buildMatchFn(args) {
2074
+ return function (string) {
2075
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2076
+ var width = options.width;
2077
+ var matchPattern = width && args.matchPatterns[width] || args.matchPatterns[args.defaultMatchWidth];
2078
+ var matchResult = string.match(matchPattern);
2079
+
2080
+ if (!matchResult) {
2081
+ return null;
2082
+ }
2083
+
2084
+ var matchedString = matchResult[0];
2085
+ var parsePatterns = width && args.parsePatterns[width] || args.parsePatterns[args.defaultParseWidth];
2086
+ var key = Array.isArray(parsePatterns) ? findIndex(parsePatterns, function (pattern) {
2087
+ return pattern.test(matchedString);
2088
+ }) : findKey(parsePatterns, function (pattern) {
2089
+ return pattern.test(matchedString);
2090
+ });
2091
+ var value;
2092
+ value = args.valueCallback ? args.valueCallback(key) : key;
2093
+ value = options.valueCallback ? options.valueCallback(value) : value;
2094
+ var rest = string.slice(matchedString.length);
2095
+ return {
2096
+ value: value,
2097
+ rest: rest
2098
+ };
2099
+ };
2100
+ }
2101
+
2102
+ function findKey(object, predicate) {
2103
+ for (var key in object) {
2104
+ if (object.hasOwnProperty(key) && predicate(object[key])) {
2105
+ return key;
2106
+ }
2107
+ }
2108
+
2109
+ return undefined;
2110
+ }
2111
+
2112
+ function findIndex(array, predicate) {
2113
+ for (var key = 0; key < array.length; key++) {
2114
+ if (predicate(array[key])) {
2115
+ return key;
2116
+ }
2117
+ }
2118
+
2119
+ return undefined;
2120
+ }
2121
+
2122
+ function buildMatchPatternFn(args) {
2123
+ return function (string) {
2124
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2125
+ var matchResult = string.match(args.matchPattern);
2126
+ if (!matchResult) return null;
2127
+ var matchedString = matchResult[0];
2128
+ var parseResult = string.match(args.parsePattern);
2129
+ if (!parseResult) return null;
2130
+ var value = args.valueCallback ? args.valueCallback(parseResult[0]) : parseResult[0];
2131
+ value = options.valueCallback ? options.valueCallback(value) : value;
2132
+ var rest = string.slice(matchedString.length);
2133
+ return {
2134
+ value: value,
2135
+ rest: rest
2136
+ };
2137
+ };
2138
+ }
2139
+
2140
+ var matchOrdinalNumberPattern = /^(\d+)(th|st|nd|rd)?/i;
2141
+ var parseOrdinalNumberPattern = /\d+/i;
2142
+ var matchEraPatterns = {
2143
+ narrow: /^(b|a)/i,
2144
+ abbreviated: /^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,
2145
+ wide: /^(before christ|before common era|anno domini|common era)/i
2146
+ };
2147
+ var parseEraPatterns = {
2148
+ any: [/^b/i, /^(a|c)/i]
2149
+ };
2150
+ var matchQuarterPatterns = {
2151
+ narrow: /^[1234]/i,
2152
+ abbreviated: /^q[1234]/i,
2153
+ wide: /^[1234](th|st|nd|rd)? quarter/i
2154
+ };
2155
+ var parseQuarterPatterns = {
2156
+ any: [/1/i, /2/i, /3/i, /4/i]
2157
+ };
2158
+ var matchMonthPatterns = {
2159
+ narrow: /^[jfmasond]/i,
2160
+ abbreviated: /^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,
2161
+ wide: /^(january|february|march|april|may|june|july|august|september|october|november|december)/i
2162
+ };
2163
+ var parseMonthPatterns = {
2164
+ narrow: [/^j/i, /^f/i, /^m/i, /^a/i, /^m/i, /^j/i, /^j/i, /^a/i, /^s/i, /^o/i, /^n/i, /^d/i],
2165
+ any: [/^ja/i, /^f/i, /^mar/i, /^ap/i, /^may/i, /^jun/i, /^jul/i, /^au/i, /^s/i, /^o/i, /^n/i, /^d/i]
2166
+ };
2167
+ var matchDayPatterns = {
2168
+ narrow: /^[smtwf]/i,
2169
+ short: /^(su|mo|tu|we|th|fr|sa)/i,
2170
+ abbreviated: /^(sun|mon|tue|wed|thu|fri|sat)/i,
2171
+ wide: /^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i
2172
+ };
2173
+ var parseDayPatterns = {
2174
+ narrow: [/^s/i, /^m/i, /^t/i, /^w/i, /^t/i, /^f/i, /^s/i],
2175
+ any: [/^su/i, /^m/i, /^tu/i, /^w/i, /^th/i, /^f/i, /^sa/i]
2176
+ };
2177
+ var matchDayPeriodPatterns = {
2178
+ narrow: /^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,
2179
+ any: /^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i
2180
+ };
2181
+ var parseDayPeriodPatterns = {
2182
+ any: {
2183
+ am: /^a/i,
2184
+ pm: /^p/i,
2185
+ midnight: /^mi/i,
2186
+ noon: /^no/i,
2187
+ morning: /morning/i,
2188
+ afternoon: /afternoon/i,
2189
+ evening: /evening/i,
2190
+ night: /night/i
2191
+ }
2192
+ };
2193
+ var match = {
2194
+ ordinalNumber: buildMatchPatternFn({
2195
+ matchPattern: matchOrdinalNumberPattern,
2196
+ parsePattern: parseOrdinalNumberPattern,
2197
+ valueCallback: function valueCallback(value) {
2198
+ return parseInt(value, 10);
2199
+ }
2200
+ }),
2201
+ era: buildMatchFn({
2202
+ matchPatterns: matchEraPatterns,
2203
+ defaultMatchWidth: 'wide',
2204
+ parsePatterns: parseEraPatterns,
2205
+ defaultParseWidth: 'any'
2206
+ }),
2207
+ quarter: buildMatchFn({
2208
+ matchPatterns: matchQuarterPatterns,
2209
+ defaultMatchWidth: 'wide',
2210
+ parsePatterns: parseQuarterPatterns,
2211
+ defaultParseWidth: 'any',
2212
+ valueCallback: function valueCallback(index) {
2213
+ return index + 1;
2214
+ }
2215
+ }),
2216
+ month: buildMatchFn({
2217
+ matchPatterns: matchMonthPatterns,
2218
+ defaultMatchWidth: 'wide',
2219
+ parsePatterns: parseMonthPatterns,
2220
+ defaultParseWidth: 'any'
2221
+ }),
2222
+ day: buildMatchFn({
2223
+ matchPatterns: matchDayPatterns,
2224
+ defaultMatchWidth: 'wide',
2225
+ parsePatterns: parseDayPatterns,
2226
+ defaultParseWidth: 'any'
2227
+ }),
2228
+ dayPeriod: buildMatchFn({
2229
+ matchPatterns: matchDayPeriodPatterns,
2230
+ defaultMatchWidth: 'any',
2231
+ parsePatterns: parseDayPeriodPatterns,
2232
+ defaultParseWidth: 'any'
2233
+ })
2234
+ };
2235
+
2236
+ /**
2237
+ * @type {Locale}
2238
+ * @category Locales
2239
+ * @summary English locale (United States).
2240
+ * @language English
2241
+ * @iso-639-2 eng
2242
+ * @author Sasha Koss [@kossnocorp]{@link https://github.com/kossnocorp}
2243
+ * @author Lesha Koss [@leshakoss]{@link https://github.com/leshakoss}
2244
+ */
2245
+ var locale = {
2246
+ code: 'en-US',
2247
+ formatDistance: formatDistance,
2248
+ formatLong: formatLong,
2249
+ formatRelative: formatRelative,
2250
+ localize: localize,
2251
+ match: match,
2252
+ options: {
2253
+ weekStartsOn: 0
2254
+ /* Sunday */
2255
+ ,
2256
+ firstWeekContainsDate: 1
2257
+ }
2258
+ };
2259
+
2260
+ // - [yYQqMLwIdDecihHKkms]o matches any available ordinal number token
2261
+ // (one of the certain letters followed by `o`)
2262
+ // - (\w)\1* matches any sequences of the same letter
2263
+ // - '' matches two quote characters in a row
2264
+ // - '(''|[^'])+('|$) matches anything surrounded by two quote characters ('),
2265
+ // except a single quote symbol, which ends the sequence.
2266
+ // Two quote characters do not end the sequence.
2267
+ // If there is no matching single quote
2268
+ // then the sequence will continue until the end of the string.
2269
+ // - . matches any single character unmatched by previous parts of the RegExps
2270
+
2271
+ var formattingTokensRegExp = /[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g; // This RegExp catches symbols escaped by quotes, and also
2272
+ // sequences of symbols P, p, and the combinations like `PPPPPPPppppp`
2273
+
2274
+ var longFormattingTokensRegExp = /P+p+|P+|p+|''|'(''|[^'])+('|$)|./g;
2275
+ var escapedStringRegExp = /^'([^]*?)'?$/;
2276
+ var doubleQuoteRegExp = /''/g;
2277
+ var unescapedLatinCharacterRegExp = /[a-zA-Z]/;
2278
+ /**
2279
+ * @name format
2280
+ * @category Common Helpers
2281
+ * @summary Format the date.
2282
+ *
2283
+ * @description
2284
+ * Return the formatted date string in the given format. The result may vary by locale.
2285
+ *
2286
+ * > ⚠️ Please note that the `format` tokens differ from Moment.js and other libraries.
2287
+ * > See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2288
+ *
2289
+ * The characters wrapped between two single quotes characters (') are escaped.
2290
+ * Two single quotes in a row, whether inside or outside a quoted sequence, represent a 'real' single quote.
2291
+ * (see the last example)
2292
+ *
2293
+ * Format of the string is based on Unicode Technical Standard #35:
2294
+ * https://www.unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table
2295
+ * with a few additions (see note 7 below the table).
2296
+ *
2297
+ * Accepted patterns:
2298
+ * | Unit | Pattern | Result examples | Notes |
2299
+ * |---------------------------------|---------|-----------------------------------|-------|
2300
+ * | Era | G..GGG | AD, BC | |
2301
+ * | | GGGG | Anno Domini, Before Christ | 2 |
2302
+ * | | GGGGG | A, B | |
2303
+ * | Calendar year | y | 44, 1, 1900, 2017 | 5 |
2304
+ * | | yo | 44th, 1st, 0th, 17th | 5,7 |
2305
+ * | | yy | 44, 01, 00, 17 | 5 |
2306
+ * | | yyy | 044, 001, 1900, 2017 | 5 |
2307
+ * | | yyyy | 0044, 0001, 1900, 2017 | 5 |
2308
+ * | | yyyyy | ... | 3,5 |
2309
+ * | Local week-numbering year | Y | 44, 1, 1900, 2017 | 5 |
2310
+ * | | Yo | 44th, 1st, 1900th, 2017th | 5,7 |
2311
+ * | | YY | 44, 01, 00, 17 | 5,8 |
2312
+ * | | YYY | 044, 001, 1900, 2017 | 5 |
2313
+ * | | YYYY | 0044, 0001, 1900, 2017 | 5,8 |
2314
+ * | | YYYYY | ... | 3,5 |
2315
+ * | ISO week-numbering year | R | -43, 0, 1, 1900, 2017 | 5,7 |
2316
+ * | | RR | -43, 00, 01, 1900, 2017 | 5,7 |
2317
+ * | | RRR | -043, 000, 001, 1900, 2017 | 5,7 |
2318
+ * | | RRRR | -0043, 0000, 0001, 1900, 2017 | 5,7 |
2319
+ * | | RRRRR | ... | 3,5,7 |
2320
+ * | Extended year | u | -43, 0, 1, 1900, 2017 | 5 |
2321
+ * | | uu | -43, 01, 1900, 2017 | 5 |
2322
+ * | | uuu | -043, 001, 1900, 2017 | 5 |
2323
+ * | | uuuu | -0043, 0001, 1900, 2017 | 5 |
2324
+ * | | uuuuu | ... | 3,5 |
2325
+ * | Quarter (formatting) | Q | 1, 2, 3, 4 | |
2326
+ * | | Qo | 1st, 2nd, 3rd, 4th | 7 |
2327
+ * | | QQ | 01, 02, 03, 04 | |
2328
+ * | | QQQ | Q1, Q2, Q3, Q4 | |
2329
+ * | | QQQQ | 1st quarter, 2nd quarter, ... | 2 |
2330
+ * | | QQQQQ | 1, 2, 3, 4 | 4 |
2331
+ * | Quarter (stand-alone) | q | 1, 2, 3, 4 | |
2332
+ * | | qo | 1st, 2nd, 3rd, 4th | 7 |
2333
+ * | | qq | 01, 02, 03, 04 | |
2334
+ * | | qqq | Q1, Q2, Q3, Q4 | |
2335
+ * | | qqqq | 1st quarter, 2nd quarter, ... | 2 |
2336
+ * | | qqqqq | 1, 2, 3, 4 | 4 |
2337
+ * | Month (formatting) | M | 1, 2, ..., 12 | |
2338
+ * | | Mo | 1st, 2nd, ..., 12th | 7 |
2339
+ * | | MM | 01, 02, ..., 12 | |
2340
+ * | | MMM | Jan, Feb, ..., Dec | |
2341
+ * | | MMMM | January, February, ..., December | 2 |
2342
+ * | | MMMMM | J, F, ..., D | |
2343
+ * | Month (stand-alone) | L | 1, 2, ..., 12 | |
2344
+ * | | Lo | 1st, 2nd, ..., 12th | 7 |
2345
+ * | | LL | 01, 02, ..., 12 | |
2346
+ * | | LLL | Jan, Feb, ..., Dec | |
2347
+ * | | LLLL | January, February, ..., December | 2 |
2348
+ * | | LLLLL | J, F, ..., D | |
2349
+ * | Local week of year | w | 1, 2, ..., 53 | |
2350
+ * | | wo | 1st, 2nd, ..., 53th | 7 |
2351
+ * | | ww | 01, 02, ..., 53 | |
2352
+ * | ISO week of year | I | 1, 2, ..., 53 | 7 |
2353
+ * | | Io | 1st, 2nd, ..., 53th | 7 |
2354
+ * | | II | 01, 02, ..., 53 | 7 |
2355
+ * | Day of month | d | 1, 2, ..., 31 | |
2356
+ * | | do | 1st, 2nd, ..., 31st | 7 |
2357
+ * | | dd | 01, 02, ..., 31 | |
2358
+ * | Day of year | D | 1, 2, ..., 365, 366 | 9 |
2359
+ * | | Do | 1st, 2nd, ..., 365th, 366th | 7 |
2360
+ * | | DD | 01, 02, ..., 365, 366 | 9 |
2361
+ * | | DDD | 001, 002, ..., 365, 366 | |
2362
+ * | | DDDD | ... | 3 |
2363
+ * | Day of week (formatting) | E..EEE | Mon, Tue, Wed, ..., Sun | |
2364
+ * | | EEEE | Monday, Tuesday, ..., Sunday | 2 |
2365
+ * | | EEEEE | M, T, W, T, F, S, S | |
2366
+ * | | EEEEEE | Mo, Tu, We, Th, Fr, Sa, Su | |
2367
+ * | ISO day of week (formatting) | i | 1, 2, 3, ..., 7 | 7 |
2368
+ * | | io | 1st, 2nd, ..., 7th | 7 |
2369
+ * | | ii | 01, 02, ..., 07 | 7 |
2370
+ * | | iii | Mon, Tue, Wed, ..., Sun | 7 |
2371
+ * | | iiii | Monday, Tuesday, ..., Sunday | 2,7 |
2372
+ * | | iiiii | M, T, W, T, F, S, S | 7 |
2373
+ * | | iiiiii | Mo, Tu, We, Th, Fr, Sa, Su | 7 |
2374
+ * | Local day of week (formatting) | e | 2, 3, 4, ..., 1 | |
2375
+ * | | eo | 2nd, 3rd, ..., 1st | 7 |
2376
+ * | | ee | 02, 03, ..., 01 | |
2377
+ * | | eee | Mon, Tue, Wed, ..., Sun | |
2378
+ * | | eeee | Monday, Tuesday, ..., Sunday | 2 |
2379
+ * | | eeeee | M, T, W, T, F, S, S | |
2380
+ * | | eeeeee | Mo, Tu, We, Th, Fr, Sa, Su | |
2381
+ * | Local day of week (stand-alone) | c | 2, 3, 4, ..., 1 | |
2382
+ * | | co | 2nd, 3rd, ..., 1st | 7 |
2383
+ * | | cc | 02, 03, ..., 01 | |
2384
+ * | | ccc | Mon, Tue, Wed, ..., Sun | |
2385
+ * | | cccc | Monday, Tuesday, ..., Sunday | 2 |
2386
+ * | | ccccc | M, T, W, T, F, S, S | |
2387
+ * | | cccccc | Mo, Tu, We, Th, Fr, Sa, Su | |
2388
+ * | AM, PM | a..aa | AM, PM | |
2389
+ * | | aaa | am, pm | |
2390
+ * | | aaaa | a.m., p.m. | 2 |
2391
+ * | | aaaaa | a, p | |
2392
+ * | AM, PM, noon, midnight | b..bb | AM, PM, noon, midnight | |
2393
+ * | | bbb | am, pm, noon, midnight | |
2394
+ * | | bbbb | a.m., p.m., noon, midnight | 2 |
2395
+ * | | bbbbb | a, p, n, mi | |
2396
+ * | Flexible day period | B..BBB | at night, in the morning, ... | |
2397
+ * | | BBBB | at night, in the morning, ... | 2 |
2398
+ * | | BBBBB | at night, in the morning, ... | |
2399
+ * | Hour [1-12] | h | 1, 2, ..., 11, 12 | |
2400
+ * | | ho | 1st, 2nd, ..., 11th, 12th | 7 |
2401
+ * | | hh | 01, 02, ..., 11, 12 | |
2402
+ * | Hour [0-23] | H | 0, 1, 2, ..., 23 | |
2403
+ * | | Ho | 0th, 1st, 2nd, ..., 23rd | 7 |
2404
+ * | | HH | 00, 01, 02, ..., 23 | |
2405
+ * | Hour [0-11] | K | 1, 2, ..., 11, 0 | |
2406
+ * | | Ko | 1st, 2nd, ..., 11th, 0th | 7 |
2407
+ * | | KK | 01, 02, ..., 11, 00 | |
2408
+ * | Hour [1-24] | k | 24, 1, 2, ..., 23 | |
2409
+ * | | ko | 24th, 1st, 2nd, ..., 23rd | 7 |
2410
+ * | | kk | 24, 01, 02, ..., 23 | |
2411
+ * | Minute | m | 0, 1, ..., 59 | |
2412
+ * | | mo | 0th, 1st, ..., 59th | 7 |
2413
+ * | | mm | 00, 01, ..., 59 | |
2414
+ * | Second | s | 0, 1, ..., 59 | |
2415
+ * | | so | 0th, 1st, ..., 59th | 7 |
2416
+ * | | ss | 00, 01, ..., 59 | |
2417
+ * | Fraction of second | S | 0, 1, ..., 9 | |
2418
+ * | | SS | 00, 01, ..., 99 | |
2419
+ * | | SSS | 000, 001, ..., 999 | |
2420
+ * | | SSSS | ... | 3 |
2421
+ * | Timezone (ISO-8601 w/ Z) | X | -08, +0530, Z | |
2422
+ * | | XX | -0800, +0530, Z | |
2423
+ * | | XXX | -08:00, +05:30, Z | |
2424
+ * | | XXXX | -0800, +0530, Z, +123456 | 2 |
2425
+ * | | XXXXX | -08:00, +05:30, Z, +12:34:56 | |
2426
+ * | Timezone (ISO-8601 w/o Z) | x | -08, +0530, +00 | |
2427
+ * | | xx | -0800, +0530, +0000 | |
2428
+ * | | xxx | -08:00, +05:30, +00:00 | 2 |
2429
+ * | | xxxx | -0800, +0530, +0000, +123456 | |
2430
+ * | | xxxxx | -08:00, +05:30, +00:00, +12:34:56 | |
2431
+ * | Timezone (GMT) | O...OOO | GMT-8, GMT+5:30, GMT+0 | |
2432
+ * | | OOOO | GMT-08:00, GMT+05:30, GMT+00:00 | 2 |
2433
+ * | Timezone (specific non-locat.) | z...zzz | GMT-8, GMT+5:30, GMT+0 | 6 |
2434
+ * | | zzzz | GMT-08:00, GMT+05:30, GMT+00:00 | 2,6 |
2435
+ * | Seconds timestamp | t | 512969520 | 7 |
2436
+ * | | tt | ... | 3,7 |
2437
+ * | Milliseconds timestamp | T | 512969520900 | 7 |
2438
+ * | | TT | ... | 3,7 |
2439
+ * | Long localized date | P | 04/29/1453 | 7 |
2440
+ * | | PP | Apr 29, 1453 | 7 |
2441
+ * | | PPP | April 29th, 1453 | 7 |
2442
+ * | | PPPP | Friday, April 29th, 1453 | 2,7 |
2443
+ * | Long localized time | p | 12:00 AM | 7 |
2444
+ * | | pp | 12:00:00 AM | 7 |
2445
+ * | | ppp | 12:00:00 AM GMT+2 | 7 |
2446
+ * | | pppp | 12:00:00 AM GMT+02:00 | 2,7 |
2447
+ * | Combination of date and time | Pp | 04/29/1453, 12:00 AM | 7 |
2448
+ * | | PPpp | Apr 29, 1453, 12:00:00 AM | 7 |
2449
+ * | | PPPppp | April 29th, 1453 at ... | 7 |
2450
+ * | | PPPPpppp| Friday, April 29th, 1453 at ... | 2,7 |
2451
+ * Notes:
2452
+ * 1. "Formatting" units (e.g. formatting quarter) in the default en-US locale
2453
+ * are the same as "stand-alone" units, but are different in some languages.
2454
+ * "Formatting" units are declined according to the rules of the language
2455
+ * in the context of a date. "Stand-alone" units are always nominative singular:
2456
+ *
2457
+ * `format(new Date(2017, 10, 6), 'do LLLL', {locale: cs}) //=> '6. listopad'`
2458
+ *
2459
+ * `format(new Date(2017, 10, 6), 'do MMMM', {locale: cs}) //=> '6. listopadu'`
2460
+ *
2461
+ * 2. Any sequence of the identical letters is a pattern, unless it is escaped by
2462
+ * the single quote characters (see below).
2463
+ * If the sequence is longer than listed in table (e.g. `EEEEEEEEEEE`)
2464
+ * the output will be the same as default pattern for this unit, usually
2465
+ * the longest one (in case of ISO weekdays, `EEEE`). Default patterns for units
2466
+ * are marked with "2" in the last column of the table.
2467
+ *
2468
+ * `format(new Date(2017, 10, 6), 'MMM') //=> 'Nov'`
2469
+ *
2470
+ * `format(new Date(2017, 10, 6), 'MMMM') //=> 'November'`
2471
+ *
2472
+ * `format(new Date(2017, 10, 6), 'MMMMM') //=> 'N'`
2473
+ *
2474
+ * `format(new Date(2017, 10, 6), 'MMMMMM') //=> 'November'`
2475
+ *
2476
+ * `format(new Date(2017, 10, 6), 'MMMMMMM') //=> 'November'`
2477
+ *
2478
+ * 3. Some patterns could be unlimited length (such as `yyyyyyyy`).
2479
+ * The output will be padded with zeros to match the length of the pattern.
2480
+ *
2481
+ * `format(new Date(2017, 10, 6), 'yyyyyyyy') //=> '00002017'`
2482
+ *
2483
+ * 4. `QQQQQ` and `qqqqq` could be not strictly numerical in some locales.
2484
+ * These tokens represent the shortest form of the quarter.
2485
+ *
2486
+ * 5. The main difference between `y` and `u` patterns are B.C. years:
2487
+ *
2488
+ * | Year | `y` | `u` |
2489
+ * |------|-----|-----|
2490
+ * | AC 1 | 1 | 1 |
2491
+ * | BC 1 | 1 | 0 |
2492
+ * | BC 2 | 2 | -1 |
2493
+ *
2494
+ * Also `yy` always returns the last two digits of a year,
2495
+ * while `uu` pads single digit years to 2 characters and returns other years unchanged:
2496
+ *
2497
+ * | Year | `yy` | `uu` |
2498
+ * |------|------|------|
2499
+ * | 1 | 01 | 01 |
2500
+ * | 14 | 14 | 14 |
2501
+ * | 376 | 76 | 376 |
2502
+ * | 1453 | 53 | 1453 |
2503
+ *
2504
+ * The same difference is true for local and ISO week-numbering years (`Y` and `R`),
2505
+ * except local week-numbering years are dependent on `options.weekStartsOn`
2506
+ * and `options.firstWeekContainsDate` (compare [getISOWeekYear]{@link https://date-fns.org/docs/getISOWeekYear}
2507
+ * and [getWeekYear]{@link https://date-fns.org/docs/getWeekYear}).
2508
+ *
2509
+ * 6. Specific non-location timezones are currently unavailable in `date-fns`,
2510
+ * so right now these tokens fall back to GMT timezones.
2511
+ *
2512
+ * 7. These patterns are not in the Unicode Technical Standard #35:
2513
+ * - `i`: ISO day of week
2514
+ * - `I`: ISO week of year
2515
+ * - `R`: ISO week-numbering year
2516
+ * - `t`: seconds timestamp
2517
+ * - `T`: milliseconds timestamp
2518
+ * - `o`: ordinal number modifier
2519
+ * - `P`: long localized date
2520
+ * - `p`: long localized time
2521
+ *
2522
+ * 8. `YY` and `YYYY` tokens represent week-numbering years but they are often confused with years.
2523
+ * You should enable `options.useAdditionalWeekYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2524
+ *
2525
+ * 9. `D` and `DD` tokens represent days of the year but they are often confused with days of the month.
2526
+ * You should enable `options.useAdditionalDayOfYearTokens` to use them. See: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2527
+ *
2528
+ * @param {Date|Number} date - the original date
2529
+ * @param {String} format - the string of tokens
2530
+ * @param {Object} [options] - an object with options.
2531
+ * @param {Locale} [options.locale=defaultLocale] - the locale object. See [Locale]{@link https://date-fns.org/docs/Locale}
2532
+ * @param {0|1|2|3|4|5|6} [options.weekStartsOn=0] - the index of the first day of the week (0 - Sunday)
2533
+ * @param {Number} [options.firstWeekContainsDate=1] - the day of January, which is
2534
+ * @param {Boolean} [options.useAdditionalWeekYearTokens=false] - if true, allows usage of the week-numbering year tokens `YY` and `YYYY`;
2535
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2536
+ * @param {Boolean} [options.useAdditionalDayOfYearTokens=false] - if true, allows usage of the day of year tokens `D` and `DD`;
2537
+ * see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2538
+ * @returns {String} the formatted date string
2539
+ * @throws {TypeError} 2 arguments required
2540
+ * @throws {RangeError} `date` must not be Invalid Date
2541
+ * @throws {RangeError} `options.locale` must contain `localize` property
2542
+ * @throws {RangeError} `options.locale` must contain `formatLong` property
2543
+ * @throws {RangeError} `options.weekStartsOn` must be between 0 and 6
2544
+ * @throws {RangeError} `options.firstWeekContainsDate` must be between 1 and 7
2545
+ * @throws {RangeError} use `yyyy` instead of `YYYY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2546
+ * @throws {RangeError} use `yy` instead of `YY` for formatting years using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2547
+ * @throws {RangeError} use `d` instead of `D` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2548
+ * @throws {RangeError} use `dd` instead of `DD` for formatting days of the month using [format provided] to the input [input provided]; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
2549
+ * @throws {RangeError} format string contains an unescaped latin alphabet character
2550
+ *
2551
+ * @example
2552
+ * // Represent 11 February 2014 in middle-endian format:
2553
+ * const result = format(new Date(2014, 1, 11), 'MM/dd/yyyy')
2554
+ * //=> '02/11/2014'
2555
+ *
2556
+ * @example
2557
+ * // Represent 2 July 2014 in Esperanto:
2558
+ * import { eoLocale } from 'date-fns/locale/eo'
2559
+ * const result = format(new Date(2014, 6, 2), "do 'de' MMMM yyyy", {
2560
+ * locale: eoLocale
2561
+ * })
2562
+ * //=> '2-a de julio 2014'
2563
+ *
2564
+ * @example
2565
+ * // Escape string by single quote characters:
2566
+ * const result = format(new Date(2014, 6, 2, 15), "h 'o''clock'")
2567
+ * //=> "3 o'clock"
2568
+ */
2569
+
2570
+ function format(dirtyDate, dirtyFormatStr, options) {
2571
+ var _ref, _options$locale, _ref2, _ref3, _ref4, _options$firstWeekCon, _options$locale2, _options$locale2$opti, _defaultOptions$local, _defaultOptions$local2, _ref5, _ref6, _ref7, _options$weekStartsOn, _options$locale3, _options$locale3$opti, _defaultOptions$local3, _defaultOptions$local4;
2572
+
2573
+ requiredArgs(2, arguments);
2574
+ var formatStr = String(dirtyFormatStr);
2575
+ var defaultOptions = getDefaultOptions();
2576
+ var locale$1 = (_ref = (_options$locale = options === null || options === void 0 ? void 0 : options.locale) !== null && _options$locale !== void 0 ? _options$locale : defaultOptions.locale) !== null && _ref !== void 0 ? _ref : locale;
2577
+ var firstWeekContainsDate = toInteger((_ref2 = (_ref3 = (_ref4 = (_options$firstWeekCon = options === null || options === void 0 ? void 0 : options.firstWeekContainsDate) !== null && _options$firstWeekCon !== void 0 ? _options$firstWeekCon : options === null || options === void 0 ? void 0 : (_options$locale2 = options.locale) === null || _options$locale2 === void 0 ? void 0 : (_options$locale2$opti = _options$locale2.options) === null || _options$locale2$opti === void 0 ? void 0 : _options$locale2$opti.firstWeekContainsDate) !== null && _ref4 !== void 0 ? _ref4 : defaultOptions.firstWeekContainsDate) !== null && _ref3 !== void 0 ? _ref3 : (_defaultOptions$local = defaultOptions.locale) === null || _defaultOptions$local === void 0 ? void 0 : (_defaultOptions$local2 = _defaultOptions$local.options) === null || _defaultOptions$local2 === void 0 ? void 0 : _defaultOptions$local2.firstWeekContainsDate) !== null && _ref2 !== void 0 ? _ref2 : 1); // Test if weekStartsOn is between 1 and 7 _and_ is not NaN
2578
+
2579
+ if (!(firstWeekContainsDate >= 1 && firstWeekContainsDate <= 7)) {
2580
+ throw new RangeError('firstWeekContainsDate must be between 1 and 7 inclusively');
2581
+ }
2582
+
2583
+ var weekStartsOn = toInteger((_ref5 = (_ref6 = (_ref7 = (_options$weekStartsOn = options === null || options === void 0 ? void 0 : options.weekStartsOn) !== null && _options$weekStartsOn !== void 0 ? _options$weekStartsOn : options === null || options === void 0 ? void 0 : (_options$locale3 = options.locale) === null || _options$locale3 === void 0 ? void 0 : (_options$locale3$opti = _options$locale3.options) === null || _options$locale3$opti === void 0 ? void 0 : _options$locale3$opti.weekStartsOn) !== null && _ref7 !== void 0 ? _ref7 : defaultOptions.weekStartsOn) !== null && _ref6 !== void 0 ? _ref6 : (_defaultOptions$local3 = defaultOptions.locale) === null || _defaultOptions$local3 === void 0 ? void 0 : (_defaultOptions$local4 = _defaultOptions$local3.options) === null || _defaultOptions$local4 === void 0 ? void 0 : _defaultOptions$local4.weekStartsOn) !== null && _ref5 !== void 0 ? _ref5 : 0); // Test if weekStartsOn is between 0 and 6 _and_ is not NaN
2584
+
2585
+ if (!(weekStartsOn >= 0 && weekStartsOn <= 6)) {
2586
+ throw new RangeError('weekStartsOn must be between 0 and 6 inclusively');
2587
+ }
2588
+
2589
+ if (!locale$1.localize) {
2590
+ throw new RangeError('locale must contain localize property');
2591
+ }
2592
+
2593
+ if (!locale$1.formatLong) {
2594
+ throw new RangeError('locale must contain formatLong property');
2595
+ }
2596
+
2597
+ var originalDate = toDate(dirtyDate);
2598
+
2599
+ if (!isValid(originalDate)) {
2600
+ throw new RangeError('Invalid time value');
2601
+ } // Convert the date in system timezone to the same date in UTC+00:00 timezone.
2602
+ // This ensures that when UTC functions will be implemented, locales will be compatible with them.
2603
+ // See an issue about UTC functions: https://github.com/date-fns/date-fns/issues/376
2604
+
2605
+
2606
+ var timezoneOffset = getTimezoneOffsetInMilliseconds(originalDate);
2607
+ var utcDate = subMilliseconds(originalDate, timezoneOffset);
2608
+ var formatterOptions = {
2609
+ firstWeekContainsDate: firstWeekContainsDate,
2610
+ weekStartsOn: weekStartsOn,
2611
+ locale: locale$1,
2612
+ _originalDate: originalDate
2613
+ };
2614
+ var result = formatStr.match(longFormattingTokensRegExp).map(function (substring) {
2615
+ var firstCharacter = substring[0];
2616
+
2617
+ if (firstCharacter === 'p' || firstCharacter === 'P') {
2618
+ var longFormatter = longFormatters[firstCharacter];
2619
+ return longFormatter(substring, locale$1.formatLong);
2620
+ }
2621
+
2622
+ return substring;
2623
+ }).join('').match(formattingTokensRegExp).map(function (substring) {
2624
+ // Replace two single quote characters with one single quote character
2625
+ if (substring === "''") {
2626
+ return "'";
2627
+ }
2628
+
2629
+ var firstCharacter = substring[0];
2630
+
2631
+ if (firstCharacter === "'") {
2632
+ return cleanEscapedString(substring);
2633
+ }
2634
+
2635
+ var formatter = formatters[firstCharacter];
2636
+
2637
+ if (formatter) {
2638
+ if (!(options !== null && options !== void 0 && options.useAdditionalWeekYearTokens) && isProtectedWeekYearToken(substring)) {
2639
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2640
+ }
2641
+
2642
+ if (!(options !== null && options !== void 0 && options.useAdditionalDayOfYearTokens) && isProtectedDayOfYearToken(substring)) {
2643
+ throwProtectedError(substring, dirtyFormatStr, String(dirtyDate));
2644
+ }
2645
+
2646
+ return formatter(utcDate, substring, locale$1.localize, formatterOptions);
2647
+ }
2648
+
2649
+ if (firstCharacter.match(unescapedLatinCharacterRegExp)) {
2650
+ throw new RangeError('Format string contains an unescaped latin alphabet character `' + firstCharacter + '`');
2651
+ }
2652
+
2653
+ return substring;
2654
+ }).join('');
2655
+ return result;
2656
+ }
2657
+
2658
+ function cleanEscapedString(input) {
2659
+ var matched = input.match(escapedStringRegExp);
2660
+
2661
+ if (!matched) {
2662
+ return input;
2663
+ }
2664
+
2665
+ return matched[1].replace(doubleQuoteRegExp, "'");
2666
+ }
2667
+
2668
+ /**
2669
+ * Default values for all Dinero objects.
2670
+ *
2671
+ * You can override default values for all subsequent Dinero objects by changing them directly on the global `Dinero` object.
2672
+ * Existing instances won't be affected.
2673
+ *
2674
+ * @property {Number} defaultAmount - The default amount for new Dinero objects (see {@link module:Dinero Dinero} for format).
2675
+ * @property {String} defaultCurrency - The default currency for new Dinero objects (see {@link module:Dinero Dinero} for format).
2676
+ * @property {Number} defaultPrecision - The default precision for new Dinero objects (see {@link module:Dinero Dinero} for format).
2677
+ *
2678
+ * @example
2679
+ * // Will set currency to 'EUR' for all Dinero objects.
2680
+ * Dinero.defaultCurrency = 'EUR'
2681
+ *
2682
+ * @type {Object}
2683
+ */
2684
+ var Defaults = {
2685
+ defaultAmount: 0,
2686
+ defaultCurrency: 'USD',
2687
+ defaultPrecision: 2
2688
+ };
2689
+ /**
2690
+ * Global settings for all Dinero objects.
2691
+ *
2692
+ * You can override global values for all subsequent Dinero objects by changing them directly on the global `Dinero` object.
2693
+ * Existing instances won't be affected.
2694
+ *
2695
+ * @property {String} globalLocale - The global locale for new Dinero objects (see {@link module:Dinero~setLocale setLocale} for format).
2696
+ * @property {String} globalFormat - The global format for new Dinero objects (see {@link module:Dinero~toFormat toFormat} for format).
2697
+ * @property {String} globalRoundingMode - The global rounding mode for new Dinero objects (see {@link module:Dinero~multiply multiply} or {@link module:Dinero~divide divide} for format).
2698
+ * @property {String} globalFormatRoundingMode - The global rounding mode to format new Dinero objects (see {@link module:Dinero~toFormat toFormat} or {@link module:Dinero~toRoundedUnit toRoundedUnit} for format).
2699
+ * @property {(String|Promise)} globalExchangeRatesApi.endpoint - The global exchange rate API endpoint for new Dinero objects, or the global promise that resolves to the exchanges rates (see {@link module:Dinero~convert convert} for format).
2700
+ * @property {String} globalExchangeRatesApi.propertyPath - The global exchange rate API property path for new Dinero objects (see {@link module:Dinero~convert convert} for format).
2701
+ * @property {Object} globalExchangeRatesApi.headers - The global exchange rate API headers for new Dinero objects (see {@link module:Dinero~convert convert} for format).
2702
+ *
2703
+ * @example
2704
+ * // Will set locale to 'fr-FR' for all Dinero objects.
2705
+ * Dinero.globalLocale = 'fr-FR'
2706
+ * @example
2707
+ * // Will set global exchange rate API parameters for all Dinero objects.
2708
+ * Dinero.globalExchangeRatesApi = {
2709
+ * endpoint: 'https://yourexchangerates.api/latest?base={{from}}',
2710
+ * propertyPath: 'data.rates.{{to}}',
2711
+ * headers: {
2712
+ * 'user-key': 'xxxxxxxxx'
2713
+ * }
2714
+ * }
2715
+ *
2716
+ * @type {Object}
2717
+ */
2718
+
2719
+ var Globals = {
2720
+ globalLocale: 'en-US',
2721
+ globalFormat: '$0,0.00',
2722
+ globalRoundingMode: 'HALF_EVEN',
2723
+ globalFormatRoundingMode: 'HALF_AWAY_FROM_ZERO',
2724
+ globalExchangeRatesApi: {
2725
+ endpoint: undefined,
2726
+ headers: undefined,
2727
+ propertyPath: undefined
2728
+ }
2729
+ };
2730
+
2731
+ function _typeof(obj) {
2732
+ "@babel/helpers - typeof";
2733
+
2734
+ if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
2735
+ _typeof = function (obj) {
2736
+ return typeof obj;
2737
+ };
2738
+ } else {
2739
+ _typeof = function (obj) {
2740
+ return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
2741
+ };
2742
+ }
2743
+
2744
+ return _typeof(obj);
2745
+ }
2746
+
2747
+ function _toArray(arr) {
2748
+ return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest();
2749
+ }
2750
+
2751
+ function _arrayWithHoles(arr) {
2752
+ if (Array.isArray(arr)) return arr;
2753
+ }
2754
+
2755
+ function _iterableToArray(iter) {
2756
+ if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
2757
+ }
2758
+
2759
+ function _unsupportedIterableToArray(o, minLen) {
2760
+ if (!o) return;
2761
+ if (typeof o === "string") return _arrayLikeToArray(o, minLen);
2762
+ var n = Object.prototype.toString.call(o).slice(8, -1);
2763
+ if (n === "Object" && o.constructor) n = o.constructor.name;
2764
+ if (n === "Map" || n === "Set") return Array.from(o);
2765
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen);
2766
+ }
2767
+
2768
+ function _arrayLikeToArray(arr, len) {
2769
+ if (len == null || len > arr.length) len = arr.length;
2770
+
2771
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
2772
+
2773
+ return arr2;
2774
+ }
2775
+
2776
+ function _nonIterableRest() {
2777
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
2778
+ }
2779
+
2780
+ /**
2781
+ * Static methods for Dinero.
2782
+ * @ignore
2783
+ *
2784
+ * @type {Object}
2785
+ */
2786
+ var Static = {
2787
+ /**
2788
+ * Returns an array of Dinero objects, normalized to the same precision (the highest).
2789
+ *
2790
+ * @memberof module:Dinero
2791
+ * @method
2792
+ *
2793
+ * @param {Dinero[]} objects - An array of Dinero objects
2794
+ *
2795
+ * @example
2796
+ * // returns an array of Dinero objects
2797
+ * // both with a precision of 3
2798
+ * // and an amount of 1000
2799
+ * Dinero.normalizePrecision([
2800
+ * Dinero({ amount: 100, precision: 2 }),
2801
+ * Dinero({ amount: 1000, precision: 3 })
2802
+ * ])
2803
+ *
2804
+ * @return {Dinero[]}
2805
+ */
2806
+ normalizePrecision: function normalizePrecision(objects) {
2807
+ var highestPrecision = objects.reduce(function (a, b) {
2808
+ return Math.max(a.getPrecision(), b.getPrecision());
2809
+ });
2810
+ return objects.map(function (object) {
2811
+ return object.getPrecision() !== highestPrecision ? object.convertPrecision(highestPrecision) : object;
2812
+ });
2813
+ },
2814
+
2815
+ /**
2816
+ * Returns the smallest Dinero object from an array of Dinero objects
2817
+ *
2818
+ * @memberof module:Dinero
2819
+ * @method
2820
+ *
2821
+ * @param {Dinero[]} objects - An array of Dinero objects
2822
+ *
2823
+ * @example
2824
+ * // returns the smallest Dinero object with amount of 500 from an array of Dinero objects with different precisions
2825
+ * Dinero.minimum([
2826
+ * Dinero({ amount: 500, precision: 3 }),
2827
+ * Dinero({ amount: 100, precision: 2 })
2828
+ * ])
2829
+ * @example
2830
+ * // returns the smallest Dinero object with amount of 50 from an array of Dinero objects
2831
+ * Dinero.minimum([
2832
+ * Dinero({ amount: 50 }),
2833
+ * Dinero({ amount: 100 })
2834
+ * ])
2835
+ *
2836
+ * @return {Dinero[]}
2837
+ */
2838
+ minimum: function minimum(objects) {
2839
+ var _objects = _toArray(objects),
2840
+ firstObject = _objects[0],
2841
+ tailObjects = _objects.slice(1);
2842
+
2843
+ var currentMinimum = firstObject;
2844
+ tailObjects.forEach(function (obj) {
2845
+ currentMinimum = currentMinimum.lessThan(obj) ? currentMinimum : obj;
2846
+ });
2847
+ return currentMinimum;
2848
+ },
2849
+
2850
+ /**
2851
+ * Returns the biggest Dinero object from an array of Dinero objects
2852
+ *
2853
+ * @memberof module:Dinero
2854
+ * @method
2855
+ *
2856
+ * @param {Dinero[]} objects - An array of Dinero objects
2857
+ *
2858
+ * @example
2859
+ * // returns the biggest Dinero object with amount of 20, from an array of Dinero objects with different precisions
2860
+ * Dinero.maximum([
2861
+ * Dinero({ amount: 20, precision: 2 }),
2862
+ * Dinero({ amount: 150, precision: 3 })
2863
+ * ])
2864
+ * @example
2865
+ * // returns the biggest Dinero object with amount of 100, from an array of Dinero objects
2866
+ * Dinero.maximum([
2867
+ * Dinero({ amount: 100 }),
2868
+ * Dinero({ amount: 50 })
2869
+ * ])
2870
+ *
2871
+ * @return {Dinero[]}
2872
+ */
2873
+ maximum: function maximum(objects) {
2874
+ var _objects2 = _toArray(objects),
2875
+ firstObject = _objects2[0],
2876
+ tailObjects = _objects2.slice(1);
2877
+
2878
+ var currentMaximum = firstObject;
2879
+ tailObjects.forEach(function (obj) {
2880
+ currentMaximum = currentMaximum.greaterThan(obj) ? currentMaximum : obj;
2881
+ });
2882
+ return currentMaximum;
2883
+ }
2884
+ };
2885
+
2886
+ /**
2887
+ * Returns whether a value is numeric.
2888
+ * @ignore
2889
+ *
2890
+ * @param {} value - The value to test.
2891
+ *
2892
+ * @return {Boolean}
2893
+ */
2894
+ function isNumeric(value) {
2895
+ return !isNaN(parseInt(value)) && isFinite(value);
2896
+ }
2897
+ /**
2898
+ * Returns whether a value is a percentage.
2899
+ * @ignore
2900
+ *
2901
+ * @param {} percentage - The percentage to test.
2902
+ *
2903
+ * @return {Boolean}
2904
+ */
2905
+
2906
+ function isPercentage(percentage) {
2907
+ return isNumeric(percentage) && percentage <= 100 && percentage >= 0;
2908
+ }
2909
+ /**
2910
+ * Returns whether an array of ratios is valid.
2911
+ * @ignore
2912
+ *
2913
+ * @param {} ratios - The ratios to test.
2914
+ *
2915
+ * @return {Boolean}
2916
+ */
2917
+
2918
+ function areValidRatios(ratios) {
2919
+ return ratios.length > 0 && ratios.every(function (ratio) {
2920
+ return ratio >= 0;
2921
+ }) && ratios.some(function (ratio) {
2922
+ return ratio > 0;
2923
+ });
2924
+ }
2925
+ /**
2926
+ * Returns whether a value is even.
2927
+ * @ignore
2928
+ *
2929
+ * @param {Number} value - The value to test.
2930
+ *
2931
+ * @return {Boolean}
2932
+ */
2933
+
2934
+ function isEven(value) {
2935
+ return value % 2 === 0;
2936
+ }
2937
+ /**
2938
+ * Returns whether a value is a float.
2939
+ * @ignore
2940
+ *
2941
+ * @param {} value - The value to test.
2942
+ *
2943
+ * @return {Boolean}
2944
+ */
2945
+
2946
+ function isFloat(value) {
2947
+ return isNumeric(value) && !Number.isInteger(value);
2948
+ }
2949
+ /**
2950
+ * Returns how many fraction digits a number has.
2951
+ * @ignore
2952
+ *
2953
+ * @param {Number} [number=0] - The number to test.
2954
+ *
2955
+ * @return {Number}
2956
+ */
2957
+
2958
+ function countFractionDigits() {
2959
+ var number = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
2960
+ var stringRepresentation = number.toString();
2961
+
2962
+ if (stringRepresentation.indexOf('e-') > 0) {
2963
+ // It's too small for a normal string representation, e.g. 1e-7 instead of 0.00000001
2964
+ return parseInt(stringRepresentation.split('e-')[1]);
2965
+ } else {
2966
+ var fractionDigits = stringRepresentation.split('.')[1];
2967
+ return fractionDigits ? fractionDigits.length : 0;
2968
+ }
2969
+ }
2970
+ /**
2971
+ * Returns whether a number is half.
2972
+ * @ignore
2973
+ *
2974
+ * @param {Number} number - The number to test.
2975
+ *
2976
+ * @return {Number}
2977
+ */
2978
+
2979
+ function isHalf(number) {
2980
+ return Math.abs(number) % 1 === 0.5;
2981
+ }
2982
+ /**
2983
+ * Fetches a JSON resource.
2984
+ * @ignore
2985
+ *
2986
+ * @param {String} url - The resource to fetch.
2987
+ * @param {Object} [options.headers] - The headers to pass.
2988
+ *
2989
+ * @throws {Error} If `request.status` is lesser than 200 or greater or equal to 400.
2990
+ * @throws {Error} If network fails.
2991
+ *
2992
+ * @return {JSON}
2993
+ */
2994
+
2995
+ function getJSON(url) {
2996
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
2997
+ return new Promise(function (resolve, reject) {
2998
+ var request = Object.assign(new XMLHttpRequest(), {
2999
+ onreadystatechange: function onreadystatechange() {
3000
+ if (request.readyState === 4) {
3001
+ if (request.status >= 200 && request.status < 400) resolve(JSON.parse(request.responseText));else reject(new Error(request.statusText));
3002
+ }
3003
+ },
3004
+ onerror: function onerror() {
3005
+ reject(new Error('Network error'));
3006
+ }
3007
+ });
3008
+ request.open('GET', url, true);
3009
+ setXHRHeaders(request, options.headers);
3010
+ request.send();
3011
+ });
3012
+ }
3013
+ /**
3014
+ * Returns an XHR object with attached headers.
3015
+ * @ignore
3016
+ *
3017
+ * @param {XMLHttpRequest} xhr - The XHR request to set headers to.
3018
+ * @param {Object} headers - The headers to set.
3019
+ *
3020
+ * @return {XMLHttpRequest}
3021
+ */
3022
+
3023
+ function setXHRHeaders(xhr) {
3024
+ var headers = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
3025
+
3026
+ for (var header in headers) {
3027
+ xhr.setRequestHeader(header, headers[header]);
3028
+ }
3029
+
3030
+ return xhr;
3031
+ }
3032
+ /**
3033
+ * Returns whether a value is undefined.
3034
+ * @ignore
3035
+ *
3036
+ * @param {} value - The value to test.
3037
+ *
3038
+ * @return {Boolean}
3039
+ */
3040
+
3041
+ function isUndefined(value) {
3042
+ return typeof value === 'undefined';
3043
+ }
3044
+ /**
3045
+ * Returns an object flattened to one level deep.
3046
+ * @ignore
3047
+ *
3048
+ * @param {Object} object - The object to flatten.
3049
+ * @param {String} separator - The separator to use between flattened nodes.
3050
+ *
3051
+ * @return {Object}
3052
+ */
3053
+
3054
+ function flattenObject(object) {
3055
+ var separator = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '.';
3056
+ var finalObject = {};
3057
+ Object.entries(object).forEach(function (item) {
3058
+ if (_typeof(item[1]) === 'object') {
3059
+ var flatObject = flattenObject(item[1]);
3060
+ Object.entries(flatObject).forEach(function (node) {
3061
+ finalObject[item[0] + separator + node[0]] = node[1];
3062
+ });
3063
+ } else {
3064
+ finalObject[item[0]] = item[1];
3065
+ }
3066
+ });
3067
+ return finalObject;
3068
+ }
3069
+ /**
3070
+ * Returns whether a value is thenable.
3071
+ * @ignore
3072
+ *
3073
+ * @param {} value - The value to test.
3074
+ *
3075
+ * @return {Boolean}
3076
+ */
3077
+
3078
+ function isThenable(value) {
3079
+ return Boolean(value) && (_typeof(value) === 'object' || typeof value === 'function') && typeof value.then === 'function';
3080
+ }
3081
+
3082
+ function Calculator() {
3083
+ var floatMultiply = function floatMultiply(a, b) {
3084
+ var getFactor = function getFactor(number) {
3085
+ return Math.pow(10, countFractionDigits(number));
3086
+ };
3087
+
3088
+ var factor = Math.max(getFactor(a), getFactor(b));
3089
+ return Math.round(a * factor) * Math.round(b * factor) / (factor * factor);
3090
+ };
3091
+
3092
+ var roundingModes = {
3093
+ HALF_ODD: function HALF_ODD(number) {
3094
+ var rounded = Math.round(number);
3095
+ return isHalf(number) ? isEven(rounded) ? rounded - 1 : rounded : rounded;
3096
+ },
3097
+ HALF_EVEN: function HALF_EVEN(number) {
3098
+ var rounded = Math.round(number);
3099
+ return isHalf(number) ? isEven(rounded) ? rounded : rounded - 1 : rounded;
3100
+ },
3101
+ HALF_UP: function HALF_UP(number) {
3102
+ return Math.round(number);
3103
+ },
3104
+ HALF_DOWN: function HALF_DOWN(number) {
3105
+ return isHalf(number) ? Math.floor(number) : Math.round(number);
3106
+ },
3107
+ HALF_TOWARDS_ZERO: function HALF_TOWARDS_ZERO(number) {
3108
+ return isHalf(number) ? Math.sign(number) * Math.floor(Math.abs(number)) : Math.round(number);
3109
+ },
3110
+ HALF_AWAY_FROM_ZERO: function HALF_AWAY_FROM_ZERO(number) {
3111
+ return isHalf(number) ? Math.sign(number) * Math.ceil(Math.abs(number)) : Math.round(number);
3112
+ },
3113
+ DOWN: function DOWN(number) {
3114
+ return Math.floor(number);
3115
+ }
3116
+ };
3117
+ return {
3118
+ /**
3119
+ * Returns the sum of two numbers.
3120
+ * @ignore
3121
+ *
3122
+ * @param {Number} a - The first number to add.
3123
+ * @param {Number} b - The second number to add.
3124
+ *
3125
+ * @return {Number}
3126
+ */
3127
+ add: function add(a, b) {
3128
+ return a + b;
3129
+ },
3130
+
3131
+ /**
3132
+ * Returns the difference of two numbers.
3133
+ * @ignore
3134
+ *
3135
+ * @param {Number} a - The first number to subtract.
3136
+ * @param {Number} b - The second number to subtract.
3137
+ *
3138
+ * @return {Number}
3139
+ */
3140
+ subtract: function subtract(a, b) {
3141
+ return a - b;
3142
+ },
3143
+
3144
+ /**
3145
+ * Returns the product of two numbers.
3146
+ * @ignore
3147
+ *
3148
+ * @param {Number} a - The first number to multiply.
3149
+ * @param {Number} b - The second number to multiply.
3150
+ *
3151
+ * @return {Number}
3152
+ */
3153
+ multiply: function multiply(a, b) {
3154
+ return isFloat(a) || isFloat(b) ? floatMultiply(a, b) : a * b;
3155
+ },
3156
+
3157
+ /**
3158
+ * Returns the quotient of two numbers.
3159
+ * @ignore
3160
+ *
3161
+ * @param {Number} a - The first number to divide.
3162
+ * @param {Number} b - The second number to divide.
3163
+ *
3164
+ * @return {Number}
3165
+ */
3166
+ divide: function divide(a, b) {
3167
+ return a / b;
3168
+ },
3169
+
3170
+ /**
3171
+ * Returns the remainder of two numbers.
3172
+ * @ignore
3173
+ *
3174
+ * @param {Number} a - The first number to divide.
3175
+ * @param {Number} b - The second number to divide.
3176
+ *
3177
+ * @return {Number}
3178
+ */
3179
+ modulo: function modulo(a, b) {
3180
+ return a % b;
3181
+ },
3182
+
3183
+ /**
3184
+ * Returns a rounded number based off a specific rounding mode.
3185
+ * @ignore
3186
+ *
3187
+ * @param {Number} number - The number to round.
3188
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use.
3189
+ *
3190
+ * @returns {Number}
3191
+ */
3192
+ round: function round(number) {
3193
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'HALF_EVEN';
3194
+ return roundingModes[roundingMode](number);
3195
+ }
3196
+ };
3197
+ }
3198
+
3199
+ var calculator = Calculator();
3200
+ function Format(format) {
3201
+ var matches = /^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(format);
3202
+ return {
3203
+ /**
3204
+ * Returns the matches.
3205
+ * @ignore
3206
+ *
3207
+ * @return {Array}
3208
+ */
3209
+ getMatches: function getMatches() {
3210
+ return matches !== null ? matches.slice(1).filter(function (match) {
3211
+ return !isUndefined(match);
3212
+ }) : [];
3213
+ },
3214
+
3215
+ /**
3216
+ * Returns the amount of fraction digits to display.
3217
+ * @ignore
3218
+ *
3219
+ * @return {Number}
3220
+ */
3221
+ getMinimumFractionDigits: function getMinimumFractionDigits() {
3222
+ var decimalPosition = function decimalPosition(match) {
3223
+ return match === '.';
3224
+ };
3225
+
3226
+ return !isUndefined(this.getMatches().find(decimalPosition)) ? this.getMatches()[calculator.add(this.getMatches().findIndex(decimalPosition), 1)].split('').length : 0;
3227
+ },
3228
+
3229
+ /**
3230
+ * Returns the currency display mode.
3231
+ * @ignore
3232
+ *
3233
+ * @return {String}
3234
+ */
3235
+ getCurrencyDisplay: function getCurrencyDisplay() {
3236
+ var modes = {
3237
+ USD: 'code',
3238
+ dollar: 'name',
3239
+ $: 'symbol'
3240
+ };
3241
+ return modes[this.getMatches().find(function (match) {
3242
+ return match === 'USD' || match === 'dollar' || match === '$';
3243
+ })];
3244
+ },
3245
+
3246
+ /**
3247
+ * Returns the formatting style.
3248
+ * @ignore
3249
+ *
3250
+ * @return {String}
3251
+ */
3252
+ getStyle: function getStyle() {
3253
+ return !isUndefined(this.getCurrencyDisplay(this.getMatches())) ? 'currency' : 'decimal';
3254
+ },
3255
+
3256
+ /**
3257
+ * Returns whether grouping should be used or not.
3258
+ * @ignore
3259
+ *
3260
+ * @return {Boolean}
3261
+ */
3262
+ getUseGrouping: function getUseGrouping() {
3263
+ return !isUndefined(this.getMatches().find(function (match) {
3264
+ return match === ',';
3265
+ }));
3266
+ }
3267
+ };
3268
+ }
3269
+
3270
+ function CurrencyConverter(options) {
3271
+ /* istanbul ignore next */
3272
+ var mergeTags = function mergeTags() {
3273
+ var string = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
3274
+ var tags = arguments.length > 1 ? arguments[1] : undefined;
3275
+
3276
+ for (var tag in tags) {
3277
+ string = string.replace("{{".concat(tag, "}}"), tags[tag]);
3278
+ }
3279
+
3280
+ return string;
3281
+ };
3282
+ /* istanbul ignore next */
3283
+
3284
+
3285
+ var getRatesFromRestApi = function getRatesFromRestApi(from, to) {
3286
+ return getJSON(mergeTags(options.endpoint, {
3287
+ from: from,
3288
+ to: to
3289
+ }), {
3290
+ headers: options.headers
3291
+ });
3292
+ };
3293
+
3294
+ return {
3295
+ /**
3296
+ * Returns the exchange rate.
3297
+ * @ignore
3298
+ *
3299
+ * @param {String} from - The base currency.
3300
+ * @param {String} to - The destination currency.
3301
+ *
3302
+ * @return {Promise}
3303
+ */
3304
+ getExchangeRate: function getExchangeRate(from, to) {
3305
+ return (isThenable(options.endpoint) ? options.endpoint : getRatesFromRestApi(from, to)).then(function (data) {
3306
+ return flattenObject(data)[mergeTags(options.propertyPath, {
3307
+ from: from,
3308
+ to: to
3309
+ })];
3310
+ });
3311
+ }
3312
+ };
3313
+ }
3314
+
3315
+ /**
3316
+ * Performs an assertion.
3317
+ * @ignore
3318
+ *
3319
+ * @param {Boolean} condition - The expression to assert.
3320
+ * @param {String} errorMessage - The message to throw if the assertion fails
3321
+ * @param {ErrorConstructor} [ErrorType=Error] - The error to throw if the assertion fails.
3322
+ *
3323
+ * @throws {Error} If `condition` returns `false`.
3324
+ */
3325
+
3326
+ function assert(condition, errorMessage) {
3327
+ var ErrorType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : Error;
3328
+ if (!condition) throw new ErrorType(errorMessage);
3329
+ }
3330
+ /**
3331
+ * Asserts a value is a percentage.
3332
+ * @ignore
3333
+ *
3334
+ * @param {} percentage - The percentage to test.
3335
+ *
3336
+ * @throws {RangeError} If `percentage` is out of range.
3337
+ */
3338
+
3339
+ function assertPercentage(percentage) {
3340
+ assert(isPercentage(percentage), 'You must provide a numeric value between 0 and 100.', RangeError);
3341
+ }
3342
+ /**
3343
+ * Asserts an array of ratios is valid.
3344
+ * @ignore
3345
+ *
3346
+ * @param {} ratios - The ratios to test.
3347
+ *
3348
+ * @throws {TypeError} If `ratios` are invalid.
3349
+ */
3350
+
3351
+ function assertValidRatios(ratios) {
3352
+ assert(areValidRatios(ratios), 'You must provide a non-empty array of numeric values greater than 0.', TypeError);
3353
+ }
3354
+ /**
3355
+ * Asserts a value is an integer.
3356
+ * @ignore
3357
+ *
3358
+ * @param {} number - The value to test.
3359
+ *
3360
+ * @throws {TypeError}
3361
+ */
3362
+
3363
+ function assertInteger(number) {
3364
+ assert(Number.isInteger(number), 'You must provide an integer.', TypeError);
3365
+ }
3366
+
3367
+ var calculator$1 = Calculator();
3368
+ /**
3369
+ * A Dinero object is an immutable data structure representing a specific monetary value.
3370
+ * It comes with methods for creating, parsing, manipulating, testing, transforming and formatting them.
3371
+ *
3372
+ * A Dinero object has:
3373
+ *
3374
+ * * An `amount`, expressed in minor currency units, as an integer.
3375
+ * * A `currency`, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
3376
+ * * A `precision`, expressed as an integer, to represent the number of decimal places in the `amount`.
3377
+ * This is helpful when you want to represent fractional minor currency units (e.g.: $10.4545).
3378
+ * You can also use it to represent a currency with a different [exponent](https://en.wikipedia.org/wiki/ISO_4217#Treatment_of_minor_currency_units_.28the_.22exponent.22.29) than `2` (e.g.: Iraqi dinar with 1000 fils in 1 dinar (exponent of `3`), Japanese yen with no sub-units (exponent of `0`)).
3379
+ * * An optional `locale` property that affects how output strings are formatted.
3380
+ *
3381
+ * Here's an overview of the public API:
3382
+ *
3383
+ * * **Access:** {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~getCurrency getCurrency}, {@link module:Dinero~getLocale getLocale} and {@link module:Dinero~getPrecision getPrecision}.
3384
+ * * **Manipulation:** {@link module:Dinero~add add}, {@link module:Dinero~subtract subtract}, {@link module:Dinero~multiply multiply}, {@link module:Dinero~divide divide}, {@link module:Dinero~percentage percentage}, {@link module:Dinero~allocate allocate} and {@link module:Dinero~convert convert}.
3385
+ * * **Testing:** {@link module:Dinero~equalsTo equalsTo}, {@link module:Dinero~lessThan lessThan}, {@link module:Dinero~lessThanOrEqual lessThanOrEqual}, {@link module:Dinero~greaterThan greaterThan}, {@link module:Dinero~greaterThanOrEqual greaterThanOrEqual}, {@link module:Dinero~isZero isZero}, {@link module:Dinero~isPositive isPositive}, {@link module:Dinero~isNegative isNegative}, {@link module:Dinero~hasSubUnits hasSubUnits}, {@link module:Dinero~hasSameCurrency hasSameCurrency} and {@link module:Dinero~hasSameAmount hasSameAmount}.
3386
+ * * **Configuration:** {@link module:Dinero~setLocale setLocale}.
3387
+ * * **Conversion & formatting:** {@link module:Dinero~toFormat toFormat}, {@link module:Dinero~toUnit toUnit}, {@link module:Dinero~toRoundedUnit toRoundedUnit}, {@link module:Dinero~toObject toObject}, {@link module:Dinero~toJSON toJSON}, {@link module:Dinero~convertPrecision convertPrecision} and {@link module:Dinero.normalizePrecision normalizePrecision}.
3388
+ *
3389
+ * Dinero.js uses `number`s under the hood, so it's constrained by the [double-precision floating-point format](https://en.wikipedia.org/wiki/Double-precision_floating-point_format). Using values over [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER) or below [`Number.MIN_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MIN_SAFE_INTEGER) will yield unpredictable results.
3390
+ * Same goes with performing calculations: once the internal `amount` value exceeds those limits, precision is no longer guaranteed.
3391
+ *
3392
+ * @module Dinero
3393
+ * @param {Number} [options.amount=0] - The amount in minor currency units (as an integer).
3394
+ * @param {String} [options.currency='USD'] - An ISO 4217 currency code.
3395
+ * @param {String} [options.precision=2] - The number of decimal places to represent.
3396
+ *
3397
+ * @throws {TypeError} If `amount` or `precision` is invalid. Integers over [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MAX_SAFE_INTEGER) or below [`Number.MIN_SAFE_INTEGER`](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Number/MIN_SAFE_INTEGER) are considered valid, even though they can lead to imprecise amounts.
3398
+ *
3399
+ * @return {Object}
3400
+ */
3401
+
3402
+ var Dinero = function Dinero(options) {
3403
+ var _Object$assign = Object.assign({}, {
3404
+ amount: Dinero.defaultAmount,
3405
+ currency: Dinero.defaultCurrency,
3406
+ precision: Dinero.defaultPrecision
3407
+ }, options),
3408
+ amount = _Object$assign.amount,
3409
+ currency = _Object$assign.currency,
3410
+ precision = _Object$assign.precision;
3411
+
3412
+ assertInteger(amount);
3413
+ assertInteger(precision);
3414
+ var globalLocale = Dinero.globalLocale,
3415
+ globalFormat = Dinero.globalFormat,
3416
+ globalRoundingMode = Dinero.globalRoundingMode,
3417
+ globalFormatRoundingMode = Dinero.globalFormatRoundingMode;
3418
+ var globalExchangeRatesApi = Object.assign({}, Dinero.globalExchangeRatesApi);
3419
+ /**
3420
+ * Uses ES5 function notation so `this` can be passed through call, apply and bind
3421
+ * @ignore
3422
+ */
3423
+
3424
+ var create = function create(options) {
3425
+ var obj = Object.assign({}, Object.assign({}, {
3426
+ amount: amount,
3427
+ currency: currency,
3428
+ precision: precision
3429
+ }, options), Object.assign({}, {
3430
+ locale: this.locale
3431
+ }, options));
3432
+ return Object.assign(Dinero({
3433
+ amount: obj.amount,
3434
+ currency: obj.currency,
3435
+ precision: obj.precision
3436
+ }), {
3437
+ locale: obj.locale
3438
+ });
3439
+ };
3440
+ /**
3441
+ * Uses ES5 function notation so `this` can be passed through call, apply and bind
3442
+ * @ignore
3443
+ */
3444
+
3445
+
3446
+ var assertSameCurrency = function assertSameCurrency(comparator) {
3447
+ assert(this.hasSameCurrency(comparator), 'You must provide a Dinero instance with the same currency.', TypeError);
3448
+ };
3449
+
3450
+ return {
3451
+ /**
3452
+ * Returns the amount.
3453
+ *
3454
+ * @example
3455
+ * // returns 500
3456
+ * Dinero({ amount: 500 }).getAmount()
3457
+ *
3458
+ * @return {Number}
3459
+ */
3460
+ getAmount: function getAmount() {
3461
+ return amount;
3462
+ },
3463
+
3464
+ /**
3465
+ * Returns the currency.
3466
+ *
3467
+ * @example
3468
+ * // returns 'EUR'
3469
+ * Dinero({ currency: 'EUR' }).getCurrency()
3470
+ *
3471
+ * @return {String}
3472
+ */
3473
+ getCurrency: function getCurrency() {
3474
+ return currency;
3475
+ },
3476
+
3477
+ /**
3478
+ * Returns the locale.
3479
+ *
3480
+ * @example
3481
+ * // returns 'fr-FR'
3482
+ * Dinero().setLocale('fr-FR').getLocale()
3483
+ *
3484
+ * @return {String}
3485
+ */
3486
+ getLocale: function getLocale() {
3487
+ return this.locale || globalLocale;
3488
+ },
3489
+
3490
+ /**
3491
+ * Returns a new Dinero object with an embedded locale.
3492
+ *
3493
+ * @param {String} newLocale - The new locale as an {@link http://tools.ietf.org/html/rfc5646 BCP 47 language tag}.
3494
+ *
3495
+ * @example
3496
+ * // Returns a Dinero object with locale 'ja-JP'
3497
+ * Dinero().setLocale('ja-JP')
3498
+ *
3499
+ * @return {Dinero}
3500
+ */
3501
+ setLocale: function setLocale(newLocale) {
3502
+ return create.call(this, {
3503
+ locale: newLocale
3504
+ });
3505
+ },
3506
+
3507
+ /**
3508
+ * Returns the precision.
3509
+ *
3510
+ * @example
3511
+ * // returns 3
3512
+ * Dinero({ precision: 3 }).getPrecision()
3513
+ *
3514
+ * @return {Number}
3515
+ */
3516
+ getPrecision: function getPrecision() {
3517
+ return precision;
3518
+ },
3519
+
3520
+ /**
3521
+ * Returns a new Dinero object with a new precision and a converted amount.
3522
+ *
3523
+ * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3524
+ * This can be necessary when you need to convert objects to a smaller precision.
3525
+ *
3526
+ * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent conversions for safer results.
3527
+ * You can also specify a different `roundingMode` to better fit your needs.
3528
+ *
3529
+ * @param {Number} newPrecision - The new precision.
3530
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3531
+ *
3532
+ * @example
3533
+ * // Returns a Dinero object with precision 3 and amount 1000
3534
+ * Dinero({ amount: 100, precision: 2 }).convertPrecision(3)
3535
+ *
3536
+ * @throws {TypeError} If `newPrecision` is invalid.
3537
+ *
3538
+ * @return {Dinero}
3539
+ */
3540
+ convertPrecision: function convertPrecision(newPrecision) {
3541
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
3542
+ assertInteger(newPrecision);
3543
+ var precision = this.getPrecision();
3544
+ var isNewPrecisionLarger = newPrecision > precision;
3545
+ var operation = isNewPrecisionLarger ? calculator$1.multiply : calculator$1.divide;
3546
+ var terms = isNewPrecisionLarger ? [newPrecision, precision] : [precision, newPrecision];
3547
+ var factor = Math.pow(10, calculator$1.subtract.apply(calculator$1, terms));
3548
+ return create.call(this, {
3549
+ amount: calculator$1.round(operation(this.getAmount(), factor), roundingMode),
3550
+ precision: newPrecision
3551
+ });
3552
+ },
3553
+
3554
+ /**
3555
+ * Returns a new Dinero object that represents the sum of this and an other Dinero object.
3556
+ *
3557
+ * If Dinero objects have a different `precision`, they will be first converted to the highest.
3558
+ *
3559
+ * @param {Dinero} addend - The Dinero object to add.
3560
+ *
3561
+ * @example
3562
+ * // returns a Dinero object with amount 600
3563
+ * Dinero({ amount: 400 }).add(Dinero({ amount: 200 }))
3564
+ * @example
3565
+ * // returns a Dinero object with amount 144545 and precision 4
3566
+ * Dinero({ amount: 400 }).add(Dinero({ amount: 104545, precision: 4 }))
3567
+ *
3568
+ * @throws {TypeError} If `addend` has a different currency.
3569
+ *
3570
+ * @return {Dinero}
3571
+ */
3572
+ add: function add(addend) {
3573
+ assertSameCurrency.call(this, addend);
3574
+ var addends = Dinero.normalizePrecision([this, addend]);
3575
+ return create.call(this, {
3576
+ amount: calculator$1.add(addends[0].getAmount(), addends[1].getAmount()),
3577
+ precision: addends[0].getPrecision()
3578
+ });
3579
+ },
3580
+
3581
+ /**
3582
+ * Returns a new Dinero object that represents the difference of this and an other Dinero object.
3583
+ *
3584
+ * If Dinero objects have a different `precision`, they will be first converted to the highest.
3585
+ *
3586
+ * @param {Dinero} subtrahend - The Dinero object to subtract.
3587
+ *
3588
+ * @example
3589
+ * // returns a Dinero object with amount 200
3590
+ * Dinero({ amount: 400 }).subtract(Dinero({ amount: 200 }))
3591
+ * @example
3592
+ * // returns a Dinero object with amount 64545 and precision 4
3593
+ * Dinero({ amount: 104545, precision: 4 }).subtract(Dinero({ amount: 400 }))
3594
+ *
3595
+ * @throws {TypeError} If `subtrahend` has a different currency.
3596
+ *
3597
+ * @return {Dinero}
3598
+ */
3599
+ subtract: function subtract(subtrahend) {
3600
+ assertSameCurrency.call(this, subtrahend);
3601
+ var subtrahends = Dinero.normalizePrecision([this, subtrahend]);
3602
+ return create.call(this, {
3603
+ amount: calculator$1.subtract(subtrahends[0].getAmount(), subtrahends[1].getAmount()),
3604
+ precision: subtrahends[0].getPrecision()
3605
+ });
3606
+ },
3607
+
3608
+ /**
3609
+ * Returns a new Dinero object that represents the multiplied value by the given factor.
3610
+ *
3611
+ * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3612
+ *
3613
+ * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
3614
+ * You can also specify a different `roundingMode` to better fit your needs.
3615
+ *
3616
+ * @param {Number} multiplier - The factor to multiply by.
3617
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3618
+ *
3619
+ * @example
3620
+ * // returns a Dinero object with amount 1600
3621
+ * Dinero({ amount: 400 }).multiply(4)
3622
+ * @example
3623
+ * // returns a Dinero object with amount 800
3624
+ * Dinero({ amount: 400 }).multiply(2.001)
3625
+ * @example
3626
+ * // returns a Dinero object with amount 801
3627
+ * Dinero({ amount: 400 }).multiply(2.00125, 'HALF_UP')
3628
+ *
3629
+ * @return {Dinero}
3630
+ */
3631
+ multiply: function multiply(multiplier) {
3632
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3633
+ return create.call(this, {
3634
+ amount: calculator$1.round(calculator$1.multiply(this.getAmount(), multiplier), roundingMode)
3635
+ });
3636
+ },
3637
+
3638
+ /**
3639
+ * Returns a new Dinero object that represents the divided value by the given factor.
3640
+ *
3641
+ * By default, fractional minor currency units are rounded using the **half to even** rule ([banker's rounding](http://wiki.c2.com/?BankersRounding)).
3642
+ *
3643
+ * Rounding *can* lead to accuracy issues as you chain many times. Consider a minimal amount of subsequent calculations for safer results.
3644
+ * You can also specify a different `roundingMode` to better fit your needs.
3645
+ *
3646
+ * As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
3647
+ *
3648
+ * @param {Number} divisor - The factor to divide by.
3649
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3650
+ *
3651
+ * @example
3652
+ * // returns a Dinero object with amount 100
3653
+ * Dinero({ amount: 400 }).divide(4)
3654
+ * @example
3655
+ * // returns a Dinero object with amount 52
3656
+ * Dinero({ amount: 105 }).divide(2)
3657
+ * @example
3658
+ * // returns a Dinero object with amount 53
3659
+ * Dinero({ amount: 105 }).divide(2, 'HALF_UP')
3660
+ *
3661
+ * @return {Dinero}
3662
+ */
3663
+ divide: function divide(divisor) {
3664
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3665
+ return create.call(this, {
3666
+ amount: calculator$1.round(calculator$1.divide(this.getAmount(), divisor), roundingMode)
3667
+ });
3668
+ },
3669
+
3670
+ /**
3671
+ * Returns a new Dinero object that represents a percentage of this.
3672
+ *
3673
+ * As rounding is applied, precision may be lost in the process. If you want to accurately split a Dinero object, use {@link module:Dinero~allocate allocate} instead.
3674
+ *
3675
+ * @param {Number} percentage - The percentage to extract (between 0 and 100).
3676
+ * @param {String} [roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3677
+ *
3678
+ * @example
3679
+ * // returns a Dinero object with amount 5000
3680
+ * Dinero({ amount: 10000 }).percentage(50)
3681
+ * @example
3682
+ * // returns a Dinero object with amount 29
3683
+ * Dinero({ amount: 57 }).percentage(50, "HALF_ODD")
3684
+ *
3685
+ * @throws {RangeError} If `percentage` is out of range.
3686
+ *
3687
+ * @return {Dinero}
3688
+ */
3689
+ percentage: function percentage(_percentage) {
3690
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalRoundingMode;
3691
+ assertPercentage(_percentage);
3692
+ return this.multiply(calculator$1.divide(_percentage, 100), roundingMode);
3693
+ },
3694
+
3695
+ /**
3696
+ * Allocates the amount of a Dinero object according to a list of ratios.
3697
+ *
3698
+ * Sometimes you need to split monetary values but percentages can't cut it without adding or losing pennies.
3699
+ * A good example is invoicing: let's say you need to bill $1,000.03 and you want a 50% downpayment.
3700
+ * If you use {@link module:Dinero~percentage percentage}, you'll get an accurate Dinero object but the amount won't be billable: you can't split a penny.
3701
+ * If you round it, you'll bill a penny extra.
3702
+ * With {@link module:Dinero~allocate allocate}, you can split a monetary amount then distribute the remainder as evenly as possible.
3703
+ *
3704
+ * You can use percentage style or ratio style for `ratios`: `[25, 75]` and `[1, 3]` will do the same thing.
3705
+ *
3706
+ * Since v1.8.0, you can use zero ratios (such as [0, 50, 50]). If there's a remainder to distribute, zero ratios are skipped and return a Dinero object with amount zero.
3707
+ *
3708
+ * @param {Number[]} ratios - The ratios to allocate the money to.
3709
+ *
3710
+ * @example
3711
+ * // returns an array of two Dinero objects
3712
+ * // the first one with an amount of 502
3713
+ * // the second one with an amount of 501
3714
+ * Dinero({ amount: 1003 }).allocate([50, 50])
3715
+ * @example
3716
+ * // returns an array of two Dinero objects
3717
+ * // the first one with an amount of 25
3718
+ * // the second one with an amount of 75
3719
+ * Dinero({ amount: 100 }).allocate([1, 3])
3720
+ * @example
3721
+ * // since version 1.8.0
3722
+ * // returns an array of three Dinero objects
3723
+ * // the first one with an amount of 0
3724
+ * // the second one with an amount of 502
3725
+ * // the third one with an amount of 501
3726
+ * Dinero({ amount: 1003 }).allocate([0, 50, 50])
3727
+ *
3728
+ * @throws {TypeError} If ratios are invalid.
3729
+ *
3730
+ * @return {Dinero[]}
3731
+ */
3732
+ allocate: function allocate(ratios) {
3733
+ var _this = this;
3734
+
3735
+ assertValidRatios(ratios);
3736
+ var total = ratios.reduce(function (a, b) {
3737
+ return calculator$1.add(a, b);
3738
+ });
3739
+ var remainder = this.getAmount();
3740
+ var shares = ratios.map(function (ratio) {
3741
+ var share = Math.floor(calculator$1.divide(calculator$1.multiply(_this.getAmount(), ratio), total));
3742
+ remainder = calculator$1.subtract(remainder, share);
3743
+ return create.call(_this, {
3744
+ amount: share
3745
+ });
3746
+ });
3747
+ var i = 0;
3748
+
3749
+ while (remainder > 0) {
3750
+ if (ratios[i] > 0) {
3751
+ shares[i] = shares[i].add(create.call(this, {
3752
+ amount: 1
3753
+ }));
3754
+ remainder = calculator$1.subtract(remainder, 1);
3755
+ }
3756
+
3757
+ i += 1;
3758
+ }
3759
+
3760
+ return shares;
3761
+ },
3762
+
3763
+ /**
3764
+ * Returns a Promise containing a new Dinero object converted to another currency.
3765
+ *
3766
+ * You have two options to provide the exchange rates:
3767
+ *
3768
+ * 1. **Use an exchange rate REST API, and let Dinero handle the fetching and conversion.**
3769
+ * This is a simple option if you have access to an exchange rate REST API and want Dinero to do the rest.
3770
+ * 2. **Fetch the exchange rates on your own and provide them directly.**
3771
+ * This is useful if you're fetching your rates from somewhere else (a file, a database), use a different protocol or query language than REST (SOAP, GraphQL) or want to fetch rates once and cache them instead of making new requests every time.
3772
+ *
3773
+ * **If you want to use a REST API**, you must provide a third-party endpoint yourself. Dinero doesn't come bundled with an exchange rates endpoint.
3774
+ *
3775
+ * Here are some exchange rate APIs you can use:
3776
+ *
3777
+ * * [Fixer](https://fixer.io)
3778
+ * * [Open Exchange Rates](https://openexchangerates.org)
3779
+ * * [Coinbase](https://api.coinbase.com/v2/exchange-rates)
3780
+ * * More [foreign](https://github.com/toddmotto/public-apis#currency-exchange) and [crypto](https://github.com/toddmotto/public-apis#cryptocurrency) exchange rate APIs.
3781
+ *
3782
+ * **If you want to fetch your own rates and provide them directly**, you need to pass a promise that resolves to the exchanges rates.
3783
+ *
3784
+ * In both cases, you need to specify at least:
3785
+ *
3786
+ * * a **destination currency**: the currency in which you want to convert your Dinero object. You can specify it with `currency`.
3787
+ * * an **endpoint**: the API URL to query exchange rates, with parameters, or a promise that resolves to the exchange rates. You can specify it with `options.endpoint`.
3788
+ * * a **property path**: the path to access the wanted rate in your API's JSON response (or the custom promise's payload). For example, with a response of:
3789
+ * ```json
3790
+ * {
3791
+ * "data": {
3792
+ * "base": "USD",
3793
+ * "destination": "EUR",
3794
+ * "rate": "0.827728919"
3795
+ * }
3796
+ * }
3797
+ * ```
3798
+ * Then the property path is `'data.rate'`. You can specify it with `options.propertyPath`.
3799
+ *
3800
+ * The base currency (the one of your Dinero object) and the destination currency can be used as "merge tags" with the mustache syntax, respectively `{{from}}` and `{{to}}`.
3801
+ * You can use these tags to refer to these values in `options.endpoint` and `options.propertyPath`.
3802
+ *
3803
+ * For example, if you need to specify the base currency as a query parameter, you can do the following:
3804
+ *
3805
+ * ```js
3806
+ * {
3807
+ * endpoint: 'https://yourexchangerates.api/latest?base={{from}}'
3808
+ * }
3809
+ * ```
3810
+ *
3811
+ * @param {String} currency - The destination currency, expressed as an {@link https://en.wikipedia.org/wiki/ISO_4217#Active_codes ISO 4217 currency code}.
3812
+ * @param {(String|Promise)} options.endpoint - The API endpoint to retrieve exchange rates. You can substitute this with a promise that resolves to the exchanges rates if you already have them.
3813
+ * @param {String} [options.propertyPath='rates.{{to}}'] - The property path to the rate.
3814
+ * @param {Object} [options.headers] - The HTTP headers to provide, if needed.
3815
+ * @param {String} [options.roundingMode='HALF_EVEN'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
3816
+ *
3817
+ * @example
3818
+ * // your global API parameters
3819
+ * Dinero.globalExchangeRatesApi = { ... }
3820
+ *
3821
+ * // returns a Promise containing a Dinero object with the destination currency
3822
+ * // and the initial amount converted to the new currency.
3823
+ * Dinero({ amount: 500 }).convert('EUR')
3824
+ * @example
3825
+ * // returns a Promise containing a Dinero object,
3826
+ * // with specific API parameters and rounding mode for this specific instance.
3827
+ * Dinero({ amount: 500 })
3828
+ * .convert('XBT', {
3829
+ * endpoint: 'https://yourexchangerates.api/latest?base={{from}}',
3830
+ * propertyPath: 'data.rates.{{to}}',
3831
+ * headers: {
3832
+ * 'user-key': 'xxxxxxxxx'
3833
+ * },
3834
+ * roundingMode: 'HALF_UP'
3835
+ * })
3836
+ * @example
3837
+ * // usage with exchange rates provided as a custom promise
3838
+ * // using the default `propertyPath` format (so it doesn't have to be specified)
3839
+ * const rates = {
3840
+ * rates: {
3841
+ * EUR: 0.81162
3842
+ * }
3843
+ * }
3844
+ *
3845
+ * Dinero({ amount: 500 })
3846
+ * .convert('EUR', {
3847
+ * endpoint: new Promise(resolve => resolve(rates))
3848
+ * })
3849
+ * @example
3850
+ * // usage with Promise.prototype.then and Promise.prototype.catch
3851
+ * Dinero({ amount: 500 })
3852
+ * .convert('EUR')
3853
+ * .then(dinero => {
3854
+ * dinero.getCurrency() // returns 'EUR'
3855
+ * })
3856
+ * .catch(err => {
3857
+ * // handle errors
3858
+ * })
3859
+ * @example
3860
+ * // usage with async/await
3861
+ * (async () => {
3862
+ * const price = await Dinero({ amount: 500 }).convert('EUR')
3863
+ * price.getCurrency() // returns 'EUR'
3864
+ * })()
3865
+ *
3866
+ * @return {Promise}
3867
+ */
3868
+ convert: function convert(currency) {
3869
+ var _this2 = this;
3870
+
3871
+ var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {},
3872
+ _ref$endpoint = _ref.endpoint,
3873
+ endpoint = _ref$endpoint === void 0 ? globalExchangeRatesApi.endpoint : _ref$endpoint,
3874
+ _ref$propertyPath = _ref.propertyPath,
3875
+ propertyPath = _ref$propertyPath === void 0 ? globalExchangeRatesApi.propertyPath || 'rates.{{to}}' : _ref$propertyPath,
3876
+ _ref$headers = _ref.headers,
3877
+ headers = _ref$headers === void 0 ? globalExchangeRatesApi.headers : _ref$headers,
3878
+ _ref$roundingMode = _ref.roundingMode,
3879
+ roundingMode = _ref$roundingMode === void 0 ? globalRoundingMode : _ref$roundingMode;
3880
+
3881
+ var options = Object.assign({}, {
3882
+ endpoint: endpoint,
3883
+ propertyPath: propertyPath,
3884
+ headers: headers,
3885
+ roundingMode: roundingMode
3886
+ });
3887
+ return CurrencyConverter(options).getExchangeRate(this.getCurrency(), currency).then(function (rate) {
3888
+ assert(!isUndefined(rate), "No rate was found for the destination currency \"".concat(currency, "\"."), TypeError);
3889
+ return create.call(_this2, {
3890
+ amount: calculator$1.round(calculator$1.multiply(_this2.getAmount(), parseFloat(rate)), options.roundingMode),
3891
+ currency: currency
3892
+ });
3893
+ });
3894
+ },
3895
+
3896
+ /**
3897
+ * Checks whether the value represented by this object equals to the other.
3898
+ *
3899
+ * @param {Dinero} comparator - The Dinero object to compare to.
3900
+ *
3901
+ * @example
3902
+ * // returns true
3903
+ * Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
3904
+ * @example
3905
+ * // returns false
3906
+ * Dinero({ amount: 500, currency: 'EUR' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
3907
+ * @example
3908
+ * // returns false
3909
+ * Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 500, currency: 'EUR' }))
3910
+ * @example
3911
+ * // returns false
3912
+ * Dinero({ amount: 500, currency: 'USD' }).equalsTo(Dinero({ amount: 800, currency: 'EUR' }))
3913
+ * @example
3914
+ * // returns true
3915
+ * Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
3916
+ * @example
3917
+ * // returns false
3918
+ * Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).equalsTo(Dinero({ amount: 10000, currency: 'EUR', precision: 3 }))
3919
+ *
3920
+ * @return {Boolean}
3921
+ */
3922
+ equalsTo: function equalsTo(comparator) {
3923
+ return this.hasSameAmount(comparator) && this.hasSameCurrency(comparator);
3924
+ },
3925
+
3926
+ /**
3927
+ * Checks whether the value represented by this object is less than the other.
3928
+ *
3929
+ * @param {Dinero} comparator - The Dinero object to compare to.
3930
+ *
3931
+ * @example
3932
+ * // returns true
3933
+ * Dinero({ amount: 500 }).lessThan(Dinero({ amount: 800 }))
3934
+ * @example
3935
+ * // returns false
3936
+ * Dinero({ amount: 800 }).lessThan(Dinero({ amount: 500 }))
3937
+ * @example
3938
+ * // returns true
3939
+ * Dinero({ amount: 5000, precision: 3 }).lessThan(Dinero({ amount: 800 }))
3940
+ * @example
3941
+ * // returns false
3942
+ * Dinero({ amount: 800 }).lessThan(Dinero({ amount: 5000, precision: 3 }))
3943
+ *
3944
+ * @throws {TypeError} If `comparator` has a different currency.
3945
+ *
3946
+ * @return {Boolean}
3947
+ */
3948
+ lessThan: function lessThan(comparator) {
3949
+ assertSameCurrency.call(this, comparator);
3950
+ var comparators = Dinero.normalizePrecision([this, comparator]);
3951
+ return comparators[0].getAmount() < comparators[1].getAmount();
3952
+ },
3953
+
3954
+ /**
3955
+ * Checks whether the value represented by this object is less than or equal to the other.
3956
+ *
3957
+ * @param {Dinero} comparator - The Dinero object to compare to.
3958
+ *
3959
+ * @example
3960
+ * // returns true
3961
+ * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 800 }))
3962
+ * @example
3963
+ * // returns true
3964
+ * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 500 }))
3965
+ * @example
3966
+ * // returns false
3967
+ * Dinero({ amount: 500 }).lessThanOrEqual(Dinero({ amount: 300 }))
3968
+ * @example
3969
+ * // returns true
3970
+ * Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 800 }))
3971
+ * @example
3972
+ * // returns true
3973
+ * Dinero({ amount: 5000, precision: 3 }).lessThanOrEqual(Dinero({ amount: 500 }))
3974
+ * @example
3975
+ * // returns false
3976
+ * Dinero({ amount: 800 }).lessThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
3977
+ *
3978
+ * @throws {TypeError} If `comparator` has a different currency.
3979
+ *
3980
+ * @return {Boolean}
3981
+ */
3982
+ lessThanOrEqual: function lessThanOrEqual(comparator) {
3983
+ assertSameCurrency.call(this, comparator);
3984
+ var comparators = Dinero.normalizePrecision([this, comparator]);
3985
+ return comparators[0].getAmount() <= comparators[1].getAmount();
3986
+ },
3987
+
3988
+ /**
3989
+ * Checks whether the value represented by this object is greater than the other.
3990
+ *
3991
+ * @param {Dinero} comparator - The Dinero object to compare to.
3992
+ *
3993
+ * @example
3994
+ * // returns false
3995
+ * Dinero({ amount: 500 }).greaterThan(Dinero({ amount: 800 }))
3996
+ * @example
3997
+ * // returns true
3998
+ * Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 500 }))
3999
+ * @example
4000
+ * // returns true
4001
+ * Dinero({ amount: 800 }).greaterThan(Dinero({ amount: 5000, precision: 3 }))
4002
+ * @example
4003
+ * // returns false
4004
+ * Dinero({ amount: 5000, precision: 3 }).greaterThan(Dinero({ amount: 800 }))
4005
+ *
4006
+ * @throws {TypeError} If `comparator` has a different currency.
4007
+ *
4008
+ * @return {Boolean}
4009
+ */
4010
+ greaterThan: function greaterThan(comparator) {
4011
+ assertSameCurrency.call(this, comparator);
4012
+ var comparators = Dinero.normalizePrecision([this, comparator]);
4013
+ return comparators[0].getAmount() > comparators[1].getAmount();
4014
+ },
4015
+
4016
+ /**
4017
+ * Checks whether the value represented by this object is greater than or equal to the other.
4018
+ *
4019
+ * @param {Dinero} comparator - The Dinero object to compare to.
4020
+ *
4021
+ * @example
4022
+ * // returns true
4023
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 300 }))
4024
+ * @example
4025
+ * // returns true
4026
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 500 }))
4027
+ * @example
4028
+ * // returns false
4029
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 800 }))
4030
+ * @example
4031
+ * // returns true
4032
+ * Dinero({ amount: 800 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
4033
+ * @example
4034
+ * // returns true
4035
+ * Dinero({ amount: 500 }).greaterThanOrEqual(Dinero({ amount: 5000, precision: 3 }))
4036
+ * @example
4037
+ * // returns false
4038
+ * Dinero({ amount: 5000, precision: 3 }).greaterThanOrEqual(Dinero({ amount: 800 }))
4039
+ *
4040
+ * @throws {TypeError} If `comparator` has a different currency.
4041
+ *
4042
+ * @return {Boolean}
4043
+ */
4044
+ greaterThanOrEqual: function greaterThanOrEqual(comparator) {
4045
+ assertSameCurrency.call(this, comparator);
4046
+ var comparators = Dinero.normalizePrecision([this, comparator]);
4047
+ return comparators[0].getAmount() >= comparators[1].getAmount();
4048
+ },
4049
+
4050
+ /**
4051
+ * Checks if the value represented by this object is zero.
4052
+ *
4053
+ * @example
4054
+ * // returns true
4055
+ * Dinero({ amount: 0 }).isZero()
4056
+ * @example
4057
+ * // returns false
4058
+ * Dinero({ amount: 100 }).isZero()
4059
+ *
4060
+ * @return {Boolean}
4061
+ */
4062
+ isZero: function isZero() {
4063
+ return this.getAmount() === 0;
4064
+ },
4065
+
4066
+ /**
4067
+ * Checks if the value represented by this object is positive.
4068
+ *
4069
+ * @example
4070
+ * // returns false
4071
+ * Dinero({ amount: -10 }).isPositive()
4072
+ * @example
4073
+ * // returns true
4074
+ * Dinero({ amount: 10 }).isPositive()
4075
+ * @example
4076
+ * // returns true
4077
+ * Dinero({ amount: 0 }).isPositive()
4078
+ *
4079
+ * @return {Boolean}
4080
+ */
4081
+ isPositive: function isPositive() {
4082
+ return this.getAmount() >= 0;
4083
+ },
4084
+
4085
+ /**
4086
+ * Checks if the value represented by this object is negative.
4087
+ *
4088
+ * @example
4089
+ * // returns true
4090
+ * Dinero({ amount: -10 }).isNegative()
4091
+ * @example
4092
+ * // returns false
4093
+ * Dinero({ amount: 10 }).isNegative()
4094
+ * @example
4095
+ * // returns false
4096
+ * Dinero({ amount: 0 }).isNegative()
4097
+ *
4098
+ * @return {Boolean}
4099
+ */
4100
+ isNegative: function isNegative() {
4101
+ return this.getAmount() < 0;
4102
+ },
4103
+
4104
+ /**
4105
+ * Checks if this has minor currency units.
4106
+ * Deprecates {@link module:Dinero~hasCents hasCents}.
4107
+ *
4108
+ * @example
4109
+ * // returns false
4110
+ * Dinero({ amount: 1100 }).hasSubUnits()
4111
+ * @example
4112
+ * // returns true
4113
+ * Dinero({ amount: 1150 }).hasSubUnits()
4114
+ *
4115
+ * @return {Boolean}
4116
+ */
4117
+ hasSubUnits: function hasSubUnits() {
4118
+ return calculator$1.modulo(this.getAmount(), Math.pow(10, precision)) !== 0;
4119
+ },
4120
+
4121
+ /**
4122
+ * Checks if this has minor currency units.
4123
+ *
4124
+ * @deprecated since version 1.4.0, will be removed in 2.0.0
4125
+ * Use {@link module:Dinero~hasSubUnits hasSubUnits} instead.
4126
+ *
4127
+ * @example
4128
+ * // returns false
4129
+ * Dinero({ amount: 1100 }).hasCents()
4130
+ * @example
4131
+ * // returns true
4132
+ * Dinero({ amount: 1150 }).hasCents()
4133
+ *
4134
+ * @return {Boolean}
4135
+ */
4136
+ hasCents: function hasCents() {
4137
+ return calculator$1.modulo(this.getAmount(), Math.pow(10, precision)) !== 0;
4138
+ },
4139
+
4140
+ /**
4141
+ * Checks whether the currency represented by this object equals to the other.
4142
+ *
4143
+ * @param {Dinero} comparator - The Dinero object to compare to.
4144
+ *
4145
+ * @example
4146
+ * // returns true
4147
+ * Dinero({ amount: 2000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'EUR' }))
4148
+ * @example
4149
+ * // returns false
4150
+ * Dinero({ amount: 1000, currency: 'EUR' }).hasSameCurrency(Dinero({ amount: 1000, currency: 'USD' }))
4151
+ *
4152
+ * @return {Boolean}
4153
+ */
4154
+ hasSameCurrency: function hasSameCurrency(comparator) {
4155
+ return this.getCurrency() === comparator.getCurrency();
4156
+ },
4157
+
4158
+ /**
4159
+ * Checks whether the amount represented by this object equals to the other.
4160
+ *
4161
+ * @param {Dinero} comparator - The Dinero object to compare to.
4162
+ *
4163
+ * @example
4164
+ * // returns true
4165
+ * Dinero({ amount: 1000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000 }))
4166
+ * @example
4167
+ * // returns false
4168
+ * Dinero({ amount: 2000, currency: 'EUR' }).hasSameAmount(Dinero({ amount: 1000, currency: 'EUR' }))
4169
+ * @example
4170
+ * // returns true
4171
+ * Dinero({ amount: 1000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
4172
+ * @example
4173
+ * // returns false
4174
+ * Dinero({ amount: 10000, currency: 'EUR', precision: 2 }).hasSameAmount(Dinero({ amount: 10000, precision: 3 }))
4175
+ *
4176
+ * @return {Boolean}
4177
+ */
4178
+ hasSameAmount: function hasSameAmount(comparator) {
4179
+ var comparators = Dinero.normalizePrecision([this, comparator]);
4180
+ return comparators[0].getAmount() === comparators[1].getAmount();
4181
+ },
4182
+
4183
+ /**
4184
+ * Returns this object formatted as a string.
4185
+ *
4186
+ * The format is a mask which defines how the output string will be formatted.
4187
+ * It defines whether to display a currency, in what format, how many fraction digits to display and whether to use grouping separators.
4188
+ * The output is formatted according to the applying locale.
4189
+ *
4190
+ * Object | Format | String
4191
+ * :--------------------------- | :---------------- | :---
4192
+ * `Dinero({ amount: 500050 })` | `'$0,0.00'` | $5,000.50
4193
+ * `Dinero({ amount: 500050 })` | `'$0,0'` | $5,001
4194
+ * `Dinero({ amount: 500050 })` | `'$0'` | $5001
4195
+ * `Dinero({ amount: 500050 })` | `'$0.0'` | $5000.5
4196
+ * `Dinero({ amount: 500050 })` | `'USD0,0.0'` | USD5,000.5
4197
+ * `Dinero({ amount: 500050 })` | `'0,0.0 dollar'` | 5,000.5 dollars
4198
+ *
4199
+ * Don't try to substitute the `$` sign or the `USD` code with your target currency, nor adapt the format string to the exact format you want.
4200
+ * The format is a mask which defines a pattern and returns a valid, localized currency string.
4201
+ * If you want to display the object in a custom way, either use {@link module:Dinero~getAmount getAmount}, {@link module:Dinero~toUnit toUnit} or {@link module:Dinero~toRoundedUnit toRoundedUnit} and manipulate the output string as you wish.
4202
+ *
4203
+ * {@link module:Dinero~toFormat toFormat} wraps around `Number.prototype.toLocaleString`. For that reason, **format will vary depending on how it's implemented in the end user's environment**.
4204
+ *
4205
+ * You can also use `toLocaleString` directly:
4206
+ * `Dinero().toRoundedUnit(digits, roundingMode).toLocaleString(locale, options)`.
4207
+ *
4208
+ * By default, amounts are rounded using the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
4209
+ * You can also specify a different `roundingMode` to better fit your needs.
4210
+ *
4211
+ * @param {String} [format='$0,0.00'] - The format mask to format to.
4212
+ * @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
4213
+ *
4214
+ * @example
4215
+ * // returns $2,000
4216
+ * Dinero({ amount: 200000 }).toFormat('$0,0')
4217
+ * @example
4218
+ * // returns €50.5
4219
+ * Dinero({ amount: 5050, currency: 'EUR' }).toFormat('$0,0.0')
4220
+ * @example
4221
+ * // returns 100 euros
4222
+ * Dinero({ amount: 10000, currency: 'EUR' }).setLocale('fr-FR').toFormat('0,0 dollar')
4223
+ * @example
4224
+ * // returns 2000
4225
+ * Dinero({ amount: 200000, currency: 'EUR' }).toFormat()
4226
+ * @example
4227
+ * // returns $10
4228
+ * Dinero({ amount: 1050 }).toFormat('$0', 'HALF_EVEN')
4229
+ *
4230
+ * @return {String}
4231
+ */
4232
+ toFormat: function toFormat() {
4233
+ var format = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : globalFormat;
4234
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
4235
+ var formatter = Format(format);
4236
+ return this.toRoundedUnit(formatter.getMinimumFractionDigits(), roundingMode).toLocaleString(this.getLocale(), {
4237
+ currencyDisplay: formatter.getCurrencyDisplay(),
4238
+ useGrouping: formatter.getUseGrouping(),
4239
+ minimumFractionDigits: formatter.getMinimumFractionDigits(),
4240
+ style: formatter.getStyle(),
4241
+ currency: this.getCurrency()
4242
+ });
4243
+ },
4244
+
4245
+ /**
4246
+ * Returns the amount represented by this object in units.
4247
+ *
4248
+ * @example
4249
+ * // returns 10.5
4250
+ * Dinero({ amount: 1050 }).toUnit()
4251
+ * @example
4252
+ * // returns 10.545
4253
+ * Dinero({ amount: 10545, precision: 3 }).toUnit()
4254
+ *
4255
+ * @return {Number}
4256
+ */
4257
+ toUnit: function toUnit() {
4258
+ return calculator$1.divide(this.getAmount(), Math.pow(10, precision));
4259
+ },
4260
+
4261
+ /**
4262
+ * Returns the amount represented by this object in rounded units.
4263
+ *
4264
+ * By default, the method uses the **half away from zero** rule ([commercial rounding](https://en.wikipedia.org/wiki/Rounding#Round_half_away_from_zero)).
4265
+ * You can also specify a different `roundingMode` to better fit your needs.
4266
+ *
4267
+ * @example
4268
+ * // returns 10.6
4269
+ * Dinero({ amount: 1055 }).toRoundedUnit(1)
4270
+ * @example
4271
+ * // returns 10
4272
+ * Dinero({ amount: 1050 }).toRoundedUnit(0, 'HALF_EVEN')
4273
+ *
4274
+ * @param {Number} digits - The number of fraction digits to round to.
4275
+ * @param {String} [roundingMode='HALF_AWAY_FROM_ZERO'] - The rounding mode to use: `'HALF_ODD'`, `'HALF_EVEN'`, `'HALF_UP'`, `'HALF_DOWN'`, `'HALF_TOWARDS_ZERO'`, `'HALF_AWAY_FROM_ZERO'` or `'DOWN'`.
4276
+ *
4277
+ * @return {Number}
4278
+ */
4279
+ toRoundedUnit: function toRoundedUnit(digits) {
4280
+ var roundingMode = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : globalFormatRoundingMode;
4281
+ var factor = Math.pow(10, digits);
4282
+ return calculator$1.divide(calculator$1.round(calculator$1.multiply(this.toUnit(), factor), roundingMode), factor);
4283
+ },
4284
+
4285
+ /**
4286
+ * Returns the object's data as an object literal.
4287
+ *
4288
+ * @example
4289
+ * // returns { amount: 500, currency: 'EUR', precision: 2 }
4290
+ * Dinero({ amount: 500, currency: 'EUR', precision: 2 }).toObject()
4291
+ *
4292
+ * @return {Object}
4293
+ */
4294
+ toObject: function toObject() {
4295
+ return {
4296
+ amount: amount,
4297
+ currency: currency,
4298
+ precision: precision
4299
+ };
4300
+ },
4301
+
4302
+ /**
4303
+ * Returns the object's data as an object literal.
4304
+ *
4305
+ * Alias of {@link module:Dinero~toObject toObject}.
4306
+ * It is defined so that calling `JSON.stringify` on a Dinero object will automatically extract the relevant data.
4307
+ *
4308
+ * @example
4309
+ * // returns '{"amount":500,"currency":"EUR","precision":2}'
4310
+ * JSON.stringify(Dinero({ amount: 500, currency: 'EUR', precision: 2 }))
4311
+ *
4312
+ * @return {Object}
4313
+ */
4314
+ toJSON: function toJSON() {
4315
+ return this.toObject();
4316
+ }
4317
+ };
4318
+ };
4319
+
4320
+ var dinero = Object.assign(Dinero, Defaults, Globals, Static);
4321
+
4322
+ function formatCurrency(amount, withSymbol = true) {
4323
+ if (!amount)
4324
+ amount = 0;
4325
+ function format(amount) {
4326
+ const formattedString = withSymbol ? '$0,0.00' : '0,0.00';
4327
+ return dinero({ amount: amount, currency: 'USD' }).toFormat(formattedString);
4328
+ }
4329
+ return (amount < 0) ? `(${format(-amount)})` : format(amount);
4330
+ }
4331
+ function formatDate(dateString) {
4332
+ if (!dateString)
4333
+ return '';
4334
+ const date = new Date(dateString);
4335
+ return format(date, 'MMM d, yyyy');
4336
+ }
4337
+ function formatTime(dateString) {
4338
+ if (!dateString)
4339
+ return '';
4340
+ const date = new Date(dateString);
4341
+ return format(date, 'h:mmaaa');
4342
+ }
4343
+
4344
+ const paymentsListCss = ":host{display:block}";
4345
+
4346
+ const PaymentsList = class {
4347
+ constructor(hostRef) {
4348
+ index.registerInstance(this, hostRef);
4349
+ this.accountId = undefined;
4350
+ this.auth = {};
4351
+ this.payments = [];
4352
+ }
4353
+ requestPropsChanged() {
4354
+ this.fetchData();
4355
+ }
4356
+ fetchData() {
4357
+ const accountId = this.accountId;
4358
+ const endpoint = `account/${accountId}/payments`;
4359
+ Api(this.auth.token).get(endpoint)
4360
+ .then((response) => {
4361
+ const data = response.data.map((dataItem) => new Payment(dataItem));
4362
+ this.payments = data;
4363
+ });
4364
+ }
4365
+ ;
4366
+ render() {
4367
+ return (index.h(index.Host, null, index.h("table", { class: "justifi-table" }, index.h("thead", null, index.h("tr", null, index.h("th", { scope: "col", title: "The date and time each payment was made" }, "Made on"), index.h("th", { scope: "col", title: "The dollar amount of each payment" }, "Amount"), index.h("th", { scope: "col" }, "Account"), index.h("th", { scope: "col" }, "Description"), index.h("th", { scope: "col" }, "Payment ID"), index.h("th", { scope: "col" }, "Cardholder"), index.h("th", { scope: "col" }, "Payment Method"), index.h("th", { scope: "col" }, "Status"))), index.h("tbody", null, this.payments.map((payment) => {
4368
+ var _a, _b, _c, _d;
4369
+ index.h("tr", null, index.h("td", null, index.h("div", null, formatDate(payment.created_at)), index.h("div", null, formatTime(payment.created_at))), index.h("td", null, formatCurrency(payment.amount)), index.h("td", null, payment.account_id), index.h("td", null, payment.description), index.h("td", null, payment.id), index.h("td", null, (_b = (_a = payment.payment_method) === null || _a === void 0 ? void 0 : _a.card) === null || _b === void 0 ? void 0 : _b.name), index.h("td", null, (_d = (_c = payment.payment_method) === null || _c === void 0 ? void 0 : _c.card) === null || _d === void 0 ? void 0 : _d.acct_last_four), index.h("td", null, payment.status));
4370
+ })))));
4371
+ }
4372
+ static get watchers() { return {
4373
+ "accountId": ["requestPropsChanged"],
4374
+ "auth": ["requestPropsChanged"]
4375
+ }; }
4376
+ };
4377
+ PaymentsList.style = paymentsListCss;
4378
+
4379
+ exports.justifi_bank_account_form = BankAccountForm;
4380
+ exports.justifi_card_form = CardForm;
80
4381
  exports.justifi_payment_method_form = PaymentMethodForm;
4382
+ exports.justifi_payments_list = PaymentsList;