Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(internet): ensure domainWord always returns a valid value in all locales #3253

Merged
merged 1 commit into from
Nov 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions src/modules/internet/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -595,9 +595,32 @@ export class InternetModule extends ModuleBase {
* @since 2.0.1
*/
domainWord(): string {
return this.faker.helpers
.slugify(`${this.faker.word.adjective()}-${this.faker.word.noun()}`)
.toLowerCase();
// Generate an ASCII "word" in the form `noun-adjective`
// For locales with non-ASCII characters, we fall back to lorem words, or a random string
const isValidSlug = (slug: string): boolean => {
return /^[a-z][a-z-]*[a-z]$/i.exec(slug) !== null;
};

const makeValidSlug = (word: string): string => {
const slug1 = this.faker.helpers.slugify(word);
if (isValidSlug(slug1)) {
return slug1;
}

const slug2 = this.faker.helpers.slugify(this.faker.lorem.word());
if (isValidSlug(slug2)) {
return slug2;
}

return this.faker.string.alpha({
casing: 'lower',
length: this.faker.number.int({ min: 4, max: 8 }),
});
ST-DDT marked this conversation as resolved.
Show resolved Hide resolved
};

const word1 = makeValidSlug(this.faker.word.adjective());
const word2 = makeValidSlug(this.faker.word.noun());
return `${word1}-${word2}`.toLowerCase();
}

/**
Expand Down
13 changes: 12 additions & 1 deletion test/modules/internet.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import validator from 'validator';
import { describe, expect, it } from 'vitest';
import { allFakers, faker } from '../../src';
import { allFakers, faker, fakerKO } from '../../src';
import { FakerError } from '../../src/errors/faker-error';
import { IPv4Network } from '../../src/modules/internet';
import { seededTests } from '../support/seeded-runs';
Expand Down Expand Up @@ -667,6 +667,17 @@ describe('internet', () => {
validator.isFQDN(value, { require_tld: false })
);
});

it('should return a lower-case domain in non-ASCII locales', () => {
const domainWord = fakerKO.internet.domainWord();

expect(domainWord).toBeTruthy();
expect(domainWord).toBeTypeOf('string');
expect(domainWord).toSatisfy(validator.isSlug);
expect(domainWord).toSatisfy((value: string) =>
validator.isFQDN(value, { require_tld: false })
);
});
});

describe('ip()', () => {
Expand Down