melperjs 16.1.0 → 17.1.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/lib/cjs/index.cjs DELETED
@@ -1,352 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.CONSTANTS = void 0;
7
- exports.Exception = Exception;
8
- exports.checkEmpty = checkEmpty;
9
- exports.coerceObjectIntegers = coerceObjectIntegers;
10
- exports.coerceObjectNumbers = coerceObjectNumbers;
11
- exports.cookiesFromHeader = cookiesFromHeader;
12
- exports.cookiesFromResponse = cookiesFromResponse;
13
- exports.cookiesToHeader = cookiesToHeader;
14
- exports.findNodeByKey = findNodeByKey;
15
- exports.forever = forever;
16
- exports.getResponseError = getResponseError;
17
- exports.isInt32 = isInt32;
18
- exports.isPositiveNumber = isPositiveNumber;
19
- exports.isTransientHttpCode = isTransientHttpCode;
20
- exports.isValidURL = isValidURL;
21
- exports.limitString = limitString;
22
- exports.mulberry32 = mulberry32;
23
- exports.objectStringify = objectStringify;
24
- exports.pascalCase = pascalCase;
25
- exports.promiseSilent = promiseSilent;
26
- exports.promiseTimeout = promiseTimeout;
27
- exports.randomBoolean = randomBoolean;
28
- exports.randomElement = randomElement;
29
- exports.randomHex = randomHex;
30
- exports.randomInteger = randomInteger;
31
- exports.randomString = randomString;
32
- exports.randomUuid = randomUuid;
33
- exports.randomWeighted = randomWeighted;
34
- exports.retry = retry;
35
- exports.safeString = safeString;
36
- exports.seedHex = seedHex;
37
- exports.shuffleObject = shuffleObject;
38
- exports.shuffleString = shuffleString;
39
- exports.sleep = sleep;
40
- exports.sleepMs = sleepMs;
41
- exports.splitTrim = splitTrim;
42
- exports.time = time;
43
- exports.titleCase = titleCase;
44
- exports.waitForProperty = waitForProperty;
45
- var _xss = _interopRequireDefault(require("xss"));
46
- var _setCookieParser = _interopRequireDefault(require("set-cookie-parser"));
47
- var _camelCase = _interopRequireDefault(require("lodash/camelCase.js"));
48
- var _upperFirst = _interopRequireDefault(require("lodash/upperFirst.js"));
49
- var _isEmpty = _interopRequireDefault(require("lodash/isEmpty.js"));
50
- var _shuffle = _interopRequireDefault(require("lodash/shuffle.js"));
51
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
52
- const CONSTANTS = exports.CONSTANTS = {
53
- LOWER_CASE: "abcdefghijklmnopqrstuvwxyz",
54
- UPPER_CASE: "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
55
- HEXADECIMAL: "0123456789abcdef",
56
- NUMBERS: "0123456789",
57
- INT32_MIN: -2147483648,
58
- INT32_MAX: 2147483647
59
- };
60
- const NUMBER_PATTERN = /^-?\d+(\.\d+)?(e[+-]?\d+)?$/i;
61
- const INTEGER_PATTERN = /^-?\d+$/;
62
- function Exception(message, response = {}, name = null) {
63
- const error = new Error(message);
64
- error.name = name || "Exception";
65
- error.response = response;
66
- if (checkEmpty(response)) {
67
- error.response = {};
68
- }
69
- return error;
70
- }
71
- function time() {
72
- return Math.floor(Date.now() / 1000);
73
- }
74
- function sleepMs(milliseconds) {
75
- return new Promise(resolve => setTimeout(resolve, milliseconds));
76
- }
77
- function sleep(seconds) {
78
- return sleepMs(seconds * 1000);
79
- }
80
- function promiseTimeout(milliseconds, promise) {
81
- let timer;
82
- const timeout = new Promise((_, reject) => {
83
- timer = setTimeout(() => reject(new Error(`Promise timed out after ${milliseconds}ms`)), milliseconds);
84
- });
85
- return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
86
- }
87
- function promiseSilent(promise) {
88
- return promise.then(() => {}).catch(() => {});
89
- }
90
- async function forever(delayMs, task, onError = null, onFinally = null) {
91
- if (!isPositiveNumber(delayMs)) throw new Error("delayMs must be a positive number");
92
- const update = value => {
93
- if (isPositiveNumber(value)) delayMs = value;
94
- };
95
- while (true) {
96
- try {
97
- update(await task());
98
- } catch (error) {
99
- if (onError) update(await onError(error));
100
- } finally {
101
- if (onFinally) {
102
- try {
103
- update(await onFinally());
104
- } catch {}
105
- }
106
- await sleepMs(delayMs);
107
- }
108
- }
109
- }
110
- async function retry(task, maxAttempts = 1, onError = null, {
111
- delayMs = 0,
112
- backoffFactor = 1
113
- } = {}) {
114
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
115
- try {
116
- return await task();
117
- } catch (error) {
118
- if (onError) await onError(attempt, error);
119
- if (attempt >= maxAttempts) throw error;
120
- if (delayMs > 0) await sleepMs(delayMs * backoffFactor ** (attempt - 1));
121
- }
122
- }
123
- }
124
- function isValidURL(url) {
125
- try {
126
- new URL(url);
127
- return true;
128
- } catch {
129
- return false;
130
- }
131
- }
132
- function splitTrim(string, separator = null) {
133
- return string.split(separator ?? /\r?\n/).map(item => item.trim()).filter(Boolean);
134
- }
135
- function checkEmpty(value) {
136
- if (typeof value === "number") return value === 0;
137
- return (0, _isEmpty.default)(value);
138
- }
139
- function pascalCase(string) {
140
- return (0, _upperFirst.default)((0, _camelCase.default)(string));
141
- }
142
- function titleCase(string, separator = " ") {
143
- return (string || "").split(separator).map(_upperFirst.default).join(separator);
144
- }
145
- function isInt32(value) {
146
- return Number.isInteger(value) && value >= CONSTANTS.INT32_MIN && value <= CONSTANTS.INT32_MAX;
147
- }
148
- function isPositiveNumber(value) {
149
- return Number.isFinite(value) && value > 0;
150
- }
151
- function coerceObjectNumbers(object) {
152
- for (const key of Object.keys(object)) {
153
- const value = object[key];
154
- if (typeof value === 'string' && NUMBER_PATTERN.test(value)) {
155
- object[key] = parseFloat(value);
156
- }
157
- }
158
- return object;
159
- }
160
- function coerceObjectIntegers(object) {
161
- for (const key of Object.keys(object)) {
162
- const value = object[key];
163
- if (typeof value === 'string' && INTEGER_PATTERN.test(value)) {
164
- object[key] = parseInt(value);
165
- }
166
- }
167
- return object;
168
- }
169
- function findNodeByKey(key, node, pair = null) {
170
- if (node && typeof node === 'object') {
171
- if (Object.hasOwn(node, key) && (pair === null || node[key] === pair)) {
172
- return node;
173
- }
174
- for (const childKey of Object.keys(node)) {
175
- const result = findNodeByKey(key, node[childKey], pair);
176
- if (result) return result;
177
- }
178
- }
179
- return null;
180
- }
181
- function waitForProperty(object, property, timeout = 5000, interval = 100) {
182
- return new Promise((resolve, reject) => {
183
- if (Object.hasOwn(object, property)) {
184
- resolve(object[property]);
185
- return;
186
- }
187
- const startTime = Date.now();
188
- const checkProperty = setInterval(() => {
189
- if (Object.hasOwn(object, property)) {
190
- clearInterval(checkProperty);
191
- resolve(object[property]);
192
- } else if (Date.now() - startTime >= timeout) {
193
- clearInterval(checkProperty);
194
- reject(new Error(`Property "${property}" did not appear within ${timeout}ms`));
195
- }
196
- }, interval);
197
- });
198
- }
199
- function shuffleObject(object) {
200
- return Object.fromEntries((0, _shuffle.default)(Object.entries(object)));
201
- }
202
- function objectStringify(object) {
203
- for (const key of Object.keys(object)) {
204
- const value = object[key];
205
- if (value !== null && typeof value === 'object') {
206
- objectStringify(value);
207
- } else {
208
- object[key] = String(value);
209
- }
210
- }
211
- return object;
212
- }
213
- function limitString(string, limit = 35, omission = "...") {
214
- string = string || "";
215
- if (string.length <= limit) return string;
216
- return string.slice(0, limit - omission.length) + omission;
217
- }
218
- function safeString(string) {
219
- return (0, _xss.default)(string || "", {
220
- whiteList: {},
221
- stripIgnoreTag: true,
222
- stripIgnoreTagBody: ["script", "style", "iframe", "object", "embed", "form"],
223
- css: false
224
- });
225
- }
226
- function shuffleString(string) {
227
- return (0, _shuffle.default)(string.split('')).join('');
228
- }
229
- function randomBoolean() {
230
- return Math.random() < 0.5;
231
- }
232
- function randomString(length, useNumbers = true, useUppercase = false) {
233
- let characters = CONSTANTS.LOWER_CASE;
234
- if (useUppercase) characters += CONSTANTS.UPPER_CASE;
235
- if (useNumbers) characters += CONSTANTS.NUMBERS;
236
- let result = '';
237
- for (let i = 0; i < length; i++) {
238
- result += characters[Math.random() * characters.length | 0];
239
- }
240
- return result;
241
- }
242
- function randomHex(length) {
243
- let result = '';
244
- for (let i = 0; i < length; i++) {
245
- result += CONSTANTS.HEXADECIMAL[Math.random() * 16 | 0];
246
- }
247
- return result;
248
- }
249
- function randomInteger(min, max = undefined) {
250
- if (typeof max === 'undefined') {
251
- max = min;
252
- min = 0;
253
- }
254
- if (typeof min !== 'number' || typeof max !== 'number') {
255
- throw new Error('min and max must be numerical values');
256
- }
257
- if (max <= min) {
258
- throw new Error('max must be greater than min');
259
- }
260
- return Math.floor(Math.random() * (max - min)) + min;
261
- }
262
- function randomUuid(useDashes = true) {
263
- const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
264
- const r = Math.random() * 16 | 0;
265
- return (c === 'x' ? r : r & 0x3 | 0x8).toString(16);
266
- });
267
- return useDashes ? uuid : uuid.replaceAll("-", "");
268
- }
269
- function randomWeighted(object) {
270
- if (checkEmpty(object)) return undefined;
271
- const elements = Object.keys(object);
272
- const weights = Object.values(object);
273
- const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
274
- const randomNum = Math.random() * 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
- function randomElement(object) {
284
- if (checkEmpty(object)) return undefined;
285
- const values = Array.isArray(object) ? object : Object.values(object);
286
- if (values.length === 0) return undefined;
287
- return values[Math.floor(Math.random() * values.length)];
288
- }
289
- function mulberry32(seed) {
290
- if (typeof seed === "string") {
291
- let h = 0;
292
- for (let i = 0; i < seed.length; i++) {
293
- h = Math.imul(h ^ seed.charCodeAt(i), 2654435761);
294
- }
295
- seed = h >>> 0;
296
- }
297
- return function () {
298
- seed = seed + 0x6D2B79F5 | 0;
299
- let t = seed;
300
- t = Math.imul(t ^ t >>> 15, t | 1);
301
- t ^= t + Math.imul(t ^ t >>> 7, t | 61);
302
- return ((t ^ t >>> 14) >>> 0) / 4294967296;
303
- };
304
- }
305
- function seedHex(seed, length) {
306
- const rng = mulberry32(String(seed));
307
- let result = '';
308
- while (result.length < length) {
309
- result += Math.floor(rng() * 0x100000000).toString(16).padStart(8, '0');
310
- }
311
- return result.slice(0, length);
312
- }
313
- function cookiesFromResponse(response, decodeValues = false) {
314
- const obj = {};
315
- const cookies = _setCookieParser.default.parse(response, {
316
- decodeValues
317
- });
318
- for (const cookie of cookies) {
319
- obj[cookie.name] = cookie.value;
320
- }
321
- return obj;
322
- }
323
- function cookiesToHeader(cookies) {
324
- if (!cookies) return "";
325
- return Object.entries(cookies).filter(([, value]) => value !== null && value !== undefined).map(([key, value]) => `${key}=${value}`).join("; ");
326
- }
327
- function cookiesFromHeader(header) {
328
- const cookies = {};
329
- if (!header) return cookies;
330
- header.split(';').forEach(cookie => {
331
- const trimmed = cookie.trim();
332
- if (!trimmed.includes('=')) return;
333
- const [key, ...valueParts] = trimmed.split('=');
334
- const trimmedKey = key.trim();
335
- if (trimmedKey) {
336
- cookies[trimmedKey] = valueParts.join('=').trim();
337
- }
338
- });
339
- return cookies;
340
- }
341
- function isTransientHttpCode(httpCode) {
342
- return !httpCode || isNaN(httpCode) || httpCode === 100 || httpCode === 402 || httpCode === 407 || 460 <= httpCode && httpCode < 470 || 500 <= httpCode;
343
- }
344
- function getResponseError(error, limit = 200) {
345
- let response;
346
- if (error?.response?.status && error.response.data) {
347
- response = `${error.response.status}|${error.response.data}`;
348
- } else if (error?.response?.data) {
349
- response = error.response.data;
350
- }
351
- return limitString(response || error.message, limit).trim();
352
- }
package/lib/cjs/node.cjs DELETED
@@ -1,302 +0,0 @@
1
- "use strict";
2
-
3
- Object.defineProperty(exports, "__esModule", {
4
- value: true
5
- });
6
- exports.base64Decode = base64Decode;
7
- exports.base64Encode = base64Encode;
8
- exports.bcryptHash = bcryptHash;
9
- exports.bcryptVerify = bcryptVerify;
10
- exports.clearDirectory = clearDirectory;
11
- exports.createNumberedDirs = createNumberedDirs;
12
- exports.executeCommand = executeCommand;
13
- exports.gitVersion = gitVersion;
14
- exports.hash = hash;
15
- exports.hostIp = hostIp;
16
- exports.md5 = md5;
17
- exports.normalizeProxy = normalizeProxy;
18
- exports.parseProxy = parseProxy;
19
- exports.proxyValue = proxyValue;
20
- exports.readJsonFile = readJsonFile;
21
- exports.readJsonFileSync = readJsonFileSync;
22
- exports.secureRandomBoolean = secureRandomBoolean;
23
- exports.secureRandomElement = secureRandomElement;
24
- exports.secureRandomHex = secureRandomHex;
25
- exports.secureRandomInteger = secureRandomInteger;
26
- exports.secureRandomString = secureRandomString;
27
- exports.secureRandomUuid = secureRandomUuid;
28
- exports.secureRandomWeighted = secureRandomWeighted;
29
- exports.sha256 = sha256;
30
- exports.uuidFromSeed = uuidFromSeed;
31
- exports.writeJsonFile = writeJsonFile;
32
- exports.writeJsonFileSync = writeJsonFileSync;
33
- var _fs = _interopRequireWildcard(require("fs"));
34
- var _path = _interopRequireDefault(require("path"));
35
- var _crypto = _interopRequireDefault(require("crypto"));
36
- var _os = require("os");
37
- var _child_process = require("child_process");
38
- var _util = require("util");
39
- var _bcryptjs = _interopRequireDefault(require("bcryptjs"));
40
- var _index = require("./index.cjs");
41
- function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
42
- function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
43
- const execAsync = (0, _util.promisify)(_child_process.exec);
44
- function secureRandomBoolean() {
45
- return secureRandomInteger(2) === 1;
46
- }
47
- function secureRandomString(length, useNumbers = true, useUppercase = false) {
48
- let characters = _index.CONSTANTS.LOWER_CASE;
49
- if (useUppercase) characters += _index.CONSTANTS.UPPER_CASE;
50
- if (useNumbers) characters += _index.CONSTANTS.NUMBERS;
51
- let result = '';
52
- for (let i = 0; i < length; i++) {
53
- result += characters[secureRandomInteger(0, characters.length)];
54
- }
55
- return result;
56
- }
57
- function secureRandomHex(length) {
58
- return _crypto.default.randomBytes(Math.ceil(length / 2)).toString('hex').slice(0, length);
59
- }
60
- function secureRandomInteger(min, max = undefined) {
61
- return _crypto.default.randomInt(min, max);
62
- }
63
- function secureRandomUuid(useDashes = true) {
64
- const uuid = _crypto.default.randomUUID();
65
- return useDashes ? uuid : uuid.replaceAll("-", "");
66
- }
67
- function secureRandomWeighted(object) {
68
- if ((0, _index.checkEmpty)(object)) return undefined;
69
- const elements = Object.keys(object);
70
- const weights = Object.values(object);
71
- const totalWeight = weights.reduce((sum, weight) => sum + weight, 0);
72
- const randomNum = secureRandomInteger(0, totalWeight);
73
- let weightSum = 0;
74
- for (let i = 0; i < elements.length; i++) {
75
- weightSum += weights[i];
76
- if (randomNum < weightSum) {
77
- return elements[i];
78
- }
79
- }
80
- }
81
- function secureRandomElement(object) {
82
- if ((0, _index.checkEmpty)(object)) return undefined;
83
- const values = Array.isArray(object) ? object : Object.values(object);
84
- if (values.length === 0) return undefined;
85
- return values[secureRandomInteger(0, values.length)];
86
- }
87
- function uuidFromSeed(seed, useDashes = true) {
88
- const hash = _crypto.default.createHash('md5').update(seed).digest();
89
- hash[6] = hash[6] & 0x0f | 0x30;
90
- hash[8] = hash[8] & 0x3f | 0x80;
91
- const hex = hash.toString('hex');
92
- if (!useDashes) return hex;
93
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
94
- }
95
- function hash(algorithm, data) {
96
- return _crypto.default.createHash(algorithm).update(data).digest("hex");
97
- }
98
- function md5(data) {
99
- return hash("md5", data);
100
- }
101
- function sha256(data) {
102
- return hash("sha256", data);
103
- }
104
- function base64Encode(data) {
105
- return Buffer.from(data).toString('base64');
106
- }
107
- function base64Decode(data, encoding = 'utf8') {
108
- return Buffer.from(data, 'base64').toString(encoding);
109
- }
110
- function bcryptHash(plainText, {
111
- key = "",
112
- strength = 12,
113
- preHash = true
114
- } = {}) {
115
- let input = plainText + key;
116
- if (preHash) {
117
- input = sha256(input);
118
- }
119
- return _bcryptjs.default.hashSync(input, strength);
120
- }
121
- function bcryptVerify(plainText, hash, {
122
- key = "",
123
- preHash = true
124
- } = {}) {
125
- let input = plainText + key;
126
- if (preHash) {
127
- input = sha256(input);
128
- }
129
- return _bcryptjs.default.compareSync(input, hash);
130
- }
131
- function normalizeProxy(proxy, protocol = "http") {
132
- proxy = proxy?.trim();
133
- if (!proxy) return null;
134
- const schemeMatch = proxy.match(/^([a-z][a-z0-9+.-]*):\/\/(.+)$/i);
135
- if (schemeMatch) {
136
- protocol = schemeMatch[1];
137
- proxy = schemeMatch[2];
138
- }
139
- let auth = "";
140
- let body = proxy;
141
- const atIdx = body.lastIndexOf("@");
142
- if (atIdx !== -1) {
143
- auth = body.slice(0, atIdx) + "@";
144
- body = body.slice(atIdx + 1);
145
- }
146
- if (!auth) {
147
- // Note: when the password itself is all-digit and port-shaped (e.g. "admin:1234:host:port"),
148
- // the heuristic cannot distinguish auth-first from host-first ordering and may pick the wrong branch.
149
- const parts = body.split(":");
150
- const isPort = s => /^\d+$/.test(s) && +s >= 1 && +s <= 65535;
151
- if (parts.length === 4) {
152
- if (isPort(parts[3]) && !isPort(parts[1])) {
153
- // user:pass:host:port
154
- auth = `${parts[0]}:${parts[1]}@`;
155
- body = `${parts[2]}:${parts[3]}`;
156
- } else {
157
- // host:port:user:pass (default)
158
- auth = `${parts[2]}:${parts[3]}@`;
159
- body = `${parts[0]}:${parts[1]}`;
160
- }
161
- } else if (parts.length === 5) {
162
- if (isPort(parts[3]) && isPort(parts[4]) && !isPort(parts[1])) {
163
- // user:pass:host:portStart:portEnd
164
- auth = `${parts[0]}:${parts[1]}@`;
165
- body = `${parts[2]}:${parts[3]}:${parts[4]}`;
166
- } else {
167
- // host:portStart:portEnd:user:pass (default)
168
- auth = `${parts[3]}:${parts[4]}@`;
169
- body = `${parts[0]}:${parts[1]}:${parts[2]}`;
170
- }
171
- }
172
- }
173
- const parts = body.split(":");
174
- if (parts.length === 3) {
175
- const start = Number(parts[1]);
176
- const end = Number(parts[2]);
177
- if (Number.isInteger(start) && Number.isInteger(end) && start >= 0 && start <= end) {
178
- body = `${parts[0]}:${(0, _index.randomInteger)(start, end + 1)}`;
179
- }
180
- }
181
- return `${protocol}://${auth}${body}`;
182
- }
183
- function parseProxy(proxy, protocol = "http") {
184
- const normalized = normalizeProxy(proxy, protocol);
185
- if (!normalized) return null;
186
- const [scheme, rest] = normalized.split("://");
187
- const atIdx = rest.lastIndexOf("@");
188
- const authPart = atIdx === -1 ? null : rest.slice(0, atIdx);
189
- const hostPart = atIdx === -1 ? rest : rest.slice(atIdx + 1);
190
- const [host, port] = hostPart.split(":");
191
- const result = {
192
- protocol: scheme,
193
- host,
194
- port: parseInt(port, 10)
195
- };
196
- if (authPart !== null) {
197
- const colonIdx = authPart.indexOf(":");
198
- const [username, password] = colonIdx === -1 ? [authPart, ""] : [authPart.slice(0, colonIdx), authPart.slice(colonIdx + 1)];
199
- result.auth = {
200
- username,
201
- password
202
- };
203
- }
204
- return result;
205
- }
206
- function proxyValue(rawProxy, replacements = {}) {
207
- const list = (0, _index.splitTrim)(rawProxy || "");
208
- if (list.length === 0) return null;
209
- const picked = list[(0, _index.randomInteger)(0, list.length)];
210
- const {
211
- SESSION,
212
- ...rest
213
- } = replacements;
214
- let sessionValue;
215
- if (SESSION === undefined) {
216
- sessionValue = (0, _index.randomHex)(8);
217
- } else if (typeof SESSION === "function") {
218
- sessionValue = SESSION();
219
- } else {
220
- sessionValue = (0, _index.seedHex)(String(SESSION), 8);
221
- }
222
- let result = normalizeProxy(picked);
223
- if (!result) return null;
224
- result = result.replace("{SESSION}", sessionValue);
225
- for (const [key, value] of Object.entries(rest)) {
226
- const v = typeof value === "function" ? value() : String(value);
227
- result = result.replace(`{${key}}`, v);
228
- }
229
- return result;
230
- }
231
- async function readJsonFile(filePath, defaultValue = {}) {
232
- try {
233
- const data = await _fs.promises.readFile(filePath, 'utf8');
234
- return JSON.parse(data);
235
- } catch {
236
- return defaultValue;
237
- }
238
- }
239
- function readJsonFileSync(filePath, defaultValue = {}) {
240
- try {
241
- const data = _fs.default.readFileSync(filePath, 'utf8');
242
- return JSON.parse(data);
243
- } catch {
244
- return defaultValue;
245
- }
246
- }
247
- function writeJsonFile(filePath, data) {
248
- const jsonData = JSON.stringify(data);
249
- return _fs.promises.writeFile(filePath, jsonData, 'utf8');
250
- }
251
- function writeJsonFileSync(filePath, data) {
252
- const jsonData = JSON.stringify(data);
253
- return _fs.default.writeFileSync(filePath, jsonData, 'utf8');
254
- }
255
- async function clearDirectory(directoryPath, keepDir = true) {
256
- await _fs.promises.rm(directoryPath, {
257
- recursive: true,
258
- force: true
259
- });
260
- if (keepDir) await _fs.promises.mkdir(directoryPath, {
261
- recursive: true
262
- });
263
- }
264
- function createNumberedDirs(mainDirectory, start = 0, end = 9) {
265
- _fs.default.mkdirSync(mainDirectory, {
266
- recursive: true
267
- });
268
- for (let i = start; i <= end; i++) {
269
- _fs.default.mkdirSync(_path.default.join(mainDirectory, `${i}`), {
270
- recursive: true
271
- });
272
- }
273
- }
274
- async function executeCommand(command) {
275
- const {
276
- stdout
277
- } = await execAsync(command);
278
- return stdout.trim();
279
- }
280
- function hostIp() {
281
- for (const list of Object.values((0, _os.networkInterfaces)())) {
282
- for (const alias of list) {
283
- if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.address.startsWith('192.168.') && !alias.internal) {
284
- return alias.address;
285
- }
286
- }
287
- }
288
- return '127.0.0.1';
289
- }
290
- function gitVersion() {
291
- try {
292
- const raw = (0, _child_process.execFileSync)('git', ['show', '-s', '--format=%ct', 'HEAD'], {
293
- encoding: 'utf8'
294
- }).trim();
295
- const timestamp = parseInt(raw, 10);
296
- if (isNaN(timestamp)) return "1.0";
297
- const iso = new Date(timestamp * 1000).toISOString();
298
- return `${iso.slice(2, 4)}${iso.slice(5, 7)}${iso.slice(8, 10)}.${iso.slice(11, 13)}${iso.slice(14, 16)}`;
299
- } catch {
300
- return "1.0";
301
- }
302
- }