wip
This commit is contained in:
@@ -0,0 +1,77 @@
|
||||
import { getTLDList } from "./tld";
|
||||
import englishWords from "@/data/english.txt?raw";
|
||||
import frenchWords from "@/data/french.txt?raw";
|
||||
import { randomElement, shuffled } from "./random";
|
||||
|
||||
export class DomainFactory {
|
||||
tldList: string[] = [];
|
||||
error: string | null = null;
|
||||
words: Record<string, string[]> = {};
|
||||
generated: string[] = [];
|
||||
|
||||
async init() {
|
||||
try {
|
||||
this.tldList = await getTLDList();
|
||||
} catch (e) {
|
||||
this.error = "Could not load TLD list";
|
||||
throw e;
|
||||
}
|
||||
|
||||
this.words.french = this.initWords(frenchWords);
|
||||
this.words.english = this.initWords(englishWords);
|
||||
}
|
||||
|
||||
initWords(raw: string): string[] {
|
||||
return raw
|
||||
.split("\n")
|
||||
.map((word) => {
|
||||
word = word
|
||||
.normalize("NFD")
|
||||
.replace(/[\u0300-\u036f]/g, "")
|
||||
.toLowerCase()
|
||||
.trim();
|
||||
if (word.includes(" ") || word.length == 0) {
|
||||
return null;
|
||||
}
|
||||
return word;
|
||||
})
|
||||
.filter((word) => word !== null);
|
||||
}
|
||||
|
||||
randomWord(lang: string): string {
|
||||
if (!this.words[lang]) {
|
||||
this.error = `No words for language: ${lang}`;
|
||||
throw new Error(this.error);
|
||||
}
|
||||
return randomElement(this.words[lang]);
|
||||
}
|
||||
|
||||
randomDomain(lang: string): string | null {
|
||||
const word = this.randomWord(lang);
|
||||
for (const tld of shuffled(this.tldList.slice())) {
|
||||
const tldEscaped: string = tld.replace(".", "");
|
||||
if (word.endsWith(tldEscaped) && word.length > tldEscaped.length + 2) {
|
||||
const domain = `${word.substring(0, word.length - tldEscaped.length)}.${tld}`;
|
||||
this.generated.push(domain);
|
||||
return domain;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
next(lang: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
let k = 10000;
|
||||
while (k > 0) {
|
||||
k--;
|
||||
const domain = this.randomDomain(lang);
|
||||
if (domain) {
|
||||
resolve(domain);
|
||||
return;
|
||||
}
|
||||
}
|
||||
this.error = "Could not generate a valid domain";
|
||||
reject(new Error(this.error));
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user