-
-
Notifications
You must be signed in to change notification settings - Fork 248
Expand file tree
/
Copy pathindex.js
More file actions
178 lines (146 loc) · 4.3 KB
/
index.js
File metadata and controls
178 lines (146 loc) · 4.3 KB
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
import { readFile, access } from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
/**
* Supports multiple languages and provides efficient word matching
*/
export class ProfanityEngine {
constructor(config = {}) {
this.isTestMode = config.testMode ?? false;
this.language = config.language ?? 'en';
this.terms = null;
this.termsSet = null;
this.isInitialized = false;
}
/**
* Only loads data when first needed
* @private
*/
async _ensureInitialized() {
if (this.isInitialized) return;
try {
const filePath = await this._getLanguageFilePath();
const fileContent = await this._readTermsFile(filePath);
this.terms = fileContent
.filter(term => term.trim())
.map(term => term.trim().toLowerCase());
this.termsSet = new Set(this.terms);
this.isInitialized = true;
} catch (error) {
this._logWarning(`Failed to initialize: ${error.message}`);
this.terms = [];
this.termsSet = new Set();
this.isInitialized = true;
}
}
/**
* Get the file path for the specified language
* @private
*/
async _getLanguageFilePath() {
const currentFilePath = fileURLToPath(import.meta.url);
const dataFolderPath = path.join(path.dirname(currentFilePath), 'data');
const languageFilePath = path.join(dataFolderPath, `${this.language}.txt`);
if (await this._fileExists(languageFilePath)) {
return languageFilePath;
}
// Fallback to English
this._logWarning(`Language file '${this.language}.txt' not found. Using 'en' as fallback.`);
return path.join(dataFolderPath, 'en.txt');
}
/**
* Check if file exists
* @private
*/
async _fileExists(filePath) {
try {
await access(filePath);
return true;
} catch {
return false;
}
}
/**
* Read and parse terms file
* @private
*/
async _readTermsFile(filePath) {
const fileContent = await readFile(filePath, 'utf8');
return fileContent.split(/\r?\n/); // Handle both \n and \r\n
}
/**
* Log warning if not in test mode
* @private
*/
_logWarning(message) {
if (!this.isTestMode) {
console.warn('Profanity Engine:', message);
}
}
/**
* Extract and normalize words from text
* @private
*/
_extractWords(text) {
if (!text || typeof text !== 'string') return [];
// Split on whitespace and punctuation, filter empty strings
return text
.toLowerCase()
.split(/[\s\p{P}]+/u)
.filter(word => word.length > 0);
}
/**
* Check if a sentence contains any profanity words
* @param {string} sentence - The text to check
* @returns {Promise<boolean>} True if profanity is found
*/
async hasCurseWords(sentence) {
await this._ensureInitialized();
if (!sentence || typeof sentence !== 'string') return false;
const words = this._extractWords(sentence);
return words.some(word => this.termsSet.has(word));
}
/**
* Get all profanity words found in a sentence
* @param {string} sentence - The text to analyze
* @returns {Promise<string[]>} Array of found profanity words
*/
async getCurseWords(sentence) {
await this._ensureInitialized();
if (!sentence || typeof sentence !== 'string') return [];
const words = this._extractWords(sentence);
const foundWords = new Set(); // Use Set to avoid duplicates
for (const word of words) {
if (this.termsSet.has(word)) {
foundWords.add(word);
}
}
return Array.from(foundWords);
}
/**
* Get all profanity terms
* @returns {Promise<string[]>} Array of all profanity terms
*/
async all() {
await this._ensureInitialized();
return [...this.terms]; // Return a copy to prevent external modification
}
/**
* Search for a specific term
* @param {string} term - The term to search for
* @returns {Promise<boolean>} True if the term is found
*/
async search(term) {
await this._ensureInitialized();
if (!term || typeof term !== 'string') return false;
return this.termsSet.has(term.trim().toLowerCase());
}
/**
* Reset the engine (useful for testing or changing language)
*/
reset() {
this.terms = null;
this.termsSet = null;
this.isInitialized = false;
}
}