-
Notifications
You must be signed in to change notification settings - Fork 399
/
Copy pathindex.js
378 lines (334 loc) · 10.3 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
/* eslint-disable react/prop-types */
import url from 'url';
import config from 'config';
import { AllHtmlEntities } from 'html-entities';
import invariant from 'invariant';
import qhistory from 'qhistory';
import { stringify, parse } from 'qs';
import {
ADDON_TYPE_COMPLETE_THEME,
ADDON_TYPE_OPENSEARCH,
ADDON_TYPE_THEME,
ADDON_TYPE_THEMES,
ADDON_TYPE_THEMES_FILTER,
API_ADDON_TYPES_MAPPING,
CATEGORY_COLORS,
OS_ALL,
OS_ANDROID,
OS_LINUX,
OS_MAC,
OS_WINDOWS,
VISIBLE_ADDON_TYPES_MAPPING,
} from 'core/constants';
import { AddonTypeNotFound } from 'core/errors';
import log from 'core/logger';
import purify from 'core/purify';
import {
USER_AGENT_OS_ANDROID,
USER_AGENT_OS_BSD_DRAGONFLY,
USER_AGENT_OS_BSD_FREEBSD,
USER_AGENT_OS_BSD_NETBSD,
USER_AGENT_OS_BSD_OPENBSD,
USER_AGENT_OS_BSD_PC,
USER_AGENT_OS_LINUX,
USER_AGENT_OS_LINUX_ARCH,
USER_AGENT_OS_LINUX_CENTOS,
USER_AGENT_OS_LINUX_DEBIAN,
USER_AGENT_OS_LINUX_FEDORA,
USER_AGENT_OS_LINUX_GENTOO,
USER_AGENT_OS_LINUX_GNU,
USER_AGENT_OS_LINUX_LINPUS,
USER_AGENT_OS_LINUX_PC,
USER_AGENT_OS_LINUX_REDHAT,
USER_AGENT_OS_LINUX_SLACKWARE,
USER_AGENT_OS_LINUX_SUSE,
USER_AGENT_OS_LINUX_UBUNTU,
USER_AGENT_OS_LINUX_VECTOR,
USER_AGENT_OS_LINUX_ZENWALK,
USER_AGENT_OS_MAC,
USER_AGENT_OS_UNIX,
USER_AGENT_OS_WINDOWS,
} from 'core/reducers/api';
export function getClientConfig(_config) {
const clientConfig = {};
for (const key of _config.get('clientConfigKeys')) {
clientConfig[key] = _config.get(key);
}
return clientConfig;
}
export function convertBoolean(value) {
switch (value) {
case true:
case 1:
case '1':
case 'true':
return true;
default:
return false;
}
}
/*
* This is a very simplistic check of the user-agent string in order to redirect to
* the right set of AMO data.
*
* More complete UA detection for compatibility will take place elsewhere.
*
*/
export function getClientApp(userAgentString) {
// We are going to return android as the application if it's *any* android browser.
// whereas the previous behaviour was to only return 'android' for FF Android.
// This way we are showing more relevant content, and if we prompt for the user to download
// firefox we can prompt them to download Firefox for Android.
if (/android/i.test(userAgentString)) {
return 'android';
}
return 'firefox';
}
export function isValidClientApp(value, { _config = config } = {}) {
return _config.get('validClientApplications').includes(value);
}
export function sanitizeHTML(text, allowTags = [], _purify = purify) {
// TODO: Accept tags to allow and run through dom-purify.
return {
__html: _purify.sanitize(text, { ALLOWED_TAGS: allowTags }),
};
}
// Convert new lines to HTML breaks.
export function nl2br(text) {
return (text || '').replace(/(\r\n|\r|\n)(?!<.+?>)/g, '<br />');
}
/*
* Sanitizes user inputted HTML, allowing some tags.
*
* This also converts new lines to breaks (<br />) as a convenience when
* users did not write entirely in HTML.
*
* This is meant to display things like an add-on's description or version
* release notes. The allowed tags are meant to match what you see in the
* Developer Hub when you hover over the *Some HTML Supported* link under
* the textarea field.
*/
export function sanitizeUserHTML(text) {
return sanitizeHTML(nl2br(text), [
'a',
'abbr',
'acronym',
'b',
'blockquote',
'br',
'code',
'em',
'i',
'li',
'ol',
'strong',
'ul',
]);
}
export function isAddonAuthor({ addon, userId }) {
if (!addon || !addon.authors || !addon.authors.length || !userId) {
return false;
}
return addon.authors.some((author) => {
return author.id === userId;
});
}
export function isAllowedOrigin(
urlString,
{ allowedOrigins = [config.get('amoCDN')] } = {},
) {
let parsedURL;
try {
parsedURL = url.parse(urlString);
} catch (e) {
log.error(`invalid urlString provided to isAllowedOrigin: ${urlString}`);
return false;
}
return allowedOrigins.includes(`${parsedURL.protocol}//${parsedURL.host}`);
}
/*
* Returns a new URL with query params appended to `urlString`.
*
* `urlString` can be a relative or absolute URL.
*/
export function addQueryParams(urlString, queryParams = {}) {
const urlObj = url.parse(urlString, true);
// Clear search, since query object will only be used if search
// property doesn't exist.
urlObj.search = undefined;
urlObj.query = { ...urlObj.query, ...queryParams };
return url.format(urlObj);
}
export function apiAddonTypeIsValid(addonType) {
return Object.prototype.hasOwnProperty.call(
API_ADDON_TYPES_MAPPING,
addonType,
);
}
export function apiAddonType(addonType) {
if (!apiAddonTypeIsValid(addonType)) {
throw new AddonTypeNotFound(
`"${addonType}" not found in API_ADDON_TYPES_MAPPING`,
);
}
return API_ADDON_TYPES_MAPPING[addonType];
}
export function visibleAddonType(addonType) {
if (
!Object.prototype.hasOwnProperty.call(
VISIBLE_ADDON_TYPES_MAPPING,
addonType,
)
) {
throw new AddonTypeNotFound(
`"${addonType}" not found in VISIBLE_ADDON_TYPES_MAPPING`,
);
}
return VISIBLE_ADDON_TYPES_MAPPING[addonType];
}
export function removeProtocolFromURL(urlWithProtocol) {
invariant(urlWithProtocol, 'urlWithProtocol is required');
// `//test.com` is a valid, protocol-relative URL which we'll allow.
return urlWithProtocol.replace(/^(https?:|)\/\//, '');
}
export function isValidLocaleUrlException(value, { _config = config } = {}) {
return _config.get('validLocaleUrlExceptions').includes(value);
}
export function isValidClientAppUrlException(value, { _config = config } = {}) {
return _config.get('validClientAppUrlExceptions').includes(value);
}
export function isValidTrailingSlashUrlException(
value,
{ _config = config } = {},
) {
return _config.get('validTrailingSlashUrlExceptions').includes(value);
}
/*
* Make sure a callback returns a rejected promise instead of throwing an error.
*
* If the callback throws an error, a rejected promise will be returned
* instead. If the callback runs without an error, its return value is not
* altered. In other words, it may or may not return a promise and that's ok.
*/
export const safePromise = (callback) => (...args) => {
try {
return callback(...args);
} catch (error) {
return Promise.reject(error);
}
};
export function trimAndAddProtocolToUrl(urlToCheck) {
let urlToReturn = urlToCheck ? urlToCheck.trim() : null;
if (urlToReturn && !urlToReturn.match(/^https?:\/\//)) {
urlToReturn = `http://${urlToReturn}`;
}
return urlToReturn;
}
export function getCategoryColor(category) {
if (!category) {
throw new Error('category is required.');
}
const maxColors = CATEGORY_COLORS[category.type];
if (!maxColors) {
throw new Error(
`addonType "${category.type}" not found in CATEGORY_COLORS.`,
);
}
if (category.id > maxColors) {
const color = parseInt(category.id / maxColors, 10);
if (color > maxColors) {
return maxColors;
}
return color;
}
return category.id;
}
export function addonHasVersionHistory(addon) {
if (!addon) {
throw new Error('addon is required');
}
return ![
ADDON_TYPE_COMPLETE_THEME,
ADDON_TYPE_OPENSEARCH,
ADDON_TYPE_THEME,
].includes(addon.type);
}
/*
* Decodes HTML entities into their respective symbols.
*/
export const decodeHtmlEntities = (string) => {
const entities = new AllHtmlEntities();
return entities.decode(string);
};
export const isTheme = (addonType) => {
return ADDON_TYPE_THEMES.includes(addonType);
};
export const getAddonTypeFilter = (addonType) => {
if (!isTheme(addonType)) {
return addonType;
}
return ADDON_TYPE_THEMES_FILTER;
};
/*
* Return an ID for a filename.
*
* This will normalize the representation of a filename on both client and
* server. The result may not be a valid filename.
*
* We need this because the babel polyfill for `__filename` on the client
* returns a relative path but `__filename` on the server returns an
* absolute path.
*/
export const normalizeFileNameId = (filename) => {
let fileId = filename;
if (!fileId.startsWith('src')) {
fileId = fileId.replace(/^.*src/, 'src');
}
return fileId;
};
export const getDisplayName = (component) => {
return component.displayName || component.name || 'Component';
};
export const addQueryParamsToHistory = ({
history,
_parse = parse,
_stringify = stringify,
}) => {
return qhistory(history, _stringify, _parse);
};
export const userAgentOSToPlatform = {
[USER_AGENT_OS_ANDROID.toLowerCase()]: OS_ANDROID,
[USER_AGENT_OS_MAC.toLowerCase()]: OS_MAC,
[USER_AGENT_OS_WINDOWS.toLowerCase()]: OS_WINDOWS,
// Not all of these are strictly Linux but giving them a Linux XPI
// will probably work 99% of the time.
[USER_AGENT_OS_BSD_DRAGONFLY.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_BSD_FREEBSD.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_BSD_NETBSD.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_BSD_OPENBSD.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_BSD_PC.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_ARCH.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_CENTOS.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_DEBIAN.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_FEDORA.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_GENTOO.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_GNU.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_LINPUS.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_PC.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_REDHAT.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_SLACKWARE.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_SUSE.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_UBUNTU.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_VECTOR.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_LINUX_ZENWALK.toLowerCase()]: OS_LINUX,
[USER_AGENT_OS_UNIX.toLowerCase()]: OS_LINUX,
};
export const findFileForPlatform = ({ userAgentInfo, platformFiles }) => {
invariant(userAgentInfo, 'userAgentInfo is required');
invariant(platformFiles, 'platformFiles is required');
const agentOsName =
userAgentInfo.os.name && userAgentInfo.os.name.toLowerCase();
const platform = agentOsName && userAgentOSToPlatform[agentOsName];
return (platform && platformFiles[platform]) || platformFiles[OS_ALL];
};