lighthouse 8.5.1 → 8.6.0-dev.20211016

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. package/changelog.md +5490 -0
  2. package/dist/report/flow.js +35 -12
  3. package/dist/report/standalone.js +20 -21
  4. package/flow-report/.eslintrc.cjs +49 -0
  5. package/flow-report/assets/styles.css +272 -9
  6. package/flow-report/jest.config.js +1 -1
  7. package/flow-report/package.json +4 -0
  8. package/flow-report/src/app.tsx +31 -9
  9. package/flow-report/src/common.tsx +86 -7
  10. package/flow-report/src/header.tsx +88 -0
  11. package/flow-report/src/help-dialog.tsx +120 -0
  12. package/flow-report/src/i18n/i18n.tsx +52 -0
  13. package/flow-report/src/i18n/localized-strings.js +11 -0
  14. package/flow-report/src/i18n/ui-strings.js +134 -0
  15. package/flow-report/src/icons.tsx +20 -3
  16. package/flow-report/src/sidebar/sidebar.tsx +11 -16
  17. package/flow-report/src/summary/category.tsx +39 -24
  18. package/flow-report/src/summary/summary.tsx +35 -32
  19. package/flow-report/src/topbar.tsx +54 -4
  20. package/flow-report/src/util.ts +26 -1
  21. package/flow-report/src/wrappers/report-renderer.tsx +1 -1
  22. package/flow-report/src/wrappers/report.tsx +6 -21
  23. package/flow-report/test/app-test.tsx +17 -13
  24. package/flow-report/test/common-test.tsx +89 -0
  25. package/flow-report/test/header-test.tsx +55 -0
  26. package/flow-report/test/sample-flow.ts +17 -0
  27. package/flow-report/test/setup/env-setup.ts +1 -0
  28. package/flow-report/test/sidebar/flow-test.tsx +6 -12
  29. package/flow-report/test/sidebar/sidebar-test.tsx +7 -13
  30. package/flow-report/test/summary/category-test.tsx +83 -34
  31. package/flow-report/test/summary/summary-test.tsx +12 -18
  32. package/flow-report/test/topbar-test.tsx +68 -0
  33. package/flow-report/test/util-test.tsx +1 -12
  34. package/flow-report/tsconfig.json +2 -0
  35. package/flow-report/types/flow-report.d.ts +2 -1
  36. package/jest.config.js +1 -15
  37. package/lighthouse-cli/bin.js +5 -0
  38. package/lighthouse-cli/cli-flags.js +10 -3
  39. package/lighthouse-cli/commands/commands.js +1 -0
  40. package/lighthouse-cli/commands/list-locales.js +16 -0
  41. package/lighthouse-cli/run.js +2 -2
  42. package/lighthouse-cli/test/smokehouse/frontends/smokehouse-bin.js +0 -0
  43. package/lighthouse-cli/test/smokehouse/report-assert.js +20 -4
  44. package/lighthouse-core/audits/byte-efficiency/byte-efficiency-audit.js +2 -1
  45. package/lighthouse-core/audits/byte-efficiency/unused-javascript.js +1 -1
  46. package/lighthouse-core/audits/seo/crawlable-anchors.js +10 -12
  47. package/lighthouse-core/computed/js-bundles.js +1 -2
  48. package/lighthouse-core/computed/unused-javascript-summary.js +3 -3
  49. package/lighthouse-core/config/config-helpers.js +1 -0
  50. package/lighthouse-core/config/config.js +2 -2
  51. package/lighthouse-core/config/default-config.js +5 -0
  52. package/lighthouse-core/fraggle-rock/api.js +10 -0
  53. package/lighthouse-core/fraggle-rock/config/filters.js +22 -3
  54. package/lighthouse-core/fraggle-rock/gather/driver.js +4 -0
  55. package/lighthouse-core/fraggle-rock/gather/navigation-runner.js +2 -2
  56. package/lighthouse-core/fraggle-rock/user-flow.js +35 -6
  57. package/lighthouse-core/gather/driver/navigation.js +5 -0
  58. package/lighthouse-core/gather/driver/prepare.js +14 -0
  59. package/lighthouse-core/gather/driver/storage.js +5 -0
  60. package/lighthouse-core/gather/gather-runner.js +2 -2
  61. package/lighthouse-core/gather/gatherers/dobetterweb/response-compression.js +5 -1
  62. package/lighthouse-core/gather/gatherers/full-page-screenshot.js +30 -24
  63. package/lighthouse-core/lib/cdt/Platform.js +55 -0
  64. package/lighthouse-core/lib/cdt/SDK.js +3 -123
  65. package/lighthouse-core/lib/cdt/generated/SourceMap.js +148 -312
  66. package/lighthouse-core/lib/csp-evaluator.js +2 -1
  67. package/lighthouse-core/lib/i18n/README.md +6 -6
  68. package/lighthouse-core/lib/i18n/i18n.js +26 -348
  69. package/lighthouse-core/lib/page-functions.js +4 -4
  70. package/lighthouse-core/lib/stack-packs.js +1 -13
  71. package/lighthouse-core/runner.js +6 -6
  72. package/lighthouse-core/scripts/manual-chrome-launcher.js +4 -1
  73. package/lighthouse-core/scripts/package.json +4 -0
  74. package/lighthouse-core/util-commonjs.js +20 -4
  75. package/package.json +19 -16
  76. package/readme.md +1 -1
  77. package/report/assets/standalone-template.html +0 -1
  78. package/report/assets/styles.css +16 -41
  79. package/report/assets/templates.html +42 -4
  80. package/report/clients/psi.js +1 -0
  81. package/report/clients/standalone.js +1 -2
  82. package/report/generator/file-namer.js +17 -8
  83. package/report/generator/report-generator.js +0 -1
  84. package/report/renderer/category-renderer.js +4 -16
  85. package/report/renderer/components.js +107 -71
  86. package/report/renderer/dom.js +19 -0
  87. package/report/renderer/logger.js +35 -2
  88. package/report/renderer/performance-category-renderer.js +23 -21
  89. package/report/renderer/pwa-category-renderer.js +1 -2
  90. package/report/renderer/report-renderer.js +21 -0
  91. package/report/renderer/report-ui-features.js +7 -19
  92. package/report/renderer/swap-locale-feature.js +82 -0
  93. package/report/renderer/util.js +20 -4
  94. package/report/test/clients/psi-test.js +0 -4
  95. package/report/test/generator/file-namer-test.js +2 -2
  96. package/report/test/renderer/category-renderer-test.js +1 -1
  97. package/report/test/renderer/performance-category-renderer-test.js +12 -0
  98. package/report/test/renderer/report-renderer-axe-test.js +86 -0
  99. package/report/test/renderer/report-renderer-test.js +0 -55
  100. package/report/test/renderer/util-test.js +68 -8
  101. package/report/test-assets/faux-psi-template.html +0 -1
  102. package/report/tsconfig.json +2 -1
  103. package/report/types/html-renderer.d.ts +2 -1
  104. package/root.js +18 -0
  105. package/shared/localization/format.js +455 -0
  106. package/{lighthouse-core/lib/cdt/Common.js → shared/localization/i18n-module.js} +3 -8
  107. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ar-XB.json +139 -4
  108. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ar.json +141 -6
  109. package/{lighthouse-core/lib/i18n → shared/localization}/locales/bg.json +139 -4
  110. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ca.json +140 -5
  111. package/{lighthouse-core/lib/i18n → shared/localization}/locales/cs.json +139 -4
  112. package/{lighthouse-core/lib/i18n → shared/localization}/locales/da.json +139 -4
  113. package/{lighthouse-core/lib/i18n → shared/localization}/locales/de.json +139 -4
  114. package/{lighthouse-core/lib/i18n → shared/localization}/locales/el.json +141 -6
  115. package/{lighthouse-core/lib/i18n → shared/localization}/locales/en-GB.json +139 -4
  116. package/{lighthouse-core/lib/i18n → shared/localization}/locales/en-US.json +129 -0
  117. package/{lighthouse-core/lib/i18n → shared/localization}/locales/en-XA.json +139 -4
  118. package/{lighthouse-core/lib/i18n → shared/localization}/locales/en-XL.json +129 -0
  119. package/{lighthouse-core/lib/i18n → shared/localization}/locales/es-419.json +139 -4
  120. package/{lighthouse-core/lib/i18n → shared/localization}/locales/es.json +139 -4
  121. package/{lighthouse-core/lib/i18n → shared/localization}/locales/fi.json +139 -4
  122. package/{lighthouse-core/lib/i18n → shared/localization}/locales/fil.json +139 -4
  123. package/{lighthouse-core/lib/i18n → shared/localization}/locales/fr.json +139 -4
  124. package/{lighthouse-core/lib/i18n → shared/localization}/locales/he.json +139 -4
  125. package/{lighthouse-core/lib/i18n → shared/localization}/locales/hi.json +142 -7
  126. package/{lighthouse-core/lib/i18n → shared/localization}/locales/hr.json +139 -4
  127. package/{lighthouse-core/lib/i18n → shared/localization}/locales/hu.json +139 -4
  128. package/{lighthouse-core/lib/i18n → shared/localization}/locales/id.json +139 -4
  129. package/{lighthouse-core/lib/i18n → shared/localization}/locales/it.json +139 -4
  130. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ja.json +139 -4
  131. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ko.json +139 -4
  132. package/{lighthouse-core/lib/i18n → shared/localization}/locales/lt.json +139 -4
  133. package/{lighthouse-core/lib/i18n → shared/localization}/locales/lv.json +139 -4
  134. package/{lighthouse-core/lib/i18n → shared/localization}/locales/nl.json +139 -4
  135. package/{lighthouse-core/lib/i18n → shared/localization}/locales/no.json +139 -4
  136. package/{lighthouse-core/lib/i18n → shared/localization}/locales/pl.json +139 -4
  137. package/{lighthouse-core/lib/i18n → shared/localization}/locales/pt-PT.json +139 -4
  138. package/{lighthouse-core/lib/i18n → shared/localization}/locales/pt.json +139 -4
  139. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ro.json +139 -4
  140. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ru.json +139 -4
  141. package/{lighthouse-core/lib/i18n → shared/localization}/locales/sk.json +139 -4
  142. package/{lighthouse-core/lib/i18n → shared/localization}/locales/sl.json +139 -4
  143. package/{lighthouse-core/lib/i18n → shared/localization}/locales/sr-Latn.json +139 -4
  144. package/{lighthouse-core/lib/i18n → shared/localization}/locales/sr.json +139 -4
  145. package/{lighthouse-core/lib/i18n → shared/localization}/locales/sv.json +139 -4
  146. package/{lighthouse-core/lib/i18n → shared/localization}/locales/ta.json +146 -11
  147. package/{lighthouse-core/lib/i18n → shared/localization}/locales/te.json +179 -44
  148. package/{lighthouse-core/lib/i18n → shared/localization}/locales/th.json +139 -4
  149. package/{lighthouse-core/lib/i18n → shared/localization}/locales/tr.json +139 -4
  150. package/{lighthouse-core/lib/i18n → shared/localization}/locales/uk.json +139 -4
  151. package/{lighthouse-core/lib/i18n → shared/localization}/locales/vi.json +139 -4
  152. package/{lighthouse-core/lib/i18n → shared/localization}/locales/zh-HK.json +139 -4
  153. package/{lighthouse-core/lib/i18n → shared/localization}/locales/zh-TW.json +139 -4
  154. package/{lighthouse-core/lib/i18n → shared/localization}/locales/zh.json +139 -4
  155. package/{lighthouse-core/lib/i18n → shared/localization}/locales.js +8 -1
  156. package/shared/localization/swap-flow-locale.js +20 -0
  157. package/{lighthouse-core/lib/i18n → shared/localization}/swap-locale.js +9 -7
  158. package/shared/test/localization/format-test.js +421 -0
  159. package/shared/test/localization/locales-test.js +47 -0
  160. package/shared/test/localization/swap-locale-test.js +140 -0
  161. package/shared/tsconfig.json +22 -0
  162. package/{lighthouse-core/lib → shared}/type-verifiers.js +0 -0
  163. package/shared/types/shared.d.ts +24 -0
  164. package/third-party/chromium-synchronization/inspector-issueAdded-types-test.js +5 -3
  165. package/third-party/chromium-synchronization/installability-errors-test.js +2 -1
  166. package/tsconfig-all.json +1 -0
  167. package/tsconfig-base.json +1 -1
  168. package/tsconfig.json +2 -3
  169. package/types/config.d.ts +1 -0
  170. package/types/es-main.d.ts +18 -0
  171. package/types/externs.d.ts +2 -0
  172. package/types/lhr/flow.d.ts +7 -0
  173. package/types/lhr/i18n.d.ts +0 -3
