@nocobase/plugin-auth 0.17.0-alpha.7 → 0.18.0-alpha.2

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.
Files changed (63) hide show
  1. package/dist/client/authenticator.d.ts +13 -0
  2. package/dist/client/basic/SignInForm.d.ts +9 -0
  3. package/dist/client/basic/SignUpForm.d.ts +13 -0
  4. package/dist/client/basic/index.d.ts +3 -0
  5. package/dist/client/index.d.ts +21 -0
  6. package/dist/client/index.js +12 -2
  7. package/dist/client/pages/AuthLayout.d.ts +2 -0
  8. package/dist/client/pages/SignInPage.d.ts +16 -0
  9. package/dist/client/pages/SignUpPage.d.ts +21 -0
  10. package/dist/client/pages/index.d.ts +3 -0
  11. package/dist/client/settings/Options.d.ts +3 -2
  12. package/dist/externalVersion.js +14 -12
  13. package/dist/locale/en-US.json +4 -1
  14. package/dist/locale/zh-CN.json +4 -1
  15. package/dist/node_modules/cron/LICENSE +0 -0
  16. package/dist/node_modules/cron/lib/cron.js +1 -1
  17. package/dist/node_modules/cron/lib/job.js +0 -0
  18. package/dist/node_modules/cron/lib/time.js +33 -20
  19. package/dist/node_modules/cron/node_modules/luxon/build/amd/luxon.js +7826 -0
  20. package/dist/node_modules/cron/node_modules/luxon/build/cjs-browser/luxon.js +7824 -0
  21. package/dist/node_modules/cron/node_modules/luxon/build/es6/luxon.js +7217 -0
  22. package/dist/node_modules/cron/node_modules/luxon/build/global/luxon.js +7829 -0
  23. package/dist/node_modules/cron/node_modules/luxon/build/global/luxon.min.js +1 -0
  24. package/dist/node_modules/cron/node_modules/luxon/build/node/luxon.js +6932 -0
  25. package/dist/node_modules/cron/node_modules/luxon/package.json +85 -0
  26. package/dist/node_modules/cron/node_modules/luxon/src/datetime.js +2248 -0
  27. package/dist/node_modules/cron/node_modules/luxon/src/duration.js +948 -0
  28. package/dist/node_modules/cron/node_modules/luxon/src/errors.js +61 -0
  29. package/dist/node_modules/cron/node_modules/luxon/src/impl/conversions.js +161 -0
  30. package/dist/node_modules/cron/node_modules/luxon/src/impl/diff.js +75 -0
  31. package/dist/node_modules/cron/node_modules/luxon/src/impl/digits.js +75 -0
  32. package/dist/node_modules/cron/node_modules/luxon/src/impl/english.js +233 -0
  33. package/dist/node_modules/cron/node_modules/luxon/src/impl/formats.js +176 -0
  34. package/dist/node_modules/cron/node_modules/luxon/src/impl/formatter.js +400 -0
  35. package/dist/node_modules/cron/node_modules/luxon/src/impl/invalid.js +14 -0
  36. package/dist/node_modules/cron/node_modules/luxon/src/impl/locale.js +494 -0
  37. package/dist/node_modules/cron/node_modules/luxon/src/impl/regexParser.js +335 -0
  38. package/dist/node_modules/cron/node_modules/luxon/src/impl/tokenParser.js +444 -0
  39. package/dist/node_modules/cron/node_modules/luxon/src/impl/util.js +274 -0
  40. package/dist/node_modules/cron/node_modules/luxon/src/impl/zoneUtil.js +34 -0
  41. package/dist/node_modules/cron/node_modules/luxon/src/info.js +169 -0
  42. package/dist/node_modules/cron/node_modules/luxon/src/interval.js +637 -0
  43. package/dist/node_modules/cron/node_modules/luxon/src/luxon.js +26 -0
  44. package/dist/node_modules/cron/node_modules/luxon/src/package.json +4 -0
  45. package/dist/node_modules/cron/node_modules/luxon/src/settings.js +148 -0
  46. package/dist/node_modules/cron/node_modules/luxon/src/zone.js +91 -0
  47. package/dist/node_modules/cron/node_modules/luxon/src/zones/IANAZone.js +189 -0
  48. package/dist/node_modules/cron/node_modules/luxon/src/zones/fixedOffsetZone.js +102 -0
  49. package/dist/node_modules/cron/node_modules/luxon/src/zones/invalidZone.js +53 -0
  50. package/dist/node_modules/cron/node_modules/luxon/src/zones/systemZone.js +61 -0
  51. package/dist/node_modules/cron/package.json +1 -1
  52. package/dist/node_modules/cron/types/index.d.ts +181 -0
  53. package/dist/node_modules/cron/types/index.test-d.ts +85 -0
  54. package/dist/server/actions/authenticators.js +3 -0
  55. package/dist/server/basic-auth.js +5 -2
  56. package/dist/server/migrations/20231218132032-fix-allow-signup.d.ts +5 -0
  57. package/dist/server/migrations/20231218132032-fix-allow-signup.js +54 -0
  58. package/dist/server/model/authenticator.d.ts +5 -2
  59. package/dist/server/model/authenticator.js +2 -2
  60. package/package.json +2 -2
  61. package/dist/client/AuthPluginProvider.d.ts +0 -2
  62. package/dist/client/basic/SigninPage.d.ts +0 -6
  63. package/dist/client/basic/SignupPage.d.ts +0 -5
