-
-
Notifications
You must be signed in to change notification settings - Fork 929
/
index.ts
490 lines (457 loc) · 13.9 KB
/
index.ts
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
import type { Faker } from '../..';
import * as random_ua from './user-agent';
export type EmojiType =
| 'smiley'
| 'body'
| 'person'
| 'nature'
| 'food'
| 'travel'
| 'activity'
| 'object'
| 'symbol'
| 'flag';
export type HTTPStatusCodeType =
| 'informational'
| 'success'
| 'clientError'
| 'serverError'
| 'redirection';
/**
* Module to generate internet related entries.
*/
export class Internet {
constructor(private readonly faker: Faker) {
// Bind `this` so namespaced is working correctly
for (const name of Object.getOwnPropertyNames(Internet.prototype)) {
if (name === 'constructor' || typeof this[name] !== 'function') {
continue;
}
this[name] = this[name].bind(this);
}
}
/**
* Returns a random avatar url.
*
* @example
* faker.internet.avatar()
* // 'https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/315.jpg'
*/
avatar(): string {
return `https://cloudflare-ipfs.com/ipfs/Qmd3W5DuhgHirLHGVixi6V76LhCkZUz6pnFt5AJBiyvHye/avatar/${this.faker.datatype.number(
1249
)}.jpg`;
}
/**
* Generates an email address using the given person's name as base.
*
* @param firstName The optional first name to use. If not specified, a random one will be chosen.
* @param lastName The optional last name to use. If not specified, a random one will be chosen.
* @param provider The mail provider domain to use. If not specified, a random free mail provider will be chosen.
* @param options The options to use. Defaults to `{ allowSpecialCharacters: false }`.
* @param options.allowSpecialCharacters Whether special characters such as ``.!#$%&'*+-/=?^_`{|}~`` should be included
* in the email address. Defaults to `false`.
*
* @example
* faker.internet.email() // 'Kassandra4@hotmail.com'
* faker.internet.email('Jeanne', 'Doe') // 'Jeanne63@yahoo.com'
* faker.internet.email('Jeanne', 'Doe', 'example.fakerjs.dev') // 'Jeanne_Doe88@example.fakerjs.dev'
* faker.internet.email('Jeanne', 'Doe', 'example.fakerjs.dev', { allowSpecialCharacters: true }) // 'Jeanne%Doe88@example.fakerjs.dev'
*/
email(
firstName?: string,
lastName?: string,
provider?: string,
options?: { allowSpecialCharacters?: boolean }
): string {
provider =
provider ||
this.faker.helpers.arrayElement(
this.faker.definitions.internet.free_email
);
let localPart: string = this.faker.helpers.slugify(
this.userName(firstName, lastName)
);
if (options?.allowSpecialCharacters) {
const usernameChars: string[] = '._-'.split('');
const specialChars: string[] = ".!#$%&'*+-/=?^_`{|}~".split('');
localPart = localPart.replace(
this.faker.helpers.arrayElement(usernameChars),
this.faker.helpers.arrayElement(specialChars)
);
}
return `${localPart}@${provider}`;
}
/**
* Generates an email address using an example mail provider using the given person's name as base.
*
* @param firstName The optional first name to use. If not specified, a random one will be chosen.
* @param lastName The optional last name to use. If not specified, a random one will be chosen.
* @param options The options to use. Defaults to `{ allowSpecialCharacters: false }`.
* @param options.allowSpecialCharacters Whether special characters such as ``.!#$%&'*+-/=?^_`{|}~`` should be included
* in the email address. Defaults to `false`.
*
* @example
* faker.internet.exampleEmail() // 'Helmer.Graham23@example.com'
* faker.internet.exampleEmail('Jeanne', 'Doe') // 'Jeanne96@example.net'
* faker.internet.exampleEmail('Jeanne', 'Doe', { allowSpecialCharacters: true }) // 'Jeanne%Doe88@example.com'
*/
exampleEmail(
firstName?: string,
lastName?: string,
options?: { allowSpecialCharacters?: boolean }
): string {
const provider = this.faker.helpers.arrayElement(
this.faker.definitions.internet.example_email
);
return this.email(firstName, lastName, provider, options);
}
/**
* Generates a username using the given person's name as base.
*
* @param firstName The optional first name to use. If not specified, a random one will be chosen.
* @param lastName The optional last name to use. If not specified, a random one will be chosen.
*
* @example
* faker.internet.userName() // 'Nettie_Zboncak40'
* faker.internet.userName('Jeanne', 'Doe') // 'Jeanne98'
*/
userName(firstName?: string, lastName?: string): string {
let result: string;
firstName = firstName || this.faker.name.firstName();
lastName = lastName || this.faker.name.lastName();
switch (this.faker.datatype.number(2)) {
case 0:
result = `${firstName}${this.faker.datatype.number(99)}`;
break;
case 1:
result =
firstName + this.faker.helpers.arrayElement(['.', '_']) + lastName;
break;
case 2:
result = `${firstName}${this.faker.helpers.arrayElement([
'.',
'_',
])}${lastName}${this.faker.datatype.number(99)}`;
break;
}
result = result.toString().replace(/'/g, '');
result = result.replace(/ /g, '');
return result;
}
/**
* Returns a random web protocol. Either `http` or `https`.
*
* @example
* faker.internet.protocol() // 'http'
* faker.internet.protocol() // 'https'
*/
protocol(): 'http' | 'https' {
const protocols: ['http', 'https'] = ['http', 'https'];
return this.faker.helpers.arrayElement(protocols);
}
/**
* Returns a random http method.
*
* Can be either of the following:
*
* - `GET`
* - `POST`
* - `PUT`
* - `DELETE`
* - `PATCH`
*
* @example
* faker.internet.httpMethod() // 'PATCH'
*/
httpMethod(): 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' {
const httpMethods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'] = [
'GET',
'POST',
'PUT',
'DELETE',
'PATCH',
];
return this.faker.helpers.arrayElement(httpMethods);
}
/**
* Generates a random HTTP status code.
*
* @param options Options object.
* @param options.types A list of the HTTP status code types that should be used.
*
* @example
* faker.internet.httpStatusCode() // 200
* faker.internet.httpStatusCode({ types: ['success', 'serverError'] }) // 500
*/
httpStatusCode(
options: { types?: ReadonlyArray<HTTPStatusCodeType> } = {}
): number {
const {
types = Object.keys(
this.faker.definitions.internet.http_status_code
) as Array<HTTPStatusCodeType>,
} = options;
const httpStatusCodeType = this.faker.helpers.arrayElement(types);
return this.faker.helpers.arrayElement(
this.faker.definitions.internet.http_status_code[httpStatusCodeType]
);
}
/**
* Generates a random url.
*
* @example
* faker.internet.url() // 'https://remarkable-hackwork.info'
*/
url(): string {
return `${this.protocol()}://${this.domainName()}`;
}
/**
* Generates a random domain name.
*
* @example
* faker.internet.domainName() // 'slow-timer.info'
*/
domainName(): string {
return `${this.domainWord()}.${this.domainSuffix()}`;
}
/**
* Returns a random domain suffix.
*
* @example
* faker.internet.domainSuffix() // 'com'
* faker.internet.domainSuffix() // 'name'
*/
domainSuffix(): string {
return this.faker.helpers.arrayElement(
this.faker.definitions.internet.domain_suffix
);
}
/**
* Generates a random domain word.
*
* @example
* faker.internet.domainWord() // 'close-reality'
* faker.internet.domainWord() // 'weird-cytoplasm'
*/
domainWord(): string {
return `${this.faker.word.adjective()}-${this.faker.word.noun()}`
.replace(/([\\~#&*{}/:<>?|\"'])/gi, '')
.replace(/\s/g, '-')
.replace(/-{2,}/g, '-')
.toLowerCase();
}
/**
* Generates a random IPv4 address.
*
* @example
* faker.internet.ip() // '245.108.222.0'
*/
ip(): string {
// TODO @Shinigami92 2022-03-21: We may want to return a IPv4 or IPv6 address here in a later major release
return this.ipv4();
}
/**
* Generates a random IPv4 address.
*
* @example
* faker.internet.ipv4() // '245.108.222.0'
*/
ipv4(): string {
const randNum = () => {
return this.faker.datatype.number(255).toFixed(0);
};
const result: string[] = [];
for (let i = 0; i < 4; i++) {
result[i] = randNum();
}
return result.join('.');
}
/**
* Generates a random IPv6 address.
*
* @example
* faker.internet.ipv6() // '269f:1230:73e3:318d:842b:daab:326d:897b'
*/
ipv6(): string {
const randHash = () => {
let result = '';
for (let i = 0; i < 4; i++) {
result += this.faker.helpers.arrayElement([
'0',
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'9',
'a',
'b',
'c',
'd',
'e',
'f',
]);
}
return result;
};
const result: string[] = [];
for (let i = 0; i < 8; i++) {
result[i] = randHash();
}
return result.join(':');
}
/**
* Generates a random port number.
*
* @example
* faker.internet.port() // '9414'
*/
port(): number {
return this.faker.datatype.number({ min: 0, max: 65535 });
}
/**
* Generates a random user agent string.
*
* @example
* faker.internet.userAgent()
* // 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_8_8) AppleWebKit/536.0.2 (KHTML, like Gecko) Chrome/27.0.849.0 Safari/536.0.2'
*/
userAgent(): string {
return random_ua.generate(this.faker);
}
/**
* Generates a random css hex color code in aesthetically pleasing color palette.
*
* Based on
* http://stackoverflow.com/questions/43044/algorithm-to-randomly-generate-an-aesthetically-pleasing-color-palette
*
* @param redBase The optional base red in range between `0` and `255`. Defaults to `0`.
* @param greenBase The optional base green in range between `0` and `255`. Defaults to `0`.
* @param blueBase The optional base blue in range between `0` and `255`. Defaults to `0`.
*
* @example
* faker.internet.color() // '#30686e'
* faker.internet.color(100, 100, 100) // '#4e5f8b'
*/
color(
redBase: number = 0,
greenBase: number = 0,
blueBase: number = 0
): string {
const colorFromBase = (base: number): string =>
Math.floor((this.faker.datatype.number(256) + base) / 2)
.toString(16)
.padStart(2, '0');
const red = colorFromBase(redBase);
const green = colorFromBase(greenBase);
const blue = colorFromBase(blueBase);
return `#${red}${green}${blue}`;
}
/**
* Generates a random mac address.
*
* @param sep The optional separator to use. Can be either `':'`, `'-'` or `''`. Defaults to `':'`.
*
* @example
* faker.internet.mac() // '32:8e:2e:09:c6:05'
*/
mac(sep?: string): string {
let i: number;
let mac = '';
let validSep = ':';
// if the client passed in a different separator than `:`,
// we will use it if it is in the list of acceptable separators (dash or no separator)
if (['-', ''].indexOf(sep) !== -1) {
validSep = sep;
}
for (i = 0; i < 12; i++) {
mac += this.faker.datatype.number(15).toString(16);
if (i % 2 === 1 && i !== 11) {
mac += validSep;
}
}
return mac;
}
/**
* Generates a random password.
*
* @param len The length of the password to generate. Defaults to `15`.
* @param memorable Whether the generated password should be memorable. Defaults to `false`.
* @param pattern The pattern that all chars should match should match.
* This option will be ignored, if `memorable` is `true`. Defaults to `/\w/`.
* @param prefix The prefix to use. Defaults to `''`.
*
* @example
* faker.internet.password() // '89G1wJuBLbGziIs'
* faker.internet.password(20) // 'aF55c_8O9kZaPOrysFB_'
* faker.internet.password(20, true) // 'lawetimufozujosodedi'
* faker.internet.password(20, true, /[A-Z]/) // 'HMAQDFFYLDDUTBKVNFVS'
* faker.internet.password(20, true, /[A-Z]/, 'Hello ') // 'Hello IREOXTDWPERQSB'
*/
password(
len: number = 15,
memorable: boolean = false,
pattern: RegExp = /\w/,
prefix: string = ''
): string {
/*
* password-generator ( function )
* Copyright(c) 2011-2013 Bermi Ferrer <bermi@bermilabs.com>
* MIT Licensed
*/
const vowel = /[aeiouAEIOU]$/;
const consonant = /[bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ]$/;
const _password = (
length: number,
memorable: boolean,
pattern: RegExp,
prefix: string
): string => {
if (prefix.length >= length) {
return prefix;
}
if (memorable) {
if (prefix.match(consonant)) {
pattern = vowel;
} else {
pattern = consonant;
}
}
const n = this.faker.datatype.number(94) + 33;
let char = String.fromCharCode(n);
if (memorable) {
char = char.toLowerCase();
}
if (!char.match(pattern)) {
return _password(length, memorable, pattern, prefix);
}
return _password(length, memorable, pattern, prefix + char);
};
return _password(len, memorable, pattern, prefix);
}
/**
* Generates a random emoji.
*
* @param options Options object.
* @param options.types A list of the emoji types that should be used.
*
* @example
* faker.internet.emoji() // '🥰'
* faker.internet.emoji({ types: ['food', 'nature'] }) // '🥐'
*/
emoji(options: { types?: ReadonlyArray<EmojiType> } = {}): string {
const {
types = Object.keys(
this.faker.definitions.internet.emoji
) as Array<EmojiType>,
} = options;
const emojiType = this.faker.helpers.arrayElement(types);
return this.faker.helpers.arrayElement(
this.faker.definitions.internet.emoji[emojiType]
);
}
}