melperjs 14.1.0 → 16.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +20 -20
- package/README.md +22 -21
- package/docs/general.md +363 -0
- package/docs/index.md +27 -0
- package/docs/node.md +285 -0
- package/lib/cjs/index.cjs +351 -0
- package/lib/cjs/node.cjs +301 -0
- package/lib/esm/index.mjs +306 -0
- package/lib/esm/node.mjs +268 -0
- package/package.json +74 -55
- package/lib/cjs/index.js +0 -386
- package/lib/cjs/node.js +0 -250
- package/lib/cjs/package.json +0 -3
- package/lib/esm/index.js +0 -341
- package/lib/esm/node.js +0 -221
package/lib/esm/index.js
DELETED
|
@@ -1,341 +0,0 @@
|
|
|
1
|
-
import xss from "xss";
|
|
2
|
-
import setCookieParser from "set-cookie-parser";
|
|
3
|
-
import camelCase from "lodash/camelCase.js";
|
|
4
|
-
import upperFirst from "lodash/upperFirst.js";
|
|
5
|
-
import isEmpty from "lodash/isEmpty.js";
|
|
6
|
-
import shuffle from "lodash/shuffle.js";
|
|
7
|
-
export const CONSTANTS = {
|
|
8
|
-
LOWER_CASE: "abcdefghijklmnopqrstuvwxyz",
|
|
9
|
-
UPPER_CASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
|
|
10
|
-
HEXADECIMAL: "0123456789abcdef",
|
|
11
|
-
NUMBERS: "0123456789",
|
|
12
|
-
INT32_MIN: -2147483648,
|
|
13
|
-
INT32_MAX: 2147483647
|
|
14
|
-
};
|
|
15
|
-
export function Exception(message, response = {}, name = null) {
|
|
16
|
-
const error = new Error(message);
|
|
17
|
-
error.name = name || "Exception";
|
|
18
|
-
error.response = response;
|
|
19
|
-
if (checkEmpty(response)) {
|
|
20
|
-
error.response = {};
|
|
21
|
-
}
|
|
22
|
-
if (!error.response?.status) {
|
|
23
|
-
error.response.status = 400;
|
|
24
|
-
}
|
|
25
|
-
return error;
|
|
26
|
-
}
|
|
27
|
-
export async function forever(cooldown, onSuccess, onError = null, onCompleted = null) {
|
|
28
|
-
const checkCooldown = value => value && !isNaN(value) && value > 0;
|
|
29
|
-
if (!checkCooldown(cooldown)) throw new Error("Cooldown must be a positive number");
|
|
30
|
-
while (true) {
|
|
31
|
-
try {
|
|
32
|
-
const value = await onSuccess();
|
|
33
|
-
if (checkCooldown(value)) cooldown = value;
|
|
34
|
-
} catch (e) {
|
|
35
|
-
const value = onError && (await onError(e));
|
|
36
|
-
if (checkCooldown(value)) cooldown = value;
|
|
37
|
-
} finally {
|
|
38
|
-
const value = onCompleted && (await onCompleted());
|
|
39
|
-
if (checkCooldown(value)) cooldown = value;
|
|
40
|
-
await sleepMs(cooldown);
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
export function time() {
|
|
45
|
-
return Math.floor(Date.now() / 1000);
|
|
46
|
-
}
|
|
47
|
-
export async function sleepMs(milliseconds) {
|
|
48
|
-
return new Promise(resolve => setTimeout(resolve, milliseconds));
|
|
49
|
-
}
|
|
50
|
-
export async function sleep(seconds) {
|
|
51
|
-
return await sleepMs(seconds * 1000);
|
|
52
|
-
}
|
|
53
|
-
export function promiseTimeout(milliseconds, promise) {
|
|
54
|
-
return new Promise((resolve, reject) => {
|
|
55
|
-
const timer = setTimeout(() => {
|
|
56
|
-
reject(new Error('Promise timed out after ' + milliseconds + 'ms'));
|
|
57
|
-
}, milliseconds);
|
|
58
|
-
promise.then(value => {
|
|
59
|
-
clearTimeout(timer);
|
|
60
|
-
resolve(value);
|
|
61
|
-
}).catch(reason => {
|
|
62
|
-
clearTimeout(timer);
|
|
63
|
-
reject(reason);
|
|
64
|
-
});
|
|
65
|
-
});
|
|
66
|
-
}
|
|
67
|
-
export function promiseSilent(promise) {
|
|
68
|
-
return promise.then(() => {}).catch(() => {});
|
|
69
|
-
}
|
|
70
|
-
export async function retryFn(fn, retries, errorFn = null) {
|
|
71
|
-
let result = null;
|
|
72
|
-
for (let attempt = 1; attempt <= retries; attempt++) {
|
|
73
|
-
try {
|
|
74
|
-
result = await fn();
|
|
75
|
-
return result;
|
|
76
|
-
} catch (error) {
|
|
77
|
-
errorFn && (await errorFn(attempt, error, result));
|
|
78
|
-
if (attempt >= retries) {
|
|
79
|
-
throw error;
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
}
|
|
83
|
-
}
|
|
84
|
-
export function isValidURL(url) {
|
|
85
|
-
try {
|
|
86
|
-
new URL(url);
|
|
87
|
-
return true;
|
|
88
|
-
} catch {
|
|
89
|
-
return false;
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
export function splitClear(rawText, separator = null) {
|
|
93
|
-
separator = separator ?? /\r?\n/;
|
|
94
|
-
return rawText.split(separator).map(item => item.trim()).filter(item => !isEmpty(item));
|
|
95
|
-
}
|
|
96
|
-
export function checkEmpty(value) {
|
|
97
|
-
if (typeof value === "number") {
|
|
98
|
-
return value === 0;
|
|
99
|
-
} else {
|
|
100
|
-
return isEmpty(value);
|
|
101
|
-
}
|
|
102
|
-
}
|
|
103
|
-
export function pascalCase(str) {
|
|
104
|
-
return upperFirst(camelCase(str));
|
|
105
|
-
}
|
|
106
|
-
export function titleCase(str, separator = " ") {
|
|
107
|
-
str = str || "";
|
|
108
|
-
const words = str.split(separator);
|
|
109
|
-
return words.map(word => upperFirst(word)).join(separator);
|
|
110
|
-
}
|
|
111
|
-
export function isInt32(value) {
|
|
112
|
-
return Number.isInteger(value) && value >= CONSTANTS.INT32_MIN && value <= CONSTANTS.INT32_MAX;
|
|
113
|
-
}
|
|
114
|
-
export function parseNumFromObj(obj) {
|
|
115
|
-
for (let key in obj) {
|
|
116
|
-
let value = obj[key];
|
|
117
|
-
let number = parseFloat(value);
|
|
118
|
-
if (typeof value === 'string' && !isNaN(number) && !value.includes("_")) {
|
|
119
|
-
value = number;
|
|
120
|
-
}
|
|
121
|
-
obj[key] = value;
|
|
122
|
-
}
|
|
123
|
-
return obj;
|
|
124
|
-
}
|
|
125
|
-
export function parseIntFromObj(obj) {
|
|
126
|
-
for (let key in obj) {
|
|
127
|
-
let value = obj[key];
|
|
128
|
-
let number = parseInt(value);
|
|
129
|
-
if (typeof value === 'string' && !isNaN(number) && value.length === number.toString().length) {
|
|
130
|
-
value = number;
|
|
131
|
-
}
|
|
132
|
-
obj[key] = value;
|
|
133
|
-
}
|
|
134
|
-
return obj;
|
|
135
|
-
}
|
|
136
|
-
export function findKeyNode(key, node, pair = null) {
|
|
137
|
-
if (node && node.hasOwnProperty(key) && (pair ? node[key] === pair : true)) {
|
|
138
|
-
return node;
|
|
139
|
-
} else if (typeof node === 'object') {
|
|
140
|
-
for (let index in node) {
|
|
141
|
-
const result = findKeyNode(key, node[index], pair);
|
|
142
|
-
if (result) {
|
|
143
|
-
return result;
|
|
144
|
-
}
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
return null;
|
|
148
|
-
}
|
|
149
|
-
export function waitForProperty(obj, propertyName, timeout = 5000, interval = 100) {
|
|
150
|
-
return new Promise((resolve, reject) => {
|
|
151
|
-
const startTime = Date.now();
|
|
152
|
-
const checkProperty = setInterval(() => {
|
|
153
|
-
if (obj.hasOwnProperty(propertyName)) {
|
|
154
|
-
clearInterval(checkProperty);
|
|
155
|
-
resolve();
|
|
156
|
-
} else if (Date.now() - startTime > timeout) {
|
|
157
|
-
clearInterval(checkProperty);
|
|
158
|
-
reject(new Error(`Property ${propertyName} did not appear within ${timeout} milliseconds`));
|
|
159
|
-
}
|
|
160
|
-
}, interval);
|
|
161
|
-
});
|
|
162
|
-
}
|
|
163
|
-
export function flipObject(obj) {
|
|
164
|
-
return Object.fromEntries(Object.entries(obj).map(([key, value]) => [value, key]));
|
|
165
|
-
}
|
|
166
|
-
export function shuffleObject(obj) {
|
|
167
|
-
const arr = Object.entries(obj);
|
|
168
|
-
for (let i = arr.length - 1; i > 0; i--) {
|
|
169
|
-
const j = Math.floor(Math.random() * (i + 1));
|
|
170
|
-
[arr[i], arr[j]] = [arr[j], arr[i]];
|
|
171
|
-
}
|
|
172
|
-
return Object.fromEntries(arr);
|
|
173
|
-
}
|
|
174
|
-
export function objectStringify(obj) {
|
|
175
|
-
for (let key in obj) {
|
|
176
|
-
if (obj.hasOwnProperty(key)) {
|
|
177
|
-
if (typeof obj[key] === 'object' && obj[key] !== null) {
|
|
178
|
-
objectStringify(obj[key]);
|
|
179
|
-
} else {
|
|
180
|
-
if (obj[key]?.toString) {
|
|
181
|
-
obj[key] = obj[key].toString();
|
|
182
|
-
} else {
|
|
183
|
-
obj[key] = String(obj[key]);
|
|
184
|
-
}
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
return obj;
|
|
189
|
-
}
|
|
190
|
-
export function modifyObjectKeys(obj, callFn) {
|
|
191
|
-
return Object.keys(obj).reduce((acc, key) => {
|
|
192
|
-
acc[callFn(key)] = obj[key];
|
|
193
|
-
return acc;
|
|
194
|
-
}, {});
|
|
195
|
-
}
|
|
196
|
-
export function limitString(str, limit = 35, omission = "...") {
|
|
197
|
-
str = str || "";
|
|
198
|
-
if (str.length <= limit) {
|
|
199
|
-
return str;
|
|
200
|
-
} else {
|
|
201
|
-
return str.substring(0, limit - omission.length) + omission;
|
|
202
|
-
}
|
|
203
|
-
}
|
|
204
|
-
export function safeString(str) {
|
|
205
|
-
str = str || "";
|
|
206
|
-
return xss(str, {
|
|
207
|
-
whiteList: {},
|
|
208
|
-
stripIgnoreTag: true,
|
|
209
|
-
stripIgnoreTagBody: ["script"]
|
|
210
|
-
});
|
|
211
|
-
}
|
|
212
|
-
export function shuffleString(str) {
|
|
213
|
-
const collection = str.split('');
|
|
214
|
-
const shuffled = shuffle(collection);
|
|
215
|
-
return shuffled.join('');
|
|
216
|
-
}
|
|
217
|
-
export function randomString(length, useNumbers = true, useUppercase = false) {
|
|
218
|
-
let characters = CONSTANTS.LOWER_CASE;
|
|
219
|
-
if (useUppercase) characters += CONSTANTS.UPPER_CASE;
|
|
220
|
-
if (useNumbers) characters += CONSTANTS.NUMBERS;
|
|
221
|
-
let randomString = '';
|
|
222
|
-
for (let i = 0; i < length; i++) {
|
|
223
|
-
const randomIndex = Math.floor(Math.random() * characters.length);
|
|
224
|
-
randomString += characters[randomIndex];
|
|
225
|
-
}
|
|
226
|
-
return randomString;
|
|
227
|
-
}
|
|
228
|
-
export function randomHex(length) {
|
|
229
|
-
let result = '';
|
|
230
|
-
for (let i = 0; i < length; i++) {
|
|
231
|
-
const randomIndex = Math.floor(Math.random() * CONSTANTS.HEXADECIMAL.length);
|
|
232
|
-
result += CONSTANTS.HEXADECIMAL[randomIndex];
|
|
233
|
-
}
|
|
234
|
-
return result;
|
|
235
|
-
}
|
|
236
|
-
export function randomInteger(min, max, callback) {
|
|
237
|
-
const minNotSpecified = typeof max === 'undefined' || typeof max === 'function';
|
|
238
|
-
if (minNotSpecified) {
|
|
239
|
-
callback = max;
|
|
240
|
-
max = min;
|
|
241
|
-
min = 0;
|
|
242
|
-
}
|
|
243
|
-
const isSync = typeof callback === 'undefined';
|
|
244
|
-
if (typeof min !== 'number' || typeof max !== 'number') {
|
|
245
|
-
throw new Error('min and max must be numerical values');
|
|
246
|
-
}
|
|
247
|
-
if (max <= min) {
|
|
248
|
-
throw new Error('max must be greater than min');
|
|
249
|
-
}
|
|
250
|
-
const randomNumber = Math.floor(Math.random() * (max - min)) + min;
|
|
251
|
-
if (isSync) {
|
|
252
|
-
return randomNumber;
|
|
253
|
-
} else {
|
|
254
|
-
if (typeof callback !== 'function') {
|
|
255
|
-
throw new Error('callback must be a function');
|
|
256
|
-
}
|
|
257
|
-
callback(randomNumber);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
export function randomUuid(useDashes = true) {
|
|
261
|
-
let d = Date.now();
|
|
262
|
-
const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
|
|
263
|
-
const r = (d + Math.random() * 16) % 16 | 0;
|
|
264
|
-
d = Math.floor(d / 16);
|
|
265
|
-
return (c === 'x' ? r : r & 0x3 | 0x8).toString(16);
|
|
266
|
-
});
|
|
267
|
-
return useDashes ? uuid : uuid.replaceAll("-", "");
|
|
268
|
-
}
|
|
269
|
-
export function randomWeighted(dict, randomFunc = null) {
|
|
270
|
-
randomFunc = randomFunc || (totalWeight => Math.random() * totalWeight);
|
|
271
|
-
let elements = Object.keys(dict);
|
|
272
|
-
let weights = Object.values(dict);
|
|
273
|
-
let totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
|
|
274
|
-
let randomNum = randomFunc(totalWeight);
|
|
275
|
-
let weightSum = 0;
|
|
276
|
-
for (let i = 0; i < elements.length; i++) {
|
|
277
|
-
weightSum += weights[i];
|
|
278
|
-
if (randomNum <= weightSum) {
|
|
279
|
-
return elements[i];
|
|
280
|
-
}
|
|
281
|
-
}
|
|
282
|
-
}
|
|
283
|
-
export function randomElement(obj) {
|
|
284
|
-
if (Array.isArray(obj)) {
|
|
285
|
-
return obj[Math.floor(Math.random() * obj.length)];
|
|
286
|
-
} else {
|
|
287
|
-
return obj[randomElement(Object.keys(obj))];
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
export function indexByTime(index) {
|
|
291
|
-
const date = new Date();
|
|
292
|
-
const hour = date.getHours();
|
|
293
|
-
const minute = date.getMinutes();
|
|
294
|
-
if (hour < 20) {
|
|
295
|
-
return (index + hour) % 10;
|
|
296
|
-
} else {
|
|
297
|
-
const totalMinutes = (hour - 20) * 60 + minute;
|
|
298
|
-
const minuteIndex = Math.floor(totalMinutes / 24);
|
|
299
|
-
return (index + minuteIndex) % 10;
|
|
300
|
-
}
|
|
301
|
-
}
|
|
302
|
-
export function cookieDict(res, decodeValues = false) {
|
|
303
|
-
let dict = {};
|
|
304
|
-
const cookies = setCookieParser.parse(res, {
|
|
305
|
-
decodeValues: decodeValues
|
|
306
|
-
});
|
|
307
|
-
for (let cookie of cookies) {
|
|
308
|
-
dict[cookie.name] = cookie.value;
|
|
309
|
-
}
|
|
310
|
-
return dict;
|
|
311
|
-
}
|
|
312
|
-
export function cookieHeader(cookieDict) {
|
|
313
|
-
return Object.entries(cookieDict).map(([key, value]) => `${key}=${value}`).join(';');
|
|
314
|
-
}
|
|
315
|
-
export function cookieStringToObject(cookieString) {
|
|
316
|
-
const cookies = {};
|
|
317
|
-
if (!cookieString) return cookies;
|
|
318
|
-
cookieString.split(';').forEach(cookie => {
|
|
319
|
-
const [key, ...valueParts] = cookie.trim().split('=');
|
|
320
|
-
if (key) {
|
|
321
|
-
cookies[key.trim()] = valueParts.join('=').trim();
|
|
322
|
-
}
|
|
323
|
-
});
|
|
324
|
-
return cookies;
|
|
325
|
-
}
|
|
326
|
-
export function isIntlHttpCode(httpCode) {
|
|
327
|
-
return httpCode === undefined || httpCode === null || isNaN(httpCode) || httpCode === 0 || httpCode === 100 || httpCode === 402 || httpCode === 407 || httpCode === 417 || 460 <= httpCode && httpCode < 470 || 500 <= httpCode;
|
|
328
|
-
}
|
|
329
|
-
export function isIntlHttpError(e) {
|
|
330
|
-
const message = e?.message?.toLowerCase?.() || "";
|
|
331
|
-
return message.includes("timeout") || message.includes("aborted") || message.includes("socket hang") || message.includes("proxy") || message.includes("tls connection") || message.includes("payment") || message.includes("expectation") || isIntlHttpCode(e?.response?.status);
|
|
332
|
-
}
|
|
333
|
-
export function getResponseError(e, limit = 115) {
|
|
334
|
-
let response;
|
|
335
|
-
if (e?.response?.status && e.response.data) {
|
|
336
|
-
response = `${e.response.status}|${e.response.data}`;
|
|
337
|
-
} else if (e?.response?.data) {
|
|
338
|
-
response = e.response.data;
|
|
339
|
-
}
|
|
340
|
-
return limitString(response || e.message, limit).trim();
|
|
341
|
-
}
|
package/lib/esm/node.js
DELETED
|
@@ -1,221 +0,0 @@
|
|
|
1
|
-
import fs from "fs";
|
|
2
|
-
import { promises as fsp } from "fs";
|
|
3
|
-
import path from "path";
|
|
4
|
-
import crypto from "crypto";
|
|
5
|
-
import { networkInterfaces } from "os";
|
|
6
|
-
import { exec, execSync } from "child_process";
|
|
7
|
-
import bcrypt from "bcryptjs";
|
|
8
|
-
import { CONSTANTS, randomWeighted, splitClear } from "./index.js";
|
|
9
|
-
export function tokenString(length, useNumbers = true, useUppercase = false) {
|
|
10
|
-
const lowercaseChars = CONSTANTS.LOWER_CASE;
|
|
11
|
-
const uppercaseChars = CONSTANTS.UPPER_CASE;
|
|
12
|
-
const numbers = CONSTANTS.NUMBERS;
|
|
13
|
-
let characters = lowercaseChars;
|
|
14
|
-
if (useUppercase) characters += uppercaseChars;
|
|
15
|
-
if (useNumbers) characters += numbers;
|
|
16
|
-
let randomString = '';
|
|
17
|
-
while (randomString.length < length) {
|
|
18
|
-
const byte = crypto.randomBytes(1)[0];
|
|
19
|
-
const index = byte % characters.length;
|
|
20
|
-
if (byte < 256 - 256 % characters.length) {
|
|
21
|
-
randomString += characters[index];
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
return randomString;
|
|
25
|
-
}
|
|
26
|
-
export function tokenHex(length) {
|
|
27
|
-
return crypto.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
|
|
28
|
-
}
|
|
29
|
-
export function tokenInteger(min, max) {
|
|
30
|
-
return crypto.randomInt(min, max);
|
|
31
|
-
}
|
|
32
|
-
export function tokenUuid(useDashes = true) {
|
|
33
|
-
const uuid = crypto.randomUUID().toString();
|
|
34
|
-
return useDashes ? uuid : uuid.replaceAll("-", "");
|
|
35
|
-
}
|
|
36
|
-
export function tokenWeighted(dict) {
|
|
37
|
-
return randomWeighted(dict, crypto.randomInt);
|
|
38
|
-
}
|
|
39
|
-
export function tokenElement(obj) {
|
|
40
|
-
if (Array.isArray(obj)) {
|
|
41
|
-
return obj[crypto.randomInt(0, obj.length)];
|
|
42
|
-
} else {
|
|
43
|
-
return obj[tokenElement(Object.keys(obj))];
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
export function executeCommand(command) {
|
|
47
|
-
return new Promise((resolve, reject) => {
|
|
48
|
-
exec(command, (error, stdout, stderr) => {
|
|
49
|
-
if (error) {
|
|
50
|
-
reject(error);
|
|
51
|
-
} else if (stderr) {
|
|
52
|
-
reject(stderr);
|
|
53
|
-
} else {
|
|
54
|
-
resolve(stdout.trim());
|
|
55
|
-
}
|
|
56
|
-
});
|
|
57
|
-
});
|
|
58
|
-
}
|
|
59
|
-
export function serverIp() {
|
|
60
|
-
const interfaces = networkInterfaces();
|
|
61
|
-
for (const devName in interfaces) {
|
|
62
|
-
const interfaceValue = interfaces[devName];
|
|
63
|
-
for (let i = 0; i < interfaceValue.length; i++) {
|
|
64
|
-
const alias = interfaceValue[i];
|
|
65
|
-
if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.address.startsWith("192.168.") && !alias.internal) return alias.address;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
return '127.0.0.1';
|
|
69
|
-
}
|
|
70
|
-
export function getVersion() {
|
|
71
|
-
try {
|
|
72
|
-
const timestamp = parseInt(execSync('git show -s --format=%ct HEAD').toString().trim());
|
|
73
|
-
if (isNaN(timestamp)) {
|
|
74
|
-
return "1.0";
|
|
75
|
-
}
|
|
76
|
-
const date = new Date(timestamp * 1000);
|
|
77
|
-
const formatDatePart = value => value.toString().padStart(2, '0');
|
|
78
|
-
const year = date.getUTCFullYear().toString().slice(-2);
|
|
79
|
-
const month = formatDatePart(date.getUTCMonth() + 1);
|
|
80
|
-
const day = formatDatePart(date.getUTCDate());
|
|
81
|
-
const hour = formatDatePart(date.getUTCHours());
|
|
82
|
-
const minute = formatDatePart(date.getUTCMinutes());
|
|
83
|
-
return `${year}${month}${day}.${hour}${minute}`;
|
|
84
|
-
} catch {
|
|
85
|
-
return "1.0";
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
export function createNumDir(mainDirectory, start = 0, end = 9) {
|
|
89
|
-
fs.mkdirSync(mainDirectory, {
|
|
90
|
-
recursive: true
|
|
91
|
-
});
|
|
92
|
-
for (let i = start; i <= end; i++) {
|
|
93
|
-
try {
|
|
94
|
-
fs.mkdirSync(path.join(mainDirectory, i.toString()), {
|
|
95
|
-
recursive: true
|
|
96
|
-
});
|
|
97
|
-
} catch (e) {
|
|
98
|
-
console.error(`createNumDir:${i}`, e.message);
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
export function hash(algorithm, data) {
|
|
103
|
-
return crypto.createHash(algorithm).update(data).digest("hex");
|
|
104
|
-
}
|
|
105
|
-
export function md5(data) {
|
|
106
|
-
return hash("md5", data);
|
|
107
|
-
}
|
|
108
|
-
export function sha256(data) {
|
|
109
|
-
return hash("sha256", data);
|
|
110
|
-
}
|
|
111
|
-
export function hashBcrypt(plainText, encryptionKey = "", rounds = 12) {
|
|
112
|
-
return bcrypt.hashSync(plainText + encryptionKey, bcrypt.genSaltSync(rounds));
|
|
113
|
-
}
|
|
114
|
-
export function verifyBcrypt(plainText, hash, encryptionKey = "") {
|
|
115
|
-
return bcrypt.compareSync(plainText + encryptionKey, hash);
|
|
116
|
-
}
|
|
117
|
-
export function formatProxy(proxy, protocol = "http") {
|
|
118
|
-
proxy = proxy.trim();
|
|
119
|
-
const splitByProtocol = proxy.split("://");
|
|
120
|
-
if (1 < splitByProtocol.length) protocol = splitByProtocol[0];
|
|
121
|
-
proxy = splitByProtocol[splitByProtocol.length - 1];
|
|
122
|
-
if (!proxy.includes("@")) {
|
|
123
|
-
const proxyParts = proxy.split(":");
|
|
124
|
-
if (4 <= proxyParts.length) {
|
|
125
|
-
proxy = `${proxyParts[proxyParts.length - 2]}:${proxyParts[proxyParts.length - 1]}@`;
|
|
126
|
-
proxyParts.pop();
|
|
127
|
-
proxyParts.pop();
|
|
128
|
-
proxy += proxyParts.join(":");
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
const proxyParts = proxy.split(':');
|
|
132
|
-
const proxyEnd = parseInt(proxyParts[proxyParts.length - 1]);
|
|
133
|
-
const proxyStart = proxyParts[proxyParts.length - 2];
|
|
134
|
-
if (!proxyStart.includes(".")) {
|
|
135
|
-
proxyParts.pop();
|
|
136
|
-
proxyParts[proxyParts.length - 1] = crypto.randomInt(parseInt(proxyStart), proxyEnd + 1).toString();
|
|
137
|
-
}
|
|
138
|
-
return protocol + "://" + proxyParts.join(':');
|
|
139
|
-
}
|
|
140
|
-
export function proxyObject(...args) {
|
|
141
|
-
let proxy = formatProxy(...args);
|
|
142
|
-
const splitByProtocol = proxy.split('://');
|
|
143
|
-
const splitById = splitByProtocol[splitByProtocol.length - 1].split('@');
|
|
144
|
-
const splitByConn = splitById[splitById.length - 1].split(':');
|
|
145
|
-
proxy = {
|
|
146
|
-
protocol: splitByProtocol[0],
|
|
147
|
-
host: splitByConn[0],
|
|
148
|
-
port: parseInt(splitByConn[1])
|
|
149
|
-
};
|
|
150
|
-
if (1 < splitById.length) {
|
|
151
|
-
const splitByAuth = splitById[0].split(':');
|
|
152
|
-
proxy.auth = {
|
|
153
|
-
username: splitByAuth[0],
|
|
154
|
-
password: splitByAuth[1]
|
|
155
|
-
};
|
|
156
|
-
}
|
|
157
|
-
return proxy;
|
|
158
|
-
}
|
|
159
|
-
export function proxyValue(proxies) {
|
|
160
|
-
let proxy;
|
|
161
|
-
proxies = proxies || "";
|
|
162
|
-
proxies = splitClear(proxies);
|
|
163
|
-
if (proxies.length < 1) return null;
|
|
164
|
-
proxy = proxies[crypto.randomInt(0, proxies.length)];
|
|
165
|
-
proxy = formatProxy(proxy);
|
|
166
|
-
proxy = proxy.replace("{SESSION}", tokenHex(8));
|
|
167
|
-
return proxy || null;
|
|
168
|
-
}
|
|
169
|
-
export async function readJsonFile(filePath, defaultValue = {}) {
|
|
170
|
-
try {
|
|
171
|
-
const data = await fsp.readFile(filePath, 'utf8');
|
|
172
|
-
return JSON.parse(data);
|
|
173
|
-
} catch (error) {
|
|
174
|
-
return defaultValue;
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
export function readJsonFileSync(filePath, defaultValue = {}) {
|
|
178
|
-
try {
|
|
179
|
-
const data = fs.readFileSync(filePath, 'utf8');
|
|
180
|
-
return JSON.parse(data);
|
|
181
|
-
} catch (error) {
|
|
182
|
-
return defaultValue;
|
|
183
|
-
}
|
|
184
|
-
}
|
|
185
|
-
export async function writeJsonFile(filePath, data) {
|
|
186
|
-
const jsonData = JSON.stringify(data);
|
|
187
|
-
return await fsp.writeFile(filePath, jsonData, 'utf8');
|
|
188
|
-
}
|
|
189
|
-
export function writeJsonFileSync(filePath, data) {
|
|
190
|
-
const jsonData = JSON.stringify(data);
|
|
191
|
-
return fs.writeFileSync(filePath, jsonData, 'utf8');
|
|
192
|
-
}
|
|
193
|
-
export async function cleanDirectory(directoryPath, keepDir = true) {
|
|
194
|
-
try {
|
|
195
|
-
const stats = await fsp.stat(directoryPath).catch(() => null);
|
|
196
|
-
if (!stats) {
|
|
197
|
-
if (keepDir) {
|
|
198
|
-
await fsp.mkdir(directoryPath, {
|
|
199
|
-
recursive: true
|
|
200
|
-
});
|
|
201
|
-
}
|
|
202
|
-
return;
|
|
203
|
-
}
|
|
204
|
-
const files = await fsp.readdir(directoryPath);
|
|
205
|
-
for (const file of files) {
|
|
206
|
-
const filePath = path.join(directoryPath, file);
|
|
207
|
-
const fileStat = await fsp.stat(filePath);
|
|
208
|
-
if (fileStat.isDirectory()) {
|
|
209
|
-
await cleanDirectory(filePath, false);
|
|
210
|
-
} else {
|
|
211
|
-
await fsp.unlink(filePath);
|
|
212
|
-
}
|
|
213
|
-
}
|
|
214
|
-
if (!keepDir) {
|
|
215
|
-
await fsp.rmdir(directoryPath);
|
|
216
|
-
}
|
|
217
|
-
return true;
|
|
218
|
-
} catch (error) {
|
|
219
|
-
throw error;
|
|
220
|
-
}
|
|
221
|
-
}
|