@@ -0,0 +1,948 @@
1
+ import { InvalidArgumentError, InvalidDurationError, InvalidUnitError } from "./errors.js";
2
+ import Formatter from "./impl/formatter.js";
3
+ import Invalid from "./impl/invalid.js";
4
+ import Locale from "./impl/locale.js";
5
+ import { parseISODuration, parseISOTimeOnly } from "./impl/regexParser.js";
6
+ import {
7
+ asNumber,
8
+ hasOwnProperty,
9
+ isNumber,
10
+ isUndefined,
11
+ normalizeObject,
12
+ roundTo,
13
+ } from "./impl/util.js";
14
+ import Settings from "./settings.js";
15
+
16
+ const INVALID = "Invalid Duration";
17
+
18
+ // unit conversion constants
19
+ export const lowOrderMatrix = {
20
+ weeks: {
21
+ days: 7,
22
+ hours: 7 * 24,
23
+ minutes: 7 * 24 * 60,
24
+ seconds: 7 * 24 * 60 * 60,
25
+ milliseconds: 7 * 24 * 60 * 60 * 1000,
26
+ },
27
+ days: {
28
+ hours: 24,
29
+ minutes: 24 * 60,
30
+ seconds: 24 * 60 * 60,
31
+ milliseconds: 24 * 60 * 60 * 1000,
32
+ },
33
+ hours: { minutes: 60, seconds: 60 * 60, milliseconds: 60 * 60 * 1000 },
34
+ minutes: { seconds: 60, milliseconds: 60 * 1000 },
35
+ seconds: { milliseconds: 1000 },
36
+ },
37
+ casualMatrix = {
38
+ years: {
39
+ quarters: 4,
40
+ months: 12,
41
+ weeks: 52,
42
+ days: 365,
43
+ hours: 365 * 24,
44
+ minutes: 365 * 24 * 60,
45
+ seconds: 365 * 24 * 60 * 60,
46
+ milliseconds: 365 * 24 * 60 * 60 * 1000,
47
+ },
48
+ quarters: {
49
+ months: 3,
50
+ weeks: 13,
51
+ days: 91,
52
+ hours: 91 * 24,
53
+ minutes: 91 * 24 * 60,
54
+ seconds: 91 * 24 * 60 * 60,
55
+ milliseconds: 91 * 24 * 60 * 60 * 1000,
56
+ },
57
+ months: {
58
+ weeks: 4,
59
+ days: 30,
60
+ hours: 30 * 24,
61
+ minutes: 30 * 24 * 60,
62
+ seconds: 30 * 24 * 60 * 60,
63
+ milliseconds: 30 * 24 * 60 * 60 * 1000,
64
+ },
65
+
66
+ ...lowOrderMatrix,
67
+ },
68
+ daysInYearAccurate = 146097.0 / 400,
69
+ daysInMonthAccurate = 146097.0 / 4800,
70
+ accurateMatrix = {
71
+ years: {
72
+ quarters: 4,
73
+ months: 12,
74
+ weeks: daysInYearAccurate / 7,
75
+ days: daysInYearAccurate,
76
+ hours: daysInYearAccurate * 24,
77
+ minutes: daysInYearAccurate * 24 * 60,
78
+ seconds: daysInYearAccurate * 24 * 60 * 60,
79
+ milliseconds: daysInYearAccurate * 24 * 60 * 60 * 1000,
80
+ },
81
+ quarters: {
82
+ months: 3,
83
+ weeks: daysInYearAccurate / 28,
84
+ days: daysInYearAccurate / 4,
85
+ hours: (daysInYearAccurate * 24) / 4,
86
+ minutes: (daysInYearAccurate * 24 * 60) / 4,
87
+ seconds: (daysInYearAccurate * 24 * 60 * 60) / 4,
88
+ milliseconds: (daysInYearAccurate * 24 * 60 * 60 * 1000) / 4,
89
+ },
90
+ months: {
91
+ weeks: daysInMonthAccurate / 7,
92
+ days: daysInMonthAccurate,
93
+ hours: daysInMonthAccurate * 24,
94
+ minutes: daysInMonthAccurate * 24 * 60,
95
+ seconds: daysInMonthAccurate * 24 * 60 * 60,
96
+ milliseconds: daysInMonthAccurate * 24 * 60 * 60 * 1000,
97
+ },
98
+ ...lowOrderMatrix,
99
+ };
100
+
101
+ // units ordered by size
102
+ const orderedUnits = [
103
+ "years",
104
+ "quarters",
105
+ "months",
106
+ "weeks",
107
+ "days",
108
+ "hours",
109
+ "minutes",
110
+ "seconds",
111
+ "milliseconds",
112
+ ];
113
+
114
+ const reverseUnits = orderedUnits.slice(0).reverse();
115
+
116
+ // clone really means "create another instance just like this one, but with these changes"
117
+ function clone(dur, alts, clear = false) {
118
+ // deep merge for vals
119
+ const conf = {
120
+ values: clear ? alts.values : { ...dur.values, ...(alts.values || {}) },
121
+ loc: dur.loc.clone(alts.loc),
122
+ conversionAccuracy: alts.conversionAccuracy || dur.conversionAccuracy,
123
+ matrix: alts.matrix || dur.matrix,
124
+ };
125
+ return new Duration(conf);
126
+ }
127
+
128
+ function antiTrunc(n) {
129
+ return n < 0 ? Math.floor(n) : Math.ceil(n);
130
+ }
131
+
132
+ // NB: mutates parameters
133
+ function convert(matrix, fromMap, fromUnit, toMap, toUnit) {
134
+ const conv = matrix[toUnit][fromUnit],
135
+ raw = fromMap[fromUnit] / conv,
136
+ sameSign = Math.sign(raw) === Math.sign(toMap[toUnit]),
137
+ // ok, so this is wild, but see the matrix in the tests
138
+ added =
139
+ !sameSign && toMap[toUnit] !== 0 && Math.abs(raw) <= 1 ? antiTrunc(raw) : Math.trunc(raw);
140
+ toMap[toUnit] += added;
141
+ fromMap[fromUnit] -= added * conv;
142
+ }
143
+
144
+ // NB: mutates parameters
145
+ function normalizeValues(matrix, vals) {
146
+ reverseUnits.reduce((previous, current) => {
147
+ if (!isUndefined(vals[current])) {
148
+ if (previous) {
149
+ convert(matrix, vals, previous, vals, current);
150
+ }
151
+ return current;
152
+ } else {
153
+ return previous;
154
+ }
155
+ }, null);
156
+ }
157
+
158
+ // Remove all properties with a value of 0 from an object
159
+ function removeZeroes(vals) {
160
+ const newVals = {};
161
+ for (const [key, value] of Object.entries(vals)) {
162
+ if (value !== 0) {
163
+ newVals[key] = value;
164
+ }
165
+ }
166
+ return newVals;
167
+ }
168
+
169
+ /**
170
+ * A Duration object represents a period of time, like "2 months" or "1 day, 1 hour". Conceptually, it's just a map of units to their quantities, accompanied by some additional configuration and methods for creating, parsing, interrogating, transforming, and formatting them. They can be used on their own or in conjunction with other Luxon types; for example, you can use {@link DateTime#plus} to add a Duration object to a DateTime, producing another DateTime.
171
+ *
172
+ * Here is a brief overview of commonly used methods and getters in Duration:
173
+ *
174
+ * * **Creation** To create a Duration, use {@link Duration.fromMillis}, {@link Duration.fromObject}, or {@link Duration.fromISO}.
175
+ * * **Unit values** See the {@link Duration#years}, {@link Duration#months}, {@link Duration#weeks}, {@link Duration#days}, {@link Duration#hours}, {@link Duration#minutes}, {@link Duration#seconds}, {@link Duration#milliseconds} accessors.
176
+ * * **Configuration** See {@link Duration#locale} and {@link Duration#numberingSystem} accessors.
177
+ * * **Transformation** To create new Durations out of old ones use {@link Duration#plus}, {@link Duration#minus}, {@link Duration#normalize}, {@link Duration#set}, {@link Duration#reconfigure}, {@link Duration#shiftTo}, and {@link Duration#negate}.
178
+ * * **Output** To convert the Duration into other representations, see {@link Duration#as}, {@link Duration#toISO}, {@link Duration#toFormat}, and {@link Duration#toJSON}
179
+ *
180
+ * There's are more methods documented below. In addition, for more information on subtler topics like internationalization and validity, see the external documentation.
181
+ */
182
+ export default class Duration {
183
+ /**
184
+ * @private
185
+ */
186
+ constructor(config) {
187
+ const accurate = config.conversionAccuracy === "longterm" || false;
188
+ let matrix = accurate ? accurateMatrix : casualMatrix;
189
+
190
+ if (config.matrix) {
191
+ matrix = config.matrix;
192
+ }
193
+
194
+ /**
195
+ * @access private
196
+ */
197
+ this.values = config.values;
198
+ /**
199
+ * @access private
200
+ */
201
+ this.loc = config.loc || Locale.create();
202
+ /**
203
+ * @access private
204
+ */
205
+ this.conversionAccuracy = accurate ? "longterm" : "casual";
206
+ /**
207
+ * @access private
208
+ */
209
+ this.invalid = config.invalid || null;
210
+ /**
211
+ * @access private
212
+ */
213
+ this.matrix = matrix;
214
+ /**
215
+ * @access private
216
+ */
217
+ this.isLuxonDuration = true;
218
+ }
219
+
220
+ /**
221
+ * Create Duration from a number of milliseconds.
222
+ * @param {number} count of milliseconds
223
+ * @param {Object} opts - options for parsing
224
+ * @param {string} [opts.locale='en-US'] - the locale to use
225
+ * @param {string} opts.numberingSystem - the numbering system to use
226
+ * @param {string} [opts.conversionAccuracy='casual'] - the conversion system to use
227
+ * @return {Duration}
228
+ */
229
+ static fromMillis(count, opts) {
230
+ return Duration.fromObject({ milliseconds: count }, opts);
231
+ }
232
+
233
+ /**
234
+ * Create a Duration from a JavaScript object with keys like 'years' and 'hours'.
235
+ * If this object is empty then a zero milliseconds duration is returned.
236
+ * @param {Object} obj - the object to create the DateTime from
237
+ * @param {number} obj.years
238
+ * @param {number} obj.quarters
239
+ * @param {number} obj.months
240
+ * @param {number} obj.weeks
241
+ * @param {number} obj.days
242
+ * @param {number} obj.hours
243
+ * @param {number} obj.minutes
244
+ * @param {number} obj.seconds
245
+ * @param {number} obj.milliseconds
246
+ * @param {Object} [opts=[]] - options for creating this Duration
247
+ * @param {string} [opts.locale='en-US'] - the locale to use
248
+ * @param {string} opts.numberingSystem - the numbering system to use
249
+ * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
250
+ * @param {string} [opts.matrix=Object] - the custom conversion system to use
251
+ * @return {Duration}
252
+ */
253
+ static fromObject(obj, opts = {}) {
254
+ if (obj == null || typeof obj !== "object") {
255
+ throw new InvalidArgumentError(
256
+ `Duration.fromObject: argument expected to be an object, got ${
257
+ obj === null ? "null" : typeof obj
258
+ }`
259
+ );
260
+ }
261
+
262
+ return new Duration({
263
+ values: normalizeObject(obj, Duration.normalizeUnit),
264
+ loc: Locale.fromObject(opts),
265
+ conversionAccuracy: opts.conversionAccuracy,
266
+ matrix: opts.matrix,
267
+ });
268
+ }
269
+
270
+ /**
271
+ * Create a Duration from DurationLike.
272
+ *
273
+ * @param {Object | number | Duration} durationLike
274
+ * One of:
275
+ * - object with keys like 'years' and 'hours'.
276
+ * - number representing milliseconds
277
+ * - Duration instance
278
+ * @return {Duration}
279
+ */
280
+ static fromDurationLike(durationLike) {
281
+ if (isNumber(durationLike)) {
282
+ return Duration.fromMillis(durationLike);
283
+ } else if (Duration.isDuration(durationLike)) {
284
+ return durationLike;
285
+ } else if (typeof durationLike === "object") {
286
+ return Duration.fromObject(durationLike);
287
+ } else {
288
+ throw new InvalidArgumentError(
289
+ `Unknown duration argument ${durationLike} of type ${typeof durationLike}`
290
+ );
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Create a Duration from an ISO 8601 duration string.
296
+ * @param {string} text - text to parse
297
+ * @param {Object} opts - options for parsing
298
+ * @param {string} [opts.locale='en-US'] - the locale to use
299
+ * @param {string} opts.numberingSystem - the numbering system to use
300
+ * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
301
+ * @param {string} [opts.matrix=Object] - the preset conversion system to use
302
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
303
+ * @example Duration.fromISO('P3Y6M1W4DT12H30M5S').toObject() //=> { years: 3, months: 6, weeks: 1, days: 4, hours: 12, minutes: 30, seconds: 5 }
304
+ * @example Duration.fromISO('PT23H').toObject() //=> { hours: 23 }
305
+ * @example Duration.fromISO('P5Y3M').toObject() //=> { years: 5, months: 3 }
306
+ * @return {Duration}
307
+ */
308
+ static fromISO(text, opts) {
309
+ const [parsed] = parseISODuration(text);
310
+ if (parsed) {
311
+ return Duration.fromObject(parsed, opts);
312
+ } else {
313
+ return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
314
+ }
315
+ }
316
+
317
+ /**
318
+ * Create a Duration from an ISO 8601 time string.
319
+ * @param {string} text - text to parse
320
+ * @param {Object} opts - options for parsing
321
+ * @param {string} [opts.locale='en-US'] - the locale to use
322
+ * @param {string} opts.numberingSystem - the numbering system to use
323
+ * @param {string} [opts.conversionAccuracy='casual'] - the preset conversion system to use
324
+ * @param {string} [opts.matrix=Object] - the conversion system to use
325
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Times
326
+ * @example Duration.fromISOTime('11:22:33.444').toObject() //=> { hours: 11, minutes: 22, seconds: 33, milliseconds: 444 }
327
+ * @example Duration.fromISOTime('11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
328
+ * @example Duration.fromISOTime('T11:00').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
329
+ * @example Duration.fromISOTime('1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
330
+ * @example Duration.fromISOTime('T1100').toObject() //=> { hours: 11, minutes: 0, seconds: 0 }
331
+ * @return {Duration}
332
+ */
333
+ static fromISOTime(text, opts) {
334
+ const [parsed] = parseISOTimeOnly(text);
335
+ if (parsed) {
336
+ return Duration.fromObject(parsed, opts);
337
+ } else {
338
+ return Duration.invalid("unparsable", `the input "${text}" can't be parsed as ISO 8601`);
339
+ }
340
+ }
341
+
342
+ /**
343
+ * Create an invalid Duration.
344
+ * @param {string} reason - simple string of why this datetime is invalid. Should not contain parameters or anything else data-dependent
345
+ * @param {string} [explanation=null] - longer explanation, may include parameters and other useful debugging information
346
+ * @return {Duration}
347
+ */
348
+ static invalid(reason, explanation = null) {
349
+ if (!reason) {
350
+ throw new InvalidArgumentError("need to specify a reason the Duration is invalid");
351
+ }
352
+
353
+ const invalid = reason instanceof Invalid ? reason : new Invalid(reason, explanation);
354
+
355
+ if (Settings.throwOnInvalid) {
356
+ throw new InvalidDurationError(invalid);
357
+ } else {
358
+ return new Duration({ invalid });
359
+ }
360
+ }
361
+
362
+ /**
363
+ * @private
364
+ */
365
+ static normalizeUnit(unit) {
366
+ const normalized = {
367
+ year: "years",
368
+ years: "years",
369
+ quarter: "quarters",
370
+ quarters: "quarters",
371
+ month: "months",
372
+ months: "months",
373
+ week: "weeks",
374
+ weeks: "weeks",
375
+ day: "days",
376
+ days: "days",
377
+ hour: "hours",
378
+ hours: "hours",
379
+ minute: "minutes",
380
+ minutes: "minutes",
381
+ second: "seconds",
382
+ seconds: "seconds",
383
+ millisecond: "milliseconds",
384
+ milliseconds: "milliseconds",
385
+ }[unit ? unit.toLowerCase() : unit];
386
+
387
+ if (!normalized) throw new InvalidUnitError(unit);
388
+
389
+ return normalized;
390
+ }
391
+
392
+ /**
393
+ * Check if an object is a Duration. Works across context boundaries
394
+ * @param {object} o
395
+ * @return {boolean}
396
+ */
397
+ static isDuration(o) {
398
+ return (o && o.isLuxonDuration) || false;
399
+ }
400
+
401
+ /**
402
+ * Get the locale of a Duration, such 'en-GB'
403
+ * @type {string}
404
+ */
405
+ get locale() {
406
+ return this.isValid ? this.loc.locale : null;
407
+ }
408
+
409
+ /**
410
+ * Get the numbering system of a Duration, such 'beng'. The numbering system is used when formatting the Duration
411
+ *
412
+ * @type {string}
413
+ */
414
+ get numberingSystem() {
415
+ return this.isValid ? this.loc.numberingSystem : null;
416
+ }
417
+
418
+ /**
419
+ * Returns a string representation of this Duration formatted according to the specified format string. You may use these tokens:
420
+ * * `S` for milliseconds
421
+ * * `s` for seconds
422
+ * * `m` for minutes
423
+ * * `h` for hours
424
+ * * `d` for days
425
+ * * `w` for weeks
426
+ * * `M` for months
427
+ * * `y` for years
428
+ * Notes:
429
+ * * Add padding by repeating the token, e.g. "yy" pads the years to two digits, "hhhh" pads the hours out to four digits
430
+ * * Tokens can be escaped by wrapping with single quotes.
431
+ * * The duration will be converted to the set of units in the format string using {@link Duration#shiftTo} and the Durations's conversion accuracy setting.
432
+ * @param {string} fmt - the format string
433
+ * @param {Object} opts - options
434
+ * @param {boolean} [opts.floor=true] - floor numerical values
435
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("y d s") //=> "1 6 2"
436
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("yy dd sss") //=> "01 06 002"
437
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toFormat("M S") //=> "12 518402000"
438
+ * @return {string}
439
+ */
440
+ toFormat(fmt, opts = {}) {
441
+ // reverse-compat since 1.2; we always round down now, never up, and we do it by default
442
+ const fmtOpts = {
443
+ ...opts,
444
+ floor: opts.round !== false && opts.floor !== false,
445
+ };
446
+ return this.isValid
447
+ ? Formatter.create(this.loc, fmtOpts).formatDurationFromString(this, fmt)
448
+ : INVALID;
449
+ }
450
+
451
+ /**
452
+ * Returns a string representation of a Duration with all units included.
453
+ * To modify its behavior use the `listStyle` and any Intl.NumberFormat option, though `unitDisplay` is especially relevant.
454
+ * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat
455
+ * @param opts - On option object to override the formatting. Accepts the same keys as the options parameter of the native `Int.NumberFormat` constructor, as well as `listStyle`.
456
+ * @example
457
+ * ```js
458
+ * var dur = Duration.fromObject({ days: 1, hours: 5, minutes: 6 })
459
+ * dur.toHuman() //=> '1 day, 5 hours, 6 minutes'
460
+ * dur.toHuman({ listStyle: "long" }) //=> '1 day, 5 hours, and 6 minutes'
461
+ * dur.toHuman({ unitDisplay: "short" }) //=> '1 day, 5 hr, 6 min'
462
+ * ```
463
+ */
464
+ toHuman(opts = {}) {
465
+ const l = orderedUnits
466
+ .map((unit) => {
467
+ const val = this.values[unit];
468
+ if (isUndefined(val)) {
469
+ return null;
470
+ }
471
+ return this.loc
472
+ .numberFormatter({ style: "unit", unitDisplay: "long", ...opts, unit: unit.slice(0, -1) })
473
+ .format(val);
474
+ })
475
+ .filter((n) => n);
476
+
477
+ return this.loc
478
+ .listFormatter({ type: "conjunction", style: opts.listStyle || "narrow", ...opts })
479
+ .format(l);
480
+ }
481
+
482
+ /**
483
+ * Returns a JavaScript object with this Duration's values.
484
+ * @example Duration.fromObject({ years: 1, days: 6, seconds: 2 }).toObject() //=> { years: 1, days: 6, seconds: 2 }
485
+ * @return {Object}
486
+ */
487
+ toObject() {
488
+ if (!this.isValid) return {};
489
+ return { ...this.values };
490
+ }
491
+
492
+ /**
493
+ * Returns an ISO 8601-compliant string representation of this Duration.
494
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Durations
495
+ * @example Duration.fromObject({ years: 3, seconds: 45 }).toISO() //=> 'P3YT45S'
496
+ * @example Duration.fromObject({ months: 4, seconds: 45 }).toISO() //=> 'P4MT45S'
497
+ * @example Duration.fromObject({ months: 5 }).toISO() //=> 'P5M'
498
+ * @example Duration.fromObject({ minutes: 5 }).toISO() //=> 'PT5M'
499
+ * @example Duration.fromObject({ milliseconds: 6 }).toISO() //=> 'PT0.006S'
500
+ * @return {string}
501
+ */
502
+ toISO() {
503
+ // we could use the formatter, but this is an easier way to get the minimum string
504
+ if (!this.isValid) return null;
505
+
506
+ let s = "P";
507
+ if (this.years !== 0) s += this.years + "Y";
508
+ if (this.months !== 0 || this.quarters !== 0) s += this.months + this.quarters * 3 + "M";
509
+ if (this.weeks !== 0) s += this.weeks + "W";
510
+ if (this.days !== 0) s += this.days + "D";
511
+ if (this.hours !== 0 || this.minutes !== 0 || this.seconds !== 0 || this.milliseconds !== 0)
512
+ s += "T";
513
+ if (this.hours !== 0) s += this.hours + "H";
514
+ if (this.minutes !== 0) s += this.minutes + "M";
515
+ if (this.seconds !== 0 || this.milliseconds !== 0)
516
+ // this will handle "floating point madness" by removing extra decimal places
517
+ // https://stackoverflow.com/questions/588004/is-floating-point-math-broken
518
+ s += roundTo(this.seconds + this.milliseconds / 1000, 3) + "S";
519
+ if (s === "P") s += "T0S";
520
+ return s;
521
+ }
522
+
523
+ /**
524
+ * Returns an ISO 8601-compliant string representation of this Duration, formatted as a time of day.
525
+ * Note that this will return null if the duration is invalid, negative, or equal to or greater than 24 hours.
526
+ * @see https://en.wikipedia.org/wiki/ISO_8601#Times
527
+ * @param {Object} opts - options
528
+ * @param {boolean} [opts.suppressMilliseconds=false] - exclude milliseconds from the format if they're 0
529
+ * @param {boolean} [opts.suppressSeconds=false] - exclude seconds from the format if they're 0
530
+ * @param {boolean} [opts.includePrefix=false] - include the `T` prefix
531
+ * @param {string} [opts.format='extended'] - choose between the basic and extended format
532
+ * @example Duration.fromObject({ hours: 11 }).toISOTime() //=> '11:00:00.000'
533
+ * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressMilliseconds: true }) //=> '11:00:00'
534
+ * @example Duration.fromObject({ hours: 11 }).toISOTime({ suppressSeconds: true }) //=> '11:00'
535
+ * @example Duration.fromObject({ hours: 11 }).toISOTime({ includePrefix: true }) //=> 'T11:00:00.000'
536
+ * @example Duration.fromObject({ hours: 11 }).toISOTime({ format: 'basic' }) //=> '110000.000'
537
+ * @return {string}
538
+ */
539
+ toISOTime(opts = {}) {
540
+ if (!this.isValid) return null;
541
+
542
+ const millis = this.toMillis();
543
+ if (millis < 0 || millis >= 86400000) return null;
544
+
545
+ opts = {
546
+ suppressMilliseconds: false,
547
+ suppressSeconds: false,
548
+ includePrefix: false,
549
+ format: "extended",
550
+ ...opts,
551
+ };
552
+
553
+ const value = this.shiftTo("hours", "minutes", "seconds", "milliseconds");
554
+
555
+ let fmt = opts.format === "basic" ? "hhmm" : "hh:mm";
556
+
557
+ if (!opts.suppressSeconds || value.seconds !== 0 || value.milliseconds !== 0) {
558
+ fmt += opts.format === "basic" ? "ss" : ":ss";
559
+ if (!opts.suppressMilliseconds || value.milliseconds !== 0) {
560
+ fmt += ".SSS";
561
+ }
562
+ }
563
+
564
+ let str = value.toFormat(fmt);
565
+
566
+ if (opts.includePrefix) {
567
+ str = "T" + str;
568
+ }
569
+
570
+ return str;
571
+ }
572
+
573
+ /**
574
+ * Returns an ISO 8601 representation of this Duration appropriate for use in JSON.
575
+ * @return {string}
576
+ */
577
+ toJSON() {
578
+ return this.toISO();
579
+ }
580
+
581
+ /**
582
+ * Returns an ISO 8601 representation of this Duration appropriate for use in debugging.
583
+ * @return {string}
584
+ */
585
+ toString() {
586
+ return this.toISO();
587
+ }
588
+
589
+ /**
590
+ * Returns an milliseconds value of this Duration.
591
+ * @return {number}
592
+ */
593
+ toMillis() {
594
+ return this.as("milliseconds");
595
+ }
596
+
597
+ /**
598
+ * Returns an milliseconds value of this Duration. Alias of {@link toMillis}
599
+ * @return {number}
600
+ */
601
+ valueOf() {
602
+ return this.toMillis();
603
+ }
604
+
605
+ /**
606
+ * Make this Duration longer by the specified amount. Return a newly-constructed Duration.
607
+ * @param {Duration|Object|number} duration - The amount to add. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
608
+ * @return {Duration}
609
+ */
610
+ plus(duration) {
611
+ if (!this.isValid) return this;
612
+
613
+ const dur = Duration.fromDurationLike(duration),
614
+ result = {};
615
+
616
+ for (const k of orderedUnits) {
617
+ if (hasOwnProperty(dur.values, k) || hasOwnProperty(this.values, k)) {
618
+ result[k] = dur.get(k) + this.get(k);
619
+ }
620
+ }
621
+
622
+ return clone(this, { values: result }, true);
623
+ }
624
+
625
+ /**
626
+ * Make this Duration shorter by the specified amount. Return a newly-constructed Duration.
627
+ * @param {Duration|Object|number} duration - The amount to subtract. Either a Luxon Duration, a number of milliseconds, the object argument to Duration.fromObject()
628
+ * @return {Duration}
629
+ */
630
+ minus(duration) {
631
+ if (!this.isValid) return this;
632
+
633
+ const dur = Duration.fromDurationLike(duration);
634
+ return this.plus(dur.negate());
635
+ }
636
+
637
+ /**
638
+ * Scale this Duration by the specified amount. Return a newly-constructed Duration.
639
+ * @param {function} fn - The function to apply to each unit. Arity is 1 or 2: the value of the unit and, optionally, the unit name. Must return a number.
640
+ * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits(x => x * 2) //=> { hours: 2, minutes: 60 }
641
+ * @example Duration.fromObject({ hours: 1, minutes: 30 }).mapUnits((x, u) => u === "hours" ? x * 2 : x) //=> { hours: 2, minutes: 30 }
642
+ * @return {Duration}
643
+ */
644
+ mapUnits(fn) {
645
+ if (!this.isValid) return this;
646
+ const result = {};
647
+ for (const k of Object.keys(this.values)) {
648
+ result[k] = asNumber(fn(this.values[k], k));
649
+ }
650
+ return clone(this, { values: result }, true);
651
+ }
652
+
653
+ /**
654
+ * Get the value of unit.
655
+ * @param {string} unit - a unit such as 'minute' or 'day'
656
+ * @example Duration.fromObject({years: 2, days: 3}).get('years') //=> 2
657
+ * @example Duration.fromObject({years: 2, days: 3}).get('months') //=> 0
658
+ * @example Duration.fromObject({years: 2, days: 3}).get('days') //=> 3
659
+ * @return {number}
660
+ */
661
+ get(unit) {
662
+ return this[Duration.normalizeUnit(unit)];
663
+ }
664
+
665
+ /**
666
+ * "Set" the values of specified units. Return a newly-constructed Duration.
667
+ * @param {Object} values - a mapping of units to numbers
668
+ * @example dur.set({ years: 2017 })
669
+ * @example dur.set({ hours: 8, minutes: 30 })
670
+ * @return {Duration}
671
+ */
672
+ set(values) {
673
+ if (!this.isValid) return this;
674
+
675
+ const mixed = { ...this.values, ...normalizeObject(values, Duration.normalizeUnit) };
676
+ return clone(this, { values: mixed });
677
+ }
678
+
679
+ /**
680
+ * "Set" the locale and/or numberingSystem. Returns a newly-constructed Duration.
681
+ * @example dur.reconfigure({ locale: 'en-GB' })
682
+ * @return {Duration}
683
+ */
684
+ reconfigure({ locale, numberingSystem, conversionAccuracy, matrix } = {}) {
685
+ const loc = this.loc.clone({ locale, numberingSystem });
686
+ const opts = { loc, matrix, conversionAccuracy };
687
+ return clone(this, opts);
688
+ }
689
+
690
+ /**
691
+ * Return the length of the duration in the specified unit.
692
+ * @param {string} unit - a unit such as 'minutes' or 'days'
693
+ * @example Duration.fromObject({years: 1}).as('days') //=> 365
694
+ * @example Duration.fromObject({years: 1}).as('months') //=> 12
695
+ * @example Duration.fromObject({hours: 60}).as('days') //=> 2.5
696
+ * @return {number}
697
+ */
698
+ as(unit) {
699
+ return this.isValid ? this.shiftTo(unit).get(unit) : NaN;
700
+ }
701
+
702
+ /**
703
+ * Reduce this Duration to its canonical representation in its current units.
704
+ * @example Duration.fromObject({ years: 2, days: 5000 }).normalize().toObject() //=> { years: 15, days: 255 }
705
+ * @example Duration.fromObject({ hours: 12, minutes: -45 }).normalize().toObject() //=> { hours: 11, minutes: 15 }
706
+ * @return {Duration}
707
+ */
708
+ normalize() {
709
+ if (!this.isValid) return this;
710
+ const vals = this.toObject();
711
+ normalizeValues(this.matrix, vals);
712
+ return clone(this, { values: vals }, true);
713
+ }
714
+
715
+ /**
716
+ * Rescale units to its largest representation
717
+ * @example Duration.fromObject({ milliseconds: 90000 }).rescale().toObject() //=> { minutes: 1, seconds: 30 }
718
+ * @return {Duration}
719
+ */
720
+ rescale() {
721
+ if (!this.isValid) return this;
722
+ const vals = removeZeroes(this.normalize().shiftToAll().toObject());
723
+ return clone(this, { values: vals }, true);
724
+ }
725
+
726
+ /**
727
+ * Convert this Duration into its representation in a different set of units.
728
+ * @example Duration.fromObject({ hours: 1, seconds: 30 }).shiftTo('minutes', 'milliseconds').toObject() //=> { minutes: 60, milliseconds: 30000 }
729
+ * @return {Duration}
730
+ */
731
+ shiftTo(...units) {
732
+ if (!this.isValid) return this;
733
+
734
+ if (units.length === 0) {
735
+ return this;
736
+ }
737
+
738
+ units = units.map((u) => Duration.normalizeUnit(u));
739
+
740
+ const built = {},
741
+ accumulated = {},
742
+ vals = this.toObject();
743
+ let lastUnit;
744
+
745
+ for (const k of orderedUnits) {
746
+ if (units.indexOf(k) >= 0) {
747
+ lastUnit = k;
748
+
749
+ let own = 0;
750
+
751
+ // anything we haven't boiled down yet should get boiled to this unit
752
+ for (const ak in accumulated) {
753
+ own += this.matrix[ak][k] * accumulated[ak];
754
+ accumulated[ak] = 0;
755
+ }
756
+
757
+ // plus anything that's already in this unit
758
+ if (isNumber(vals[k])) {
759
+ own += vals[k];
760
+ }
761
+
762
+ const i = Math.trunc(own);
763
+ built[k] = i;
764
+ accumulated[k] = (own * 1000 - i * 1000) / 1000;
765
+
766
+ // plus anything further down the chain that should be rolled up in to this
767
+ for (const down in vals) {
768
+ if (orderedUnits.indexOf(down) > orderedUnits.indexOf(k)) {
769
+ convert(this.matrix, vals, down, built, k);
770
+ }
771
+ }
772
+ // otherwise, keep it in the wings to boil it later
773
+ } else if (isNumber(vals[k])) {
774
+ accumulated[k] = vals[k];
775
+ }
776
+ }
777
+
778
+ // anything leftover becomes the decimal for the last unit
779
+ // lastUnit must be defined since units is not empty
780
+ for (const key in accumulated) {
781
+ if (accumulated[key] !== 0) {
782
+ built[lastUnit] +=
783
+ key === lastUnit ? accumulated[key] : accumulated[key] / this.matrix[lastUnit][key];
784
+ }
785
+ }
786
+
787
+ return clone(this, { values: built }, true).normalize();
788
+ }
789
+
790
+ /**
791
+ * Shift this Duration to all available units.
792
+ * Same as shiftTo("years", "months", "weeks", "days", "hours", "minutes", "seconds", "milliseconds")
793
+ * @return {Duration}
794
+ */
795
+ shiftToAll() {
796
+ if (!this.isValid) return this;
797
+ return this.shiftTo(
798
+ "years",
799
+ "months",
800
+ "weeks",
801
+ "days",
802
+ "hours",
803
+ "minutes",
804
+ "seconds",
805
+ "milliseconds"
806
+ );
807
+ }
808
+
809
+ /**
810
+ * Return the negative of this Duration.
811
+ * @example Duration.fromObject({ hours: 1, seconds: 30 }).negate().toObject() //=> { hours: -1, seconds: -30 }
812
+ * @return {Duration}
813
+ */
814
+ negate() {
815
+ if (!this.isValid) return this;
816
+ const negated = {};
817
+ for (const k of Object.keys(this.values)) {
818
+ negated[k] = this.values[k] === 0 ? 0 : -this.values[k];
819
+ }
820
+ return clone(this, { values: negated }, true);
821
+ }
822
+
823
+ /**
824
+ * Get the years.
825
+ * @type {number}
826
+ */
827
+ get years() {
828
+ return this.isValid ? this.values.years || 0 : NaN;
829
+ }
830
+
831
+ /**
832
+ * Get the quarters.
833
+ * @type {number}
834
+ */
835
+ get quarters() {
836
+ return this.isValid ? this.values.quarters || 0 : NaN;
837
+ }
838
+
839
+ /**
840
+ * Get the months.
841
+ * @type {number}
842
+ */
843
+ get months() {
844
+ return this.isValid ? this.values.months || 0 : NaN;
845
+ }
846
+
847
+ /**
848
+ * Get the weeks
849
+ * @type {number}
850
+ */
851
+ get weeks() {
852
+ return this.isValid ? this.values.weeks || 0 : NaN;
853
+ }
854
+
855
+ /**
856
+ * Get the days.
857
+ * @type {number}
858
+ */
859
+ get days() {
860
+ return this.isValid ? this.values.days || 0 : NaN;
861
+ }
862
+
863
+ /**
864
+ * Get the hours.
865
+ * @type {number}
866
+ */
867
+ get hours() {
868
+ return this.isValid ? this.values.hours || 0 : NaN;
869
+ }
870
+
871
+ /**
872
+ * Get the minutes.
873
+ * @type {number}
874
+ */
875
+ get minutes() {
876
+ return this.isValid ? this.values.minutes || 0 : NaN;
877
+ }
878
+
879
+ /**
880
+ * Get the seconds.
881
+ * @return {number}
882
+ */
883
+ get seconds() {
884
+ return this.isValid ? this.values.seconds || 0 : NaN;
885
+ }
886
+
887
+ /**
888
+ * Get the milliseconds.
889
+ * @return {number}
890
+ */
891
+ get milliseconds() {
892
+ return this.isValid ? this.values.milliseconds || 0 : NaN;
893
+ }
894
+
895
+ /**
896
+ * Returns whether the Duration is invalid. Invalid durations are returned by diff operations
897
+ * on invalid DateTimes or Intervals.
898
+ * @return {boolean}
899
+ */
900
+ get isValid() {
901
+ return this.invalid === null;
902
+ }
903
+
904
+ /**
905
+ * Returns an error code if this Duration became invalid, or null if the Duration is valid
906
+ * @return {string}
907
+ */
908
+ get invalidReason() {
909
+ return this.invalid ? this.invalid.reason : null;
910
+ }
911
+
912
+ /**
913
+ * Returns an explanation of why this Duration became invalid, or null if the Duration is valid
914
+ * @type {string}
915
+ */
916
+ get invalidExplanation() {
917
+ return this.invalid ? this.invalid.explanation : null;
918
+ }
919
+
920
+ /**
921
+ * Equality check
922
+ * Two Durations are equal iff they have the same units and the same values for each unit.
923
+ * @param {Duration} other
924
+ * @return {boolean}
925
+ */
926
+ equals(other) {
927
+ if (!this.isValid || !other.isValid) {
928
+ return false;
929
+ }
930
+
931
+ if (!this.loc.equals(other.loc)) {
932
+ return false;
933
+ }
934
+
935
+ function eq(v1, v2) {
936
+ // Consider 0 and undefined as equal
937
+ if (v1 === undefined || v1 === 0) return v2 === undefined || v2 === 0;
938
+ return v1 === v2;
939
+ }
940
+
941
+ for (const u of orderedUnits) {
942
+ if (!eq(this.values[u], other.values[u])) {
943
+ return false;
944
+ }
945
+ }
946
+ return true;
947
+ }
948
+ }