@formatjs/intl-durationformat 0.9.1 → 0.10.0

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.
package/src/core.js CHANGED
@@ -1,257 +1,308 @@
1
1
  // Core implementation of Intl.DurationFormat polyfill
2
2
  // Follows the TC39 Intl.DurationFormat proposal specification
3
- import { CanonicalizeLocaleList, GetNumberOption, GetOption, OrdinaryHasInstance, SupportedLocales, ToObject, invariant, } from '@formatjs/ecma402-abstract';
4
- import { ResolveLocale } from '@formatjs/intl-localematcher';
5
- import { GetDurationUnitOptions } from './abstract/GetDurationUnitOptions.js';
6
- import { PartitionDurationFormatPattern } from './abstract/PartitionDurationFormatPattern.js';
7
- import { ToDurationRecord } from './abstract/ToDurationRecord.js';
8
- import { getInternalSlots } from './get_internal_slots.js';
9
- import { numberingSystemNames } from './numbering-systems.generated.js';
10
- import { TIME_SEPARATORS } from './time-separators.generated.js';
3
+ import { CanonicalizeLocaleList, GetNumberOption, GetOption, OrdinaryHasInstance, SupportedLocales, ToObject, invariant } from "@formatjs/ecma402-abstract";
4
+ import { ResolveLocale } from "@formatjs/intl-localematcher";
5
+ import { GetDurationUnitOptions } from "./abstract/GetDurationUnitOptions.js";
6
+ import { PartitionDurationFormatPattern } from "./abstract/PartitionDurationFormatPattern.js";
7
+ import { ToDurationRecord } from "./abstract/ToDurationRecord.js";
8
+ import { getInternalSlots } from "./get_internal_slots.js";
9
+ import { numberingSystemNames } from "./numbering-systems.generated.js";
10
+ import { TIME_SEPARATORS } from "./time-separators.generated.js";
11
+ import "./types.js";
11
12
  // Keys that should be included in resolvedOptions() output
12
13
  // These represent all the configurable options for duration formatting
