hfs 0.57.24 → 0.57.27-beta2

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.
Files changed (72) hide show
  1. package/admin/assets/{index-CMArzROW.js → index-DSkhXlWX.js} +129 -129
  2. package/admin/assets/{sha512-BbjMQS_R.js → sha512-CoddZKeD.js} +1 -1
  3. package/admin/index.html +1 -1
  4. package/frontend/assets/{index-legacy-uM-kzXmI.js → index-legacy-C4Gclsbz.js} +4 -4
  5. package/frontend/assets/{sha512-legacy-CWlrw4EZ.js → sha512-legacy-C-FMk44u.js} +1 -1
  6. package/frontend/index.html +1 -1
  7. package/package.json +5 -4
  8. package/src/QuickZipStream.js +11 -8
  9. package/src/SendList.js +10 -8
  10. package/src/ThrottledStream.js +8 -6
  11. package/src/acme.js +5 -7
  12. package/src/adminApis.js +6 -7
  13. package/src/api.accounts.js +7 -9
  14. package/src/api.auth.js +7 -11
  15. package/src/api.get_file_list.js +13 -19
  16. package/src/api.lang.js +1 -1
  17. package/src/api.log.js +1 -2
  18. package/src/api.monitor.js +2 -3
  19. package/src/api.net.js +2 -3
  20. package/src/api.plugins.js +8 -10
  21. package/src/api.vfs.js +15 -20
  22. package/src/apiMiddleware.js +4 -4
  23. package/src/auth.js +6 -9
  24. package/src/basicWeb.js +1 -2
  25. package/src/block.js +1 -1
  26. package/src/commands.js +9 -9
  27. package/src/comments.js +4 -5
  28. package/src/config.js +10 -10
  29. package/src/connections.js +11 -6
  30. package/src/consoleLog.js +6 -6
  31. package/src/const.js +4 -4
  32. package/src/cross.js +19 -21
  33. package/src/customHtml.js +3 -4
  34. package/src/ddns.js +4 -4
  35. package/src/debounceAsync.js +3 -3
  36. package/src/errorPages.js +2 -3
  37. package/src/events.js +7 -10
  38. package/src/fileAttr.js +12 -8
  39. package/src/first.js +13 -8
  40. package/src/frontEndApis.js +5 -5
  41. package/src/geo.js +5 -7
  42. package/src/github.js +14 -17
  43. package/src/i18n.js +3 -4
  44. package/src/icons.js +1 -1
  45. package/src/index.js +2 -3
  46. package/src/lang.js +5 -6
  47. package/src/listen.js +25 -28
  48. package/src/log.js +20 -20
  49. package/src/middlewares.js +12 -15
  50. package/src/misc.js +15 -14
  51. package/src/nat.js +14 -16
  52. package/src/outboundProxy.js +7 -7
  53. package/src/perm.js +12 -13
  54. package/src/persistence.js +1 -1
  55. package/src/plugins.js +62 -73
  56. package/src/roots.js +1 -2
  57. package/src/selfCheck.js +5 -4
  58. package/src/serveFile.js +7 -8
  59. package/src/serveGuiAndSharedFiles.js +7 -9
  60. package/src/serveGuiFiles.js +11 -21
  61. package/src/stat.js +40 -0
  62. package/src/statWorker.js +11 -0
  63. package/src/throttler.js +5 -7
  64. package/src/update.js +9 -9
  65. package/src/upload.js +11 -13
  66. package/src/util-files.js +48 -32
  67. package/src/util-http.js +80 -29
  68. package/src/util-os.js +5 -8
  69. package/src/vfs.js +77 -68
  70. package/src/walkDir.js +9 -9
  71. package/src/watchLoad.js +4 -4
  72. package/src/zip.js +5 -10
@@ -17,12 +17,18 @@ const events_1 = __importDefault(require("./events"));
17
17
  const geo_1 = require("./geo");
18
18
  const lodash_1 = __importDefault(require("lodash"));
