From 3d1e3dda8655dd3d57d5bfce8c1e5709811889a8 Mon Sep 17 00:00:00 2001 From: Chris Bobbe Date: Mon, 24 Aug 2020 15:24:18 -0700 Subject: [PATCH 1/8] android: Use `Intl` variant of JavaScriptCore. We don't want to be using JavaScriptCore forever, if we can avoid it; we're tracking the switch to Hermes as #4131. In fact, Hermes doesn't yet support Intl. For now, this tiny code change will allow `react-intl` to work on Android. A `react-intl` doc [1] links to instructions [2] [3] to use a variant of JavaScriptCore that supports `Intl`. So, follow those instructions. Reportedly, this change will add 6MiB per architecture. #3547 was recently resolved, though, giving us some wiggle room. [1] https://formatjs.io/docs/react-intl/#react-native [2] https://github.com/react-native-community/jsc-android-buildscripts#international-variant [3] They're slightly out-of-date, currently, but it's still easy to tell what to do; see https://github.com/facebook/react-native/commit/d7f5153cd#diff-b8dd15c78827c1b48f9fe21c45686142R100-R111 for the new edit to make to `android/app/build.gradle`. --- android/app/build.gradle | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/build.gradle b/android/app/build.gradle index f6588271ec3..13e8e6a3765 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -133,7 +133,7 @@ def shrinkResourcesInProguardBuilds = false * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ -def jscFlavor = 'org.webkit:android-jsc:+' +def jscFlavor = 'org.webkit:android-jsc-intl:+' /** * Whether to enable the Hermes VM. From f8351f0a6fb89c3777309823c7400ec20e03e58e Mon Sep 17 00:00:00 2001 From: Chris Bobbe Date: Thu, 22 Oct 2020 17:41:20 -0700 Subject: [PATCH 2/8] i18n: Stop using ' character. In `react-intl` v3, the escape character is changed to the apostrophe (') [1]. So, don't use it in our text. [1] https://formatjs.io/docs/react-intl/upgrade-guide-3x/#escape-character-has-been-changed-to-apostrophe- --- src/compose/MentionWarnings.js | 2 +- src/message/messageActionSheet.js | 2 +- src/user-status/UserStatusScreen.js | 2 +- src/webview/webViewEventHandlers.js | 2 +- static/translations/messages_en.json | 8 ++++---- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/compose/MentionWarnings.js b/src/compose/MentionWarnings.js index c3727f7bb54..77e1212d983 100644 --- a/src/compose/MentionWarnings.js +++ b/src/compose/MentionWarnings.js @@ -73,7 +73,7 @@ class MentionWarnings extends PureComponent { showSubscriptionStatusLoadError = (mentionedUser: UserOrBot) => { const _ = this.context; - const alertTitle = _("Couldn't load information about {fullName}", { + const alertTitle = _('Couldn’t load information about {fullName}', { fullName: mentionedUser.full_name, }); showToast(alertTitle); diff --git a/src/message/messageActionSheet.js b/src/message/messageActionSheet.js index 06cb91b1c8d..0068ff0d99f 100644 --- a/src/message/messageActionSheet.js +++ b/src/message/messageActionSheet.js @@ -112,7 +112,7 @@ muteTopic.title = 'Mute topic'; muteTopic.errorMessage = 'Failed to mute topic'; const deleteTopic = async ({ auth, message, dispatch, ownEmail, _ }) => { - const alertTitle = _("Are you sure you want to delete the topic '{topic}'?", { + const alertTitle = _('Are you sure you want to delete the topic “{topic}”?', { topic: message.subject, }); const AsyncAlert = async (): Promise => diff --git a/src/user-status/UserStatusScreen.js b/src/user-status/UserStatusScreen.js index 990f6f61932..dbf1f407b6f 100644 --- a/src/user-status/UserStatusScreen.js +++ b/src/user-status/UserStatusScreen.js @@ -82,7 +82,7 @@ class UserStatusScreen extends PureComponent { autoFocus maxLength={60} style={styles.statusTextInput} - placeholder="What's your status?" + placeholder="What’s your status?" value={statusText} onChangeText={this.setStatusTextState} /> diff --git a/src/webview/webViewEventHandlers.js b/src/webview/webViewEventHandlers.js index 2acc2285412..60c8a3694a8 100644 --- a/src/webview/webViewEventHandlers.js +++ b/src/webview/webViewEventHandlers.js @@ -273,7 +273,7 @@ export const handleMessageListEvent = (props: Props, _: GetText, event: MessageL } case 'time': { - const alertText = _("This time is in your timezone. Original text was '{originalText}'.", { + const alertText = _('This time is in your timezone. Original text was “{originalText}”.', { originalText: event.originalText, }); Alert.alert('', alertText); diff --git a/static/translations/messages_en.json b/static/translations/messages_en.json index 43af6f3b644..63d2e1bde90 100644 --- a/static/translations/messages_en.json +++ b/static/translations/messages_en.json @@ -48,10 +48,10 @@ "Add a reaction": "Add a reaction", "Copy to clipboard": "Copy to clipboard", "Link copied to clipboard": "Link copied to clipboard", - "This time is in your timezone. Original text was '{originalText}'.": "This time is in your timezone. Original text was '{originalText}'.", + "This time is in your timezone. Original text was “{originalText}”.": "This time is in your timezone. Original text was “{originalText}”.", "Mute topic": "Mute topic", "Delete topic": "Delete topic", - "Are you sure you want to delete the topic '{topic}'?": "Are you sure you want to delete the topic '{topic}'?", + "Are you sure you want to delete the topic “{topic}”?": "Are you sure you want to delete the topic “{topic}”?", "This will also delete all messages in the topic.": "This will also delete all messages in the topic.", "Unmute topic": "Unmute topic", "Mute stream": "Mute stream", @@ -215,8 +215,8 @@ "Sending Message...": "Sending Message...", "Failed to send message": "Failed to send message", "Message sent": "Message sent", - "Couldn't load information about {fullName}": "Couldn't load information about {fullName}", - "What's your status?": "What's your status?", + "Couldn’t load information about {fullName}": "Couldn’t load information about {fullName}", + "What’s your status?": "What’s your status?", "Click to join video call": "Click to join video call", "📅 In a meeting": "📅 In a meeting", "🚌 Commuting": "🚌 Commuting", From 30e4d19ccbf610e2f25610ea075f988e60300267 Mon Sep 17 00:00:00 2001 From: Chris Bobbe Date: Thu, 6 Aug 2020 10:41:48 -0700 Subject: [PATCH 3/8] deps: Update `react-intl` to v3, which uses the new Context API. The old Context API is fundamentally broken, and much time has been spent engineering a way around it. This new version doesn't use it anymore, which is a relief! It's the last of our dependencies that did, at least in a way we had to be aware of. Now, our `intl` consumers will re-`render` when we expect them to -- and they'll no longer need the `key` hack. Nor will we need to "translate" (as we've been doing in `TranslationContextTranslator`) from the old to the new API. Following the upgrade guide [1], this commit does the following: - Stop using `addLocaleData`. It was removed, and we no longer need it. - No polyfilling. The section "Migrate to using native Intl APIs" suggests there may be something we have to do here, but it doesn't mention React Native specifically. There is a RN mention elsewhere, though, in the "Overview" doc [2]. So, follow that. In a recent commit, we made Android use the `Intl` variant of JavaScriptCore, and we trust a few rumors [3] (and the fact that it works for me) that JSC on iOS 10+ already has `Intl` support (our Deployment Target is 11.0), not having found a changelog or release announcement to confirm. - Remove `vendor/intl/intl.js`; we don't need it after the upgrade. It's not clear from fcc9466ac why (or if) we really needed it before the upgrade. - Remove the section in our React architecture doc about the old Context API! - Change out the libdef. There wasn't one from FlowTyped, as usual, so, translate from the TypeScript ambient type files with Flowgen and do manual tweaks. - Revert 5b6014e83 because v3 of this package doesn't use `prop-types` [4]. After running `yarn`, though, we got a peer-dep warning from "react-navigation > create-react-context@0.2.2". So, undo the reversion by adding `prop-types` back in, at the same semver range, and run `yarn`. Other breaking changes that don't affect us are mentioned in the upgrade guide. Also, run `yarn yarn-deduplicate && yarn` as prompted by `tools/test deps`. [1] https://formatjs.io/docs/react-intl/upgrade-guide-3x [2] https://formatjs.io/docs/react-intl/#react-native [3] See https://github.com/facebook/react-native/issues/19737#issuecomment-397625361 and https://github.com/facebook/react-native/issues/19251#issuecomment-389510354, and discussion on CZO at https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/.60.40formatjs.60.20polyfills/near/998279. [4] https://github.com/formatjs/formatjs/issues/1382#issuecomment-515627742 --- docs/architecture/react.md | 35 +- docs/howto/translations.md | 8 +- flow-typed/npm/react-intl_v2.x.x.js | 262 -- flow-typed/react-intl.js | 965 ----- flow-typed/react-intl_vx.x.x.js | 1123 ++++++ package.json | 2 +- src/ZulipMobile.js | 2 - src/boot/TranslationProvider.js | 41 +- src/i18n/locale.js | 84 - vendor/intl/LICENSE.txt | 66 - vendor/intl/intl.js | 5740 --------------------------- yarn.lock | 104 +- 12 files changed, 1214 insertions(+), 7218 deletions(-) delete mode 100644 flow-typed/npm/react-intl_v2.x.x.js delete mode 100644 flow-typed/react-intl.js create mode 100644 flow-typed/react-intl_vx.x.x.js delete mode 100644 src/i18n/locale.js delete mode 100644 vendor/intl/LICENSE.txt delete mode 100644 vendor/intl/intl.js diff --git a/docs/architecture/react.md b/docs/architecture/react.md index 657e1c5684f..efc631048e8 100644 --- a/docs/architecture/react.md +++ b/docs/architecture/react.md @@ -109,10 +109,10 @@ third-party library we use that isn't there yet. We should use the [current Context API](https://reactjs.org/docs/context.html) instead of the [legacy -one](https://reactjs.org/docs/legacy-context.html) wherever possible. -The new API aggressively ensures consumers will be updated -(re-`render`ed) on context changes, and the old one doesn't (see -below). From the [new API's +one](https://reactjs.org/docs/legacy-context.html) in our own code, +and avoid libraries that haven't updated yet. The new API aggressively +ensures consumers will be updated (re-`render`ed) on context changes, +and the old one doesn't. From the [new API's doc](https://reactjs.org/docs/context.html): > All consumers that are descendants of a Provider will re-render @@ -147,33 +147,6 @@ bad effects that `shouldComponentUpdate` returning `false` is meant to prevent: losing the scroll position, mainly (but also, we expect, discarding the image cache, etc.). -#### Legacy Context API - -The legacy Context API is -[declared](https://reactjs.org/docs/legacy-context.html#updating-context) -fundamentally broken because consumers could be blocked from receiving -updates to the context, and not just by the consumer's own -`shouldComponentUpdate`: - -> The problem is, if a context value provided by component changes, -> descendants that use that value won’t update if an intermediate -> parent returns `false` from `shouldComponentUpdate`. This is totally -> out of control of the components using context, so there’s basically -> no way to reliably update the context. - -We have to think about the legacy Context API because the `react-intl` -library's `IntlProvider` uses it to provide the `intl` context. Our -workaround is a "`key` hack": - -If `locale` changes, we make the entire React component tree at and -below `IntlProvider` remount. (Not merely re-`render`: completely -vanish and start over with `componentDidMount`; see the note at [this -doc](https://5d4b5feba32acd0008d0df98--reactjs.netlify.app/docs/reconciliation.html) -starting with "Keys should be stable, predictable, and unique".) We do -this with the [`key` -attribute](https://reactjs.org/docs/lists-and-keys.html), which isn't -recommended for use except in lists. - ### The exception: `MessageList` We have one React component that we wrote (beyond `connect` calls) that diff --git a/docs/howto/translations.md b/docs/howto/translations.md index f9c0fb0883f..70cb57b6277 100644 --- a/docs/howto/translations.md +++ b/docs/howto/translations.md @@ -156,14 +156,14 @@ to contribute translations into in the Zulip project on Transifex, which we do when someone expresses interest in contributing them. Each messages file in `static/translations/` should be reflected in -three boring, more-or-less mechanical lists: +two boring, more-or-less mechanical lists: * `flow-typed/translations.js` - * `src/i18n/locale.js` * `src/i18n/messages.js` The first of these has a comment with a trivial command to help -automate updating it. The others are smaller, and are maintained -manually. It'd be good to fully automate all of them; we haven't yet. +automate updating it. The other is smaller, and is maintained +manually. It'd be good to fully automate both of these; we haven't +yet. So, when a new messages file appears, update those three lists. Then see if the next section applies too... diff --git a/flow-typed/npm/react-intl_v2.x.x.js b/flow-typed/npm/react-intl_v2.x.x.js deleted file mode 100644 index 761cab29449..00000000000 --- a/flow-typed/npm/react-intl_v2.x.x.js +++ /dev/null @@ -1,262 +0,0 @@ -// flow-typed signature: 2c24ad1e7e27aef3bbc9a1eac12e1565 -// flow-typed version: c6154227d1/react-intl_v2.x.x/flow_>=v0.63.x <=v0.103.x - -/** - * Original implementation of this file by @marudor at https://github.com/marudor/flowInterfaces - * Copied here based on intention to merge with flow-typed expressed here: - * https://github.com/marudor/flowInterfaces/issues/6 - */ -// Mostly from https://github.com/yahoo/react-intl/wiki/API#react-intl-api -declare module "react-intl" { - import type { Element, ChildrenArray } from "react"; - - declare type $npm$ReactIntl$LocaleData = { - locale: string, - [key: string]: any - }; - - declare type $npm$ReactIntl$MessageDescriptor = { - id: string, - description?: string, - defaultMessage?: string - }; - - declare type $npm$ReactIntl$IntlConfig = { - locale: string, - formats: Object, - messages: { [id: string]: string }, - - defaultLocale?: string, - defaultFormats?: Object - }; - - declare type $npm$ReactIntl$IntlProviderConfig = { - locale?: string, - formats?: Object, - messages?: { [id: string]: string }, - - defaultLocale?: string, - defaultFormats?: Object - }; - - declare type $npm$ReactIntl$IntlFormat = { - formatDate: (value: any, options?: Object) => string, - formatTime: (value: any, options?: Object) => string, - formatRelative: (value: any, options?: Object) => string, - formatNumber: (value: any, options?: Object) => string, - formatPlural: (value: any, options?: Object) => string, - formatMessage: ( - messageDescriptor: $npm$ReactIntl$MessageDescriptor, - values?: Object - ) => string, - formatHTMLMessage: ( - messageDescriptor: $npm$ReactIntl$MessageDescriptor, - values?: Object - ) => string - }; - - declare type $npm$ReactIntl$IntlShape = $npm$ReactIntl$IntlConfig & - $npm$ReactIntl$IntlFormat & { now: () => number }; - - declare type $npm$ReactIntl$DateTimeFormatOptions = { - localeMatcher?: "best fit" | "lookup", - formatMatcher?: "basic" | "best fit", - - timeZone?: string, - hour12?: boolean, - - weekday?: "narrow" | "short" | "long", - era?: "narrow" | "short" | "long", - year?: "numeric" | "2-digit", - month?: "numeric" | "2-digit" | "narrow" | "short" | "long", - day?: "numeric" | "2-digit", - hour?: "numeric" | "2-digit", - minute?: "numeric" | "2-digit", - second?: "numeric" | "2-digit", - timeZoneName?: "short" | "long" - }; - - declare type $npm$ReactIntl$RelativeFormatOptions = { - style?: "best fit" | "numeric", - units?: "second" | "minute" | "hour" | "day" | "month" | "year" - }; - - declare type $npm$ReactIntl$NumberFormatOptions = { - localeMatcher?: "best fit" | "lookup", - - style?: "decimal" | "currency" | "percent", - - currency?: string, - currencyDisplay?: "symbol" | "code" | "name", - - useGrouping?: boolean, - - minimumIntegerDigits?: number, - minimumFractionDigits?: number, - maximumFractionDigits?: number, - minimumSignificantDigits?: number, - maximumSignificantDigits?: number - }; - - declare type $npm$ReactIntl$PluralFormatOptions = { - style?: "cardinal" | "ordinal" - }; - - declare type $npm$ReactIntl$PluralCategoryString = - | "zero" - | "one" - | "two" - | "few" - | "many" - | "other"; - - declare type $npm$ReactIntl$DateParseable = number | string | Date; - // PropType checker - declare function intlShape( - props: Object, - propName: string, - componentName: string - ): void; - declare function addLocaleData( - data: $npm$ReactIntl$LocaleData | Array<$npm$ReactIntl$LocaleData> - ): void; - declare function defineMessages< - T: { [key: string]: $Exact<$npm$ReactIntl$MessageDescriptor> } - >( - messageDescriptors: T - ): T; - - declare type InjectIntlProvidedProps = { - intl: $npm$ReactIntl$IntlShape - } - - declare type InjectIntlVoidProps = { - intl: $npm$ReactIntl$IntlShape | void - } - - declare type ComponentWithDefaultProps = - | React$ComponentType - | React$StatelessFunctionalComponent - | ChildrenArray>; - - declare type InjectIntlOptions = { - intlPropName?: string, - withRef?: boolean - } - - declare class IntlInjectedComponent extends React$Component { - static WrappedComponent: Class>, - static defaultProps: TDefaultProps, - props: TOwnProps - } - - declare type IntlInjectedComponentClass = Class< - IntlInjectedComponent - >; - - declare function injectIntl>( - WrappedComponent: Component, - options?: InjectIntlOptions, - ): React$ComponentType< - $Diff, InjectIntlVoidProps> - >; - - declare function formatMessage( - messageDescriptor: $npm$ReactIntl$MessageDescriptor, - values?: Object - ): string; - declare function formatHTMLMessage( - messageDescriptor: $npm$ReactIntl$MessageDescriptor, - values?: Object - ): string; - declare function formatDate( - value: any, - options?: $npm$ReactIntl$DateTimeFormatOptions & { format: string } - ): string; - declare function formatTime( - value: any, - options?: $npm$ReactIntl$DateTimeFormatOptions & { format: string } - ): string; - declare function formatRelative( - value: any, - options?: $npm$ReactIntl$RelativeFormatOptions & { - format: string, - now: any - } - ): string; - declare function formatNumber( - value: any, - options?: $npm$ReactIntl$NumberFormatOptions & { format: string } - ): string; - declare function formatPlural( - value: any, - options?: $npm$ReactIntl$PluralFormatOptions - ): $npm$ReactIntl$PluralCategoryString; - - declare class FormattedMessage extends React$Component< - $npm$ReactIntl$MessageDescriptor & { - values?: Object, - tagName?: string, - children?: - | ((...formattedMessage: Array) => React$Node) - | (string => React$Node) - } - > {} - declare class FormattedHTMLMessage extends React$Component< - $npm$ReactIntl$DateTimeFormatOptions & { - values?: Object, - tagName?: string, - children?: (...formattedMessage: Array) => React$Node - } - > {} - declare class FormattedDate extends React$Component< - $npm$ReactIntl$DateTimeFormatOptions & { - value: $npm$ReactIntl$DateParseable, - format?: string, - children?: (formattedDate: string) => React$Node - } - > {} - declare class FormattedTime extends React$Component< - $npm$ReactIntl$DateTimeFormatOptions & { - value: $npm$ReactIntl$DateParseable, - format?: string, - children?: (formattedDate: string) => React$Node - } - > {} - declare class FormattedRelative extends React$Component< - $npm$ReactIntl$RelativeFormatOptions & { - value: $npm$ReactIntl$DateParseable, - format?: string, - updateInterval?: number, - initialNow?: $npm$ReactIntl$DateParseable, - children?: (formattedDate: string) => React$Node - } - > {} - declare class FormattedNumber extends React$Component< - $npm$ReactIntl$NumberFormatOptions & { - value: number | string, - format?: string, - children?: (formattedNumber: string) => React$Node - } - > {} - declare class FormattedPlural extends React$Component< - $npm$ReactIntl$PluralFormatOptions & { - value: number | string, - other: React$Node, - zero?: React$Node, - one?: React$Node, - two?: React$Node, - few?: React$Node, - many?: React$Node, - children?: (formattedPlural: React$Node) => React$Node - } - > {} - declare class IntlProvider extends React$Component< - $npm$ReactIntl$IntlProviderConfig & { - children?: React$Node, - initialNow?: $npm$ReactIntl$DateParseable - } - > {} - declare type IntlShape = $npm$ReactIntl$IntlShape; - declare type MessageDescriptor = $npm$ReactIntl$MessageDescriptor; -} diff --git a/flow-typed/react-intl.js b/flow-typed/react-intl.js deleted file mode 100644 index 65739e823a1..00000000000 --- a/flow-typed/react-intl.js +++ /dev/null @@ -1,965 +0,0 @@ -// Copied from npm/react-intl_... -- except s/any/mixed/g -declare type $npm$ReactIntl$LocaleData = { - locale: string, - [key: string]: mixed, -}; - -/* - * Crudely @generated like so: - * $ ls node_modules/react-intl/locale-data/ \ - | perl -lne ' - s/\.js$//; - print "\ -declare module '\''react-intl/locale-data/$_'\'' { - declare export default \$npm\$ReactIntl\$LocaleData; -}"; - ' >>flow-typed/react-intl.js - */ - -declare module 'react-intl/locale-data/af' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/agq' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ak' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/am' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ar' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ars' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/asa' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/as' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ast' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/az' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bas' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/be' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bem' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bez' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bm' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/br' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/brx' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/bs' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ca' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ce' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/cgg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/chr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ckb' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/cs' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/cu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/cy' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/da' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/dav' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/de' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/dje' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/dsb' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/dua' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/dv' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/dyo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/dz' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ebu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ee' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/el' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/en' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/eo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/es' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/et' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/eu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ewo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/fa' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ff' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/fi' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/fil' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/fo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/fr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/fur' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/fy' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ga' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/gd' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/gl' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/gsw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/gu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/guw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/guz' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/gv' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ha' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/haw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/he' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/hi' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/hr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/hsb' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/hu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/hy' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/id' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ig' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ii' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/index' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/in' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/is' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/it' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/iu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/iw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ja' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/jbo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/jgo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ji' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/jmc' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/jv' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/jw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kab' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kaj' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ka' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kam' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kcg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kde' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kea' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/khq' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ki' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kkj' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kk' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kl' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kln' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/km' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ko' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kok' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ksb' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ksf' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ksh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ks' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ku' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/kw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ky' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lag' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lb' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lkt' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ln' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lrc' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lt' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/luo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/luy' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/lv' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mas' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mer' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mfe' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mgh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mgo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mk' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ml' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ms' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mt' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mua' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/my' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/mzn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nah' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/naq' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nb' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nd' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nds' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ne' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nl' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nmg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nnh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/no' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nqo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nso' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nus' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ny' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/nyn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/om' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/or' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/os' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/pa' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/pap' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/pl' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/prg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ps' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/pt' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/qu' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/rm' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/rn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/rof' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ro' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ru' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/rw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/rwk' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sah' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/saq' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sbp' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sdh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/seh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/se' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ses' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sg' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/shi' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/si' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sk' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sl' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sma' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/smi' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/smj' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/smn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sms' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/so' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sq' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ss' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ssy' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/st' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sv' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/sw' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/syr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ta' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/te' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/teo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/th' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/tig' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ti' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/tk' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/tl' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/tn' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/to' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/tr' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ts' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/twq' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/tzm' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ug' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/uk' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ur' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/uz' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/vai' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/ve' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/vi' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/vo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/vun' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/wae' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/wa' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/wo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/xh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/xog' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/yav' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/yi' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/yo' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/yue' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/zgh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/zh' { - declare export default $npm$ReactIntl$LocaleData; -} - -declare module 'react-intl/locale-data/zu' { - declare export default $npm$ReactIntl$LocaleData; -} diff --git a/flow-typed/react-intl_vx.x.x.js b/flow-typed/react-intl_vx.x.x.js new file mode 100644 index 00000000000..96704f06ed8 --- /dev/null +++ b/flow-typed/react-intl_vx.x.x.js @@ -0,0 +1,1123 @@ +// `react-intl` and all its dependencies, translated from the +// relevant-looking TypeScript .d.ts files, with minimal tweaks to +// make it work. + +// Currently not very useful; anything at `React.` is `any`; see +// https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/libdef.3A.20react-native-webview/near/896571. +// We should use Flow's builtin React type annotations, like +// React$Node instead of React.Node. + +// react-intl/dist/react-intl.d.ts +declare module 'react-intl' { + /** + * Flowtype definitions for react-intl + * Generated by Flowgen from a Typescript Definition + * Flowgen v1.11.0 + */ + + import type { DisplayNames } from '@formatjs/intl-displaynames'; + + declare type ArgumentElement = BaseElement; + declare interface ArgumentPart { + type: typeof PART_TYPE.argument; + value: any; + } + declare interface BaseElement> { + type: T; + value: string; + location?: Location; + } + /** + * Create intl object + * @param config intl config + * @param cache cache for formatter instances to prevent memory leak + */ + declare export function createIntl(config: OptionalIntlConfig, cache?: IntlCache): IntlShape; + declare export function createIntlCache(): IntlCache; + declare export interface CustomFormatConfig { + format?: string; + } + declare export type CustomFormats = { + relative?: { [key: string]: IntlRelativeTimeFormatOptions, ... }, + ... + } & $Rest; + declare type DateElement = SimpleFormatElement; + declare interface DateTimeSkeleton { + type: typeof SKELETON_TYPE.dateTime; + pattern: string; + location?: Location; + } + declare var DEFAULT_INTL_CONFIG: Pick< + IntlConfig, + | 'formats' + | 'messages' + | 'timeZone' + | 'textComponent' + | 'defaultLocale' + | 'defaultFormats' + | 'onError', + >; + declare export function defineMessages(msgs: U): U; + declare interface ElementPart { + type: 'element'; + value: string; + } + declare interface FieldData { + // $FlowFixMe - illegal name + '0'?: string; + // $FlowFixMe - illegal name + '1'?: string; + // $FlowFixMe - illegal name + '-1'?: string; + // $FlowFixMe - illegal name + '2'?: string; + // $FlowFixMe - illegal name + '-2'?: string; + // $FlowFixMe - illegal name + '3'?: string; + // $FlowFixMe - illegal name + '-3'?: string; + future: RelativeTimeData; + past: RelativeTimeData; + } + declare export type FormatDateOptions = Exclude & + CustomFormatConfig; + declare export type FormatDisplayNameOptions = Exclude; + declare export type FormatListOptions = Exclude; + declare export type FormatNumberOptions = Exclude & + CustomFormatConfig; + declare export type FormatPluralOptions = Exclude & + CustomFormatConfig; + declare export type FormatRelativeTimeOptions = Exclude< + IntlRelativeTimeFormatOptions, + 'localeMatcher', + > & + CustomFormatConfig; + declare interface Formats { + number: { [key: string]: Intl.NumberFormatOptions, ... }; + date: { [key: string]: Intl.DateTimeFormatOptions, ... }; + time: { [key: string]: Intl.DateTimeFormatOptions, ... }; + } + declare type FormattableUnit = Unit | Units; + declare export var FormattedDate: React.FC< + Intl.DateTimeFormatOptions & + CustomFormatConfig & { + value: string | number | Date | void, + ... + }, + >; + declare export var FormattedDateParts: React.FC< + Intl.DateTimeFormatOptions & + CustomFormatConfig & { + value: string | number | Date | void, + children( + val: Intl.DateTimeFormatPart[], + ): React.ReactElement< + any, + | string + | (( + props: any, + ) => React.ReactElement< + any, + string | any | ((props: any) => React.Component), + > | null) + | ((props: any) => React.Component), + > | null, + ... + }, + >; + declare export var FormattedDisplayName: React.FC< + DisplayNamesOptions & { + value: string | number | { [key: string]: any }, + ... + }, + >; + declare export class FormattedHTMLMessage + mixins FormattedMessage<{ + [string]: PrimitiveType, + ..., + }> { + static displayName: string; + static defaultProps: { + tagName: 'span', + values: { ... }, + ... + }; + render(): React$Node; + } + declare export var FormattedList: React.FC< + IntlListFormatOptions & { + value: React.Node[], + ... + }, + >; + + // changed `mixins` to `extends` in Flow to TS translation + declare export class FormattedMessage< + V: { [key: string]: any, ... } = { + [key: string]: PrimitiveType | React.ReactElement<> | FormatXMLElementFn, + ..., + }, + > extends React.Component> { + static displayName: string; + static defaultProps: { + values: { ... }, + ... + }; + shouldComponentUpdate(nextProps: Props_3): boolean; + render(): React$Node; + } + declare export var FormattedNumber: React.FC< + UnifiedNumberFormatOptions & + CustomFormatConfig & { + value: number, + ... + }, + >; + declare export var FormattedNumberParts: React.FC< + $PropertyType & { + value: $ElementType>, 0>, + children(val: Intl.NumberFormatPart[]): React.ReactElement<> | null, + ... + }, + >; + declare export var FormattedPlural: React.ForwardRefExoticComponent< + Pick< + Props_2, + | 'children' + | 'other' + | 'zero' + | 'one' + | 'two' + | 'few' + | 'many' + | 'localeMatcher' + | 'format' + | 'type' + | 'value', + > & { + forwardedRef?: ((instance: any) => void) | React.RefObject | null | void, + ... + } & React.RefAttributes, + > & { + WrappedComponent: React.ComponentType, + ... + }; + // changed `mixins` to `extends` in Flow to TS translation + declare export class FormattedRelativeTime extends React.PureComponent { + _updateTimer: any; + static displayName: string; + static defaultProps: Pick; + state: State_2; + constructor(props: Props): this; + scheduleNextUpdate(x: Props, x: State_2): void; + componentDidMount(): void; + componentDidUpdate(): void; + componentWillUnmount(): void; + static getDerivedStateFromProps(props: Props, state: State_2): $Rest | null; + render(): React$Node; + } + declare export var FormattedTime: React.FC< + Intl.DateTimeFormatOptions & + CustomFormatConfig & { + value: string | number | Date | void, + ... + }, + >; + declare export var FormattedTimeParts: React.FC< + Intl.DateTimeFormatOptions & + CustomFormatConfig & { + value: string | number | Date | void, + children( + val: Intl.DateTimeFormatPart[], + ): React.ReactElement< + any, + | string + | (( + props: any, + ) => React.ReactElement< + any, + string | any | ((props: any) => React.Component), + > | null) + | ((props: any) => React.Component), + > | null, + ... + }, + >; + declare type Formatter = { + formatDate: FormatDateOptions, + formatTime: FormatDateOptions, + formatNumber: FormatNumberOptions, + formatList: FormatListOptions, + formatDisplayName: FormatDisplayNameOptions, + ... + }; + declare export interface Formatters { + getDateTimeFormat( + ...args: ConstructorParameters + ): Intl.DateTimeFormat; + getNumberFormat(...args: ConstructorParameters): Intl.NumberFormat; + getMessageFormat(...args: ConstructorParameters): IntlMessageFormat; + getRelativeTimeFormat( + ...args: ConstructorParameters + ): RelativeTimeFormat; + getPluralRules(...args: ConstructorParameters): Intl.PluralRules; + getListFormat(...args: ConstructorParameters): ListFormat; + getDisplayNames(...args: ConstructorParameters): DisplayNames; + } + declare interface Formatters_2 { + getNumberFormat(...args: ConstructorParameters): Intl.NumberFormat; + getDateTimeFormat( + ...args: ConstructorParameters + ): Intl.DateTimeFormat; + getPluralRules(...args: ConstructorParameters): Intl.PluralRules; + } + declare type FormatXMLElementFn = (...args: any[]) => string | { [key: string]: any }; + declare export function injectIntl>( + WrappedComponent: React.ComponentType

, + options?: Opts, + ): React.FC> & { + WrappedComponent: React.ComponentType

, + ... + }; + declare export function injectIntl< + IntlPropName: string, + P: WrappedComponentProps, + T: React.ComponentType

, + >( + WrappedComponent: React.ComponentType

, + options?: Opts, + ): React.ForwardRefExoticComponent< + React.PropsWithoutRef> & React.RefAttributes, + > & { + WrappedComponent: React.ComponentType

, + ... + }; + declare export interface IntlCache { + dateTime: { [key: string]: Intl.DateTimeFormat, ... }; + number: { [key: string]: Intl.NumberFormat, ... }; + message: { [key: string]: IntlMessageFormat, ... }; + relativeTime: { [key: string]: RelativeTimeFormat, ... }; + pluralRules: { [key: string]: Intl.PluralRules, ... }; + list: { [key: string]: ListFormat, ... }; + displayNames: { [key: string]: DisplayNames, ... }; + } + declare export interface IntlConfig { + locale: string; + timeZone?: string; + formats: CustomFormats; + textComponent?: React.ComponentType<> | $Keys; + messages: { [key: string]: string, ... } | { [key: string]: MessageFormatElement[], ... }; + defaultLocale: string; + defaultFormats: CustomFormats; + onError(err: string): void; + } + declare export var IntlContext: React.Context; + // Changed from `interface` to `type` in TS to Flow translation. + declare export type IntlFormatters = { + formatDate( + value: $ElementType>, 0> | string, + opts?: FormatDateOptions, + ): string, + formatTime( + value: $ElementType>, 0> | string, + opts?: FormatDateOptions, + ): string, + formatDateToParts( + value: $ElementType>, 0> | string, + opts?: FormatDateOptions, + ): Intl.DateTimeFormatPart[], + formatTimeToParts( + value: $ElementType>, 0> | string, + opts?: FormatDateOptions, + ): Intl.DateTimeFormatPart[], + formatRelativeTime( + value: $ElementType>, 0>, + unit?: $ElementType>, 1>, + opts?: FormatRelativeTimeOptions, + ): string, + formatNumber( + value: $ElementType>, 0>, + opts?: FormatNumberOptions, + ): string, + formatNumberToParts( + value: $ElementType>, 0>, + opts?: FormatNumberOptions, + ): Intl.NumberFormatPart[], + formatPlural( + value: $ElementType>, 0>, + opts?: FormatPluralOptions, + ): $Call<((...args: any[]) => R) => R, $PropertyType>, + formatMessage( + descriptor: MessageDescriptor, + // The `+` was added to make the properties covariant rather + // than invariant, something TypeScript can't do. + values?: { +[key: string]: PrimitiveType, ... }, + ): string, + formatMessage( + descriptor: MessageDescriptor, + // The `+` was added to make the properties covariant rather + // than invariant, something TypeScript can't do. + values?: { +[key: string]: PrimitiveType | React.ReactElement<> | FormatXMLElementFn, ... }, + ): string | React.ReactNodeArray, + formatHTMLMessage( + descriptor: MessageDescriptor, + values?: { [key: string]: PrimitiveType, ... }, + ): React.Node, + formatList(values: Array, opts?: FormatListOptions): string, + formatList(values: Array, opts?: FormatListOptions): React.Node, + formatDisplayName( + value: $ElementType>, 0>, + opts?: FormatDisplayNameOptions, + ): string | void, + }; + declare interface IntlListFormatOptions { + /** + * The locale matching algorithm to use. + * Possible values are "lookup" and "best fit"; the default is "best fit". + * For information about this option, see + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation. + */ + localeMatcher?: 'best fit' | 'lookup'; + + /** + * The format of output message. Possible values are: + * - "always" (default, e.g., 1 day ago), + * - or "auto" (e.g., yesterday). + * The "auto" value allows to not always have to + * use numeric values in the output. + */ + type?: 'conjunction' | 'disjunction' | 'unit'; + + /** + * The length of the internationalized message. Possible values are: + * - "long" (default, e.g., in 1 month) + * - "short" (e.g., in 1 mo.), + * - or "narrow" (e.g., in 1 mo.). + * The narrow style could be similar to the short style for some locales. + */ + style?: 'long' | 'short' | 'narrow'; + } + declare class IntlMessageFormat { + constructor( + message: string | MessageFormatElement[], + locales?: string | string[], + overrideFormats?: $Rest, + opts?: Options, + ): this; + format: (values?: { [key: string]: PrimitiveType, ... } | void) => string; + formatToParts: (values?: { [key: string]: any, ... } | void) => MessageFormatPart[]; + formatHTMLMessage: ( + values?: { + [key: string]: + | string + | number + | boolean + | { [key: string]: any } + | Date + | FormatXMLElementFn + | null + | void, + ..., + } | void, + ) => (string | { [key: string]: any })[]; + resolvedOptions: () => { + locale: string, + ... + }; + getAst: () => MessageFormatElement[]; + static defaultLocale: string; + static __parse: typeof parse | void; + static formats: { + number: { + currency: { + style: string, + ... + }, + percent: { + style: string, + ... + }, + ... + }, + date: { + short: { + month: string, + day: string, + year: string, + ... + }, + medium: { + month: string, + day: string, + year: string, + ... + }, + long: { + month: string, + day: string, + year: string, + ... + }, + full: { + weekday: string, + month: string, + day: string, + year: string, + ... + }, + ... + }, + time: { + short: { + hour: string, + minute: string, + ... + }, + medium: { + hour: string, + minute: string, + second: string, + ... + }, + long: { + hour: string, + minute: string, + second: string, + timeZoneName: string, + ... + }, + full: { + hour: string, + minute: string, + second: string, + timeZoneName: string, + ... + }, + ... + }, + ... + }; + } + // changed `mixins` to `extends` in Flow to TS translation + declare export class IntlProvider extends React.PureComponent { + static displayName: string; + static defaultProps: Pick< + IntlConfig, + | 'formats' + | 'messages' + | 'timeZone' + | 'textComponent' + | 'defaultLocale' + | 'defaultFormats' + | 'onError', + >; + state: State; + static getDerivedStateFromProps( + props: OptionalIntlConfig, + x: State, + ): $Rest | null; + render(): React$Node; + } + declare interface IntlRelativeTimeFormatOptions { + /** + * The locale matching algorithm to use. + * Possible values are "lookup" and "best fit"; the default is "best fit". + * For information about this option, see + * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation. + */ + localeMatcher?: 'best fit' | 'lookup'; + + /** + * The format of output message. Possible values are: + * - "always" (default, e.g., 1 day ago), + * - or "auto" (e.g., yesterday). + * The "auto" value allows to not always have to + * use numeric values in the output. + */ + numeric?: 'always' | 'auto'; + + /** + * The length of the internationalized message. Possible values are: + * - "long" (default, e.g., in 1 month) + * - "short" (e.g., in 1 mo.), + * - or "narrow" (e.g., in 1 mo.). + * The narrow style could be similar to the short style for some locales. + */ + style?: 'long' | 'short' | 'narrow'; + } + declare export type IntlShape = { + formatters: Formatters, + ... + } & IntlConfig & + IntlFormatters; + declare interface IParseOptions { + filename?: string; + startRule?: string; + tracer?: any; + [key: string]: any; + } + declare type LDMLPluralRule = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'; + declare class ListFormat { + constructor(locales?: string | string[], options?: IntlListFormatOptions): this; + format(elements: string[]): string; + formatToParts(elements: string[]): Part_2[]; + resolvedOptions(): ResolvedIntlListFormatOptions; + static supportedLocalesOf( + locales: string | string[], + options?: Pick, + ): string[]; + static __addLocaleData(...data: ListPatternLocaleData[]): void; + static localeData: { [key: string]: ListPatternFieldsData, ... }; + static polyfilled: boolean; + } + declare interface ListPattern { + start: string; + middle: string; + end: string; + pair: string; + } + declare interface ListPatternData { + long: ListPattern; + short?: ListPattern; + narrow?: ListPattern; + } + declare interface ListPatternFieldsData { + conjunction?: ListPatternData; + disjunction?: ListPatternData; + unit?: ListPatternData; + } + declare type ListPatternLocaleData = LocaleData; + declare type LiteralElement = BaseElement; + declare interface LiteralPart { + type: 'literal'; + value: string; + } + declare interface LiteralPart_2 { + type: typeof PART_TYPE.literal; + value: string; + } + declare type Locale = string; + declare interface LocaleData { + data: { [key: Locale]: T, ... }; + aliases: { [key: string]: string, ... }; + availableLocales: string[]; + parentLocales: { [key: string]: string, ... }; + } + declare type LocaleFieldsData = $ObjMapi<{ [k: RelativeTimeField]: any }, (f) => FieldData> & { + nu?: Array, + ... + }; + declare interface Location { + start: LocationDetails; + end: LocationDetails; + } + declare interface LocationDetails { + offset: number; + line: number; + column: number; + } + + // Changed from `interface` to `type` in TS to Flow translation. + declare export type MessageDescriptor = { + id?: string | number, + description?: string | { [key: string]: any }, + defaultMessage?: string, + }; + declare type MessageFormatElement = + | LiteralElement + | ArgumentElement + | NumberElement + | DateElement + | TimeElement + | SelectElement + | PluralElement + | PoundElement; + declare type MessageFormatPart = LiteralPart_2 | ArgumentPart; + declare type NumberElement = SimpleFormatElement; + declare interface NumberFormatDigitOptions { + minimumIntegerDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; + minimumSignificantDigits?: number; + maximumSignificantDigits?: number; + } + declare interface NumberSkeleton { + type: typeof SKELETON_TYPE._number; + tokens: NumberSkeletonToken[]; + location?: Location; + } + declare interface NumberSkeletonToken { + stem: string; + options: string[]; + } + declare export type Omit> = Pick, K>>; + declare type OptionalIntlConfig = Omit> & + $Rest; + declare interface Options { + formatters?: Formatters_2; + } + declare interface Options_2 { + /** + * Whether to convert `#` in plural rule options + * to `{var, number}` + * Default is true + */ + normalizeHashtagInPlural?: boolean; + + /** + * Capture location info in AST + * Default is false + */ + captureLocation?: boolean; + } + declare interface Opts { + intlPropName?: IntlPropName; + forwardRef?: ForwardRef; + enforceContext?: boolean; + } + declare function parse(input: string, opts?: ParseOptions): MessageFormatElement[]; + declare type ParseOptions = Options_2 & IParseOptions; + declare type Part = LiteralPart | RelativeTimeFormatNumberPart; + declare type Part_2 = LiteralPart | ElementPart; + declare var PART_TYPE: {| + +literal: 0, // 0 + +argument: 1, // 1 + |}; + declare type PluralElement = { + options: { [key: ValidPluralRule]: PluralOrSelectOption, ... }, + offset: number, + pluralType: $PropertyType, + ... + } & BaseElement; + declare interface PluralOrSelectOption { + value: MessageFormatElement[]; + location?: Location; + } + declare interface PoundElement { + type: typeof TYPE.pound; + location?: Location; + } + declare type PrimitiveType = string | number | boolean | null | void | Date; + declare type Props = { + value?: number, + unit?: Unit, + updateIntervalInSeconds?: number, + children?: (value: string) => React.ReactChild, + ... + } & FormatRelativeTimeOptions; + declare type Props_2 = { + value: number, + intl: IntlShape, + other: React.Node, + zero?: React.Node, + one?: React.Node, + two?: React.Node, + few?: React.Node, + many?: React.Node, + children?: (value: React.Node) => React.ReactElement<> | null, + ... + } & FormatPluralOptions; + declare type Props_3 = { + values?: V, + tagName?: React.ElementType, + children?: (...nodes: React.ReactNodeArray) => React.Node, + ... + } & MessageDescriptor; + declare export var RawIntlProvider: React.Provider; + declare type RelativeTimeData = $ObjMapi<{ [k: LDMLPluralRule]: any }, (u) => string>; + declare type RelativeTimeField = + | 'second' + | 'second-short' + | 'second-narrow' + | 'minute' + | 'minute-short' + | 'minute-narrow' + | 'hour' + | 'hour-short' + | 'hour-narrow' + | 'day' + | 'day-short' + | 'day-narrow' + | 'week' + | 'week-short' + | 'week-narrow' + | 'month' + | 'month-short' + | 'month-narrow' + | 'quarter' + | 'quarter-short' + | 'quarter-narrow' + | 'year' + | 'year-short' + | 'year-narrow'; + declare class RelativeTimeFormat { + constructor(locales?: string | string[], options?: IntlRelativeTimeFormatOptions): this; + format(value: number, unit: FormattableUnit): string; + formatToParts(value: number, unit: FormattableUnit): Part[]; + resolvedOptions(): ResolvedIntlRelativeTimeFormatOptions; + static supportedLocalesOf( + locales: string | string[], + options?: Pick, + ): string[]; + static __addLocaleData(...data: RelativeTimeLocaleData[]): void; + static localeData: { [key: string]: UnpackedLocaleFieldsData, ... }; + static polyfilled: boolean; + } + declare type RelativeTimeFormatNumberPart = { + unit: Unit, + ... + } & Intl.NumberFormatPart; + declare type RelativeTimeLocaleData = LocaleData; + declare interface ResolvedIntlListFormatOptions { + /** + * The BCP 47 language tag for the locale actually used. + * If any Unicode extension values were requested in the + * input BCP 47 language tag that led to this locale, + * the key-value pairs that were requested and are + * supported for this locale are included in locale. + */ + locale: string; + + /** + * The format of output message. Possible values are: + * - "always" (default, e.g., 1 day ago), + * - or "auto" (e.g., yesterday). + * The "auto" value allows to not always have to + * use numeric values in the output. + */ + type: 'conjunction' | 'disjunction' | 'unit'; + + /** + * The length of the internationalized message. Possible values are: + * - "long" (default, e.g., in 1 month) + * - "short" (e.g., in 1 mo.), + * - or "narrow" (e.g., in 1 mo.). + * The narrow style could be similar to the short style for some locales. + */ + style: 'long' | 'short' | 'narrow'; + } + declare type ResolvedIntlRelativeTimeFormatOptions = { + /** + * The BCP 47 language tag for the locale actually used. + * If any Unicode extension values were requested in the + * input BCP 47 language tag that led to this locale, + * the key-value pairs that were requested and are + * supported for this locale are included in locale. + */ + locale: string, + + /** + * The value requested using the Unicode + * extension key "nu" or filled in as a default. + */ + numberingSystem: string, + ... + }; + declare type SelectElement = { + options: { [key: string]: PluralOrSelectOption, ... }, + ... + } & BaseElement; + declare type SimpleFormatElement, S: Skeleton> = { + style?: string | S | null, + ... + } & BaseElement; + declare type Skeleton = NumberSkeleton | DateTimeSkeleton; + declare var SKELETON_TYPE: {| + // underscore added in translating from TS; Flow complains of + // "Unexpected reserved type" + +_number: 0, // 0 + +dateTime: 1, // 1 + |}; + declare interface State { + /** + * Explicit intl cache to prevent memory leaks + */ + cache: IntlCache; + + /** + * Intl object we created + */ + intl?: IntlShape; + + /** + * list of memoized config we care about. + * This is important since creating intl is + * very expensive + */ + prevConfig: OptionalIntlConfig; + } + declare interface State_2 { + prevUnit?: Unit; + prevValue?: number; + currentValueInSeconds: number; + } + declare type TimeElement = SimpleFormatElement; + + declare var TYPE: {| + +literal: 0, // 0 + +argument: 1, // 1 + // underscore added in translating from TS; Flow complains of + // "Unexpected reserved type" + +_number: 2, // 2 + +date: 3, // 3 + +time: 4, // 4 + +select: 5, // 5 + +plural: 6, // 6 + +pound: 7, // 7 + |}; + declare type UnifiedNumberFormatOptions = Intl.NumberFormatOptions & + NumberFormatDigitOptions & { + localeMatcher?: UnifiedNumberFormatOptionsLocaleMatcher, + style?: UnifiedNumberFormatOptionsStyle, + compactDisplay?: UnifiedNumberFormatOptionsCompactDisplay, + currencyDisplay?: UnifiedNumberFormatOptionsCurrencyDisplay, + currencySign?: UnifiedNumberFormatOptionsCurrencySign, + notation?: UnifiedNumberFormatOptionsNotation, + signDisplay?: UnifiedNumberFormatOptionsSignDisplay, + unit?: Unit_2, + unitDisplay?: UnifiedNumberFormatOptionsUnitDisplay, + ... + }; + declare type UnifiedNumberFormatOptionsCompactDisplay = 'short' | 'long'; + declare type UnifiedNumberFormatOptionsCurrencyDisplay = + | 'symbol' + | 'code' + | 'name' + | 'narrowSymbol'; + declare type UnifiedNumberFormatOptionsCurrencySign = 'standard' | 'accounting'; + declare type UnifiedNumberFormatOptionsLocaleMatcher = 'lookup' | 'best fit'; + declare type UnifiedNumberFormatOptionsNotation = + | 'standard' + | 'scientific' + | 'engineering' + | 'compact'; + declare type UnifiedNumberFormatOptionsSignDisplay = 'auto' | 'always' | 'never' | 'exceptZero'; + declare type UnifiedNumberFormatOptionsStyle = 'decimal' | 'percent' | 'currency' | 'unit'; + declare type UnifiedNumberFormatOptionsUnitDisplay = 'long' | 'short' | 'narrow'; + declare type Unit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; + declare type Unit_2 = + | 'degree' + | 'acre' + | 'hectare' + | 'percent' + | 'bit' + | 'byte' + | 'gigabit' + | 'gigabyte' + | 'kilobit' + | 'kilobyte' + | 'megabit' + | 'megabyte' + | 'petabyte' + | 'terabit' + | 'terabyte' + | 'day' + | 'hour' + | 'millisecond' + | 'minute' + | 'month' + | 'second' + | 'week' + | 'year' + | 'centimeter' + | 'foot' + | 'inch' + | 'kilometer' + | 'meter' + | 'mile-scandinavian' + | 'mile' + | 'millimeter' + | 'yard' + | 'gram' + | 'kilogram' + | 'ounce' + | 'pound' + | 'stone' + | 'celsius' + | 'fahrenheit' + | 'fluid-ounce' + | 'gallon' + | 'liter' + | 'milliliter'; + declare type Units = + | 'seconds' + | 'minutes' + | 'hours' + | 'days' + | 'weeks' + | 'months' + | 'quarters' + | 'years'; + declare type UnpackedLocaleFieldsData = $ObjMapi< + { [k: RelativeTimeField]: any }, + (f) => FieldData, + > & { + nu: Array, + ... + }; + declare export function useIntl(): IntlShape; + declare type ValidPluralRule = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other' | string; + declare export type WithIntlProps

= Omit>> & { + forwardedRef?: React.Ref, + ... + }; + declare export type WrappedComponentProps = $ObjMapi< + { [k: IntlPropName]: any }, + (k) => IntlShape, + >; + declare export {}; +} + +// @formatjs/intl-utils/dist/types.d.ts +declare module '@formatjs/intl-utils/types' { + declare export type Locale = string; + declare export interface LocaleData { + data: { [Locale]: T, ... }; + aliases: { [string]: string, ... }; + availableLocales: string[]; + parentLocales: { [string]: string, ... }; + } +} + +// @formatjs/intl-utils/dist/displaynames-types.d.ts +declare module '@formatjs/intl-utils/displaynames-types' { + import type { LocaleData } from '@formatjs/intl-utils/types'; + + declare export type LanguageTag = string; + declare export type RegionCode = string; + declare export type ScriptCode = string; + declare export type CurrencyCode = string; + declare export interface DisplayNamesData { + /** + * Note that for style fields, `short` and `narrow` might not exist. + * At runtime, the fallback order will be narrow -> short -> long. + */ + types: { + /** + * Maps language subtag like `zh-CN` to their display names. + */ + language: { + narrow: { [key: LanguageTag]: string, ... }, + short: { [key: LanguageTag]: string, ... }, + long: { [key: LanguageTag]: string, ... }, + ... + }, + region: { + narrow: { [key: RegionCode]: string, ... }, + short: { [key: RegionCode]: string, ... }, + long: { [key: RegionCode]: string, ... }, + ... + }, + script: { + narrow: { [key: ScriptCode]: string, ... }, + short: { [key: ScriptCode]: string, ... }, + long: { [key: ScriptCode]: string, ... }, + ... + }, + currency: { + narrow: { [key: CurrencyCode]: string, ... }, + short: { [key: CurrencyCode]: string, ... }, + long: { [key: CurrencyCode]: string, ... }, + ... + }, + ... + }; + + /** + * Not in spec, but we need this to display both language and region in display name. + * e.g. zh-Hans-SG + "{0}({1})" -> 简体中文(新加坡) + * Here {0} is replaced by language display name and {1} is replaced by region display name. + */ + patterns: { + locale: string, + ... + }; + } + declare export type DisplayNamesLocaleData = LocaleData; + declare export {}; +} + +// @formatjs/intl-utils/dist/index.d.ts +declare module '@formatjs/intl-utils' { + /** + * Flowtype definitions for @formatjs/intl-utils/dist/index.d.ts + * Generated by Flowgen from a Typescript Definition + * Flowgen v1.11.0 + */ + + // Only the part we use is uncommented. + + // declare export { selectUnit } from './diff'; + // declare export { + // defaultNumberOption, + // getAliasesByLang, + // getInternalSlot, + // getMultiInternalSlots, + // getNumberOption, + // getOption, + // getParentLocalesByLang, + // isLiteralPart, + // LiteralPart, + // partitionPattern, + // setInternalSlot, + // setMultiInternalSlots, + // setNumberFormatDigitOptions, + // toObject, + // objectIs, + // isWellFormedCurrencyCode, + // toString, + // } from './polyfill-utils'; + // declare export { + // createResolveLocale, + // getLocaleHierarchy, + // supportedLocales, + // unpackData, + // isMissingLocaleDataError, + // } from './resolve-locale'; + // declare export * from './units' + // declare export * from './relative-time-types' + // declare export * from './unified-numberformat-types' + // declare export * from './list-types' + // declare export * from './plural-rules-types' + // declare export * from './number-types' + declare export * from '@formatjs/intl-utils/displaynames-types' + // declare export { getCanonicalLocales } from './get-canonical-locales'; + // declare export { invariant } from './invariant'; +} + +// @formatjs/intl-displaynames/dist/index.d.ts +declare module '@formatjs/intl-displaynames' { + /** + * Flowtype definitions for index + * Generated by Flowgen from a Typescript Definition + * Flowgen v1.11.0 + */ + + import type { DisplayNamesLocaleData, DisplayNamesData } from '@formatjs/intl-utils'; + + declare export interface DisplayNamesOptions { + localeMatcher?: 'lookup' | 'best fit'; + style?: 'narrow' | 'short' | 'long'; + type?: 'language' | 'region' | 'script' | 'currency'; + fallback?: 'code' | 'none'; + } + declare export interface DisplayNamesResolvedOptions { + locale: string; + style: $NonMaybeType<$PropertyType>; + type: $NonMaybeType<$PropertyType>; + fallback: $NonMaybeType<$PropertyType>; + } + declare export class DisplayNames { + constructor(locales?: string | string[], options?: DisplayNamesOptions): this; + static supportedLocalesOf( + locales?: string | string[], + options?: Pick, + ): string[]; + static __addLocaleData(...data: DisplayNamesLocaleData[]): void; + of(code: string | number | { [key: string]: any }): string | void; + resolvedOptions(): DisplayNamesResolvedOptions; + static localeData: { [key: string]: DisplayNamesData, ... }; + static +polyfilled: any; // true + } +} diff --git a/package.json b/package.json index df483c36da6..129676f40ff 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "lodash.union": "^4.6.0", "lodash.uniqby": "^4.4.0", "react": "16.11.0", - "react-intl": "^2.4.0", + "react-intl": "^3.12.1", "react-native": "0.62.2", "react-native-device-info": "^6.0.2", "react-native-document-picker": "^3.2.4", diff --git a/src/ZulipMobile.js b/src/ZulipMobile.js index 5bb53d63d35..0958f67cb21 100644 --- a/src/ZulipMobile.js +++ b/src/ZulipMobile.js @@ -2,7 +2,6 @@ import React from 'react'; import 'react-native-url-polyfill/auto'; -import '../vendor/intl/intl'; import StoreProvider from './boot/StoreProvider'; import TranslationProvider from './boot/TranslationProvider'; import ThemeProvider from './boot/ThemeProvider'; @@ -14,7 +13,6 @@ import InitialNavigationDispatcher from './nav/InitialNavigationDispatcher'; import AppWithNavigation from './nav/AppWithNavigation'; import NavigationService from './nav/NavigationService'; -import './i18n/locale'; import { initializeSentry } from './sentry'; initializeSentry(); diff --git a/src/boot/TranslationProvider.js b/src/boot/TranslationProvider.js index e43b97af468..ba04da7bd48 100644 --- a/src/boot/TranslationProvider.js +++ b/src/boot/TranslationProvider.js @@ -2,17 +2,14 @@ import React, { PureComponent } from 'react'; import type { ComponentType, ElementConfig, Node as React$Node } from 'react'; import { Text } from 'react-native'; -import { IntlProvider } from 'react-intl'; +import { IntlProvider, IntlContext } from 'react-intl'; import type { IntlShape } from 'react-intl'; import type { GetText, Dispatch } from '../types'; import { connect } from '../react-redux'; import { getSettings } from '../selectors'; -import '../../vendor/intl/intl'; import messages from '../i18n/messages'; -import '../i18n/locale'; - // $FlowFixMe could put a well-typed mock value here, to help write tests export const TranslationContext = React.createContext(undefined); @@ -45,29 +42,19 @@ const makeGetText = (intl: IntlShape): GetText => { }; /** - * Consume the old-API context from IntlProvider, and provide a new-API context. - * - * This consumes the context provided by react-intl through React's - * "legacy context API" from before 16.3, and provides a context through the - * new API. + * Consume IntlProvider's context, and provide it in a different shape. * - * See https://reactjs.org/docs/context.html - * vs. https://reactjs.org/docs/legacy-context.html . + * See the `GetTypes` type for why we like the new shape. */ class TranslationContextTranslator extends PureComponent<{| +children: React$Node, |}> { - context: { intl: IntlShape }; - - static contextTypes = { - intl: () => null, - }; - - _ = makeGetText(this.context.intl); + static contextType = IntlContext; + context: IntlShape; render() { return ( - + {this.props.children} ); @@ -85,21 +72,7 @@ class TranslationProvider extends PureComponent { const { locale, children } = this.props; return ( - /* `IntlProvider` uses React's "legacy context API", deprecated since - * React 16.3, of which the docs say: - * - * ## Updating Context - * - * Don't do it. - * - * React has an API to update context, but it is fundamentally - * broken and you should not use it. - * - * To work around that, we set `key={locale}` to force the whole tree - * to rerender if the locale changes. Not cheap, but the locale - * changing is rare. - */ - + {children} ); diff --git a/src/i18n/locale.js b/src/i18n/locale.js deleted file mode 100644 index d83095000e5..00000000000 --- a/src/i18n/locale.js +++ /dev/null @@ -1,84 +0,0 @@ -/* @flow strict-local */ - -import { addLocaleData } from 'react-intl'; -import ar from 'react-intl/locale-data/ar'; -import bg from 'react-intl/locale-data/bg'; -import ca from 'react-intl/locale-data/ca'; -import cs from 'react-intl/locale-data/cs'; -import da from 'react-intl/locale-data/da'; -import de from 'react-intl/locale-data/de'; -import el from 'react-intl/locale-data/el'; -import en from 'react-intl/locale-data/en'; -import es from 'react-intl/locale-data/es'; -import fa from 'react-intl/locale-data/fa'; -import fi from 'react-intl/locale-data/fi'; -import fr from 'react-intl/locale-data/fr'; -import gl from 'react-intl/locale-data/gl'; -import hi from 'react-intl/locale-data/hi'; -import hr from 'react-intl/locale-data/hr'; -import hu from 'react-intl/locale-data/hu'; -import id from 'react-intl/locale-data/id'; -import it from 'react-intl/locale-data/it'; -import ja from 'react-intl/locale-data/ja'; -import ko from 'react-intl/locale-data/ko'; -import lt from 'react-intl/locale-data/lt'; -import ml from 'react-intl/locale-data/ml'; -import nb from 'react-intl/locale-data/nb'; -import nl from 'react-intl/locale-data/nl'; -import pa from 'react-intl/locale-data/pa'; -import pl from 'react-intl/locale-data/pl'; -import pt from 'react-intl/locale-data/pt'; -import ro from 'react-intl/locale-data/ro'; -import ru from 'react-intl/locale-data/ru'; -import sk from 'react-intl/locale-data/sk'; -import sr from 'react-intl/locale-data/sr'; -import sv from 'react-intl/locale-data/sv'; -import ta from 'react-intl/locale-data/ta'; -import te from 'react-intl/locale-data/te'; -import tr from 'react-intl/locale-data/tr'; -import uk from 'react-intl/locale-data/uk'; -import uz from 'react-intl/locale-data/uz'; -import vi from 'react-intl/locale-data/vi'; -import zh from 'react-intl/locale-data/zh'; - -[ - ar, - bg, - ca, - cs, - da, - de, - el, - en, - es, - fa, - fi, - fr, - gl, - hi, - hr, - hu, - id, - it, - ja, - ko, - lt, - ml, - nb, - nl, - pa, - pl, - pt, - ro, - ru, - sk, - sr, - sv, - ta, - te, - tr, - uk, - uz, - vi, - zh, -].forEach(locale => addLocaleData(locale)); diff --git a/vendor/intl/LICENSE.txt b/vendor/intl/LICENSE.txt deleted file mode 100644 index cc5593be61e..00000000000 --- a/vendor/intl/LICENSE.txt +++ /dev/null @@ -1,66 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2013 Andy Earnshaw - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. - - ------------------------------------------------------------------------------- -Contents of the `locale-data` directory are a modified form of the Unicode CLDR -data found at http://www.unicode.org/cldr/data/. It comes with the following -license. - -COPYRIGHT AND PERMISSION NOTICE - -Copyright (c) 1991-2013 Unicode, Inc. All rights reserved. Distributed under -the Terms of Use in http://www.unicode.org/copyright.html. - -Permission is hereby granted, free of charge, to any person obtaining a copy of -the Unicode data files and any associated documentation (the "Data Files") or -Unicode software and any associated documentation (the "Software") to deal in -the Data Files or Software without restriction, including without limitation -the rights to use, copy, modify, merge, publish, distribute, and/or sell copies -of the Data Files or Software, and to permit persons to whom the Data Files or -Software are furnished to do so, provided that (a) the above copyright -notice(s) and this permission notice appear with all copies of the Data Files -or Software, (b) both the above copyright notice(s) and this permission notice -appear in associated documentation, and (c) there is clear notice in each -modified Data File or in the Software as well as in the documentation -associated with the Data File(s) or Software that the data or software has been -modified. - -THE DATA FILES AND SOFTWARE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD -PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS INCLUDED IN -THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL -DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, -WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING -OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THE DATA FILES OR -SOFTWARE. - -Except as contained in this notice, the name of a copyright holder shall not be -used in advertising or otherwise to promote the sale, use or other dealings in -these Data Files or Software without prior written authorization of the -copyright holder. - -Unicode and the Unicode logo are trademarks of Unicode, Inc. in the United -States and other countries. All third party trademarks referenced herein are -the property of their respective owners. - diff --git a/vendor/intl/intl.js b/vendor/intl/intl.js deleted file mode 100644 index d041f4224ec..00000000000 --- a/vendor/intl/intl.js +++ /dev/null @@ -1,5740 +0,0 @@ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : - typeof define === 'function' && define.amd ? define(factory) : - (global.IntlPolyfill = factory()); -}(this, (function () { 'use strict'; - -var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { - return typeof obj; -} : function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; -}; - -var jsx = function () { - var REACT_ELEMENT_TYPE = typeof Symbol === "function" && Symbol.for && Symbol.for("react.element") || 0xeac7; - return function createRawReactElement(type, props, key, children) { - var defaultProps = type && type.defaultProps; - var childrenLength = arguments.length - 3; - - if (!props && childrenLength !== 0) { - props = {}; - } - - if (props && defaultProps) { - for (var propName in defaultProps) { - if (props[propName] === void 0) { - props[propName] = defaultProps[propName]; - } - } - } else if (!props) { - props = defaultProps || {}; - } - - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 3]; - } - - props.children = childArray; - } - - return { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key === undefined ? null : '' + key, - ref: null, - props: props, - _owner: null - }; - }; -}(); - -var asyncIterator = function (iterable) { - if (typeof Symbol === "function") { - if (Symbol.asyncIterator) { - var method = iterable[Symbol.asyncIterator]; - if (method != null) return method.call(iterable); - } - - if (Symbol.iterator) { - return iterable[Symbol.iterator](); - } - } - - throw new TypeError("Object is not async iterable"); -}; - -var asyncGenerator = function () { - function AwaitValue(value) { - this.value = value; - } - - function AsyncGenerator(gen) { - var front, back; - - function send(key, arg) { - return new Promise(function (resolve, reject) { - var request = { - key: key, - arg: arg, - resolve: resolve, - reject: reject, - next: null - }; - - if (back) { - back = back.next = request; - } else { - front = back = request; - resume(key, arg); - } - }); - } - - function resume(key, arg) { - try { - var result = gen[key](arg); - var value = result.value; - - if (value instanceof AwaitValue) { - Promise.resolve(value.value).then(function (arg) { - resume("next", arg); - }, function (arg) { - resume("throw", arg); - }); - } else { - settle(result.done ? "return" : "normal", result.value); - } - } catch (err) { - settle("throw", err); - } - } - - function settle(type, value) { - switch (type) { - case "return": - front.resolve({ - value: value, - done: true - }); - break; - - case "throw": - front.reject(value); - break; - - default: - front.resolve({ - value: value, - done: false - }); - break; - } - - front = front.next; - - if (front) { - resume(front.key, front.arg); - } else { - back = null; - } - } - - this._invoke = send; - - if (typeof gen.return !== "function") { - this.return = undefined; - } - } - - if (typeof Symbol === "function" && Symbol.asyncIterator) { - AsyncGenerator.prototype[Symbol.asyncIterator] = function () { - return this; - }; - } - - AsyncGenerator.prototype.next = function (arg) { - return this._invoke("next", arg); - }; - - AsyncGenerator.prototype.throw = function (arg) { - return this._invoke("throw", arg); - }; - - AsyncGenerator.prototype.return = function (arg) { - return this._invoke("return", arg); - }; - - return { - wrap: function (fn) { - return function () { - return new AsyncGenerator(fn.apply(this, arguments)); - }; - }, - await: function (value) { - return new AwaitValue(value); - } - }; -}(); - -var asyncGeneratorDelegate = function (inner, awaitWrap) { - var iter = {}, - waiting = false; - - function pump(key, value) { - waiting = true; - value = new Promise(function (resolve) { - resolve(inner[key](value)); - }); - return { - done: false, - value: awaitWrap(value) - }; - } - - ; - - if (typeof Symbol === "function" && Symbol.iterator) { - iter[Symbol.iterator] = function () { - return this; - }; - } - - iter.next = function (value) { - if (waiting) { - waiting = false; - return value; - } - - return pump("next", value); - }; - - if (typeof inner.throw === "function") { - iter.throw = function (value) { - if (waiting) { - waiting = false; - throw value; - } - - return pump("throw", value); - }; - } - - if (typeof inner.return === "function") { - iter.return = function (value) { - return pump("return", value); - }; - } - - return iter; -}; - -var asyncToGenerator = function (fn) { - return function () { - var gen = fn.apply(this, arguments); - return new Promise(function (resolve, reject) { - function step(key, arg) { - try { - var info = gen[key](arg); - var value = info.value; - } catch (error) { - reject(error); - return; - } - - if (info.done) { - resolve(value); - } else { - return Promise.resolve(value).then(function (value) { - step("next", value); - }, function (err) { - step("throw", err); - }); - } - } - - return step("next"); - }); - }; -}; - -var classCallCheck = function (instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } -}; - -var createClass = function () { - function defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - return function (Constructor, protoProps, staticProps) { - if (protoProps) defineProperties(Constructor.prototype, protoProps); - if (staticProps) defineProperties(Constructor, staticProps); - return Constructor; - }; -}(); - -var defineEnumerableProperties = function (obj, descs) { - for (var key in descs) { - var desc = descs[key]; - desc.configurable = desc.enumerable = true; - if ("value" in desc) desc.writable = true; - Object.defineProperty(obj, key, desc); - } - - return obj; -}; - -var defaults = function (obj, defaults) { - var keys = Object.getOwnPropertyNames(defaults); - - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var value = Object.getOwnPropertyDescriptor(defaults, key); - - if (value && value.configurable && obj[key] === undefined) { - Object.defineProperty(obj, key, value); - } - } - - return obj; -}; - -var defineProperty$1 = function (obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -}; - -var _extends = Object.assign || function (target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i]; - - for (var key in source) { - if (Object.prototype.hasOwnProperty.call(source, key)) { - target[key] = source[key]; - } - } - } - - return target; -}; - -var get = function get(object, property, receiver) { - if (object === null) object = Function.prototype; - var desc = Object.getOwnPropertyDescriptor(object, property); - - if (desc === undefined) { - var parent = Object.getPrototypeOf(object); - - if (parent === null) { - return undefined; - } else { - return get(parent, property, receiver); - } - } else if ("value" in desc) { - return desc.value; - } else { - var getter = desc.get; - - if (getter === undefined) { - return undefined; - } - - return getter.call(receiver); - } -}; - -var inherits = function (subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - enumerable: false, - writable: true, - configurable: true - } - }); - if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; -}; - -var _instanceof = function (left, right) { - if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) { - return right[Symbol.hasInstance](left); - } else { - return left instanceof right; - } -}; - -var interopRequireDefault = function (obj) { - return obj && obj.__esModule ? obj : { - default: obj - }; -}; - -var interopRequireWildcard = function (obj) { - if (obj && obj.__esModule) { - return obj; - } else { - var newObj = {}; - - if (obj != null) { - for (var key in obj) { - if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; - } - } - - newObj.default = obj; - return newObj; - } -}; - -var newArrowCheck = function (innerThis, boundThis) { - if (innerThis !== boundThis) { - throw new TypeError("Cannot instantiate an arrow function"); - } -}; - -var objectDestructuringEmpty = function (obj) { - if (obj == null) throw new TypeError("Cannot destructure undefined"); -}; - -var objectWithoutProperties = function (obj, keys) { - var target = {}; - - for (var i in obj) { - if (keys.indexOf(i) >= 0) continue; - if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; - target[i] = obj[i]; - } - - return target; -}; - -var possibleConstructorReturn = function (self, call) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return call && (typeof call === "object" || typeof call === "function") ? call : self; -}; - -var selfGlobal = typeof global === "undefined" ? self : global; - -var set = function set(object, property, value, receiver) { - var desc = Object.getOwnPropertyDescriptor(object, property); - - if (desc === undefined) { - var parent = Object.getPrototypeOf(object); - - if (parent !== null) { - set(parent, property, value, receiver); - } - } else if ("value" in desc && desc.writable) { - desc.value = value; - } else { - var setter = desc.set; - - if (setter !== undefined) { - setter.call(receiver, value); - } - } - - return value; -}; - -var slicedToArray = function () { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = undefined; - - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - - return _arr; - } - - return function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); - -var slicedToArrayLoose = function (arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - var _arr = []; - - for (var _iterator = arr[Symbol.iterator](), _step; !(_step = _iterator.next()).done;) { - _arr.push(_step.value); - - if (i && _arr.length === i) break; - } - - return _arr; - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } -}; - -var taggedTemplateLiteral = function (strings, raw) { - return Object.freeze(Object.defineProperties(strings, { - raw: { - value: Object.freeze(raw) - } - })); -}; - -var taggedTemplateLiteralLoose = function (strings, raw) { - strings.raw = raw; - return strings; -}; - -var temporalRef = function (val, name, undef) { - if (val === undef) { - throw new ReferenceError(name + " is not defined - temporal dead zone"); - } else { - return val; - } -}; - -var temporalUndefined = {}; - -var toArray = function (arr) { - return Array.isArray(arr) ? arr : Array.from(arr); -}; - -var toConsumableArray = function (arr) { - if (Array.isArray(arr)) { - for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) arr2[i] = arr[i]; - - return arr2; - } else { - return Array.from(arr); - } -}; - - - -var babelHelpers$1 = Object.freeze({ - jsx: jsx, - asyncIterator: asyncIterator, - asyncGenerator: asyncGenerator, - asyncGeneratorDelegate: asyncGeneratorDelegate, - asyncToGenerator: asyncToGenerator, - classCallCheck: classCallCheck, - createClass: createClass, - defineEnumerableProperties: defineEnumerableProperties, - defaults: defaults, - defineProperty: defineProperty$1, - get: get, - inherits: inherits, - interopRequireDefault: interopRequireDefault, - interopRequireWildcard: interopRequireWildcard, - newArrowCheck: newArrowCheck, - objectDestructuringEmpty: objectDestructuringEmpty, - objectWithoutProperties: objectWithoutProperties, - possibleConstructorReturn: possibleConstructorReturn, - selfGlobal: selfGlobal, - set: set, - slicedToArray: slicedToArray, - slicedToArrayLoose: slicedToArrayLoose, - taggedTemplateLiteral: taggedTemplateLiteral, - taggedTemplateLiteralLoose: taggedTemplateLiteralLoose, - temporalRef: temporalRef, - temporalUndefined: temporalUndefined, - toArray: toArray, - toConsumableArray: toConsumableArray, - typeof: _typeof, - extends: _extends, - instanceof: _instanceof -}); - -var realDefineProp = function () { - var sentinel = function sentinel() {}; - try { - Object.defineProperty(sentinel, 'a', { - get: function get() { - return 1; - } - }); - Object.defineProperty(sentinel, 'prototype', { writable: false }); - return sentinel.a === 1 && sentinel.prototype instanceof Object; - } catch (e) { - return false; - } -}(); - -// Need a workaround for getters in ES3 -var es3 = !realDefineProp && !Object.prototype.__defineGetter__; - -// We use this a lot (and need it for proto-less objects) -var hop = Object.prototype.hasOwnProperty; - -// Naive defineProperty for compatibility -var defineProperty = realDefineProp ? Object.defineProperty : function (obj, name, desc) { - if ('get' in desc && obj.__defineGetter__) obj.__defineGetter__(name, desc.get);else if (!hop.call(obj, name) || 'value' in desc) obj[name] = desc.value; -}; - -// Array.prototype.indexOf, as good as we need it to be -var arrIndexOf = Array.prototype.indexOf || function (search) { - /*jshint validthis:true */ - var t = this; - if (!t.length) return -1; - - for (var i = arguments[1] || 0, max = t.length; i < max; i++) { - if (t[i] === search) return i; - } - - return -1; -}; - -// Create an object with the specified prototype (2nd arg required for Record) -var objCreate = Object.create || function (proto, props) { - var obj = void 0; - - function F() {} - F.prototype = proto; - obj = new F(); - - for (var k in props) { - if (hop.call(props, k)) defineProperty(obj, k, props[k]); - } - - return obj; -}; - -// Snapshot some (hopefully still) native built-ins -var arrSlice = Array.prototype.slice; -var arrConcat = Array.prototype.concat; -var arrPush = Array.prototype.push; -var arrJoin = Array.prototype.join; -var arrShift = Array.prototype.shift; - -// Naive Function.prototype.bind for compatibility -var fnBind = Function.prototype.bind || function (thisObj) { - var fn = this, - args = arrSlice.call(arguments, 1); - - // All our (presently) bound functions have either 1 or 0 arguments. By returning - // different function signatures, we can pass some tests in ES3 environments - if (fn.length === 1) { - return function () { - return fn.apply(thisObj, arrConcat.call(args, arrSlice.call(arguments))); - }; - } - return function () { - return fn.apply(thisObj, arrConcat.call(args, arrSlice.call(arguments))); - }; -}; - -// Object housing internal properties for constructors -var internals = objCreate(null); - -// Keep internal properties internal -var secret = Math.random(); - -// Helper functions -// ================ - -/** - * A function to deal with the inaccuracy of calculating log10 in pre-ES6 - * JavaScript environments. Math.log(num) / Math.LN10 was responsible for - * causing issue #62. - */ -function log10Floor(n) { - // ES6 provides the more accurate Math.log10 - if (typeof Math.log10 === 'function') return Math.floor(Math.log10(n)); - - var x = Math.round(Math.log(n) * Math.LOG10E); - return x - (Number('1e' + x) > n); -} - -/** - * A map that doesn't contain Object in its prototype chain - */ -function Record(obj) { - // Copy only own properties over unless this object is already a Record instance - for (var k in obj) { - if (obj instanceof Record || hop.call(obj, k)) defineProperty(this, k, { value: obj[k], enumerable: true, writable: true, configurable: true }); - } -} -Record.prototype = objCreate(null); - -/** - * An ordered list - */ -function List() { - defineProperty(this, 'length', { writable: true, value: 0 }); - - if (arguments.length) arrPush.apply(this, arrSlice.call(arguments)); -} -List.prototype = objCreate(null); - -/** - * Constructs a regular expression to restore tainted RegExp properties - */ -function createRegExpRestore() { - if (internals.disableRegExpRestore) { - return function () {/* no-op */}; - } - - var regExpCache = { - lastMatch: RegExp.lastMatch || '', - leftContext: RegExp.leftContext, - multiline: RegExp.multiline, - input: RegExp.input - }, - has = false; - - // Create a snapshot of all the 'captured' properties - for (var i = 1; i <= 9; i++) { - has = (regExpCache['$' + i] = RegExp['$' + i]) || has; - }return function () { - // Now we've snapshotted some properties, escape the lastMatch string - var esc = /[.?*+^$[\]\\(){}|-]/g, - lastMatch = regExpCache.lastMatch.replace(esc, '\\$&'), - exprStr = ''; - - // If any of the captured strings were non-empty, iterate over them all - if (has) { - for (var _i = 1; _i <= 9; _i++) { - var m = regExpCache['$' + _i]; - - // If it's empty, add an empty capturing group - if (!m) { - exprStr += '('; - lastMatch = ')' + lastMatch; - } - // Else find the string in lm and escape & wrap it to capture it - else { - m = m.replace(esc, '\\$&'); - exprStr += lastMatch.substring(0, lastMatch.indexOf(m)) + '('; - lastMatch = m + ')' + lastMatch.substring(lastMatch.indexOf(m) + m.length); - } - } - } - - exprStr += lastMatch; - - // Shorten the regex by replacing each part of the expression with a match - // for a string of that exact length. This is safe for the type of - // expressions generated above, because the expression matches the whole - // match string, so we know each group and each segment between capturing - // groups can be matched by its length alone. - // - // The purpose of the regex is to match sequences of characters other - // than unescaped parentheses. This is a more complicated requirement - // than it seems at first glance, because it's necessary to match a - // parenthesis which appears immediately after a backslash ("\("), but - // not a parenthesis which appears immediately after an escaped backslash - // ("\\("). We can't simply match [^\\]\\(, because the previous - // backslash could itself have a backslash preceding (and escaping) it. - // - // Any attempts to simplify this regex are encouraged! A replacement - // regex should match the strings "a\\\(\\\)\\" and "a\\\)\\\(" in the - // test string "a\\\(\\\)\\(a\\\)\\\()". - exprStr = exprStr.replace(/((^|[^\\])((\\\\)*\\[()])+|[^()])+/g, function (match) { - return '[\\s\\S]{' + match.replace(/\\(.)/g, '$1').length + '}'; - }); - - // Create the regular expression that will reconstruct the RegExp properties - var expr = new RegExp(exprStr, regExpCache.multiline ? 'gm' : 'g'); - - // Set the lastIndex of the generated expression to ensure that the match - // is found in the correct index. - expr.lastIndex = regExpCache.leftContext.length; - - expr.exec(regExpCache.input); - }; -} - -/** - * Mimics ES5's abstract ToObject() function - */ -function toObject(arg) { - if (arg === null) throw new TypeError('Cannot convert null or undefined to object'); - - if ((typeof arg === 'undefined' ? 'undefined' : babelHelpers$1['typeof'](arg)) === 'object') return arg; - return Object(arg); -} - -function toNumber(arg) { - if (typeof arg === 'number') return arg; - return Number(arg); -} - -function toInteger(arg) { - var number = toNumber(arg); - if (isNaN(number)) return 0; - if (number === +0 || number === -0 || number === +Infinity || number === -Infinity) return number; - if (number < 0) return Math.floor(Math.abs(number)) * -1; - return Math.floor(Math.abs(number)); -} - -function toLength(arg) { - var len = toInteger(arg); - if (len <= 0) return 0; - if (len === Infinity) return Math.pow(2, 53) - 1; - return Math.min(len, Math.pow(2, 53) - 1); -} - -/** - * Returns "internal" properties for an object - */ -function getInternalProperties(obj) { - if (hop.call(obj, '__getInternalProperties')) return obj.__getInternalProperties(secret); - - return objCreate(null); -} - -/** -* Defines regular expressions for various operations related to the BCP 47 syntax, -* as defined at http://tools.ietf.org/html/bcp47#section-2.1 -*/ - -// extlang = 3ALPHA ; selected ISO 639 codes -// *2("-" 3ALPHA) ; permanently reserved -var extlang = '[a-z]{3}(?:-[a-z]{3}){0,2}'; - -// language = 2*3ALPHA ; shortest ISO 639 code -// ["-" extlang] ; sometimes followed by -// ; extended language subtags -// / 4ALPHA ; or reserved for future use -// / 5*8ALPHA ; or registered language subtag -var language = '(?:[a-z]{2,3}(?:-' + extlang + ')?|[a-z]{4}|[a-z]{5,8})'; - -// script = 4ALPHA ; ISO 15924 code -var script = '[a-z]{4}'; - -// region = 2ALPHA ; ISO 3166-1 code -// / 3DIGIT ; UN M.49 code -var region = '(?:[a-z]{2}|\\d{3})'; - -// variant = 5*8alphanum ; registered variants -// / (DIGIT 3alphanum) -var variant = '(?:[a-z0-9]{5,8}|\\d[a-z0-9]{3})'; - -// ; Single alphanumerics -// ; "x" reserved for private use -// singleton = DIGIT ; 0 - 9 -// / %x41-57 ; A - W -// / %x59-5A ; Y - Z -// / %x61-77 ; a - w -// / %x79-7A ; y - z -var singleton = '[0-9a-wy-z]'; - -// extension = singleton 1*("-" (2*8alphanum)) -var extension = singleton + '(?:-[a-z0-9]{2,8})+'; - -// privateuse = "x" 1*("-" (1*8alphanum)) -var privateuse = 'x(?:-[a-z0-9]{1,8})+'; - -// irregular = "en-GB-oed" ; irregular tags do not match -// / "i-ami" ; the 'langtag' production and -// / "i-bnn" ; would not otherwise be -// / "i-default" ; considered 'well-formed' -// / "i-enochian" ; These tags are all valid, -// / "i-hak" ; but most are deprecated -// / "i-klingon" ; in favor of more modern -// / "i-lux" ; subtags or subtag -// / "i-mingo" ; combination -// / "i-navajo" -// / "i-pwn" -// / "i-tao" -// / "i-tay" -// / "i-tsu" -// / "sgn-BE-FR" -// / "sgn-BE-NL" -// / "sgn-CH-DE" -var irregular = '(?:en-GB-oed' + '|i-(?:ami|bnn|default|enochian|hak|klingon|lux|mingo|navajo|pwn|tao|tay|tsu)' + '|sgn-(?:BE-FR|BE-NL|CH-DE))'; - -// regular = "art-lojban" ; these tags match the 'langtag' -// / "cel-gaulish" ; production, but their subtags -// / "no-bok" ; are not extended language -// / "no-nyn" ; or variant subtags: their meaning -// / "zh-guoyu" ; is defined by their registration -// / "zh-hakka" ; and all of these are deprecated -// / "zh-min" ; in favor of a more modern -// / "zh-min-nan" ; subtag or sequence of subtags -// / "zh-xiang" -var regular = '(?:art-lojban|cel-gaulish|no-bok|no-nyn' + '|zh-(?:guoyu|hakka|min|min-nan|xiang))'; - -// grandfathered = irregular ; non-redundant tags registered -// / regular ; during the RFC 3066 era -var grandfathered = '(?:' + irregular + '|' + regular + ')'; - -// langtag = language -// ["-" script] -// ["-" region] -// *("-" variant) -// *("-" extension) -// ["-" privateuse] -var langtag = language + '(?:-' + script + ')?(?:-' + region + ')?(?:-' + variant + ')*(?:-' + extension + ')*(?:-' + privateuse + ')?'; - -// Language-Tag = langtag ; normal language tags -// / privateuse ; private use tag -// / grandfathered ; grandfathered tags -var expBCP47Syntax = RegExp('^(?:' + langtag + '|' + privateuse + '|' + grandfathered + ')$', 'i'); - -// Match duplicate variants in a language tag -var expVariantDupes = RegExp('^(?!x).*?-(' + variant + ')-(?:\\w{4,8}-(?!x-))*\\1\\b', 'i'); - -// Match duplicate singletons in a language tag (except in private use) -var expSingletonDupes = RegExp('^(?!x).*?-(' + singleton + ')-(?:\\w+-(?!x-))*\\1\\b', 'i'); - -// Match all extension sequences -var expExtSequences = RegExp('-' + extension, 'ig'); - -// Sect 6.2 Language Tags -// ====================== - -// Default locale is the first-added locale data for us -var defaultLocale = void 0; -function setDefaultLocale(locale) { - defaultLocale = locale; -} - -// IANA Subtag Registry redundant tag and subtag maps -var redundantTags = { - tags: { - "art-lojban": "jbo", - "i-ami": "ami", - "i-bnn": "bnn", - "i-hak": "hak", - "i-klingon": "tlh", - "i-lux": "lb", - "i-navajo": "nv", - "i-pwn": "pwn", - "i-tao": "tao", - "i-tay": "tay", - "i-tsu": "tsu", - "no-bok": "nb", - "no-nyn": "nn", - "sgn-BE-FR": "sfb", - "sgn-BE-NL": "vgt", - "sgn-CH-DE": "sgg", - "zh-guoyu": "cmn", - "zh-hakka": "hak", - "zh-min-nan": "nan", - "zh-xiang": "hsn", - "sgn-BR": "bzs", - "sgn-CO": "csn", - "sgn-DE": "gsg", - "sgn-DK": "dsl", - "sgn-ES": "ssp", - "sgn-FR": "fsl", - "sgn-GB": "bfi", - "sgn-GR": "gss", - "sgn-IE": "isg", - "sgn-IT": "ise", - "sgn-JP": "jsl", - "sgn-MX": "mfs", - "sgn-NI": "ncs", - "sgn-NL": "dse", - "sgn-NO": "nsl", - "sgn-PT": "psr", - "sgn-SE": "swl", - "sgn-US": "ase", - "sgn-ZA": "sfs", - "zh-cmn": "cmn", - "zh-cmn-Hans": "cmn-Hans", - "zh-cmn-Hant": "cmn-Hant", - "zh-gan": "gan", - "zh-wuu": "wuu", - "zh-yue": "yue" - }, - subtags: { - BU: "MM", - DD: "DE", - FX: "FR", - TP: "TL", - YD: "YE", - ZR: "CD", - heploc: "alalc97", - 'in': "id", - iw: "he", - ji: "yi", - jw: "jv", - mo: "ro", - ayx: "nun", - bjd: "drl", - ccq: "rki", - cjr: "mom", - cka: "cmr", - cmk: "xch", - drh: "khk", - drw: "prs", - gav: "dev", - hrr: "jal", - ibi: "opa", - kgh: "kml", - lcq: "ppr", - mst: "mry", - myt: "mry", - sca: "hle", - tie: "ras", - tkk: "twm", - tlw: "weo", - tnf: "prs", - ybd: "rki", - yma: "lrr" - }, - extLang: { - aao: ["aao", "ar"], - abh: ["abh", "ar"], - abv: ["abv", "ar"], - acm: ["acm", "ar"], - acq: ["acq", "ar"], - acw: ["acw", "ar"], - acx: ["acx", "ar"], - acy: ["acy", "ar"], - adf: ["adf", "ar"], - ads: ["ads", "sgn"], - aeb: ["aeb", "ar"], - aec: ["aec", "ar"], - aed: ["aed", "sgn"], - aen: ["aen", "sgn"], - afb: ["afb", "ar"], - afg: ["afg", "sgn"], - ajp: ["ajp", "ar"], - apc: ["apc", "ar"], - apd: ["apd", "ar"], - arb: ["arb", "ar"], - arq: ["arq", "ar"], - ars: ["ars", "ar"], - ary: ["ary", "ar"], - arz: ["arz", "ar"], - ase: ["ase", "sgn"], - asf: ["asf", "sgn"], - asp: ["asp", "sgn"], - asq: ["asq", "sgn"], - asw: ["asw", "sgn"], - auz: ["auz", "ar"], - avl: ["avl", "ar"], - ayh: ["ayh", "ar"], - ayl: ["ayl", "ar"], - ayn: ["ayn", "ar"], - ayp: ["ayp", "ar"], - bbz: ["bbz", "ar"], - bfi: ["bfi", "sgn"], - bfk: ["bfk", "sgn"], - bjn: ["bjn", "ms"], - bog: ["bog", "sgn"], - bqn: ["bqn", "sgn"], - bqy: ["bqy", "sgn"], - btj: ["btj", "ms"], - bve: ["bve", "ms"], - bvl: ["bvl", "sgn"], - bvu: ["bvu", "ms"], - bzs: ["bzs", "sgn"], - cdo: ["cdo", "zh"], - cds: ["cds", "sgn"], - cjy: ["cjy", "zh"], - cmn: ["cmn", "zh"], - coa: ["coa", "ms"], - cpx: ["cpx", "zh"], - csc: ["csc", "sgn"], - csd: ["csd", "sgn"], - cse: ["cse", "sgn"], - csf: ["csf", "sgn"], - csg: ["csg", "sgn"], - csl: ["csl", "sgn"], - csn: ["csn", "sgn"], - csq: ["csq", "sgn"], - csr: ["csr", "sgn"], - czh: ["czh", "zh"], - czo: ["czo", "zh"], - doq: ["doq", "sgn"], - dse: ["dse", "sgn"], - dsl: ["dsl", "sgn"], - dup: ["dup", "ms"], - ecs: ["ecs", "sgn"], - esl: ["esl", "sgn"], - esn: ["esn", "sgn"], - eso: ["eso", "sgn"], - eth: ["eth", "sgn"], - fcs: ["fcs", "sgn"], - fse: ["fse", "sgn"], - fsl: ["fsl", "sgn"], - fss: ["fss", "sgn"], - gan: ["gan", "zh"], - gds: ["gds", "sgn"], - gom: ["gom", "kok"], - gse: ["gse", "sgn"], - gsg: ["gsg", "sgn"], - gsm: ["gsm", "sgn"], - gss: ["gss", "sgn"], - gus: ["gus", "sgn"], - hab: ["hab", "sgn"], - haf: ["haf", "sgn"], - hak: ["hak", "zh"], - hds: ["hds", "sgn"], - hji: ["hji", "ms"], - hks: ["hks", "sgn"], - hos: ["hos", "sgn"], - hps: ["hps", "sgn"], - hsh: ["hsh", "sgn"], - hsl: ["hsl", "sgn"], - hsn: ["hsn", "zh"], - icl: ["icl", "sgn"], - ils: ["ils", "sgn"], - inl: ["inl", "sgn"], - ins: ["ins", "sgn"], - ise: ["ise", "sgn"], - isg: ["isg", "sgn"], - isr: ["isr", "sgn"], - jak: ["jak", "ms"], - jax: ["jax", "ms"], - jcs: ["jcs", "sgn"], - jhs: ["jhs", "sgn"], - jls: ["jls", "sgn"], - jos: ["jos", "sgn"], - jsl: ["jsl", "sgn"], - jus: ["jus", "sgn"], - kgi: ["kgi", "sgn"], - knn: ["knn", "kok"], - kvb: ["kvb", "ms"], - kvk: ["kvk", "sgn"], - kvr: ["kvr", "ms"], - kxd: ["kxd", "ms"], - lbs: ["lbs", "sgn"], - lce: ["lce", "ms"], - lcf: ["lcf", "ms"], - liw: ["liw", "ms"], - lls: ["lls", "sgn"], - lsg: ["lsg", "sgn"], - lsl: ["lsl", "sgn"], - lso: ["lso", "sgn"], - lsp: ["lsp", "sgn"], - lst: ["lst", "sgn"], - lsy: ["lsy", "sgn"], - ltg: ["ltg", "lv"], - lvs: ["lvs", "lv"], - lzh: ["lzh", "zh"], - max: ["max", "ms"], - mdl: ["mdl", "sgn"], - meo: ["meo", "ms"], - mfa: ["mfa", "ms"], - mfb: ["mfb", "ms"], - mfs: ["mfs", "sgn"], - min: ["min", "ms"], - mnp: ["mnp", "zh"], - mqg: ["mqg", "ms"], - mre: ["mre", "sgn"], - msd: ["msd", "sgn"], - msi: ["msi", "ms"], - msr: ["msr", "sgn"], - mui: ["mui", "ms"], - mzc: ["mzc", "sgn"], - mzg: ["mzg", "sgn"], - mzy: ["mzy", "sgn"], - nan: ["nan", "zh"], - nbs: ["nbs", "sgn"], - ncs: ["ncs", "sgn"], - nsi: ["nsi", "sgn"], - nsl: ["nsl", "sgn"], - nsp: ["nsp", "sgn"], - nsr: ["nsr", "sgn"], - nzs: ["nzs", "sgn"], - okl: ["okl", "sgn"], - orn: ["orn", "ms"], - ors: ["ors", "ms"], - pel: ["pel", "ms"], - pga: ["pga", "ar"], - pks: ["pks", "sgn"], - prl: ["prl", "sgn"], - prz: ["prz", "sgn"], - psc: ["psc", "sgn"], - psd: ["psd", "sgn"], - pse: ["pse", "ms"], - psg: ["psg", "sgn"], - psl: ["psl", "sgn"], - pso: ["pso", "sgn"], - psp: ["psp", "sgn"], - psr: ["psr", "sgn"], - pys: ["pys", "sgn"], - rms: ["rms", "sgn"], - rsi: ["rsi", "sgn"], - rsl: ["rsl", "sgn"], - sdl: ["sdl", "sgn"], - sfb: ["sfb", "sgn"], - sfs: ["sfs", "sgn"], - sgg: ["sgg", "sgn"], - sgx: ["sgx", "sgn"], - shu: ["shu", "ar"], - slf: ["slf", "sgn"], - sls: ["sls", "sgn"], - sqk: ["sqk", "sgn"], - sqs: ["sqs", "sgn"], - ssh: ["ssh", "ar"], - ssp: ["ssp", "sgn"], - ssr: ["ssr", "sgn"], - svk: ["svk", "sgn"], - swc: ["swc", "sw"], - swh: ["swh", "sw"], - swl: ["swl", "sgn"], - syy: ["syy", "sgn"], - tmw: ["tmw", "ms"], - tse: ["tse", "sgn"], - tsm: ["tsm", "sgn"], - tsq: ["tsq", "sgn"], - tss: ["tss", "sgn"], - tsy: ["tsy", "sgn"], - tza: ["tza", "sgn"], - ugn: ["ugn", "sgn"], - ugy: ["ugy", "sgn"], - ukl: ["ukl", "sgn"], - uks: ["uks", "sgn"], - urk: ["urk", "ms"], - uzn: ["uzn", "uz"], - uzs: ["uzs", "uz"], - vgt: ["vgt", "sgn"], - vkk: ["vkk", "ms"], - vkt: ["vkt", "ms"], - vsi: ["vsi", "sgn"], - vsl: ["vsl", "sgn"], - vsv: ["vsv", "sgn"], - wuu: ["wuu", "zh"], - xki: ["xki", "sgn"], - xml: ["xml", "sgn"], - xmm: ["xmm", "ms"], - xms: ["xms", "sgn"], - yds: ["yds", "sgn"], - ysl: ["ysl", "sgn"], - yue: ["yue", "zh"], - zib: ["zib", "sgn"], - zlm: ["zlm", "ms"], - zmi: ["zmi", "ms"], - zsl: ["zsl", "sgn"], - zsm: ["zsm", "ms"] - } -}; - -/** - * Convert only a-z to uppercase as per section 6.1 of the spec - */ -function toLatinUpperCase(str) { - var i = str.length; - - while (i--) { - var ch = str.charAt(i); - - if (ch >= "a" && ch <= "z") str = str.slice(0, i) + ch.toUpperCase() + str.slice(i + 1); - } - - return str; -} - -/** - * The IsStructurallyValidLanguageTag abstract operation verifies that the locale - * argument (which must be a String value) - * - * - represents a well-formed BCP 47 language tag as specified in RFC 5646 section - * 2.1, or successor, - * - does not include duplicate variant subtags, and - * - does not include duplicate singleton subtags. - * - * The abstract operation returns true if locale can be generated from the ABNF - * grammar in section 2.1 of the RFC, starting with Language-Tag, and does not - * contain duplicate variant or singleton subtags (other than as a private use - * subtag). It returns false otherwise. Terminal value characters in the grammar are - * interpreted as the Unicode equivalents of the ASCII octet values given. - */ -function /* 6.2.2 */IsStructurallyValidLanguageTag(locale) { - // represents a well-formed BCP 47 language tag as specified in RFC 5646 - if (!expBCP47Syntax.test(locale)) return false; - - // does not include duplicate variant subtags, and - if (expVariantDupes.test(locale)) return false; - - // does not include duplicate singleton subtags. - if (expSingletonDupes.test(locale)) return false; - - return true; -} - -/** - * The CanonicalizeLanguageTag abstract operation returns the canonical and case- - * regularized form of the locale argument (which must be a String value that is - * a structurally valid BCP 47 language tag as verified by the - * IsStructurallyValidLanguageTag abstract operation). It takes the steps - * specified in RFC 5646 section 4.5, or successor, to bring the language tag - * into canonical form, and to regularize the case of the subtags, but does not - * take the steps to bring a language tag into “extlang form” and to reorder - * variant subtags. - - * The specifications for extensions to BCP 47 language tags, such as RFC 6067, - * may include canonicalization rules for the extension subtag sequences they - * define that go beyond the canonicalization rules of RFC 5646 section 4.5. - * Implementations are allowed, but not required, to apply these additional rules. - */ -function /* 6.2.3 */CanonicalizeLanguageTag(locale) { - var match = void 0, - parts = void 0; - - // A language tag is in 'canonical form' when the tag is well-formed - // according to the rules in Sections 2.1 and 2.2 - - // Section 2.1 says all subtags use lowercase... - locale = locale.toLowerCase(); - - // ...with 2 exceptions: 'two-letter and four-letter subtags that neither - // appear at the start of the tag nor occur after singletons. Such two-letter - // subtags are all uppercase (as in the tags "en-CA-x-ca" or "sgn-BE-FR") and - // four-letter subtags are titlecase (as in the tag "az-Latn-x-latn"). - parts = locale.split('-'); - for (var i = 1, max = parts.length; i < max; i++) { - // Two-letter subtags are all uppercase - if (parts[i].length === 2) parts[i] = parts[i].toUpperCase(); - - // Four-letter subtags are titlecase - else if (parts[i].length === 4) parts[i] = parts[i].charAt(0).toUpperCase() + parts[i].slice(1); - - // Is it a singleton? - else if (parts[i].length === 1 && parts[i] !== 'x') break; - } - locale = arrJoin.call(parts, '-'); - - // The steps laid out in RFC 5646 section 4.5 are as follows: - - // 1. Extension sequences are ordered into case-insensitive ASCII order - // by singleton subtag. - if ((match = locale.match(expExtSequences)) && match.length > 1) { - // The built-in sort() sorts by ASCII order, so use that - match.sort(); - - // Replace all extensions with the joined, sorted array - locale = locale.replace(RegExp('(?:' + expExtSequences.source + ')+', 'i'), arrJoin.call(match, '')); - } - - // 2. Redundant or grandfathered tags are replaced by their 'Preferred- - // Value', if there is one. - if (hop.call(redundantTags.tags, locale)) locale = redundantTags.tags[locale]; - - // 3. Subtags are replaced by their 'Preferred-Value', if there is one. - // For extlangs, the original primary language subtag is also - // replaced if there is a primary language subtag in the 'Preferred- - // Value'. - parts = locale.split('-'); - - for (var _i = 1, _max = parts.length; _i < _max; _i++) { - if (hop.call(redundantTags.subtags, parts[_i])) parts[_i] = redundantTags.subtags[parts[_i]];else if (hop.call(redundantTags.extLang, parts[_i])) { - parts[_i] = redundantTags.extLang[parts[_i]][0]; - - // For extlang tags, the prefix needs to be removed if it is redundant - if (_i === 1 && redundantTags.extLang[parts[1]][1] === parts[0]) { - parts = arrSlice.call(parts, _i++); - _max -= 1; - } - } - } - - return arrJoin.call(parts, '-'); -} - -/** - * The DefaultLocale abstract operation returns a String value representing the - * structurally valid (6.2.2) and canonicalized (6.2.3) BCP 47 language tag for the - * host environment’s current locale. - */ -function /* 6.2.4 */DefaultLocale() { - return defaultLocale; -} - -// Sect 6.3 Currency Codes -// ======================= - -var expCurrencyCode = /^[A-Z]{3}$/; - -/** - * The IsWellFormedCurrencyCode abstract operation verifies that the currency argument - * (after conversion to a String value) represents a well-formed 3-letter ISO currency - * code. The following steps are taken: - */ -function /* 6.3.1 */IsWellFormedCurrencyCode(currency) { - // 1. Let `c` be ToString(currency) - var c = String(currency); - - // 2. Let `normalized` be the result of mapping c to upper case as described - // in 6.1. - var normalized = toLatinUpperCase(c); - - // 3. If the string length of normalized is not 3, return false. - // 4. If normalized contains any character that is not in the range "A" to "Z" - // (U+0041 to U+005A), return false. - if (expCurrencyCode.test(normalized) === false) return false; - - // 5. Return true - return true; -} - -// Sect 9.2 Abstract Operations -// ============================ - -var expUnicodeExSeq = /-u(?:-[0-9a-z]{2,8})+/gi; // See `extension` below - -function /* 9.2.1 */CanonicalizeLocaleList(locales) { - // The abstract operation CanonicalizeLocaleList takes the following steps: - - // 1. If locales is undefined, then a. Return a new empty List - if (locales === undefined) return new List(); - - // 2. Let seen be a new empty List. - var seen = new List(); - - // 3. If locales is a String value, then - // a. Let locales be a new array created as if by the expression new - // Array(locales) where Array is the standard built-in constructor with - // that name and locales is the value of locales. - locales = typeof locales === 'string' ? [locales] : locales; - - // 4. Let O be ToObject(locales). - var O = toObject(locales); - - // 5. Let lenValue be the result of calling the [[Get]] internal method of - // O with the argument "length". - // 6. Let len be ToUint32(lenValue). - var len = toLength(O.length); - - // 7. Let k be 0. - var k = 0; - - // 8. Repeat, while k < len - while (k < len) { - // a. Let Pk be ToString(k). - var Pk = String(k); - - // b. Let kPresent be the result of calling the [[HasProperty]] internal - // method of O with argument Pk. - var kPresent = Pk in O; - - // c. If kPresent is true, then - if (kPresent) { - // i. Let kValue be the result of calling the [[Get]] internal - // method of O with argument Pk. - var kValue = O[Pk]; - - // ii. If the type of kValue is not String or Object, then throw a - // TypeError exception. - if (kValue === null || typeof kValue !== 'string' && (typeof kValue === "undefined" ? "undefined" : babelHelpers$1["typeof"](kValue)) !== 'object') throw new TypeError('String or Object type expected'); - - // iii. Let tag be ToString(kValue). - var tag = String(kValue); - - // iv. If the result of calling the abstract operation - // IsStructurallyValidLanguageTag (defined in 6.2.2), passing tag as - // the argument, is false, then throw a RangeError exception. - if (!IsStructurallyValidLanguageTag(tag)) throw new RangeError("'" + tag + "' is not a structurally valid language tag"); - - // v. Let tag be the result of calling the abstract operation - // CanonicalizeLanguageTag (defined in 6.2.3), passing tag as the - // argument. - tag = CanonicalizeLanguageTag(tag); - - // vi. If tag is not an element of seen, then append tag as the last - // element of seen. - if (arrIndexOf.call(seen, tag) === -1) arrPush.call(seen, tag); - } - - // d. Increase k by 1. - k++; - } - - // 9. Return seen. - return seen; -} - -/** - * The BestAvailableLocale abstract operation compares the provided argument - * locale, which must be a String value with a structurally valid and - * canonicalized BCP 47 language tag, against the locales in availableLocales and - * returns either the longest non-empty prefix of locale that is an element of - * availableLocales, or undefined if there is no such element. It uses the - * fallback mechanism of RFC 4647, section 3.4. The following steps are taken: - */ -function /* 9.2.2 */BestAvailableLocale(availableLocales, locale) { - // 1. Let candidate be locale - var candidate = locale; - - // 2. Repeat - while (candidate) { - // a. If availableLocales contains an element equal to candidate, then return - // candidate. - if (arrIndexOf.call(availableLocales, candidate) > -1) return candidate; - - // b. Let pos be the character index of the last occurrence of "-" - // (U+002D) within candidate. If that character does not occur, return - // undefined. - var pos = candidate.lastIndexOf('-'); - - if (pos < 0) return; - - // c. If pos ≥ 2 and the character "-" occurs at index pos-2 of candidate, - // then decrease pos by 2. - if (pos >= 2 && candidate.charAt(pos - 2) === '-') pos -= 2; - - // d. Let candidate be the substring of candidate from position 0, inclusive, - // to position pos, exclusive. - candidate = candidate.substring(0, pos); - } -} - -/** - * The LookupMatcher abstract operation compares requestedLocales, which must be - * a List as returned by CanonicalizeLocaleList, against the locales in - * availableLocales and determines the best available language to meet the - * request. The following steps are taken: - */ -function /* 9.2.3 */LookupMatcher(availableLocales, requestedLocales) { - // 1. Let i be 0. - var i = 0; - - // 2. Let len be the number of elements in requestedLocales. - var len = requestedLocales.length; - - // 3. Let availableLocale be undefined. - var availableLocale = void 0; - - var locale = void 0, - noExtensionsLocale = void 0; - - // 4. Repeat while i < len and availableLocale is undefined: - while (i < len && !availableLocale) { - // a. Let locale be the element of requestedLocales at 0-origined list - // position i. - locale = requestedLocales[i]; - - // b. Let noExtensionsLocale be the String value that is locale with all - // Unicode locale extension sequences removed. - noExtensionsLocale = String(locale).replace(expUnicodeExSeq, ''); - - // c. Let availableLocale be the result of calling the - // BestAvailableLocale abstract operation (defined in 9.2.2) with - // arguments availableLocales and noExtensionsLocale. - availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale); - - // d. Increase i by 1. - i++; - } - - // 5. Let result be a new Record. - var result = new Record(); - - // 6. If availableLocale is not undefined, then - if (availableLocale !== undefined) { - // a. Set result.[[locale]] to availableLocale. - result['[[locale]]'] = availableLocale; - - // b. If locale and noExtensionsLocale are not the same String value, then - if (String(locale) !== String(noExtensionsLocale)) { - // i. Let extension be the String value consisting of the first - // substring of locale that is a Unicode locale extension sequence. - var extension = locale.match(expUnicodeExSeq)[0]; - - // ii. Let extensionIndex be the character position of the initial - // "-" of the first Unicode locale extension sequence within locale. - var extensionIndex = locale.indexOf('-u-'); - - // iii. Set result.[[extension]] to extension. - result['[[extension]]'] = extension; - - // iv. Set result.[[extensionIndex]] to extensionIndex. - result['[[extensionIndex]]'] = extensionIndex; - } - } - // 7. Else - else - // a. Set result.[[locale]] to the value returned by the DefaultLocale abstract - // operation (defined in 6.2.4). - result['[[locale]]'] = DefaultLocale(); - - // 8. Return result - return result; -} - -/** - * The BestFitMatcher abstract operation compares requestedLocales, which must be - * a List as returned by CanonicalizeLocaleList, against the locales in - * availableLocales and determines the best available language to meet the - * request. The algorithm is implementation dependent, but should produce results - * that a typical user of the requested locales would perceive as at least as - * good as those produced by the LookupMatcher abstract operation. Options - * specified through Unicode locale extension sequences must be ignored by the - * algorithm. Information about such subsequences is returned separately. - * The abstract operation returns a record with a [[locale]] field, whose value - * is the language tag of the selected locale, which must be an element of - * availableLocales. If the language tag of the request locale that led to the - * selected locale contained a Unicode locale extension sequence, then the - * returned record also contains an [[extension]] field whose value is the first - * Unicode locale extension sequence, and an [[extensionIndex]] field whose value - * is the index of the first Unicode locale extension sequence within the request - * locale language tag. - */ -function /* 9.2.4 */BestFitMatcher(availableLocales, requestedLocales) { - return LookupMatcher(availableLocales, requestedLocales); -} - -// @spec[tc39/ecma402/master/spec/negotiation.html] -// @clause[sec-unicodeextensionsubtags] -function UnicodeExtensionSubtags(extension) { - // 1. Let size be the number of elements in extension. - var size = extension.length; - // 2. If size = 0, then - if (size === 0) { - // a. Return « ». - return []; - } - // 3. Let extensionSubtags be « ». - var extensionSubtags = []; - // 4. Let attribute be true. - var attribute = true; - // 5. Let q be 3. - var q = 3; - // 6. Let p be q. - var p = q; - // 7. Let t be q. - var t = q; - // 8. Repeat, while q < size - while (q < size) { - // a. Let c be the code unit value of the element at index q in the String extension. - var c = extension.codePointAt(q); - // a. If c is 0x002D (HYPHEN-MINUS), then - if (c === 0x002D) { - // i. If q - p = 2, then - if (q - p === 2) { - // 1. If p - t > 1, then - if (p - t > 1) { - // a. Let type be a String value equal to the substring of extension consisting of the code units at indices t (inclusive) through p - 1 (exclusive). - var type = extension.substring(t, p - 1); - // a. Append type as the last element of extensionSubtags. - extensionSubtags.push(type); - } - // 2. Let key be a String value equal to the substring of extension consisting of the code units at indices p (inclusive) through q (exclusive). - var key = extension.substring(p, q); - // 3. Append key as the last element of extensionSubtags. - extensionSubtags.push(key); - // 4. Let t be q + 1. - t = q + 1; - // 5. Let attribute be false. - attribute = false; - // ii. Else if attribute is true, then - } else if (attribute === true) { - // 1. Let attr be a String value equal to the substring of extension consisting of the code units at indices p (inclusive) through q (exclusive). - var attr = extension.substring(p, q); - // 2. Append attr as the last element of extensionSubtags. - extensionSubtags.push(attr); - // 3. Let t be q + 1. - t = q + 1; - } - // iii. Let p be q + 1. - p = q + 1; - } - // a. Let q be q + 1. - q = q + 1; - } - // 9. If size - p = 2, then - if (size - p === 2) { - // a. If p - t > 1, then - if (p - t > 1) { - // i. Let type be a String value equal to the substring of extension consisting of the code units at indices t (inclusive) through p - 1 (exclusive). - var _type = extension.substring(t, p - 1); - // ii. Append type as the last element of extensionSubtags. - extensionSubtags.push(_type); - } - // a. Let t be p. - t = p; - } - // 10. Let tail be a String value equal to the substring of extension consisting of the code units at indices t (inclusive) through size (exclusive). - var tail = extension.substring(t, size); - // 11. Append tail as the last element of extensionSubtags. - extensionSubtags.push(tail); - // 12. Return extensionSubtags. - return extensionSubtags; -} - -/** - * The ResolveLocale abstract operation compares a BCP 47 language priority list - * requestedLocales against the locales in availableLocales and determines the - * best available language to meet the request. availableLocales and - * requestedLocales must be provided as List values, options as a Record. - */ -function /* 9.2.5 */ResolveLocale(availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) { - if (availableLocales.length === 0) { - throw new ReferenceError('No locale data has been provided for this object yet.'); - } - - // The following steps are taken: - // 1. Let matcher be the value of options.[[localeMatcher]]. - var matcher = options['[[localeMatcher]]']; - - var r = void 0; - - // 2. If matcher is "lookup", then - if (matcher === 'lookup') - // a. Let r be the result of calling the LookupMatcher abstract operation - // (defined in 9.2.3) with arguments availableLocales and - // requestedLocales. - r = LookupMatcher(availableLocales, requestedLocales); - - // 3. Else - else - // a. Let r be the result of calling the BestFitMatcher abstract - // operation (defined in 9.2.4) with arguments availableLocales and - // requestedLocales. - r = BestFitMatcher(availableLocales, requestedLocales); - - // 4. Let foundLocale be the value of r.[[locale]]. - var foundLocale = r['[[locale]]']; - - var extensionSubtags = void 0, - extensionSubtagsLength = void 0; - - // 5. If r has an [[extension]] field, then - if (hop.call(r, '[[extension]]')) { - // a. Let extension be the value of r.[[extension]]. - var extension = r['[[extension]]']; - // b. Let _extensionSubtags_ be - // CreateArrayFromList(UnicodeExtensionSubtags(_extension_)). - extensionSubtags = UnicodeExtensionSubtags(extension); - // c. Let _extensionSubtagsLength_ be Get(_extensionSubtags_, *"length"*) - extensionSubtagsLength = extensionSubtags.length; - } - - // 6. Let result be a new Record. - var result = new Record(); - - // 7. Set result.[[dataLocale]] to foundLocale. - result['[[dataLocale]]'] = foundLocale; - - // 8. Let supportedExtension be "-u". - var supportedExtension = '-u'; - // 9. Let i be 0. - var i = 0; - // 10. Let len be the result of calling the [[Get]] internal method of - // relevantExtensionKeys with argument "length". - var len = relevantExtensionKeys.length; - - // 11 Repeat while i < len: - while (i < len) { - // a. Let key be the result of calling the [[Get]] internal method of - // relevantExtensionKeys with argument ToString(i). - var key = relevantExtensionKeys[i]; - // b. Let foundLocaleData be the result of calling the [[Get]] internal - // method of localeData with the argument foundLocale. - var foundLocaleData = localeData[foundLocale]; - // c. Let keyLocaleData be the result of calling the [[Get]] internal - // method of foundLocaleData with the argument key. - var keyLocaleData = foundLocaleData[key]; - // d. Let value be the result of calling the [[Get]] internal method of - // keyLocaleData with argument "0". - var value = keyLocaleData['0']; - // e. Let supportedExtensionAddition be "". - var supportedExtensionAddition = ''; - // f. Let indexOf be the standard built-in function object defined in - // ES5, 15.4.4.14. - var indexOf = arrIndexOf; - - // g. If extensionSubtags is not undefined, then - if (extensionSubtags !== undefined) { - // i. Let keyPos be the result of calling the [[Call]] internal - // method of indexOf with extensionSubtags as the this value and - // an argument list containing the single item key. - var keyPos = indexOf.call(extensionSubtags, key); - - // ii. If keyPos ≠ -1, then - if (keyPos !== -1) { - // 1. If keyPos + 1 < extensionSubtagsLength and the length of the - // result of calling the [[Get]] internal method of - // extensionSubtags with argument ToString(keyPos +1) is greater - // than 2, then - if (keyPos + 1 < extensionSubtagsLength && extensionSubtags[keyPos + 1].length > 2) { - // a. Let requestedValue be the result of calling the [[Get]] - // internal method of extensionSubtags with argument - // ToString(keyPos + 1). - var requestedValue = extensionSubtags[keyPos + 1]; - // b. Let valuePos be the result of calling the [[Call]] - // internal method of indexOf with keyLocaleData as the - // this value and an argument list containing the single - // item requestedValue. - var valuePos = indexOf.call(keyLocaleData, requestedValue); - - // c. If valuePos ≠ -1, then - if (valuePos !== -1) { - // i. Let value be requestedValue. - value = requestedValue, - // ii. Let supportedExtensionAddition be the - // concatenation of "-", key, "-", and value. - supportedExtensionAddition = '-' + key + '-' + value; - } - } - // 2. Else - else { - // a. Let valuePos be the result of calling the [[Call]] - // internal method of indexOf with keyLocaleData as the this - // value and an argument list containing the single item - // "true". - var _valuePos = indexOf(keyLocaleData, 'true'); - - // b. If valuePos ≠ -1, then - if (_valuePos !== -1) - // i. Let value be "true". - value = 'true'; - } - } - } - // h. If options has a field [[]], then - if (hop.call(options, '[[' + key + ']]')) { - // i. Let optionsValue be the value of options.[[]]. - var optionsValue = options['[[' + key + ']]']; - - // ii. If the result of calling the [[Call]] internal method of indexOf - // with keyLocaleData as the this value and an argument list - // containing the single item optionsValue is not -1, then - if (indexOf.call(keyLocaleData, optionsValue) !== -1) { - // 1. If optionsValue is not equal to value, then - if (optionsValue !== value) { - // a. Let value be optionsValue. - value = optionsValue; - // b. Let supportedExtensionAddition be "". - supportedExtensionAddition = ''; - } - } - } - // i. Set result.[[]] to value. - result['[[' + key + ']]'] = value; - - // j. Append supportedExtensionAddition to supportedExtension. - supportedExtension += supportedExtensionAddition; - - // k. Increase i by 1. - i++; - } - // 12. If the length of supportedExtension is greater than 2, then - if (supportedExtension.length > 2) { - // a. - var privateIndex = foundLocale.indexOf("-x-"); - // b. - if (privateIndex === -1) { - // i. - foundLocale = foundLocale + supportedExtension; - } - // c. - else { - // i. - var preExtension = foundLocale.substring(0, privateIndex); - // ii. - var postExtension = foundLocale.substring(privateIndex); - // iii. - foundLocale = preExtension + supportedExtension + postExtension; - } - // d. asserting - skipping - // e. - foundLocale = CanonicalizeLanguageTag(foundLocale); - } - // 13. Set result.[[locale]] to foundLocale. - result['[[locale]]'] = foundLocale; - - // 14. Return result. - return result; -} - -/** - * The LookupSupportedLocales abstract operation returns the subset of the - * provided BCP 47 language priority list requestedLocales for which - * availableLocales has a matching locale when using the BCP 47 Lookup algorithm. - * Locales appear in the same order in the returned list as in requestedLocales. - * The following steps are taken: - */ -function /* 9.2.6 */LookupSupportedLocales(availableLocales, requestedLocales) { - // 1. Let len be the number of elements in requestedLocales. - var len = requestedLocales.length; - // 2. Let subset be a new empty List. - var subset = new List(); - // 3. Let k be 0. - var k = 0; - - // 4. Repeat while k < len - while (k < len) { - // a. Let locale be the element of requestedLocales at 0-origined list - // position k. - var locale = requestedLocales[k]; - // b. Let noExtensionsLocale be the String value that is locale with all - // Unicode locale extension sequences removed. - var noExtensionsLocale = String(locale).replace(expUnicodeExSeq, ''); - // c. Let availableLocale be the result of calling the - // BestAvailableLocale abstract operation (defined in 9.2.2) with - // arguments availableLocales and noExtensionsLocale. - var availableLocale = BestAvailableLocale(availableLocales, noExtensionsLocale); - - // d. If availableLocale is not undefined, then append locale to the end of - // subset. - if (availableLocale !== undefined) arrPush.call(subset, locale); - - // e. Increment k by 1. - k++; - } - - // 5. Let subsetArray be a new Array object whose elements are the same - // values in the same order as the elements of subset. - var subsetArray = arrSlice.call(subset); - - // 6. Return subsetArray. - return subsetArray; -} - -/** - * The BestFitSupportedLocales abstract operation returns the subset of the - * provided BCP 47 language priority list requestedLocales for which - * availableLocales has a matching locale when using the Best Fit Matcher - * algorithm. Locales appear in the same order in the returned list as in - * requestedLocales. The steps taken are implementation dependent. - */ -function /*9.2.7 */BestFitSupportedLocales(availableLocales, requestedLocales) { - // ###TODO: implement this function as described by the specification### - return LookupSupportedLocales(availableLocales, requestedLocales); -} - -/** - * The SupportedLocales abstract operation returns the subset of the provided BCP - * 47 language priority list requestedLocales for which availableLocales has a - * matching locale. Two algorithms are available to match the locales: the Lookup - * algorithm described in RFC 4647 section 3.4, and an implementation dependent - * best-fit algorithm. Locales appear in the same order in the returned list as - * in requestedLocales. The following steps are taken: - */ -function /*9.2.8 */SupportedLocales(availableLocales, requestedLocales, options) { - var matcher = void 0, - subset = void 0; - - // 1. If options is not undefined, then - if (options !== undefined) { - // a. Let options be ToObject(options). - options = new Record(toObject(options)); - // b. Let matcher be the result of calling the [[Get]] internal method of - // options with argument "localeMatcher". - matcher = options.localeMatcher; - - // c. If matcher is not undefined, then - if (matcher !== undefined) { - // i. Let matcher be ToString(matcher). - matcher = String(matcher); - - // ii. If matcher is not "lookup" or "best fit", then throw a RangeError - // exception. - if (matcher !== 'lookup' && matcher !== 'best fit') throw new RangeError('matcher should be "lookup" or "best fit"'); - } - } - // 2. If matcher is undefined or "best fit", then - if (matcher === undefined || matcher === 'best fit') - // a. Let subset be the result of calling the BestFitSupportedLocales - // abstract operation (defined in 9.2.7) with arguments - // availableLocales and requestedLocales. - subset = BestFitSupportedLocales(availableLocales, requestedLocales); - // 3. Else - else - // a. Let subset be the result of calling the LookupSupportedLocales - // abstract operation (defined in 9.2.6) with arguments - // availableLocales and requestedLocales. - subset = LookupSupportedLocales(availableLocales, requestedLocales); - - // 4. For each named own property name P of subset, - for (var P in subset) { - if (!hop.call(subset, P)) continue; - - // a. Let desc be the result of calling the [[GetOwnProperty]] internal - // method of subset with P. - // b. Set desc.[[Writable]] to false. - // c. Set desc.[[Configurable]] to false. - // d. Call the [[DefineOwnProperty]] internal method of subset with P, desc, - // and true as arguments. - defineProperty(subset, P, { - writable: false, configurable: false, value: subset[P] - }); - } - - // Wrap in try catch for older browsers that don't support setting length of - // array such as FF 22 and below. - try { - // "Freeze" the array so no new elements can be added - defineProperty(subset, 'length', { writable: false }); - } catch (e) {} - - // 5. Return subset - return subset; -} - -/** - * The GetOption abstract operation extracts the value of the property named - * property from the provided options object, converts it to the required type, - * checks whether it is one of a List of allowed values, and fills in a fallback - * value if necessary. - */ -function /*9.2.9 */GetOption(options, property, type, values, fallback) { - // 1. Let value be the result of calling the [[Get]] internal method of - // options with argument property. - var value = options[property]; - - // 2. If value is not undefined, then - if (value !== undefined) { - // a. Assert: type is "boolean" or "string". - // b. If type is "boolean", then let value be ToBoolean(value). - // c. If type is "string", then let value be ToString(value). - value = type === 'boolean' ? Boolean(value) : type === 'string' ? String(value) : value; - - // d. If values is not undefined, then - if (values !== undefined) { - // i. If values does not contain an element equal to value, then throw a - // RangeError exception. - if (arrIndexOf.call(values, value) === -1) throw new RangeError("'" + value + "' is not an allowed value for `" + property + '`'); - } - - // e. Return value. - return value; - } - // Else return fallback. - return fallback; -} - -/** - * The GetNumberOption abstract operation extracts a property value from the - * provided options object, converts it to a Number value, checks whether it is - * in the allowed range, and fills in a fallback value if necessary. - */ -function /* 9.2.10 */GetNumberOption(options, property, minimum, maximum, fallback) { - // 1. Let value be the result of calling the [[Get]] internal method of - // options with argument property. - var value = options[property]; - - // 2. If value is not undefined, then - if (value !== undefined) { - // a. Let value be ToNumber(value). - value = Number(value); - - // b. If value is NaN or less than minimum or greater than maximum, throw a - // RangeError exception. - if (isNaN(value) || value < minimum || value > maximum) throw new RangeError('Value is not a number or outside accepted range'); - - // c. Return floor(value). - return Math.floor(value); - } - // 3. Else return fallback. - return fallback; -} - -// 8 The Intl Object -var Intl$1 = {}; - -// 8.2 Function Properties of the Intl Object - -// 8.2.1 -// @spec[tc39/ecma402/master/spec/intl.html] -// @clause[sec-intl.getcanonicallocales] -function getCanonicalLocales(locales) { - // 1. Let ll be ? CanonicalizeLocaleList(locales). - var ll = CanonicalizeLocaleList(locales); - // 2. Return CreateArrayFromList(ll). - { - var result = []; - - var len = ll.length; - var k = 0; - - while (k < len) { - result[k] = ll[k]; - k++; - } - return result; - } -} - -Object.defineProperty(Intl$1, 'getCanonicalLocales', { - enumerable: false, - configurable: true, - writable: true, - value: getCanonicalLocales -}); - -// 11.1 The Intl.NumberFormat constructor -// ====================================== - -// Currency minor units output from get-4217 grunt task, formatted -var currencyMinorUnits = { - BHD: 3, BYR: 0, XOF: 0, BIF: 0, XAF: 0, CLF: 4, CLP: 0, KMF: 0, DJF: 0, - XPF: 0, GNF: 0, ISK: 0, IQD: 3, JPY: 0, JOD: 3, KRW: 0, KWD: 3, LYD: 3, - OMR: 3, PYG: 0, RWF: 0, TND: 3, UGX: 0, UYI: 0, VUV: 0, VND: 0 -}; - -// Define the NumberFormat constructor internally so it cannot be tainted -function NumberFormatConstructor() { - var locales = arguments[0]; - var options = arguments[1]; - - if (!this || this === Intl$1) { - return new Intl$1.NumberFormat(locales, options); - } - - return InitializeNumberFormat(toObject(this), locales, options); -} - -defineProperty(Intl$1, 'NumberFormat', { - configurable: true, - writable: true, - value: NumberFormatConstructor -}); - -// Must explicitly set prototypes as unwritable -defineProperty(Intl$1.NumberFormat, 'prototype', { - writable: false -}); - -/* - * @spec[tc39/ecma402/master/spec/numberformat.html] - * @clause[sec-setnumberformatdigitoptions] - */ -function /*11.1.1 */SetNumberFormatDigitOptions(intlObj, options, mnfdDefault) { - // 1. Assert: Type(intlObj) is Object and intlObj.[[initializedIntlObject]] is true. - - // 2. Assert: Type(options) is Object. - - // 3. Assert: type(mnfdDefault) is Number. - - // 4. Let mnid be ? GetNumberOption(options, "minimumIntegerDigits,", 1, 21, 1). - var mnid = GetNumberOption(options, 'minimumIntegerDigits', 1, 21, 1); - - // 5. Let mnfd be ? GetNumberOption(options, "minimumFractionDigits", 0, 20, mnfdDefault). - var mnfd = GetNumberOption(options, 'minimumFractionDigits', 0, 20, mnfdDefault); - - // 6. Let mxfd be ? GetNumberOption(options, "maximumFractionDigits", mnfd, 20). - var mxfd = GetNumberOption(options, 'maximumFractionDigits', mnfd, 20); - - // 7. Let mnsd be ? Get(options, "minimumSignificantDigits"). - var mnsd = options.minimumSignificantDigits; - - // 8. Let mxsd be ? Get(options, "maximumSignificantDigits"). - var mxsd = options.maximumSignificantDigits; - - // 9. Set intlObj.[[minimumIntegerDigits]] to mnid. - intlObj['[[minimumIntegerDigits]]'] = mnid; - - // 10. Set intlObj.[[minimumFractionDigits]] to mnfd. - intlObj['[[minimumFractionDigits]]'] = mnfd; - - // 11. Set intlObj.[[maximumFractionDigits]] to mxfd. - intlObj['[[maximumFractionDigits]]'] = mxfd; - - // 12. If mnsd is not undefined or mxsd is not undefined, then - if (mnsd !== undefined || mxsd !== undefined) { - // a. Let mnsd be ? GetNumberOption(options, "minimumSignificantDigits", 1, 21, 1). - mnsd = GetNumberOption(options, "minimumSignificantDigits", 1, 21, 1); - - // b. Let mxsd be ? GetNumberOption(options, "maximumSignificantDigits", mnsd, 21, 21). - mxsd = GetNumberOption(options, "maximumSignificantDigits", mnsd, 21, 21); - - // c. Set intlObj.[[minimumSignificantDigits]] to mnsd. - intlObj['[[minimumSignificantDigits]]'] = mnsd; - - // d. Set intlObj.[[maximumSignificantDigits]] to mxsd. - intlObj['[[maximumSignificantDigits]]'] = mxsd; - } -} - -/** - * The abstract operation InitializeNumberFormat accepts the arguments - * numberFormat (which must be an object), locales, and options. It initializes - * numberFormat as a NumberFormat object. - */ -function /*11.1.2 */InitializeNumberFormat(numberFormat, locales, options) { - // This will be a internal properties object if we're not already initialized - var internal = getInternalProperties(numberFormat); - - // Create an object whose props can be used to restore the values of RegExp props - var regexpRestore = createRegExpRestore(); - - // 1. If numberFormat has an [[initializedIntlObject]] internal property with - // value true, throw a TypeError exception. - if (internal['[[initializedIntlObject]]'] === true) throw new TypeError('`this` object has already been initialized as an Intl object'); - - // Need this to access the `internal` object - defineProperty(numberFormat, '__getInternalProperties', { - value: function value() { - // NOTE: Non-standard, for internal use only - if (arguments[0] === secret) return internal; - } - }); - - // 2. Set the [[initializedIntlObject]] internal property of numberFormat to true. - internal['[[initializedIntlObject]]'] = true; - - // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList - // abstract operation (defined in 9.2.1) with argument locales. - var requestedLocales = CanonicalizeLocaleList(locales); - - // 4. If options is undefined, then - if (options === undefined) - // a. Let options be the result of creating a new object as if by the - // expression new Object() where Object is the standard built-in constructor - // with that name. - options = {}; - - // 5. Else - else - // a. Let options be ToObject(options). - options = toObject(options); - - // 6. Let opt be a new Record. - var opt = new Record(), - - - // 7. Let matcher be the result of calling the GetOption abstract operation - // (defined in 9.2.9) with the arguments options, "localeMatcher", "string", - // a List containing the two String values "lookup" and "best fit", and - // "best fit". - matcher = GetOption(options, 'localeMatcher', 'string', new List('lookup', 'best fit'), 'best fit'); - - // 8. Set opt.[[localeMatcher]] to matcher. - opt['[[localeMatcher]]'] = matcher; - - // 9. Let localeData be the value of the [[localeData]] internal property of - // NumberFormat. - var localeData = internals.NumberFormat['[[localeData]]']; - - // 10. Let r be the result of calling the ResolveLocale abstract operation - // (defined in 9.2.5) with the [[availableLocales]] internal property of - // NumberFormat, requestedLocales, opt, the [[relevantExtensionKeys]] - // internal property of NumberFormat, and localeData. - var r = ResolveLocale(internals.NumberFormat['[[availableLocales]]'], requestedLocales, opt, internals.NumberFormat['[[relevantExtensionKeys]]'], localeData); - - // 11. Set the [[locale]] internal property of numberFormat to the value of - // r.[[locale]]. - internal['[[locale]]'] = r['[[locale]]']; - - // 12. Set the [[numberingSystem]] internal property of numberFormat to the value - // of r.[[nu]]. - internal['[[numberingSystem]]'] = r['[[nu]]']; - - // The specification doesn't tell us to do this, but it's helpful later on - internal['[[dataLocale]]'] = r['[[dataLocale]]']; - - // 13. Let dataLocale be the value of r.[[dataLocale]]. - var dataLocale = r['[[dataLocale]]']; - - // 14. Let s be the result of calling the GetOption abstract operation with the - // arguments options, "style", "string", a List containing the three String - // values "decimal", "percent", and "currency", and "decimal". - var s = GetOption(options, 'style', 'string', new List('decimal', 'percent', 'currency'), 'decimal'); - - // 15. Set the [[style]] internal property of numberFormat to s. - internal['[[style]]'] = s; - - // 16. Let c be the result of calling the GetOption abstract operation with the - // arguments options, "currency", "string", undefined, and undefined. - var c = GetOption(options, 'currency', 'string'); - - // 17. If c is not undefined and the result of calling the - // IsWellFormedCurrencyCode abstract operation (defined in 6.3.1) with - // argument c is false, then throw a RangeError exception. - if (c !== undefined && !IsWellFormedCurrencyCode(c)) throw new RangeError("'" + c + "' is not a valid currency code"); - - // 18. If s is "currency" and c is undefined, throw a TypeError exception. - if (s === 'currency' && c === undefined) throw new TypeError('Currency code is required when style is currency'); - - var cDigits = void 0; - - // 19. If s is "currency", then - if (s === 'currency') { - // a. Let c be the result of converting c to upper case as specified in 6.1. - c = c.toUpperCase(); - - // b. Set the [[currency]] internal property of numberFormat to c. - internal['[[currency]]'] = c; - - // c. Let cDigits be the result of calling the CurrencyDigits abstract - // operation (defined below) with argument c. - cDigits = CurrencyDigits(c); - } - - // 20. Let cd be the result of calling the GetOption abstract operation with the - // arguments options, "currencyDisplay", "string", a List containing the - // three String values "code", "symbol", and "name", and "symbol". - var cd = GetOption(options, 'currencyDisplay', 'string', new List('code', 'symbol', 'name'), 'symbol'); - - // 21. If s is "currency", then set the [[currencyDisplay]] internal property of - // numberFormat to cd. - if (s === 'currency') internal['[[currencyDisplay]]'] = cd; - - // 22. If s is "currency", then - // a. Let mnfdDefault be cDigits. - // 23. Else, - // a. Let mnfdDefault be 0. - var mnfdDefault = s === "currency" ? cDigits : 0; - - // 24. Perform ? SetNumberFormatDigitOptions(numberFormat, options, mnfdDefault). - SetNumberFormatDigitOptions(internal, options, mnfdDefault); - - // 25. If numberFormat.[[maximumFractionDigits]] is undefined, then - if (internal['[[maximumFractionDigits]]'] === undefined) { - // a. If s is "currency", then - if (s === 'currency') { - // i. Set numberFormat.[[maximumFractionDigits]] to max(numberFormat.[[minimumFractionDigits]], cDigits). - internal['[[maximumFractionDigits]]'] = Math.max(internal['[[minimumFractionDigits]]'], cDigits); - // b. Else if s is "percent", then - } else if (s === 'percent') { - // i. Set numberFormat.[[maximumFractionDigits]] to max(numberFormat.[[minimumFractionDigits]], 0). - internal['[[maximumFractionDigits]]'] = Math.max(internal['[[minimumFractionDigits]]'], 0); - // c. Else, - } else { - // i. Set numberFormat.[[maximumFractionDigits]] to max(numberFormat.[[minimumFractionDigits]], 3). - internal['[[maximumFractionDigits]]'] = Math.max(internal['[[minimumFractionDigits]]'], 3); - } - } - - // 26. Let g be the result of calling the GetOption abstract operation with the - // arguments options, "useGrouping", "boolean", undefined, and true. - var g = GetOption(options, 'useGrouping', 'boolean', undefined, true); - - // 27. Set the [[useGrouping]] internal property of numberFormat to g. - internal['[[useGrouping]]'] = g; - - // 28. Let dataLocaleData be the result of calling the [[Get]] internal method of - // localeData with argument dataLocale. - var dataLocaleData = localeData[dataLocale]; - - // 29. Let patterns be the result of calling the [[Get]] internal method of - // dataLocaleData with argument "patterns". - var patterns = dataLocaleData.patterns; - - // 30. Assert: patterns is an object (see 11.2.3) - - // 31. Let stylePatterns be the result of calling the [[Get]] internal method of - // patterns with argument s. - var stylePatterns = patterns[s]; - - // 32. Set the [[positivePattern]] internal property of numberFormat to the - // result of calling the [[Get]] internal method of stylePatterns with the - // argument "positivePattern". - internal['[[positivePattern]]'] = stylePatterns.positivePattern; - - // 33. Set the [[negativePattern]] internal property of numberFormat to the - // result of calling the [[Get]] internal method of stylePatterns with the - // argument "negativePattern". - internal['[[negativePattern]]'] = stylePatterns.negativePattern; - - // 34. Set the [[boundFormat]] internal property of numberFormat to undefined. - internal['[[boundFormat]]'] = undefined; - - // 35. Set the [[initializedNumberFormat]] internal property of numberFormat to - // true. - internal['[[initializedNumberFormat]]'] = true; - - // In ES3, we need to pre-bind the format() function - if (es3) numberFormat.format = GetFormatNumber.call(numberFormat); - - // Restore the RegExp properties - regexpRestore(); - - // 36. Return the newly initialised object - return numberFormat; -} - -function CurrencyDigits(currency) { - // When the CurrencyDigits abstract operation is called with an argument currency - // (which must be an upper case String value), the following steps are taken: - - // 1. If the ISO 4217 currency and funds code list contains currency as an - // alphabetic code, then return the minor unit value corresponding to the - // currency from the list; else return 2. - return currencyMinorUnits[currency] !== undefined ? currencyMinorUnits[currency] : 2; -} - -/* 11.2.3 */internals.NumberFormat = { - '[[availableLocales]]': [], - '[[relevantExtensionKeys]]': ['nu'], - '[[localeData]]': {} -}; - -/** - * When the supportedLocalesOf method of Intl.NumberFormat is called, the - * following steps are taken: - */ -/* 11.2.2 */ -defineProperty(Intl$1.NumberFormat, 'supportedLocalesOf', { - configurable: true, - writable: true, - value: fnBind.call(function (locales) { - // Bound functions only have the `this` value altered if being used as a constructor, - // this lets us imitate a native function that has no constructor - if (!hop.call(this, '[[availableLocales]]')) throw new TypeError('supportedLocalesOf() is not a constructor'); - - // Create an object whose props can be used to restore the values of RegExp props - var regexpRestore = createRegExpRestore(), - - - // 1. If options is not provided, then let options be undefined. - options = arguments[1], - - - // 2. Let availableLocales be the value of the [[availableLocales]] internal - // property of the standard built-in object that is the initial value of - // Intl.NumberFormat. - - availableLocales = this['[[availableLocales]]'], - - - // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList - // abstract operation (defined in 9.2.1) with argument locales. - requestedLocales = CanonicalizeLocaleList(locales); - - // Restore the RegExp properties - regexpRestore(); - - // 4. Return the result of calling the SupportedLocales abstract operation - // (defined in 9.2.8) with arguments availableLocales, requestedLocales, - // and options. - return SupportedLocales(availableLocales, requestedLocales, options); - }, internals.NumberFormat) -}); - -/** - * This named accessor property returns a function that formats a number - * according to the effective locale and the formatting options of this - * NumberFormat object. - */ -/* 11.3.2 */defineProperty(Intl$1.NumberFormat.prototype, 'format', { - configurable: true, - get: GetFormatNumber -}); - -function GetFormatNumber() { - var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this); - - // Satisfy test 11.3_b - if (!internal || !internal['[[initializedNumberFormat]]']) throw new TypeError('`this` value for format() is not an initialized Intl.NumberFormat object.'); - - // The value of the [[Get]] attribute is a function that takes the following - // steps: - - // 1. If the [[boundFormat]] internal property of this NumberFormat object - // is undefined, then: - if (internal['[[boundFormat]]'] === undefined) { - // a. Let F be a Function object, with internal properties set as - // specified for built-in functions in ES5, 15, or successor, and the - // length property set to 1, that takes the argument value and - // performs the following steps: - var F = function F(value) { - // i. If value is not provided, then let value be undefined. - // ii. Let x be ToNumber(value). - // iii. Return the result of calling the FormatNumber abstract - // operation (defined below) with arguments this and x. - return FormatNumber(this, /* x = */Number(value)); - }; - - // b. Let bind be the standard built-in function object defined in ES5, - // 15.3.4.5. - // c. Let bf be the result of calling the [[Call]] internal method of - // bind with F as the this value and an argument list containing - // the single item this. - var bf = fnBind.call(F, this); - - // d. Set the [[boundFormat]] internal property of this NumberFormat - // object to bf. - internal['[[boundFormat]]'] = bf; - } - // Return the value of the [[boundFormat]] internal property of this - // NumberFormat object. - return internal['[[boundFormat]]']; -} - -function formatToParts() { - var value = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this); - if (!internal || !internal['[[initializedNumberFormat]]']) throw new TypeError('`this` value for formatToParts() is not an initialized Intl.NumberFormat object.'); - - var x = Number(value); - return FormatNumberToParts(this, x); -} - -Object.defineProperty(Intl$1.NumberFormat.prototype, 'formatToParts', { - configurable: true, - enumerable: false, - writable: true, - value: formatToParts -}); - -/* - * @spec[tc39/ecma402/master/spec/numberformat.html] - * @clause[sec-formatnumbertoparts] - */ -function FormatNumberToParts(numberFormat, x) { - // 1. Let parts be ? PartitionNumberPattern(numberFormat, x). - var parts = PartitionNumberPattern(numberFormat, x); - // 2. Let result be ArrayCreate(0). - var result = []; - // 3. Let n be 0. - var n = 0; - // 4. For each part in parts, do: - for (var i = 0; parts.length > i; i++) { - var part = parts[i]; - // a. Let O be ObjectCreate(%ObjectPrototype%). - var O = {}; - // a. Perform ? CreateDataPropertyOrThrow(O, "type", part.[[type]]). - O.type = part['[[type]]']; - // a. Perform ? CreateDataPropertyOrThrow(O, "value", part.[[value]]). - O.value = part['[[value]]']; - // a. Perform ? CreateDataPropertyOrThrow(result, ? ToString(n), O). - result[n] = O; - // a. Increment n by 1. - n += 1; - } - // 5. Return result. - return result; -} - -/* - * @spec[tc39/ecma402/master/spec/numberformat.html] - * @clause[sec-formatnumberstring] - */ -function FormatNumberToString(numberFormat, x) { - var internal = getInternalProperties(numberFormat); - var result = void 0; - - // 1. Assert: numberFormat.[[initializedIntlObject]] is true. - - // 2. If the numberFormat.[[minimumSignificantDigits]] and numberFormat.[[maximumSignificantDigits]] are present, then - if (hop.call(internal, '[[minimumSignificantDigits]]') && hop.call(internal, '[[maximumSignificantDigits]]')) { - // a. Let result be ToRawPrecision(x, numberFormat.[[minimumSignificantDigits]], numberFormat.[[maximumSignificantDigits]]). - result = ToRawPrecision(x, internal['[[minimumSignificantDigits]]'], internal['[[maximumSignificantDigits]]']); - } - // 3. Else, - else { - // a. Let result be ToRawFixed(x, numberFormat.[[minimumIntegerDigits]], numberFormat.[[minimumFractionDigits]], numberFormat.[[maximumFractionDigits]]). - result = ToRawFixed(x, internal['[[minimumIntegerDigits]]'], internal['[[minimumFractionDigits]]'], internal['[[maximumFractionDigits]]']); - } - // 4. Return result. - return result; -} - -/* - * @spec[tc39/ecma402/master/spec/numberformat.html] - * @clause[sec-partitionnumberpattern] - */ -function PartitionNumberPattern(numberFormat, x) { - - var internal = getInternalProperties(numberFormat), - locale = internal['[[dataLocale]]'], - nums = internal['[[numberingSystem]]'], - data = internals.NumberFormat['[[localeData]]'][locale], - ild = data.symbols[nums] || data.symbols.latn, - pattern = void 0; - - // 1. If x is not NaN and x < 0, then: - if (!isNaN(x) && x < 0) { - // a. Let x be -x. - x = -x; - // b. Let pattern be the value of numberFormat.[[negativePattern]]. - pattern = internal['[[negativePattern]]']; - } - // 2. Else, - else { - // a. Let pattern be the value of numberFormat.[[positivePattern]]. - pattern = internal['[[positivePattern]]']; - } - // 3. Let result be a new empty List. - var result = new List(); - // 4. Let beginIndex be Call(%StringProto_indexOf%, pattern, "{", 0). - var beginIndex = pattern.indexOf('{', 0); - // 5. Let endIndex be 0. - var endIndex = 0; - // 6. Let nextIndex be 0. - var nextIndex = 0; - // 7. Let length be the number of code units in pattern. - var length = pattern.length; - // 8. Repeat while beginIndex is an integer index into pattern: - while (beginIndex > -1 && beginIndex < length) { - // a. Set endIndex to Call(%StringProto_indexOf%, pattern, "}", beginIndex) - endIndex = pattern.indexOf('}', beginIndex); - // b. If endIndex = -1, throw new Error exception. - if (endIndex === -1) throw new Error(); - // c. If beginIndex is greater than nextIndex, then: - if (beginIndex > nextIndex) { - // i. Let literal be a substring of pattern from position nextIndex, inclusive, to position beginIndex, exclusive. - var literal = pattern.substring(nextIndex, beginIndex); - // ii. Add new part record { [[type]]: "literal", [[value]]: literal } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'literal', '[[value]]': literal }); - } - // d. Let p be the substring of pattern from position beginIndex, exclusive, to position endIndex, exclusive. - var p = pattern.substring(beginIndex + 1, endIndex); - // e. If p is equal "number", then: - if (p === "number") { - // i. If x is NaN, - if (isNaN(x)) { - // 1. Let n be an ILD String value indicating the NaN value. - var n = ild.nan; - // 2. Add new part record { [[type]]: "nan", [[value]]: n } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'nan', '[[value]]': n }); - } - // ii. Else if isFinite(x) is false, - else if (!isFinite(x)) { - // 1. Let n be an ILD String value indicating infinity. - var _n = ild.infinity; - // 2. Add new part record { [[type]]: "infinity", [[value]]: n } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'infinity', '[[value]]': _n }); - } - // iii. Else, - else { - // 1. If numberFormat.[[style]] is "percent", let x be 100 × x. - if (internal['[[style]]'] === 'percent') x *= 100; - - // 2. Let n be FormatNumberToString(numberFormat, x). - var _n2 = FormatNumberToString(numberFormat, x); - - // 3. If the numberFormat.[[numberingSystem]] matches one of the values in the "Numbering System" column of Table 3 below, then - if (numSys[nums]) { - (function () { - // a. Let digits be an array whose 10 String valued elements are the UTF-16 string representations of the 10 digits specified in the "Digits" column of the matching row in Table 2. - var digits = numSys[nums]; - // a. Replace each digit in n with the value of digits[digit]. - _n2 = String(_n2).replace(/\d/g, function (digit) { - return digits[digit]; - }); - })(); - } - // 4. Else use an implementation dependent algorithm to map n to the appropriate representation of n in the given numbering system. - else _n2 = String(_n2); // ###TODO### - - var integer = void 0; - var fraction = void 0; - // 5. Let decimalSepIndex be Call(%StringProto_indexOf%, n, ".", 0). - var decimalSepIndex = _n2.indexOf('.', 0); - // 6. If decimalSepIndex > 0, then: - if (decimalSepIndex > 0) { - // a. Let integer be the substring of n from position 0, inclusive, to position decimalSepIndex, exclusive. - integer = _n2.substring(0, decimalSepIndex); - // b. Let fraction be the substring of n from position decimalSepIndex, exclusive, to the end of n. - fraction = _n2.substring(decimalSepIndex + 1, decimalSepIndex.length); - } - // 7. Else: - else { - // a. Let integer be n. - integer = _n2; - // b. Let fraction be undefined. - fraction = undefined; - } - // 8. If the value of the numberFormat.[[useGrouping]] is true, - if (internal['[[useGrouping]]'] === true) { - // a. Let groupSepSymbol be the ILND String representing the grouping separator. - var groupSepSymbol = ild.group; - // b. Let groups be a List whose elements are, in left to right order, the substrings defined by ILND set of locations within the integer. - var groups = []; - // ----> implementation: - // Primary group represents the group closest to the decimal - var pgSize = data.patterns.primaryGroupSize || 3; - // Secondary group is every other group - var sgSize = data.patterns.secondaryGroupSize || pgSize; - // Group only if necessary - if (integer.length > pgSize) { - // Index of the primary grouping separator - var end = integer.length - pgSize; - // Starting index for our loop - var idx = end % sgSize; - var start = integer.slice(0, idx); - if (start.length) arrPush.call(groups, start); - // Loop to separate into secondary grouping digits - while (idx < end) { - arrPush.call(groups, integer.slice(idx, idx + sgSize)); - idx += sgSize; - } - // Add the primary grouping digits - arrPush.call(groups, integer.slice(end)); - } else { - arrPush.call(groups, integer); - } - // c. Assert: The number of elements in groups List is greater than 0. - if (groups.length === 0) throw new Error(); - // d. Repeat, while groups List is not empty: - while (groups.length) { - // i. Remove the first element from groups and let integerGroup be the value of that element. - var integerGroup = arrShift.call(groups); - // ii. Add new part record { [[type]]: "integer", [[value]]: integerGroup } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'integer', '[[value]]': integerGroup }); - // iii. If groups List is not empty, then: - if (groups.length) { - // 1. Add new part record { [[type]]: "group", [[value]]: groupSepSymbol } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'group', '[[value]]': groupSepSymbol }); - } - } - } - // 9. Else, - else { - // a. Add new part record { [[type]]: "integer", [[value]]: integer } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'integer', '[[value]]': integer }); - } - // 10. If fraction is not undefined, then: - if (fraction !== undefined) { - // a. Let decimalSepSymbol be the ILND String representing the decimal separator. - var decimalSepSymbol = ild.decimal; - // b. Add new part record { [[type]]: "decimal", [[value]]: decimalSepSymbol } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'decimal', '[[value]]': decimalSepSymbol }); - // c. Add new part record { [[type]]: "fraction", [[value]]: fraction } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'fraction', '[[value]]': fraction }); - } - } - } - // f. Else if p is equal "plusSign", then: - else if (p === "plusSign") { - // i. Let plusSignSymbol be the ILND String representing the plus sign. - var plusSignSymbol = ild.plusSign; - // ii. Add new part record { [[type]]: "plusSign", [[value]]: plusSignSymbol } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'plusSign', '[[value]]': plusSignSymbol }); - } - // g. Else if p is equal "minusSign", then: - else if (p === "minusSign") { - // i. Let minusSignSymbol be the ILND String representing the minus sign. - var minusSignSymbol = ild.minusSign; - // ii. Add new part record { [[type]]: "minusSign", [[value]]: minusSignSymbol } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'minusSign', '[[value]]': minusSignSymbol }); - } - // h. Else if p is equal "percentSign" and numberFormat.[[style]] is "percent", then: - else if (p === "percentSign" && internal['[[style]]'] === "percent") { - // i. Let percentSignSymbol be the ILND String representing the percent sign. - var percentSignSymbol = ild.percentSign; - // ii. Add new part record { [[type]]: "percentSign", [[value]]: percentSignSymbol } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'literal', '[[value]]': percentSignSymbol }); - } - // i. Else if p is equal "currency" and numberFormat.[[style]] is "currency", then: - else if (p === "currency" && internal['[[style]]'] === "currency") { - // i. Let currency be the value of numberFormat.[[currency]]. - var currency = internal['[[currency]]']; - - var cd = void 0; - - // iii. If numberFormat.[[currencyDisplay]] is "code", then - if (internal['[[currencyDisplay]]'] === "code") { - // 1. Let cd be currency. - cd = currency; - } - // iv. Else if numberFormat.[[currencyDisplay]] is "symbol", then - else if (internal['[[currencyDisplay]]'] === "symbol") { - // 1. Let cd be an ILD string representing currency in short form. If the implementation does not have such a representation of currency, use currency itself. - cd = data.currencies[currency] || currency; - } - // v. Else if numberFormat.[[currencyDisplay]] is "name", then - else if (internal['[[currencyDisplay]]'] === "name") { - // 1. Let cd be an ILD string representing currency in long form. If the implementation does not have such a representation of currency, then use currency itself. - cd = currency; - } - // vi. Add new part record { [[type]]: "currency", [[value]]: cd } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'currency', '[[value]]': cd }); - } - // j. Else, - else { - // i. Let literal be the substring of pattern from position beginIndex, inclusive, to position endIndex, inclusive. - var _literal = pattern.substring(beginIndex, endIndex); - // ii. Add new part record { [[type]]: "literal", [[value]]: literal } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'literal', '[[value]]': _literal }); - } - // k. Set nextIndex to endIndex + 1. - nextIndex = endIndex + 1; - // l. Set beginIndex to Call(%StringProto_indexOf%, pattern, "{", nextIndex) - beginIndex = pattern.indexOf('{', nextIndex); - } - // 9. If nextIndex is less than length, then: - if (nextIndex < length) { - // a. Let literal be the substring of pattern from position nextIndex, inclusive, to position length, exclusive. - var _literal2 = pattern.substring(nextIndex, length); - // b. Add new part record { [[type]]: "literal", [[value]]: literal } as a new element of the list result. - arrPush.call(result, { '[[type]]': 'literal', '[[value]]': _literal2 }); - } - // 10. Return result. - return result; -} - -/* - * @spec[tc39/ecma402/master/spec/numberformat.html] - * @clause[sec-formatnumber] - */ -function FormatNumber(numberFormat, x) { - // 1. Let parts be ? PartitionNumberPattern(numberFormat, x). - var parts = PartitionNumberPattern(numberFormat, x); - // 2. Let result be an empty String. - var result = ''; - // 3. For each part in parts, do: - for (var i = 0; parts.length > i; i++) { - var part = parts[i]; - // a. Set result to a String value produced by concatenating result and part.[[value]]. - result += part['[[value]]']; - } - // 4. Return result. - return result; -} - -/** - * When the ToRawPrecision abstract operation is called with arguments x (which - * must be a finite non-negative number), minPrecision, and maxPrecision (both - * must be integers between 1 and 21) the following steps are taken: - */ -function ToRawPrecision(x, minPrecision, maxPrecision) { - // 1. Let p be maxPrecision. - var p = maxPrecision; - - var m = void 0, - e = void 0; - - // 2. If x = 0, then - if (x === 0) { - // a. Let m be the String consisting of p occurrences of the character "0". - m = arrJoin.call(Array(p + 1), '0'); - // b. Let e be 0. - e = 0; - } - // 3. Else - else { - // a. Let e and n be integers such that 10ᵖ⁻¹ ≤ n < 10ᵖ and for which the - // exact mathematical value of n × 10ᵉ⁻ᵖ⁺¹ – x is as close to zero as - // possible. If there are two such sets of e and n, pick the e and n for - // which n × 10ᵉ⁻ᵖ⁺¹ is larger. - e = log10Floor(Math.abs(x)); - - // Easier to get to m from here - var f = Math.round(Math.exp(Math.abs(e - p + 1) * Math.LN10)); - - // b. Let m be the String consisting of the digits of the decimal - // representation of n (in order, with no leading zeroes) - m = String(Math.round(e - p + 1 < 0 ? x * f : x / f)); - } - - // 4. If e ≥ p, then - if (e >= p) - // a. Return the concatenation of m and e-p+1 occurrences of the character "0". - return m + arrJoin.call(Array(e - p + 1 + 1), '0'); - - // 5. If e = p-1, then - else if (e === p - 1) - // a. Return m. - return m; - - // 6. If e ≥ 0, then - else if (e >= 0) - // a. Let m be the concatenation of the first e+1 characters of m, the character - // ".", and the remaining p–(e+1) characters of m. - m = m.slice(0, e + 1) + '.' + m.slice(e + 1); - - // 7. If e < 0, then - else if (e < 0) - // a. Let m be the concatenation of the String "0.", –(e+1) occurrences of the - // character "0", and the string m. - m = '0.' + arrJoin.call(Array(-(e + 1) + 1), '0') + m; - - // 8. If m contains the character ".", and maxPrecision > minPrecision, then - if (m.indexOf(".") >= 0 && maxPrecision > minPrecision) { - // a. Let cut be maxPrecision – minPrecision. - var cut = maxPrecision - minPrecision; - - // b. Repeat while cut > 0 and the last character of m is "0": - while (cut > 0 && m.charAt(m.length - 1) === '0') { - // i. Remove the last character from m. - m = m.slice(0, -1); - - // ii. Decrease cut by 1. - cut--; - } - - // c. If the last character of m is ".", then - if (m.charAt(m.length - 1) === '.') - // i. Remove the last character from m. - m = m.slice(0, -1); - } - // 9. Return m. - return m; -} - -/** - * @spec[tc39/ecma402/master/spec/numberformat.html] - * @clause[sec-torawfixed] - * When the ToRawFixed abstract operation is called with arguments x (which must - * be a finite non-negative number), minInteger (which must be an integer between - * 1 and 21), minFraction, and maxFraction (which must be integers between 0 and - * 20) the following steps are taken: - */ -function ToRawFixed(x, minInteger, minFraction, maxFraction) { - // 1. Let f be maxFraction. - var f = maxFraction; - // 2. Let n be an integer for which the exact mathematical value of n ÷ 10f – x is as close to zero as possible. If there are two such n, pick the larger n. - var n = Math.pow(10, f) * x; // diverging... - // 3. If n = 0, let m be the String "0". Otherwise, let m be the String consisting of the digits of the decimal representation of n (in order, with no leading zeroes). - var m = n === 0 ? "0" : n.toFixed(0); // divering... - - { - // this diversion is needed to take into consideration big numbers, e.g.: - // 1.2344501e+37 -> 12344501000000000000000000000000000000 - var idx = void 0; - var exp = (idx = m.indexOf('e')) > -1 ? m.slice(idx + 1) : 0; - if (exp) { - m = m.slice(0, idx).replace('.', ''); - m += arrJoin.call(Array(exp - (m.length - 1) + 1), '0'); - } - } - - var int = void 0; - // 4. If f ≠ 0, then - if (f !== 0) { - // a. Let k be the number of characters in m. - var k = m.length; - // a. If k ≤ f, then - if (k <= f) { - // i. Let z be the String consisting of f+1–k occurrences of the character "0". - var z = arrJoin.call(Array(f + 1 - k + 1), '0'); - // ii. Let m be the concatenation of Strings z and m. - m = z + m; - // iii. Let k be f+1. - k = f + 1; - } - // a. Let a be the first k–f characters of m, and let b be the remaining f characters of m. - var a = m.substring(0, k - f), - b = m.substring(k - f, m.length); - // a. Let m be the concatenation of the three Strings a, ".", and b. - m = a + "." + b; - // a. Let int be the number of characters in a. - int = a.length; - } - // 5. Else, let int be the number of characters in m. - else int = m.length; - // 6. Let cut be maxFraction – minFraction. - var cut = maxFraction - minFraction; - // 7. Repeat while cut > 0 and the last character of m is "0": - while (cut > 0 && m.slice(-1) === "0") { - // a. Remove the last character from m. - m = m.slice(0, -1); - // a. Decrease cut by 1. - cut--; - } - // 8. If the last character of m is ".", then - if (m.slice(-1) === ".") { - // a. Remove the last character from m. - m = m.slice(0, -1); - } - // 9. If int < minInteger, then - if (int < minInteger) { - // a. Let z be the String consisting of minInteger–int occurrences of the character "0". - var _z = arrJoin.call(Array(minInteger - int + 1), '0'); - // a. Let m be the concatenation of Strings z and m. - m = _z + m; - } - // 10. Return m. - return m; -} - -// Sect 11.3.2 Table 2, Numbering systems -// ====================================== -var numSys = { - arab: ["\u0660", "\u0661", "\u0662", "\u0663", "\u0664", "\u0665", "\u0666", "\u0667", "\u0668", "\u0669"], - arabext: ["\u06F0", "\u06F1", "\u06F2", "\u06F3", "\u06F4", "\u06F5", "\u06F6", "\u06F7", "\u06F8", "\u06F9"], - bali: ["\u1B50", "\u1B51", "\u1B52", "\u1B53", "\u1B54", "\u1B55", "\u1B56", "\u1B57", "\u1B58", "\u1B59"], - beng: ["\u09E6", "\u09E7", "\u09E8", "\u09E9", "\u09EA", "\u09EB", "\u09EC", "\u09ED", "\u09EE", "\u09EF"], - deva: ["\u0966", "\u0967", "\u0968", "\u0969", "\u096A", "\u096B", "\u096C", "\u096D", "\u096E", "\u096F"], - fullwide: ["\uFF10", "\uFF11", "\uFF12", "\uFF13", "\uFF14", "\uFF15", "\uFF16", "\uFF17", "\uFF18", "\uFF19"], - gujr: ["\u0AE6", "\u0AE7", "\u0AE8", "\u0AE9", "\u0AEA", "\u0AEB", "\u0AEC", "\u0AED", "\u0AEE", "\u0AEF"], - guru: ["\u0A66", "\u0A67", "\u0A68", "\u0A69", "\u0A6A", "\u0A6B", "\u0A6C", "\u0A6D", "\u0A6E", "\u0A6F"], - hanidec: ["\u3007", "\u4E00", "\u4E8C", "\u4E09", "\u56DB", "\u4E94", "\u516D", "\u4E03", "\u516B", "\u4E5D"], - khmr: ["\u17E0", "\u17E1", "\u17E2", "\u17E3", "\u17E4", "\u17E5", "\u17E6", "\u17E7", "\u17E8", "\u17E9"], - knda: ["\u0CE6", "\u0CE7", "\u0CE8", "\u0CE9", "\u0CEA", "\u0CEB", "\u0CEC", "\u0CED", "\u0CEE", "\u0CEF"], - laoo: ["\u0ED0", "\u0ED1", "\u0ED2", "\u0ED3", "\u0ED4", "\u0ED5", "\u0ED6", "\u0ED7", "\u0ED8", "\u0ED9"], - latn: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"], - limb: ["\u1946", "\u1947", "\u1948", "\u1949", "\u194A", "\u194B", "\u194C", "\u194D", "\u194E", "\u194F"], - mlym: ["\u0D66", "\u0D67", "\u0D68", "\u0D69", "\u0D6A", "\u0D6B", "\u0D6C", "\u0D6D", "\u0D6E", "\u0D6F"], - mong: ["\u1810", "\u1811", "\u1812", "\u1813", "\u1814", "\u1815", "\u1816", "\u1817", "\u1818", "\u1819"], - mymr: ["\u1040", "\u1041", "\u1042", "\u1043", "\u1044", "\u1045", "\u1046", "\u1047", "\u1048", "\u1049"], - orya: ["\u0B66", "\u0B67", "\u0B68", "\u0B69", "\u0B6A", "\u0B6B", "\u0B6C", "\u0B6D", "\u0B6E", "\u0B6F"], - tamldec: ["\u0BE6", "\u0BE7", "\u0BE8", "\u0BE9", "\u0BEA", "\u0BEB", "\u0BEC", "\u0BED", "\u0BEE", "\u0BEF"], - telu: ["\u0C66", "\u0C67", "\u0C68", "\u0C69", "\u0C6A", "\u0C6B", "\u0C6C", "\u0C6D", "\u0C6E", "\u0C6F"], - thai: ["\u0E50", "\u0E51", "\u0E52", "\u0E53", "\u0E54", "\u0E55", "\u0E56", "\u0E57", "\u0E58", "\u0E59"], - tibt: ["\u0F20", "\u0F21", "\u0F22", "\u0F23", "\u0F24", "\u0F25", "\u0F26", "\u0F27", "\u0F28", "\u0F29"] -}; - -/** - * This function provides access to the locale and formatting options computed - * during initialization of the object. - * - * The function returns a new object whose properties and attributes are set as - * if constructed by an object literal assigning to each of the following - * properties the value of the corresponding internal property of this - * NumberFormat object (see 11.4): locale, numberingSystem, style, currency, - * currencyDisplay, minimumIntegerDigits, minimumFractionDigits, - * maximumFractionDigits, minimumSignificantDigits, maximumSignificantDigits, and - * useGrouping. Properties whose corresponding internal properties are not present - * are not assigned. - */ -/* 11.3.3 */defineProperty(Intl$1.NumberFormat.prototype, 'resolvedOptions', { - configurable: true, - writable: true, - value: function value() { - var prop = void 0, - descs = new Record(), - props = ['locale', 'numberingSystem', 'style', 'currency', 'currencyDisplay', 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits', 'useGrouping'], - internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this); - - // Satisfy test 11.3_b - if (!internal || !internal['[[initializedNumberFormat]]']) throw new TypeError('`this` value for resolvedOptions() is not an initialized Intl.NumberFormat object.'); - - for (var i = 0, max = props.length; i < max; i++) { - if (hop.call(internal, prop = '[[' + props[i] + ']]')) descs[props[i]] = { value: internal[prop], writable: true, configurable: true, enumerable: true }; - } - - return objCreate({}, descs); - } -}); - -/* jslint esnext: true */ - -// Match these datetime components in a CLDR pattern, except those in single quotes -var expDTComponents = /(?:[Eec]{1,6}|G{1,5}|[Qq]{1,5}|(?:[yYur]+|U{1,5})|[ML]{1,5}|d{1,2}|D{1,3}|F{1}|[abB]{1,5}|[hkHK]{1,2}|w{1,2}|W{1}|m{1,2}|s{1,2}|[zZOvVxX]{1,4})(?=([^']*'[^']*')*[^']*$)/g; -// trim patterns after transformations -var expPatternTrimmer = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g; -// Skip over patterns with these datetime components because we don't have data -// to back them up: -// timezone, weekday, amoung others -var unwantedDTCs = /[rqQASjJgwWIQq]/; // xXVO were removed from this list in favor of computing matches with timeZoneName values but printing as empty string - -var dtKeys = ["era", "year", "month", "day", "weekday", "quarter"]; -var tmKeys = ["hour", "minute", "second", "hour12", "timeZoneName"]; - -function isDateFormatOnly(obj) { - for (var i = 0; i < tmKeys.length; i += 1) { - if (obj.hasOwnProperty(tmKeys[i])) { - return false; - } - } - return true; -} - -function isTimeFormatOnly(obj) { - for (var i = 0; i < dtKeys.length; i += 1) { - if (obj.hasOwnProperty(dtKeys[i])) { - return false; - } - } - return true; -} - -function joinDateAndTimeFormats(dateFormatObj, timeFormatObj) { - var o = { _: {} }; - for (var i = 0; i < dtKeys.length; i += 1) { - if (dateFormatObj[dtKeys[i]]) { - o[dtKeys[i]] = dateFormatObj[dtKeys[i]]; - } - if (dateFormatObj._[dtKeys[i]]) { - o._[dtKeys[i]] = dateFormatObj._[dtKeys[i]]; - } - } - for (var j = 0; j < tmKeys.length; j += 1) { - if (timeFormatObj[tmKeys[j]]) { - o[tmKeys[j]] = timeFormatObj[tmKeys[j]]; - } - if (timeFormatObj._[tmKeys[j]]) { - o._[tmKeys[j]] = timeFormatObj._[tmKeys[j]]; - } - } - return o; -} - -function computeFinalPatterns(formatObj) { - // From http://www.unicode.org/reports/tr35/tr35-dates.html#Date_Format_Patterns: - // 'In patterns, two single quotes represents a literal single quote, either - // inside or outside single quotes. Text within single quotes is not - // interpreted in any way (except for two adjacent single quotes).' - formatObj.pattern12 = formatObj.extendedPattern.replace(/'([^']*)'/g, function ($0, literal) { - return literal ? literal : "'"; - }); - - // pattern 12 is always the default. we can produce the 24 by removing {ampm} - formatObj.pattern = formatObj.pattern12.replace('{ampm}', '').replace(expPatternTrimmer, ''); - return formatObj; -} - -function expDTComponentsMeta($0, formatObj) { - switch ($0.charAt(0)) { - // --- Era - case 'G': - formatObj.era = ['short', 'short', 'short', 'long', 'narrow'][$0.length - 1]; - return '{era}'; - - // --- Year - case 'y': - case 'Y': - case 'u': - case 'U': - case 'r': - formatObj.year = $0.length === 2 ? '2-digit' : 'numeric'; - return '{year}'; - - // --- Quarter (not supported in this polyfill) - case 'Q': - case 'q': - formatObj.quarter = ['numeric', '2-digit', 'short', 'long', 'narrow'][$0.length - 1]; - return '{quarter}'; - - // --- Month - case 'M': - case 'L': - formatObj.month = ['numeric', '2-digit', 'short', 'long', 'narrow'][$0.length - 1]; - return '{month}'; - - // --- Week (not supported in this polyfill) - case 'w': - // week of the year - formatObj.week = $0.length === 2 ? '2-digit' : 'numeric'; - return '{weekday}'; - case 'W': - // week of the month - formatObj.week = 'numeric'; - return '{weekday}'; - - // --- Day - case 'd': - // day of the month - formatObj.day = $0.length === 2 ? '2-digit' : 'numeric'; - return '{day}'; - case 'D': // day of the year - case 'F': // day of the week - case 'g': - // 1..n: Modified Julian day - formatObj.day = 'numeric'; - return '{day}'; - - // --- Week Day - case 'E': - // day of the week - formatObj.weekday = ['short', 'short', 'short', 'long', 'narrow', 'short'][$0.length - 1]; - return '{weekday}'; - case 'e': - // local day of the week - formatObj.weekday = ['numeric', '2-digit', 'short', 'long', 'narrow', 'short'][$0.length - 1]; - return '{weekday}'; - case 'c': - // stand alone local day of the week - formatObj.weekday = ['numeric', undefined, 'short', 'long', 'narrow', 'short'][$0.length - 1]; - return '{weekday}'; - - // --- Period - case 'a': // AM, PM - case 'b': // am, pm, noon, midnight - case 'B': - // flexible day periods - formatObj.hour12 = true; - return '{ampm}'; - - // --- Hour - case 'h': - case 'H': - formatObj.hour = $0.length === 2 ? '2-digit' : 'numeric'; - return '{hour}'; - case 'k': - case 'K': - formatObj.hour12 = true; // 12-hour-cycle time formats (using h or K) - formatObj.hour = $0.length === 2 ? '2-digit' : 'numeric'; - return '{hour}'; - - // --- Minute - case 'm': - formatObj.minute = $0.length === 2 ? '2-digit' : 'numeric'; - return '{minute}'; - - // --- Second - case 's': - formatObj.second = $0.length === 2 ? '2-digit' : 'numeric'; - return '{second}'; - case 'S': - case 'A': - formatObj.second = 'numeric'; - return '{second}'; - - // --- Timezone - case 'z': // 1..3, 4: specific non-location format - case 'Z': // 1..3, 4, 5: The ISO8601 varios formats - case 'O': // 1, 4: miliseconds in day short, long - case 'v': // 1, 4: generic non-location format - case 'V': // 1, 2, 3, 4: time zone ID or city - case 'X': // 1, 2, 3, 4: The ISO8601 varios formats - case 'x': - // 1, 2, 3, 4: The ISO8601 varios formats - // this polyfill only supports much, for now, we are just doing something dummy - formatObj.timeZoneName = $0.length < 4 ? 'short' : 'long'; - return '{timeZoneName}'; - } -} - -/** - * Converts the CLDR availableFormats into the objects and patterns required by - * the ECMAScript Internationalization API specification. - */ -function createDateTimeFormat(skeleton, pattern) { - // we ignore certain patterns that are unsupported to avoid this expensive op. - if (unwantedDTCs.test(pattern)) return undefined; - - var formatObj = { - originalPattern: pattern, - _: {} - }; - - // Replace the pattern string with the one required by the specification, whilst - // at the same time evaluating it for the subsets and formats - formatObj.extendedPattern = pattern.replace(expDTComponents, function ($0) { - // See which symbol we're dealing with - return expDTComponentsMeta($0, formatObj._); - }); - - // Match the skeleton string with the one required by the specification - // this implementation is based on the Date Field Symbol Table: - // http://unicode.org/reports/tr35/tr35-dates.html#Date_Field_Symbol_Table - // Note: we are adding extra data to the formatObject even though this polyfill - // might not support it. - skeleton.replace(expDTComponents, function ($0) { - // See which symbol we're dealing with - return expDTComponentsMeta($0, formatObj); - }); - - return computeFinalPatterns(formatObj); -} - -/** - * Processes DateTime formats from CLDR to an easier-to-parse format. - * the result of this operation should be cached the first time a particular - * calendar is analyzed. - * - * The specification requires we support at least the following subsets of - * date/time components: - * - * - 'weekday', 'year', 'month', 'day', 'hour', 'minute', 'second' - * - 'weekday', 'year', 'month', 'day' - * - 'year', 'month', 'day' - * - 'year', 'month' - * - 'month', 'day' - * - 'hour', 'minute', 'second' - * - 'hour', 'minute' - * - * We need to cherry pick at least these subsets from the CLDR data and convert - * them into the pattern objects used in the ECMA-402 API. - */ -function createDateTimeFormats(formats) { - var availableFormats = formats.availableFormats; - var timeFormats = formats.timeFormats; - var dateFormats = formats.dateFormats; - var result = []; - var skeleton = void 0, - pattern = void 0, - computed = void 0, - i = void 0, - j = void 0; - var timeRelatedFormats = []; - var dateRelatedFormats = []; - - // Map available (custom) formats into a pattern for createDateTimeFormats - for (skeleton in availableFormats) { - if (availableFormats.hasOwnProperty(skeleton)) { - pattern = availableFormats[skeleton]; - computed = createDateTimeFormat(skeleton, pattern); - if (computed) { - result.push(computed); - // in some cases, the format is only displaying date specific props - // or time specific props, in which case we need to also produce the - // combined formats. - if (isDateFormatOnly(computed)) { - dateRelatedFormats.push(computed); - } else if (isTimeFormatOnly(computed)) { - timeRelatedFormats.push(computed); - } - } - } - } - - // Map time formats into a pattern for createDateTimeFormats - for (skeleton in timeFormats) { - if (timeFormats.hasOwnProperty(skeleton)) { - pattern = timeFormats[skeleton]; - computed = createDateTimeFormat(skeleton, pattern); - if (computed) { - result.push(computed); - timeRelatedFormats.push(computed); - } - } - } - - // Map date formats into a pattern for createDateTimeFormats - for (skeleton in dateFormats) { - if (dateFormats.hasOwnProperty(skeleton)) { - pattern = dateFormats[skeleton]; - computed = createDateTimeFormat(skeleton, pattern); - if (computed) { - result.push(computed); - dateRelatedFormats.push(computed); - } - } - } - - // combine custom time and custom date formats when they are orthogonals to complete the - // formats supported by CLDR. - // This Algo is based on section "Missing Skeleton Fields" from: - // http://unicode.org/reports/tr35/tr35-dates.html#availableFormats_appendItems - for (i = 0; i < timeRelatedFormats.length; i += 1) { - for (j = 0; j < dateRelatedFormats.length; j += 1) { - if (dateRelatedFormats[j].month === 'long') { - pattern = dateRelatedFormats[j].weekday ? formats.full : formats.long; - } else if (dateRelatedFormats[j].month === 'short') { - pattern = formats.medium; - } else { - pattern = formats.short; - } - computed = joinDateAndTimeFormats(dateRelatedFormats[j], timeRelatedFormats[i]); - computed.originalPattern = pattern; - computed.extendedPattern = pattern.replace('{0}', timeRelatedFormats[i].extendedPattern).replace('{1}', dateRelatedFormats[j].extendedPattern).replace(/^[,\s]+|[,\s]+$/gi, ''); - result.push(computeFinalPatterns(computed)); - } - } - - return result; -} - -// this represents the exceptions of the rule that are not covered by CLDR availableFormats -// for single property configurations, they play no role when using multiple properties, and -// those that are not in this table, are not exceptions or are not covered by the data we -// provide. -var validSyntheticProps = { - second: { - numeric: 's', - '2-digit': 'ss' - }, - minute: { - numeric: 'm', - '2-digit': 'mm' - }, - year: { - numeric: 'y', - '2-digit': 'yy' - }, - day: { - numeric: 'd', - '2-digit': 'dd' - }, - month: { - numeric: 'L', - '2-digit': 'LL', - narrow: 'LLLLL', - short: 'LLL', - long: 'LLLL' - }, - weekday: { - narrow: 'ccccc', - short: 'ccc', - long: 'cccc' - } -}; - -function generateSyntheticFormat(propName, propValue) { - if (validSyntheticProps[propName] && validSyntheticProps[propName][propValue]) { - var _ref2; - - return _ref2 = { - originalPattern: validSyntheticProps[propName][propValue], - _: defineProperty$1({}, propName, propValue), - extendedPattern: "{" + propName + "}" - }, defineProperty$1(_ref2, propName, propValue), defineProperty$1(_ref2, "pattern12", "{" + propName + "}"), defineProperty$1(_ref2, "pattern", "{" + propName + "}"), _ref2; - } -} - -// 12.1 The Intl.DateTimeFormat constructor -// ================================== - -// An object map of date component keys, saves using a regex later -var dateWidths = objCreate(null, { narrow: {}, short: {}, long: {} }); - -/** - * Returns a string for a date component, resolved using multiple inheritance as specified - * as specified in the Unicode Technical Standard 35. - */ -function resolveDateString(data, ca, component, width, key) { - // From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance: - // 'In clearly specified instances, resources may inherit from within the same locale. - // For example, ... the Buddhist calendar inherits from the Gregorian calendar.' - var obj = data[ca] && data[ca][component] ? data[ca][component] : data.gregory[component], - - - // "sideways" inheritance resolves strings when a key doesn't exist - alts = { - narrow: ['short', 'long'], - short: ['long', 'narrow'], - long: ['short', 'narrow'] - }, - - - // - resolved = hop.call(obj, width) ? obj[width] : hop.call(obj, alts[width][0]) ? obj[alts[width][0]] : obj[alts[width][1]]; - - // `key` wouldn't be specified for components 'dayPeriods' - return key !== null ? resolved[key] : resolved; -} - -// Define the DateTimeFormat constructor internally so it cannot be tainted -function DateTimeFormatConstructor() { - var locales = arguments[0]; - var options = arguments[1]; - - if (!this || this === Intl$1) { - return new Intl$1.DateTimeFormat(locales, options); - } - return InitializeDateTimeFormat(toObject(this), locales, options); -} - -defineProperty(Intl$1, 'DateTimeFormat', { - configurable: true, - writable: true, - value: DateTimeFormatConstructor -}); - -// Must explicitly set prototypes as unwritable -defineProperty(DateTimeFormatConstructor, 'prototype', { - writable: false -}); - -/** - * The abstract operation InitializeDateTimeFormat accepts the arguments dateTimeFormat - * (which must be an object), locales, and options. It initializes dateTimeFormat as a - * DateTimeFormat object. - */ -function /* 12.1.1.1 */InitializeDateTimeFormat(dateTimeFormat, locales, options) { - // This will be a internal properties object if we're not already initialized - var internal = getInternalProperties(dateTimeFormat); - - // Create an object whose props can be used to restore the values of RegExp props - var regexpRestore = createRegExpRestore(); - - // 1. If dateTimeFormat has an [[initializedIntlObject]] internal property with - // value true, throw a TypeError exception. - if (internal['[[initializedIntlObject]]'] === true) throw new TypeError('`this` object has already been initialized as an Intl object'); - - // Need this to access the `internal` object - defineProperty(dateTimeFormat, '__getInternalProperties', { - value: function value() { - // NOTE: Non-standard, for internal use only - if (arguments[0] === secret) return internal; - } - }); - - // 2. Set the [[initializedIntlObject]] internal property of numberFormat to true. - internal['[[initializedIntlObject]]'] = true; - - // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList - // abstract operation (defined in 9.2.1) with argument locales. - var requestedLocales = CanonicalizeLocaleList(locales); - - // 4. Let options be the result of calling the ToDateTimeOptions abstract - // operation (defined below) with arguments options, "any", and "date". - options = ToDateTimeOptions(options, 'any', 'date'); - - // 5. Let opt be a new Record. - var opt = new Record(); - - // 6. Let matcher be the result of calling the GetOption abstract operation - // (defined in 9.2.9) with arguments options, "localeMatcher", "string", a List - // containing the two String values "lookup" and "best fit", and "best fit". - var matcher = GetOption(options, 'localeMatcher', 'string', new List('lookup', 'best fit'), 'best fit'); - - // 7. Set opt.[[localeMatcher]] to matcher. - opt['[[localeMatcher]]'] = matcher; - - // 8. Let DateTimeFormat be the standard built-in object that is the initial - // value of Intl.DateTimeFormat. - var DateTimeFormat = internals.DateTimeFormat; // This is what we *really* need - - // 9. Let localeData be the value of the [[localeData]] internal property of - // DateTimeFormat. - var localeData = DateTimeFormat['[[localeData]]']; - - // 10. Let r be the result of calling the ResolveLocale abstract operation - // (defined in 9.2.5) with the [[availableLocales]] internal property of - // DateTimeFormat, requestedLocales, opt, the [[relevantExtensionKeys]] - // internal property of DateTimeFormat, and localeData. - var r = ResolveLocale(DateTimeFormat['[[availableLocales]]'], requestedLocales, opt, DateTimeFormat['[[relevantExtensionKeys]]'], localeData); - - // 11. Set the [[locale]] internal property of dateTimeFormat to the value of - // r.[[locale]]. - internal['[[locale]]'] = r['[[locale]]']; - - // 12. Set the [[calendar]] internal property of dateTimeFormat to the value of - // r.[[ca]]. - internal['[[calendar]]'] = r['[[ca]]']; - - // 13. Set the [[numberingSystem]] internal property of dateTimeFormat to the value of - // r.[[nu]]. - internal['[[numberingSystem]]'] = r['[[nu]]']; - - // The specification doesn't tell us to do this, but it's helpful later on - internal['[[dataLocale]]'] = r['[[dataLocale]]']; - - // 14. Let dataLocale be the value of r.[[dataLocale]]. - var dataLocale = r['[[dataLocale]]']; - - // 15. Let tz be the result of calling the [[Get]] internal method of options with - // argument "timeZone". - var tz = options.timeZone; - - // 16. If tz is not undefined, then - if (tz !== undefined) { - // a. Let tz be ToString(tz). - // b. Convert tz to upper case as described in 6.1. - // NOTE: If an implementation accepts additional time zone values, as permitted - // under certain conditions by the Conformance clause, different casing - // rules apply. - tz = toLatinUpperCase(tz); - - // c. If tz is not "UTC", then throw a RangeError exception. - // ###TODO: accept more time zones### - if (tz !== 'UTC') throw new RangeError('timeZone is not supported.'); - } - - // 17. Set the [[timeZone]] internal property of dateTimeFormat to tz. - internal['[[timeZone]]'] = tz; - - // 18. Let opt be a new Record. - opt = new Record(); - - // 19. For each row of Table 3, except the header row, do: - for (var prop in dateTimeComponents) { - if (!hop.call(dateTimeComponents, prop)) continue; - - // 20. Let prop be the name given in the Property column of the row. - // 21. Let value be the result of calling the GetOption abstract operation, - // passing as argument options, the name given in the Property column of the - // row, "string", a List containing the strings given in the Values column of - // the row, and undefined. - var value = GetOption(options, prop, 'string', dateTimeComponents[prop]); - - // 22. Set opt.[[]] to value. - opt['[[' + prop + ']]'] = value; - } - - // Assigned a value below - var bestFormat = void 0; - - // 23. Let dataLocaleData be the result of calling the [[Get]] internal method of - // localeData with argument dataLocale. - var dataLocaleData = localeData[dataLocale]; - - // 24. Let formats be the result of calling the [[Get]] internal method of - // dataLocaleData with argument "formats". - // Note: we process the CLDR formats into the spec'd structure - var formats = ToDateTimeFormats(dataLocaleData.formats); - - // 25. Let matcher be the result of calling the GetOption abstract operation with - // arguments options, "formatMatcher", "string", a List containing the two String - // values "basic" and "best fit", and "best fit". - matcher = GetOption(options, 'formatMatcher', 'string', new List('basic', 'best fit'), 'best fit'); - - // Optimization: caching the processed formats as a one time operation by - // replacing the initial structure from localeData - dataLocaleData.formats = formats; - - // 26. If matcher is "basic", then - if (matcher === 'basic') { - // 27. Let bestFormat be the result of calling the BasicFormatMatcher abstract - // operation (defined below) with opt and formats. - bestFormat = BasicFormatMatcher(opt, formats); - - // 28. Else - } else { - { - // diverging - var _hr = GetOption(options, 'hour12', 'boolean' /*, undefined, undefined*/); - opt.hour12 = _hr === undefined ? dataLocaleData.hour12 : _hr; - } - // 29. Let bestFormat be the result of calling the BestFitFormatMatcher - // abstract operation (defined below) with opt and formats. - bestFormat = BestFitFormatMatcher(opt, formats); - } - - // 30. For each row in Table 3, except the header row, do - for (var _prop in dateTimeComponents) { - if (!hop.call(dateTimeComponents, _prop)) continue; - - // a. Let prop be the name given in the Property column of the row. - // b. Let pDesc be the result of calling the [[GetOwnProperty]] internal method of - // bestFormat with argument prop. - // c. If pDesc is not undefined, then - if (hop.call(bestFormat, _prop)) { - // i. Let p be the result of calling the [[Get]] internal method of bestFormat - // with argument prop. - var p = bestFormat[_prop]; - { - // diverging - p = bestFormat._ && hop.call(bestFormat._, _prop) ? bestFormat._[_prop] : p; - } - - // ii. Set the [[]] internal property of dateTimeFormat to p. - internal['[[' + _prop + ']]'] = p; - } - } - - var pattern = void 0; // Assigned a value below - - // 31. Let hr12 be the result of calling the GetOption abstract operation with - // arguments options, "hour12", "boolean", undefined, and undefined. - var hr12 = GetOption(options, 'hour12', 'boolean' /*, undefined, undefined*/); - - // 32. If dateTimeFormat has an internal property [[hour]], then - if (internal['[[hour]]']) { - // a. If hr12 is undefined, then let hr12 be the result of calling the [[Get]] - // internal method of dataLocaleData with argument "hour12". - hr12 = hr12 === undefined ? dataLocaleData.hour12 : hr12; - - // b. Set the [[hour12]] internal property of dateTimeFormat to hr12. - internal['[[hour12]]'] = hr12; - - // c. If hr12 is true, then - if (hr12 === true) { - // i. Let hourNo0 be the result of calling the [[Get]] internal method of - // dataLocaleData with argument "hourNo0". - var hourNo0 = dataLocaleData.hourNo0; - - // ii. Set the [[hourNo0]] internal property of dateTimeFormat to hourNo0. - internal['[[hourNo0]]'] = hourNo0; - - // iii. Let pattern be the result of calling the [[Get]] internal method of - // bestFormat with argument "pattern12". - pattern = bestFormat.pattern12; - } - - // d. Else - else - // i. Let pattern be the result of calling the [[Get]] internal method of - // bestFormat with argument "pattern". - pattern = bestFormat.pattern; - } - - // 33. Else - else - // a. Let pattern be the result of calling the [[Get]] internal method of - // bestFormat with argument "pattern". - pattern = bestFormat.pattern; - - // 34. Set the [[pattern]] internal property of dateTimeFormat to pattern. - internal['[[pattern]]'] = pattern; - - // 35. Set the [[boundFormat]] internal property of dateTimeFormat to undefined. - internal['[[boundFormat]]'] = undefined; - - // 36. Set the [[initializedDateTimeFormat]] internal property of dateTimeFormat to - // true. - internal['[[initializedDateTimeFormat]]'] = true; - - // In ES3, we need to pre-bind the format() function - if (es3) dateTimeFormat.format = GetFormatDateTime.call(dateTimeFormat); - - // Restore the RegExp properties - regexpRestore(); - - // Return the newly initialised object - return dateTimeFormat; -} - -/** - * Several DateTimeFormat algorithms use values from the following table, which provides - * property names and allowable values for the components of date and time formats: - */ -var dateTimeComponents = { - weekday: ["narrow", "short", "long"], - era: ["narrow", "short", "long"], - year: ["2-digit", "numeric"], - month: ["2-digit", "numeric", "narrow", "short", "long"], - day: ["2-digit", "numeric"], - hour: ["2-digit", "numeric"], - minute: ["2-digit", "numeric"], - second: ["2-digit", "numeric"], - timeZoneName: ["short", "long"] -}; - -/** - * When the ToDateTimeOptions abstract operation is called with arguments options, - * required, and defaults, the following steps are taken: - */ -function ToDateTimeFormats(formats) { - if (Object.prototype.toString.call(formats) === '[object Array]') { - return formats; - } - return createDateTimeFormats(formats); -} - -/** - * When the ToDateTimeOptions abstract operation is called with arguments options, - * required, and defaults, the following steps are taken: - */ -function ToDateTimeOptions(options, required, defaults) { - // 1. If options is undefined, then let options be null, else let options be - // ToObject(options). - if (options === undefined) options = null;else { - // (#12) options needs to be a Record, but it also needs to inherit properties - var opt2 = toObject(options); - options = new Record(); - - for (var k in opt2) { - options[k] = opt2[k]; - } - } - - // 2. Let create be the standard built-in function object defined in ES5, 15.2.3.5. - var create = objCreate; - - // 3. Let options be the result of calling the [[Call]] internal method of create with - // undefined as the this value and an argument list containing the single item - // options. - options = create(options); - - // 4. Let needDefaults be true. - var needDefaults = true; - - // 5. If required is "date" or "any", then - if (required === 'date' || required === 'any') { - // a. For each of the property names "weekday", "year", "month", "day": - // i. If the result of calling the [[Get]] internal method of options with the - // property name is not undefined, then let needDefaults be false. - if (options.weekday !== undefined || options.year !== undefined || options.month !== undefined || options.day !== undefined) needDefaults = false; - } - - // 6. If required is "time" or "any", then - if (required === 'time' || required === 'any') { - // a. For each of the property names "hour", "minute", "second": - // i. If the result of calling the [[Get]] internal method of options with the - // property name is not undefined, then let needDefaults be false. - if (options.hour !== undefined || options.minute !== undefined || options.second !== undefined) needDefaults = false; - } - - // 7. If needDefaults is true and defaults is either "date" or "all", then - if (needDefaults && (defaults === 'date' || defaults === 'all')) - // a. For each of the property names "year", "month", "day": - // i. Call the [[DefineOwnProperty]] internal method of options with the - // property name, Property Descriptor {[[Value]]: "numeric", [[Writable]]: - // true, [[Enumerable]]: true, [[Configurable]]: true}, and false. - options.year = options.month = options.day = 'numeric'; - - // 8. If needDefaults is true and defaults is either "time" or "all", then - if (needDefaults && (defaults === 'time' || defaults === 'all')) - // a. For each of the property names "hour", "minute", "second": - // i. Call the [[DefineOwnProperty]] internal method of options with the - // property name, Property Descriptor {[[Value]]: "numeric", [[Writable]]: - // true, [[Enumerable]]: true, [[Configurable]]: true}, and false. - options.hour = options.minute = options.second = 'numeric'; - - // 9. Return options. - return options; -} - -/** - * When the BasicFormatMatcher abstract operation is called with two arguments options and - * formats, the following steps are taken: - */ -function BasicFormatMatcher(options, formats) { - // 1. Let removalPenalty be 120. - var removalPenalty = 120; - - // 2. Let additionPenalty be 20. - var additionPenalty = 20; - - // 3. Let longLessPenalty be 8. - var longLessPenalty = 8; - - // 4. Let longMorePenalty be 6. - var longMorePenalty = 6; - - // 5. Let shortLessPenalty be 6. - var shortLessPenalty = 6; - - // 6. Let shortMorePenalty be 3. - var shortMorePenalty = 3; - - // 7. Let bestScore be -Infinity. - var bestScore = -Infinity; - - // 8. Let bestFormat be undefined. - var bestFormat = void 0; - - // 9. Let i be 0. - var i = 0; - - // 10. Assert: formats is an Array object. - - // 11. Let len be the result of calling the [[Get]] internal method of formats with argument "length". - var len = formats.length; - - // 12. Repeat while i < len: - while (i < len) { - // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i). - var format = formats[i]; - - // b. Let score be 0. - var score = 0; - - // c. For each property shown in Table 3: - for (var property in dateTimeComponents) { - if (!hop.call(dateTimeComponents, property)) continue; - - // i. Let optionsProp be options.[[]]. - var optionsProp = options['[[' + property + ']]']; - - // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format - // with argument property. - // iii. If formatPropDesc is not undefined, then - // 1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property. - var formatProp = hop.call(format, property) ? format[property] : undefined; - - // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by - // additionPenalty. - if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty; - - // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by - // removalPenalty. - else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty; - - // vi. Else - else { - // 1. Let values be the array ["2-digit", "numeric", "narrow", "short", - // "long"]. - var values = ['2-digit', 'numeric', 'narrow', 'short', 'long']; - - // 2. Let optionsPropIndex be the index of optionsProp within values. - var optionsPropIndex = arrIndexOf.call(values, optionsProp); - - // 3. Let formatPropIndex be the index of formatProp within values. - var formatPropIndex = arrIndexOf.call(values, formatProp); - - // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2). - var delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2); - - // 5. If delta = 2, decrease score by longMorePenalty. - if (delta === 2) score -= longMorePenalty; - - // 6. Else if delta = 1, decrease score by shortMorePenalty. - else if (delta === 1) score -= shortMorePenalty; - - // 7. Else if delta = -1, decrease score by shortLessPenalty. - else if (delta === -1) score -= shortLessPenalty; - - // 8. Else if delta = -2, decrease score by longLessPenalty. - else if (delta === -2) score -= longLessPenalty; - } - } - - // d. If score > bestScore, then - if (score > bestScore) { - // i. Let bestScore be score. - bestScore = score; - - // ii. Let bestFormat be format. - bestFormat = format; - } - - // e. Increase i by 1. - i++; - } - - // 13. Return bestFormat. - return bestFormat; -} - -/** - * When the BestFitFormatMatcher abstract operation is called with two arguments options - * and formats, it performs implementation dependent steps, which should return a set of - * component representations that a typical user of the selected locale would perceive as - * at least as good as the one returned by BasicFormatMatcher. - * - * This polyfill defines the algorithm to be the same as BasicFormatMatcher, - * with the addition of bonus points awarded where the requested format is of - * the same data type as the potentially matching format. - * - * This algo relies on the concept of closest distance matching described here: - * http://unicode.org/reports/tr35/tr35-dates.html#Matching_Skeletons - * Typically a “best match” is found using a closest distance match, such as: - * - * Symbols requesting a best choice for the locale are replaced. - * j → one of {H, k, h, K}; C → one of {a, b, B} - * -> Covered by cldr.js matching process - * - * For fields with symbols representing the same type (year, month, day, etc): - * Most symbols have a small distance from each other. - * M ≅ L; E ≅ c; a ≅ b ≅ B; H ≅ k ≅ h ≅ K; ... - * -> Covered by cldr.js matching process - * - * Width differences among fields, other than those marking text vs numeric, are given small distance from each other. - * MMM ≅ MMMM - * MM ≅ M - * Numeric and text fields are given a larger distance from each other. - * MMM ≈ MM - * Symbols representing substantial differences (week of year vs week of month) are given much larger a distances from each other. - * d ≋ D; ... - * Missing or extra fields cause a match to fail. (But see Missing Skeleton Fields). - * - * - * For example, - * - * { month: 'numeric', day: 'numeric' } - * - * should match - * - * { month: '2-digit', day: '2-digit' } - * - * rather than - * - * { month: 'short', day: 'numeric' } - * - * This makes sense because a user requesting a formatted date with numeric parts would - * not expect to see the returned format containing narrow, short or long part names - */ -function BestFitFormatMatcher(options, formats) { - /** Diverging: this block implements the hack for single property configuration, eg.: - * - * `new Intl.DateTimeFormat('en', {day: 'numeric'})` - * - * should produce a single digit with the day of the month. This is needed because - * CLDR `availableFormats` data structure doesn't cover these cases. - */ - { - var optionsPropNames = []; - for (var property in dateTimeComponents) { - if (!hop.call(dateTimeComponents, property)) continue; - - if (options['[[' + property + ']]'] !== undefined) { - optionsPropNames.push(property); - } - } - if (optionsPropNames.length === 1) { - var _bestFormat = generateSyntheticFormat(optionsPropNames[0], options['[[' + optionsPropNames[0] + ']]']); - if (_bestFormat) { - return _bestFormat; - } - } - } - - // 1. Let removalPenalty be 120. - var removalPenalty = 120; - - // 2. Let additionPenalty be 20. - var additionPenalty = 20; - - // 3. Let longLessPenalty be 8. - var longLessPenalty = 8; - - // 4. Let longMorePenalty be 6. - var longMorePenalty = 6; - - // 5. Let shortLessPenalty be 6. - var shortLessPenalty = 6; - - // 6. Let shortMorePenalty be 3. - var shortMorePenalty = 3; - - var patternPenalty = 2; - - var hour12Penalty = 1; - - // 7. Let bestScore be -Infinity. - var bestScore = -Infinity; - - // 8. Let bestFormat be undefined. - var bestFormat = void 0; - - // 9. Let i be 0. - var i = 0; - - // 10. Assert: formats is an Array object. - - // 11. Let len be the result of calling the [[Get]] internal method of formats with argument "length". - var len = formats.length; - - // 12. Repeat while i < len: - while (i < len) { - // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i). - var format = formats[i]; - - // b. Let score be 0. - var score = 0; - - // c. For each property shown in Table 3: - for (var _property in dateTimeComponents) { - if (!hop.call(dateTimeComponents, _property)) continue; - - // i. Let optionsProp be options.[[]]. - var optionsProp = options['[[' + _property + ']]']; - - // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format - // with argument property. - // iii. If formatPropDesc is not undefined, then - // 1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property. - var formatProp = hop.call(format, _property) ? format[_property] : undefined; - - // Diverging: using the default properties produced by the pattern/skeleton - // to match it with user options, and apply a penalty - var patternProp = hop.call(format._, _property) ? format._[_property] : undefined; - if (optionsProp !== patternProp) { - score -= patternPenalty; - } - - // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by - // additionPenalty. - if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty; - - // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by - // removalPenalty. - else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty; - - // vi. Else - else { - // 1. Let values be the array ["2-digit", "numeric", "narrow", "short", - // "long"]. - var values = ['2-digit', 'numeric', 'narrow', 'short', 'long']; - - // 2. Let optionsPropIndex be the index of optionsProp within values. - var optionsPropIndex = arrIndexOf.call(values, optionsProp); - - // 3. Let formatPropIndex be the index of formatProp within values. - var formatPropIndex = arrIndexOf.call(values, formatProp); - - // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2). - var delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2); - - { - // diverging from spec - // When the bestFit argument is true, subtract additional penalty where data types.js are not the same - if (formatPropIndex <= 1 && optionsPropIndex >= 2 || formatPropIndex >= 2 && optionsPropIndex <= 1) { - // 5. If delta = 2, decrease score by longMorePenalty. - if (delta > 0) score -= longMorePenalty;else if (delta < 0) score -= longLessPenalty; - } else { - // 5. If delta = 2, decrease score by longMorePenalty. - if (delta > 1) score -= shortMorePenalty;else if (delta < -1) score -= shortLessPenalty; - } - } - } - } - - { - // diverging to also take into consideration differences between 12 or 24 hours - // which is special for the best fit only. - if (format._.hour12 !== options.hour12) { - score -= hour12Penalty; - } - } - - // d. If score > bestScore, then - if (score > bestScore) { - // i. Let bestScore be score. - bestScore = score; - // ii. Let bestFormat be format. - bestFormat = format; - } - - // e. Increase i by 1. - i++; - } - - // 13. Return bestFormat. - return bestFormat; -} - -/* 12.2.3 */internals.DateTimeFormat = { - '[[availableLocales]]': [], - '[[relevantExtensionKeys]]': ['ca', 'nu'], - '[[localeData]]': {} -}; - -/** - * When the supportedLocalesOf method of Intl.DateTimeFormat is called, the - * following steps are taken: - */ -/* 12.2.2 */ -defineProperty(Intl$1.DateTimeFormat, 'supportedLocalesOf', { - configurable: true, - writable: true, - value: fnBind.call(function (locales) { - // Bound functions only have the `this` value altered if being used as a constructor, - // this lets us imitate a native function that has no constructor - if (!hop.call(this, '[[availableLocales]]')) throw new TypeError('supportedLocalesOf() is not a constructor'); - - // Create an object whose props can be used to restore the values of RegExp props - var regexpRestore = createRegExpRestore(), - - - // 1. If options is not provided, then let options be undefined. - options = arguments[1], - - - // 2. Let availableLocales be the value of the [[availableLocales]] internal - // property of the standard built-in object that is the initial value of - // Intl.NumberFormat. - - availableLocales = this['[[availableLocales]]'], - - - // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList - // abstract operation (defined in 9.2.1) with argument locales. - requestedLocales = CanonicalizeLocaleList(locales); - - // Restore the RegExp properties - regexpRestore(); - - // 4. Return the result of calling the SupportedLocales abstract operation - // (defined in 9.2.8) with arguments availableLocales, requestedLocales, - // and options. - return SupportedLocales(availableLocales, requestedLocales, options); - }, internals.NumberFormat) -}); - -/** - * This named accessor property returns a function that formats a number - * according to the effective locale and the formatting options of this - * DateTimeFormat object. - */ -/* 12.3.2 */defineProperty(Intl$1.DateTimeFormat.prototype, 'format', { - configurable: true, - get: GetFormatDateTime -}); - -function GetFormatDateTime() { - var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this); - - // Satisfy test 12.3_b - if (!internal || !internal['[[initializedDateTimeFormat]]']) throw new TypeError('`this` value for format() is not an initialized Intl.DateTimeFormat object.'); - - // The value of the [[Get]] attribute is a function that takes the following - // steps: - - // 1. If the [[boundFormat]] internal property of this DateTimeFormat object - // is undefined, then: - if (internal['[[boundFormat]]'] === undefined) { - // a. Let F be a Function object, with internal properties set as - // specified for built-in functions in ES5, 15, or successor, and the - // length property set to 0, that takes the argument date and - // performs the following steps: - var F = function F() { - var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - // i. If date is not provided or is undefined, then let x be the - // result as if by the expression Date.now() where Date.now is - // the standard built-in function defined in ES5, 15.9.4.4. - // ii. Else let x be ToNumber(date). - // iii. Return the result of calling the FormatDateTime abstract - // operation (defined below) with arguments this and x. - var x = date === undefined ? Date.now() : toNumber(date); - return FormatDateTime(this, x); - }; - // b. Let bind be the standard built-in function object defined in ES5, - // 15.3.4.5. - // c. Let bf be the result of calling the [[Call]] internal method of - // bind with F as the this value and an argument list containing - // the single item this. - var bf = fnBind.call(F, this); - // d. Set the [[boundFormat]] internal property of this NumberFormat - // object to bf. - internal['[[boundFormat]]'] = bf; - } - // Return the value of the [[boundFormat]] internal property of this - // NumberFormat object. - return internal['[[boundFormat]]']; -} - -function formatToParts$1() { - var date = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; - - var internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this); - - if (!internal || !internal['[[initializedDateTimeFormat]]']) throw new TypeError('`this` value for formatToParts() is not an initialized Intl.DateTimeFormat object.'); - - var x = date === undefined ? Date.now() : toNumber(date); - return FormatToPartsDateTime(this, x); -} - -Object.defineProperty(Intl$1.DateTimeFormat.prototype, 'formatToParts', { - enumerable: false, - writable: true, - configurable: true, - value: formatToParts$1 -}); - -function CreateDateTimeParts(dateTimeFormat, x) { - // 1. If x is not a finite Number, then throw a RangeError exception. - if (!isFinite(x)) throw new RangeError('Invalid valid date passed to format'); - - var internal = dateTimeFormat.__getInternalProperties(secret); - - // Creating restore point for properties on the RegExp object... please wait - /* let regexpRestore = */createRegExpRestore(); // ###TODO: review this - - // 2. Let locale be the value of the [[locale]] internal property of dateTimeFormat. - var locale = internal['[[locale]]']; - - // 3. Let nf be the result of creating a new NumberFormat object as if by the - // expression new Intl.NumberFormat([locale], {useGrouping: false}) where - // Intl.NumberFormat is the standard built-in constructor defined in 11.1.3. - var nf = new Intl$1.NumberFormat([locale], { useGrouping: false }); - - // 4. Let nf2 be the result of creating a new NumberFormat object as if by the - // expression new Intl.NumberFormat([locale], {minimumIntegerDigits: 2, useGrouping: - // false}) where Intl.NumberFormat is the standard built-in constructor defined in - // 11.1.3. - var nf2 = new Intl$1.NumberFormat([locale], { minimumIntegerDigits: 2, useGrouping: false }); - - // 5. Let tm be the result of calling the ToLocalTime abstract operation (defined - // below) with x, the value of the [[calendar]] internal property of dateTimeFormat, - // and the value of the [[timeZone]] internal property of dateTimeFormat. - var tm = ToLocalTime(x, internal['[[calendar]]'], internal['[[timeZone]]']); - - // 6. Let result be the value of the [[pattern]] internal property of dateTimeFormat. - var pattern = internal['[[pattern]]']; - - // 7. - var result = new List(); - - // 8. - var index = 0; - - // 9. - var beginIndex = pattern.indexOf('{'); - - // 10. - var endIndex = 0; - - // Need the locale minus any extensions - var dataLocale = internal['[[dataLocale]]']; - - // Need the calendar data from CLDR - var localeData = internals.DateTimeFormat['[[localeData]]'][dataLocale].calendars; - var ca = internal['[[calendar]]']; - - // 11. - while (beginIndex !== -1) { - var fv = void 0; - // a. - endIndex = pattern.indexOf('}', beginIndex); - // b. - if (endIndex === -1) { - throw new Error('Unclosed pattern'); - } - // c. - if (beginIndex > index) { - arrPush.call(result, { - type: 'literal', - value: pattern.substring(index, beginIndex) - }); - } - // d. - var p = pattern.substring(beginIndex + 1, endIndex); - // e. - if (dateTimeComponents.hasOwnProperty(p)) { - // i. Let f be the value of the [[

]] internal property of dateTimeFormat. - var f = internal['[[' + p + ']]']; - // ii. Let v be the value of tm.[[

]]. - var v = tm['[[' + p + ']]']; - // iii. If p is "year" and v ≤ 0, then let v be 1 - v. - if (p === 'year' && v <= 0) { - v = 1 - v; - } - // iv. If p is "month", then increase v by 1. - else if (p === 'month') { - v++; - } - // v. If p is "hour" and the value of the [[hour12]] internal property of - // dateTimeFormat is true, then - else if (p === 'hour' && internal['[[hour12]]'] === true) { - // 1. Let v be v modulo 12. - v = v % 12; - // 2. If v is 0 and the value of the [[hourNo0]] internal property of - // dateTimeFormat is true, then let v be 12. - if (v === 0 && internal['[[hourNo0]]'] === true) { - v = 12; - } - } - - // vi. If f is "numeric", then - if (f === 'numeric') { - // 1. Let fv be the result of calling the FormatNumber abstract operation - // (defined in 11.3.2) with arguments nf and v. - fv = FormatNumber(nf, v); - } - // vii. Else if f is "2-digit", then - else if (f === '2-digit') { - // 1. Let fv be the result of calling the FormatNumber abstract operation - // with arguments nf2 and v. - fv = FormatNumber(nf2, v); - // 2. If the length of fv is greater than 2, let fv be the substring of fv - // containing the last two characters. - if (fv.length > 2) { - fv = fv.slice(-2); - } - } - // viii. Else if f is "narrow", "short", or "long", then let fv be a String - // value representing f in the desired form; the String value depends upon - // the implementation and the effective locale and calendar of - // dateTimeFormat. If p is "month", then the String value may also depend - // on whether dateTimeFormat has a [[day]] internal property. If p is - // "timeZoneName", then the String value may also depend on the value of - // the [[inDST]] field of tm. - else if (f in dateWidths) { - switch (p) { - case 'month': - fv = resolveDateString(localeData, ca, 'months', f, tm['[[' + p + ']]']); - break; - - case 'weekday': - try { - fv = resolveDateString(localeData, ca, 'days', f, tm['[[' + p + ']]']); - // fv = resolveDateString(ca.days, f)[tm['[['+ p +']]']]; - } catch (e) { - throw new Error('Could not find weekday data for locale ' + locale); - } - break; - - case 'timeZoneName': - fv = ''; // ###TODO - break; - - case 'era': - try { - fv = resolveDateString(localeData, ca, 'eras', f, tm['[[' + p + ']]']); - } catch (e) { - throw new Error('Could not find era data for locale ' + locale); - } - break; - - default: - fv = tm['[[' + p + ']]']; - } - } - // ix - arrPush.call(result, { - type: p, - value: fv - }); - // f. - } else if (p === 'ampm') { - // i. - var _v = tm['[[hour]]']; - // ii./iii. - fv = resolveDateString(localeData, ca, 'dayPeriods', _v > 11 ? 'pm' : 'am', null); - // iv. - arrPush.call(result, { - type: 'dayPeriod', - value: fv - }); - // g. - } else { - arrPush.call(result, { - type: 'literal', - value: pattern.substring(beginIndex, endIndex + 1) - }); - } - // h. - index = endIndex + 1; - // i. - beginIndex = pattern.indexOf('{', index); - } - // 12. - if (endIndex < pattern.length - 1) { - arrPush.call(result, { - type: 'literal', - value: pattern.substr(endIndex + 1) - }); - } - // 13. - return result; -} - -/** - * When the FormatDateTime abstract operation is called with arguments dateTimeFormat - * (which must be an object initialized as a DateTimeFormat) and x (which must be a Number - * value), it returns a String value representing x (interpreted as a time value as - * specified in ES5, 15.9.1.1) according to the effective locale and the formatting - * options of dateTimeFormat. - */ -function FormatDateTime(dateTimeFormat, x) { - var parts = CreateDateTimeParts(dateTimeFormat, x); - var result = ''; - - for (var i = 0; parts.length > i; i++) { - var part = parts[i]; - result += part.value; - } - return result; -} - -function FormatToPartsDateTime(dateTimeFormat, x) { - var parts = CreateDateTimeParts(dateTimeFormat, x); - var result = []; - for (var i = 0; parts.length > i; i++) { - var part = parts[i]; - result.push({ - type: part.type, - value: part.value - }); - } - return result; -} - -/** - * When the ToLocalTime abstract operation is called with arguments date, calendar, and - * timeZone, the following steps are taken: - */ -function ToLocalTime(date, calendar, timeZone) { - // 1. Apply calendrical calculations on date for the given calendar and time zone to - // produce weekday, era, year, month, day, hour, minute, second, and inDST values. - // The calculations should use best available information about the specified - // calendar and time zone. If the calendar is "gregory", then the calculations must - // match the algorithms specified in ES5, 15.9.1, except that calculations are not - // bound by the restrictions on the use of best available information on time zones - // for local time zone adjustment and daylight saving time adjustment imposed by - // ES5, 15.9.1.7 and 15.9.1.8. - // ###TODO### - var d = new Date(date), - m = 'get' + (timeZone || ''); - - // 2. Return a Record with fields [[weekday]], [[era]], [[year]], [[month]], [[day]], - // [[hour]], [[minute]], [[second]], and [[inDST]], each with the corresponding - // calculated value. - return new Record({ - '[[weekday]]': d[m + 'Day'](), - '[[era]]': +(d[m + 'FullYear']() >= 0), - '[[year]]': d[m + 'FullYear'](), - '[[month]]': d[m + 'Month'](), - '[[day]]': d[m + 'Date'](), - '[[hour]]': d[m + 'Hours'](), - '[[minute]]': d[m + 'Minutes'](), - '[[second]]': d[m + 'Seconds'](), - '[[inDST]]': false // ###TODO### - }); -} - -/** - * The function returns a new object whose properties and attributes are set as if - * constructed by an object literal assigning to each of the following properties the - * value of the corresponding internal property of this DateTimeFormat object (see 12.4): - * locale, calendar, numberingSystem, timeZone, hour12, weekday, era, year, month, day, - * hour, minute, second, and timeZoneName. Properties whose corresponding internal - * properties are not present are not assigned. - */ -/* 12.3.3 */defineProperty(Intl$1.DateTimeFormat.prototype, 'resolvedOptions', { - writable: true, - configurable: true, - value: function value() { - var prop = void 0, - descs = new Record(), - props = ['locale', 'calendar', 'numberingSystem', 'timeZone', 'hour12', 'weekday', 'era', 'year', 'month', 'day', 'hour', 'minute', 'second', 'timeZoneName'], - internal = this !== null && babelHelpers$1["typeof"](this) === 'object' && getInternalProperties(this); - - // Satisfy test 12.3_b - if (!internal || !internal['[[initializedDateTimeFormat]]']) throw new TypeError('`this` value for resolvedOptions() is not an initialized Intl.DateTimeFormat object.'); - - for (var i = 0, max = props.length; i < max; i++) { - if (hop.call(internal, prop = '[[' + props[i] + ']]')) descs[props[i]] = { value: internal[prop], writable: true, configurable: true, enumerable: true }; - } - - return objCreate({}, descs); - } -}); - -// Sect 13 Locale Sensitive Functions of the ECMAScript Language Specification -// =========================================================================== - -var ls = Intl$1.__localeSensitiveProtos = { - Number: {}, - Date: {} -}; - -/** - * When the toLocaleString method is called with optional arguments locales and options, - * the following steps are taken: - */ -/* 13.2.1 */ls.Number.toLocaleString = function () { - // Satisfy test 13.2.1_1 - if (Object.prototype.toString.call(this) !== '[object Number]') throw new TypeError('`this` value must be a number for Number.prototype.toLocaleString()'); - - // 1. Let x be this Number value (as defined in ES5, 15.7.4). - // 2. If locales is not provided, then let locales be undefined. - // 3. If options is not provided, then let options be undefined. - // 4. Let numberFormat be the result of creating a new object as if by the - // expression new Intl.NumberFormat(locales, options) where - // Intl.NumberFormat is the standard built-in constructor defined in 11.1.3. - // 5. Return the result of calling the FormatNumber abstract operation - // (defined in 11.3.2) with arguments numberFormat and x. - return FormatNumber(new NumberFormatConstructor(arguments[0], arguments[1]), this); -}; - -/** - * When the toLocaleString method is called with optional arguments locales and options, - * the following steps are taken: - */ -/* 13.3.1 */ls.Date.toLocaleString = function () { - // Satisfy test 13.3.0_1 - if (Object.prototype.toString.call(this) !== '[object Date]') throw new TypeError('`this` value must be a Date instance for Date.prototype.toLocaleString()'); - - // 1. Let x be this time value (as defined in ES5, 15.9.5). - var x = +this; - - // 2. If x is NaN, then return "Invalid Date". - if (isNaN(x)) return 'Invalid Date'; - - // 3. If locales is not provided, then let locales be undefined. - var locales = arguments[0]; - - // 4. If options is not provided, then let options be undefined. - var options = arguments[1]; - - // 5. Let options be the result of calling the ToDateTimeOptions abstract - // operation (defined in 12.1.1) with arguments options, "any", and "all". - options = ToDateTimeOptions(options, 'any', 'all'); - - // 6. Let dateTimeFormat be the result of creating a new object as if by the - // expression new Intl.DateTimeFormat(locales, options) where - // Intl.DateTimeFormat is the standard built-in constructor defined in 12.1.3. - var dateTimeFormat = new DateTimeFormatConstructor(locales, options); - - // 7. Return the result of calling the FormatDateTime abstract operation (defined - // in 12.3.2) with arguments dateTimeFormat and x. - return FormatDateTime(dateTimeFormat, x); -}; - -/** - * When the toLocaleDateString method is called with optional arguments locales and - * options, the following steps are taken: - */ -/* 13.3.2 */ls.Date.toLocaleDateString = function () { - // Satisfy test 13.3.0_1 - if (Object.prototype.toString.call(this) !== '[object Date]') throw new TypeError('`this` value must be a Date instance for Date.prototype.toLocaleDateString()'); - - // 1. Let x be this time value (as defined in ES5, 15.9.5). - var x = +this; - - // 2. If x is NaN, then return "Invalid Date". - if (isNaN(x)) return 'Invalid Date'; - - // 3. If locales is not provided, then let locales be undefined. - var locales = arguments[0], - - - // 4. If options is not provided, then let options be undefined. - options = arguments[1]; - - // 5. Let options be the result of calling the ToDateTimeOptions abstract - // operation (defined in 12.1.1) with arguments options, "date", and "date". - options = ToDateTimeOptions(options, 'date', 'date'); - - // 6. Let dateTimeFormat be the result of creating a new object as if by the - // expression new Intl.DateTimeFormat(locales, options) where - // Intl.DateTimeFormat is the standard built-in constructor defined in 12.1.3. - var dateTimeFormat = new DateTimeFormatConstructor(locales, options); - - // 7. Return the result of calling the FormatDateTime abstract operation (defined - // in 12.3.2) with arguments dateTimeFormat and x. - return FormatDateTime(dateTimeFormat, x); -}; - -/** - * When the toLocaleTimeString method is called with optional arguments locales and - * options, the following steps are taken: - */ -/* 13.3.3 */ls.Date.toLocaleTimeString = function () { - // Satisfy test 13.3.0_1 - if (Object.prototype.toString.call(this) !== '[object Date]') throw new TypeError('`this` value must be a Date instance for Date.prototype.toLocaleTimeString()'); - - // 1. Let x be this time value (as defined in ES5, 15.9.5). - var x = +this; - - // 2. If x is NaN, then return "Invalid Date". - if (isNaN(x)) return 'Invalid Date'; - - // 3. If locales is not provided, then let locales be undefined. - var locales = arguments[0]; - - // 4. If options is not provided, then let options be undefined. - var options = arguments[1]; - - // 5. Let options be the result of calling the ToDateTimeOptions abstract - // operation (defined in 12.1.1) with arguments options, "time", and "time". - options = ToDateTimeOptions(options, 'time', 'time'); - - // 6. Let dateTimeFormat be the result of creating a new object as if by the - // expression new Intl.DateTimeFormat(locales, options) where - // Intl.DateTimeFormat is the standard built-in constructor defined in 12.1.3. - var dateTimeFormat = new DateTimeFormatConstructor(locales, options); - - // 7. Return the result of calling the FormatDateTime abstract operation (defined - // in 12.3.2) with arguments dateTimeFormat and x. - return FormatDateTime(dateTimeFormat, x); -}; - -var _cp = [function (n, ord) { - if (ord) return 'other'; - return 'other'; -}, function (n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : 'other'; -}, function (n, ord) { - if (ord) return 'other'; - return n == 0 || n == 1 ? 'one' : 'other'; -}, function (n, ord) { - var s = String(n).split('.'), - v0 = !s[1]; - if (ord) return 'other'; - return n == 1 && v0 ? 'one' : 'other'; -}]; - -var plurals = { - af: _cp[1], - - ak: _cp[2], - - am: function am(n, ord) { - if (ord) return 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - ar: function ar(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n, - n100 = t0 && s[0].slice(-2); - if (ord) return 'other'; - return n == 0 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n100 >= 3 && n100 <= 10 ? 'few' : n100 >= 11 && n100 <= 99 ? 'many' : 'other'; - }, - - ars: function ars(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n, - n100 = t0 && s[0].slice(-2); - if (ord) return 'other'; - return n == 0 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n100 >= 3 && n100 <= 10 ? 'few' : n100 >= 11 && n100 <= 99 ? 'many' : 'other'; - }, - - as: function as(n, ord) { - if (ord) return n == 1 || n == 5 || n == 7 || n == 8 || n == 9 || n == 10 ? 'one' : n == 2 || n == 3 ? 'two' : n == 4 ? 'few' : n == 6 ? 'many' : 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - asa: _cp[1], - - ast: _cp[3], - - az: function az(n, ord) { - var s = String(n).split('.'), - i = s[0], - i10 = i.slice(-1), - i100 = i.slice(-2), - i1000 = i.slice(-3); - if (ord) return i10 == 1 || i10 == 2 || i10 == 5 || i10 == 7 || i10 == 8 || i100 == 20 || i100 == 50 || i100 == 70 || i100 == 80 ? 'one' : i10 == 3 || i10 == 4 || i1000 == 100 || i1000 == 200 || i1000 == 300 || i1000 == 400 || i1000 == 500 || i1000 == 600 || i1000 == 700 || i1000 == 800 || i1000 == 900 ? 'few' : i == 0 || i10 == 6 || i100 == 40 || i100 == 60 || i100 == 90 ? 'many' : 'other'; - return n == 1 ? 'one' : 'other'; - }, - - be: function be(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2); - if (ord) return (n10 == 2 || n10 == 3) && n100 != 12 && n100 != 13 ? 'few' : 'other'; - return n10 == 1 && n100 != 11 ? 'one' : n10 >= 2 && n10 <= 4 && (n100 < 12 || n100 > 14) ? 'few' : t0 && n10 == 0 || n10 >= 5 && n10 <= 9 || n100 >= 11 && n100 <= 14 ? 'many' : 'other'; - }, - - bem: _cp[1], - - bez: _cp[1], - - bg: _cp[1], - - bh: _cp[2], - - bm: _cp[0], - - bn: function bn(n, ord) { - if (ord) return n == 1 || n == 5 || n == 7 || n == 8 || n == 9 || n == 10 ? 'one' : n == 2 || n == 3 ? 'two' : n == 4 ? 'few' : n == 6 ? 'many' : 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - bo: _cp[0], - - br: function br(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2), - n1000000 = t0 && s[0].slice(-6); - if (ord) return 'other'; - return n10 == 1 && n100 != 11 && n100 != 71 && n100 != 91 ? 'one' : n10 == 2 && n100 != 12 && n100 != 72 && n100 != 92 ? 'two' : (n10 == 3 || n10 == 4 || n10 == 9) && (n100 < 10 || n100 > 19) && (n100 < 70 || n100 > 79) && (n100 < 90 || n100 > 99) ? 'few' : n != 0 && t0 && n1000000 == 0 ? 'many' : 'other'; - }, - - brx: _cp[1], - - bs: function bs(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2), - f10 = f.slice(-1), - f100 = f.slice(-2); - if (ord) return 'other'; - return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) || f10 >= 2 && f10 <= 4 && (f100 < 12 || f100 > 14) ? 'few' : 'other'; - }, - - ca: function ca(n, ord) { - var s = String(n).split('.'), - v0 = !s[1]; - if (ord) return n == 1 || n == 3 ? 'one' : n == 2 ? 'two' : n == 4 ? 'few' : 'other'; - return n == 1 && v0 ? 'one' : 'other'; - }, - - ce: _cp[1], - - cgg: _cp[1], - - chr: _cp[1], - - ckb: _cp[1], - - cs: function cs(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1]; - if (ord) return 'other'; - return n == 1 && v0 ? 'one' : i >= 2 && i <= 4 && v0 ? 'few' : !v0 ? 'many' : 'other'; - }, - - cy: function cy(n, ord) { - if (ord) return n == 0 || n == 7 || n == 8 || n == 9 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n == 3 || n == 4 ? 'few' : n == 5 || n == 6 ? 'many' : 'other'; - return n == 0 ? 'zero' : n == 1 ? 'one' : n == 2 ? 'two' : n == 3 ? 'few' : n == 6 ? 'many' : 'other'; - }, - - da: function da(n, ord) { - var s = String(n).split('.'), - i = s[0], - t0 = Number(s[0]) == n; - if (ord) return 'other'; - return n == 1 || !t0 && (i == 0 || i == 1) ? 'one' : 'other'; - }, - - de: _cp[3], - - dsb: function dsb(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i100 = i.slice(-2), - f100 = f.slice(-2); - if (ord) return 'other'; - return v0 && i100 == 1 || f100 == 1 ? 'one' : v0 && i100 == 2 || f100 == 2 ? 'two' : v0 && (i100 == 3 || i100 == 4) || f100 == 3 || f100 == 4 ? 'few' : 'other'; - }, - - dv: _cp[1], - - dz: _cp[0], - - ee: _cp[1], - - el: _cp[1], - - en: function en(n, ord) { - var s = String(n).split('.'), - v0 = !s[1], - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2); - if (ord) return n10 == 1 && n100 != 11 ? 'one' : n10 == 2 && n100 != 12 ? 'two' : n10 == 3 && n100 != 13 ? 'few' : 'other'; - return n == 1 && v0 ? 'one' : 'other'; - }, - - eo: _cp[1], - - es: _cp[1], - - et: _cp[3], - - eu: _cp[1], - - fa: function fa(n, ord) { - if (ord) return 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - ff: function ff(n, ord) { - if (ord) return 'other'; - return n >= 0 && n < 2 ? 'one' : 'other'; - }, - - fi: _cp[3], - - fil: function fil(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i10 = i.slice(-1), - f10 = f.slice(-1); - if (ord) return n == 1 ? 'one' : 'other'; - return v0 && (i == 1 || i == 2 || i == 3) || v0 && i10 != 4 && i10 != 6 && i10 != 9 || !v0 && f10 != 4 && f10 != 6 && f10 != 9 ? 'one' : 'other'; - }, - - fo: _cp[1], - - fr: function fr(n, ord) { - if (ord) return n == 1 ? 'one' : 'other'; - return n >= 0 && n < 2 ? 'one' : 'other'; - }, - - fur: _cp[1], - - fy: _cp[3], - - ga: function ga(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n; - if (ord) return n == 1 ? 'one' : 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : t0 && n >= 3 && n <= 6 ? 'few' : t0 && n >= 7 && n <= 10 ? 'many' : 'other'; - }, - - gd: function gd(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n; - if (ord) return 'other'; - return n == 1 || n == 11 ? 'one' : n == 2 || n == 12 ? 'two' : t0 && n >= 3 && n <= 10 || t0 && n >= 13 && n <= 19 ? 'few' : 'other'; - }, - - gl: _cp[3], - - gsw: _cp[1], - - gu: function gu(n, ord) { - if (ord) return n == 1 ? 'one' : n == 2 || n == 3 ? 'two' : n == 4 ? 'few' : n == 6 ? 'many' : 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - guw: _cp[2], - - gv: function gv(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2); - if (ord) return 'other'; - return v0 && i10 == 1 ? 'one' : v0 && i10 == 2 ? 'two' : v0 && (i100 == 0 || i100 == 20 || i100 == 40 || i100 == 60 || i100 == 80) ? 'few' : !v0 ? 'many' : 'other'; - }, - - ha: _cp[1], - - haw: _cp[1], - - he: function he(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1], - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1); - if (ord) return 'other'; - return n == 1 && v0 ? 'one' : i == 2 && v0 ? 'two' : v0 && (n < 0 || n > 10) && t0 && n10 == 0 ? 'many' : 'other'; - }, - - hi: function hi(n, ord) { - if (ord) return n == 1 ? 'one' : n == 2 || n == 3 ? 'two' : n == 4 ? 'few' : n == 6 ? 'many' : 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - hr: function hr(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2), - f10 = f.slice(-1), - f100 = f.slice(-2); - if (ord) return 'other'; - return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) || f10 >= 2 && f10 <= 4 && (f100 < 12 || f100 > 14) ? 'few' : 'other'; - }, - - hsb: function hsb(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i100 = i.slice(-2), - f100 = f.slice(-2); - if (ord) return 'other'; - return v0 && i100 == 1 || f100 == 1 ? 'one' : v0 && i100 == 2 || f100 == 2 ? 'two' : v0 && (i100 == 3 || i100 == 4) || f100 == 3 || f100 == 4 ? 'few' : 'other'; - }, - - hu: function hu(n, ord) { - if (ord) return n == 1 || n == 5 ? 'one' : 'other'; - return n == 1 ? 'one' : 'other'; - }, - - hy: function hy(n, ord) { - if (ord) return n == 1 ? 'one' : 'other'; - return n >= 0 && n < 2 ? 'one' : 'other'; - }, - - id: _cp[0], - - ig: _cp[0], - - ii: _cp[0], - - "in": _cp[0], - - is: function is(n, ord) { - var s = String(n).split('.'), - i = s[0], - t0 = Number(s[0]) == n, - i10 = i.slice(-1), - i100 = i.slice(-2); - if (ord) return 'other'; - return t0 && i10 == 1 && i100 != 11 || !t0 ? 'one' : 'other'; - }, - - it: function it(n, ord) { - var s = String(n).split('.'), - v0 = !s[1]; - if (ord) return n == 11 || n == 8 || n == 80 || n == 800 ? 'many' : 'other'; - return n == 1 && v0 ? 'one' : 'other'; - }, - - iu: function iu(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - iw: function iw(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1], - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1); - if (ord) return 'other'; - return n == 1 && v0 ? 'one' : i == 2 && v0 ? 'two' : v0 && (n < 0 || n > 10) && t0 && n10 == 0 ? 'many' : 'other'; - }, - - ja: _cp[0], - - jbo: _cp[0], - - jgo: _cp[1], - - ji: _cp[3], - - jmc: _cp[1], - - jv: _cp[0], - - jw: _cp[0], - - ka: function ka(n, ord) { - var s = String(n).split('.'), - i = s[0], - i100 = i.slice(-2); - if (ord) return i == 1 ? 'one' : i == 0 || i100 >= 2 && i100 <= 20 || i100 == 40 || i100 == 60 || i100 == 80 ? 'many' : 'other'; - return n == 1 ? 'one' : 'other'; - }, - - kab: function kab(n, ord) { - if (ord) return 'other'; - return n >= 0 && n < 2 ? 'one' : 'other'; - }, - - kaj: _cp[1], - - kcg: _cp[1], - - kde: _cp[0], - - kea: _cp[0], - - kk: function kk(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1); - if (ord) return n10 == 6 || n10 == 9 || t0 && n10 == 0 && n != 0 ? 'many' : 'other'; - return n == 1 ? 'one' : 'other'; - }, - - kkj: _cp[1], - - kl: _cp[1], - - km: _cp[0], - - kn: function kn(n, ord) { - if (ord) return 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - ko: _cp[0], - - ks: _cp[1], - - ksb: _cp[1], - - ksh: function ksh(n, ord) { - if (ord) return 'other'; - return n == 0 ? 'zero' : n == 1 ? 'one' : 'other'; - }, - - ku: _cp[1], - - kw: function kw(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - ky: _cp[1], - - lag: function lag(n, ord) { - var s = String(n).split('.'), - i = s[0]; - if (ord) return 'other'; - return n == 0 ? 'zero' : (i == 0 || i == 1) && n != 0 ? 'one' : 'other'; - }, - - lb: _cp[1], - - lg: _cp[1], - - lkt: _cp[0], - - ln: _cp[2], - - lo: function lo(n, ord) { - if (ord) return n == 1 ? 'one' : 'other'; - return 'other'; - }, - - lt: function lt(n, ord) { - var s = String(n).split('.'), - f = s[1] || '', - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2); - if (ord) return 'other'; - return n10 == 1 && (n100 < 11 || n100 > 19) ? 'one' : n10 >= 2 && n10 <= 9 && (n100 < 11 || n100 > 19) ? 'few' : f != 0 ? 'many' : 'other'; - }, - - lv: function lv(n, ord) { - var s = String(n).split('.'), - f = s[1] || '', - v = f.length, - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2), - f100 = f.slice(-2), - f10 = f.slice(-1); - if (ord) return 'other'; - return t0 && n10 == 0 || n100 >= 11 && n100 <= 19 || v == 2 && f100 >= 11 && f100 <= 19 ? 'zero' : n10 == 1 && n100 != 11 || v == 2 && f10 == 1 && f100 != 11 || v != 2 && f10 == 1 ? 'one' : 'other'; - }, - - mas: _cp[1], - - mg: _cp[2], - - mgo: _cp[1], - - mk: function mk(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2), - f10 = f.slice(-1); - if (ord) return i10 == 1 && i100 != 11 ? 'one' : i10 == 2 && i100 != 12 ? 'two' : (i10 == 7 || i10 == 8) && i100 != 17 && i100 != 18 ? 'many' : 'other'; - return v0 && i10 == 1 || f10 == 1 ? 'one' : 'other'; - }, - - ml: _cp[1], - - mn: _cp[1], - - mo: function mo(n, ord) { - var s = String(n).split('.'), - v0 = !s[1], - t0 = Number(s[0]) == n, - n100 = t0 && s[0].slice(-2); - if (ord) return n == 1 ? 'one' : 'other'; - return n == 1 && v0 ? 'one' : !v0 || n == 0 || n != 1 && n100 >= 1 && n100 <= 19 ? 'few' : 'other'; - }, - - mr: function mr(n, ord) { - if (ord) return n == 1 ? 'one' : n == 2 || n == 3 ? 'two' : n == 4 ? 'few' : 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - }, - - ms: function ms(n, ord) { - if (ord) return n == 1 ? 'one' : 'other'; - return 'other'; - }, - - mt: function mt(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n, - n100 = t0 && s[0].slice(-2); - if (ord) return 'other'; - return n == 1 ? 'one' : n == 0 || n100 >= 2 && n100 <= 10 ? 'few' : n100 >= 11 && n100 <= 19 ? 'many' : 'other'; - }, - - my: _cp[0], - - nah: _cp[1], - - naq: function naq(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - nb: _cp[1], - - nd: _cp[1], - - ne: function ne(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n; - if (ord) return t0 && n >= 1 && n <= 4 ? 'one' : 'other'; - return n == 1 ? 'one' : 'other'; - }, - - nl: _cp[3], - - nn: _cp[1], - - nnh: _cp[1], - - no: _cp[1], - - nqo: _cp[0], - - nr: _cp[1], - - nso: _cp[2], - - ny: _cp[1], - - nyn: _cp[1], - - om: _cp[1], - - or: _cp[1], - - os: _cp[1], - - pa: _cp[2], - - pap: _cp[1], - - pl: function pl(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2); - if (ord) return 'other'; - return n == 1 && v0 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) ? 'few' : v0 && i != 1 && (i10 == 0 || i10 == 1) || v0 && i10 >= 5 && i10 <= 9 || v0 && i100 >= 12 && i100 <= 14 ? 'many' : 'other'; - }, - - prg: function prg(n, ord) { - var s = String(n).split('.'), - f = s[1] || '', - v = f.length, - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2), - f100 = f.slice(-2), - f10 = f.slice(-1); - if (ord) return 'other'; - return t0 && n10 == 0 || n100 >= 11 && n100 <= 19 || v == 2 && f100 >= 11 && f100 <= 19 ? 'zero' : n10 == 1 && n100 != 11 || v == 2 && f10 == 1 && f100 != 11 || v != 2 && f10 == 1 ? 'one' : 'other'; - }, - - ps: _cp[1], - - pt: function pt(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n; - if (ord) return 'other'; - return t0 && n >= 0 && n <= 2 && n != 2 ? 'one' : 'other'; - }, - - "pt-PT": _cp[3], - - rm: _cp[1], - - ro: function ro(n, ord) { - var s = String(n).split('.'), - v0 = !s[1], - t0 = Number(s[0]) == n, - n100 = t0 && s[0].slice(-2); - if (ord) return n == 1 ? 'one' : 'other'; - return n == 1 && v0 ? 'one' : !v0 || n == 0 || n != 1 && n100 >= 1 && n100 <= 19 ? 'few' : 'other'; - }, - - rof: _cp[1], - - root: _cp[0], - - ru: function ru(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2); - if (ord) return 'other'; - return v0 && i10 == 1 && i100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) ? 'few' : v0 && i10 == 0 || v0 && i10 >= 5 && i10 <= 9 || v0 && i100 >= 11 && i100 <= 14 ? 'many' : 'other'; - }, - - rwk: _cp[1], - - sah: _cp[0], - - saq: _cp[1], - - sdh: _cp[1], - - se: function se(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - seh: _cp[1], - - ses: _cp[0], - - sg: _cp[0], - - sh: function sh(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2), - f10 = f.slice(-1), - f100 = f.slice(-2); - if (ord) return 'other'; - return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) || f10 >= 2 && f10 <= 4 && (f100 < 12 || f100 > 14) ? 'few' : 'other'; - }, - - shi: function shi(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n; - if (ord) return 'other'; - return n >= 0 && n <= 1 ? 'one' : t0 && n >= 2 && n <= 10 ? 'few' : 'other'; - }, - - si: function si(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || ''; - if (ord) return 'other'; - return n == 0 || n == 1 || i == 0 && f == 1 ? 'one' : 'other'; - }, - - sk: function sk(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1]; - if (ord) return 'other'; - return n == 1 && v0 ? 'one' : i >= 2 && i <= 4 && v0 ? 'few' : !v0 ? 'many' : 'other'; - }, - - sl: function sl(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1], - i100 = i.slice(-2); - if (ord) return 'other'; - return v0 && i100 == 1 ? 'one' : v0 && i100 == 2 ? 'two' : v0 && (i100 == 3 || i100 == 4) || !v0 ? 'few' : 'other'; - }, - - sma: function sma(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - smi: function smi(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - smj: function smj(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - smn: function smn(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - sms: function sms(n, ord) { - if (ord) return 'other'; - return n == 1 ? 'one' : n == 2 ? 'two' : 'other'; - }, - - sn: _cp[1], - - so: _cp[1], - - sq: function sq(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2); - if (ord) return n == 1 ? 'one' : n10 == 4 && n100 != 14 ? 'many' : 'other'; - return n == 1 ? 'one' : 'other'; - }, - - sr: function sr(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i10 = i.slice(-1), - i100 = i.slice(-2), - f10 = f.slice(-1), - f100 = f.slice(-2); - if (ord) return 'other'; - return v0 && i10 == 1 && i100 != 11 || f10 == 1 && f100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) || f10 >= 2 && f10 <= 4 && (f100 < 12 || f100 > 14) ? 'few' : 'other'; - }, - - ss: _cp[1], - - ssy: _cp[1], - - st: _cp[1], - - sv: function sv(n, ord) { - var s = String(n).split('.'), - v0 = !s[1], - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2); - if (ord) return (n10 == 1 || n10 == 2) && n100 != 11 && n100 != 12 ? 'one' : 'other'; - return n == 1 && v0 ? 'one' : 'other'; - }, - - sw: _cp[3], - - syr: _cp[1], - - ta: _cp[1], - - te: _cp[1], - - teo: _cp[1], - - th: _cp[0], - - ti: _cp[2], - - tig: _cp[1], - - tk: _cp[1], - - tl: function tl(n, ord) { - var s = String(n).split('.'), - i = s[0], - f = s[1] || '', - v0 = !s[1], - i10 = i.slice(-1), - f10 = f.slice(-1); - if (ord) return n == 1 ? 'one' : 'other'; - return v0 && (i == 1 || i == 2 || i == 3) || v0 && i10 != 4 && i10 != 6 && i10 != 9 || !v0 && f10 != 4 && f10 != 6 && f10 != 9 ? 'one' : 'other'; - }, - - tn: _cp[1], - - to: _cp[0], - - tr: _cp[1], - - ts: _cp[1], - - tzm: function tzm(n, ord) { - var s = String(n).split('.'), - t0 = Number(s[0]) == n; - if (ord) return 'other'; - return n == 0 || n == 1 || t0 && n >= 11 && n <= 99 ? 'one' : 'other'; - }, - - ug: _cp[1], - - uk: function uk(n, ord) { - var s = String(n).split('.'), - i = s[0], - v0 = !s[1], - t0 = Number(s[0]) == n, - n10 = t0 && s[0].slice(-1), - n100 = t0 && s[0].slice(-2), - i10 = i.slice(-1), - i100 = i.slice(-2); - if (ord) return n10 == 3 && n100 != 13 ? 'few' : 'other'; - return v0 && i10 == 1 && i100 != 11 ? 'one' : v0 && i10 >= 2 && i10 <= 4 && (i100 < 12 || i100 > 14) ? 'few' : v0 && i10 == 0 || v0 && i10 >= 5 && i10 <= 9 || v0 && i100 >= 11 && i100 <= 14 ? 'many' : 'other'; - }, - - ur: _cp[3], - - uz: _cp[1], - - ve: _cp[1], - - vi: function vi(n, ord) { - if (ord) return n == 1 ? 'one' : 'other'; - return 'other'; - }, - - vo: _cp[1], - - vun: _cp[1], - - wa: _cp[2], - - wae: _cp[1], - - wo: _cp[0], - - xh: _cp[1], - - xog: _cp[1], - - yi: _cp[3], - - yo: _cp[0], - - yue: _cp[0], - - zh: _cp[0], - - zu: function zu(n, ord) { - if (ord) return 'other'; - return n >= 0 && n <= 1 ? 'one' : 'other'; - } -}; - -function PluralRules() { - var locales = arguments[0]; - var options = arguments[1]; - - if (!this || this === Intl$1) { - return new Intl$1.PluralRules(locales, options); - } - return InitializePluralRules(toObject(this), locales, options); -} - -defineProperty(Intl$1, 'PluralRules', { - configurable: true, - writable: true, - value: PluralRules -}); - -defineProperty(PluralRules, 'prototype', { - writable: false -}); - -function InitializePluralRules(pluralRules, locales, options) { - var internal = getInternalProperties(pluralRules); - - // 1. If pluralRules.[[InitializedIntlObject]] is true, throw a TypeError exception. - if (internal['[[InitializedIntlObject]]'] === true) throw new TypeError('`this` object has already been initialized as an Intl object'); - - defineProperty(pluralRules, '__getInternalProperties', { - value: function value() { - // NOTE: Non-standard, for internal use only - if (arguments[0] === secret) return internal; - } - }); - - // 2. Set pluralRules.[[InitializedIntlObject]] to true. - internal['[[InitializedIntlObject]]'] = true; - - // 3. Let requestedLocales be ? CanonicalizeLocaleList(locales). - var requestedLocales = CanonicalizeLocaleList(locales); - - // 4. If options is undefined, then - if (options === undefined) - // a. Let options be ObjectCreate(%ObjectPrototype%). - options = {}; - // 5. Else - else - // a. Let options be ? ToObject(options). - options = toObject(options); - - // 6. Let t be ? GetOption(options, "type", "string", « "cardinal", "ordinal" », "cardinal"). - var t = GetOption(options, 'type', 'string', new List('cardinal', 'ordinal'), 'cardinal'); - - // 7 . Set pluralRules.[[Type]] to t. - internal['[[type]]'] = t; - - // 8. Let opt be a new Record. - var opt = new Record(); - - // 9. Let matcher be ? GetOption(options, "localeMatcher", "string", « "lookup", "best fit" », "best fit"). - var matcher = GetOption(options, 'localeMatcher', 'string', new List('lookup', 'best fit'), 'best fit'); - // 10. Set opt.[[localeMatcher]] to matcher. - opt['[[localeMatcher]]'] = matcher; - - // 11. Perform ? SetNumberFormatOptions(pluralRules, options, 0). - SetNumberFormatDigitOptions(internals, options, 0); - - // 12. If pluralRules.[[maximumFractionDigits]] is undefined, then - if (internals['[[maximumFractionDigits]]'] === undefined) { - // a. Set pluralRules.[[maximumFractionDigits]] to max(pluralRules.[[minimumFractionDigits]], 3). - internals['[[maximumFractionDigits]]'] = Math.max(internals['[[minimumFractionDigits]]'], 3); - } - - var localeData = internals.PluralRules['[[localeData]]']; - - // 13. Let r be ResolveLocale(%PluralRules%.[[AvailableLocales]], requestedLocales, opt). - var r = ResolveLocale(internals.PluralRules['[[availableLocales]]'], requestedLocales, opt, internals.PluralRules['[[relevantExtensionKeys]]'], localeData); - - // 14. Set pluralRules.[[Locale]] to the value of r.[[Locale]]. - internal['[[locale]]'] = r['[[locale]]']; - - // 15. Set pluralRules.[[InitializedPluralRules]] to true. - internal['[[InitializedPluralRules]]'] = true; - - // 16. Return pluralRules. - return pluralRules; -} - -// make-plurals handls GetOperands -function PluralRuleSelection(locale, type, s) { - for (var l = locale; l; l = l.replace(/[-_]?[^-_]*$/, '')) { - var pf = plurals[l]; - if (pf) return pf(s, type === 'ordinal'); - } - return 'other'; -} - -function ResolvePlural(pluralRules, n) { - // 1. Assert: Type(pluralRules) is Object and pluralRules has an [[InitializedPluralRules]] internal slot whose value is true. - - // 2. Assert: Type(n) is Number. - - // 3. If isFinite(n) is false, then - if (!Number.isFinite(n)) { - // a. Return "other". - return 'other'; - } - - var internal = getInternalProperties(pluralRules); - - // 4. Let locale be pluralRules.[[Locale]]. - var locale = internal['[[locale]]']; - - // 5. Let type be pluralRules.[[Type]]. - var type = internal['[[type]]']; - - // 8. Return ? PluralRuleSelection(locale, type, n, operands). - return PluralRuleSelection(locale, type, n); -} - -internals.PluralRules = { - '[[availableLocales]]': Object.keys(plurals), - '[[relevantExtensionKeys]]': [], - '[[localeData]]': {} -}; - -defineProperty(Intl$1.PluralRules, 'supportedLocalesOf', { - configurable: true, - writable: true, - value: fnBind.call(function (locales) { - // Bound functions only have the `this` value altered if being used as a constructor, - // this lets us imitate a native function that has no constructor - if (!hop.call(this, '[[availableLocales]]')) throw new TypeError('supportedLocalesOf() is not a constructor'); - - // Create an object whose props can be used to restore the values of RegExp props - var regexpRestore = createRegExpRestore(), - - - // 1. If options is not provided, then let options be undefined. - options = arguments[1], - - - // 2. Let availableLocales be the value of the [[availableLocales]] internal - // property of the standard built-in object that is the initial value of - // Intl.NumberFormat. - - availableLocales = this['[[availableLocales]]'], - - - // 3. Let requestedLocales be the result of calling the CanonicalizeLocaleList - // abstract operation (defined in 9.2.1) with argument locales. - requestedLocales = CanonicalizeLocaleList(locales); - - // Restore the RegExp properties - regexpRestore(); - - // 4. Return the result of calling the SupportedLocales abstract operation - // (defined in 9.2.8) with arguments availableLocales, requestedLocales, - // and options. - return SupportedLocales(availableLocales, requestedLocales, options); - }, internals.PluralRules) -}); - -defineProperty(Intl$1.PluralRules.prototype, 'select', { - configurable: true, - value: function value(_value) { - var pluralRules = this; - var n = Number(_value); - return ResolvePlural(pluralRules, n); - } -}); - -defineProperty(Intl$1.PluralRules.prototype, 'resolvedOptions', { - configurable: true, - writable: true, - value: function value() { - var prop = void 0, - descs = new Record(), - props = ['locale', 'type', 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits'], - internal = this !== null && babelHelpers$1['typeof'](this) === 'object' && getInternalProperties(this); - - if (!internal || !internal['[[InitializedPluralRules]]']) throw new TypeError('`this` value for resolvedOptions() is not an initialized Intl.PluralRules object.'); - - for (var i = 0, max = props.length; i < max; i++) { - if (hop.call(internal, prop = '[[' + props[i] + ']]')) descs[props[i]] = { value: internal[prop], writable: true, configurable: true, enumerable: true }; - } - - return objCreate({}, descs); - } -}); - -/** - * @license Copyright 2013 Andy Earnshaw, MIT License - * - * Implements the ECMAScript Internationalization API in ES5-compatible environments, - * following the ECMA-402 specification as closely as possible - * - * ECMA-402: http://ecma-international.org/ecma-402/1.0/ - * - * CLDR format locale data should be provided using IntlPolyfill.__addLocaleData(). - */ - -defineProperty(Intl$1, '__applyLocaleSensitivePrototypes', { - writable: true, - configurable: true, - value: function value() { - defineProperty(Number.prototype, 'toLocaleString', { writable: true, configurable: true, value: ls.Number.toLocaleString }); - // Need this here for IE 8, to avoid the _DontEnum_ bug - defineProperty(Date.prototype, 'toLocaleString', { writable: true, configurable: true, value: ls.Date.toLocaleString }); - - for (var k in ls.Date) { - if (hop.call(ls.Date, k)) defineProperty(Date.prototype, k, { writable: true, configurable: true, value: ls.Date[k] }); - } - } -}); - -/** - * Can't really ship a single script with data for hundreds of locales, so we provide - * this __addLocaleData method as a means for the developer to add the data on an - * as-needed basis - */ -defineProperty(Intl$1, '__addLocaleData', { - value: function value(data) { - if (!IsStructurallyValidLanguageTag(data.locale)) throw new Error("Invalid language tag \"" + data.locale + "\" when calling __addLocaleData(\"" + data.locale + "\", ...) to register new locale data."); - - addLocaleData(data, data.locale); - } -}); - -function addLocaleData(data, tag) { - // Both NumberFormat and DateTimeFormat require number data, so throw if it isn't present - if (!data.number) throw new Error("Object passed doesn't contain locale data for Intl.NumberFormat"); - - var locale = void 0, - locales = [tag], - parts = tag.split('-'); - - // Create fallbacks for locale data with scripts, e.g. Latn, Hans, Vaii, etc - if (parts.length > 2 && parts[1].length === 4) arrPush.call(locales, parts[0] + '-' + parts[2]); - - while (locale = arrShift.call(locales)) { - // Add to NumberFormat internal properties as per 11.2.3 - arrPush.call(internals.NumberFormat['[[availableLocales]]'], locale); - internals.NumberFormat['[[localeData]]'][locale] = data.number; - - // ...and DateTimeFormat internal properties as per 12.2.3 - if (data.date) { - data.date.nu = data.number.nu; - arrPush.call(internals.DateTimeFormat['[[availableLocales]]'], locale); - internals.DateTimeFormat['[[localeData]]'][locale] = data.date; - } - } - - // If this is the first set of locale data added, make it the default - if (defaultLocale === undefined) setDefaultLocale(tag); -} - -defineProperty(Intl$1, '__disableRegExpRestore', { - value: function value() { - internals.disableRegExpRestore = true; - } -}); - -// hack to export the polyfill as global Intl if needed -if (typeof Intl === 'undefined') { - try { - window.Intl = Intl$1; - Intl$1.__applyLocaleSensitivePrototypes(); - } catch (e) { - // can be read only property - } -} - -return Intl$1; - -}))); -//# sourceMappingURL=Intl.js.map diff --git a/yarn.lock b/yarn.lock index df7594a0b04..b85d9af9966 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1173,6 +1173,39 @@ dependencies: cross-spawn "^6.0.5" +"@formatjs/intl-displaynames@^1.2.0": + version "1.2.10" + resolved "https://registry.yarnpkg.com/@formatjs/intl-displaynames/-/intl-displaynames-1.2.10.tgz#bb9625cca90b099978cd967c6a98aaf4e23fc878" + integrity sha512-GROA2RP6+7Ouu0WnHFF78O5XIU7pBfI19WM1qm93l6MFWibUk67nCfVCK3VAYJkLy8L8ZxjkYT11VIAfvSz8wg== + dependencies: + "@formatjs/intl-utils" "^2.3.0" + +"@formatjs/intl-listformat@^1.4.1": + version "1.4.8" + resolved "https://registry.yarnpkg.com/@formatjs/intl-listformat/-/intl-listformat-1.4.8.tgz#70b81005e7dcf74329cb5b314a940ce5fce36cd0" + integrity sha512-WNMQlEg0e50VZrGIkgD5n7+DAMGt3boKi1GJALfhFMymslJb5i+5WzWxyj/3a929Z6MAFsmzRIJjKuv+BxKAOQ== + dependencies: + "@formatjs/intl-utils" "^2.3.0" + +"@formatjs/intl-relativetimeformat@^4.5.9": + version "4.5.16" + resolved "https://registry.yarnpkg.com/@formatjs/intl-relativetimeformat/-/intl-relativetimeformat-4.5.16.tgz#7449cef3213dd66d25924ca41f125f87b58df95a" + integrity sha512-IQ0haY97oHAH5OYUdykNiepdyEWj3SAT+Fp9ZpR85ov2JNiFx+12WWlxlVS8ehdyncC2ZMt/SwFIy2huK2+6/A== + dependencies: + "@formatjs/intl-utils" "^2.3.0" + +"@formatjs/intl-unified-numberformat@^3.2.0": + version "3.3.7" + resolved "https://registry.yarnpkg.com/@formatjs/intl-unified-numberformat/-/intl-unified-numberformat-3.3.7.tgz#9995a24568908188e716d81a1de5b702b2ee00e2" + integrity sha512-KnWgLRHzCAgT9eyt3OS34RHoyD7dPDYhRcuKn+/6Kv2knDF8Im43J6vlSW6Hm1w63fNq3ZIT1cFk7RuVO3Psag== + dependencies: + "@formatjs/intl-utils" "^2.3.0" + +"@formatjs/intl-utils@^2.2.0", "@formatjs/intl-utils@^2.3.0": + version "2.3.0" + resolved "https://registry.yarnpkg.com/@formatjs/intl-utils/-/intl-utils-2.3.0.tgz#2dc8c57044de0340eb53a7ba602e59abf80dc799" + integrity sha512-KWk80UPIzPmUg+P0rKh6TqspRw0G6eux1PuJr+zz47ftMaZ9QDwbGzHZbtzWkl5hgayM/qrKRutllRC7D/vVXQ== + "@hapi/address@2.x.x": version "2.1.4" resolved "https://registry.yarnpkg.com/@hapi/address/-/address-2.1.4.tgz#5d67ed43f3fd41a69d4b9ff7b56e7c0d1d0a81e5" @@ -2399,6 +2432,11 @@ "@types/react" "*" hoist-non-react-statics "^3.3.0" +"@types/invariant@^2.2.31": + version "2.2.34" + resolved "https://registry.yarnpkg.com/@types/invariant/-/invariant-2.2.34.tgz#05e4f79f465c2007884374d4795452f995720bbe" + integrity sha512-lYUtmJ9BqUN688fGY1U1HZoWT1/Jrmgigx2loq4ZcJpICECm/Om3V314BxdzypO0u5PORKGMM6x0OXaljV1YFg== + "@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1": version "2.0.3" resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.3.tgz#4ba8ddb720221f432e443bd5f9117fd22cfd4762" @@ -6112,29 +6150,25 @@ interpret@^1.0.0: resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.4.0.tgz#665ab8bc4da27a774a40584e812e3e0fa45b1a1e" integrity sha512-agE4QfB2Lkp9uICn7BAqoscw4SZP9kTE2hxiFI3jBPmXJfdqiahTbUuKGsMoN2GtqL9AxhYioAcVvgsb1HvRbA== -intl-format-cache@^2.0.5: - version "2.2.9" - resolved "https://registry.yarnpkg.com/intl-format-cache/-/intl-format-cache-2.2.9.tgz#fb560de20c549cda20b569cf1ffb6dc62b5b93b4" - integrity sha512-Zv/u8wRpekckv0cLkwpVdABYST4hZNTDaX7reFetrYTJwxExR2VyTqQm+l0WmL0Qo8Mjb9Tf33qnfj0T7pjxdQ== - -intl-messageformat-parser@1.4.0: - version "1.4.0" - resolved "https://registry.yarnpkg.com/intl-messageformat-parser/-/intl-messageformat-parser-1.4.0.tgz#b43d45a97468cadbe44331d74bb1e8dea44fc075" - integrity sha1-tD1FqXRoytvkQzHXS7Ho3qRPwHU= +intl-format-cache@^4.2.21: + version "4.3.1" + resolved "https://registry.yarnpkg.com/intl-format-cache/-/intl-format-cache-4.3.1.tgz#484d31a9872161e6c02139349b259a6229ade377" + integrity sha512-OEUYNA7D06agqPOYhbTkl0T8HA3QKSuwWh1HiClEnpd9vw7N+3XsQt5iZ0GUEchp5CW1fQk/tary+NsbF3yQ1Q== -intl-messageformat@^2.0.0, intl-messageformat@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/intl-messageformat/-/intl-messageformat-2.2.0.tgz#345bcd46de630b7683330c2e52177ff5eab484fc" - integrity sha1-NFvNRt5jC3aDMwwuUhd/9eq0hPw= +intl-messageformat-parser@^3.6.4: + version "3.6.4" + resolved "https://registry.yarnpkg.com/intl-messageformat-parser/-/intl-messageformat-parser-3.6.4.tgz#5199d106d816c3dda26ee0694362a9cf823978fb" + integrity sha512-RgPGwue0mJtoX2Ax8EmMzJzttxjnva7gx0Q7mKJ4oALrTZvtmCeAw5Msz2PcjW4dtCh/h7vN/8GJCxZO1uv+OA== dependencies: - intl-messageformat-parser "1.4.0" + "@formatjs/intl-unified-numberformat" "^3.2.0" -intl-relativeformat@^2.1.0: - version "2.2.0" - resolved "https://registry.yarnpkg.com/intl-relativeformat/-/intl-relativeformat-2.2.0.tgz#6aca95d019ec8d30b6c5653b6629f9983ea5b6c5" - integrity sha512-4bV/7kSKaPEmu6ArxXf9xjv1ny74Zkwuey8Pm01NH4zggPP7JHwg2STk8Y3JdspCKRDriwIyLRfEXnj2ZLr4Bw== +intl-messageformat@^7.8.4: + version "7.8.4" + resolved "https://registry.yarnpkg.com/intl-messageformat/-/intl-messageformat-7.8.4.tgz#c29146a06b9cd26662978a4d95fff2b133e3642f" + integrity sha512-yS0cLESCKCYjseCOGXuV4pxJm/buTfyCJ1nzQjryHmSehlptbZbn9fnlk1I9peLopZGGbjj46yHHiTAEZ1qOTA== dependencies: - intl-messageformat "^2.0.0" + intl-format-cache "^4.2.21" + intl-messageformat-parser "^3.6.4" into-stream@^3.1.0: version "3.1.0" @@ -6144,7 +6178,7 @@ into-stream@^3.1.0: from2 "^2.1.1" p-is-promise "^1.1.0" -invariant@2.2.4, invariant@^2.1.1, invariant@^2.2.2, invariant@^2.2.4: +invariant@2.2.4, invariant@^2.2.2, invariant@^2.2.4: version "2.2.4" resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6" integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA== @@ -9799,16 +9833,23 @@ react-dom@16.11.0: prop-types "^15.6.2" scheduler "^0.17.0" -react-intl@^2.4.0: - version "2.9.0" - resolved "https://registry.yarnpkg.com/react-intl/-/react-intl-2.9.0.tgz#c97c5d17d4718f1575fdbd5a769f96018a3b1843" - integrity sha512-27jnDlb/d2A7mSJwrbOBnUgD+rPep+abmoJE511Tf8BnoONIAUehy/U1zZCHGO17mnOwMWxqN4qC0nW11cD6rA== +react-intl@^3.12.1: + version "3.12.1" + resolved "https://registry.yarnpkg.com/react-intl/-/react-intl-3.12.1.tgz#e9a783ea20302e9da25e4eda59e5593a43d2ec80" + integrity sha512-cgumW29mwROIqyp8NXStYsoIm27+8FqnxykiLSawWjOxGIBeLuN/+p2srei5SRIumcJefOkOIHP+NDck05RgHg== dependencies: - hoist-non-react-statics "^3.3.0" - intl-format-cache "^2.0.5" - intl-messageformat "^2.1.0" - intl-relativeformat "^2.1.0" - invariant "^2.1.1" + "@formatjs/intl-displaynames" "^1.2.0" + "@formatjs/intl-listformat" "^1.4.1" + "@formatjs/intl-relativetimeformat" "^4.5.9" + "@formatjs/intl-unified-numberformat" "^3.2.0" + "@formatjs/intl-utils" "^2.2.0" + "@types/hoist-non-react-statics" "^3.3.1" + "@types/invariant" "^2.2.31" + hoist-non-react-statics "^3.3.2" + intl-format-cache "^4.2.21" + intl-messageformat "^7.8.4" + intl-messageformat-parser "^3.6.4" + shallow-equal "^1.2.1" react-is@^16.12.0, react-is@^16.13.0, react-is@^16.7.0, react-is@^16.8.1, react-is@^16.8.4, react-is@^16.8.6, react-is@^16.9.0: version "16.13.1" @@ -10721,6 +10762,11 @@ setprototypeof@1.1.1: resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.1.1.tgz#7e95acb24aa92f5885e0abef5ba131330d4ae683" integrity sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw== +shallow-equal@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/shallow-equal/-/shallow-equal-1.2.1.tgz#4c16abfa56043aa20d050324efa68940b0da79da" + integrity sha512-S4vJDjHHMBaiZuT9NPb616CSmLf618jawtv3sufLl6ivK8WocjAo58cXwbRV1cgqxH0Qbv+iUt6m05eqEa2IRA== + shebang-command@^1.2.0: version "1.2.0" resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-1.2.0.tgz#44aac65b695b03398968c39f363fee5deafdf1ea" From 253d49361117f8ef382d243badbb3010cb8c8098 Mon Sep 17 00:00:00 2001 From: Chris Bobbe Date: Thu, 6 Aug 2020 14:45:37 -0700 Subject: [PATCH 4/8] react-intl libdef: Make some React type annotations useful. Anything at `React.` is `any` [1]. So, in a few places, use Flow's builtin React type annotations, like React$Node instead of React.Node. These are the obvious ones that we use. I tried exhaustively translating everything from the `React.` namespace into a `React$` equivalent, but things broke in mysterious ways. Better to do it incrementally, then, and we can come back if we want more of it to work. [1] https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/libdef.3A.20react-native-webview/near/896571 --- flow-typed/react-intl_vx.x.x.js | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/flow-typed/react-intl_vx.x.x.js b/flow-typed/react-intl_vx.x.x.js index 96704f06ed8..0bfc866cf01 100644 --- a/flow-typed/react-intl_vx.x.x.js +++ b/flow-typed/react-intl_vx.x.x.js @@ -2,7 +2,7 @@ // relevant-looking TypeScript .d.ts files, with minimal tweaks to // make it work. -// Currently not very useful; anything at `React.` is `any`; see +// Anything at `React.` is `any`; see // https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/libdef.3A.20react-native-webview/near/896571. // We should use Flow's builtin React type annotations, like // React$Node instead of React.Node. @@ -158,7 +158,7 @@ declare module 'react-intl' { [key: string]: PrimitiveType | React.ReactElement<> | FormatXMLElementFn, ..., }, - > extends React.Component> { + > extends React$Component> { static displayName: string; static defaultProps: { values: { ... }, @@ -312,7 +312,7 @@ declare module 'react-intl' { defaultFormats: CustomFormats; onError(err: string): void; } - declare export var IntlContext: React.Context; + declare export var IntlContext: React$Context; // Changed from `interface` to `type` in TS to Flow translation. declare export type IntlFormatters = { formatDate( From 487bc04526514b84e2a115bc581c1a9007a27861 Mon Sep 17 00:00:00 2001 From: Chris Bobbe Date: Thu, 6 Aug 2020 14:49:03 -0700 Subject: [PATCH 5/8] react-intl libdef: Make more React type annotations useful. Following from the previous commit, these are all the ones I'd really feel confident and comfortable doing, above and beyond the ones I expect to be most visible. Plenty of `React.` occurrences remain. Let's fix these carefully if it turns out they're suppressing some really useful type checking, but I don't expect it to be really easy. --- flow-typed/react-intl_vx.x.x.js | 46 ++++++++++++++++----------------- 1 file changed, 23 insertions(+), 23 deletions(-) diff --git a/flow-typed/react-intl_vx.x.x.js b/flow-typed/react-intl_vx.x.x.js index 0bfc866cf01..b74368094e2 100644 --- a/flow-typed/react-intl_vx.x.x.js +++ b/flow-typed/react-intl_vx.x.x.js @@ -119,9 +119,9 @@ declare module 'react-intl' { props: any, ) => React.ReactElement< any, - string | any | ((props: any) => React.Component), + string | any | ((props: any) => React$Component), > | null) - | ((props: any) => React.Component), + | ((props: any) => React$Component), > | null, ... }, @@ -147,7 +147,7 @@ declare module 'react-intl' { } declare export var FormattedList: React.FC< IntlListFormatOptions & { - value: React.Node[], + value: React$Node[], ... }, >; @@ -200,7 +200,7 @@ declare module 'react-intl' { ... } & React.RefAttributes, > & { - WrappedComponent: React.ComponentType, + WrappedComponent: React$ComponentType, ... }; // changed `mixins` to `extends` in Flow to TS translation @@ -237,9 +237,9 @@ declare module 'react-intl' { props: any, ) => React.ReactElement< any, - string | any | ((props: any) => React.Component), + string | any | ((props: any) => React$Component), > | null) - | ((props: any) => React.Component), + | ((props: any) => React$Component), > | null, ... }, @@ -274,23 +274,23 @@ declare module 'react-intl' { } declare type FormatXMLElementFn = (...args: any[]) => string | { [key: string]: any }; declare export function injectIntl>( - WrappedComponent: React.ComponentType

, + WrappedComponent: React$ComponentType

, options?: Opts, ): React.FC> & { - WrappedComponent: React.ComponentType

, + WrappedComponent: React$ComponentType

, ... }; declare export function injectIntl< IntlPropName: string, P: WrappedComponentProps, - T: React.ComponentType

, + T: React$ComponentType

, >( - WrappedComponent: React.ComponentType

, + WrappedComponent: React$ComponentType

, options?: Opts, ): React.ForwardRefExoticComponent< React.PropsWithoutRef> & React.RefAttributes, > & { - WrappedComponent: React.ComponentType

, + WrappedComponent: React$ComponentType

, ... }; declare export interface IntlCache { @@ -306,7 +306,7 @@ declare module 'react-intl' { locale: string; timeZone?: string; formats: CustomFormats; - textComponent?: React.ComponentType<> | $Keys; + textComponent?: React$ComponentType<> | $Keys; messages: { [key: string]: string, ... } | { [key: string]: MessageFormatElement[], ... }; defaultLocale: string; defaultFormats: CustomFormats; @@ -363,9 +363,9 @@ declare module 'react-intl' { formatHTMLMessage( descriptor: MessageDescriptor, values?: { [key: string]: PrimitiveType, ... }, - ): React.Node, + ): React$Node, formatList(values: Array, opts?: FormatListOptions): string, - formatList(values: Array, opts?: FormatListOptions): React.Node, + formatList(values: Array, opts?: FormatListOptions): React$Node, formatDisplayName( value: $ElementType>, 0>, opts?: FormatDisplayNameOptions, @@ -709,19 +709,19 @@ declare module 'react-intl' { declare type Props_2 = { value: number, intl: IntlShape, - other: React.Node, - zero?: React.Node, - one?: React.Node, - two?: React.Node, - few?: React.Node, - many?: React.Node, - children?: (value: React.Node) => React.ReactElement<> | null, + other: React$Node, + zero?: React$Node, + one?: React$Node, + two?: React$Node, + few?: React$Node, + many?: React$Node, + children?: (value: React$Node) => React.ReactElement<> | null, ... } & FormatPluralOptions; - declare type Props_3 = { + declare type Props_3 = { values?: V, tagName?: React.ElementType, - children?: (...nodes: React.ReactNodeArray) => React.Node, + children?: (...nodes: React.ReactNodeArray) => React$Node, ... } & MessageDescriptor; declare export var RawIntlProvider: React.Provider; From 8038528393bb83ea23da231cb36a58891061e9bd Mon Sep 17 00:00:00 2001 From: Chris Bobbe Date: Thu, 6 Aug 2020 16:58:44 -0700 Subject: [PATCH 6/8] deps: Update `react-intl` from v3 to v5, the latest. The upgrade guides for v4 [1] and v5 [2] are pretty short and simple, so, might as well jump to the latest (currently 5.8.6) all at once. We restrict the version range to that single version (instead of using a caret or a tilde), since `react-intl` doesn't invite its users to expect breaking changes to be handled well [3]. We also change our useless `typescript` dev-dependency's version to a range that's in the intersection of the range `react-intl` gives for it, and the range we found in 78daeb607. With v4 (and continuing into v5), we get a big stroke of luck for the libdef. There's a single TypeScript file that contains all the necessary types [4], so we only need to run Flowgen once, on that one file. This saves a lot of the kind of work we had to do for v3. The v4 declared breaking changes don't apply to us. One v5 breaking change applies to us: - `FormattedMessage` render prop is no longer variadic. We've only ever cared about the first argument passed to the render prop, so, grab just that one, to minimally handle the API change. In fact, it seems like a bug that we're not paying attention to any others that are passed. But it looks like no others are being passed, currently; we haven't explicitly made that happen. But we'll stop using this confusing pattern in an upcoming commit; see discussion [5]. [1] https://formatjs.io/docs/react-intl/upgrade-guide-4x [2] https://formatjs.io/docs/react-intl/upgrade-guide-5x [3] https://github.com/formatjs/formatjs/pull/2067#issuecomment-714171574 [4] except for React, which is normal, and which we'll address to some extent in the next commit. [5] https://github.com/zulip/zulip-mobile/pull/4222#discussion_r468244576 --- flow-typed/react-intl_vx.x.x.js | 765 ++++++++++++++------------------ package.json | 4 +- src/common/Input.js | 4 +- yarn.lock | 137 +++--- 4 files changed, 425 insertions(+), 485 deletions(-) diff --git a/flow-typed/react-intl_vx.x.x.js b/flow-typed/react-intl_vx.x.x.js index b74368094e2..6c2296564c3 100644 --- a/flow-typed/react-intl_vx.x.x.js +++ b/flow-typed/react-intl_vx.x.x.js @@ -1,13 +1,16 @@ -// `react-intl` and all its dependencies, translated from the -// relevant-looking TypeScript .d.ts files, with minimal tweaks to -// make it work. +// `react-intl`, translated from the relevant-looking TypeScript .d.ts +// file, with minimal tweaks to make it work. -// Anything at `React.` is `any`; see +// Anything at `React_2.` is `any`; see // https://chat.zulip.org/#narrow/stream/243-mobile-team/topic/libdef.3A.20react-native-webview/near/896571. // We should use Flow's builtin React type annotations, like // React$Node instead of React.Node. -// react-intl/dist/react-intl.d.ts +// Not sure why the TypeScript uses React_2 instead of just React, but +// we've kept it intact. +import * as React_2 from 'react'; + +// react-intl/react-intl.d.ts declare module 'react-intl' { /** * Flowtype definitions for react-intl @@ -15,17 +18,11 @@ declare module 'react-intl' { * Flowgen v1.11.0 */ - import type { DisplayNames } from '@formatjs/intl-displaynames'; - declare type ArgumentElement = BaseElement; - declare interface ArgumentPart { - type: typeof PART_TYPE.argument; - value: any; - } declare interface BaseElement> { type: T; value: string; - location?: Location; + location?: Location_2; } /** * Create intl object @@ -34,6 +31,7 @@ declare module 'react-intl' { */ declare export function createIntl(config: OptionalIntlConfig, cache?: IntlCache): IntlShape; declare export function createIntlCache(): IntlCache; + declare type CurrencyCode = string; declare export interface CustomFormatConfig { format?: string; } @@ -42,10 +40,32 @@ declare module 'react-intl' { ... } & $Rest; declare type DateElement = SimpleFormatElement; + declare type DateTimeFormatOptions = { + hourCycle?: 'h11' | 'h12' | 'h23' | 'h24', + dateStyle?: 'full' | 'long' | 'medium' | 'short', + timeStyle?: 'full' | 'long' | 'medium' | 'short', + fractionalSecondDigits?: number, + calendar?: + | 'buddhist' + | 'chinese' + | 'coptic' + | 'ethiopia' + | 'ethiopic' + | 'gregory' + | 'hebrew' + | 'indian' + | 'islamic' + | 'iso8601' + | 'japanese' + | 'persian' + | 'roc', + numberingSystem?: string, + ... + } & Intl.DateTimeFormatOptions; declare interface DateTimeSkeleton { type: typeof SKELETON_TYPE.dateTime; pattern: string; - location?: Location; + location?: Location_2; } declare var DEFAULT_INTL_CONFIG: Pick< IntlConfig, @@ -57,13 +77,90 @@ declare module 'react-intl' { | 'defaultFormats' | 'onError', >; - declare export function defineMessages(msgs: U): U; + declare export function defineMessage(msg: T): T; + declare export function defineMessages, T, U: { [key: K]: T, ... }>(msgs: U): U; + declare class DisplayNames { + constructor(locales?: string | string[], options?: DisplayNamesOptions): this; + static supportedLocalesOf( + locales?: string | string[], + options?: Pick, + ): string[]; + static __addLocaleData(...data: DisplayNamesLocaleData[]): void; + of(code: string | number | { [key: string]: any }): string | void; + resolvedOptions(): DisplayNamesResolvedOptions; + static localeData: { [key: string]: DisplayNamesData, ... }; + static +polyfilled: any; // true + } + declare interface DisplayNamesData { + /** + * Note that for style fields, `short` and `narrow` might not exist. + * At runtime, the fallback order will be narrow -> short -> long. + */ + types: { + /** + * Maps language subtag like `zh-CN` to their display names. + */ + language: { + narrow: { [key: LanguageTag]: string, ... }, + short: { [key: LanguageTag]: string, ... }, + long: { [key: LanguageTag]: string, ... }, + ... + }, + region: { + narrow: { [key: RegionCode]: string, ... }, + short: { [key: RegionCode]: string, ... }, + long: { [key: RegionCode]: string, ... }, + ... + }, + script: { + narrow: { [key: ScriptCode]: string, ... }, + short: { [key: ScriptCode]: string, ... }, + long: { [key: ScriptCode]: string, ... }, + ... + }, + currency: { + narrow: { [key: CurrencyCode]: string, ... }, + short: { [key: CurrencyCode]: string, ... }, + long: { [key: CurrencyCode]: string, ... }, + ... + }, + ... + }; + + /** + * Not in spec, but we need this to display both language and region in display name. + * e.g. zh-Hans-SG + "{0}({1})" -> 简体中文(新加坡) + * Here {0} is replaced by language display name and {1} is replaced by region display name. + */ + patterns: { + locale: string, + ... + }; + } + declare type DisplayNamesLocaleData = LocaleData; + declare interface DisplayNamesOptions { + localeMatcher?: 'lookup' | 'best fit'; + style?: 'narrow' | 'short' | 'long'; + type?: 'language' | 'region' | 'script' | 'currency'; + fallback?: 'code' | 'none'; + } + declare interface DisplayNamesResolvedOptions { + locale: string; + style: $NonMaybeType<$PropertyType>; + type: $NonMaybeType<$PropertyType>; + fallback: $NonMaybeType<$PropertyType>; + } declare interface ElementPart { type: 'element'; value: string; } + declare var ErrorCode: {| + +MISSING_VALUE: 'MISSING_VALUE', // "MISSING_VALUE" + +INVALID_VALUE: 'INVALID_VALUE', // "INVALID_VALUE" + +MISSING_INTL_API: 'MISSING_INTL_API', // "MISSING_INTL_API" + |}; declare interface FieldData { - // $FlowFixMe - illegal name + // $FlowFixMe - illegal name (these fixmes added in TS to Flow translation) '0'?: string; // $FlowFixMe - illegal name '1'?: string; @@ -80,11 +177,24 @@ declare module 'react-intl' { future: RelativeTimeData; past: RelativeTimeData; } - declare export type FormatDateOptions = Exclude & + declare export type FormatDateOptions = Exclude & CustomFormatConfig; declare export type FormatDisplayNameOptions = Exclude; + declare class FormatError mixins Error { + +code: $Values; + + /** + * Original message we're trying to format + * `undefined` if we're only dealing w/ AST + * @type {(string | void)} + * @memberof FormatError + */ + +originalMessage: string | void; + constructor(msg: string, code: $Values, originalMessage?: string): this; + toString(): string; + } declare export type FormatListOptions = Exclude; - declare export type FormatNumberOptions = Exclude & + declare export type FormatNumberOptions = Exclude & CustomFormatConfig; declare export type FormatPluralOptions = Exclude & CustomFormatConfig; @@ -99,112 +209,64 @@ declare module 'react-intl' { time: { [key: string]: Intl.DateTimeFormatOptions, ... }; } declare type FormattableUnit = Unit | Units; - declare export var FormattedDate: React.FC< - Intl.DateTimeFormatOptions & + declare export var FormattedDate: React_2.FC< + DateTimeFormatOptions & CustomFormatConfig & { value: string | number | Date | void, ... }, >; - declare export var FormattedDateParts: React.FC< - Intl.DateTimeFormatOptions & - CustomFormatConfig & { - value: string | number | Date | void, - children( - val: Intl.DateTimeFormatPart[], - ): React.ReactElement< - any, - | string - | (( - props: any, - ) => React.ReactElement< - any, - string | any | ((props: any) => React$Component), - > | null) - | ((props: any) => React$Component), - > | null, - ... - }, + declare export var FormattedDateParts: React_2.FC< + FormatDateOptions & { + value: $ElementType>, 0> | string, + children(val: Intl.DateTimeFormatPart[]): React_2.ReactElement<> | null, + ... + }, >; - declare export var FormattedDisplayName: React.FC< + declare export var FormattedDisplayName: React_2.FC< DisplayNamesOptions & { value: string | number | { [key: string]: any }, ... }, >; - declare export class FormattedHTMLMessage - mixins FormattedMessage<{ - [string]: PrimitiveType, - ..., - }> { - static displayName: string; - static defaultProps: { - tagName: 'span', - values: { ... }, - ... - }; - render(): React$Node; - } - declare export var FormattedList: React.FC< + declare export var FormattedList: React_2.FC< IntlListFormatOptions & { - value: React$Node[], + value: React_2.Node[], ... }, >; - - // changed `mixins` to `extends` in Flow to TS translation declare export class FormattedMessage< V: { [key: string]: any, ... } = { - [key: string]: PrimitiveType | React.ReactElement<> | FormatXMLElementFn, + [key: string]: + | PrimitiveType + | React_2.ReactElement<> + | FormatXMLElementFn, ..., }, - > extends React$Component> { + > mixins React_2.Component> { static displayName: string; - static defaultProps: { - values: { ... }, - ... - }; shouldComponentUpdate(nextProps: Props_3): boolean; render(): React$Node; } - declare export var FormattedNumber: React.FC< - UnifiedNumberFormatOptions & + declare export var FormattedNumber: React_2.FC< + NumberFormatOptions & CustomFormatConfig & { value: number, ... }, >; - declare export var FormattedNumberParts: React.FC< + declare export var FormattedNumberParts: React_2.FC< $PropertyType & { value: $ElementType>, 0>, - children(val: Intl.NumberFormatPart[]): React.ReactElement<> | null, + children(val: Intl.NumberFormatPart[]): React_2.ReactElement<> | null, ... }, >; - declare export var FormattedPlural: React.ForwardRefExoticComponent< - Pick< - Props_2, - | 'children' - | 'other' - | 'zero' - | 'one' - | 'two' - | 'few' - | 'many' - | 'localeMatcher' - | 'format' - | 'type' - | 'value', - > & { - forwardedRef?: ((instance: any) => void) | React.RefObject | null | void, - ... - } & React.RefAttributes, - > & { - WrappedComponent: React$ComponentType, + declare export var FormattedPlural: React_2.FC> & { + WrappedComponent: React_2.ComponentType, ... }; - // changed `mixins` to `extends` in Flow to TS translation - declare export class FormattedRelativeTime extends React.PureComponent { + declare export class FormattedRelativeTime mixins React_2.PureComponent { _updateTimer: any; static displayName: string; static defaultProps: Pick; @@ -217,32 +279,19 @@ declare module 'react-intl' { static getDerivedStateFromProps(props: Props, state: State_2): $Rest | null; render(): React$Node; } - declare export var FormattedTime: React.FC< - Intl.DateTimeFormatOptions & + declare export var FormattedTime: React_2.FC< + DateTimeFormatOptions & CustomFormatConfig & { value: string | number | Date | void, ... }, >; - declare export var FormattedTimeParts: React.FC< - Intl.DateTimeFormatOptions & - CustomFormatConfig & { - value: string | number | Date | void, - children( - val: Intl.DateTimeFormatPart[], - ): React.ReactElement< - any, - | string - | (( - props: any, - ) => React.ReactElement< - any, - string | any | ((props: any) => React$Component), - > | null) - | ((props: any) => React$Component), - > | null, - ... - }, + declare export var FormattedTimeParts: React_2.FC< + FormatDateOptions & { + value: $ElementType>, 0> | string, + children(val: Intl.DateTimeFormatPart[]): React_2.ReactElement<> | null, + ... + }, >; declare type Formatter = { formatDate: FormatDateOptions, @@ -263,7 +312,7 @@ declare module 'react-intl' { ): RelativeTimeFormat; getPluralRules(...args: ConstructorParameters): Intl.PluralRules; getListFormat(...args: ConstructorParameters): ListFormat; - getDisplayNames(...args: ConstructorParameters): DisplayNames; + getDisplayNames(...args: ConstructorParameters): DisplayNames; } declare interface Formatters_2 { getNumberFormat(...args: ConstructorParameters): Intl.NumberFormat; @@ -272,25 +321,27 @@ declare module 'react-intl' { ): Intl.DateTimeFormat; getPluralRules(...args: ConstructorParameters): Intl.PluralRules; } - declare type FormatXMLElementFn = (...args: any[]) => string | { [key: string]: any }; + declare type FormatXMLElementFn> = ( + parts: Array, + ) => R; declare export function injectIntl>( - WrappedComponent: React$ComponentType

, + WrappedComponent: React_2.ComponentType

, options?: Opts, - ): React.FC> & { - WrappedComponent: React$ComponentType

, + ): React_2.FC> & { + WrappedComponent: React_2.ComponentType

, ... }; declare export function injectIntl< IntlPropName: string, P: WrappedComponentProps, - T: React$ComponentType

, + T: React_2.ComponentType

, >( - WrappedComponent: React$ComponentType

, + WrappedComponent: React_2.ComponentType

, options?: Opts, - ): React.ForwardRefExoticComponent< - React.PropsWithoutRef> & React.RefAttributes, + ): React_2.ForwardRefExoticComponent< + React_2.PropsWithoutRef>> & React_2.RefAttributes, > & { - WrappedComponent: React$ComponentType

, + WrappedComponent: React_2.ComponentType

, ... }; declare export interface IntlCache { @@ -306,71 +357,75 @@ declare module 'react-intl' { locale: string; timeZone?: string; formats: CustomFormats; - textComponent?: React$ComponentType<> | $Keys; + textComponent?: React_2.ComponentType<> | $Keys; messages: { [key: string]: string, ... } | { [key: string]: MessageFormatElement[], ... }; defaultLocale: string; defaultFormats: CustomFormats; - onError(err: string): void; + wrapRichTextChunksInFragment?: boolean; + onError( + err: + | MissingTranslationError + | MessageFormatError + | MissingDataError + | InvalidConfigError + | UnsupportedFormatterError + | FormatError, + ): void; } - declare export var IntlContext: React$Context; - // Changed from `interface` to `type` in TS to Flow translation. - declare export type IntlFormatters = { + declare export var IntlContext: React_2.Context; + declare export interface IntlFormatters { formatDate( value: $ElementType>, 0> | string, opts?: FormatDateOptions, - ): string, + ): string; formatTime( value: $ElementType>, 0> | string, opts?: FormatDateOptions, - ): string, + ): string; formatDateToParts( value: $ElementType>, 0> | string, opts?: FormatDateOptions, - ): Intl.DateTimeFormatPart[], + ): Intl.DateTimeFormatPart[]; formatTimeToParts( value: $ElementType>, 0> | string, opts?: FormatDateOptions, - ): Intl.DateTimeFormatPart[], + ): Intl.DateTimeFormatPart[]; formatRelativeTime( value: $ElementType>, 0>, unit?: $ElementType>, 1>, opts?: FormatRelativeTimeOptions, - ): string, + ): string; formatNumber( value: $ElementType>, 0>, opts?: FormatNumberOptions, - ): string, + ): string; formatNumberToParts( value: $ElementType>, 0>, opts?: FormatNumberOptions, - ): Intl.NumberFormatPart[], + ): Intl.NumberFormatPart[]; formatPlural( value: $ElementType>, 0>, opts?: FormatPluralOptions, - ): $Call<((...args: any[]) => R) => R, $PropertyType>, + ): $Call<((...args: any[]) => R) => R, $PropertyType>; formatMessage( descriptor: MessageDescriptor, // The `+` was added to make the properties covariant rather // than invariant, something TypeScript can't do. - values?: { +[key: string]: PrimitiveType, ... }, - ): string, + values?: { +[key: string]: PrimitiveType | FormatXMLElementFn, ... }, + ): string; formatMessage( descriptor: MessageDescriptor, // The `+` was added to make the properties covariant rather // than invariant, something TypeScript can't do. - values?: { +[key: string]: PrimitiveType | React.ReactElement<> | FormatXMLElementFn, ... }, - ): string | React.ReactNodeArray, - formatHTMLMessage( - descriptor: MessageDescriptor, - values?: { [key: string]: PrimitiveType, ... }, - ): React$Node, - formatList(values: Array, opts?: FormatListOptions): string, - formatList(values: Array, opts?: FormatListOptions): React$Node, + values?: { +[key: string]: PrimitiveType | React_2.Node | FormatXMLElementFn, ... }, + ): React$Node; + formatList(values: Array, opts?: FormatListOptions): string; + formatList(values: Array, opts?: FormatListOptions): React_2.Node; formatDisplayName( value: $ElementType>, 0>, opts?: FormatDisplayNameOptions, - ): string | void, - }; + ): string | void; + } declare interface IntlListFormatOptions { /** * The locale matching algorithm to use. @@ -405,28 +460,40 @@ declare module 'react-intl' { overrideFormats?: $Rest, opts?: Options, ): this; - format: (values?: { [key: string]: PrimitiveType, ... } | void) => string; - formatToParts: (values?: { [key: string]: any, ... } | void) => MessageFormatPart[]; - formatHTMLMessage: ( + format: ( values?: { [key: string]: | string | number | boolean - | { [key: string]: any } | Date - | FormatXMLElementFn + | T + | FormatXMLElementFn | null | void, ..., } | void, - ) => (string | { [key: string]: any })[]; + ) => string | T | (string | T)[]; + formatToParts: ( + values?: { + [key: string]: + | string + | number + | boolean + | Date + | T + | FormatXMLElementFn + | null + | void, + ..., + } | void, + ) => MessageFormatPart[]; resolvedOptions: () => { locale: string, ... }; getAst: () => MessageFormatElement[]; - static defaultLocale: string; + defaultLocale: string; static __parse: typeof parse | void; static formats: { number: { @@ -499,18 +566,18 @@ declare module 'react-intl' { ... }; } - // changed `mixins` to `extends` in Flow to TS translation - declare export class IntlProvider extends React.PureComponent { + declare export class IntlProvider + mixins React_2.PureComponent, State> { static displayName: string; static defaultProps: Pick< IntlConfig, | 'formats' - | 'messages' | 'timeZone' + | 'onError' + | 'messages' | 'textComponent' | 'defaultLocale' - | 'defaultFormats' - | 'onError', + | 'defaultFormats', >; state: State; static getDerivedStateFromProps( @@ -550,13 +617,18 @@ declare module 'react-intl' { formatters: Formatters, ... } & IntlConfig & - IntlFormatters; + IntlFormatters<>; + declare export class InvalidConfigError + mixins ReactIntlError { + constructor(message: string, exception?: Error): this; + } declare interface IParseOptions { filename?: string; startRule?: string; tracer?: any; [key: string]: any; } + declare type LanguageTag = string; declare type LDMLPluralRule = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other'; declare class ListFormat { constructor(locales?: string | string[], options?: IntlListFormatOptions): this; @@ -600,15 +672,13 @@ declare module 'react-intl' { declare type Locale = string; declare interface LocaleData { data: { [key: Locale]: T, ... }; - aliases: { [key: string]: string, ... }; availableLocales: string[]; - parentLocales: { [key: string]: string, ... }; } declare type LocaleFieldsData = $ObjMapi<{ [k: RelativeTimeField]: any }, (f) => FieldData> & { nu?: Array, ... }; - declare interface Location { + declare interface Location_2 { start: LocationDetails; end: LocationDetails; } @@ -617,8 +687,7 @@ declare module 'react-intl' { line: number; column: number; } - - // Changed from `interface` to `type` in TS to Flow translation. + // Changed from interface to type in TS to Flow translation declare export type MessageDescriptor = { id?: string | number, description?: string | { [key: string]: any }, @@ -632,30 +701,84 @@ declare module 'react-intl' { | TimeElement | SelectElement | PluralElement + | TagElement | PoundElement; - declare type MessageFormatPart = LiteralPart_2 | ArgumentPart; + declare export class MessageFormatError + mixins ReactIntlError { + +descriptor?: MessageDescriptor; + constructor( + message: string, + locale: string, + descriptor?: MessageDescriptor, + exception?: Error, + ): this; + } + declare type MessageFormatPart = LiteralPart_2 | ObjectPart; + declare export class MissingDataError + mixins ReactIntlError { + constructor(message: string, exception?: Error): this; + } + declare export class MissingTranslationError + mixins ReactIntlError { + +descriptor?: MessageDescriptor; + constructor(descriptor: MessageDescriptor, locale: string): this; + } declare type NumberElement = SimpleFormatElement; declare interface NumberFormatDigitOptions { minimumIntegerDigits?: number; - minimumFractionDigits?: number; - maximumFractionDigits?: number; minimumSignificantDigits?: number; maximumSignificantDigits?: number; + minimumFractionDigits?: number; + maximumFractionDigits?: number; } + declare type NumberFormatNotation = 'standard' | 'scientific' | 'engineering' | 'compact'; + declare type NumberFormatOptions = Intl.NumberFormatOptions & + NumberFormatDigitOptions & { + localeMatcher?: NumberFormatOptionsLocaleMatcher, + style?: NumberFormatOptionsStyle, + compactDisplay?: NumberFormatOptionsCompactDisplay, + currencyDisplay?: NumberFormatOptionsCurrencyDisplay, + currencySign?: NumberFormatOptionsCurrencySign, + notation?: NumberFormatOptionsNotation, + signDisplay?: NumberFormatOptionsSignDisplay, + unit?: string, + unitDisplay?: NumberFormatOptionsUnitDisplay, + numberingSystem?: string, + ... + }; + declare type NumberFormatOptionsCompactDisplay = 'short' | 'long'; + declare type NumberFormatOptionsCurrencyDisplay = 'symbol' | 'code' | 'name' | 'narrowSymbol'; + declare type NumberFormatOptionsCurrencySign = 'standard' | 'accounting'; + declare type NumberFormatOptionsLocaleMatcher = 'lookup' | 'best fit'; + declare type NumberFormatOptionsNotation = NumberFormatNotation; + declare type NumberFormatOptionsSignDisplay = 'auto' | 'always' | 'never' | 'exceptZero'; + declare type NumberFormatOptionsStyle = 'decimal' | 'percent' | 'currency' | 'unit'; + declare type NumberFormatOptionsUnitDisplay = 'long' | 'short' | 'narrow'; declare interface NumberSkeleton { type: typeof SKELETON_TYPE._number; tokens: NumberSkeletonToken[]; - location?: Location; + location?: Location_2; } declare interface NumberSkeletonToken { stem: string; options: string[]; } - declare export type Omit> = Pick, K>>; + declare interface ObjectPart { + type: typeof PART_TYPE.object; + value: T; + } declare type OptionalIntlConfig = Omit> & $Rest; declare interface Options { formatters?: Formatters_2; + + /** + * Whether to treat HTML/XML tags as string literal + * instead of parsing them as tag token. + * When this is false we only allow simple tags without + * any attributes + */ + ignoreTag?: boolean; } declare interface Options_2 { /** @@ -670,6 +793,14 @@ declare module 'react-intl' { * Default is false */ captureLocation?: boolean; + + /** + * Whether to treat HTML/XML tags as string literal + * instead of parsing them as tag token. + * When this is false we only allow simple tags without + * any attributes + */ + ignoreTag?: boolean; } declare interface Opts { intlPropName?: IntlPropName; @@ -682,7 +813,7 @@ declare module 'react-intl' { declare type Part_2 = LiteralPart | ElementPart; declare var PART_TYPE: {| +literal: 0, // 0 - +argument: 1, // 1 + +object: 1, // 1 |}; declare type PluralElement = { options: { [key: ValidPluralRule]: PluralOrSelectOption, ... }, @@ -692,39 +823,53 @@ declare module 'react-intl' { } & BaseElement; declare interface PluralOrSelectOption { value: MessageFormatElement[]; - location?: Location; + location?: Location_2; } declare interface PoundElement { type: typeof TYPE.pound; - location?: Location; + location?: Location_2; } declare type PrimitiveType = string | number | boolean | null | void | Date; declare type Props = { value?: number, unit?: Unit, updateIntervalInSeconds?: number, - children?: (value: string) => React.ReactChild, + children?: (value: string) => React_2.ReactChild, ... } & FormatRelativeTimeOptions; declare type Props_2 = { value: number, intl: IntlShape, - other: React$Node, - zero?: React$Node, - one?: React$Node, - two?: React$Node, - few?: React$Node, - many?: React$Node, - children?: (value: React$Node) => React.ReactElement<> | null, + other: React_2.Node, + zero?: React_2.Node, + one?: React_2.Node, + two?: React_2.Node, + few?: React_2.Node, + many?: React_2.Node, + children?: (value: React_2.Node) => React_2.ReactElement<> | null, ... } & FormatPluralOptions; - declare type Props_3 = { + declare type Props_3 = { values?: V, - tagName?: React.ElementType, - children?: (...nodes: React.ReactNodeArray) => React$Node, + tagName?: React_2.ElementType, + children?: (...nodes: React_2.ReactNodeArray) => React_2.Node, ... } & MessageDescriptor; - declare export var RawIntlProvider: React.Provider; + declare export var RawIntlProvider: React_2.Provider; + declare export class ReactIntlError< + T: $Values = typeof ReactIntlErrorCode.FORMAT_ERROR, + > mixins Error { + +code: T; + constructor(code: T, message: string, exception?: Error): this; + } + declare export var ReactIntlErrorCode: {| + +FORMAT_ERROR: 'FORMAT_ERROR', // "FORMAT_ERROR" + +UNSUPPORTED_FORMATTER: 'UNSUPPORTED_FORMATTER', // "UNSUPPORTED_FORMATTER" + +INVALID_CONFIG: 'INVALID_CONFIG', // "INVALID_CONFIG" + +MISSING_DATA: 'MISSING_DATA', // "MISSING_DATA" + +MISSING_TRANSLATION: 'MISSING_TRANSLATION', // "MISSING_TRANSLATION" + |}; + declare type RegionCode = string; declare type RelativeTimeData = $ObjMapi<{ [k: LDMLPluralRule]: any }, (u) => string>; declare type RelativeTimeField = | 'second' @@ -761,7 +906,7 @@ declare module 'react-intl' { options?: Pick, ): string[]; static __addLocaleData(...data: RelativeTimeLocaleData[]): void; - static localeData: { [key: string]: UnpackedLocaleFieldsData, ... }; + static localeData: { [key: string]: LocaleFieldsData, ... }; static polyfilled: boolean; } declare type RelativeTimeFormatNumberPart = { @@ -814,6 +959,7 @@ declare module 'react-intl' { numberingSystem: string, ... }; + declare type ScriptCode = string; declare type SelectElement = { options: { [key: string]: PluralOrSelectOption, ... }, ... @@ -824,8 +970,7 @@ declare module 'react-intl' { } & BaseElement; declare type Skeleton = NumberSkeleton | DateTimeSkeleton; declare var SKELETON_TYPE: {| - // underscore added in translating from TS; Flow complains of - // "Unexpected reserved type" + // Underscore added in TS to Flow translation ("Unexpected reserved type") +_number: 0, // 0 +dateTime: 1, // 1 |}; @@ -852,94 +997,26 @@ declare module 'react-intl' { prevValue?: number; currentValueInSeconds: number; } + declare interface TagElement { + type: typeof TYPE.tag; + value: string; + children: MessageFormatElement[]; + location?: Location_2; + } declare type TimeElement = SimpleFormatElement; - declare var TYPE: {| +literal: 0, // 0 +argument: 1, // 1 - // underscore added in translating from TS; Flow complains of - // "Unexpected reserved type" + // Underscore added in TS to Flow translation ("Unexpected reserved type") +_number: 2, // 2 +date: 3, // 3 +time: 4, // 4 +select: 5, // 5 +plural: 6, // 6 +pound: 7, // 7 + +tag: 8, // 8 |}; - declare type UnifiedNumberFormatOptions = Intl.NumberFormatOptions & - NumberFormatDigitOptions & { - localeMatcher?: UnifiedNumberFormatOptionsLocaleMatcher, - style?: UnifiedNumberFormatOptionsStyle, - compactDisplay?: UnifiedNumberFormatOptionsCompactDisplay, - currencyDisplay?: UnifiedNumberFormatOptionsCurrencyDisplay, - currencySign?: UnifiedNumberFormatOptionsCurrencySign, - notation?: UnifiedNumberFormatOptionsNotation, - signDisplay?: UnifiedNumberFormatOptionsSignDisplay, - unit?: Unit_2, - unitDisplay?: UnifiedNumberFormatOptionsUnitDisplay, - ... - }; - declare type UnifiedNumberFormatOptionsCompactDisplay = 'short' | 'long'; - declare type UnifiedNumberFormatOptionsCurrencyDisplay = - | 'symbol' - | 'code' - | 'name' - | 'narrowSymbol'; - declare type UnifiedNumberFormatOptionsCurrencySign = 'standard' | 'accounting'; - declare type UnifiedNumberFormatOptionsLocaleMatcher = 'lookup' | 'best fit'; - declare type UnifiedNumberFormatOptionsNotation = - | 'standard' - | 'scientific' - | 'engineering' - | 'compact'; - declare type UnifiedNumberFormatOptionsSignDisplay = 'auto' | 'always' | 'never' | 'exceptZero'; - declare type UnifiedNumberFormatOptionsStyle = 'decimal' | 'percent' | 'currency' | 'unit'; - declare type UnifiedNumberFormatOptionsUnitDisplay = 'long' | 'short' | 'narrow'; declare type Unit = 'second' | 'minute' | 'hour' | 'day' | 'week' | 'month' | 'quarter' | 'year'; - declare type Unit_2 = - | 'degree' - | 'acre' - | 'hectare' - | 'percent' - | 'bit' - | 'byte' - | 'gigabit' - | 'gigabyte' - | 'kilobit' - | 'kilobyte' - | 'megabit' - | 'megabyte' - | 'petabyte' - | 'terabit' - | 'terabyte' - | 'day' - | 'hour' - | 'millisecond' - | 'minute' - | 'month' - | 'second' - | 'week' - | 'year' - | 'centimeter' - | 'foot' - | 'inch' - | 'kilometer' - | 'meter' - | 'mile-scandinavian' - | 'mile' - | 'millimeter' - | 'yard' - | 'gram' - | 'kilogram' - | 'ounce' - | 'pound' - | 'stone' - | 'celsius' - | 'fahrenheit' - | 'fluid-ounce' - | 'gallon' - | 'liter' - | 'milliliter'; declare type Units = | 'seconds' | 'minutes' @@ -949,17 +1026,14 @@ declare module 'react-intl' { | 'months' | 'quarters' | 'years'; - declare type UnpackedLocaleFieldsData = $ObjMapi< - { [k: RelativeTimeField]: any }, - (f) => FieldData, - > & { - nu: Array, - ... - }; + declare export class UnsupportedFormatterError + mixins ReactIntlError { + constructor(message: string, exception?: Error): this; + } declare export function useIntl(): IntlShape; declare type ValidPluralRule = 'zero' | 'one' | 'two' | 'few' | 'many' | 'other' | string; declare export type WithIntlProps

= Omit>> & { - forwardedRef?: React.Ref, + forwardedRef?: React_2.Ref, ... }; declare export type WrappedComponentProps = $ObjMapi< @@ -968,156 +1042,3 @@ declare module 'react-intl' { >; declare export {}; } - -// @formatjs/intl-utils/dist/types.d.ts -declare module '@formatjs/intl-utils/types' { - declare export type Locale = string; - declare export interface LocaleData { - data: { [Locale]: T, ... }; - aliases: { [string]: string, ... }; - availableLocales: string[]; - parentLocales: { [string]: string, ... }; - } -} - -// @formatjs/intl-utils/dist/displaynames-types.d.ts -declare module '@formatjs/intl-utils/displaynames-types' { - import type { LocaleData } from '@formatjs/intl-utils/types'; - - declare export type LanguageTag = string; - declare export type RegionCode = string; - declare export type ScriptCode = string; - declare export type CurrencyCode = string; - declare export interface DisplayNamesData { - /** - * Note that for style fields, `short` and `narrow` might not exist. - * At runtime, the fallback order will be narrow -> short -> long. - */ - types: { - /** - * Maps language subtag like `zh-CN` to their display names. - */ - language: { - narrow: { [key: LanguageTag]: string, ... }, - short: { [key: LanguageTag]: string, ... }, - long: { [key: LanguageTag]: string, ... }, - ... - }, - region: { - narrow: { [key: RegionCode]: string, ... }, - short: { [key: RegionCode]: string, ... }, - long: { [key: RegionCode]: string, ... }, - ... - }, - script: { - narrow: { [key: ScriptCode]: string, ... }, - short: { [key: ScriptCode]: string, ... }, - long: { [key: ScriptCode]: string, ... }, - ... - }, - currency: { - narrow: { [key: CurrencyCode]: string, ... }, - short: { [key: CurrencyCode]: string, ... }, - long: { [key: CurrencyCode]: string, ... }, - ... - }, - ... - }; - - /** - * Not in spec, but we need this to display both language and region in display name. - * e.g. zh-Hans-SG + "{0}({1})" -> 简体中文(新加坡) - * Here {0} is replaced by language display name and {1} is replaced by region display name. - */ - patterns: { - locale: string, - ... - }; - } - declare export type DisplayNamesLocaleData = LocaleData; - declare export {}; -} - -// @formatjs/intl-utils/dist/index.d.ts -declare module '@formatjs/intl-utils' { - /** - * Flowtype definitions for @formatjs/intl-utils/dist/index.d.ts - * Generated by Flowgen from a Typescript Definition - * Flowgen v1.11.0 - */ - - // Only the part we use is uncommented. - - // declare export { selectUnit } from './diff'; - // declare export { - // defaultNumberOption, - // getAliasesByLang, - // getInternalSlot, - // getMultiInternalSlots, - // getNumberOption, - // getOption, - // getParentLocalesByLang, - // isLiteralPart, - // LiteralPart, - // partitionPattern, - // setInternalSlot, - // setMultiInternalSlots, - // setNumberFormatDigitOptions, - // toObject, - // objectIs, - // isWellFormedCurrencyCode, - // toString, - // } from './polyfill-utils'; - // declare export { - // createResolveLocale, - // getLocaleHierarchy, - // supportedLocales, - // unpackData, - // isMissingLocaleDataError, - // } from './resolve-locale'; - // declare export * from './units' - // declare export * from './relative-time-types' - // declare export * from './unified-numberformat-types' - // declare export * from './list-types' - // declare export * from './plural-rules-types' - // declare export * from './number-types' - declare export * from '@formatjs/intl-utils/displaynames-types' - // declare export { getCanonicalLocales } from './get-canonical-locales'; - // declare export { invariant } from './invariant'; -} - -// @formatjs/intl-displaynames/dist/index.d.ts -declare module '@formatjs/intl-displaynames' { - /** - * Flowtype definitions for index - * Generated by Flowgen from a Typescript Definition - * Flowgen v1.11.0 - */ - - import type { DisplayNamesLocaleData, DisplayNamesData } from '@formatjs/intl-utils'; - - declare export interface DisplayNamesOptions { - localeMatcher?: 'lookup' | 'best fit'; - style?: 'narrow' | 'short' | 'long'; - type?: 'language' | 'region' | 'script' | 'currency'; - fallback?: 'code' | 'none'; - } - declare export interface DisplayNamesResolvedOptions { - locale: string; - style: $NonMaybeType<$PropertyType>; - type: $NonMaybeType<$PropertyType>; - fallback: $NonMaybeType<$PropertyType>; - } - declare export class DisplayNames { - constructor(locales?: string | string[], options?: DisplayNamesOptions): this; - static supportedLocalesOf( - locales?: string | string[], - options?: Pick, - ): string[]; - static __addLocaleData(...data: DisplayNamesLocaleData[]): void; - of(code: string | number | { [key: string]: any }): string | void; - resolvedOptions(): DisplayNamesResolvedOptions; - static localeData: { [key: string]: DisplayNamesData, ... }; - static +polyfilled: any; // true - } -} diff --git a/package.json b/package.json index 129676f40ff..b2b7c6f331b 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "lodash.union": "^4.6.0", "lodash.uniqby": "^4.4.0", "react": "16.11.0", - "react-intl": "^3.12.1", + "react-intl": "5.8.6", "react-native": "0.62.2", "react-native-device-info": "^6.0.2", "react-native-document-picker": "^3.2.4", @@ -139,7 +139,7 @@ "react-native-web": "^0.13.3", "redux-mock-store": "^1.5.1", "rollup": "^2.26.5", - "typescript": "^3.9.7", + "typescript": "~3.8.3", "yarn-deduplicate": "^3.0.0" } } diff --git a/src/common/Input.js b/src/common/Input.js index d3c51acdcc5..14e40b6839e 100644 --- a/src/common/Input.js +++ b/src/common/Input.js @@ -82,10 +82,10 @@ export default class Input extends PureComponent { defaultMessage={fullPlaceholder.text} values={fullPlaceholder.values} > - {(text: string) => ( + {(chunks: string[]) => ( Date: Fri, 7 Aug 2020 12:05:39 -0700 Subject: [PATCH 7/8] react-intl libdef: Make some React type annotations useful. Not sure why the TypeScript file is calling it React_2 instead of React...anyway, handle these, like we did in two recent commits. --- flow-typed/react-intl_vx.x.x.js | 73 +++++++++++++++++---------------- 1 file changed, 38 insertions(+), 35 deletions(-) diff --git a/flow-typed/react-intl_vx.x.x.js b/flow-typed/react-intl_vx.x.x.js index 6c2296564c3..4e2c9909149 100644 --- a/flow-typed/react-intl_vx.x.x.js +++ b/flow-typed/react-intl_vx.x.x.js @@ -209,29 +209,29 @@ declare module 'react-intl' { time: { [key: string]: Intl.DateTimeFormatOptions, ... }; } declare type FormattableUnit = Unit | Units; - declare export var FormattedDate: React_2.FC< + declare export var FormattedDate: React$StatelessFunctionalComponent< DateTimeFormatOptions & CustomFormatConfig & { value: string | number | Date | void, ... }, >; - declare export var FormattedDateParts: React_2.FC< + declare export var FormattedDateParts: React$StatelessFunctionalComponent< FormatDateOptions & { value: $ElementType>, 0> | string, children(val: Intl.DateTimeFormatPart[]): React_2.ReactElement<> | null, ... }, >; - declare export var FormattedDisplayName: React_2.FC< + declare export var FormattedDisplayName: React$StatelessFunctionalComponent< DisplayNamesOptions & { value: string | number | { [key: string]: any }, ... }, >; - declare export var FormattedList: React_2.FC< + declare export var FormattedList: React$StatelessFunctionalComponent< IntlListFormatOptions & { - value: React_2.Node[], + value: React$Node[], ... }, >; @@ -240,33 +240,35 @@ declare module 'react-intl' { [key: string]: | PrimitiveType | React_2.ReactElement<> - | FormatXMLElementFn, + | FormatXMLElementFn, ..., }, - > mixins React_2.Component> { + // Changed `mixins` to `extends` in TS to Flow translation + > extends React$Component> { static displayName: string; shouldComponentUpdate(nextProps: Props_3): boolean; render(): React$Node; } - declare export var FormattedNumber: React_2.FC< + declare export var FormattedNumber: React$StatelessFunctionalComponent< NumberFormatOptions & CustomFormatConfig & { value: number, ... }, >; - declare export var FormattedNumberParts: React_2.FC< + declare export var FormattedNumberParts: React$StatelessFunctionalComponent< $PropertyType & { value: $ElementType>, 0>, children(val: Intl.NumberFormatPart[]): React_2.ReactElement<> | null, ... }, >; - declare export var FormattedPlural: React_2.FC> & { - WrappedComponent: React_2.ComponentType, + declare export var FormattedPlural: React$StatelessFunctionalComponent> & { + WrappedComponent: React$ComponentType, ... }; - declare export class FormattedRelativeTime mixins React_2.PureComponent { + // Changed `mixins` to `extends` in TS to Flow translation + declare export class FormattedRelativeTime extends React$PureComponent { _updateTimer: any; static displayName: string; static defaultProps: Pick; @@ -279,14 +281,14 @@ declare module 'react-intl' { static getDerivedStateFromProps(props: Props, state: State_2): $Rest | null; render(): React$Node; } - declare export var FormattedTime: React_2.FC< + declare export var FormattedTime: React$StatelessFunctionalComponent< DateTimeFormatOptions & CustomFormatConfig & { value: string | number | Date | void, ... }, >; - declare export var FormattedTimeParts: React_2.FC< + declare export var FormattedTimeParts: React$StatelessFunctionalComponent< FormatDateOptions & { value: $ElementType>, 0> | string, children(val: Intl.DateTimeFormatPart[]): React_2.ReactElement<> | null, @@ -325,23 +327,23 @@ declare module 'react-intl' { parts: Array, ) => R; declare export function injectIntl>( - WrappedComponent: React_2.ComponentType

, + WrappedComponent: React$ComponentType

, options?: Opts, - ): React_2.FC> & { - WrappedComponent: React_2.ComponentType

, + ): React$StatelessFunctionalComponent> & { + WrappedComponent: React$ComponentType

, ... }; declare export function injectIntl< IntlPropName: string, P: WrappedComponentProps, - T: React_2.ComponentType

, + T: React$ComponentType

, >( - WrappedComponent: React_2.ComponentType

, + WrappedComponent: React$ComponentType

, options?: Opts, ): React_2.ForwardRefExoticComponent< React_2.PropsWithoutRef>> & React_2.RefAttributes, > & { - WrappedComponent: React_2.ComponentType

, + WrappedComponent: React$ComponentType

, ... }; declare export interface IntlCache { @@ -357,7 +359,7 @@ declare module 'react-intl' { locale: string; timeZone?: string; formats: CustomFormats; - textComponent?: React_2.ComponentType<> | $Keys; + textComponent?: React$ComponentType<> | $Keys; messages: { [key: string]: string, ... } | { [key: string]: MessageFormatElement[], ... }; defaultLocale: string; defaultFormats: CustomFormats; @@ -372,8 +374,8 @@ declare module 'react-intl' { | FormatError, ): void; } - declare export var IntlContext: React_2.Context; - declare export interface IntlFormatters { + declare export var IntlContext: React$Context; + declare export interface IntlFormatters { formatDate( value: $ElementType>, 0> | string, opts?: FormatDateOptions, @@ -417,10 +419,10 @@ declare module 'react-intl' { descriptor: MessageDescriptor, // The `+` was added to make the properties covariant rather // than invariant, something TypeScript can't do. - values?: { +[key: string]: PrimitiveType | React_2.Node | FormatXMLElementFn, ... }, + values?: { +[key: string]: PrimitiveType | React$Node | FormatXMLElementFn, ... }, ): React$Node; formatList(values: Array, opts?: FormatListOptions): string; - formatList(values: Array, opts?: FormatListOptions): React_2.Node; + formatList(values: Array, opts?: FormatListOptions): React$Node; formatDisplayName( value: $ElementType>, 0>, opts?: FormatDisplayNameOptions, @@ -567,7 +569,8 @@ declare module 'react-intl' { }; } declare export class IntlProvider - mixins React_2.PureComponent, State> { + // Changed `mixins` to `extends` in TS to Flow translation + extends React$PureComponent, State> { static displayName: string; static defaultProps: Pick< IntlConfig, @@ -840,19 +843,19 @@ declare module 'react-intl' { declare type Props_2 = { value: number, intl: IntlShape, - other: React_2.Node, - zero?: React_2.Node, - one?: React_2.Node, - two?: React_2.Node, - few?: React_2.Node, - many?: React_2.Node, - children?: (value: React_2.Node) => React_2.ReactElement<> | null, + other: React$Node, + zero?: React$Node, + one?: React$Node, + two?: React$Node, + few?: React$Node, + many?: React$Node, + children?: (value: React$Node) => React_2.ReactElement<> | null, ... } & FormatPluralOptions; - declare type Props_3 = { + declare type Props_3 = { values?: V, tagName?: React_2.ElementType, - children?: (...nodes: React_2.ReactNodeArray) => React_2.Node, + children?: (...nodes: React_2.ReactNodeArray) => React$Node, ... } & MessageDescriptor; declare export var RawIntlProvider: React_2.Provider; From 273481110f7430a119d226cf36a786c5ec645813 Mon Sep 17 00:00:00 2001 From: Chris Bobbe Date: Tue, 11 Aug 2020 12:28:12 -0700 Subject: [PATCH 8/8] common/Input: Avoid not-recommended way of using `react-intl` API. Following from discussion on GitHub [1]. We would have a bug if multiple chunks were passed to the render callback prop [2], since we're just using the first one. It looks like multiple chunks won't be passed, since we haven't explicitly made that happen. Glad to have this API misuse exposed by the API change in `react-intl` v5, which we took in a recent commit: "`FormattedMessage` render prop is no longer variadic". But we don't need to use this render prop pattern at all. From the docs [3]: """ If you need to customize rendering, you can either [...] or pass a function as the child. """ We just need plain old strings, without customization. So, just do the more straightforward thing we do in a bunch of places: use `formatMessage` as it's wrapped by `_`. Plumb through `_` using `withGetText` as recommended by the JSDoc for `GetText`: """ Alternatively, for when `context` is already in use: use `withGetText` and then say `const { _ } = this.props`. """ [1] https://github.com/zulip/zulip-mobile/pull/4222#discussion_r468244576 [2] The render callback prop's name is `children`. The "Function as Child Component" pattern is sometimes opposed because `children` is rarely an appropriate, expressive name; see, e.g., https://americanexpress.io/faccs-are-an-antipattern/. Here, it also doesn't seem to be well-typed in the libdef. I'm unsure if the "FaCC" pattern makes it especially hard to get well-typed, but it seems plausible. [3] https://github.com/zulip/zulip-mobile/pull/4222#discussion_r468244576 --- src/common/Input.js | 40 ++++++++++++++---------------- src/common/InputWithClearButton.js | 2 +- src/common/PasswordInput.js | 2 +- 3 files changed, 20 insertions(+), 24 deletions(-) diff --git a/src/common/Input.js b/src/common/Input.js index 14e40b6839e..1cd1398b810 100644 --- a/src/common/Input.js +++ b/src/common/Input.js @@ -1,11 +1,11 @@ /* @flow strict-local */ import React, { PureComponent } from 'react'; import { TextInput, Platform } from 'react-native'; -import { FormattedMessage } from 'react-intl'; -import type { LocalizableText } from '../types'; +import type { LocalizableText, GetText } from '../types'; import type { ThemeData } from '../styles'; import { ThemeContext, HALF_COLOR, BORDER_COLOR } from '../styles'; +import { withGetText } from '../boot/TranslationProvider'; export type Props = $ReadOnly<{| // Should be fixed in RN v0.63 (#4245); see @@ -15,6 +15,8 @@ export type Props = $ReadOnly<{| placeholder: LocalizableText, onChangeText?: (text: string) => void, textInputRef?: React$Ref, + + _: GetText, |}>; type State = {| @@ -35,7 +37,7 @@ type State = {| * @prop ...all other TextInput props - Passed through verbatim to TextInput. * See upstream: https://reactnative.dev/docs/textinput */ -export default class Input extends PureComponent { +class Input extends PureComponent { static contextType = ThemeContext; context: ThemeData; @@ -69,7 +71,7 @@ export default class Input extends PureComponent { }; render() { - const { style, placeholder, textInputRef, ...restProps } = this.props; + const { style, placeholder, textInputRef, _, ...restProps } = this.props; const { isFocused } = this.state; const fullPlaceholder = typeof placeholder === 'object' /* force linebreak */ @@ -77,24 +79,18 @@ export default class Input extends PureComponent { : { text: placeholder, values: undefined }; return ( - - {(chunks: string[]) => ( - - )} - + ); } } + +export default withGetText(Input); diff --git a/src/common/InputWithClearButton.js b/src/common/InputWithClearButton.js index 79a5a38904e..334082890a8 100644 --- a/src/common/InputWithClearButton.js +++ b/src/common/InputWithClearButton.js @@ -14,7 +14,7 @@ const componentStyles = createStyleSheet({ }, }); -type Props = $ReadOnly<$Diff>; +type Props = $ReadOnly<$Diff>; type State = {| canBeCleared: boolean, diff --git a/src/common/PasswordInput.js b/src/common/PasswordInput.js index 2904bf34502..bbe66f6c5e8 100644 --- a/src/common/PasswordInput.js +++ b/src/common/PasswordInput.js @@ -27,7 +27,7 @@ const styles = createStyleSheet({ type Props = $ReadOnly<$Diff>; + { secureTextEntry: mixed, autoCorrect: mixed, autoCapitalize: mixed, _: mixed }>>; type State = {| isHidden: boolean,