13
- var RESOLVED_OPTIONS_KEYS = [
14
- 'locale',
15
- 'style',
16
- 'years',
17
- 'yearsDisplay',
18
- 'months',
19
- 'monthsDisplay',
20
- 'weeks',
21
- 'weeksDisplay',
22
- 'days',
23
- 'daysDisplay',
24
- 'hours',
25
- 'hoursDisplay',
26
- 'minutes',
27
- 'minutesDisplay',
28
- 'seconds',
29
- 'secondsDisplay',
30
- 'milliseconds',
31
- 'millisecondsDisplay',
32
- 'microseconds',
33
- 'microsecondsDisplay',
34
- 'nanoseconds',
35
- 'nanosecondsDisplay',
36
- 'numberingSystem',
37
- 'fractionalDigits',
14
+ const RESOLVED_OPTIONS_KEYS = [
15
+ "locale",
16
+ "style",
17
+ "years",
18
+ "yearsDisplay",
19
+ "months",
20
+ "monthsDisplay",
21
+ "weeks",
22
+ "weeksDisplay",
23
+ "days",
24
+ "daysDisplay",
25
+ "hours",
26
+ "hoursDisplay",
27
+ "minutes",
28
+ "minutesDisplay",
29
+ "seconds",
30
+ "secondsDisplay",
31
+ "milliseconds",
32
+ "millisecondsDisplay",
33
+ "microseconds",
34
+ "microsecondsDisplay",
35
+ "nanoseconds",
36
+ "nanosecondsDisplay",
37
+ "numberingSystem",
38
+ "fractionalDigits"
38
39
  ];
39
40
  // Configuration table for all duration units (from spec Table 3)
40
41
  // Defines the style and display options for each unit, along with their defaults
41
42
  // Units are processed in order from largest (years) to smallest (nanoseconds)
42
- var TABLE_3 = [
43
- {
44
- styleSlot: 'years',
45
- displaySlot: 'yearsDisplay',
46
- unit: 'years',
47
- values: ['long', 'short', 'narrow'],
48
- digitalDefault: 'short',
49
- },
50
- {
51
- styleSlot: 'months',
52
- displaySlot: 'monthsDisplay',
53
- unit: 'months',
54
- values: ['long', 'short', 'narrow'],
55
- digitalDefault: 'short',
56
- },
57
- {
58
- styleSlot: 'weeks',
59
- displaySlot: 'weeksDisplay',
60
- unit: 'weeks',
61
- values: ['long', 'short', 'narrow'],
62
- digitalDefault: 'short',
63
- },
64
- {
65
- styleSlot: 'days',
66
- displaySlot: 'daysDisplay',
67
- unit: 'days',
68
- values: ['long', 'short', 'narrow'],
69
- digitalDefault: 'short',
70
- },
71
- {
72
- styleSlot: 'hours',
73
- displaySlot: 'hoursDisplay',
74
- unit: 'hours',
75
- values: ['long', 'short', 'narrow', 'numeric', '2-digit'],
76
- digitalDefault: 'numeric',
77
- },
78
- {
79
- styleSlot: 'minutes',
80
- displaySlot: 'minutesDisplay',
81
- unit: 'minutes',
82
- values: ['long', 'short', 'narrow', 'numeric', '2-digit'],
83
- digitalDefault: 'numeric',
84
- },
85
- {
86
- styleSlot: 'seconds',
87
- displaySlot: 'secondsDisplay',
88
- unit: 'seconds',
89
- values: ['long', 'short', 'narrow', 'numeric', '2-digit'],
90
- digitalDefault: 'numeric',
91
- },
92
- {
93
- styleSlot: 'milliseconds',
94
- displaySlot: 'millisecondsDisplay',
95
- unit: 'milliseconds',
96
- values: ['long', 'short', 'narrow', 'numeric'],
97
- digitalDefault: 'numeric',
98
- },
99
- {
100
- styleSlot: 'microseconds',
101
- displaySlot: 'microsecondsDisplay',
102
- unit: 'microseconds',
103
- values: ['long', 'short', 'narrow', 'numeric'],
104
- digitalDefault: 'numeric',
105
- },
106
- {
107
- styleSlot: 'nanoseconds',
108
- displaySlot: 'nanosecondsDisplay',
109
- unit: 'nanoseconds',
110
- values: ['long', 'short', 'narrow', 'numeric'],
111
- digitalDefault: 'numeric',
112
- },
43
+ const TABLE_3 = [
44
+ {
45
+ styleSlot: "years",
46
+ displaySlot: "yearsDisplay",
47
+ unit: "years",
48
+ values: [
49
+ "long",
50
+ "short",
51
+ "narrow"
52
+ ],
53
+ digitalDefault: "short"
54
+ },
55
+ {
56
+ styleSlot: "months",
57
+ displaySlot: "monthsDisplay",
58
+ unit: "months",
59
+ values: [
60
+ "long",
61
+ "short",
62
+ "narrow"
63
+ ],
64
+ digitalDefault: "short"
65
+ },
66
+ {
67
+ styleSlot: "weeks",
68
+ displaySlot: "weeksDisplay",
69
+ unit: "weeks",
70
+ values: [
71
+ "long",
72
+ "short",
73
+ "narrow"
74
+ ],
75
+ digitalDefault: "short"
76
+ },
77
+ {
78
+ styleSlot: "days",
79
+ displaySlot: "daysDisplay",
80
+ unit: "days",
81
+ values: [
82
+ "long",
83
+ "short",
84
+ "narrow"
85
+ ],
86
+ digitalDefault: "short"
87
+ },
88
+ {
89
+ styleSlot: "hours",
90
+ displaySlot: "hoursDisplay",
91
+ unit: "hours",
92
+ values: [
93
+ "long",
94
+ "short",
95
+ "narrow",
96
+ "numeric",
97
+ "2-digit"
98
+ ],
99
+ digitalDefault: "numeric"
100
+ },
101
+ {
102
+ styleSlot: "minutes",
103
+ displaySlot: "minutesDisplay",
104
+ unit: "minutes",
105
+ values: [
106
+ "long",
107
+ "short",
108
+ "narrow",
109
+ "numeric",
110
+ "2-digit"
111
+ ],
112
+ digitalDefault: "numeric"
113
+ },
114
+ {
115
+ styleSlot: "seconds",
116
+ displaySlot: "secondsDisplay",
117
+ unit: "seconds",
118
+ values: [
119
+ "long",
120
+ "short",
121
+ "narrow",
122
+ "numeric",
123
+ "2-digit"
124
+ ],
125
+ digitalDefault: "numeric"
126
+ },
127
+ {
128
+ styleSlot: "milliseconds",
129
+ displaySlot: "millisecondsDisplay",
130
+ unit: "milliseconds",
131
+ values: [
132
+ "long",
133
+ "short",
134
+ "narrow",
135
+ "numeric"
136
+ ],
137
+ digitalDefault: "numeric"
138
+ },
139
+ {
140
+ styleSlot: "microseconds",
141
+ displaySlot: "microsecondsDisplay",
142
+ unit: "microseconds",
143
+ values: [
144
+ "long",
145
+ "short",
146
+ "narrow",
147
+ "numeric"
148
+ ],
149
+ digitalDefault: "numeric"
150
+ },
151
+ {
152
+ styleSlot: "nanoseconds",
153
+ displaySlot: "nanosecondsDisplay",
154
+ unit: "nanoseconds",
155
+ values: [
156
+ "long",
157
+ "short",
158
+ "narrow",
159
+ "numeric"
160
+ ],
161
+ digitalDefault: "numeric"
162
+ }
113
163
  ];
114
164
  /**
115
- * DurationFormat provides locale-sensitive duration formatting
116
- * Implements the Intl.DurationFormat API from the TC39 proposal
117
- */
118
- var DurationFormat = /** @class */ (function () {
119
- function DurationFormat(locales, options) {
120
- // Ensure constructor is called with 'new' keyword
121
- // test262/test/intl402/ListFormat/constructor/constructor/newtarget-undefined.js
122
- // Cannot use `new.target` bc of IE11 & TS transpiles it to something else
123
- var newTarget = this && this instanceof DurationFormat ? this.constructor : void 0;
124
- if (!newTarget) {
125
- throw new TypeError("Intl.DurationFormat must be called with 'new'");
126
- }
127
- // Canonicalize the requested locales into a standard format
128
- var requestedLocales = CanonicalizeLocaleList(locales);
129
- var opt = Object.create(null);
130
- var opts = options === undefined ? Object.create(null) : ToObject(options);
131
- // Get locale matching algorithm preference ('best fit' or 'lookup')
132
- var matcher = GetOption(opts, 'localeMatcher', 'string', ['best fit', 'lookup'], 'best fit');
133
- // Get numbering system (e.g., 'latn', 'arab', 'deva')
134
- var numberingSystem = GetOption(opts, 'numberingSystem', 'string', undefined, undefined);
135
- if (numberingSystem !== undefined &&
136
- numberingSystemNames.indexOf(numberingSystem) < 0) {
137
- // Validate that the numbering system is recognized
138
- throw RangeError("Invalid numberingSystems: ".concat(numberingSystem));
139
- }
140
- opt.nu = numberingSystem;
141
- opt.localeMatcher = matcher;
142
- // Resolve the best matching locale from available locales
143
- var localeData = DurationFormat.localeData, availableLocales = DurationFormat.availableLocales;
144
- var r = ResolveLocale(availableLocales, requestedLocales, opt,
145
- // [[RelevantExtensionKeys]] slot - only 'nu' (numbering system) is supported
146
- ['nu'], localeData, DurationFormat.getDefaultLocale);
147
- var locale = r.locale;
148
- // Initialize internal slots for this formatter instance
149
- var internalSlots = getInternalSlots(this);
150
- internalSlots.initializedDurationFormat = true;
151
- internalSlots.locale = locale;
152
- internalSlots.numberingSystem = r.nu;
153
- // Get overall formatting style: 'long' (3 hours), 'short' (3 hr), 'narrow' (3h), or 'digital' (3:00:00)
154
- var style = GetOption(opts, 'style', 'string', ['long', 'short', 'narrow', 'digital'], 'short');
155
- internalSlots.style = style;
156
- internalSlots.dataLocale = r.dataLocale;
157
- // Process each duration unit (years through nanoseconds) to determine
158
- // its display style and when to show it (always/auto/never)
159
- var prevStyle = '';
160
- TABLE_3.forEach(function (row) {
161
- var styleSlot = row.styleSlot, displaySlot = row.displaySlot, unit = row.unit, valueList = row.values, digitalBase = row.digitalDefault;
162
- // Get the style and display options for this unit
163
- var unitOptions = GetDurationUnitOptions(unit, opts, style, valueList, digitalBase, prevStyle);
164
- internalSlots[styleSlot] = unitOptions.style;
165
- internalSlots[displaySlot] = unitOptions.display;
166
- // Track the previous style for time units (hours through microseconds)
167
- // This is used to ensure consistent digital formatting across related units
168
- if (unit === 'hours' ||
169
- unit === 'minutes' ||
170
- unit === 'seconds' ||
171
- unit === 'milliseconds' ||
172
- unit === 'microseconds') {
173
- prevStyle = unitOptions.style;
174
- }
175
- });
176
- // Get the number of fractional digits for sub-second precision (0-9)
177
- internalSlots.fractionalDigits = GetNumberOption(opts, 'fractionalDigits', 0, 9, undefined);
178
- }
179
- DurationFormat.prototype.resolvedOptions = function () {
180
- if (typeof this !== 'object' ||
181
- !OrdinaryHasInstance(DurationFormat, this)) {
182
- throw TypeError('Method Intl.DurationFormat.prototype.resolvedOptions called on incompatible receiver');
183
- }
184
- var internalSlots = getInternalSlots(this);
185
- var ro = {};
186
- for (var _i = 0, RESOLVED_OPTIONS_KEYS_1 = RESOLVED_OPTIONS_KEYS; _i < RESOLVED_OPTIONS_KEYS_1.length; _i++) {
187
- var key = RESOLVED_OPTIONS_KEYS_1[_i];
188
- var v = internalSlots[key];
189
- if (key === 'fractionalDigits') {
190
- if (v !== undefined) {
191
- v = Number(v);
192
- }
193
- }
194
- else {
195
- invariant(v !== undefined, "Missing internal slot ".concat(key));
196
- }
197
- ro[key] = v;
198
- }
199
- return ro;
200
- };
201
- DurationFormat.prototype.formatToParts = function (duration) {
202
- var locInternalSlots = getInternalSlots(this);
203
- if (locInternalSlots.initializedDurationFormat === undefined) {
204
- throw new TypeError('Error uninitialized locale');
205
- }
206
- var record = ToDurationRecord(duration);
207
- var parts = PartitionDurationFormatPattern(this, record);
208
- var result = [];
209
- for (var _i = 0, parts_1 = parts; _i < parts_1.length; _i++) {
210
- var _a = parts_1[_i], type = _a.type, unit = _a.unit, value = _a.value;
211
- var obj = { type: type, value: value };
212
- if (unit) {
213
- obj.unit = unit;
214
- }
215
- result.push(obj);
216
- }
217
- return result;
218
- };
219
- DurationFormat.prototype.format = function (duration) {
220
- var locInternalSlots = getInternalSlots(this);
221
- if (locInternalSlots.initializedDurationFormat === undefined) {
222
- throw new TypeError('Error uninitialized locale');
223
- }
224
- var record = ToDurationRecord(duration);
225
- var parts = PartitionDurationFormatPattern(this, record);
226
- var result = '';
227
- for (var _i = 0, parts_2 = parts; _i < parts_2.length; _i++) {
228
- var value = parts_2[_i].value;
229
- result += value;
230
- }
231
- return result;
232
- };
233
- DurationFormat.supportedLocalesOf = function (locales, options) {
234
- return SupportedLocales(DurationFormat.availableLocales, CanonicalizeLocaleList(locales), options);
235
- };
236
- DurationFormat.__defaultLocale = 'en';
237
- DurationFormat.availableLocales = new Set();
238
- DurationFormat.localeData = Object.keys(TIME_SEPARATORS.localeData).reduce(function (all, locale) {
239
- DurationFormat.availableLocales.add(locale);
240
- var nu = TIME_SEPARATORS.localeData[locale].nu;
241
- all[locale] = {
242
- nu: nu,
243
- digitalFormat: TIME_SEPARATORS.localeData[locale].separator ||
244
- nu.reduce(function (separators, n) {
245
- separators[n] = TIME_SEPARATORS.default;
246
- return separators;
247
- }, {}),
248
- };
249
- return all;
250
- }, {});
251
- DurationFormat.getDefaultLocale = function () {
252
- return DurationFormat.__defaultLocale;
253
- };
254
- DurationFormat.polyfilled = true;
255
- return DurationFormat;
256
- }());
257
- export { DurationFormat };
165
+ * DurationFormat provides locale-sensitive duration formatting
166
+ * Implements the Intl.DurationFormat API from the TC39 proposal
167
+ */
168
+ export class DurationFormat {
169
+ constructor(locales, options) {
170
+ // Ensure constructor is called with 'new' keyword
171
+ // test262/test/intl402/ListFormat/constructor/constructor/newtarget-undefined.js
172
+ // Cannot use `new.target` bc of IE11 & TS transpiles it to something else
173
+ const newTarget = this && this instanceof DurationFormat ? this.constructor : void 0;
174
+ if (!newTarget) {
175
+ throw new TypeError("Intl.DurationFormat must be called with 'new'");
176
+ }
177
+ // Canonicalize the requested locales into a standard format
178
+ const requestedLocales = CanonicalizeLocaleList(locales);
179
+ const opt = Object.create(null);
180
+ const opts = options === undefined ? Object.create(null) : ToObject(options);
181
+ // Get locale matching algorithm preference ('best fit' or 'lookup')
182
+ const matcher = GetOption(opts, "localeMatcher", "string", ["best fit", "lookup"], "best fit");
183
+ // Get numbering system (e.g., 'latn', 'arab', 'deva')
184
+ const numberingSystem = GetOption(opts, "numberingSystem", "string", undefined, undefined);
185
+ if (numberingSystem !== undefined && numberingSystemNames.indexOf(numberingSystem) < 0) {
186
+ // Validate that the numbering system is recognized
187
+ throw RangeError(`Invalid numberingSystems: ${numberingSystem}`);
188
+ }
189
+ opt.nu = numberingSystem;
190
+ opt.localeMatcher = matcher;
191
+ // Resolve the best matching locale from available locales
192
+ const { localeData, availableLocales } = DurationFormat;
193
+ const r = ResolveLocale(
194
+ availableLocales,
195
+ requestedLocales,
196
+ opt,
197
+ // [[RelevantExtensionKeys]] slot - only 'nu' (numbering system) is supported
198
+ ["nu"],
199
+ localeData,
200
+ DurationFormat.getDefaultLocale
201
+ );
202
+ const locale = r.locale;
203
+ // Initialize internal slots for this formatter instance
204
+ const internalSlots = getInternalSlots(this);
205
+ internalSlots.initializedDurationFormat = true;
206
+ internalSlots.locale = locale;
207
+ internalSlots.numberingSystem = r.nu;
208
+ // Get overall formatting style: 'long' (3 hours), 'short' (3 hr), 'narrow' (3h), or 'digital' (3:00:00)
209
+ const style = GetOption(opts, "style", "string", [
210
+ "long",
211
+ "short",
212
+ "narrow",
213
+ "digital"
214
+ ], "short");
215
+ internalSlots.style = style;
216
+ internalSlots.dataLocale = r.dataLocale;
217
+ // Process each duration unit (years through nanoseconds) to determine
218
+ // its display style and when to show it (always/auto/never)
219
+ let prevStyle = "";
220
+ TABLE_3.forEach((row) => {
221
+ const { styleSlot, displaySlot, unit, values: valueList, digitalDefault: digitalBase } = row;
222
+ // Get the style and display options for this unit
223
+ const unitOptions = GetDurationUnitOptions(unit, opts, style, valueList, digitalBase, prevStyle);
224
+ internalSlots[styleSlot] = unitOptions.style;
225
+ internalSlots[displaySlot] = unitOptions.display;
226
+ // Track the previous style for time units (hours through microseconds)
227
+ // This is used to ensure consistent digital formatting across related units
228
+ if (unit === "hours" || unit === "minutes" || unit === "seconds" || unit === "milliseconds" || unit === "microseconds") {
229
+ prevStyle = unitOptions.style;
230
+ }
231
+ });
232
+ // Get the number of fractional digits for sub-second precision (0-9)
233
+ internalSlots.fractionalDigits = GetNumberOption(opts, "fractionalDigits", 0, 9, undefined);
234
+ }
235
+ resolvedOptions() {
236
+ if (typeof this !== "object" || !OrdinaryHasInstance(DurationFormat, this)) {
237
+ throw TypeError("Method Intl.DurationFormat.prototype.resolvedOptions called on incompatible receiver");
238
+ }
239
+ const internalSlots = getInternalSlots(this);
240
+ const ro = {};
241
+ for (const key of RESOLVED_OPTIONS_KEYS) {
242
+ let v = internalSlots[key];
243
+ if (key === "fractionalDigits") {
244
+ if (v !== undefined) {
245
+ v = Number(v);
246
+ }
247
+ } else {
248
+ invariant(v !== undefined, `Missing internal slot ${key}`);
249
+ }
250
+ ro[key] = v;
251
+ }
252
+ return ro;
253
+ }
254
+ formatToParts(duration) {
255
+ const locInternalSlots = getInternalSlots(this);
256
+ if (locInternalSlots.initializedDurationFormat === undefined) {
257
+ throw new TypeError("Error uninitialized locale");
258
+ }
259
+ const record = ToDurationRecord(duration);
260
+ const parts = PartitionDurationFormatPattern(this, record);
261
+ const result = [];
262
+ for (const { type, unit, value } of parts) {
263
+ const obj = {
264
+ type,
265
+ value
266
+ };
267
+ if (unit) {
268
+ obj.unit = unit;
269
+ }
270
+ result.push(obj);
271
+ }
272
+ return result;
273
+ }
274
+ format(duration) {
275
+ const locInternalSlots = getInternalSlots(this);
276
+ if (locInternalSlots.initializedDurationFormat === undefined) {
277
+ throw new TypeError("Error uninitialized locale");
278
+ }
279
+ const record = ToDurationRecord(duration);
280
+ const parts = PartitionDurationFormatPattern(this, record);
281
+ let result = "";
282
+ for (const { value } of parts) {
283
+ result += value;
284
+ }
285
+ return result;
286
+ }
287
+ static supportedLocalesOf(locales, options) {
288
+ return SupportedLocales(DurationFormat.availableLocales, CanonicalizeLocaleList(locales), options);
289
+ }
290
+ static __defaultLocale = "en";
291
+ static availableLocales = new Set();
292
+ static localeData = Object.keys(TIME_SEPARATORS.localeData).reduce((all, locale) => {
293
+ DurationFormat.availableLocales.add(locale);
294
+ const nu = TIME_SEPARATORS.localeData[locale].nu;
295
+ all[locale] = {
296
+ nu,
297
+ digitalFormat: TIME_SEPARATORS.localeData[locale].separator || nu.reduce((separators, n) => {
298
+ separators[n] = TIME_SEPARATORS.default;
299
+ return separators;
300
+ }, {})
301
+ };
302
+ return all;
303
+ }, {});
304
+ static getDefaultLocale = () => {
305
+ return DurationFormat.__defaultLocale;
306
+ };
307
+ static polyfilled = true;
308
+ }
@@ -1,2 +1,2 @@
1
- import type { DurationFormat, IntlDurationFormatInternal } from './types.js';
1
+ import type { DurationFormat, IntlDurationFormatInternal } from "./types.js";
2
2
  export declare function getInternalSlots(x: DurationFormat): IntlDurationFormatInternal;
@@ -1,9 +1,9 @@
1
- var internalSlotMap = new WeakMap();
1
+ const internalSlotMap = new WeakMap();
2
2
  export function getInternalSlots(x) {
3
- var internalSlots = internalSlotMap.get(x);
4
- if (!internalSlots) {
5
- internalSlots = Object.create(null);
6
- internalSlotMap.set(x, internalSlots);
7
- }
8
- return internalSlots;
3
+ let internalSlots = internalSlotMap.get(x);
4
+ if (!internalSlots) {
5
+ internalSlots = Object.create(null);
6
+ internalSlotMap.set(x, internalSlots);
7
+ }
8
+ return internalSlots;
9
9
  }