19
19
  class Connection {
20
+ socket;
21
+ started = new Date();
22
+ sent = 0; // socket-scoped, not request-scoped
23
+ got = 0;
24
+ outSpeed;
25
+ inSpeed;
26
+ ctx; // this is set externally, during koa middleware, using updateConnectionForCtx, but only for regular requests; some connections may never have a ctx
27
+ country;
28
+ _cachedIp;
20
29
  // the sockets we collect are the plain ones, as soon as the tcp layer is connected
21
30
  constructor(socket) {
22
31
  this.socket = socket;
23
- this.started = new Date();
24
- this.sent = 0; // socket-scoped, not request-scoped
25
- this.got = 0;
26
32
  all.push(this);
27
33
  socket.on('close', () => {
28
34
  all.splice(all.indexOf(this), 1);
@@ -31,12 +37,11 @@ class Connection {
31
37
  events_1.default.emit('connection', this);
32
38
  }
33
39
  get ip() {
34
- var _a, _b;
35
40
  if (this._cachedIp && this.ctx && this._cachedIp !== this.ctx.ip) {
36
41
  events_1.default.emit('connectionNewIp', this, this._cachedIp, this.ctx.ip);
37
42
  this._cachedIp = undefined;
38
43
  }
39
- return ((_a = this.ctx) === null || _a === void 0 ? void 0 : _a.ip) || ((_b = this._cachedIp) !== null && _b !== void 0 ? _b : (this._cachedIp = normalizeIp(this.socket.remoteAddress || '')));
44
+ return this.ctx?.ip || (this._cachedIp ??= normalizeIp(this.socket.remoteAddress || ''));
40
45
  }
41
46
  get secure() {
42
47
  return this.socket.server.cert > '';
@@ -50,7 +55,7 @@ const all = [];
50
55
  function newConnection(socket) {
51
56
  const ip = normalizeIp(socket.remoteAddress || '');
52
57
  const res = events_1.default.emit('newSocket', { socket, ip });
53
- const msg = (res === null || res === void 0 ? void 0 : res.isDefaultPrevented()) ? 'plugin (newSocket)' : res === null || res === void 0 ? void 0 : res.find(lodash_1.default.isString);
58
+ const msg = res?.isDefaultPrevented() ? 'plugin (newSocket)' : res?.find(lodash_1.default.isString);
54
59
  if (!msg)
55
60
  return new Connection(socket);
56
61
  disconnect(socket, msg);
package/src/consoleLog.js CHANGED
@@ -21,10 +21,10 @@ for (const k of ['log', 'warn', 'error', 'debug']) {
21
21
  const msg = safeJoin(args); // if args contains a symbol, join will throw
22
22
  const rec = { ts, k, msg };
23
23
  exports.consoleLog.push(rec);
24
- if (exports.consoleLog.length > 100000) // limit to avoid infinite space
25
- exports.consoleLog.splice(0, 1000);
24
+ if (exports.consoleLog.length > 100_000) // limit to avoid infinite space
25
+ exports.consoleLog.splice(0, 1_000);
26
26
  events_1.default.emit('console', rec);
27
- f === null || f === void 0 ? void 0 : f.write(`${(0, cross_1.formatTimestamp)(ts)} [${k}] ${msg}\n`);
27
+ f?.write(`${(0, cross_1.formatTimestamp)(ts)} [${k}] ${msg}\n`);
28
28
  if (k !== 'log')
29
29
  args.unshift('!');
30
30
  }
@@ -35,20 +35,20 @@ function safeJoin(a) {
35
35
  try {
36
36
  return a.join(' ');
37
37
  }
38
- catch (_a) {
38
+ catch {
39
39
  return a.map(x => {
40
40
  if (x == null)
41
41
  return '';
42
42
  try {
43
43
  return String(x);
44
44
  }
45
- catch (_a) {
45
+ catch {
46
46
  if (Array.isArray(x))
47
47
  return `[${safeJoin(x)}]`;
48
48
  try {
49
49
  return JSON.stringify(x);
50
50
  }
51
- catch (_b) {
51
+ catch {
52
52
  return 'N/A';
53
53
  }
54
54
  }
package/src/const.js CHANGED
@@ -49,7 +49,7 @@ const path_1 = require("path");
49
49
  const cross_1 = require("./cross");
50
50
  const argv_1 = require("./argv");
51
51
  __exportStar(require("./cross-const"), exports);
52
- exports.API_VERSION = 12.94;
52
+ exports.API_VERSION = 12.95;
53
53
  exports.COMPATIBLE_API_VERSION = 1; // while changes in the api are not breaking, this number stays the same, otherwise it is made equal to API_VERSION
54
54
  // you can add arguments with this file, currently used for the update process on mac/linux
55
55
  exports.ARGS_FILE = (0, path_1.join)((0, os_1.homedir)(), 'hfs-args');
@@ -59,12 +59,12 @@ try {
59
59
  lodash_1.default.defaults(argv_1.argv, (0, minimist_1.default)(JSON.parse(s)));
60
60
  fs.unlinkSync(exports.ARGS_FILE);
61
61
  }
62
- catch (_a) { }
62
+ catch { }
63
63
  exports.DEV = process.env.DEV ? 'DEV' : '';
64
64
  exports.ORIGINAL_CWD = process.cwd();
65
65
  exports.HFS_STARTED = new Date();
66
66
  const PKG_PATH = (0, path_1.join)(__dirname, '..', 'package.json');
67
- exports.BUILD_TIMESTAMP = "2025-10-24T19:37:42.115Z";
67
+ exports.BUILD_TIMESTAMP = "2025-11-30T11:15:41.563Z";
68
68
  const pkg = JSON.parse(fs.readFileSync(PKG_PATH, 'utf8'));
69
69
  exports.VERSION = pkg.version;
70
70
  exports.RUNNING_BETA = exports.VERSION.includes('-');
@@ -123,7 +123,7 @@ function useHomeDir() {
123
123
  fs.writeFileSync(exports.CONFIG_FILE, ''); // not found, try to create
124
124
  fs.unlinkSync(exports.CONFIG_FILE);
125
125
  }
126
- catch (_a) {
126
+ catch {
127
127
  return true;
128
128
  }
129
129
  }
package/src/cross.js CHANGED
@@ -101,7 +101,7 @@ __exportStar(require("./cross-const"), exports);
101
101
  exports.WEBSITE = 'https://rejetto.com/hfs/';
102
102
  exports.REPO_URL = `https://github.com/${cross_const_1.HFS_REPO}/`;
103
103
  exports.WIKI_URL = exports.REPO_URL + 'wiki/';
104
- exports.MINUTE = 60000;
104
+ exports.MINUTE = 60_000;
105
105
  exports.HOUR = 60 * exports.MINUTE;
106
106
  exports.DAY = 24 * exports.HOUR;
107
107
  exports.MAX_TILE_SIZE = 10;
@@ -146,10 +146,9 @@ function isWhoObject(v) {
146
146
  }
147
147
  const MULTIPLIERS = ['', 'K', 'M', 'G', 'T'];
148
148
  function formatBytes(n, { post = 'B', k = 0, digits = NaN, sep = ' ' } = {}) {
149
- var _a;
150
149
  if (isNaN(Number(n)) || n < 0)
151
150
  return '';
152
- k || (k = (_a = formatBytes.k) !== null && _a !== void 0 ? _a : 1024); // default value
151
+ k ||= formatBytes.k ?? 1024; // default value
153
152
  const i = n && Math.min(MULTIPLIERS.length - 1, Math.floor(Math.log2(n) / Math.log2(k)));
154
153
  n /= k ** i;
155
154
  const nAsString = i && !isNaN(digits) ? n.toFixed(digits)
@@ -176,7 +175,11 @@ function wait(ms, val) {
176
175
  }
177
176
  // throws after ms
178
177
  function haveTimeout(ms, job, error) {
179
- return Promise.race([job, wait(ms).then(() => { throw error || Error('timeout'); })]);
178
+ let h;
179
+ return Promise.race([
180
+ job.finally(() => clearTimeout(h)), // don't leave pending timeout if the job is done first
181
+ new Promise((_resolve, reject) => h = setTimeout(() => reject(error || Error('timeout')), ms))
182
+ ]);
180
183
  }
181
184
  function objSameKeys(src, newValue) {
182
185
  return Object.fromEntries(Object.entries(src).map(([k, v]) => [k, newValue(v, k)]));
@@ -227,7 +230,7 @@ function try_(cb, onException) {
227
230
  return cb();
228
231
  }
229
232
  catch (e) {
230
- return onException === null || onException === void 0 ? void 0 : onException(e);
233
+ return onException?.(e);
231
234
  }
232
235
  }
233
236
  function with_(par, cb) {
@@ -253,8 +256,7 @@ function pendingPromise() {
253
256
  return Object.assign(ret, takeOut);
254
257
  }
255
258
  function basename(path) {
256
- var _a;
257
- return ((_a = path.match(/([^\\/]+)[\\/]*$/)) === null || _a === void 0 ? void 0 : _a[1]) || '';
259
+ return path.match(/([^\\/]+)[\\/]*$/)?.[1] || '';
258
260
  }
259
261
  function dirname(path) {
260
262
  return path.slice(0, Math.max(0, path.lastIndexOf('/', path.length - 1)));
@@ -263,8 +265,8 @@ function tryJson(s, except) {
263
265
  try {
264
266
  return s && JSON.parse(s);
265
267
  }
266
- catch (_a) {
267
- return except === null || except === void 0 ? void 0 : except(s);
268
+ catch {
269
+ return except?.(s);
268
270
  }
269
271
  }
270
272
  function swap(obj, k1, k2) {
@@ -377,7 +379,7 @@ function repeat(everyMs, cb) {
377
379
  try {
378
380
  await cb(stopIt);
379
381
  } // you can use stopIt passed as a parameter or the returned value, whatever makes you happy
380
- catch (_a) { }
382
+ catch { }
381
383
  await wait(everyMs);
382
384
  }
383
385
  })();
@@ -418,17 +420,15 @@ function isTimestampString(v) {
418
420
  return typeof v === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d+)?Z*$/.test(v);
419
421
  }
420
422
  function isEqualLax(a, b, overrideRule) {
421
- var _a;
422
- return (_a = overrideRule === null || overrideRule === void 0 ? void 0 : overrideRule(a, b)) !== null && _a !== void 0 ? _a : (a == b || a && b && typeof a === 'object' && typeof b === 'object'
423
+ return overrideRule?.(a, b) ?? (a == b || a && b && typeof a === 'object' && typeof b === 'object'
423
424
  && Object.entries(a).every(([k, v]) => isEqualLax(v, b[k], overrideRule))
424
425
  && Object.entries(b).every(([k, v]) => k in a /*already checked*/ || isEqualLax(v, a[k], overrideRule)));
425
426
  }
426
427
  function xlate(input, table) {
427
- var _a;
428
- return (_a = table[input]) !== null && _a !== void 0 ? _a : input;
428
+ return table[input] ?? input;
429
429
  }
430
430
  function normalizeHost(host) {
431
- return host[0] === '[' ? host.slice(1, host.indexOf(']')) : host === null || host === void 0 ? void 0 : host.split(':')[0];
431
+ return host[0] === '[' ? host.slice(1, host.indexOf(']')) : host?.split(':')[0];
432
432
  }
433
433
  function isIpLocalHost(ip) {
434
434
  return ip === '::1' || ip.endsWith('127.0.0.1');
@@ -480,9 +480,8 @@ function makeMatcher(mask, emptyMaskReturns = false) {
480
480
  }
481
481
  // this is caching all matchers, so don't use it with frequently changing masks. Benchmarks revealed that _.memoize make it slower than not using it, while this simple cache can speed up to 30x
482
482
  function matches(s, mask, emptyMaskReturns = false) {
483
- var _a, _b;
484
- const cache = (_a = matches).cache || (_a.cache = {});
485
- return (cache[_b = mask + (emptyMaskReturns ? '1' : '0')] || (cache[_b] = makeMatcher(mask, emptyMaskReturns)))(s);
483
+ const cache = matches.cache ||= {};
484
+ return (cache[mask + (emptyMaskReturns ? '1' : '0')] ||= makeMatcher(mask, emptyMaskReturns))(s);
486
485
  }
487
486
  // if delimiter is specified, it is prefixed to symbols. If it contains a space, the part after the space is considered as suffix.
488
487
  function replace(s, symbols, delimiter = '') {
@@ -513,7 +512,7 @@ function safeDecodeURIComponent(s) {
513
512
  try {
514
513
  return decodeURIComponent(s);
515
514
  }
516
- catch (_a) {
515
+ catch {
517
516
  return s;
518
517
  }
519
518
  }
@@ -543,9 +542,8 @@ function toMutable(value) {
543
542
  return Array.isArray(value) ? value.slice() : { ...value };
544
543
  }
545
544
  function shortenAgent(agent) {
546
- var _a;
547
545
  return lodash_1.default.findKey(BROWSERS, re => re.test(agent))
548
- || ((_a = /^[^/(]+ ?/.exec(agent)) === null || _a === void 0 ? void 0 : _a[0])
546
+ || /^[^/(]+ ?/.exec(agent)?.[0]
549
547
  || agent;
550
548
  }
551
549
  const BROWSERS = {
package/src/customHtml.js CHANGED
@@ -22,7 +22,6 @@ exports.disableCustomHtml = (0, config_1.defineConfig)(misc_1.CFG.disable_custom
22
22
  function watchLoadCustomHtml(folder = '') {
23
23
  const sections = new Map();
24
24
  const res = (0, watchLoad_1.watchLoad)((0, misc_1.prefix)('', folder, '/') + FILE, data => {
25
- var _a;
26
25
  const re = /^\[([^\]]+)] *$/gm;
27
26
  sections.clear();
28
27
  if (!data)
@@ -31,10 +30,10 @@ function watchLoadCustomHtml(folder = '') {
31
30
  do {
32
31
  let last = re.lastIndex;
33
32
  const match = re.exec(data);
34
- const content = data.slice(last, !match ? undefined : re.lastIndex - (((_a = match === null || match === void 0 ? void 0 : match[0]) === null || _a === void 0 ? void 0 : _a.length) || 0)).trim();
33
+ const content = data.slice(last, !match ? undefined : re.lastIndex - (match?.[0]?.length || 0)).trim();
35
34
  if (content)
36
35
  sections.set(name, content);
37
- name = match === null || match === void 0 ? void 0 : match[1];
36
+ name = match?.[1];
38
37
  } while (name);
39
38
  });
40
39
  return Object.assign(res, { sections });
@@ -50,7 +49,7 @@ function getAllSections() {
50
49
  return Object.fromEntries(all.map(x => [x, getSection(x)]));
51
50
  }
52
51
  async function saveCustomHtml(sections) {
53
- const text = Object.entries(sections).filter(([k, v]) => v === null || v === void 0 ? void 0 : v.trim()).map(([k, v]) => `[${k}]\n${v}\n\n`).join('');
52
+ const text = Object.entries(sections).filter(([k, v]) => v?.trim()).map(([k, v]) => `[${k}]\n${v}\n\n`).join('');
54
53
  await (0, promises_1.writeFile)(FILE, text);
55
54
  exports.customHtml.sections.clear();
56
55
  for (const [k, v] of Object.entries(sections))
package/src/ddns.js CHANGED
@@ -22,8 +22,8 @@ let stopFetching;
22
22
  let lastIPs;
23
23
  let lastMap;
24
24
  events_1.default.onListeners(EVENT, cbs => {
25
- stopFetching === null || stopFetching === void 0 ? void 0 : stopFetching();
26
- if (!(cbs === null || cbs === void 0 ? void 0 : cbs.size))
25
+ stopFetching?.();
26
+ if (!cbs?.size)
27
27
  return;
28
28
  stopFetching = (0, cross_1.repeat)(cross_1.HOUR, async () => {
29
29
  const IPs = await (0, nat_1.getPublicIps)();
@@ -41,7 +41,7 @@ events_1.default.onListeners(EVENT, cbs => {
41
41
  let stopListening;
42
42
  let last;
43
43
  dynamicDnsUrl.sub(v => {
44
- stopListening === null || stopListening === void 0 ? void 0 : stopListening();
44
+ stopListening?.();
45
45
  if (!v)
46
46
  return;
47
47
  stopListening = events_1.default.on(EVENT, async () => {
@@ -60,7 +60,7 @@ dynamicDnsUrl.sub(v => {
60
60
  }));
61
61
  last = lodash_1.default.find(all, 'error') || all[0]; // the system is designed for just one result, and we give precedence to errors
62
62
  events_1.default.emit('dynamicDnsError', last);
63
- console.log('dynamic dns update', (last === null || last === void 0 ? void 0 : last.error) || 'ok');
63
+ console.log('dynamic dns update', last?.error || 'ok');
64
64
  }, { callNow: true });
65
65
  });
66
66
  async function get_dynamic_dns_error() {
@@ -19,7 +19,7 @@ callback, options = {}) {
19
19
  const interceptingWrapper = (...args) => latestDebouncer = debouncer(...args);
20
20
  return Object.assign(interceptingWrapper, {
21
21
  clearRetain: () => latestCallback = undefined,
22
- flush: () => runningCallback !== null && runningCallback !== void 0 ? runningCallback : exec(),
22
+ flush: () => runningCallback ?? exec(),
23
23
  isWorking: () => runningCallback,
24
24
  ...cancelable && {
25
25
  cancel() {
@@ -32,10 +32,10 @@ callback, options = {}) {
32
32
  if (reuseRunning && runningCallback)
33
33
  return runningCallback;
34
34
  const now = Date.now();
35
- if (latestCallback && now - latestTimestamp < (latestHasFailed ? retainFailure !== null && retainFailure !== void 0 ? retainFailure : retain : retain))
35
+ if (latestCallback && now - latestTimestamp < (latestHasFailed ? retainFailure ?? retain : retain))
36
36
  return await latestCallback;
37
37
  whoIsWaiting = args;
38
- waitingSince || (waitingSince = now);
38
+ waitingSince ||= now;
39
39
  const waitingCap = maxWait - (now - (waitingSince || started));
40
40
  const waitFor = Math.min(waitingCap, leading ? wait - (now - started) : wait);
41
41
  if (waitFor > 0)
package/src/errorPages.js CHANGED
@@ -11,7 +11,6 @@ function getErrorSections() {
11
11
  }
12
12
  // to be used with errors whose recipient is possibly human
13
13
  async function sendErrorPage(ctx, code = ctx.status) {
14
- var _a, _b;
15
14
  ctx.type = 'text';
16
15
  ctx.set('content-disposition', ''); // reset ctx.attachment (or forceDownload)
17
16
  ctx.status = code;
@@ -21,8 +20,8 @@ async function sendErrorPage(ctx, code = ctx.status) {
21
20
  const lang = await (0, lang_1.getLangData)(ctx);
22
21
  if (!lang)
23
22
  return;
24
- const trans = (_a = Object.values(lang)[0]) === null || _a === void 0 ? void 0 : _a.translate;
25
- ctx.body = (_b = trans === null || trans === void 0 ? void 0 : trans[msg]) !== null && _b !== void 0 ? _b : msg;
23
+ const trans = Object.values(lang)[0]?.translate;
24
+ ctx.body = trans?.[msg] ?? msg;
26
25
  const errorPage = (0, customHtml_1.getSection)(ctx.status === cross_1.HTTP_UNAUTHORIZED ? 'unauthorized' : String(ctx.status));
27
26
  if (!errorPage)
28
27
  return;
package/src/events.js CHANGED
@@ -4,11 +4,9 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.BetterEventEmitter = void 0;
5
5
  const LISTENERS_SUFFIX = '\0listeners';
6
6
  class BetterEventEmitter {
7
- constructor() {
8
- this.listeners = new Map();
9
- this.preventDefault = Symbol();
10
- this.stop = this.preventDefault; // legacy pre-0.54 (introduced in 0.53)
11
- }
7
+ listeners = new Map();
8
+ preventDefault = Symbol();
9
+ stop = this.preventDefault; // legacy pre-0.54 (introduced in 0.53)
12
10
  on(event, listener, { warnAfter = 10, callNow = false } = {}) {
13
11
  if (typeof event === 'string')
14
12
  event = [event];
@@ -25,7 +23,7 @@ class BetterEventEmitter {
25
23
  try {
26
24
  listener();
27
25
  }
28
- catch (_a) { }
26
+ catch { }
29
27
  return () => {
30
28
  for (const e of event) {
31
29
  const cbs = this.listeners.get(e);
@@ -47,7 +45,7 @@ class BetterEventEmitter {
47
45
  off = this.on(event, function (...args) {
48
46
  off();
49
47
  resolve(args.slice(0, -1)); // remove the extra argument at the end of our emit()
50
- return listener === null || listener === void 0 ? void 0 : listener(...args);
48
+ return listener?.(...args);
51
49
  });
52
50
  });
53
51
  return Object.assign(off, { then: pro.then.bind(pro) });
@@ -60,12 +58,11 @@ class BetterEventEmitter {
60
58
  };
61
59
  }
62
60
  anyListener(event) {
63
- var _a;
64
- return Boolean((_a = this.listeners.get(event)) === null || _a === void 0 ? void 0 : _a.size);
61
+ return Boolean(this.listeners.get(event)?.size);
65
62
  }
66
63
  emit(event, ...args) {
67
64
  let cbs = this.listeners.get(event);
68
- if (!(cbs === null || cbs === void 0 ? void 0 : cbs.size))
65
+ if (!cbs?.size)
69
66
  return;
70
67
  const output = [];
71
68
  let prevented = false;
package/src/fileAttr.js CHANGED
@@ -10,6 +10,7 @@ const promises_1 = require("fs/promises");
10
10
  const cross_1 = require("./cross");
11
11
  const first_1 = require("./first");
12
12
  const promises_2 = require("node:fs/promises");
13
+ const util_files_1 = require("./util-files");
13
14
  const const_1 = require("./const");
14
15
  const fsx = (0, cross_1.try_)(() => {
15
16
  const lib = require('fs-x-attributes');
@@ -23,10 +24,9 @@ if ((0, fs_1.existsSync)(FN))
23
24
  const FILE_ATTR_PREFIX = 'user.hfs.'; // user. prefix to be linux compatible
24
25
  /* @param v must be JSON-able or undefined */
25
26
  async function storeFileAttr(path, k, v) {
26
- var _a, _b;
27
- const s = await (0, promises_2.stat)(path).catch(() => null);
27
+ const s = await (0, util_files_1.statWithTimeout)(path).catch(() => null);
28
28
  // since we don't have fsx.remove, we simulate it with an empty string
29
- if (s && await (fsx === null || fsx === void 0 ? void 0 : fsx.set(path, FILE_ATTR_PREFIX + k, v === undefined ? '' : JSON.stringify(v)).then(() => 1, () => 0))) {
29
+ if (s && await fsx?.set(path, FILE_ATTR_PREFIX + k, v === undefined ? '' : JSON.stringify(v)).then(() => 1, () => 0)) {
30
30
  if (const_1.IS_WINDOWS)
31
31
  (0, promises_2.utimes)(path, s.atime, s.mtime); // restore timestamps, necessary only on Windows
32
32
  return true;
@@ -38,18 +38,22 @@ async function storeFileAttr(path, k, v) {
38
38
  else
39
39
  await fileAttrDb.open(FN);
40
40
  // pipe should be a safe separator
41
- return (_b = await ((_a = fileAttrDb.put(`${path}|${k}`, v)) === null || _a === void 0 ? void 0 : _a.catch((e) => {
41
+ return await fileAttrDb.put(`${path}|${k}`, v)?.catch((e) => {
42
42
  console.error("couldn't store metadata on", path, String(e.message || e));
43
43
  return false;
44
- }))) !== null && _b !== void 0 ? _b : true; // if put is undefined, the value was already there
44
+ }) ?? true; // if put is undefined, the value was already there
45
45
  }
46
46
  async function loadFileAttr(path, k) {
47
- var _a;
48
- return (_a = await (fsx === null || fsx === void 0 ? void 0 : fsx.get(path, FILE_ATTR_PREFIX + k).then((x) => x === '' ? undefined : (0, cross_1.tryJson)(String(x)), () => fileAttrDb.isOpen() ? fileAttrDb.get(`${path}|${k}`) : null))) !== null && _a !== void 0 ? _a : undefined; // normalize, as we get null instead of undefined on windows
47
+ return await fsx?.get(path, FILE_ATTR_PREFIX + k)
48
+ .then((x) => x === '' ? undefined : (0, cross_1.tryJson)(String(x)), () => fileAttrDb.isOpen() ? fileAttrDb.get(`${path}|${k}`) : null)
49
+ ?? undefined; // normalize, as we get null instead of undefined on windows
49
50
  }
50
51
  async function purgeFileAttr() {
51
52
  let n = 0;
52
- await Promise.all(Array.from(fileAttrDb.keys()).map(k => (0, promises_1.access)(k).catch(() => n++ && void fileAttrDb.del(k))));
53
+ await Promise.all(Array.from(fileAttrDb.keys()).map(k => {
54
+ const [fn] = k.split('|');
55
+ return fn && (0, promises_1.access)(fn).catch(() => n++ && void fileAttrDb.del(k));
56
+ }));
53
57
  if (n)
54
58
  await fileAttrDb.rewrite();
55
59
  console.log(`removed ${n} entrie(s)`);
package/src/first.js CHANGED
@@ -10,17 +10,22 @@ function onProcessExit(cb) {
10
10
  }
11
11
  exports.quitting = false;
12
12
  onProcessExit(() => exports.quitting = true);
13
- onFirstEvent(process, ['exit', 'SIGQUIT', 'SIGTERM', 'SIGINT', 'SIGHUP'], signal => Promise.allSettled(Array.from(cbs).map(cb => cb(signal))).then(() => {
14
- console.log('quitting');
13
+ onFirstEvent(process, ['exit', 'SIGQUIT', 'SIGTERM', 'SIGINT', 'SIGHUP']).then(([signal]) => Promise.allSettled(Array.from(cbs).map(cb => cb(signal))).then(() => {
14
+ console.log('quitting', signal || '');
15
15
  process.exit(0);
16
16
  }));
17
- function onFirstEvent(emitter, events, cb) {
18
- let already = false;
19
- for (const e of events)
20
- emitter.once(e, (...args) => {
17
+ function onFirstEvent(emitter, events) {
18
+ return new Promise(resolve => {
19
+ let already = false;
20
+ for (const e of events)
21
+ emitter.on(e, listener);
22
+ function listener(...args) {
21
23
  if (already)
22
24
  return;
23
25
  already = true;
24
- cb(...args);
25
- });
26
+ for (const e of events)
27
+ emitter.removeListener(e, listener);
28
+ resolve(args);
29
+ }
30
+ });
26
31
  }
@@ -70,7 +70,7 @@ exports.frontEndApis = {
70
70
  });
71
71
  },
72
72
  async get_file_details({ uris }, ctx) {
73
- if (typeof (uris === null || uris === void 0 ? void 0 : uris[0]) !== 'string')
73
+ if (typeof uris?.[0] !== 'string')
74
74
  return new apiMiddleware_1.ApiError(const_1.HTTP_BAD_REQUEST, 'bad uris');
75
75
  const isAdmin = (0, adminApis_1.ctxAdminAccess)(ctx);
76
76
  return {
@@ -114,7 +114,7 @@ exports.frontEndApis = {
114
114
  const node = await (0, vfs_1.urlToNode)(uri, ctx);
115
115
  if (!node)
116
116
  throw new apiMiddleware_1.ApiError(const_1.HTTP_NOT_FOUND);
117
- if ((0, vfs_1.isRoot)(node) || dest.includes('/') || (0, util_files_1.dirTraversal)(dest))
117
+ if ((0, vfs_1.isRoot)(node) || dest.includes('/') || (0, util_files_1.hasDirTraversal)(dest))
118
118
  throw new apiMiddleware_1.ApiError(const_1.HTTP_FORBIDDEN);
119
119
  if (!(0, vfs_1.hasPermission)(node, 'can_delete', ctx))
120
120
  throw new apiMiddleware_1.ApiError(const_1.HTTP_UNAUTHORIZED);
@@ -147,12 +147,12 @@ exports.frontEndApis = {
147
147
  if (typeof from1 !== 'string')
148
148
  return const_1.HTTP_BAD_REQUEST;
149
149
  const srcNode = await (0, vfs_1.urlToNode)(from1, ctx);
150
- const src = srcNode === null || srcNode === void 0 ? void 0 : srcNode.source;
150
+ const src = srcNode?.source;
151
151
  if (!src)
152
152
  return const_1.HTTP_NOT_FOUND;
153
153
  const dest = (0, path_1.join)(destNode.source, (0, path_1.basename)(src));
154
154
  if (lodash_1.default.isFunction(override))
155
- return override === null || override === void 0 ? void 0 : override(srcNode, dest);
155
+ return override?.(srcNode, dest);
156
156
  return (0, vfs_1.statusCodeForMissingPerm)(srcNode, 'can_delete', ctx)
157
157
  || (0, promises_1.rename)(src, dest).catch(async (e) => {
158
158
  if (e.code !== 'EXDEV')
@@ -200,7 +200,7 @@ exports.frontEndApis = {
200
200
  let bytes = 0;
201
201
  let files = 0;
202
202
  for await (const n of (0, vfs_1.walkNode)(folder, { ctx, onlyFiles: true, depth: Infinity })) {
203
- bytes += await (0, vfs_1.nodeStats)(n).then(x => (x === null || x === void 0 ? void 0 : x.size) || 0, () => 0);
203
+ bytes += await (0, vfs_1.nodeStats)(n).then(x => x?.size || 0, () => 0);
204
204
  files++;
205
205
  partialFolderSize[id] = { bytes, files };
206
206
  }
package/src/geo.js CHANGED
@@ -20,10 +20,9 @@ setInterval(checkFiles, misc_1.DAY); // keep updated at run-time
20
20
  // benchmark: memoize can make this 44x faster
21
21
  exports.ip2country = lodash_1.default.memoize((ip) => ip2location.getCountryShortAsync(ip).then(v => v === '-' ? '' : v, () => ''));
22
22
  const geoFilter = async (ctx, next) => {
23
- var _a;
24
23
  if (enabled.get() && !(0, misc_1.isLocalHost)(ctx) && !(0, misc_1.isIpLan)(ctx.ip)) {
25
24
  const { connection } = ctx.state;
26
- const country = (_a = connection.country) !== null && _a !== void 0 ? _a : (connection.country = await (0, exports.ip2country)(ctx.ip));
25
+ const country = connection.country ??= await (0, exports.ip2country)(ctx.ip);
27
26
  if (country)
28
27
  (0, connections_1.updateConnection)(connection, { country });
29
28
  if (!ctx.state.skipFilters && allow.get() !== null)
@@ -37,14 +36,13 @@ function isOpen() {
37
36
  return Boolean(ip2location.getPackageVersion());
38
37
  }
39
38
  async function checkFiles() {
40
- var _a, _b;
41
39
  if (!enabled.get())
42
40
  return;
43
41
  const ZIP_FILE = 'IP2LOCATION-LITE-DB1.IPV6.BIN';
44
42
  const URL = `https://download.ip2location.com/lite/${ZIP_FILE}.ZIP`;
45
43
  const LOCAL_FILE = 'geo_ip.bin';
46
44
  const TEMP = LOCAL_FILE + '.downloading';
47
- const { mtime = 0 } = await (0, promises_1.stat)(LOCAL_FILE).catch(() => ({ mtime: 0 }));
45
+ const { mtime = 0 } = await (0, misc_1.statWithTimeout)(LOCAL_FILE).catch(() => ({ mtime: 0 }));
48
46
  const name = 'geo-ip db';
49
47
  const now = Date.now();
50
48
  if (+mtime < now - 31 * misc_1.DAY) // month-old or non-existing
@@ -52,16 +50,16 @@ async function checkFiles() {
52
50
  const req = await (0, misc_1.httpStream)(URL);
53
51
  console.log(`downloading ${name}`);
54
52
  await (0, misc_1.unzip)(req, path => path.toUpperCase().endsWith(ZIP_FILE) && TEMP);
55
- await (0, promises_1.stat)(TEMP); // check existence
53
+ await (0, misc_1.statWithTimeout)(TEMP); // check existence
56
54
  if (isOpen())
57
55
  ip2location.close();
58
56
  await (0, promises_1.unlink)(LOCAL_FILE).catch(() => { });
59
57
  await (0, promises_1.rename)(TEMP, LOCAL_FILE);
60
- (_b = (_a = exports.ip2country.cache).clear) === null || _b === void 0 ? void 0 : _b.call(_a);
58
+ exports.ip2country.cache.clear?.();
61
59
  console.log(`${name} download completed`);
62
60
  }
63
61
  catch (e) {
64
- console.error(`Failed to download ${name}${mtime ? ", falling back on old data" : ''}:`, (e === null || e === void 0 ? void 0 : e.message) || String(e));
62
+ console.error(`Failed to download ${name}${mtime ? ", falling back on old data" : ''}:`, e?.message || String(e));
65
63
  }
66
64
  else if (isOpen())
67
65
  return;