@e-mc/module 0.0.1

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/index.js ADDED
@@ -0,0 +1,3326 @@
1
+ "use strict";
2
+ /* eslint no-global-assign: "off" */
3
+ var _a, _b, _c, _d, _e, _f, _g;
4
+ Object.defineProperty(exports, "__esModule", { value: true });
5
+ const path = require("path");
6
+ const fs = require("fs");
7
+ const os = require("os");
8
+ const crypto = require("crypto");
9
+ const url = require("url");
10
+ const filetype = require("file-type");
11
+ const mime = require("mime-types");
12
+ const chalk = require("chalk");
13
+ const stripansi = require("strip-ansi");
14
+ const EventEmitter = require("events");
15
+ const types_1 = require("../types");
16
+ const kSessionId = Symbol('sessionId');
17
+ const kBroadcastId = Symbol('broadcastId');
18
+ const kTempDir = Symbol('tempDir');
19
+ const kPermission = Symbol('permission');
20
+ const kSupports = Symbol('supports');
21
+ const kAbortHandler = Symbol('abortHandler');
22
+ const kAbortEvent = Symbol('abortEvent');
23
+ const PROCESS_CWD = process.cwd();
24
+ const PROCESS_STDOUT = process.stdout;
25
+ const PLATFORM_WIN32 = process.platform === 'win32';
26
+ const OS_HOMEDIR = os.homedir();
27
+ const MEM_TOTAL = os.totalmem();
28
+ const CPU_CORETOTAL = os.cpus().length;
29
+ const [VER_MAJOR, VER_MINOR, VER_PATCH] = process.version.substring(1).split('.').map(value => +value);
30
+ const CACHE_READTEXT = new Map();
31
+ const CACHE_READBUFFER = new Map();
32
+ const CACHE_READCJS = new Map();
33
+ let CACHE_EXEC = new WeakMap();
34
+ let CACHE_CPU = new WeakMap();
35
+ let CACHE_CPUHOST = new WeakMap();
36
+ let CACHE_TOTAL = 0;
37
+ const SETTINGS = {
38
+ enabled: true,
39
+ production: undefined,
40
+ format: {
41
+ title: {
42
+ width: 6,
43
+ justify: 'right'
44
+ },
45
+ value: {
46
+ width: 71,
47
+ justify: 'left'
48
+ },
49
+ hint: {
50
+ width: 32,
51
+ unit: 'auto'
52
+ },
53
+ meter: {
54
+ width: Infinity,
55
+ bgColor: 'bgCyan',
56
+ bgAltColor: 'bgYellow'
57
+ },
58
+ session_id: {},
59
+ message: {}
60
+ },
61
+ meter: {
62
+ http: 100,
63
+ process: 250
64
+ },
65
+ status: {
66
+ fatal: true,
67
+ error: true,
68
+ warn: true,
69
+ info: true,
70
+ debug: true,
71
+ trace: true
72
+ },
73
+ color: true,
74
+ session_id: 0,
75
+ message: true,
76
+ stack_trace: false,
77
+ unknown: true,
78
+ system: true,
79
+ node: true,
80
+ process: {
81
+ cpu: true,
82
+ cpu_bar: true,
83
+ cpu_single_core: true,
84
+ mem: true,
85
+ mem_format: '%'
86
+ },
87
+ image: true,
88
+ compress: true,
89
+ watch: true,
90
+ file: true,
91
+ cloud: true,
92
+ db: true,
93
+ time_elapsed: true,
94
+ time_process: true,
95
+ exec: true,
96
+ http: false,
97
+ stdout: true
98
+ };
99
+ const VALUES = {
100
+ ["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */]: 'cjs',
101
+ ["node.require.npm" /* KEY_NAME.NODE_REQUIRE_NPM */]: true,
102
+ ["node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */]: true,
103
+ ["node.process.cpu_usage" /* KEY_NAME.NODE_PROCESS_CPUUSAGE */]: true,
104
+ ["node.process.memory_usage" /* KEY_NAME.NODE_PROCESS_MEMORYUSAGE */]: true,
105
+ ["node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */]: true,
106
+ ["temp.dir" /* KEY_NAME.TEMP_DIR */]: "tmp" /* INTERNAL.TEMP_DIR */,
107
+ ["temp.write" /* KEY_NAME.TEMP_WRITE */]: false,
108
+ ["process.password" /* KEY_NAME.PROCESS_PASSWORD */]: '',
109
+ ["process.cipher.algorithm" /* KEY_NAME.PROCESS_CIPHER_ALGORITHM */]: '',
110
+ ["process.env.apply" /* KEY_NAME.PROCESS_ENV_APPLY */]: false,
111
+ ["permission.process_exec" /* KEY_NAME.PERMISSION_PROCESS_EXEC */]: [],
112
+ ["permission.home_read" /* KEY_NAME.PERMISSION_HOMEREAD */]: false,
113
+ ["permission.home_write" /* KEY_NAME.PERMISSION_HOMEWRITE */]: false,
114
+ ["memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */]: false,
115
+ ["error.out" /* KEY_NAME.ERROR_OUT */]: null,
116
+ ["error.fatal" /* KEY_NAME.ERROR_FATAL */]: false,
117
+ ["broadcast.out" /* KEY_NAME.BROADCAST_OUT */]: null,
118
+ ["logger.level" /* KEY_NAME.LOGGER_LEVEL */]: -1
119
+ };
120
+ const REGEXP_SHELLOPT = /^(-[^\s=]+|--[^-\s=][^\s=]*)(=)?\s*(.*)$/;
121
+ const REGEXP_SHELLVAL = /[^0-9a-z%+-./:=@_]/gi;
122
+ const REGEXP_TORRENT = /^(?:magnet:\?xt=|(?:https?|s?ftp):\/\/[^/][^\n]*?\.(?:torrent|metalink|meta4)(?:\?[^\n]*)?$)/i;
123
+ let LOG_NEWLINE = true;
124
+ let LOG_EMPTYLINE = false;
125
+ let TEMP_DIR = path.join(PROCESS_CWD, "tmp" /* INTERNAL.TEMP_DIR */);
126
+ const PNPM_VER = (function () {
127
+ try {
128
+ const pathname = path.resolve('./node_modules/.modules.yaml');
129
+ if (fs.existsSync(pathname)) {
130
+ return fs.readFileSync(pathname, 'utf-8');
131
+ }
132
+ }
133
+ catch {
134
+ }
135
+ return '';
136
+ })();
137
+ const YARN_VER = (function () {
138
+ try {
139
+ const pathname = path.resolve('./.pnp.cjs');
140
+ if (fs.existsSync(pathname)) {
141
+ return require(pathname);
142
+ }
143
+ }
144
+ catch {
145
+ }
146
+ return null;
147
+ })();
148
+ function applyStyle(options, style) {
149
+ var _h;
150
+ for (const attr in style) {
151
+ (_h = options)[attr] ?? (_h[attr] = style[attr]);
152
+ }
153
+ return options;
154
+ }
155
+ function checkColorOptions(type, settings, options) {
156
+ if (typeof settings !== 'object') {
157
+ return false;
158
+ }
159
+ let result = false;
160
+ if (settings.valueColor) {
161
+ options.valueColor || (options.valueColor = settings.valueColor);
162
+ result = true;
163
+ }
164
+ if (settings.valueBgColor) {
165
+ options.valueBgColor || (options.valueBgColor = settings.valueBgColor);
166
+ result = true;
167
+ }
168
+ if (typeof settings.valueBold === 'boolean') {
169
+ options.valueBold ?? (options.valueBold = settings.valueBold);
170
+ }
171
+ if (settings.hintColor) {
172
+ options.hintColor || (options.hintColor = settings.hintColor);
173
+ result = true;
174
+ }
175
+ if (settings.hintBgColor) {
176
+ options.hintBgColor || (options.hintBgColor = settings.hintBgColor);
177
+ result = true;
178
+ }
179
+ if (typeof settings.hintBold === 'boolean') {
180
+ options.hintBold ?? (options.hintBold = settings.hintBold);
181
+ }
182
+ if (type & types_1.LOG_TYPE.FAIL) {
183
+ return result;
184
+ }
185
+ if (settings.titleColor) {
186
+ options.titleColor || (options.titleColor = settings.titleColor);
187
+ result = true;
188
+ }
189
+ if (settings.titleBgColor) {
190
+ options.titleBgColor || (options.titleBgColor = settings.titleBgColor);
191
+ result = true;
192
+ }
193
+ if (typeof settings.titleBold === 'boolean') {
194
+ options.titleBold ?? (options.titleBold = settings.titleBold);
195
+ }
196
+ if (settings.messageColor) {
197
+ options.messageColor || (options.messageColor = settings.messageColor);
198
+ result = true;
199
+ }
200
+ if (settings.messageBgColor) {
201
+ options.messageBgColor || (options.messageBgColor = settings.messageBgColor);
202
+ result = true;
203
+ }
204
+ if (typeof settings.messageBold === 'boolean') {
205
+ options.messageBold ?? (options.messageBold = settings.messageBold);
206
+ }
207
+ return result;
208
+ }
209
+ function tryCreateDir(value) {
210
+ try {
211
+ if (fs.mkdirSync(value, { recursive: true }) && fs.statSync(value).isDirectory()) {
212
+ return true;
213
+ }
214
+ }
215
+ catch {
216
+ }
217
+ for (let i = value.length - 1, pathname = '', subDir = []; i >= 0; --i) {
218
+ const ch = value[i];
219
+ if (ch !== path.sep) {
220
+ pathname = ch + pathname;
221
+ }
222
+ else if (pathname) {
223
+ let dir = value.substring(0, i + 1);
224
+ subDir.push(pathname);
225
+ if (fs.existsSync(dir)) {
226
+ if (!fs.statSync(dir).isDirectory()) {
227
+ throw errorDirectory(dir);
228
+ }
229
+ for (let j = subDir.length - 1; j >= 0; --j) {
230
+ dir += subDir[j];
231
+ if (!fs.existsSync(dir)) {
232
+ fs.mkdirSync(dir);
233
+ }
234
+ else if (!fs.statSync(dir).isDirectory()) {
235
+ throw errorDirectory(dir);
236
+ }
237
+ dir += path.sep;
238
+ }
239
+ return true;
240
+ }
241
+ pathname = '';
242
+ }
243
+ }
244
+ return false;
245
+ }
246
+ function tryRemoveDir(value, empty, recursive) {
247
+ const temp = typeof empty === 'number';
248
+ let options;
249
+ if (!temp) {
250
+ if (Module.supported(14, 14)) {
251
+ fs.rmSync(value, { recursive, force: true });
252
+ if (empty) {
253
+ fs.mkdirSync(value);
254
+ }
255
+ return [];
256
+ }
257
+ options = { recursive };
258
+ }
259
+ value = Module.normalizePath(value, 1);
260
+ const failed = [];
261
+ const nameMap = new WeakMap();
262
+ let files;
263
+ if (temp) {
264
+ files = [];
265
+ fs.readdirSync(value).forEach(name => {
266
+ try {
267
+ const stat = fs.statSync(value + name);
268
+ nameMap.set(stat, name);
269
+ files.push(stat);
270
+ }
271
+ catch {
272
+ failed.push(value + name);
273
+ }
274
+ });
275
+ }
276
+ else {
277
+ files = fs.readdirSync(value, { withFileTypes: true });
278
+ }
279
+ const current = Date.now();
280
+ for (let i = 0, length = files.length; i < length; ++i) {
281
+ const file = files[i];
282
+ const pathname = value + (file.name || nameMap.get(file));
283
+ try {
284
+ if (file.isDirectory()) {
285
+ if (recursive) {
286
+ if (options) {
287
+ fs.rmdirSync(pathname, options);
288
+ }
289
+ else if (!Module.removeDir(pathname, typeof empty === 'number' ? empty : true)) {
290
+ failed.push(pathname);
291
+ }
292
+ }
293
+ }
294
+ else if (!temp || file.ctimeMs + empty <= current) {
295
+ fs.unlinkSync(pathname);
296
+ }
297
+ }
298
+ catch {
299
+ failed.push(pathname);
300
+ }
301
+ }
302
+ if (!empty && failed.length === 0) {
303
+ fs.rmdirSync(value);
304
+ }
305
+ return failed;
306
+ }
307
+ function errorObject(message) {
308
+ switch (typeof message) {
309
+ case 'string':
310
+ return new Error(message);
311
+ case 'number':
312
+ return (0, types_1.errorMessage)("Error code" /* ERR_MESSAGE.ERROR_CODE */, message.toString());
313
+ default:
314
+ return message instanceof Error ? message : new Error(Module.asString(message) || "Unknown" /* ERR_MESSAGE.UNKNOWN */);
315
+ }
316
+ }
317
+ function isFailed(options) {
318
+ if (options.failed) {
319
+ if (!options.titleColor && !options.titleBgColor) {
320
+ Object.assign(options, Module.LOG_STYLE_NOTICE);
321
+ }
322
+ return true;
323
+ }
324
+ return false;
325
+ }
326
+ function getErrorMessage(err) {
327
+ return SETTINGS.stack_trace && err.stack || err.message || err.toString() || "Unknown" /* ERR_MESSAGE.UNKNOWN */;
328
+ }
329
+ function writeLine(value) {
330
+ PROCESS_STDOUT.write((!LOG_NEWLINE ? '\n' : '') + value + '\n');
331
+ LOG_NEWLINE = true;
332
+ LOG_EMPTYLINE = false;
333
+ }
334
+ function errorPermission(value) {
335
+ return (0, types_1.errorValue)("Unsupported access" /* ERR_MESSAGE.UNSUPPORTED_ACCESS */, value);
336
+ }
337
+ function parseFileArgs(options = {}, callback) {
338
+ let promises;
339
+ if (typeof options === 'boolean') {
340
+ promises = options;
341
+ options = {};
342
+ }
343
+ else if (isFunction(options)) {
344
+ callback = options;
345
+ options = {};
346
+ }
347
+ if (typeof callback === 'boolean') {
348
+ promises = callback;
349
+ callback = undefined;
350
+ }
351
+ return [options, promises, callback];
352
+ }
353
+ function formatTimeHint(value) {
354
+ switch (SETTINGS.format.hint.unit) {
355
+ case 'ms':
356
+ return value + 'ms';
357
+ case 's':
358
+ return (value / 1000) + 's';
359
+ default:
360
+ return (0, types_1.formatTime)(value);
361
+ }
362
+ }
363
+ function getTimeOffset(time, current) {
364
+ if (!time) {
365
+ return 0;
366
+ }
367
+ if (Array.isArray(time)) {
368
+ return (0, types_1.convertTime)(process.hrtime(time));
369
+ }
370
+ return (current || Date.now()) - (time instanceof Date ? time.getTime() : time);
371
+ }
372
+ function getTimeStamp(options, include) {
373
+ const timeStamp = options.timeStamp;
374
+ if (timeStamp instanceof Date) {
375
+ return timeStamp.getTime();
376
+ }
377
+ if (include) {
378
+ return Date.now();
379
+ }
380
+ }
381
+ function getCacheItem(map, key) {
382
+ const item = map.get(key);
383
+ if (item) {
384
+ item[0] = Date.now();
385
+ return item[1];
386
+ }
387
+ }
388
+ function addCacheItem(map, key, data) {
389
+ if (!map.has(key)) {
390
+ ++CACHE_TOTAL;
391
+ }
392
+ map.set(key, [Date.now(), data]);
393
+ }
394
+ function checkFunction(value) {
395
+ if (typeof value === 'function') {
396
+ Object.defineProperty(value, "__cjs__" /* INTERNAL.CJS */, { value: true });
397
+ return value;
398
+ }
399
+ return null;
400
+ }
401
+ function encryptMessage(data, cipher, algorithm) {
402
+ var _h;
403
+ if (cipher?.key && cipher.iv) {
404
+ if (!algorithm) {
405
+ algorithm = cipher.algorithm || 'aes-256-gcm';
406
+ }
407
+ const result = (0, types_1.encryptUTF8)(algorithm, cipher.key, cipher.iv, data);
408
+ if (result) {
409
+ VALUES[_h = "process.cipher.algorithm" /* KEY_NAME.PROCESS_CIPHER_ALGORITHM */] || (VALUES[_h] = algorithm);
410
+ return result;
411
+ }
412
+ }
413
+ return data;
414
+ }
415
+ function setCpuAndMem(options) {
416
+ let host, usage;
417
+ if (!options.messageUnit && (usage = ('startCPU' in this) && this.startCPU || CACHE_CPUHOST.get(this) || (host = this.host) && CACHE_CPUHOST.get(host))) {
418
+ options.messageUnit = Module.formatCpuMem(usage);
419
+ }
420
+ }
421
+ function hasFileSystem(type, value, options, ignoreExists, overwrite) {
422
+ let result;
423
+ if (path.isAbsolute(value)) {
424
+ if (options.absolutePath === false) {
425
+ if (options.throwsPermission) {
426
+ throw errorPermission(value);
427
+ }
428
+ return '';
429
+ }
430
+ result = path.normalize(value);
431
+ }
432
+ else if (!(result = Module.fromLocalPath(value))) {
433
+ if (options.throwsDoesNotExist) {
434
+ throw (0, types_1.errorValue)("File not found" /* ERR_MESSAGE.NOTFOUND_FILE */, value);
435
+ }
436
+ return '';
437
+ }
438
+ if (overwrite === false && Module.isPath(result)) {
439
+ if (options.throwsPermission) {
440
+ throw errorPermission(value);
441
+ }
442
+ return '';
443
+ }
444
+ if (!ignoreExists && !Module.isPath(result)) {
445
+ if (options.throwsDoesNotExist) {
446
+ throw (0, types_1.errorValue)("File not found" /* ERR_MESSAGE.NOTFOUND_FILE */, value);
447
+ }
448
+ return '';
449
+ }
450
+ if (options.ignorePermission) {
451
+ return result;
452
+ }
453
+ const method = type === 1 /* FILE_SYSTEM.WRITE */ ? 'canWrite' : 'canRead';
454
+ if (options.ownPermissionOnly) {
455
+ if (this.hasOwnPermission() && !this[method](result)) {
456
+ if (options.throwsPermission) {
457
+ throw errorPermission(result);
458
+ }
459
+ return '';
460
+ }
461
+ }
462
+ else if (options.hostPermissionOnly) {
463
+ const host = this.host;
464
+ if (host?.permission && !host[method](result)) {
465
+ if (options.throwsPermission) {
466
+ throw errorPermission(result);
467
+ }
468
+ return '';
469
+ }
470
+ }
471
+ else if (this.permission && !this[method](result)) {
472
+ if (options.throwsPermission) {
473
+ throw errorPermission(result);
474
+ }
475
+ return '';
476
+ }
477
+ return result;
478
+ }
479
+ function applyLogId(options) {
480
+ if (options.sessionId === undefined) {
481
+ options.sessionId = this.sessionId;
482
+ }
483
+ let value = options.broadcastId;
484
+ if (value === undefined) {
485
+ if (value = this.broadcastId) {
486
+ options.broadcastId = this.supports('stripAnsi') ? value : { value, stripAnsi: false };
487
+ }
488
+ }
489
+ else if (!this.supports('stripAnsi')) {
490
+ if ((0, types_1.isPlainObject)(value)) {
491
+ value.stripAnsi = false;
492
+ }
493
+ else {
494
+ options.broadcastId = { value, stripAnsi: false };
495
+ }
496
+ }
497
+ return options;
498
+ }
499
+ function withinDir(value, base) {
500
+ value = path.normalize(value);
501
+ return (PLATFORM_WIN32 ? value.toLowerCase() : value).startsWith(ensureDir(PLATFORM_WIN32 ? base.toLowerCase() : base));
502
+ }
503
+ function formatPercent(value, precision = 3) {
504
+ if (value <= 0) {
505
+ return '0%';
506
+ }
507
+ if (value === Math.floor(value)) {
508
+ return value + '00%';
509
+ }
510
+ return (value * 100).toPrecision(precision) + '%';
511
+ }
512
+ function tryIncrementDir(value, increment) {
513
+ const baseDir = trimDir(value);
514
+ let i = 0, outErr;
515
+ do {
516
+ try {
517
+ if (tryCreateDir(value)) {
518
+ return [value, i];
519
+ }
520
+ }
521
+ catch (err) {
522
+ if (increment === 0) {
523
+ outErr = err;
524
+ }
525
+ }
526
+ value = baseDir + '_' + ++i;
527
+ } while (increment-- > 0);
528
+ return [outErr, -1];
529
+ }
530
+ const asFile = (value) => value instanceof URL ? value.protocol === 'file:' ? url.fileURLToPath(value) : '' : value;
531
+ const wrapQuote = (value) => '"' + value.replace(/"/g, '\\"') + '"';
532
+ const isFunction = (value) => typeof value === 'function';
533
+ const isFileURL = (value) => /^file:\/\//i.test(value);
534
+ const errorDirectory = (value) => (0, types_1.errorValue)("Path is not a directory" /* ERR_MESSAGE.NOT_DIRECTORY */, value);
535
+ const sanitizePath = (value) => (0, types_1.isString)(value) ? path.resolve(value.trim()) : '';
536
+ const ensureDir = (value) => value[value.length - 1] !== path.sep ? value + path.sep : value;
537
+ const trimDir = (value) => value[value.length - 1] === path.sep ? value.substring(0, value.length - 1) : value;
538
+ const getExtension = (value) => path.extname(value).toLowerCase().substring(1);
539
+ const hasString = (item, value) => (0, types_1.isString)(value) && (item === value || Array.isArray(item) && item.includes(value));
540
+ const getCpuTimes = () => os.cpus().reduce((a, b) => a + b.times.user + b.times.sys, 0) * 1000 /* TIME.S */;
541
+ class Module extends EventEmitter {
542
+ constructor() {
543
+ super(...arguments);
544
+ this.status = [];
545
+ this.errors = [];
546
+ this._moduleName = 'unknown';
547
+ this._host = null;
548
+ this._abortable = false;
549
+ this._threadable = false;
550
+ this._logEnabled = true;
551
+ this._logFlushed = false;
552
+ this._logLevel = VALUES["logger.level" /* KEY_NAME.LOGGER_LEVEL */];
553
+ this._hostEvents = ['abort'];
554
+ this._logQueued = [];
555
+ this[_a] = '';
556
+ this[_b] = VALUES["temp.dir" /* KEY_NAME.TEMP_DIR */];
557
+ this[_c] = '';
558
+ this[_d] = null;
559
+ this[_e] = { stripAnsi: { value: true, modified: false } };
560
+ this[_f] = new AbortController();
561
+ this[_g] = null;
562
+ }
563
+ static get VERSION() { return "5.0.0" /* INTERNAL.VERSION */; }
564
+ static get LOG_TYPE() { return types_1.LOG_TYPE; }
565
+ static get STATUS_TYPE() { return types_1.STATUS_TYPE; }
566
+ static get MAX_TIMEOUT() { return 2147483647; }
567
+ static supported(major, minor = 0, patch = 0, lts) {
568
+ if (VER_MAJOR < major) {
569
+ return false;
570
+ }
571
+ if (VER_MAJOR === major) {
572
+ if (VER_MINOR < minor) {
573
+ return false;
574
+ }
575
+ if (VER_MINOR === minor) {
576
+ return VER_PATCH >= patch;
577
+ }
578
+ return true;
579
+ }
580
+ return !lts;
581
+ }
582
+ static enabled(key, username) {
583
+ switch (key) {
584
+ case "memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */: {
585
+ const users = VALUES[key];
586
+ return users === false || !!username && (users === true || users.includes(username));
587
+ }
588
+ case "temp.dir" /* KEY_NAME.TEMP_DIR */:
589
+ return VALUES[key] !== "tmp" /* INTERNAL.TEMP_DIR */;
590
+ case "node.require.npm" /* KEY_NAME.NODE_REQUIRE_NPM */:
591
+ case "node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */:
592
+ case "node.process.cpu_usage" /* KEY_NAME.NODE_PROCESS_CPUUSAGE */:
593
+ case "node.process.memory_usage" /* KEY_NAME.NODE_PROCESS_MEMORYUSAGE */:
594
+ case "node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */:
595
+ case "temp.write" /* KEY_NAME.TEMP_WRITE */:
596
+ case "permission.home_read" /* KEY_NAME.PERMISSION_HOMEREAD */:
597
+ case "permission.home_write" /* KEY_NAME.PERMISSION_HOMEWRITE */:
598
+ case "process.env.apply" /* KEY_NAME.PROCESS_ENV_APPLY */:
599
+ case "error.fatal" /* KEY_NAME.ERROR_FATAL */:
600
+ return VALUES[key];
601
+ case "node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */:
602
+ case "process.password" /* KEY_NAME.PROCESS_PASSWORD */:
603
+ case "process.cipher.algorithm" /* KEY_NAME.PROCESS_CIPHER_ALGORITHM */:
604
+ return VALUES[key] !== '';
605
+ case "permission.process_exec" /* KEY_NAME.PERMISSION_PROCESS_EXEC */:
606
+ return VALUES[key].length > 0;
607
+ case "error.out" /* KEY_NAME.ERROR_OUT */:
608
+ case "broadcast.out" /* KEY_NAME.BROADCAST_OUT */:
609
+ return VALUES[key] !== null;
610
+ case "logger.level" /* KEY_NAME.LOGGER_LEVEL */:
611
+ return VALUES[key] >= 0;
612
+ default:
613
+ return false;
614
+ }
615
+ }
616
+ static hasLogType(value) {
617
+ if (value === 0) {
618
+ if (SETTINGS.unknown === false) {
619
+ return false;
620
+ }
621
+ }
622
+ else if ((value & 1 /* LOG_VALUE.SYSTEM */) && SETTINGS.system === false ||
623
+ (value & 2 /* LOG_VALUE.NODE */) && SETTINGS.node === false ||
624
+ (value & 4 /* LOG_VALUE.PROCESS */) && SETTINGS.process === false ||
625
+ (value & 8 /* LOG_VALUE.COMPRESS */) && SETTINGS.compress === false ||
626
+ (value & 16 /* LOG_VALUE.WATCH */) && SETTINGS.watch === false ||
627
+ (value & 32 /* LOG_VALUE.FILE */) && SETTINGS.file === false ||
628
+ (value & 64 /* LOG_VALUE.CLOUD */) && SETTINGS.cloud === false ||
629
+ (value & 128 /* LOG_VALUE.TIME_ELAPSED */) && SETTINGS.time_elapsed === false ||
630
+ (value & 256 /* LOG_VALUE.TIME_PROCESS */) && SETTINGS.time_process === false ||
631
+ (value & 1024 /* LOG_VALUE.HTTP */) && SETTINGS.http === false ||
632
+ (value & 2048 /* LOG_VALUE.IMAGE */) && SETTINGS.image === false ||
633
+ (value & 4096 /* LOG_VALUE.EXEC */) && SETTINGS.exec === false ||
634
+ (value & 32768 /* LOG_VALUE.STDOUT */) && SETTINGS.stdout === false ||
635
+ (value & 65536 /* LOG_VALUE.DB */) && SETTINGS.db === false) {
636
+ return false;
637
+ }
638
+ return true;
639
+ }
640
+ static formatMessage(type, title, value, message, options = {}) {
641
+ if (options.type) {
642
+ type |= options.type;
643
+ }
644
+ const BROADCAST_OUT = VALUES["broadcast.out" /* KEY_NAME.BROADCAST_OUT */];
645
+ const sessionId = options.sessionId;
646
+ let broadcastId = options.broadcastId;
647
+ if ((type & 512 /* LOG_VALUE.FAIL */) === 512 /* LOG_VALUE.FAIL */ && VALUES["error.out" /* KEY_NAME.ERROR_OUT */]) {
648
+ try {
649
+ const ERROR_OUT = VALUES["error.out" /* KEY_NAME.ERROR_OUT */];
650
+ const errorOptions = { type: type & ~512 /* LOG_VALUE.FAIL */, value, timeStamp: getTimeStamp(options, true), sessionId };
651
+ // @ts-ignore
652
+ if (ERROR_OUT["__cjs__" /* INTERNAL.CJS */]) {
653
+ ERROR_OUT(errorObject(message), errorOptions);
654
+ }
655
+ else {
656
+ ERROR_OUT.apply(VALUES["node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */] ? process : null, VALUES["node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */] ? [errorObject(message), errorOptions, require] : [errorObject(message), errorOptions]);
657
+ }
658
+ }
659
+ catch {
660
+ }
661
+ }
662
+ if (broadcastId && !BROADCAST_OUT || (!SETTINGS.enabled || !this.hasLogType(type) && !options.alwaysVisible) && !(broadcastId && BROADCAST_OUT)) {
663
+ return;
664
+ }
665
+ let messageUnitIndent = options.messageUnitIndent, coloring;
666
+ if (!broadcastId) {
667
+ (0, types_1.setLogCurrent)({ type, title, value, message });
668
+ coloring = !(options.useColor === false || SETTINGS.color === false);
669
+ }
670
+ else if ((0, types_1.isPlainObject)(broadcastId)) {
671
+ coloring = broadcastId.stripAnsi === false;
672
+ broadcastId = broadcastId.value;
673
+ }
674
+ const format = SETTINGS.format;
675
+ const formatTitle = format.title;
676
+ const formatValue = format.value;
677
+ const id = sessionId && SETTINGS.session_id ? ' ' + sessionId.padStart(SETTINGS.session_id, '0') + ' ' : '';
678
+ const titleIndent = options.titleIndent ? typeof options.titleIndent === 'number' ? Math.max(options.titleIndent, 0) : 0 : -1;
679
+ let output, error, hint, valueWidth = Math.max(formatValue.width - (id ? SETTINGS.session_id + 1 : 0), 1), titleJustify = options.titleJustify || ((type & 512 /* LOG_VALUE.FAIL */) || options.failed ? 'center' : formatTitle.justify);
680
+ if (Array.isArray(value)) {
681
+ hint = value[1] ?? '';
682
+ value = value[0];
683
+ }
684
+ if (message && message instanceof Error) {
685
+ message = getErrorMessage(message);
686
+ error = true;
687
+ }
688
+ if (messageUnitIndent) {
689
+ let indentChar;
690
+ if (Array.isArray(messageUnitIndent)) {
691
+ [messageUnitIndent, indentChar] = messageUnitIndent;
692
+ }
693
+ if (messageUnitIndent > 0) {
694
+ message = (indentChar || ' ').repeat(messageUnitIndent) + this.asString(message);
695
+ }
696
+ }
697
+ const truncateStart = (content, length = 0) => length > 3 && content.length > length ? content.substring(0, length - 3) + '...' : content;
698
+ const truncateEnd = (content, length) => content.length > length ? '...' + content.substring(content.length - length + 3) : content;
699
+ const getValue = () => alignColumn(truncateEnd(value, valueWidth - (titleIndent > 0 ? titleIndent - formatTitle.width : !title && message ? -(formatTitle.width + 3) : 0) - 1), valueWidth, formatValue.justify);
700
+ const alignColumn = (content, width, justify, padding = 0) => {
701
+ const offset = width - content.length;
702
+ const spacing = padding === 1 ? ' ' : padding > 0 ? ' '.repeat(padding) : '';
703
+ if (offset <= 0) {
704
+ return offset === 0 && padding > 0 ? justify === 'left' ? spacing + content : content + spacing : content;
705
+ }
706
+ switch (justify) {
707
+ case 'right':
708
+ return content.padStart(width) + spacing;
709
+ case 'center':
710
+ return content.padStart(content.length + Math.ceil((offset + padding) / 2)).padEnd(width + padding);
711
+ default:
712
+ return spacing + content.padEnd(width);
713
+ }
714
+ };
715
+ const formatColumn = (content, color, bgColor, bold, bgAltColor, maxLength = 0) => {
716
+ if (content === undefined || content === null) {
717
+ return '';
718
+ }
719
+ let indent = '';
720
+ if (typeof content === 'string') {
721
+ let modified;
722
+ if (bgAltColor !== undefined) {
723
+ const match = /^([ -]+)([\S\s]*)$/.exec(content);
724
+ if (match) {
725
+ indent = match[1];
726
+ if (bgAltColor) {
727
+ try {
728
+ indent = (bgAltColor[0] === '#' ? chalk.bgHex(bgAltColor) : chalk[bgAltColor])(indent);
729
+ }
730
+ catch {
731
+ }
732
+ }
733
+ content = match[2];
734
+ modified = true;
735
+ }
736
+ }
737
+ if (!modified && !content.trim()) {
738
+ return content;
739
+ }
740
+ }
741
+ else {
742
+ content = this.asString(content);
743
+ }
744
+ if (maxLength > 0) {
745
+ content = truncateStart(content, maxLength);
746
+ }
747
+ if (color || bgColor) {
748
+ try {
749
+ let current = bold ? chalk.bold : chalk;
750
+ if (typeof color === 'string' && color.length > 1) {
751
+ current = color[0] === '#' ? current.hex(color) : current[color];
752
+ }
753
+ if (typeof bgColor === 'string' && bgColor.length > 1) {
754
+ current = bgColor[0] === '#' ? current.bgHex(bgColor) : current[bgColor];
755
+ }
756
+ return indent + current(content);
757
+ }
758
+ catch {
759
+ }
760
+ }
761
+ return indent + (bold ? chalk.bold(content) : content);
762
+ };
763
+ if (type === 0 /* LOG_VALUE.UNKNOWN */) {
764
+ checkColorOptions(type, SETTINGS.unknown, options);
765
+ }
766
+ else {
767
+ if (type & 4096 /* LOG_VALUE.EXEC */) {
768
+ checkColorOptions(type, SETTINGS.exec, options);
769
+ }
770
+ else if (type & 32 /* LOG_VALUE.FILE */) {
771
+ checkColorOptions(type, SETTINGS.file, options);
772
+ }
773
+ else if (type & 2 /* LOG_VALUE.NODE */) {
774
+ if (!checkColorOptions(type, SETTINGS.node, options)) {
775
+ applyStyle(options, this.LOG_STYLE_REVERSE);
776
+ options.hintColor || (options.hintColor = 'yellow');
777
+ }
778
+ titleJustify = 'center';
779
+ }
780
+ else if (type & 1 /* LOG_VALUE.SYSTEM */) {
781
+ checkColorOptions(type, SETTINGS.system, options);
782
+ if (options.titleBgColor) {
783
+ titleJustify = 'center';
784
+ }
785
+ }
786
+ if (type & 1024 /* LOG_VALUE.HTTP */) {
787
+ checkColorOptions(type, SETTINGS.http, options);
788
+ }
789
+ else if (type & 64 /* LOG_VALUE.CLOUD */) {
790
+ checkColorOptions(type, SETTINGS.cloud, options);
791
+ }
792
+ else if (type & 65536 /* LOG_VALUE.DB */) {
793
+ checkColorOptions(type, SETTINGS.db, options);
794
+ }
795
+ else if (type & 16 /* LOG_VALUE.WATCH */) {
796
+ checkColorOptions(type, SETTINGS.watch, options);
797
+ titleJustify = 'center';
798
+ }
799
+ else if (type & 2048 /* LOG_VALUE.IMAGE */) {
800
+ checkColorOptions(type, SETTINGS.image, options);
801
+ }
802
+ else if (type & 8 /* LOG_VALUE.COMPRESS */) {
803
+ checkColorOptions(type, SETTINGS.compress, options);
804
+ }
805
+ else if ((type & 4 /* LOG_VALUE.PROCESS */) && !options.titleColor && !checkColorOptions(type, SETTINGS.process, options)) {
806
+ options.titleColor = 'magenta';
807
+ }
808
+ if (type & 128 /* LOG_VALUE.TIME_ELAPSED */) {
809
+ if (!checkColorOptions(type, SETTINGS.time_elapsed, options)) {
810
+ options.hintColor || (options.hintColor = 'yellow');
811
+ }
812
+ if (options.titleBgColor) {
813
+ titleJustify = 'center';
814
+ }
815
+ }
816
+ else if (type & 256 /* LOG_VALUE.TIME_PROCESS */) {
817
+ if (options.failed) {
818
+ options.messageBgColor || (options.messageBgColor = 'bgGrey');
819
+ }
820
+ else {
821
+ const { color, bgColor, bold } = format.meter;
822
+ if (!options.messageBgColor && !options.messageColor) {
823
+ if (color) {
824
+ options.messageColor = color;
825
+ }
826
+ if (bgColor) {
827
+ options.messageBgColor = bgColor;
828
+ }
829
+ }
830
+ if (bold) {
831
+ options.messageBold ?? (options.messageBold = true);
832
+ }
833
+ }
834
+ }
835
+ }
836
+ title = titleIndent !== -1 ? ' '.repeat(titleIndent || (formatTitle.width + 3)) : (0, types_1.isString)(title) ? alignColumn(title.toUpperCase(), formatTitle.width, titleJustify, 1) : '';
837
+ if (hint) {
838
+ const formatHint = format.hint;
839
+ let { hintColor, hintBgColor, hintBold } = options, hintWidth = formatHint.width;
840
+ valueWidth -= Math.min(hint.length, hintWidth) + 2;
841
+ if (hint.length > hintWidth && value.length + 1 < valueWidth) {
842
+ const offset = Math.min(valueWidth - (value.length + 1), hint.length - hintWidth);
843
+ hintWidth += offset;
844
+ valueWidth -= offset;
845
+ }
846
+ if (!hintColor && !hintBgColor) {
847
+ ({ color: hintColor, bgColor: hintBgColor } = formatHint);
848
+ hintBold ?? (hintBold = formatHint.bold);
849
+ }
850
+ value = getValue() + (coloring ? chalk.blackBright('[') + formatColumn(truncateEnd(hint, hintWidth), hintColor, hintBgColor, hintBold) + chalk.blackBright(']') : `[${truncateEnd(hint, hintWidth)}]`);
851
+ }
852
+ else if (title) {
853
+ value = getValue();
854
+ }
855
+ const unit = options.messageUnit ? type & 256 /* LOG_VALUE.TIME_PROCESS */ ? options.messageUnit.padStart(options.messageUnitMinWidth || 0) : options.messageUnit : '';
856
+ const getMessage = (m, u) => type & 256 /* LOG_VALUE.TIME_PROCESS */ && messageUnitIndent === undefined ? (u + m).trimEnd() : u ? (m + (messageUnitIndent === undefined ? ' ' : '') + u).trimStart() : m;
857
+ if (coloring) {
858
+ let { titleColor, titleBgColor, valueColor, valueBgColor, valueBold, messageWidth, messageColor, messageBgColor, messageBold } = options;
859
+ if (!titleColor && !titleBgColor) {
860
+ ({ color: titleColor, bgColor: titleBgColor } = formatTitle);
861
+ }
862
+ if (!valueColor && !valueBgColor) {
863
+ ({ color: valueColor, bgColor: valueBgColor } = formatValue);
864
+ valueBold ?? (valueBold = formatValue.bold);
865
+ }
866
+ try {
867
+ let v = value, i = id, m = message;
868
+ if (i) {
869
+ const { color: sessionIdColor, bgColor: sessionIdBgColor, bold: sessionIdBold } = format.session_id;
870
+ i = sessionIdColor || sessionIdBgColor || sessionIdBold ? formatColumn(i, sessionIdColor, sessionIdBgColor, sessionIdBold) : chalk.grey(i);
871
+ }
872
+ if ((m || unit) && SETTINGS.message !== false) {
873
+ if (error) {
874
+ m && (m = chalk.redBright('{') + chalk.bgWhite.blackBright(m) + chalk.redBright('}'));
875
+ }
876
+ else {
877
+ const formatMessage = format.message;
878
+ if (!messageColor && !messageBgColor) {
879
+ ({ color: messageColor, bgColor: messageBgColor, bold: messageBold } = formatMessage);
880
+ messageBold ?? (messageBold = formatMessage.bold);
881
+ }
882
+ messageWidth ?? (messageWidth = formatMessage.width);
883
+ let u = unit;
884
+ if (u) {
885
+ if ((0, types_1.isObject)(SETTINGS.time_process)) {
886
+ const time_process = SETTINGS.time_process;
887
+ u = formatColumn(u, time_process.messageColor || 'grey', time_process.messageBgColor, time_process.messageBold);
888
+ }
889
+ else {
890
+ u = formatColumn(u, 'grey');
891
+ }
892
+ }
893
+ m = formatColumn(m, messageColor, messageBgColor, messageBold, messageUnitIndent !== undefined ? format.meter.bgAltColor : undefined, messageWidth);
894
+ m = chalk.blackBright('(') + getMessage(m, u) + chalk.blackBright(')');
895
+ }
896
+ }
897
+ else {
898
+ if (!i) {
899
+ v = v.trim();
900
+ }
901
+ m = '';
902
+ }
903
+ output = (titleIndent !== -1 ? title : title ? formatColumn(title, titleColor || 'green', titleBgColor, (options.titleBold || formatTitle.bold) ?? false) + chalk.blackBright(':') + ' ' : '') + formatColumn(v, valueColor, valueBgColor, valueBold) + (i ? i : ' ') + m;
904
+ }
905
+ catch {
906
+ }
907
+ }
908
+ if (!output) {
909
+ const m = truncateStart(this.asString(message), options.messageWidth ?? format.message.width);
910
+ output = (titleIndent !== -1 ? title : title ? title + ': ' : '') + value + (id ? id : ' ') + (m && SETTINGS.message !== false ? (error ? '{' : '(') + getMessage(m, unit) + (error ? '}' : ')') : '');
911
+ }
912
+ if (broadcastId) {
913
+ if (BROADCAST_OUT) {
914
+ try {
915
+ options = { ...options, broadcastId, timeStamp: getTimeStamp(options, false) };
916
+ // @ts-ignore
917
+ if (BROADCAST_OUT["__cjs__" /* INTERNAL.CJS */]) {
918
+ BROADCAST_OUT(output, options);
919
+ }
920
+ else {
921
+ BROADCAST_OUT.apply(VALUES["node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */] ? process : null, VALUES["node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */] ? [output, options, require] : [output, options]);
922
+ }
923
+ }
924
+ catch {
925
+ }
926
+ }
927
+ return;
928
+ }
929
+ const newline = options.newline;
930
+ if (!newline) {
931
+ LOG_EMPTYLINE = false;
932
+ }
933
+ else {
934
+ const lines = (newline === true ? 1 : Math.abs(newline)) - (LOG_EMPTYLINE ? 1 : 0);
935
+ if (lines > 0) {
936
+ PROCESS_STDOUT.write(lines === 1 ? '\n' : '\n'.repeat(lines));
937
+ LOG_EMPTYLINE = true;
938
+ }
939
+ }
940
+ if (type & 512 /* LOG_VALUE.FAIL */) {
941
+ process.stderr.write((!LOG_NEWLINE ? '\n' : '') + output + '\n');
942
+ }
943
+ else if (typeof options.progressBar === 'boolean' && typeof PROCESS_STDOUT.clearLine === 'function') {
944
+ if (!LOG_NEWLINE && !options.progressBar) {
945
+ PROCESS_STDOUT.write('\n' + output);
946
+ }
947
+ else {
948
+ PROCESS_STDOUT.clearLine(0);
949
+ PROCESS_STDOUT.cursorTo(0);
950
+ PROCESS_STDOUT.write(output);
951
+ }
952
+ LOG_NEWLINE = false;
953
+ }
954
+ else {
955
+ writeLine(output);
956
+ }
957
+ if (typeof newline === 'number' && newline < 0) {
958
+ PROCESS_STDOUT.write('\n'.repeat(Math.abs(newline)));
959
+ LOG_EMPTYLINE = true;
960
+ }
961
+ }
962
+ static writeFail(value, message, options) {
963
+ let type;
964
+ if ((0, types_1.isObject)(options)) {
965
+ ({ type } = options);
966
+ }
967
+ else {
968
+ if (typeof options === 'number') {
969
+ type = options;
970
+ }
971
+ options = {};
972
+ }
973
+ this.formatMessage(((type || 1 /* LOG_VALUE.SYSTEM */) | 512 /* LOG_VALUE.FAIL */), "FAIL!" /* ERR_MESSAGE.FAIL */, value, message, applyStyle(options, this.LOG_STYLE_FAIL));
974
+ }
975
+ static parseFunction(value, absolute, sync = true) {
976
+ let context, requireExt, external;
977
+ if ((0, types_1.isObject)(absolute)) {
978
+ ({ context, requireExt, external, absolute, sync = true } = absolute);
979
+ }
980
+ if (requireExt === undefined || requireExt === true) {
981
+ requireExt = VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */];
982
+ }
983
+ let result = (0, types_1.asFunction)(value, sync);
984
+ if (!result && (0, types_1.isString)(value)) {
985
+ let location = value.trim(), pathname;
986
+ if (location.startsWith('npm:')) {
987
+ location = location.substring(4);
988
+ }
989
+ else if (pathname = absolute && path.isAbsolute(location) ? location : this.fromLocalPath(location)) {
990
+ if (requireExt && VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */] && hasString(requireExt, getExtension(pathname))) {
991
+ try {
992
+ result = checkFunction(require(pathname));
993
+ }
994
+ catch {
995
+ }
996
+ }
997
+ if (!result) {
998
+ try {
999
+ result = (0, types_1.asFunction)(fs.readFileSync(pathname, 'utf-8'), sync);
1000
+ }
1001
+ catch (err) {
1002
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, value], err, 32 /* LOG_VALUE.FILE */);
1003
+ }
1004
+ }
1005
+ }
1006
+ if (external && !pathname && VALUES["node.require.npm" /* KEY_NAME.NODE_REQUIRE_NPM */] && location.length <= 214 && /^(?:@(?:[a-z\d-][a-z\d-._]*\/)+)?[a-z\d-][a-z\d-._]*$/.test(location)) {
1007
+ try {
1008
+ // @ts-ignore
1009
+ result = checkFunction(require(types_1.IMPORT_MAP[location] || location));
1010
+ }
1011
+ catch {
1012
+ }
1013
+ }
1014
+ }
1015
+ if (result) {
1016
+ if (context !== undefined) {
1017
+ result.bind(context);
1018
+ }
1019
+ return result;
1020
+ }
1021
+ return null;
1022
+ }
1023
+ static asString(value, cacheKey) {
1024
+ if ((0, types_1.isEmpty)(value)) {
1025
+ return '';
1026
+ }
1027
+ switch (typeof value) {
1028
+ case 'string':
1029
+ return value;
1030
+ case 'object':
1031
+ if (value.constructor === Object || Object.getPrototypeOf(value) === null) {
1032
+ if (Object.keys(value).length === 0) {
1033
+ return '';
1034
+ }
1035
+ }
1036
+ else if (!Array.isArray(value)) {
1037
+ if (value instanceof Error) {
1038
+ return value.message;
1039
+ }
1040
+ if (value instanceof Date) {
1041
+ return value.toJSON();
1042
+ }
1043
+ if (Buffer.isBuffer(value) || value instanceof URL) {
1044
+ return value.toString();
1045
+ }
1046
+ }
1047
+ try {
1048
+ const content = JSON.stringify(value);
1049
+ if (content && content !== '{}') {
1050
+ return content;
1051
+ }
1052
+ }
1053
+ catch {
1054
+ }
1055
+ if (cacheKey) {
1056
+ break;
1057
+ }
1058
+ default:
1059
+ try {
1060
+ return value.toString();
1061
+ }
1062
+ catch {
1063
+ }
1064
+ break;
1065
+ }
1066
+ if (cacheKey === 'throws') {
1067
+ throw new Error("Not able to cache" /* ERR_MESSAGE.NOT_CACHEABLE */);
1068
+ }
1069
+ return cacheKey ? (0, types_1.generateUUID)() : '';
1070
+ }
1071
+ static asHash(data, algorithm, minLength = 0) {
1072
+ let options;
1073
+ if (typeof minLength !== 'number') {
1074
+ options = minLength;
1075
+ minLength = 0;
1076
+ }
1077
+ if (typeof algorithm === 'number') {
1078
+ minLength = algorithm;
1079
+ algorithm = '';
1080
+ }
1081
+ else if ((0, types_1.isObject)(algorithm)) {
1082
+ options = algorithm;
1083
+ algorithm = '';
1084
+ }
1085
+ let digest;
1086
+ if (options) {
1087
+ options = { ...options };
1088
+ if ('minLength' in options) {
1089
+ minLength = options.minLength;
1090
+ delete options.minLength;
1091
+ }
1092
+ if ('algorithm' in options) {
1093
+ algorithm = options.algorithm;
1094
+ delete options.algorithm;
1095
+ }
1096
+ if ('digest' in options) {
1097
+ digest = options.digest;
1098
+ delete options.digest;
1099
+ }
1100
+ }
1101
+ if (minLength > 0 && typeof data === 'string' && data.length > minLength) {
1102
+ return data;
1103
+ }
1104
+ try {
1105
+ return crypto.createHash(algorithm || 'sha256', options).update(data).digest(digest || 'hex');
1106
+ }
1107
+ catch {
1108
+ return '';
1109
+ }
1110
+ }
1111
+ static toPosix(value, filename, normalize) {
1112
+ if (typeof filename === 'boolean') {
1113
+ normalize = filename;
1114
+ filename = undefined;
1115
+ }
1116
+ if (typeof value === 'string') {
1117
+ let pathname = value.trim(), convert = true;
1118
+ if (normalize) {
1119
+ pathname = path.normalize(pathname);
1120
+ convert = PLATFORM_WIN32;
1121
+ }
1122
+ if (convert) {
1123
+ pathname = pathname.replace(/(?:^\\|\\+)/g, '/');
1124
+ }
1125
+ if (pathname = pathname.replace(/\/+$/, '')) {
1126
+ if (normalize && PLATFORM_WIN32) {
1127
+ const match = /^([A-Z]):\//.exec(pathname);
1128
+ if (match) {
1129
+ pathname = match[1].toLowerCase() + pathname.substring(1);
1130
+ }
1131
+ }
1132
+ return pathname + (filename ? '/' + filename : '');
1133
+ }
1134
+ }
1135
+ return filename || '';
1136
+ }
1137
+ static isURL(value, ...exclude) {
1138
+ const match = /^([a-z][a-z\d+-.]*):\/\//i.exec(value);
1139
+ return !!match && (exclude.length === 0 || !exclude.includes(match[1].toLowerCase()));
1140
+ }
1141
+ static isFile(value, type) {
1142
+ if (!type) {
1143
+ value = asFile(value);
1144
+ return !!value && this.isPath(value, true);
1145
+ }
1146
+ if (typeof value === 'string') {
1147
+ switch (type) {
1148
+ case 'http':
1149
+ return /^http:\/\/[^/]/i.test(value);
1150
+ case 'https':
1151
+ return /^https:\/\/[^/]/i.test(value);
1152
+ case 'http/s':
1153
+ return /^https?:\/\/[^/]/i.test(value);
1154
+ case 'unc':
1155
+ return /^(?:\\\\|\/\/)[\w.-]+[\\/][\w-]+\$?[\\/][^\n]*?[^\\/]$/.test(value);
1156
+ case 'ftp':
1157
+ return /^ftp:\/\/[^/]/i.test(value);
1158
+ case 'sftp':
1159
+ return /^sftp:\/\/[^/]/i.test(value);
1160
+ case 's/ftp':
1161
+ return /^s?ftp:\/\/[^/]/i.test(value);
1162
+ case 'torrent':
1163
+ return REGEXP_TORRENT.test(value);
1164
+ }
1165
+ }
1166
+ else if (value instanceof URL) {
1167
+ switch (type) {
1168
+ case 'http':
1169
+ return value.protocol === 'http:';
1170
+ case 'https':
1171
+ return value.protocol === 'https:';
1172
+ case 'http/s':
1173
+ return value.protocol === 'http:' || value.protocol === 'https:';
1174
+ case 'unc':
1175
+ return /^(?:\\\\|\/\/)[\w.-]+[\\/][\w-]+\$?[\\/][^\n]*?[^\\/]$/.test(value.toString());
1176
+ case 'ftp':
1177
+ return value.protocol === 'ftp:';
1178
+ case 'sftp':
1179
+ return value.protocol === 'sftp:';
1180
+ case 's/ftp':
1181
+ return value.protocol === 'ftp:' || value.protocol === 'sftp:';
1182
+ case 'torrent':
1183
+ return REGEXP_TORRENT.test(value.toString());
1184
+ }
1185
+ }
1186
+ return false;
1187
+ }
1188
+ static isDir(value) {
1189
+ try {
1190
+ return fs.statSync(value).isDirectory();
1191
+ }
1192
+ catch {
1193
+ return false;
1194
+ }
1195
+ }
1196
+ static isPath(value, type) {
1197
+ try {
1198
+ if (!type) {
1199
+ return fs.existsSync(value);
1200
+ }
1201
+ switch (type) {
1202
+ case true:
1203
+ return fs.statSync(value).isFile();
1204
+ case 'unc-exists':
1205
+ if (!fs.existsSync(value)) {
1206
+ return false;
1207
+ }
1208
+ case 'unc':
1209
+ return /^(?:\\\\|\/\/)[\w.-]+[\\/][\w-]+\$?(?:[\\/]?|[\\/][^\n]+)$/.test(asFile(value));
1210
+ }
1211
+ }
1212
+ catch (err) {
1213
+ return !type && this.isErrorCode(err, 'EBUSY', 'EPERM');
1214
+ }
1215
+ }
1216
+ static isErrorCode(err, ...code) {
1217
+ if (err instanceof Error) {
1218
+ const value = err.code;
1219
+ return typeof value === 'string' && code.includes(value);
1220
+ }
1221
+ return false;
1222
+ }
1223
+ static resolveFile(value) {
1224
+ if (isFileURL(value = value instanceof URL ? value.toString() : value.trim())) {
1225
+ try {
1226
+ return url.fileURLToPath(value);
1227
+ }
1228
+ catch {
1229
+ }
1230
+ return '';
1231
+ }
1232
+ if (/^\\\\\?\\[A-Za-z]:\\/.test(value)) {
1233
+ return process.platform === 'win32' && !/\\\\|\\\.+\\|\\[^\n]+?\.+\\/.test(value = value.substring(4)) ? value : '';
1234
+ }
1235
+ return this.fromLocalPath(value) || value;
1236
+ }
1237
+ static resolvePath(value, base) {
1238
+ try {
1239
+ if (this.isURL(value = value.trim())) {
1240
+ return isFileURL(value) ? url.fileURLToPath(value) : new URL(value).href;
1241
+ }
1242
+ if (base instanceof URL || this.isURL(base)) {
1243
+ return new URL(value, base).href;
1244
+ }
1245
+ if (typeof base === 'string' && path.isAbsolute(base)) {
1246
+ return path.resolve(base, value);
1247
+ }
1248
+ }
1249
+ catch {
1250
+ }
1251
+ return '';
1252
+ }
1253
+ static joinPath(...values) {
1254
+ let normalize;
1255
+ if (typeof values[values.length - 1] === 'boolean') {
1256
+ normalize = values.pop();
1257
+ }
1258
+ const paths = values.map(item => typeof item === 'string' ? item.trim() : '').filter(item => item).map(value => this.toPosix(value, normalize));
1259
+ let result = paths[0] || '';
1260
+ for (let i = 1; i < paths.length; ++i) {
1261
+ const trailing = paths[i];
1262
+ result += (trailing[0] !== '/' && result[result.length - 1] !== '/' ? '/' : '') + trailing;
1263
+ }
1264
+ return result;
1265
+ }
1266
+ static normalizePath(value, flags = 0) {
1267
+ if (typeof value === 'string') {
1268
+ if (typeof flags === 'boolean') {
1269
+ flags = flags ? 2 : 0;
1270
+ }
1271
+ let result = value.trim();
1272
+ result = flags & 1 ? path.resolve(result) : path.normalize(result);
1273
+ if ((flags & 3) && result.length) {
1274
+ result = ensureDir(result);
1275
+ }
1276
+ return (flags & 4) && PLATFORM_WIN32 ? this.toPosix(result) : result;
1277
+ }
1278
+ return '';
1279
+ }
1280
+ static fromLocalPath(value) {
1281
+ const ch = value[0];
1282
+ if (ch === '.' && /^\.{1,2}[\\/][^\\/]/.test(value)) {
1283
+ return path.join(PROCESS_CWD, value);
1284
+ }
1285
+ if (ch === '~' && value[1] === '/') {
1286
+ return VALUES["permission.home_read" /* KEY_NAME.PERMISSION_HOMEREAD */] ? path.join(OS_HOMEDIR, value.substring(2)) : '';
1287
+ }
1288
+ try {
1289
+ if (fs.existsSync(value = path.join(PROCESS_CWD, value))) {
1290
+ return value;
1291
+ }
1292
+ }
1293
+ catch {
1294
+ }
1295
+ return '';
1296
+ }
1297
+ static createDir(value, overwrite) {
1298
+ const outDir = sanitizePath(value = asFile(value));
1299
+ if (outDir) {
1300
+ try {
1301
+ const stat = fs.statSync(outDir);
1302
+ if (stat.isDirectory()) {
1303
+ return true;
1304
+ }
1305
+ if (overwrite && (stat.isFile() || stat.isSymbolicLink())) {
1306
+ try {
1307
+ fs.unlinkSync(outDir);
1308
+ }
1309
+ catch {
1310
+ this.formatMessage(32 /* LOG_VALUE.FILE */, 'WARN', "Unable to overwrite file" /* ERR_MESSAGE.OVERWRITE_FILE */, value, { ...this.LOG_STYLE_WARN });
1311
+ return false;
1312
+ }
1313
+ }
1314
+ else {
1315
+ return false;
1316
+ }
1317
+ }
1318
+ catch (err) {
1319
+ if (this.isErrorCode(err, 'EBUSY', 'EPERM')) {
1320
+ return false;
1321
+ }
1322
+ }
1323
+ try {
1324
+ return tryCreateDir(outDir);
1325
+ }
1326
+ catch (err) {
1327
+ this.writeFail(["Unable to create directory" /* ERR_MESSAGE.CREATE_DIRECTORY */, value], err, 32 /* LOG_VALUE.FILE */);
1328
+ }
1329
+ }
1330
+ return false;
1331
+ }
1332
+ static removeDir(value, empty = false, recursive = true) {
1333
+ if (value = asFile(value)) {
1334
+ try {
1335
+ if (typeof empty === 'number' && empty <= 0) {
1336
+ empty = true;
1337
+ }
1338
+ if (this.isDir(value)) {
1339
+ return tryRemoveDir(value, empty, !!recursive).length === 0;
1340
+ }
1341
+ if (!fs.existsSync(value)) {
1342
+ if (empty && typeof empty !== 'number') {
1343
+ this.createDir(value);
1344
+ }
1345
+ return true;
1346
+ }
1347
+ }
1348
+ catch (err) {
1349
+ this.writeFail(["Unable to remove directory" /* ERR_MESSAGE.REMOVE_DIRECTORY */, value], err, 32 /* LOG_VALUE.FILE */);
1350
+ }
1351
+ }
1352
+ return false;
1353
+ }
1354
+ static copyDir(src, dest, move, recursive = true) {
1355
+ const srcOut = sanitizePath(asFile(src));
1356
+ if (!srcOut || !this.isDir(srcOut)) {
1357
+ return Promise.reject(errorDirectory(asFile(src) || "Unknown" /* ERR_MESSAGE.UNKNOWN */));
1358
+ }
1359
+ const destOut = sanitizePath(asFile(dest));
1360
+ if (!destOut || !this.createDir(destOut)) {
1361
+ return Promise.reject(errorDirectory(asFile(dest) || "Unknown" /* ERR_MESSAGE.UNKNOWN */));
1362
+ }
1363
+ let symFile, symDir, ignoreFile, ignoreDir, silent, overwrite;
1364
+ if ((0, types_1.isObject)(move)) {
1365
+ ({ move, recursive = true, symFile, symDir, ignoreFile, ignoreDir, silent, overwrite } = move);
1366
+ }
1367
+ return new Promise(resolve => {
1368
+ const tasks = [];
1369
+ const success = [];
1370
+ const failed = [];
1371
+ const ignored = [];
1372
+ const methodName = move ? 'rename' : 'copyFile';
1373
+ const srcFound = [];
1374
+ const symFound = [];
1375
+ (function recurse(paths, depth) {
1376
+ const srcDir = path.join(srcOut, ...paths);
1377
+ const destDir = path.join(destOut, ...paths);
1378
+ srcFound.push(srcDir);
1379
+ if (this.createDir(destDir)) {
1380
+ try {
1381
+ fs.readdirSync(srcDir, { withFileTypes: true }).forEach(file => {
1382
+ const name = file.name;
1383
+ const destPath = path.join(destDir, name);
1384
+ let srcPath = path.join(srcDir, name), isDir = false, isFile = file.isFile() ? 1 : 0;
1385
+ const ignore = () => !ignored.includes(srcPath) && ignored.push(srcPath);
1386
+ if (file.isSymbolicLink()) {
1387
+ const previous = symFound.includes(srcPath);
1388
+ symFound.push(srcPath);
1389
+ try {
1390
+ const realPath = fs.realpathSync(srcPath);
1391
+ const stat = fs.statSync(realPath);
1392
+ if (stat.isFile()) {
1393
+ if (symFile === false || !(fs.existsSync(destPath) && !fs.statSync(destPath).isFile())) {
1394
+ return ignore();
1395
+ }
1396
+ srcPath = realPath;
1397
+ isFile = 2;
1398
+ }
1399
+ else {
1400
+ if (symDir !== true || previous || !stat.isDirectory()) {
1401
+ return ignore();
1402
+ }
1403
+ isFile = 0;
1404
+ isDir = true;
1405
+ }
1406
+ }
1407
+ catch {
1408
+ return ignore();
1409
+ }
1410
+ }
1411
+ if (isFile) {
1412
+ if (ignoreFile?.test(name)) {
1413
+ return ignore();
1414
+ }
1415
+ if (overwrite === false) {
1416
+ try {
1417
+ if (fs.existsSync(destPath)) {
1418
+ return ignore();
1419
+ }
1420
+ }
1421
+ catch {
1422
+ return ignore();
1423
+ }
1424
+ }
1425
+ tasks.push(fs.promises[isFile === 2 ? 'copyFile' : methodName](srcPath, destPath)
1426
+ .then(() => {
1427
+ success.push(destPath);
1428
+ })
1429
+ .catch(err => {
1430
+ failed.push(srcPath);
1431
+ if (!silent) {
1432
+ this.writeFail([move ? "Unable to move file" /* ERR_MESSAGE.MOVE_FILE */ : "Unable to copy file" /* ERR_MESSAGE.COPY_FILE */, path.basename(srcPath)], err, 32 /* LOG_VALUE.FILE */);
1433
+ }
1434
+ }));
1435
+ }
1436
+ else if (depth > 0 && (isDir || file.isDirectory())) {
1437
+ if (ignoreDir?.test(name)) {
1438
+ return ignore();
1439
+ }
1440
+ recurse.call(this, paths.concat(name), depth - 1);
1441
+ }
1442
+ });
1443
+ }
1444
+ catch (err) {
1445
+ failed.push(srcDir);
1446
+ if (!silent) {
1447
+ this.writeFail(["Unable to read directory" /* ERR_MESSAGE.READ_DIRECTORY */, path.basename(srcDir)], err, 32 /* LOG_VALUE.FILE */);
1448
+ }
1449
+ }
1450
+ }
1451
+ else {
1452
+ failed.push(srcDir);
1453
+ }
1454
+ }).call(this, [], !recursive ? 0 : typeof recursive === 'number' ? recursive : Infinity);
1455
+ Promise.all(tasks).then(() => {
1456
+ if (move) {
1457
+ const remaining = failed.slice(0);
1458
+ for (const sym of symFound) {
1459
+ try {
1460
+ fs.realpathSync(sym);
1461
+ }
1462
+ catch {
1463
+ fs.unlinkSync(sym);
1464
+ }
1465
+ }
1466
+ for (const srcDir of srcFound.reverse()) {
1467
+ const dirName = ensureDir(srcDir);
1468
+ if (!remaining.includes(srcDir) && !remaining.some(file => file.startsWith(dirName))) {
1469
+ try {
1470
+ fs.rmdirSync(srcDir);
1471
+ }
1472
+ catch {
1473
+ failed.push(srcDir);
1474
+ remaining.push(srcDir);
1475
+ }
1476
+ }
1477
+ }
1478
+ }
1479
+ resolve({ success, failed, ignored });
1480
+ });
1481
+ });
1482
+ }
1483
+ static renameFile(src, dest, throws = true) {
1484
+ try {
1485
+ fs.renameSync(src, dest);
1486
+ return true;
1487
+ }
1488
+ catch (err) {
1489
+ if (this.isErrorCode(err, 'EXDEV')) {
1490
+ let copied = false;
1491
+ try {
1492
+ fs.copyFileSync(src, dest);
1493
+ copied = true;
1494
+ fs.unlinkSync(src);
1495
+ return true;
1496
+ }
1497
+ catch (error) {
1498
+ if (copied) {
1499
+ this.formatMessage(32 /* LOG_VALUE.FILE */, 'WARN', ["Unable to delete file" /* ERR_MESSAGE.DELETE_FILE */, path.basename(src instanceof URL ? url.fileURLToPath(src) : src)], error, { ...this.LOG_STYLE_WARN });
1500
+ throws = false;
1501
+ }
1502
+ }
1503
+ }
1504
+ if (throws) {
1505
+ throw err;
1506
+ }
1507
+ }
1508
+ return false;
1509
+ }
1510
+ static readText(value, encoding, cache) {
1511
+ if (typeof encoding === 'boolean') {
1512
+ cache = encoding;
1513
+ encoding = undefined;
1514
+ }
1515
+ const src = sanitizePath(asFile(value));
1516
+ if (src && this.isPath(src, true)) {
1517
+ let result;
1518
+ if (cache && (result = getCacheItem(CACHE_READTEXT, src))) {
1519
+ return result;
1520
+ }
1521
+ try {
1522
+ result = fs.readFileSync(value, (0, types_1.getEncoding)(encoding));
1523
+ if (cache && result) {
1524
+ addCacheItem(CACHE_READTEXT, src, result);
1525
+ }
1526
+ return result;
1527
+ }
1528
+ catch (err) {
1529
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(src)], err, 32 /* LOG_VALUE.FILE */);
1530
+ }
1531
+ }
1532
+ return '';
1533
+ }
1534
+ static readBuffer(value, cache) {
1535
+ const src = sanitizePath(asFile(value));
1536
+ if (src && this.isPath(src, true)) {
1537
+ let result;
1538
+ if (cache && (result = getCacheItem(CACHE_READBUFFER, src))) {
1539
+ return result;
1540
+ }
1541
+ try {
1542
+ result = fs.readFileSync(value);
1543
+ if (cache && result) {
1544
+ addCacheItem(CACHE_READBUFFER, src, result);
1545
+ }
1546
+ return result;
1547
+ }
1548
+ catch (err) {
1549
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(src)], err, 32 /* LOG_VALUE.FILE */);
1550
+ }
1551
+ }
1552
+ return null;
1553
+ }
1554
+ static resolveMime(data) {
1555
+ return typeof data === 'string' ? filetype.fromFile(data) : filetype.fromBuffer(data);
1556
+ }
1557
+ static lookupMime(value, extension) {
1558
+ return (extension ? mime.extension(value) : mime.lookup(value)) || '';
1559
+ }
1560
+ static initCpuUsage(instance) {
1561
+ if (!VALUES["node.process.cpu_usage" /* KEY_NAME.NODE_PROCESS_CPUUSAGE */]) {
1562
+ return { user: 0, system: 0 };
1563
+ }
1564
+ const result = process.cpuUsage();
1565
+ CACHE_CPU.set(result, getCpuTimes());
1566
+ if (instance) {
1567
+ CACHE_CPUHOST.set(instance, result);
1568
+ }
1569
+ return result;
1570
+ }
1571
+ static getCpuUsage(start, format) {
1572
+ if (VALUES["node.process.cpu_usage" /* KEY_NAME.NODE_PROCESS_CPUUSAGE */]) {
1573
+ let value = CACHE_CPU.get(start);
1574
+ if (value === undefined) {
1575
+ CACHE_CPU.set(start, getCpuTimes());
1576
+ }
1577
+ else if ((value = getCpuTimes() - value) >= 0) {
1578
+ let result = 0;
1579
+ if (value > 0) {
1580
+ const { user, system } = process.cpuUsage(start);
1581
+ const usage = user + system;
1582
+ result = usage > 0 ? Math.min(usage / value, 1) * (typeof SETTINGS.process === 'object' && SETTINGS.process.cpu_single_core ? 1 : CPU_CORETOTAL) : 0;
1583
+ }
1584
+ return format ? formatPercent(result) : result;
1585
+ }
1586
+ }
1587
+ return format ? '' : 0;
1588
+ }
1589
+ static getMemUsage(format) {
1590
+ if (!VALUES["node.process.memory_usage" /* KEY_NAME.NODE_PROCESS_MEMORYUSAGE */]) {
1591
+ return format ? '' : 0;
1592
+ }
1593
+ const usage = process.memoryUsage();
1594
+ let result = 0;
1595
+ for (const name in usage) {
1596
+ if (name !== 'heapUsed') {
1597
+ result += usage[name];
1598
+ }
1599
+ }
1600
+ if (typeof format === 'string') {
1601
+ const unit = format.toUpperCase();
1602
+ switch (unit) {
1603
+ case 'B':
1604
+ case 'KB':
1605
+ return (0, types_1.formatSize)(result, { unit, decimalPlaces: 0 });
1606
+ case 'MB':
1607
+ return (0, types_1.formatSize)(result, { unit, decimalPlaces: 1 });
1608
+ case 'GB':
1609
+ case 'TB':
1610
+ case 'PB':
1611
+ return (0, types_1.formatSize)(result, { unit });
1612
+ }
1613
+ }
1614
+ return format ? formatPercent(result / MEM_TOTAL) : result;
1615
+ }
1616
+ static formatCpuMem(start, all) {
1617
+ let cpu, cpu_bar, cpu_single_core, mem, mem_format;
1618
+ if (typeof SETTINGS.process === 'object') {
1619
+ ({ cpu, cpu_bar, cpu_single_core, mem, mem_format } = SETTINGS.process);
1620
+ }
1621
+ let result = '';
1622
+ if (cpu || all) {
1623
+ let usage = this.getCpuUsage(start, !cpu_bar);
1624
+ if (usage) {
1625
+ if (typeof usage === 'number') {
1626
+ if (!cpu_single_core) {
1627
+ usage /= CPU_CORETOTAL;
1628
+ }
1629
+ if (usage + 0.005 /* CPU_MEM.BAR_100_OFFSET */ >= 1) {
1630
+ usage = 1;
1631
+ }
1632
+ let bar = 20 /* CPU_MEM.BAR_LENGTH */, red = 0.9 /* CPU_MEM.BAR_RED */, yellow = 0.75 /* CPU_MEM.BAR_YELLOW */;
1633
+ if (typeof cpu_bar === 'number') {
1634
+ bar = cpu_bar;
1635
+ }
1636
+ else if (Array.isArray(cpu_bar) && cpu_bar[0] >= 10 /* CPU_MEM.BAR_MIN_LENGTH */) {
1637
+ let r, y;
1638
+ [bar, r = 0.9 /* CPU_MEM.BAR_RED */, y = 0.75 /* CPU_MEM.BAR_YELLOW */] = cpu_bar;
1639
+ if (r > 0 && r < 1 && y > 0 && y < 1 && y < r) {
1640
+ red = r;
1641
+ yellow = y;
1642
+ }
1643
+ }
1644
+ const unit = Math.max(bar, 10 /* CPU_MEM.BAR_MIN_LENGTH */);
1645
+ const length = Math.floor(usage * unit);
1646
+ const hint = usage === 1 ? "MAX" /* CPU_MEM.BAR_100 */ : formatPercent(usage, 2);
1647
+ result += chalk[usage >= red ? 'bgRed' : usage >= yellow ? 'bgYellow' : 'bgBlue'].white(':'.repeat(length)) + chalk.bgGrey.white(':'.repeat(unit - length)) + (hint ? chalk.bgWhite.grey(` ${hint} `) : '');
1648
+ }
1649
+ else {
1650
+ result += usage + ' CPU' + (!cpu_single_core ? '/' + CPU_CORETOTAL : '');
1651
+ }
1652
+ }
1653
+ }
1654
+ if (mem || all) {
1655
+ const usage = this.getMemUsage(mem_format || true);
1656
+ if (usage) {
1657
+ result += (result ? ' ' : '') + usage + ' MEM';
1658
+ }
1659
+ }
1660
+ return result;
1661
+ }
1662
+ static getPackageVersion(value, unstable, startDir) {
1663
+ if (typeof unstable === 'string') {
1664
+ startDir = unstable;
1665
+ unstable = false;
1666
+ }
1667
+ let rootPackage;
1668
+ if (Array.isArray(value)) {
1669
+ [rootPackage, value] = value;
1670
+ }
1671
+ const folders = [PROCESS_CWD];
1672
+ if (startDir && withinDir(startDir = path.normalize(startDir), PROCESS_CWD)) {
1673
+ startDir = startDir.replace(/[\\/]+$/, '');
1674
+ let i = -1, j = PROCESS_CWD.length + 1;
1675
+ while ((i = startDir.indexOf(path.sep, j)) !== -1) {
1676
+ const current = startDir.substring(0, i);
1677
+ if (!current.endsWith(path.sep + 'node_modules')) {
1678
+ folders.push(current);
1679
+ }
1680
+ j = i + 1;
1681
+ }
1682
+ folders.push(startDir);
1683
+ folders.reverse();
1684
+ }
1685
+ for (const folder of folders) {
1686
+ try {
1687
+ const pkg = path.join(folder, `node_modules/${value}/package.json`);
1688
+ if (fs.existsSync(pkg)) {
1689
+ const { name, version } = JSON.parse(fs.readFileSync(pkg, 'utf-8'));
1690
+ if (name === value && typeof version === 'string') {
1691
+ return version.trim();
1692
+ }
1693
+ }
1694
+ }
1695
+ catch {
1696
+ }
1697
+ }
1698
+ const latest = (result) => {
1699
+ if (result.length > 1) {
1700
+ result.sort((a, b) => {
1701
+ const c = a.split('.');
1702
+ const d = b.split('.');
1703
+ if (!unstable) {
1704
+ const g = c.some(e => isNaN(+e));
1705
+ const h = d.some(f => isNaN(+f));
1706
+ if (g && !h) {
1707
+ return 1;
1708
+ }
1709
+ if (h && !g) {
1710
+ return -1;
1711
+ }
1712
+ }
1713
+ return (function recurse() {
1714
+ const e = c.shift();
1715
+ const f = d.shift();
1716
+ if (!e || !f) {
1717
+ return 0;
1718
+ }
1719
+ if (e !== f) {
1720
+ const g = parseInt(f) - parseInt(e);
1721
+ if (g === 0) {
1722
+ if (isNaN(+e) && !isNaN(+f)) {
1723
+ return 1;
1724
+ }
1725
+ if (isNaN(+f) && !isNaN(+e)) {
1726
+ return -1;
1727
+ }
1728
+ return e < f ? 1 : -1;
1729
+ }
1730
+ return g;
1731
+ }
1732
+ return recurse();
1733
+ })();
1734
+ });
1735
+ }
1736
+ return result[0];
1737
+ };
1738
+ if (PNPM_VER) {
1739
+ const result = [];
1740
+ const pattern = new RegExp(`/${(0, types_1.escapePattern)(value)}/([^:]+):`, 'g');
1741
+ let match;
1742
+ while (match = pattern.exec(PNPM_VER)) {
1743
+ result.push(match[1]);
1744
+ }
1745
+ if (result.length) {
1746
+ return latest(result);
1747
+ }
1748
+ }
1749
+ if (YARN_VER) {
1750
+ folders.forEach((folder, index) => {
1751
+ folder = ensureDir(folder).replace(path.sep + 'node_modules' + path.sep, path.sep + 'packages' + path.sep);
1752
+ folders[index] = PLATFORM_WIN32 ? folder.toLowerCase() : folder;
1753
+ });
1754
+ try {
1755
+ const result = [];
1756
+ let treeRoots = YARN_VER.getDependencyTreeRoots(), version;
1757
+ if (rootPackage) {
1758
+ treeRoots = treeRoots.filter(item => item.name === rootPackage);
1759
+ }
1760
+ const getVersion = (item) => {
1761
+ const dependency = item.packageDependencies.get(value);
1762
+ if (typeof dependency === 'string') {
1763
+ const pkg = dependency.split('npm:');
1764
+ if (pkg.length > 1) {
1765
+ return pkg.pop();
1766
+ }
1767
+ }
1768
+ };
1769
+ for (const folder of folders) {
1770
+ for (const locator of treeRoots) {
1771
+ const item = YARN_VER.getPackageInformation(locator);
1772
+ if (item && (PLATFORM_WIN32 ? item.packageLocation.toLowerCase() : item.packageLocation) === folder && (version = getVersion(item))) {
1773
+ return version;
1774
+ }
1775
+ }
1776
+ }
1777
+ for (const locator of treeRoots) {
1778
+ const item = YARN_VER.getPackageInformation(locator);
1779
+ if (item && (version = getVersion(item))) {
1780
+ result.push(version);
1781
+ }
1782
+ }
1783
+ if (result.length) {
1784
+ return latest(result);
1785
+ }
1786
+ }
1787
+ catch {
1788
+ }
1789
+ }
1790
+ return '0.0.0';
1791
+ }
1792
+ static checkSemVer(name, min = 0, max = Infinity, unstable, startDir) {
1793
+ if ((0, types_1.isObject)(min)) {
1794
+ ({ min = 0, max = Infinity, unstable, startDir } = min);
1795
+ }
1796
+ else if ((0, types_1.isObject)(unstable)) {
1797
+ ({ unstable, startDir } = unstable);
1798
+ }
1799
+ if (typeof min === 'number' && Math.floor(min) !== min) {
1800
+ min = min.toString();
1801
+ }
1802
+ if (typeof max === 'number' && Math.floor(max) !== max) {
1803
+ max = max.toString();
1804
+ }
1805
+ const minVersion = typeof min === 'string' ? min.split('.').map(ver => parseInt(ver)) : [min];
1806
+ let maxVersion, maxRange;
1807
+ if (typeof max === 'string') {
1808
+ maxVersion = max.split('.').map(ver => parseInt(ver));
1809
+ }
1810
+ else if (max === Infinity) {
1811
+ maxVersion = [Infinity];
1812
+ }
1813
+ else {
1814
+ maxVersion = [max - 1];
1815
+ maxRange = true;
1816
+ }
1817
+ let version = this.getPackageVersion(name, unstable, startDir);
1818
+ if (version === '0.0.0') {
1819
+ return false;
1820
+ }
1821
+ version = version.split('.').map(ver => parseInt(ver));
1822
+ for (let i = 0, length = Math.max(version.length, minVersion.length), lower = false, upper = false; i < length; ++i) {
1823
+ const ver = version[i] || 0;
1824
+ min = minVersion[i] || 0;
1825
+ max = maxVersion[i] || (maxRange ? Infinity : 0);
1826
+ if (!lower) {
1827
+ if (ver < min) {
1828
+ return false;
1829
+ }
1830
+ lower = ver > min;
1831
+ }
1832
+ if (!upper) {
1833
+ if (ver > max) {
1834
+ return false;
1835
+ }
1836
+ upper = ver < max;
1837
+ }
1838
+ }
1839
+ return true;
1840
+ }
1841
+ static sanitizeCmd(value) {
1842
+ if (value.indexOf(' ') !== -1) {
1843
+ return PLATFORM_WIN32 ? wrapQuote(value) : value.replace(/[ ]/g, '\\ ');
1844
+ }
1845
+ return value;
1846
+ }
1847
+ static sanitizeArgs(values, doubleQuote) {
1848
+ const result = typeof values === 'string' ? [values] : values;
1849
+ const pattern = /^(["'])(.*)\1$/;
1850
+ const sanitize = (value) => value.replace(REGEXP_SHELLVAL, capture => (capture === '$' || capture === '`' ? '\\' : '') + '\\' + capture);
1851
+ for (let i = 0; i < result.length; ++i) {
1852
+ let value = result[i].trim(), leading = '';
1853
+ if (value !== '--') {
1854
+ const opt = REGEXP_SHELLOPT.exec(value);
1855
+ if (opt) {
1856
+ if (!opt[2] && !opt[3]) {
1857
+ result[i] = opt[1];
1858
+ continue;
1859
+ }
1860
+ leading = opt[1] + (opt[2] || ' ');
1861
+ value = opt[3];
1862
+ }
1863
+ if (value) {
1864
+ const quoted = pattern.exec(value);
1865
+ if (PLATFORM_WIN32) {
1866
+ if (quoted) {
1867
+ if (quoted[1] === '"') {
1868
+ result[i] = leading + value;
1869
+ continue;
1870
+ }
1871
+ value = quoted[2];
1872
+ }
1873
+ if (value.indexOf(' ') !== -1) {
1874
+ value = wrapQuote(value);
1875
+ }
1876
+ }
1877
+ else {
1878
+ let type = doubleQuote;
1879
+ if (quoted) {
1880
+ if (quoted[1] === "'") {
1881
+ result[i] = leading + value;
1882
+ continue;
1883
+ }
1884
+ value = quoted[2];
1885
+ type = true;
1886
+ }
1887
+ if (REGEXP_SHELLVAL.test(value)) {
1888
+ if (type) {
1889
+ value = '"' + sanitize(value) + '"';
1890
+ }
1891
+ else {
1892
+ value = "'" + value.replace(/'/g, "'\\''") + "'";
1893
+ }
1894
+ }
1895
+ }
1896
+ }
1897
+ else if (opt) {
1898
+ leading = leading.trim();
1899
+ if (!PLATFORM_WIN32 && leading.length > 2 && leading[1] !== '-') {
1900
+ leading = sanitize(leading);
1901
+ }
1902
+ }
1903
+ }
1904
+ result[i] = leading + value;
1905
+ }
1906
+ return (typeof values === 'string' ? result[0] : result);
1907
+ }
1908
+ static purgeMemory(percent = 1, limit = 0) {
1909
+ if (typeof limit === 'boolean') {
1910
+ limit = 0;
1911
+ }
1912
+ let result = 0;
1913
+ if (limit === 0 || limit >= CACHE_TOTAL) {
1914
+ if (percent >= 1) {
1915
+ result += CACHE_READTEXT.size + CACHE_READBUFFER.size + CACHE_READCJS.size;
1916
+ CACHE_READTEXT.clear();
1917
+ CACHE_READBUFFER.clear();
1918
+ CACHE_READCJS.clear();
1919
+ CACHE_EXEC = new WeakMap();
1920
+ CACHE_CPU = new WeakMap();
1921
+ CACHE_CPUHOST = new WeakMap();
1922
+ (0, types_1.purgeMemory)();
1923
+ CACHE_TOTAL = 0;
1924
+ }
1925
+ else if (percent > 0) {
1926
+ const stored = [];
1927
+ for (const map of [CACHE_READTEXT, CACHE_READBUFFER, CACHE_READCJS]) {
1928
+ for (const [key, value] of map) {
1929
+ stored.push([map, key, value[0]]);
1930
+ }
1931
+ }
1932
+ stored.sort((a, b) => a[2] - b[2]);
1933
+ result = Math.floor(stored.length * percent);
1934
+ for (let i = 0; i < result; ++i) {
1935
+ const [map, key] = stored[i];
1936
+ map.delete(key);
1937
+ }
1938
+ CACHE_TOTAL = stored.length - result;
1939
+ }
1940
+ }
1941
+ return Promise.resolve(result);
1942
+ }
1943
+ static canWrite(name) {
1944
+ switch (name) {
1945
+ case 'temp':
1946
+ return VALUES["temp.write" /* KEY_NAME.TEMP_WRITE */];
1947
+ case 'home':
1948
+ return VALUES["permission.home_write" /* KEY_NAME.PERMISSION_HOMEWRITE */];
1949
+ default:
1950
+ return false;
1951
+ }
1952
+ }
1953
+ static loadSettings(settings, password) {
1954
+ var _h;
1955
+ const current = VALUES["process.password" /* KEY_NAME.PROCESS_PASSWORD */];
1956
+ if (current) {
1957
+ const proc = settings.process || {};
1958
+ if (!password && !(password = proc.password)) {
1959
+ return false;
1960
+ }
1961
+ const algorithm = VALUES["process.cipher.algorithm" /* KEY_NAME.PROCESS_CIPHER_ALGORITHM */];
1962
+ if (algorithm) {
1963
+ password = encryptMessage(password, proc.cipher, algorithm);
1964
+ }
1965
+ if (password !== current) {
1966
+ return false;
1967
+ }
1968
+ }
1969
+ else if ((0, types_1.isString)(password)) {
1970
+ VALUES["process.password" /* KEY_NAME.PROCESS_PASSWORD */] = encryptMessage(password, settings.process?.cipher);
1971
+ }
1972
+ const { temp, node, permission, memory, error, logger } = settings;
1973
+ if ((0, types_1.isPlainObject)(node)) {
1974
+ const { process: proc, require: req } = node;
1975
+ if ((0, types_1.isPlainObject)(proc)) {
1976
+ const { cpu_usage, memory_usage, inline } = proc;
1977
+ if (typeof cpu_usage === 'boolean') {
1978
+ VALUES["node.process.cpu_usage" /* KEY_NAME.NODE_PROCESS_CPUUSAGE */] = cpu_usage;
1979
+ }
1980
+ if (typeof memory_usage === 'boolean') {
1981
+ VALUES["node.process.memory_usage" /* KEY_NAME.NODE_PROCESS_MEMORYUSAGE */] = memory_usage;
1982
+ }
1983
+ if (typeof inline === 'boolean') {
1984
+ VALUES["node.process.inline" /* KEY_NAME.NODE_PROCESS_INLINE */] = inline;
1985
+ }
1986
+ }
1987
+ if ((0, types_1.isPlainObject)(req)) {
1988
+ const { ext, npm, inline } = req;
1989
+ if (!ext) {
1990
+ VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */] = '';
1991
+ }
1992
+ else if (typeof ext === 'string') {
1993
+ VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */] = ext.trim().toLowerCase();
1994
+ }
1995
+ else if (Array.isArray(ext)) {
1996
+ const items = ext.map(value => (0, types_1.isString)(value) ? value.trim().toLowerCase() : '').filter(value => value);
1997
+ VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */] = items.length ? items : '';
1998
+ }
1999
+ else {
2000
+ VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */] = 'cjs';
2001
+ }
2002
+ if (typeof npm === 'boolean') {
2003
+ VALUES["node.require.npm" /* KEY_NAME.NODE_REQUIRE_NPM */] = npm;
2004
+ }
2005
+ if (typeof inline === 'boolean') {
2006
+ VALUES["node.require.inline" /* KEY_NAME.NODE_REQUIRE_INLINE */] = inline;
2007
+ }
2008
+ }
2009
+ }
2010
+ if ((0, types_1.isPlainObject)(settings.process)) {
2011
+ const { env, cipher, password: pwd } = settings.process;
2012
+ if (env && typeof env.apply === 'boolean') {
2013
+ VALUES["process.env.apply" /* KEY_NAME.PROCESS_ENV_APPLY */] = env.apply;
2014
+ }
2015
+ if ((0, types_1.isString)(pwd)) {
2016
+ VALUES[_h = "process.password" /* KEY_NAME.PROCESS_PASSWORD */] || (VALUES[_h] = encryptMessage(pwd, cipher));
2017
+ }
2018
+ }
2019
+ if (memory && (0, types_1.isPlainObject)(memory.settings)) {
2020
+ const users = memory.settings.users;
2021
+ if (typeof users === 'boolean' || Array.isArray(users)) {
2022
+ VALUES["memory.settings.users" /* KEY_NAME.MEMORY_SETTINGS_USERS */] = users;
2023
+ }
2024
+ }
2025
+ if ((0, types_1.isPlainObject)(logger)) {
2026
+ const { enabled, level, production, broadcast, stack_trace } = logger;
2027
+ if (typeof enabled === 'boolean') {
2028
+ SETTINGS.enabled = enabled;
2029
+ }
2030
+ if (level !== undefined) {
2031
+ const value = (0, types_1.isString)(level) ? types_1.STATUS_TYPE[level.trim().toUpperCase()] : level;
2032
+ if (value >= -1 && value <= types_1.STATUS_TYPE.TRACE) {
2033
+ VALUES["logger.level" /* KEY_NAME.LOGGER_LEVEL */] = value;
2034
+ }
2035
+ }
2036
+ if (Array.isArray(production)) {
2037
+ SETTINGS.production = production.slice(0);
2038
+ }
2039
+ for (const attr in logger) {
2040
+ switch (attr) {
2041
+ case 'format': {
2042
+ const format = logger.format;
2043
+ if ((0, types_1.isPlainObject)(format)) {
2044
+ for (const section in format) {
2045
+ const stored = SETTINGS.format[section];
2046
+ const target = format[section];
2047
+ if (stored && (0, types_1.isPlainObject)(target)) {
2048
+ for (let name in target) {
2049
+ const value = target[name];
2050
+ switch (name) {
2051
+ case 'bg_color':
2052
+ name = 'bgColor';
2053
+ break;
2054
+ case 'bg_alt_color':
2055
+ name = 'bgAltColor';
2056
+ break;
2057
+ }
2058
+ switch (name) {
2059
+ case 'width': {
2060
+ const width = parseInt(value);
2061
+ if (width > 0) {
2062
+ stored[name] = width;
2063
+ }
2064
+ break;
2065
+ }
2066
+ case 'bold':
2067
+ if (typeof value === 'boolean') {
2068
+ stored[name] = value;
2069
+ }
2070
+ break;
2071
+ case 'color':
2072
+ case 'bgColor':
2073
+ case 'bgAltColor':
2074
+ case 'justify':
2075
+ case 'unit':
2076
+ if (typeof value === 'string') {
2077
+ stored[name] = value;
2078
+ }
2079
+ break;
2080
+ }
2081
+ }
2082
+ }
2083
+ }
2084
+ }
2085
+ break;
2086
+ }
2087
+ case 'meter': {
2088
+ const meter = logger.meter;
2089
+ if ((0, types_1.isPlainObject)(meter)) {
2090
+ for (const name in meter) {
2091
+ const increment = +meter[name];
2092
+ if (increment > 0) {
2093
+ SETTINGS.meter[name] = increment;
2094
+ }
2095
+ }
2096
+ }
2097
+ break;
2098
+ }
2099
+ case 'status': {
2100
+ const status = logger.status;
2101
+ const target = SETTINGS.status;
2102
+ if (typeof status === 'boolean') {
2103
+ for (const name in target) {
2104
+ target[name] = status;
2105
+ }
2106
+ }
2107
+ else if ((0, types_1.isPlainObject)(status)) {
2108
+ for (const name in status) {
2109
+ if (name in target) {
2110
+ target[name] = !!status[name];
2111
+ }
2112
+ }
2113
+ }
2114
+ break;
2115
+ }
2116
+ case 'session_id': {
2117
+ let session_id = logger.session_id;
2118
+ if (session_id !== undefined) {
2119
+ if (!session_id) {
2120
+ SETTINGS.session_id = 0;
2121
+ }
2122
+ else if (session_id === true) {
2123
+ SETTINGS.session_id = 3;
2124
+ }
2125
+ else if ((session_id = +session_id) > 0) {
2126
+ SETTINGS.session_id = session_id;
2127
+ }
2128
+ }
2129
+ break;
2130
+ }
2131
+ case 'process': {
2132
+ const process = logger.process;
2133
+ if (process) {
2134
+ if (!(0, types_1.isObject)(SETTINGS.process)) {
2135
+ SETTINGS.process = { cpu: true, cpu_bar: true, cpu_single_core: true, mem: true, mem_format: '%' };
2136
+ }
2137
+ if ((0, types_1.isObject)(process)) {
2138
+ Object.assign(SETTINGS.process, process);
2139
+ }
2140
+ else {
2141
+ Object.assign(SETTINGS.process, { cpu: true, mem: true });
2142
+ }
2143
+ }
2144
+ else if (process !== undefined) {
2145
+ SETTINGS.process = false;
2146
+ }
2147
+ break;
2148
+ }
2149
+ default:
2150
+ if (attr in SETTINGS) {
2151
+ SETTINGS[attr] = logger[attr];
2152
+ }
2153
+ break;
2154
+ }
2155
+ }
2156
+ if (broadcast?.out) {
2157
+ VALUES["broadcast.out" /* KEY_NAME.BROADCAST_OUT */] = this.parseFunction(broadcast.out, { external: true, absolute: true });
2158
+ }
2159
+ if (stack_trace && stack_trace !== true && +stack_trace > 0) {
2160
+ Error.stackTraceLimit = +stack_trace;
2161
+ }
2162
+ }
2163
+ if (error) {
2164
+ if (error.out) {
2165
+ VALUES["error.out" /* KEY_NAME.ERROR_OUT */] = this.parseFunction(error.out, { external: true, absolute: true });
2166
+ }
2167
+ if (typeof error.fatal === 'boolean') {
2168
+ VALUES["error.fatal" /* KEY_NAME.ERROR_FATAL */] = error.fatal;
2169
+ }
2170
+ }
2171
+ if (permission && Array.isArray(permission.process_exec)) {
2172
+ VALUES["permission.process_exec" /* KEY_NAME.PERMISSION_PROCESS_EXEC */] = permission.process_exec.filter(item => typeof item === 'string' || (0, types_1.isObject)(item) && typeof item.command === 'string').map(exec => {
2173
+ if (typeof exec === 'string') {
2174
+ return exec.trim();
2175
+ }
2176
+ if (typeof exec.warn === 'string') {
2177
+ exec.warn = [exec.warn];
2178
+ }
2179
+ exec.command = exec.command.trim();
2180
+ return exec;
2181
+ });
2182
+ }
2183
+ {
2184
+ let dir = settings.temp_dir, write;
2185
+ if ((0, types_1.isPlainObject)(temp)) {
2186
+ dir || (dir = temp.dir);
2187
+ write = temp.write;
2188
+ }
2189
+ let modified;
2190
+ if ((0, types_1.isString)(dir) && path.isAbsolute(dir = path.normalize(dir).replace(/[\\/]$/, ''))) {
2191
+ if (withinDir(dir, PROCESS_CWD)) {
2192
+ dir = dir.substring(ensureDir(PROCESS_CWD).length);
2193
+ }
2194
+ else {
2195
+ this.formatMessage(1 /* LOG_VALUE.SYSTEM */, 'WARN', 'Temp directory can only be relative', dir, { ...this.LOG_STYLE_WARN, newline: true });
2196
+ dir = undefined;
2197
+ }
2198
+ }
2199
+ if (!(0, types_1.isString)(dir)) {
2200
+ dir = VALUES["temp.dir" /* KEY_NAME.TEMP_DIR */];
2201
+ }
2202
+ if (typeof write === 'boolean') {
2203
+ modified = VALUES["temp.write" /* KEY_NAME.TEMP_WRITE */] !== write;
2204
+ VALUES["temp.write" /* KEY_NAME.TEMP_WRITE */] = write;
2205
+ }
2206
+ do {
2207
+ const [output, index] = tryIncrementDir(path.join(PROCESS_CWD, dir), 5);
2208
+ if ((0, types_1.isString)(output)) {
2209
+ if (index > 0) {
2210
+ dir = trimDir(dir) + '_' + index;
2211
+ }
2212
+ if (dir !== VALUES["temp.dir" /* KEY_NAME.TEMP_DIR */]) {
2213
+ VALUES["temp.dir" /* KEY_NAME.TEMP_DIR */] = dir;
2214
+ modified = true;
2215
+ }
2216
+ (0, types_1.setTempDir)(TEMP_DIR = output);
2217
+ break;
2218
+ }
2219
+ if (output instanceof Error) {
2220
+ this.writeFail(["Unable to create temp directory" /* ERR_MESSAGE.TEMP_DIRECTORY */, dir], output, 32 /* LOG_VALUE.FILE */);
2221
+ }
2222
+ } while ((dir !== "tmp" /* INTERNAL.TEMP_DIR */) && (dir = "tmp" /* INTERNAL.TEMP_DIR */));
2223
+ if (modified) {
2224
+ this.formatMessage(1 /* LOG_VALUE.SYSTEM */, 'TEMP', ["Directory was modified" /* VAL_MESSAGE.MODIFIED_DIRECTORY */, dir], TEMP_DIR + (VALUES["temp.write" /* KEY_NAME.TEMP_WRITE */] ? ' - writeable' : ''), { ...this.LOG_STYLE_NOTICE, newline: true });
2225
+ }
2226
+ settings.temp_dir = dir;
2227
+ if ((0, types_1.isPlainObject)(temp)) {
2228
+ temp.dir = dir;
2229
+ }
2230
+ }
2231
+ return true;
2232
+ }
2233
+ supported(major, minor, patch, lts) {
2234
+ return Module.supported(major, minor, patch, lts);
2235
+ }
2236
+ supports(name, value) {
2237
+ if (typeof value === 'boolean') {
2238
+ this[kSupports][name] = { value, modified: true };
2239
+ return value;
2240
+ }
2241
+ const host = this.host;
2242
+ const item = this[kSupports][name];
2243
+ return host && !item?.modified ? host.supports(name) : item?.value === true;
2244
+ }
2245
+ getTempDir(pathname, filename, createDir) {
2246
+ let increment = 0, moduleDir, uuidDir;
2247
+ if ((0, types_1.isPlainObject)(pathname)) {
2248
+ ({ pathname, filename, moduleDir, uuidDir, createDir, increment = 0 } = pathname);
2249
+ }
2250
+ else {
2251
+ if (typeof filename === 'boolean') {
2252
+ createDir = filename;
2253
+ filename = undefined;
2254
+ }
2255
+ if (typeof pathname === 'boolean') {
2256
+ uuidDir = pathname;
2257
+ pathname = undefined;
2258
+ }
2259
+ }
2260
+ const leading = [PROCESS_CWD, this.tempDir];
2261
+ if (moduleDir) {
2262
+ leading.push(this.moduleName);
2263
+ }
2264
+ let result;
2265
+ if ((0, types_1.isString)(pathname)) {
2266
+ leading.push(pathname);
2267
+ createDir ?? (createDir = true);
2268
+ }
2269
+ if (uuidDir) {
2270
+ leading.push((0, types_1.generateUUID)());
2271
+ createDir ?? (createDir = true);
2272
+ }
2273
+ if ((createDir || increment > 0) && !Module.isDir(result = path.join(...leading))) {
2274
+ const [output] = tryIncrementDir(result, increment);
2275
+ if (!(0, types_1.isString)(output)) {
2276
+ if (output instanceof Error) {
2277
+ this.writeFail(["Unable to create temp directory" /* ERR_MESSAGE.TEMP_DIRECTORY */, result], output, 32 /* LOG_VALUE.FILE */);
2278
+ }
2279
+ return '';
2280
+ }
2281
+ result = output;
2282
+ }
2283
+ if (filename) {
2284
+ const trailing = (filename[0] === '.' ? (0, types_1.generateUUID)() : '') + filename;
2285
+ if (result) {
2286
+ return path.join(result, trailing);
2287
+ }
2288
+ leading.push(trailing);
2289
+ }
2290
+ return result || path.join(...leading);
2291
+ }
2292
+ canRead(uri, options) {
2293
+ let permission = this.permission, ownPermissionOnly = false;
2294
+ if (options) {
2295
+ if (options.hostPermissionOnly) {
2296
+ let host;
2297
+ if (!(permission = (host = this.host) && host.permission)) {
2298
+ return true;
2299
+ }
2300
+ }
2301
+ else if (options.ownPermissionOnly) {
2302
+ if (!(permission = this[kPermission])) {
2303
+ return true;
2304
+ }
2305
+ ownPermissionOnly = true;
2306
+ }
2307
+ }
2308
+ if (permission && (Module.isFile(uri, 'unc') ? permission.hasUNCRead(path.normalize(uri)) || ownPermissionOnly && !permission.getUNCRead() : path.isAbsolute(uri = path.resolve(uri)) && (permission.hasDiskRead(uri) || ownPermissionOnly && !permission.getDiskRead()))) {
2309
+ return true;
2310
+ }
2311
+ return VALUES["permission.home_read" /* KEY_NAME.PERMISSION_HOMEREAD */] && withinDir(uri, OS_HOMEDIR);
2312
+ }
2313
+ canWrite(uri, options) {
2314
+ let permission = this.permission, ownPermissionOnly = false;
2315
+ if (options) {
2316
+ if (options.hostPermissionOnly) {
2317
+ let host;
2318
+ if (!(permission = (host = this.host) && host.permission)) {
2319
+ return true;
2320
+ }
2321
+ }
2322
+ else if (options.ownPermissionOnly) {
2323
+ if (!(permission = this[kPermission])) {
2324
+ return true;
2325
+ }
2326
+ ownPermissionOnly = true;
2327
+ }
2328
+ }
2329
+ if (permission && (Module.isFile(uri, 'unc') ? permission.hasUNCWrite(path.normalize(uri)) || ownPermissionOnly && !permission.getUNCWrite() : path.isAbsolute(uri = path.resolve(uri)) && (permission.hasDiskWrite(uri) || ownPermissionOnly && !permission.getDiskWrite()))) {
2330
+ return true;
2331
+ }
2332
+ return VALUES["temp.write" /* KEY_NAME.TEMP_WRITE */] && withinDir(uri, TEMP_DIR) || VALUES["permission.home_write" /* KEY_NAME.PERMISSION_HOMEWRITE */] && withinDir(uri, OS_HOMEDIR);
2333
+ }
2334
+ readFile(src, options = {}, callback) {
2335
+ let promises, outSrc;
2336
+ [options, promises, callback] = parseFileArgs(options, callback);
2337
+ if (outSrc = hasFileSystem.call(this, 0 /* FILE_SYSTEM.READ */, src, options)) {
2338
+ const { requireExt, cache } = options;
2339
+ const encoding = options.encoding && (0, types_1.getEncoding)(options.encoding);
2340
+ const setCache = (data, cjs) => {
2341
+ if (data) {
2342
+ if (cache) {
2343
+ addCacheItem(cjs ? CACHE_READCJS : encoding ? CACHE_READTEXT : CACHE_READBUFFER, outSrc, data);
2344
+ }
2345
+ this.emit('file:read', outSrc, data, options);
2346
+ }
2347
+ };
2348
+ let result;
2349
+ if (requireExt && VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */] && hasString(requireExt === true ? VALUES["node.require.ext" /* KEY_NAME.NODE_REQUIRE_EXT */] : requireExt, getExtension(src))) {
2350
+ if (cache) {
2351
+ result = getCacheItem(CACHE_READCJS, outSrc);
2352
+ }
2353
+ if (!result) {
2354
+ try {
2355
+ result = require(outSrc);
2356
+ setCache(result, true);
2357
+ checkFunction(result);
2358
+ }
2359
+ catch {
2360
+ }
2361
+ }
2362
+ }
2363
+ if (cache) {
2364
+ result || (result = (encoding ? getCacheItem(CACHE_READTEXT, outSrc) : getCacheItem(CACHE_READBUFFER, outSrc)));
2365
+ }
2366
+ if (promises) {
2367
+ if (result) {
2368
+ return Promise.resolve(result);
2369
+ }
2370
+ return fs.promises.readFile(outSrc, encoding).then(data => {
2371
+ setCache(data);
2372
+ return data;
2373
+ });
2374
+ }
2375
+ if (isFunction(callback)) {
2376
+ if (result) {
2377
+ callback(null, result);
2378
+ }
2379
+ else {
2380
+ fs.readFile(outSrc, encoding, (err, data) => {
2381
+ if (!err) {
2382
+ setCache(data);
2383
+ }
2384
+ callback(err, data);
2385
+ });
2386
+ }
2387
+ return;
2388
+ }
2389
+ try {
2390
+ if (!result) {
2391
+ setCache(result = fs.readFileSync(outSrc, encoding));
2392
+ }
2393
+ return result;
2394
+ }
2395
+ catch (err) {
2396
+ this.writeFail(["Unable to read file" /* ERR_MESSAGE.READ_FILE */, path.basename(src)], err, 32 /* LOG_VALUE.FILE */);
2397
+ }
2398
+ }
2399
+ else if (promises) {
2400
+ return Promise.reject(errorPermission(src));
2401
+ }
2402
+ else if (isFunction(callback)) {
2403
+ callback(errorPermission(src));
2404
+ }
2405
+ }
2406
+ writeFile(src, data, options = {}, callback) {
2407
+ let promises, outSrc;
2408
+ [options, promises, callback] = parseFileArgs(options, callback);
2409
+ if (outSrc = hasFileSystem.call(this, 1 /* FILE_SYSTEM.WRITE */, src, options, true, options.overwrite)) {
2410
+ if (promises) {
2411
+ return fs.promises.writeFile(outSrc, data, options.encoding).then(() => {
2412
+ this.emit('file:write', outSrc, options);
2413
+ return true;
2414
+ });
2415
+ }
2416
+ if (isFunction(callback)) {
2417
+ fs.writeFile(outSrc, data, { encoding: options.encoding }, err => {
2418
+ if (!err) {
2419
+ this.emit('file:write', outSrc, options);
2420
+ }
2421
+ callback(err);
2422
+ });
2423
+ return;
2424
+ }
2425
+ try {
2426
+ fs.writeFileSync(outSrc, data, options.encoding);
2427
+ this.emit('file:write', outSrc, options);
2428
+ return true;
2429
+ }
2430
+ catch (err) {
2431
+ this.writeFail(["Unable to write file" /* ERR_MESSAGE.WRITE_FILE */, path.basename(src)], err, 32 /* LOG_VALUE.FILE */);
2432
+ }
2433
+ }
2434
+ else if (promises) {
2435
+ return Promise.reject(errorPermission(src));
2436
+ }
2437
+ else if (isFunction(callback)) {
2438
+ callback(errorPermission(src));
2439
+ return;
2440
+ }
2441
+ return false;
2442
+ }
2443
+ deleteFile(src, options = {}, callback) {
2444
+ let promises, outSrc;
2445
+ [options, promises, callback] = parseFileArgs(options, callback);
2446
+ if (outSrc = hasFileSystem.call(this, 1 /* FILE_SYSTEM.WRITE */, src, options)) {
2447
+ if (promises) {
2448
+ return fs.promises.unlink(outSrc).then(() => {
2449
+ this.emit('file:delete', outSrc, options);
2450
+ return true;
2451
+ });
2452
+ }
2453
+ if (isFunction(callback)) {
2454
+ fs.unlink(outSrc, err => {
2455
+ if (!err) {
2456
+ this.emit('file:delete', outSrc, options);
2457
+ }
2458
+ callback(err);
2459
+ });
2460
+ return;
2461
+ }
2462
+ try {
2463
+ fs.unlinkSync(outSrc);
2464
+ }
2465
+ catch (err) {
2466
+ if (!Module.isErrorCode(err, 'ENOENT')) {
2467
+ this.writeFail(["Unable to delete file" /* ERR_MESSAGE.DELETE_FILE */, path.basename(src)], err, 32 /* LOG_VALUE.FILE */);
2468
+ return false;
2469
+ }
2470
+ }
2471
+ this.emit('file:delete', outSrc, options);
2472
+ return true;
2473
+ }
2474
+ else if (promises) {
2475
+ return Promise.reject(errorPermission(src));
2476
+ }
2477
+ else if (isFunction(callback)) {
2478
+ callback(errorPermission(src));
2479
+ return;
2480
+ }
2481
+ return false;
2482
+ }
2483
+ copyFile(src, dest, options = {}, callback) {
2484
+ let promises, outSrc, outDest;
2485
+ [options, promises, callback] = parseFileArgs(options, callback);
2486
+ if ((outSrc = hasFileSystem.call(this, 0 /* FILE_SYSTEM.READ */, src, options)) && (outDest = hasFileSystem.call(this, 1 /* FILE_SYSTEM.WRITE */, dest, options, true, options.overwrite))) {
2487
+ const destDir = path.dirname(outDest);
2488
+ if (!Module.isDir(destDir) && (options.createDir === false || !Module.createDir(destDir))) {
2489
+ if (promises) {
2490
+ return Promise.reject(errorPermission(destDir));
2491
+ }
2492
+ if (isFunction(callback)) {
2493
+ callback(errorPermission(destDir));
2494
+ return;
2495
+ }
2496
+ if (options.throwsPermission) {
2497
+ throw errorPermission(destDir);
2498
+ }
2499
+ }
2500
+ else {
2501
+ options.outSrc = outSrc;
2502
+ if (promises) {
2503
+ return fs.promises.copyFile(outSrc, outDest).then(() => {
2504
+ this.emit('file:copy', outDest, options);
2505
+ return true;
2506
+ });
2507
+ }
2508
+ if (isFunction(callback)) {
2509
+ fs.copyFile(outSrc, outDest, err => {
2510
+ if (!err) {
2511
+ this.emit('file:copy', outDest, options);
2512
+ }
2513
+ callback(err);
2514
+ });
2515
+ return;
2516
+ }
2517
+ try {
2518
+ fs.copyFileSync(outSrc, outDest);
2519
+ this.emit('file:copy', outDest, options);
2520
+ return true;
2521
+ }
2522
+ catch (err) {
2523
+ this.writeFail(["Unable to copy file" /* ERR_MESSAGE.COPY_FILE */, dest], err, 32 /* LOG_VALUE.FILE */);
2524
+ }
2525
+ }
2526
+ }
2527
+ else if (promises) {
2528
+ return Promise.reject(errorPermission(src));
2529
+ }
2530
+ else if (isFunction(callback)) {
2531
+ callback(errorPermission(!outSrc ? src : dest));
2532
+ return;
2533
+ }
2534
+ return false;
2535
+ }
2536
+ moveFile(src, dest, options = {}, callback) {
2537
+ let promises, outSrc, outDest;
2538
+ [options, promises, callback] = parseFileArgs(options, callback);
2539
+ if ((outSrc = hasFileSystem.call(this, 1 /* FILE_SYSTEM.WRITE */, src, options)) && (outDest = hasFileSystem.call(this, 1 /* FILE_SYSTEM.WRITE */, dest, options, true, options.overwrite))) {
2540
+ const destDir = path.dirname(outDest);
2541
+ if (!Module.isDir(destDir) && (options.createDir === false || !Module.createDir(destDir))) {
2542
+ if (promises) {
2543
+ return Promise.reject(errorPermission(destDir));
2544
+ }
2545
+ if (isFunction(callback)) {
2546
+ callback(errorPermission(destDir));
2547
+ return;
2548
+ }
2549
+ if (options.throwsPermission) {
2550
+ throw errorPermission(destDir);
2551
+ }
2552
+ }
2553
+ else {
2554
+ options.outSrc = outSrc;
2555
+ const checkError = (err) => {
2556
+ if (Module.isErrorCode(err, 'EXDEV')) {
2557
+ try {
2558
+ fs.copyFileSync(outSrc, outDest);
2559
+ fs.unlinkSync(outSrc);
2560
+ return true;
2561
+ }
2562
+ catch {
2563
+ fs.unlink(outDest, () => { });
2564
+ }
2565
+ }
2566
+ return false;
2567
+ };
2568
+ if (promises) {
2569
+ return new Promise((resolve, reject) => {
2570
+ fs.rename(outSrc, outDest, err => {
2571
+ if (err && checkError(err)) {
2572
+ err = null;
2573
+ }
2574
+ if (!err) {
2575
+ this.emit('file:move', outDest, options);
2576
+ resolve(true);
2577
+ }
2578
+ else {
2579
+ reject(err);
2580
+ }
2581
+ });
2582
+ });
2583
+ }
2584
+ if (isFunction(callback)) {
2585
+ fs.rename(outSrc, outDest, err => {
2586
+ if (err && checkError(err)) {
2587
+ err = null;
2588
+ }
2589
+ if (!err) {
2590
+ this.emit('file:move', outDest, options);
2591
+ }
2592
+ callback(err);
2593
+ });
2594
+ return;
2595
+ }
2596
+ try {
2597
+ fs.renameSync(outSrc, outDest);
2598
+ this.emit('file:move', outDest, options);
2599
+ return true;
2600
+ }
2601
+ catch (err) {
2602
+ if (checkError(err)) {
2603
+ this.emit('file:move', outDest, options);
2604
+ return true;
2605
+ }
2606
+ this.writeFail(["Unable to move file" /* ERR_MESSAGE.MOVE_FILE */, dest], err, 32 /* LOG_VALUE.FILE */);
2607
+ }
2608
+ }
2609
+ }
2610
+ else {
2611
+ if (outSrc) {
2612
+ src = dest;
2613
+ }
2614
+ if (promises) {
2615
+ return Promise.reject(errorPermission(src));
2616
+ }
2617
+ if (isFunction(callback)) {
2618
+ callback(errorPermission(src));
2619
+ return;
2620
+ }
2621
+ }
2622
+ return false;
2623
+ }
2624
+ createDir(src, options = {}, callback) {
2625
+ let promises, outSrc;
2626
+ [options, promises, callback] = parseFileArgs(options, callback);
2627
+ if (outSrc = hasFileSystem.call(this, 1 /* FILE_SYSTEM.WRITE */, src, options, true)) {
2628
+ if (Module.isDir(outSrc)) {
2629
+ if (promises) {
2630
+ return Promise.resolve(true);
2631
+ }
2632
+ if (isFunction(callback)) {
2633
+ callback(null);
2634
+ return;
2635
+ }
2636
+ return true;
2637
+ }
2638
+ try {
2639
+ if (fs.existsSync(outSrc)) {
2640
+ if (promises) {
2641
+ return Promise.reject(errorDirectory(outSrc));
2642
+ }
2643
+ if (isFunction(callback)) {
2644
+ callback(errorDirectory(outSrc));
2645
+ return;
2646
+ }
2647
+ if (options.throwsPermission) {
2648
+ throw errorPermission(outSrc);
2649
+ }
2650
+ }
2651
+ else {
2652
+ if (promises || isFunction(callback)) {
2653
+ const result = new Promise(resolve => {
2654
+ resolve(tryCreateDir(outSrc));
2655
+ }).then(success => {
2656
+ this.emit('dir:create', outSrc, options);
2657
+ if (callback) {
2658
+ callback(null);
2659
+ }
2660
+ return success;
2661
+ });
2662
+ if (callback) {
2663
+ result.catch(err => callback(err));
2664
+ }
2665
+ return promises ? result : undefined;
2666
+ }
2667
+ if (tryCreateDir(outSrc)) {
2668
+ this.emit('dir:create', outSrc, options);
2669
+ return true;
2670
+ }
2671
+ }
2672
+ }
2673
+ catch (err) {
2674
+ this.writeFail(["Unable to create directory" /* ERR_MESSAGE.CREATE_DIRECTORY */, src], err, 32 /* LOG_VALUE.FILE */);
2675
+ }
2676
+ }
2677
+ else if (promises) {
2678
+ return Promise.reject(errorPermission(src));
2679
+ }
2680
+ else if (isFunction(callback)) {
2681
+ callback(errorPermission(src));
2682
+ return;
2683
+ }
2684
+ return false;
2685
+ }
2686
+ removeDir(src, options = {}, callback) {
2687
+ let promises, outSrc;
2688
+ [options, promises, callback] = parseFileArgs(options, callback);
2689
+ if (outSrc = hasFileSystem.call(this, 1 /* FILE_SYSTEM.WRITE */, src, options, true)) {
2690
+ try {
2691
+ if (Module.isDir(outSrc)) {
2692
+ const { emptyDir = false, recursive = true } = options;
2693
+ const errorResponse = (failed) => new Error("Unsupported access" /* ERR_MESSAGE.UNSUPPORTED_ACCESS */ + ':' + (failed.length > 1 ? failed.map(value => `\n- ${value}`) : ' ' + failed[0]));
2694
+ if (promises || isFunction(callback)) {
2695
+ const result = new Promise((resolve, reject) => {
2696
+ const failed = tryRemoveDir(outSrc, emptyDir, !!recursive);
2697
+ if (failed.length === 0) {
2698
+ resolve(true);
2699
+ }
2700
+ else {
2701
+ reject(errorResponse(failed));
2702
+ }
2703
+ })
2704
+ .then(success => {
2705
+ this.emit('dir:remove', outSrc, options);
2706
+ if (callback) {
2707
+ callback(null);
2708
+ }
2709
+ return success;
2710
+ });
2711
+ if (callback) {
2712
+ result.catch(err => callback(err));
2713
+ }
2714
+ return promises ? result : undefined;
2715
+ }
2716
+ const failed = tryRemoveDir(outSrc, emptyDir, !!recursive);
2717
+ if (failed.length === 0) {
2718
+ this.emit('dir:remove', outSrc, options);
2719
+ return true;
2720
+ }
2721
+ throw errorResponse(failed);
2722
+ }
2723
+ else if (fs.existsSync(outSrc)) {
2724
+ if (promises) {
2725
+ return Promise.reject(errorDirectory(outSrc));
2726
+ }
2727
+ if (isFunction(callback)) {
2728
+ callback(errorDirectory(outSrc));
2729
+ return;
2730
+ }
2731
+ }
2732
+ else {
2733
+ if (promises) {
2734
+ return Promise.resolve(true);
2735
+ }
2736
+ if (isFunction(callback)) {
2737
+ callback(null);
2738
+ return;
2739
+ }
2740
+ return true;
2741
+ }
2742
+ }
2743
+ catch (err) {
2744
+ this.writeFail(["Unable to remove directory" /* ERR_MESSAGE.REMOVE_DIRECTORY */, src], err, 32 /* LOG_VALUE.FILE */);
2745
+ }
2746
+ }
2747
+ else if (promises) {
2748
+ return Promise.reject(errorPermission(src));
2749
+ }
2750
+ else if (isFunction(callback)) {
2751
+ callback(errorPermission(src));
2752
+ return;
2753
+ }
2754
+ return false;
2755
+ }
2756
+ allSettled(tasks, rejected, options) {
2757
+ rejected || (rejected = "Unknown" /* ERR_MESSAGE.UNKNOWN */);
2758
+ return Promise.allSettled(tasks).then(result => {
2759
+ const items = [];
2760
+ for (const item of result) {
2761
+ if (item.status === 'fulfilled') {
2762
+ items.push(item);
2763
+ }
2764
+ else if (item.reason) {
2765
+ this.writeFail(rejected, item.reason, options);
2766
+ }
2767
+ }
2768
+ return items;
2769
+ })
2770
+ .catch(err => {
2771
+ this.writeFail(rejected, err, options);
2772
+ return [];
2773
+ });
2774
+ }
2775
+ writeFail(value, message, options) {
2776
+ let type;
2777
+ if ((0, types_1.isPlainObject)(options)) {
2778
+ ({ type } = options);
2779
+ }
2780
+ else {
2781
+ if (typeof options === 'number') {
2782
+ type = options;
2783
+ }
2784
+ options = {};
2785
+ }
2786
+ this.formatFail(type || types_1.LOG_TYPE.SYSTEM, "FAIL!" /* ERR_MESSAGE.FAIL */, value, message, options);
2787
+ }
2788
+ writeTimeProcess(title, value, startTime, options = {}) {
2789
+ const { type = 0, statusType = 0 } = options;
2790
+ const http = type & 1024 /* LOG_VALUE.HTTP */;
2791
+ const meter = SETTINGS.meter;
2792
+ const failed = isFailed(options);
2793
+ const increment = options.meterIncrement || (http ? meter.http
2794
+ : type & 2048 /* LOG_VALUE.IMAGE */ ? meter.image
2795
+ : type & 8 /* LOG_VALUE.COMPRESS */ ? meter.compress
2796
+ : meter.process) || 250;
2797
+ const duration = getTimeOffset(startTime);
2798
+ let meterTime = duration, delayTime = options.delayTime;
2799
+ if (delayTime !== undefined) {
2800
+ if (Array.isArray(delayTime)) {
2801
+ delayTime = Math.max((0, types_1.convertTime)(delayTime), 0);
2802
+ if (delayTime < meterTime) {
2803
+ meterTime -= delayTime;
2804
+ }
2805
+ else {
2806
+ delayTime = 0;
2807
+ }
2808
+ }
2809
+ if (delayTime >= 0) {
2810
+ options.messageUnitIndent = [Math.round(delayTime / increment), '-'];
2811
+ }
2812
+ }
2813
+ if (failed && !http) {
2814
+ value = "Failed" /* ERR_MESSAGE.FAILED */ + ' -> ' + value;
2815
+ }
2816
+ const args = [
2817
+ (256 /* LOG_VALUE.TIME_PROCESS */ | type),
2818
+ title,
2819
+ [value, formatTimeHint(duration)],
2820
+ (failed ? 'X' : '>').repeat(Math.min(Math.ceil(meterTime / increment), SETTINGS.format.meter.width)),
2821
+ options
2822
+ ];
2823
+ applyLogId.call(this, options);
2824
+ if (statusType > 0) {
2825
+ this.addLog(statusType, value, typeof startTime === 'number' ? startTime : undefined, duration);
2826
+ }
2827
+ if (options.queue && !this._logFlushed) {
2828
+ this._logQueued.push(args);
2829
+ }
2830
+ else {
2831
+ setCpuAndMem.call(this, options);
2832
+ Module.formatMessage(...args);
2833
+ }
2834
+ if (!options.bypassLog) {
2835
+ this.addLog(types_1.STATUS_TYPE.INFO, title + ' -> ' + value, Date.now(), duration);
2836
+ }
2837
+ }
2838
+ writeTimeElapsed(title, value, startTime, options = {}) {
2839
+ const { type = 0, statusType = 0 } = options;
2840
+ let message;
2841
+ if (Array.isArray(value)) {
2842
+ message = value[1];
2843
+ value = value[0];
2844
+ }
2845
+ else if (options.showCpu) {
2846
+ setCpuAndMem.call(this, options);
2847
+ }
2848
+ else {
2849
+ message = value;
2850
+ value = '';
2851
+ }
2852
+ value || (value = isFailed(options) ? "Failed" /* ERR_MESSAGE.FAILED */ : "Success" /* VAL_MESSAGE.SUCCESS */);
2853
+ const duration = getTimeOffset(startTime);
2854
+ const args = [
2855
+ (128 /* LOG_VALUE.TIME_ELAPSED */ | type),
2856
+ title,
2857
+ [value, formatTimeHint(duration)],
2858
+ message,
2859
+ options
2860
+ ];
2861
+ applyLogId.call(this, options);
2862
+ if (statusType > 0) {
2863
+ this.addLog(statusType, value, typeof startTime === 'number' ? startTime : undefined, duration);
2864
+ }
2865
+ if (options.queue && !this._logFlushed) {
2866
+ this._logQueued.push(args);
2867
+ }
2868
+ else {
2869
+ Module.formatMessage(...args);
2870
+ }
2871
+ }
2872
+ formatFail(type, title, value, message, options = {}) {
2873
+ options.type = type;
2874
+ const result = this.checkFail(message, options);
2875
+ if (result) {
2876
+ if (result.type !== undefined) {
2877
+ type = result.type;
2878
+ }
2879
+ if (result.value !== undefined) {
2880
+ value = result.value;
2881
+ }
2882
+ if (result.message !== undefined) {
2883
+ message = result.message;
2884
+ }
2885
+ }
2886
+ else if (result === false) {
2887
+ return;
2888
+ }
2889
+ if (options.passThrough) {
2890
+ message = null;
2891
+ }
2892
+ const args = [(type | 512 /* LOG_VALUE.FAIL */), title, value, message, applyStyle(options, Module.LOG_STYLE_FAIL)];
2893
+ applyLogId.call(this, options);
2894
+ if (options.queue !== false && !options.passThrough && !this._logFlushed) {
2895
+ if (VALUES["error.out" /* KEY_NAME.ERROR_OUT */]) {
2896
+ options.timeStamp = Date.now();
2897
+ }
2898
+ this._logQueued.push(args);
2899
+ }
2900
+ else {
2901
+ Module.formatMessage(...args);
2902
+ }
2903
+ const host = this.host;
2904
+ const target = host || this;
2905
+ let fatal;
2906
+ if (options.exec && (type & 4096 /* LOG_VALUE.EXEC */) && target.willAbort("(exec)" /* ABORT_NAME.EXEC */)) {
2907
+ const exec = { ...options.exec };
2908
+ let output = VALUES["permission.process_exec" /* KEY_NAME.PERMISSION_PROCESS_EXEC */].find(item => exec.command === ((0, types_1.isObject)(item) ? item.command : item));
2909
+ if (output) {
2910
+ if ((0, types_1.isPlainObject)(output)) {
2911
+ output = { ...output };
2912
+ if (Array.isArray(output.warn)) {
2913
+ (exec.warn || (exec.warn = [])).push(...output.warn);
2914
+ }
2915
+ delete output.command;
2916
+ delete output.warn;
2917
+ }
2918
+ else {
2919
+ output = undefined;
2920
+ }
2921
+ if (target.listenerCount('exec') > 0) {
2922
+ target.emit('exec', exec, output);
2923
+ }
2924
+ else {
2925
+ this.emit('exec', exec, output);
2926
+ }
2927
+ }
2928
+ else {
2929
+ this.formatMessage(4096 /* LOG_VALUE.EXEC */, "WARN!" /* ERR_MESSAGE.WARN */, "Exec command not permitted" /* ERR_MESSAGE.EXEC_PERMISSION */, exec.command, { ...Module.LOG_STYLE_WARN });
2930
+ }
2931
+ }
2932
+ if (options.passThrough) {
2933
+ return;
2934
+ }
2935
+ if (options.abortable !== false && (options.fatal !== false || this.isFatal(message))) {
2936
+ if (target.willAbort("(unknown)" /* ABORT_NAME.UNKNOWN */)) {
2937
+ if (host) {
2938
+ host.abort();
2939
+ }
2940
+ else {
2941
+ this.abort();
2942
+ }
2943
+ fatal = true;
2944
+ }
2945
+ else if (host && this.abortable) {
2946
+ if (host.abortable) {
2947
+ host.abort();
2948
+ }
2949
+ this.abort();
2950
+ fatal = true;
2951
+ }
2952
+ else if ((type & 8192 /* LOG_VALUE.PERMISSION */ && (!host || host.willAbort("(permission)" /* ABORT_NAME.PERMISSION */))) ||
2953
+ (type & 1 /* LOG_VALUE.SYSTEM */) && target.willAbort("(system)" /* ABORT_NAME.SYSTEM */) ||
2954
+ (type & 2 /* LOG_VALUE.NODE */) && target.willAbort("(node)" /* ABORT_NAME.NODE */) ||
2955
+ (type & 8 /* LOG_VALUE.COMPRESS */) && target.willAbort("(compress)" /* ABORT_NAME.COMPRESS */) ||
2956
+ (type & 16 /* LOG_VALUE.WATCH */) && target.willAbort("(watch)" /* ABORT_NAME.WATCH */) ||
2957
+ (type & 32 /* LOG_VALUE.FILE */) && target.willAbort("(file)" /* ABORT_NAME.FILE */) ||
2958
+ (type & 64 /* LOG_VALUE.CLOUD */) && target.willAbort("(cloud)" /* ABORT_NAME.CLOUD */) ||
2959
+ (type & 1024 /* LOG_VALUE.HTTP */) && target.willAbort("(http)" /* ABORT_NAME.HTTP */) ||
2960
+ (type & 2048 /* LOG_VALUE.IMAGE */) && target.willAbort("(image)" /* ABORT_NAME.IMAGE */) ||
2961
+ (type & 4096 /* LOG_VALUE.EXEC */) && target.willAbort("(exec)" /* ABORT_NAME.EXEC */) ||
2962
+ (type & 16384 /* LOG_VALUE.TIMEOUT */) && target.willAbort("(timeout)" /* ABORT_NAME.TIMEOUT */) ||
2963
+ (type & 65536 /* LOG_VALUE.DB */) && target.willAbort("(db)" /* ABORT_NAME.DB */)) {
2964
+ if (host) {
2965
+ if (host.abortable) {
2966
+ host.abort();
2967
+ fatal = true;
2968
+ }
2969
+ }
2970
+ else if (this.abortable) {
2971
+ this.abort();
2972
+ fatal = true;
2973
+ }
2974
+ }
2975
+ }
2976
+ if (message) {
2977
+ if (this._logEnabled) {
2978
+ if (fatal) {
2979
+ const timeStamp = Date.now();
2980
+ this.addLog(types_1.STATUS_TYPE.FATAL, message, timeStamp, options.startTime && getTimeOffset(options.startTime, timeStamp));
2981
+ }
2982
+ else {
2983
+ this.addLog(options.statusType || types_1.STATUS_TYPE.ERROR, message);
2984
+ }
2985
+ this.errors.push(message instanceof Error ? getErrorMessage(message) : message);
2986
+ }
2987
+ if (this.listenerCount('error') > 0) {
2988
+ this.emit('error', errorObject(message));
2989
+ }
2990
+ else if (host && host.listenerCount('error') > 0) {
2991
+ host.emit('error', errorObject(message));
2992
+ }
2993
+ }
2994
+ }
2995
+ formatMessage(type, title, value, message, options = {}) {
2996
+ const statusType = options.statusType || 0;
2997
+ const args = [type, title, value, message, options];
2998
+ applyLogId.call(this, options);
2999
+ if (statusType > 0) {
3000
+ this.addLog(statusType, message || (Array.isArray(value) ? value[0] : value));
3001
+ }
3002
+ if (options.queue && !this._logFlushed) {
3003
+ if (VALUES["error.out" /* KEY_NAME.ERROR_OUT */] && (type & 512 /* LOG_VALUE.FAIL */)) {
3004
+ options.timeStamp = Date.now();
3005
+ }
3006
+ this._logQueued.push(args);
3007
+ }
3008
+ else {
3009
+ Module.formatMessage(...args);
3010
+ }
3011
+ }
3012
+ checkPackage(err, name, value, options) {
3013
+ if (typeof value === 'number') {
3014
+ options = value;
3015
+ value = undefined;
3016
+ }
3017
+ else if ((0, types_1.isPlainObject)(value)) {
3018
+ options = value;
3019
+ value = undefined;
3020
+ }
3021
+ if (err instanceof Error && err.code === types_1.ERR_CODE.MODULE_NOT_FOUND && (0, types_1.isString)(name)) {
3022
+ if (typeof options === 'number') {
3023
+ options = undefined;
3024
+ }
3025
+ this.writeFail("Unknown" /* ERR_MESSAGE.UNKNOWN */, err, { ...options, type: types_1.LOG_TYPE.SYSTEM, code: types_1.ERR_CODE.MODULE_NOT_FOUND, exec: { command: 'npm', args: ['i', name] } });
3026
+ return true;
3027
+ }
3028
+ if (value) {
3029
+ this.writeFail(value, err, options);
3030
+ }
3031
+ return false;
3032
+ }
3033
+ checkFail(message, options) {
3034
+ const code = options.code;
3035
+ if (code && message instanceof Error) {
3036
+ const valid = message.code === code;
3037
+ switch (code) {
3038
+ case types_1.ERR_CODE.MODULE_NOT_FOUND: {
3039
+ const exec = options.exec;
3040
+ if (exec) {
3041
+ if (valid && !this.aborted) {
3042
+ const command = exec.command + (exec.args ? ' ' + exec.args.join(' ') : '');
3043
+ const target = this.host || this;
3044
+ let session = CACHE_EXEC.get(target);
3045
+ if (!session) {
3046
+ CACHE_EXEC.set(target, session = []);
3047
+ }
3048
+ if (session.includes(command)) {
3049
+ return false;
3050
+ }
3051
+ session.push(command);
3052
+ let type = options.type || 0;
3053
+ type |= 4096 /* LOG_VALUE.EXEC */;
3054
+ type &= ~1 /* LOG_VALUE.SYSTEM */;
3055
+ if (options.passThrough) {
3056
+ options.passThrough = false;
3057
+ message = null;
3058
+ }
3059
+ return { type, value: ["Install required?" /* ERR_MESSAGE.INSTALL */, command], message };
3060
+ }
3061
+ delete options.exec;
3062
+ }
3063
+ break;
3064
+ }
3065
+ }
3066
+ }
3067
+ }
3068
+ writeLog(type, value, timeStamp, duration) {
3069
+ let queue;
3070
+ if ((0, types_1.isObject)(type)) {
3071
+ if (typeof value === 'boolean') {
3072
+ queue = value;
3073
+ }
3074
+ ({ type = types_1.STATUS_TYPE.UNKNOWN, value, timeStamp, duration } = type);
3075
+ }
3076
+ const output = Module.asString(value);
3077
+ if (output) {
3078
+ if ((queue || (0, types_1.isPlainObject)(timeStamp) && timeStamp.queue) && !this._logFlushed) {
3079
+ this._logQueued.push([-1, output]);
3080
+ }
3081
+ else {
3082
+ writeLine(output);
3083
+ }
3084
+ }
3085
+ this.addLog(type, value, timeStamp, duration);
3086
+ }
3087
+ addLog(type, value, timeStamp, duration, from, source) {
3088
+ if (!this._logEnabled || SETTINGS.production && process.env.NODE_ENV === 'production' && (SETTINGS.production.includes(this.moduleName) || from && SETTINGS.production.includes(from))) {
3089
+ return;
3090
+ }
3091
+ if ((0, types_1.isObject)(type)) {
3092
+ ({ type = types_1.STATUS_TYPE.UNKNOWN, value, timeStamp, duration, from, source } = type);
3093
+ }
3094
+ else if (typeof timeStamp === 'string') {
3095
+ if (typeof duration === 'string') {
3096
+ source = duration;
3097
+ duration = undefined;
3098
+ }
3099
+ from = timeStamp;
3100
+ timeStamp = 0;
3101
+ }
3102
+ else if ((0, types_1.isObject)(timeStamp)) {
3103
+ ({ timeStamp, duration, from, source } = timeStamp);
3104
+ }
3105
+ const name = types_1.STATUS_TYPE[type] || types_1.STATUS_TYPE[type = 0];
3106
+ const logLevel = this.logLevel;
3107
+ if ((0, types_1.isEmpty)(value) || logLevel > 0 && (type > logLevel || type === 0 && logLevel < types_1.STATUS_TYPE.DEBUG) || SETTINGS.status[name.toLowerCase()] === false) {
3108
+ return;
3109
+ }
3110
+ let message = '';
3111
+ if (!timeStamp) {
3112
+ timeStamp = Date.now();
3113
+ }
3114
+ else if (timeStamp instanceof Date) {
3115
+ timeStamp = timeStamp.getTime();
3116
+ }
3117
+ if (typeof duration === 'string') {
3118
+ if (typeof from === 'string') {
3119
+ source = from;
3120
+ }
3121
+ from = duration;
3122
+ duration = undefined;
3123
+ }
3124
+ if (typeof value === 'string') {
3125
+ message = this.supports('stripAnsi') ? stripansi(value) : value;
3126
+ }
3127
+ else if (value instanceof Error) {
3128
+ if (value.name === 'AbortError') {
3129
+ return;
3130
+ }
3131
+ if (value.stack && SETTINGS.status.trace) {
3132
+ message = value.message;
3133
+ this.status.push({ type: types_1.STATUS_TYPE.TRACE, value: message ? value.stack.replace(message, '').trim() : value.stack, timeStamp, name: types_1.STATUS_TYPE[types_1.STATUS_TYPE.TRACE], duration, sessionId: this.sessionId, from: this.moduleName, source });
3134
+ }
3135
+ else {
3136
+ message = getErrorMessage(value);
3137
+ }
3138
+ }
3139
+ else {
3140
+ try {
3141
+ message = Array.isArray(value) ? value.join(' / ') : value.toString();
3142
+ }
3143
+ catch {
3144
+ message = '';
3145
+ }
3146
+ }
3147
+ this.status.push({ value: message.trim() || "Unknown" /* ERR_MESSAGE.UNKNOWN */, name, duration, timeStamp, type, sessionId: this.sessionId, from: from || this.moduleName, source });
3148
+ }
3149
+ getLog(...type) {
3150
+ return this.status.filter(item => type.includes(item.type));
3151
+ }
3152
+ flushLog() {
3153
+ this._logFlushed = true;
3154
+ const logQueued = this._logQueued;
3155
+ if (logQueued.length) {
3156
+ logQueued.sort((a, b) => b[0] - a[0]);
3157
+ logQueued.forEach(args => {
3158
+ if (args.length === 2) {
3159
+ if (!this.broadcastId) {
3160
+ writeLine(args[1]);
3161
+ return;
3162
+ }
3163
+ args = [args[0], '', this.supports('stripAnsi') ? stripansi(args[1]) : args[1], null, applyLogId.call(this, { sessionId: '' })];
3164
+ }
3165
+ Module.formatMessage(...args);
3166
+ });
3167
+ logQueued.length = 0;
3168
+ }
3169
+ }
3170
+ reset() {
3171
+ if (this.aborted) {
3172
+ this[kAbortHandler] = new AbortController();
3173
+ }
3174
+ this.status.length = 0;
3175
+ this.errors.length = 0;
3176
+ this._logQueued.length = 0;
3177
+ this._logFlushed = false;
3178
+ }
3179
+ detach() {
3180
+ const host = this.host;
3181
+ if (host) {
3182
+ this.abortable = false;
3183
+ host.modules.delete(this);
3184
+ host.subProcesses.delete(this);
3185
+ const listener = this[kAbortEvent];
3186
+ if (listener) {
3187
+ host.signal.removeEventListener('abort', listener);
3188
+ this[kAbortEvent] = null;
3189
+ }
3190
+ this._host = null;
3191
+ }
3192
+ }
3193
+ abort() {
3194
+ if (!this.aborted) {
3195
+ this[kAbortHandler].abort();
3196
+ }
3197
+ }
3198
+ willAbort(value) {
3199
+ return false;
3200
+ }
3201
+ hasOwnPermission() {
3202
+ return !!this[kPermission];
3203
+ }
3204
+ isFatal(err) {
3205
+ const fatal = this.host?.config.error?.fatal;
3206
+ return fatal ?? VALUES["error.fatal" /* KEY_NAME.ERROR_FATAL */];
3207
+ }
3208
+ get moduleName() {
3209
+ return this._moduleName;
3210
+ }
3211
+ set host(value) {
3212
+ this.detach();
3213
+ if (this._host = value) {
3214
+ this.sessionId = value.sessionId;
3215
+ this.broadcastId = value.broadcastId;
3216
+ this._logEnabled = value.willLog(this.moduleName);
3217
+ const aborting = this._hostEvents.includes('abort');
3218
+ if (value.aborted) {
3219
+ if (aborting) {
3220
+ this.abort();
3221
+ }
3222
+ }
3223
+ else if (!value.subProcesses.has(this)) {
3224
+ this.abortable = value.willAbort(this);
3225
+ value.modules.add(this);
3226
+ if (aborting) {
3227
+ value.signal.addEventListener('abort', this[kAbortEvent] = () => this.abort(), { once: true });
3228
+ }
3229
+ }
3230
+ }
3231
+ }
3232
+ get host() {
3233
+ return this._host;
3234
+ }
3235
+ set sessionId(value) {
3236
+ this[kSessionId] = value;
3237
+ }
3238
+ get sessionId() {
3239
+ return this[kSessionId] || (this.host ? this.host.sessionId : '');
3240
+ }
3241
+ set broadcastId(value) {
3242
+ this[kBroadcastId] = value;
3243
+ }
3244
+ get broadcastId() {
3245
+ return this[kBroadcastId] || (this.host ? this.host.broadcastId : '');
3246
+ }
3247
+ set permission(value) {
3248
+ this[kPermission] = value;
3249
+ }
3250
+ get permission() {
3251
+ let host;
3252
+ return this[kPermission] || (host = this.host) && host.permission;
3253
+ }
3254
+ get signal() {
3255
+ return this[kAbortHandler].signal;
3256
+ }
3257
+ get aborted() {
3258
+ return this.signal.aborted;
3259
+ }
3260
+ set abortable(value) {
3261
+ this._abortable = value;
3262
+ }
3263
+ get abortable() {
3264
+ return this._abortable;
3265
+ }
3266
+ get threadable() {
3267
+ return this._threadable;
3268
+ }
3269
+ get logType() {
3270
+ return types_1.LOG_TYPE;
3271
+ }
3272
+ set logLevel(value) {
3273
+ if ((0, types_1.isString)(value)) {
3274
+ value = types_1.STATUS_TYPE[value.toUpperCase()];
3275
+ }
3276
+ if (value >= 0 && value <= types_1.STATUS_TYPE.TRACE) {
3277
+ this._logLevel = value;
3278
+ }
3279
+ }
3280
+ get logLevel() {
3281
+ const value = this._logLevel;
3282
+ if (value === -1) {
3283
+ const host = this.host;
3284
+ return host ? host.logLevel : 0;
3285
+ }
3286
+ return value;
3287
+ }
3288
+ get statusType() {
3289
+ return types_1.STATUS_TYPE;
3290
+ }
3291
+ set tempDir(value) {
3292
+ if (path.isAbsolute(value)) {
3293
+ if (!withinDir(value, PROCESS_CWD)) {
3294
+ return;
3295
+ }
3296
+ value = value.substring(ensureDir(PROCESS_CWD).length);
3297
+ }
3298
+ if (Module.isDir(path.join(PROCESS_CWD, value))) {
3299
+ this[kTempDir] = value;
3300
+ }
3301
+ }
3302
+ get tempDir() {
3303
+ return this[kTempDir];
3304
+ }
3305
+ }
3306
+ _a = kSessionId, _b = kTempDir, _c = kBroadcastId, _d = kPermission, _e = kSupports, _f = kAbortHandler, _g = kAbortEvent;
3307
+ Module.PROCESS_TIMEOUT = 0;
3308
+ Module.LOG_STYLE_FAIL = Object.freeze({ titleBgColor: 'bgRed', titleColor: 'white', titleBold: true });
3309
+ Module.LOG_STYLE_SUCCESS = Object.freeze({ titleBgColor: 'bgBlack', titleColor: 'green', titleBold: true });
3310
+ Module.LOG_STYLE_INFO = Object.freeze({ titleBgColor: 'bgBlue', titleColor: 'white' });
3311
+ Module.LOG_STYLE_WARN = Object.freeze({ titleBgColor: 'bgBlack', titleColor: 'yellow', titleBold: true });
3312
+ Module.LOG_STYLE_NOTICE = Object.freeze({ titleBgColor: 'bgGrey', titleColor: 'white' });
3313
+ Module.LOG_STYLE_REVERSE = Object.freeze({ titleBgColor: 'bgWhite', titleColor: 'black', messageBgColor: 'bgGrey' });
3314
+ if (!Module.supported(15, 4)) {
3315
+ ({ AbortController: global.AbortController } = require('abort-controller'));
3316
+ ({ EventTarget: global.EventTarget } = require('event-target-shim'));
3317
+ }
3318
+ EventEmitter.defaultMaxListeners = Infinity;
3319
+ Object.freeze(types_1.LOG_TYPE);
3320
+ Object.freeze(types_1.STATUS_TYPE);
3321
+ exports.default = Module;
3322
+
3323
+ if (exports.default) {
3324
+ module.exports = exports.default;
3325
+ module.exports.default = exports.default;
3326
+ }