@@ -0,0 +1,455 @@
1
+ /**
2
+ * @license Copyright 2021 The Lighthouse Authors. All Rights Reserved.
3
+ * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
4
+ * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
5
+ */
6
+ 'use strict';
7
+
8
+ const fs = require('fs');
9
+
10
+ const MessageFormat = require('intl-messageformat').default;
11
+ const {isObjectOfUnknownValues, isObjectOrArrayOfUnknownValues} = require('../type-verifiers.js');
12
+
13
+ /** Contains available locales with messages. May be an empty object if bundled. */
14
+ const LOCALE_MESSAGES = require('./locales.js');
15
+
16
+ const DEFAULT_LOCALE = 'en-US';
17
+
18
+ /**
19
+ * The locale tags for the localized messages available to Lighthouse on disk.
20
+ * When bundled, these will be inlined by brfs.
21
+ * These locales are considered the "canonical" locales. We support other locales which
22
+ * are simply aliases to one of these. ex: es-AR (alias) -> es-419 (canonical)
23
+ */
24
+ let CANONICAL_LOCALES = ['__availableLocales__'];
25
+ // TODO: need brfs in gh-pages-app. For now, above is replaced, see build-i18n.module.js
26
+ if (fs.readdirSync) {
27
+ CANONICAL_LOCALES = fs.readdirSync(__dirname + '/locales/')
28
+ .filter(basename => basename.endsWith('.json') && !basename.endsWith('.ctc.json'))
29
+ .map(locale => locale.replace('.json', ''))
30
+ .sort();
31
+ }
32
+
33
+ /** @typedef {import('intl-messageformat-parser').Element} MessageElement */
34
+ /** @typedef {import('intl-messageformat-parser').ArgumentElement} ArgumentElement */
35
+
36
+ const MESSAGE_I18N_ID_REGEX = / | [^\s]+$/;
37
+
38
+ const formats = {
39
+ number: {
40
+ bytes: {
41
+ maximumFractionDigits: 0,
42
+ },
43
+ milliseconds: {
44
+ maximumFractionDigits: 0,
45
+ },
46
+ seconds: {
47
+ // Force the seconds to the tenths place for limited output and ease of scanning
48
+ minimumFractionDigits: 1,
49
+ maximumFractionDigits: 1,
50
+ },
51
+ extendedPercent: {
52
+ // Force allow up to two digits after decimal place in percentages. (Intl.NumberFormat options)
53
+ maximumFractionDigits: 2,
54
+ style: 'percent',
55
+ },
56
+ },
57
+ };
58
+
59
+ /**
60
+ * Function to retrieve all 'argumentElement's from an ICU message. An argumentElement
61
+ * is an ICU element with an argument in it, like '{varName}' or '{varName, number, bytes}'. This
62
+ * differs from 'messageElement's which are just arbitrary text in a message.
63
+ *
64
+ * Notes:
65
+ * This function will recursively inspect plural elements for nested argumentElements.
66
+ *
67
+ * We need to find all the elements from the plural format sections, but
68
+ * they need to be deduplicated. I.e. "=1{hello {icu}} =other{hello {icu}}"
69
+ * the variable "icu" would appear twice if it wasn't de duplicated. And they cannot
70
+ * be stored in a set because they are not equal since their locations are different,
71
+ * thus they are stored via a Map keyed on the "id" which is the ICU varName.
72
+ *
73
+ * @param {Array<MessageElement>} icuElements
74
+ * @param {Map<string, ArgumentElement>} [seenElementsById]
75
+ * @return {Map<string, ArgumentElement>}
76
+ */
77
+ function collectAllCustomElementsFromICU(icuElements, seenElementsById = new Map()) {
78
+ for (const el of icuElements) {
79
+ // We are only interested in elements that need ICU formatting (argumentElements)
80
+ if (el.type !== 'argumentElement') continue;
81
+
82
+ seenElementsById.set(el.id, el);
83
+
84
+ // Plurals need to be inspected recursively
85
+ if (!el.format || el.format.type !== 'pluralFormat') continue;
86
+ // Look at all options of the plural (=1{} =other{}...)
87
+ for (const option of el.format.options) {
88
+ // Run collections on each option's elements
89
+ collectAllCustomElementsFromICU(option.value.elements, seenElementsById);
90
+ }
91
+ }
92
+
93
+ return seenElementsById;
94
+ }
95
+
96
+ /**
97
+ * Returns a copy of the `values` object, with the values formatted based on how
98
+ * they will be used in their icuMessage, e.g. KB or milliseconds. The original
99
+ * object is unchanged.
100
+ * @param {MessageFormat} messageFormatter
101
+ * @param {Readonly<Record<string, string | number>>} values
102
+ * @param {string} lhlMessage Used for clear error logging.
103
+ * @return {Record<string, string | number>}
104
+ */
105
+ function _preformatValues(messageFormatter, values, lhlMessage) {
106
+ const elementMap = collectAllCustomElementsFromICU(messageFormatter.getAst().elements);
107
+ const argumentElements = [...elementMap.values()];
108
+
109
+ /** @type {Record<string, string | number>} */
110
+ const formattedValues = {};
111
+
112
+ for (const {id, format} of argumentElements) {
113
+ // Throw an error if a message's value isn't provided
114
+ if (id && (id in values) === false) {
115
+ throw new Error(`ICU Message "${lhlMessage}" contains a value reference ("${id}") ` +
116
+ `that wasn't provided`);
117
+ }
118
+
119
+ const value = values[id];
120
+
121
+ // Direct `{id}` replacement and non-numeric values need no formatting.
122
+ if (!format || format.type !== 'numberFormat') {
123
+ formattedValues[id] = value;
124
+ continue;
125
+ }
126
+
127
+ if (typeof value !== 'number') {
128
+ throw new Error(`ICU Message "${lhlMessage}" contains a numeric reference ("${id}") ` +
129
+ 'but provided value was not a number');
130
+ }
131
+
132
+ // Format values for known styles.
133
+ if (format.style === 'milliseconds') {
134
+ // Round all milliseconds to the nearest 10.
135
+ formattedValues[id] = Math.round(value / 10) * 10;
136
+ } else if (format.style === 'seconds' && id === 'timeInMs') {
137
+ // Convert all seconds to the correct unit (currently only for `timeInMs`).
138
+ formattedValues[id] = Math.round(value / 100) / 10;
139
+ } else if (format.style === 'bytes') {
140
+ // Replace all the bytes with KB.
141
+ formattedValues[id] = value / 1024;
142
+ } else {
143
+ // For all other number styles, the value isn't changed.
144
+ formattedValues[id] = value;
145
+ }
146
+ }
147
+
148
+ // Throw an error if a value is provided but has no placeholder in the message.
149
+ for (const valueId of Object.keys(values)) {
150
+ if (valueId in formattedValues) continue;
151
+
152
+ // errorCode is a special case always allowed to help LHError ease-of-use.
153
+ if (valueId === 'errorCode') {
154
+ formattedValues.errorCode = values.errorCode;
155
+ continue;
156
+ }
157
+
158
+ throw new Error(`Provided value "${valueId}" does not match any placeholder in ` +
159
+ `ICU message "${lhlMessage}"`);
160
+ }
161
+
162
+ return formattedValues;
163
+ }
164
+
165
+ /**
166
+ * Format string `message` by localizing `values` and inserting them. `message`
167
+ * is assumed to already be in the given locale.
168
+ * If you need to localize a messagem `getFormatted` is probably what you want.
169
+ * @param {string} message
170
+ * @param {Record<string, string | number>} values
171
+ * @param {LH.Locale} locale
172
+ * @return {string}
173
+ */
174
+ function formatMessage(message, values = {}, locale) {
175
+ // When using accented english, force the use of a different locale for number formatting.
176
+ const localeForMessageFormat = (locale === 'en-XA' || locale === 'en-XL') ? 'de-DE' : locale;
177
+
178
+ const formatter = new MessageFormat(message, localeForMessageFormat, formats);
179
+
180
+ // Preformat values for the message format like KB and milliseconds.
181
+ const valuesForMessageFormat = _preformatValues(formatter, values, message);
182
+
183
+ return formatter.format(valuesForMessageFormat);
184
+ }
185
+
186
+ /**
187
+ * Retrieves the localized version of `icuMessage` and formats with any given
188
+ * value replacements.
189
+ * @param {LH.IcuMessage} icuMessage
190
+ * @param {LH.Locale} locale
191
+ * @return {string}
192
+ */
193
+ function _localizeIcuMessage(icuMessage, locale) {
194
+ const localeMessages = _getLocaleMessages(locale);
195
+ const localeMessage = localeMessages[icuMessage.i18nId];
196
+
197
+ // Use the DEFAULT_LOCALE fallback (usually the original english message) if we couldn't
198
+ // find a message in the specified locale. Possible reasons:
199
+ // - string drift between Lighthouse versions
200
+ // - in a bundle stripped of locale files but running in the DEFAULT_LOCALE
201
+ // - new strings haven't been updated yet in a local dev run
202
+ // Better to have an english message than no message at all; in some cases it
203
+ // won't even matter.
204
+ if (!localeMessage) {
205
+ return icuMessage.formattedDefault;
206
+ }
207
+
208
+ return formatMessage(localeMessage.message, icuMessage.values, locale);
209
+ }
210
+
211
+ /**
212
+ * @param {LH.Locale} locale
213
+ * @return {Record<string, string>}
214
+ */
215
+ function getRendererFormattedStrings(locale) {
216
+ const localeMessages = _getLocaleMessages(locale);
217
+
218
+ // If `localeMessages` is empty in the bundled and DEFAULT_LOCALE case, this
219
+ // will be empty and the report will fall back to the util UIStrings for these.
220
+ const icuMessageIds = Object.keys(localeMessages).filter(f => f.startsWith('report/'));
221
+ /** @type {Record<string, string>} */
222
+ const strings = {};
223
+ for (const icuMessageId of icuMessageIds) {
224
+ const {filename, key} = getIcuMessageIdParts(icuMessageId);
225
+ if (!filename.endsWith('util.js')) throw new Error(`Unexpected message: ${icuMessageId}`);
226
+
227
+ strings[key] = localeMessages[icuMessageId].message;
228
+ }
229
+
230
+ return strings;
231
+ }
232
+
233
+ /**
234
+ * Returns whether `icuMessageOrNot`` is an `LH.IcuMessage` instance.
235
+ * @param {unknown} icuMessageOrNot
236
+ * @return {icuMessageOrNot is LH.IcuMessage}
237
+ */
238
+ function isIcuMessage(icuMessageOrNot) {
239
+ if (!isObjectOfUnknownValues(icuMessageOrNot)) {
240
+ return false;
241
+ }
242
+
243
+ const {i18nId, values, formattedDefault} = icuMessageOrNot;
244
+ if (typeof i18nId !== 'string') {
245
+ return false;
246
+ }
247
+
248
+ // formattedDefault is required.
249
+ if (typeof formattedDefault !== 'string') {
250
+ return false;
251
+ }
252
+
253
+ // Values is optional.
254
+ if (values !== undefined) {
255
+ if (!isObjectOfUnknownValues(values)) {
256
+ return false;
257
+ }
258
+ for (const value of Object.values(values)) {
259
+ if (typeof value !== 'string' && typeof value !== 'number') {
260
+ return false;
261
+ }
262
+ }
263
+ }
264
+
265
+ // Finally return true if i18nId seems correct.
266
+ return MESSAGE_I18N_ID_REGEX.test(i18nId);
267
+ }
268
+
269
+ /**
270
+ * Get the localized and formatted form of `icuMessageOrRawString` if it's an
271
+ * LH.IcuMessage, or get it back directly if it's already a string.
272
+ * Warning: this function throws if `icuMessageOrRawString` is not the expected
273
+ * type (use function from `createIcuMessageFn` to create a valid LH.IcuMessage)
274
+ * or `locale` isn't supported (use `lookupLocale` to find a valid locale).
275
+ * @param {LH.IcuMessage | string} icuMessageOrRawString
276
+ * @param {LH.Locale} locale
277
+ * @return {string}
278
+ */
279
+ function getFormatted(icuMessageOrRawString, locale) {
280
+ if (isIcuMessage(icuMessageOrRawString)) {
281
+ return _localizeIcuMessage(icuMessageOrRawString, locale);
282
+ }
283
+
284
+ if (typeof icuMessageOrRawString === 'string') {
285
+ return icuMessageOrRawString;
286
+ }
287
+
288
+ // Should be impossible from types, but do a strict check in case malformed JSON makes it this far.
289
+ throw new Error('Attempted to format invalid icuMessage type');
290
+ }
291
+
292
+ /** @param {string[]} pathInLHR */
293
+ function _formatPathAsString(pathInLHR) {
294
+ let pathAsString = '';
295
+ for (const property of pathInLHR) {
296
+ if (/^[a-z]+$/i.test(property)) {
297
+ if (pathAsString.length) pathAsString += '.';
298
+ pathAsString += property;
299
+ } else {
300
+ if (/]|"|'|\s/.test(property)) throw new Error(`Cannot handle "${property}" in i18n`);
301
+ pathAsString += `[${property}]`;
302
+ }
303
+ }
304
+
305
+ return pathAsString;
306
+ }
307
+
308
+ /**
309
+ * Recursively walk the input object, looking for property values that are
310
+ * `LH.IcuMessage`s and replace them with their localized values. Primarily
311
+ * used with the full LHR or a Config as input.
312
+ * Returns a map of locations that were replaced to the `IcuMessage` that was at
313
+ * that location.
314
+ * @param {unknown} inputObject
315
+ * @param {LH.Locale} locale
316
+ * @return {LH.Result.IcuMessagePaths}
317
+ */
318
+ function replaceIcuMessages(inputObject, locale) {
319
+ /**
320
+ * @param {unknown} subObject
321
+ * @param {LH.Result.IcuMessagePaths} icuMessagePaths
322
+ * @param {string[]} pathInLHR
323
+ */
324
+ function replaceInObject(subObject, icuMessagePaths, pathInLHR = []) {
325
+ if (!isObjectOrArrayOfUnknownValues(subObject)) return;
326
+
327
+ for (const [property, possibleIcuMessage] of Object.entries(subObject)) {
328
+ const currentPathInLHR = pathInLHR.concat([property]);
329
+
330
+ // Replace any IcuMessages with a localized string.
331
+ if (isIcuMessage(possibleIcuMessage)) {
332
+ const formattedString = getFormatted(possibleIcuMessage, locale);
333
+ const messageInstancesInLHR = icuMessagePaths[possibleIcuMessage.i18nId] || [];
334
+ const currentPathAsString = _formatPathAsString(currentPathInLHR);
335
+
336
+ messageInstancesInLHR.push(
337
+ possibleIcuMessage.values ?
338
+ {values: possibleIcuMessage.values, path: currentPathAsString} :
339
+ currentPathAsString
340
+ );
341
+
342
+ // @ts-ignore - tsc doesn't like that `property` can be either string key or array index.
343
+ subObject[property] = formattedString;
344
+ icuMessagePaths[possibleIcuMessage.i18nId] = messageInstancesInLHR;
345
+ } else {
346
+ replaceInObject(possibleIcuMessage, icuMessagePaths, currentPathInLHR);
347
+ }
348
+ }
349
+ }
350
+
351
+ /** @type {LH.Result.IcuMessagePaths} */
352
+ const icuMessagePaths = {};
353
+ replaceInObject(inputObject, icuMessagePaths);
354
+ return icuMessagePaths;
355
+ }
356
+
357
+ /**
358
+ * Returns the locale messages for the given `locale`, if they exist.
359
+ * Throws if an unsupported locale.
360
+ *
361
+ * NOTE: If DEFAULT_LOCALE is requested and this is inside a bundle with locale
362
+ * messages stripped, an empty object will be returned. Default fallbacks will need to handle that case.
363
+ * @param {LH.Locale} locale
364
+ * @return {import('./locales').LhlMessages}
365
+ */
366
+ function _getLocaleMessages(locale) {
367
+ const localeMessages = LOCALE_MESSAGES[locale];
368
+ if (!localeMessages) {
369
+ if (locale === DEFAULT_LOCALE) {
370
+ // If the default locale isn't in LOCALE_MESSAGES, this is likely executing
371
+ // in a bundle. Let the caller use the fallbacks available.
372
+ return {};
373
+ }
374
+ throw new Error(`Unsupported locale '${locale}'`);
375
+ }
376
+
377
+ return localeMessages;
378
+ }
379
+
380
+ /**
381
+ * Returns whether the `requestedLocale` can be used.
382
+ * @param {LH.Locale} requestedLocale
383
+ * @return {boolean}
384
+ */
385
+ function hasLocale(requestedLocale) {
386
+ // The default locale is always supported through `IcuMessage.formattedDefault`.
387
+ if (requestedLocale === DEFAULT_LOCALE) return true;
388
+
389
+ const hasIntlSupport = Intl.NumberFormat.supportedLocalesOf([requestedLocale]).length > 0;
390
+ const hasMessages = Boolean(LOCALE_MESSAGES[requestedLocale]);
391
+
392
+ return hasIntlSupport && hasMessages;
393
+ }
394
+
395
+ /**
396
+ * Returns a list of canonical locales, as defined by the existent message files.
397
+ * In practice, each of these may have aliases in the full list returned by
398
+ * `getAvailableLocales()`.
399
+ * TODO: create a CanonicalLocale type
400
+ * @return {Array<string>}
401
+ */
402
+ function getCanonicalLocales() {
403
+ return CANONICAL_LOCALES;
404
+ }
405
+
406
+ /**
407
+ * Returns a list of available locales.
408
+ * - if full build, this includes all canonical locales, aliases, and any locale added
409
+ * via `registerLocaleData`.
410
+ * - if bundled and locale messages have been stripped (locales.js shimmed), this includes
411
+ * only DEFAULT_LOCALE and any locales from `registerLocaleData`.
412
+ * @return {Array<LH.Locale>}
413
+ */
414
+ function getAvailableLocales() {
415
+ const localesWithMessages = new Set([...Object.keys(LOCALE_MESSAGES), DEFAULT_LOCALE]);
416
+ return /** @type {Array<LH.Locale>} */ ([...localesWithMessages].sort());
417
+ }
418
+
419
+ /**
420
+ * Populate the i18n string lookup dict with locale data
421
+ * Used when the host environment selects the locale and serves lighthouse the intended locale file
422
+ * @see https://docs.google.com/document/d/1jnt3BqKB-4q3AE94UWFA0Gqspx8Sd_jivlB7gQMlmfk/edit
423
+ * @param {LH.Locale} locale
424
+ * @param {import('./locales').LhlMessages} lhlMessages
425
+ */
426
+ function registerLocaleData(locale, lhlMessages) {
427
+ LOCALE_MESSAGES[locale] = lhlMessages;
428
+ }
429
+
430
+ /**
431
+ * @param {string} i18nMessageId
432
+ */
433
+ function getIcuMessageIdParts(i18nMessageId) {
434
+ if (!MESSAGE_I18N_ID_REGEX.test(i18nMessageId)) {
435
+ throw Error(`"${i18nMessageId}" does not appear to be a valid ICU message id`);
436
+ }
437
+ const [filename, key] = i18nMessageId.split(' | ');
438
+ return {filename, key};
439
+ }
440
+
441
+ module.exports = {
442
+ DEFAULT_LOCALE,
443
+ _formatPathAsString,
444
+ collectAllCustomElementsFromICU,
445
+ isIcuMessage,
446
+ getFormatted,
447
+ getRendererFormattedStrings,
448
+ replaceIcuMessages,
449
+ hasLocale,
450
+ registerLocaleData,
451
+ formatMessage,
452
+ getIcuMessageIdParts,
453
+ getAvailableLocales,
454
+ getCanonicalLocales,
455
+ };
@@ -1,14 +1,9 @@
1
1
  /**
2
- * @license Copyright 2020 The Lighthouse Authors. All Rights Reserved.
2
+ * @license Copyright 2021 Google Inc. All Rights Reserved.
3
3
  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
4
4
  * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
5
5
  */
6
6
  'use strict';
7
7
 
8
- /** @fileoverview Needed for the generated/SourceMap.js file */
9
-
10
- const Common = {
11
- console,
12
- };
13
-
14
- module.exports = Common;
8
+ module.exports.swapLocale = require('./swap-locale.js');
9
+ module.exports.format = require('./format.js');