@photostructure/fs-metadata 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (116) hide show
  1. package/C++_REVIEW_TODO.md +1 -1
  2. package/CHANGELOG.md +11 -1
  3. package/CLAUDE.md +30 -23
  4. package/CONTRIBUTING.md +41 -0
  5. package/binding.gyp +2 -1
  6. package/dist/index.cjs +1439 -0
  7. package/dist/index.cjs.map +1 -0
  8. package/dist/index.d.cts +360 -0
  9. package/dist/index.d.mts +360 -0
  10. package/dist/index.d.ts +360 -0
  11. package/dist/index.mjs +1397 -0
  12. package/dist/index.mjs.map +1 -0
  13. package/package.json +19 -22
  14. package/prebuilds/darwin-arm64/@photostructure+fs-metadata.glibc.node +0 -0
  15. package/prebuilds/linux-arm64/@photostructure+fs-metadata.musl.node +0 -0
  16. package/prebuilds/linux-x64/@photostructure+fs-metadata.glibc.node +0 -0
  17. package/prebuilds/linux-x64/@photostructure+fs-metadata.musl.node +0 -0
  18. package/prebuilds/win32-x64/@photostructure+fs-metadata.glibc.node +0 -0
  19. package/scripts/check-memory.mjs +53 -173
  20. package/scripts/clang-tidy.mjs +1 -1
  21. package/scripts/sanitizers-test.sh +151 -0
  22. package/scripts/valgrind-test.mjs +1 -1
  23. package/scripts/{valgrind.sh → valgrind-test.sh} +15 -0
  24. package/src/common/error_utils.h +23 -0
  25. package/src/common/metadata_worker.h +4 -1
  26. package/src/darwin/hidden.cpp +13 -6
  27. package/src/darwin/volume_metadata.cpp +2 -2
  28. package/src/darwin/volume_mount_points.cpp +8 -1
  29. package/src/linux/blkid_cache.cpp +8 -2
  30. package/src/linux/volume_metadata.cpp +1 -1
  31. package/src/test-utils/worker-thread-helper.cjs +88 -0
  32. package/src/windows/hidden.cpp +20 -11
  33. package/coverage/base.css +0 -224
  34. package/coverage/block-navigation.js +0 -87
  35. package/coverage/favicon.png +0 -0
  36. package/coverage/index.html +0 -131
  37. package/coverage/lcov-report/base.css +0 -224
  38. package/coverage/lcov-report/block-navigation.js +0 -87
  39. package/coverage/lcov-report/favicon.png +0 -0
  40. package/coverage/lcov-report/index.html +0 -131
  41. package/coverage/lcov-report/prettify.css +0 -1
  42. package/coverage/lcov-report/prettify.js +0 -2
  43. package/coverage/lcov-report/sort-arrow-sprite.png +0 -0
  44. package/coverage/lcov-report/sorter.js +0 -196
  45. package/coverage/lcov-report/src/array.ts.html +0 -217
  46. package/coverage/lcov-report/src/async.ts.html +0 -547
  47. package/coverage/lcov-report/src/debuglog.ts.html +0 -187
  48. package/coverage/lcov-report/src/defer.ts.html +0 -175
  49. package/coverage/lcov-report/src/dirname.ts.html +0 -124
  50. package/coverage/lcov-report/src/error.ts.html +0 -322
  51. package/coverage/lcov-report/src/fs.ts.html +0 -316
  52. package/coverage/lcov-report/src/glob.ts.html +0 -472
  53. package/coverage/lcov-report/src/hidden.ts.html +0 -724
  54. package/coverage/lcov-report/src/index.html +0 -521
  55. package/coverage/lcov-report/src/index.ts.html +0 -676
  56. package/coverage/lcov-report/src/linux/dev_disk.ts.html +0 -316
  57. package/coverage/lcov-report/src/linux/index.html +0 -146
  58. package/coverage/lcov-report/src/linux/mount_points.ts.html +0 -364
  59. package/coverage/lcov-report/src/linux/mtab.ts.html +0 -493
  60. package/coverage/lcov-report/src/mount_point.ts.html +0 -106
  61. package/coverage/lcov-report/src/number.ts.html +0 -148
  62. package/coverage/lcov-report/src/object.ts.html +0 -265
  63. package/coverage/lcov-report/src/options.ts.html +0 -475
  64. package/coverage/lcov-report/src/path.ts.html +0 -268
  65. package/coverage/lcov-report/src/platform.ts.html +0 -112
  66. package/coverage/lcov-report/src/random.ts.html +0 -205
  67. package/coverage/lcov-report/src/remote_info.ts.html +0 -553
  68. package/coverage/lcov-report/src/stack_path.ts.html +0 -298
  69. package/coverage/lcov-report/src/string.ts.html +0 -382
  70. package/coverage/lcov-report/src/string_enum.ts.html +0 -208
  71. package/coverage/lcov-report/src/system_volume.ts.html +0 -301
  72. package/coverage/lcov-report/src/unc.ts.html +0 -274
  73. package/coverage/lcov-report/src/units.ts.html +0 -274
  74. package/coverage/lcov-report/src/uuid.ts.html +0 -157
  75. package/coverage/lcov-report/src/volume_health_status.ts.html +0 -259
  76. package/coverage/lcov-report/src/volume_metadata.ts.html +0 -787
  77. package/coverage/lcov-report/src/volume_mount_points.ts.html +0 -388
  78. package/coverage/lcov.info +0 -3581
  79. package/coverage/prettify.css +0 -1
  80. package/coverage/prettify.js +0 -2
  81. package/coverage/sort-arrow-sprite.png +0 -0
  82. package/coverage/sorter.js +0 -196
  83. package/coverage/src/array.ts.html +0 -217
  84. package/coverage/src/async.ts.html +0 -547
  85. package/coverage/src/debuglog.ts.html +0 -187
  86. package/coverage/src/defer.ts.html +0 -175
  87. package/coverage/src/dirname.ts.html +0 -124
  88. package/coverage/src/error.ts.html +0 -322
  89. package/coverage/src/fs.ts.html +0 -316
  90. package/coverage/src/glob.ts.html +0 -472
  91. package/coverage/src/hidden.ts.html +0 -724
  92. package/coverage/src/index.html +0 -521
  93. package/coverage/src/index.ts.html +0 -676
  94. package/coverage/src/linux/dev_disk.ts.html +0 -316
  95. package/coverage/src/linux/index.html +0 -146
  96. package/coverage/src/linux/mount_points.ts.html +0 -364
  97. package/coverage/src/linux/mtab.ts.html +0 -493
  98. package/coverage/src/mount_point.ts.html +0 -106
  99. package/coverage/src/number.ts.html +0 -148
  100. package/coverage/src/object.ts.html +0 -265
  101. package/coverage/src/options.ts.html +0 -475
  102. package/coverage/src/path.ts.html +0 -268
  103. package/coverage/src/platform.ts.html +0 -112
  104. package/coverage/src/random.ts.html +0 -205
  105. package/coverage/src/remote_info.ts.html +0 -553
  106. package/coverage/src/stack_path.ts.html +0 -298
  107. package/coverage/src/string.ts.html +0 -382
  108. package/coverage/src/string_enum.ts.html +0 -208
  109. package/coverage/src/system_volume.ts.html +0 -301
  110. package/coverage/src/unc.ts.html +0 -274
  111. package/coverage/src/units.ts.html +0 -274
  112. package/coverage/src/uuid.ts.html +0 -157
  113. package/coverage/src/volume_health_status.ts.html +0 -259
  114. package/coverage/src/volume_metadata.ts.html +0 -787
  115. package/coverage/src/volume_mount_points.ts.html +0 -388
  116. package/scripts/run-asan.sh +0 -92
package/dist/index.mjs ADDED
@@ -0,0 +1,1397 @@
1
+ // node_modules/tsup/assets/esm_shims.js
2
+ import path from "path";
3
+ import { fileURLToPath } from "url";
4
+ var getFilename = () => fileURLToPath(import.meta.url);
5
+ var getDirname = () => path.dirname(getFilename());
6
+ var __dirname = /* @__PURE__ */ getDirname();
7
+
8
+ // src/index.ts
9
+ import NodeGypBuild from "node-gyp-build";
10
+
11
+ // src/debuglog.ts
12
+ import { debuglog, format } from "util";
13
+ function defer(thunk) {
14
+ let t;
15
+ return () => t ??= thunk();
16
+ }
17
+ var debugLogContext = defer(() => {
18
+ for (const ea of ["fs-metadata", "fs-meta"]) {
19
+ if (debuglog(ea).enabled) {
20
+ return ea;
21
+ }
22
+ if (debuglog(ea.toUpperCase()).enabled) {
23
+ return ea;
24
+ }
25
+ }
26
+ return "photostructure:fs-metadata";
27
+ });
28
+ var isDebugEnabled = defer(() => {
29
+ return debuglog(debugLogContext()).enabled ?? false;
30
+ });
31
+ function debug(msg, ...args) {
32
+ if (!isDebugEnabled()) return;
33
+ const now = /* @__PURE__ */ new Date();
34
+ const timestamp = `[${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}.${now.getMilliseconds().toString().padStart(3, "0")}] ${debugLogContext()} `;
35
+ process.stderr.write(timestamp + format(msg, ...args) + "\n");
36
+ }
37
+
38
+ // src/defer.ts
39
+ function defer2(thunk) {
40
+ let computed = false;
41
+ let value;
42
+ const fn = () => {
43
+ if (!computed) {
44
+ computed = true;
45
+ value = thunk();
46
+ }
47
+ return value;
48
+ };
49
+ fn.reset = () => {
50
+ computed = false;
51
+ };
52
+ return fn;
53
+ }
54
+
55
+ // src/stack_path.ts
56
+ import { dirname } from "path";
57
+
58
+ // src/platform.ts
59
+ import { arch, platform } from "process";
60
+ var isLinux = platform === "linux";
61
+ var isWindows = platform === "win32";
62
+ var isMacOS = platform === "darwin";
63
+ var isArm = isLinux && arch.startsWith("arm");
64
+
65
+ // src/string.ts
66
+ function isString(input) {
67
+ return typeof input === "string";
68
+ }
69
+ function toS(input) {
70
+ return isString(input) ? input : input == null ? "" : String(input);
71
+ }
72
+ function isNotBlank(input) {
73
+ return typeof input === "string" && input.trim().length > 0;
74
+ }
75
+ function isBlank(input) {
76
+ return !isNotBlank(input);
77
+ }
78
+ function toNotBlank(input) {
79
+ return isNotBlank(input) ? input : void 0;
80
+ }
81
+ function decodeEscapeSequences(input) {
82
+ const escapeRegex = /\\(?:([0-7]{2,6})|x([0-9a-fA-F]{2,4}))/g;
83
+ return input.replace(escapeRegex, (match, octal, hex) => {
84
+ if (octal != null) {
85
+ return String.fromCharCode(parseInt(octal, 8));
86
+ }
87
+ if (hex != null) {
88
+ return String.fromCharCode(parseInt(hex, 16));
89
+ }
90
+ throw new Error(`Invalid escape sequence: ${match}`);
91
+ });
92
+ }
93
+ function sortObjectsByLocale(arr, fn, locales, options) {
94
+ return arr.sort((a, b) => fn(a).localeCompare(fn(b), locales, options));
95
+ }
96
+
97
+ // src/stack_path.ts
98
+ function getCallerDirname() {
99
+ const e = new Error();
100
+ if (e.stack == null) {
101
+ Error.captureStackTrace(e);
102
+ }
103
+ return dirname(extractCallerPath(e.stack));
104
+ }
105
+ var patterns = isWindows ? [
106
+ // Standard: "at functionName (C:\path\file.js:1:1)"
107
+ /\bat\s.+?\((?<path>[A-Z]:\\.+):\d+:\d+\)$/,
108
+ // direct: "at C:\path\file.js:1:1"
109
+ /\bat\s(?<path>[A-Z]:\\.+):\d+:\d+$/,
110
+ // UNC: "at functionName (\\server\share\path\file.js:1:1)"
111
+ /\bat\s.+?\((?<path>\\\\.+):\d+:\d+\)$/,
112
+ // direct: "at \\server\share\path\file.js:1:1"
113
+ /\bat\s(?<path>\\\\.+):\d+:\d+$/
114
+ ] : [
115
+ // Standard: "at functionName (/path/file.js:1:1)"
116
+ /\bat\s.+?\((?<path>\/.+?):\d+:\d+\)$/,
117
+ // Anonymous or direct: "at /path/file.js:1:1"
118
+ /\bat\s(.+[^/]\s)?(?<path>\/.+?):\d+:\d+$/
119
+ ];
120
+ var MaybeUrlRE = /^[a-z]{2,5}:\/\//i;
121
+ function extractCallerPath(stack) {
122
+ const frames = stack.split("\n").filter(Boolean);
123
+ const callerFrame = frames.findIndex(
124
+ (frame) => frame.includes("getCallerDirname")
125
+ );
126
+ if (callerFrame === -1) {
127
+ throw new Error("Invalid stack trace format: missing caller frame");
128
+ }
129
+ for (let i = callerFrame + 1; i < frames.length; i++) {
130
+ const frame = frames[i];
131
+ for (const pattern of patterns) {
132
+ const g = toS(frame).trim().match(pattern)?.groups;
133
+ if (g != null && isNotBlank(g["path"])) {
134
+ const path2 = g["path"];
135
+ if (MaybeUrlRE.test(path2)) {
136
+ try {
137
+ return new URL(path2).pathname;
138
+ } catch {
139
+ }
140
+ }
141
+ return path2;
142
+ }
143
+ }
144
+ }
145
+ throw new Error("Invalid stack trace format: no parsable frames");
146
+ }
147
+
148
+ // src/dirname.ts
149
+ function _dirname() {
150
+ try {
151
+ if (typeof __dirname !== "undefined") return __dirname;
152
+ } catch {
153
+ }
154
+ return getCallerDirname();
155
+ }
156
+
157
+ // src/fs.ts
158
+ import { statSync } from "fs";
159
+ import { opendir, stat } from "fs/promises";
160
+ import { join, resolve } from "path";
161
+
162
+ // src/async.ts
163
+ import { availableParallelism } from "os";
164
+ import { env } from "process";
165
+
166
+ // src/number.ts
167
+ function isNumber(value) {
168
+ return typeof value === "number" && isFinite(value);
169
+ }
170
+ var INTEGER_REGEX = /^-?\d+$/;
171
+ function toInt(value) {
172
+ try {
173
+ if (value == null) return;
174
+ const s = String(value).trim();
175
+ return INTEGER_REGEX.test(s) ? parseInt(s) : void 0;
176
+ } catch {
177
+ return;
178
+ }
179
+ }
180
+ function gt0(value) {
181
+ return isNumber(value) && value > 0;
182
+ }
183
+
184
+ // src/units.ts
185
+ var SecondMs = 1e3;
186
+ var MinuteMs = 60 * SecondMs;
187
+ var HourMs = 60 * MinuteMs;
188
+ var DayMs = 24 * HourMs;
189
+ var KiB = 1024;
190
+ var MiB = 1024 * KiB;
191
+ var GiB = 1024 * MiB;
192
+ var TiB = 1024 * GiB;
193
+ var f = 1023.995 / 1024;
194
+
195
+ // src/async.ts
196
+ var TimeoutError = class extends Error {
197
+ constructor(message, captureStackTrace = true) {
198
+ super(message);
199
+ this.name = "TimeoutError";
200
+ if (captureStackTrace && Error.captureStackTrace) {
201
+ Error.captureStackTrace(this, this.constructor);
202
+ }
203
+ }
204
+ };
205
+ async function withTimeout(opts) {
206
+ const desc = isBlank(opts.desc) ? "thenOrTimeout()" : opts.desc;
207
+ if (!isNumber(opts.timeoutMs)) {
208
+ throw new TypeError(
209
+ desc + ": Expected timeoutMs to be numeric, but got " + JSON.stringify(opts.timeoutMs)
210
+ );
211
+ }
212
+ const timeoutMs = Math.floor(opts.timeoutMs);
213
+ if (timeoutMs < 0) {
214
+ throw new TypeError(
215
+ desc + ": Expected timeoutMs to be > 0, but got " + timeoutMs
216
+ );
217
+ }
218
+ if (timeoutMs > DayMs) {
219
+ throw new TypeError(
220
+ desc + ": Invalid timeoutMs is too large: must be less than one day, but got " + timeoutMs
221
+ );
222
+ }
223
+ if (timeoutMs === 0) {
224
+ return opts.promise;
225
+ }
226
+ const timeoutError = new TimeoutError(
227
+ `${desc}: timeout after ${timeoutMs}ms`
228
+ );
229
+ if (env["NODE_ENV"] === "test" && timeoutMs === 1) {
230
+ timeoutError.message += "(timeout test)";
231
+ opts.promise.catch(() => {
232
+ });
233
+ throw timeoutError;
234
+ }
235
+ let timeoutId;
236
+ opts.promise.catch(() => {
237
+ }).finally(() => {
238
+ if (timeoutId != null) {
239
+ clearTimeout(timeoutId);
240
+ timeoutId = void 0;
241
+ }
242
+ });
243
+ const timeoutPromise = new Promise((_, reject) => {
244
+ timeoutId = setTimeout(() => {
245
+ if (timeoutId != null) {
246
+ timeoutError.message += "(timeout callback)";
247
+ reject(timeoutError);
248
+ }
249
+ timeoutId = void 0;
250
+ }, timeoutMs);
251
+ });
252
+ return Promise.race([opts.promise, timeoutPromise]);
253
+ }
254
+ async function mapConcurrent({
255
+ items,
256
+ fn,
257
+ maxConcurrency = availableParallelism()
258
+ }) {
259
+ if (!gt0(maxConcurrency)) {
260
+ throw new Error(
261
+ `maxConcurrency must be a positive integer, got: ${maxConcurrency}`
262
+ );
263
+ }
264
+ if (typeof fn !== "function") {
265
+ throw new TypeError(`fn must be a function, got: ${typeof fn}`);
266
+ }
267
+ const results = [];
268
+ const executing = /* @__PURE__ */ new Set();
269
+ for (const [index, item] of items.entries()) {
270
+ while (executing.size >= maxConcurrency) {
271
+ await Promise.race(executing);
272
+ }
273
+ const p = results[index] = fn(item).catch((error) => error);
274
+ executing.add(p);
275
+ p.finally(() => executing.delete(p));
276
+ }
277
+ return Promise.all(results);
278
+ }
279
+
280
+ // src/fs.ts
281
+ async function statAsync(path2, options) {
282
+ return stat(path2, options);
283
+ }
284
+ async function canStatAsync(path2) {
285
+ try {
286
+ return null != await statAsync(path2);
287
+ } catch {
288
+ return false;
289
+ }
290
+ }
291
+ async function findAncestorDir(dir, file) {
292
+ dir = resolve(dir);
293
+ try {
294
+ const s = await statAsync(join(dir, file));
295
+ if (s.isFile()) return dir;
296
+ } catch {
297
+ }
298
+ const parent = resolve(dir, "..");
299
+ return parent === dir ? void 0 : findAncestorDir(parent, file);
300
+ }
301
+ async function canReaddir(dir, timeoutMs) {
302
+ return withTimeout({
303
+ desc: "canReaddir()",
304
+ promise: _canReaddir(dir),
305
+ timeoutMs
306
+ });
307
+ }
308
+ async function _canReaddir(dir) {
309
+ await (await opendir(dir)).close();
310
+ return true;
311
+ }
312
+
313
+ // src/hidden.ts
314
+ import { rename } from "fs/promises";
315
+ import { basename, dirname as dirname3, join as join2 } from "path";
316
+
317
+ // src/object.ts
318
+ function isObject(value) {
319
+ return value != null && typeof value === "object" && !Array.isArray(value);
320
+ }
321
+ function map(obj, fn) {
322
+ return obj == null ? void 0 : fn(obj);
323
+ }
324
+ function omit(obj, ...keys) {
325
+ const result = {};
326
+ const keysSet = new Set(keys);
327
+ for (const key of Object.keys(obj)) {
328
+ if (!keysSet.has(key)) {
329
+ result[key] = obj[key];
330
+ }
331
+ }
332
+ return result;
333
+ }
334
+ function compactValues(obj) {
335
+ const result = {};
336
+ if (obj == null || !isObject(obj)) return {};
337
+ for (const [key, value] of Object.entries(obj)) {
338
+ if (value != null && (!isString(value) || isNotBlank(value))) {
339
+ result[key] = value;
340
+ }
341
+ }
342
+ return result;
343
+ }
344
+
345
+ // src/error.ts
346
+ function toMessage(context, cause) {
347
+ const causeStr = cause instanceof Error ? cause.message : typeof cause === "string" ? cause : cause ? JSON.stringify(cause) : "";
348
+ return context + (isBlank(causeStr) ? "" : ": " + causeStr);
349
+ }
350
+ var WrappedError = class extends Error {
351
+ errno;
352
+ code;
353
+ syscall;
354
+ path;
355
+ constructor(context, options) {
356
+ super(toMessage(context, options?.cause));
357
+ const cause = map(options?.cause, toError);
358
+ const opts = { ...compactValues(cause), ...compactValues(options) };
359
+ if (isNotBlank(options?.name)) {
360
+ this.name = options.name;
361
+ }
362
+ if (cause != null) {
363
+ this.cause = cause;
364
+ if (cause instanceof Error) {
365
+ this.stack = `${this.stack}
366
+ Caused by: ${cause.stack}`;
367
+ }
368
+ }
369
+ if (isNumber(opts.errno)) {
370
+ this.errno = opts.errno;
371
+ }
372
+ if (isNotBlank(opts.code)) {
373
+ this.code = opts.code;
374
+ }
375
+ if (isNotBlank(opts.syscall)) {
376
+ this.syscall = opts.syscall;
377
+ }
378
+ if (isNotBlank(options?.path)) {
379
+ this.path = options.path;
380
+ }
381
+ }
382
+ get details() {
383
+ return compactValues(omit(this, "name", "message", "cause"));
384
+ }
385
+ toString() {
386
+ const details = this.details;
387
+ const detailsStr = Object.keys(details).length === 0 ? "" : " " + JSON.stringify(details);
388
+ return `${super.toString()}${detailsStr}`;
389
+ }
390
+ };
391
+ function toError(cause) {
392
+ return cause instanceof Error ? cause : new Error(String(cause));
393
+ }
394
+
395
+ // src/path.ts
396
+ import { dirname as dirname2, resolve as resolve2 } from "path";
397
+ function normalizePath(mountPoint) {
398
+ if (isBlank(mountPoint)) return void 0;
399
+ const result = isWindows ? normalizeWindowsPath(mountPoint) : normalizePosixPath(mountPoint);
400
+ return result != null ? resolve2(result) : void 0;
401
+ }
402
+ function normalizePosixPath(mountPoint) {
403
+ if (isBlank(mountPoint)) return void 0;
404
+ if (mountPoint === "/") return mountPoint;
405
+ if (mountPoint[mountPoint.length - 1] !== "/") return mountPoint;
406
+ let end = mountPoint.length - 1;
407
+ while (end > 0 && mountPoint[end] === "/") {
408
+ end--;
409
+ }
410
+ return mountPoint.slice(0, end + 1);
411
+ }
412
+ function normalizeWindowsPath(mountPoint) {
413
+ return /^[a-z]:$/i.test(mountPoint) ? mountPoint.toUpperCase() + "\\" : mountPoint;
414
+ }
415
+ function isRootDirectory(path2) {
416
+ const n = normalizePath(path2);
417
+ return n == null ? false : isWindows ? dirname2(n) === n : n === "/";
418
+ }
419
+
420
+ // src/hidden.ts
421
+ var HiddenSupportByPlatform = {
422
+ win32: {
423
+ supported: {
424
+ dotPrefix: false,
425
+ systemFlag: true
426
+ }
427
+ },
428
+ darwin: {
429
+ supported: {
430
+ dotPrefix: true,
431
+ systemFlag: true
432
+ }
433
+ },
434
+ linux: {
435
+ supported: {
436
+ dotPrefix: true,
437
+ systemFlag: false
438
+ }
439
+ }
440
+ };
441
+ var LocalSupport = HiddenSupportByPlatform[process.platform]?.supported ?? {
442
+ dotPrefix: false,
443
+ systemFlag: false
444
+ };
445
+ async function isHiddenImpl(pathname, nativeFn2) {
446
+ const norm = normalizePath(pathname);
447
+ if (norm == null) {
448
+ throw new Error("Invalid pathname: " + JSON.stringify(pathname));
449
+ }
450
+ return LocalSupport.dotPrefix && isPosixHidden(norm) || LocalSupport.systemFlag && isSystemHidden(norm, nativeFn2);
451
+ }
452
+ async function isHiddenRecursiveImpl(path2, nativeFn2) {
453
+ let norm = normalizePath(path2);
454
+ if (norm == null) {
455
+ throw new Error("Invalid path: " + JSON.stringify(path2));
456
+ }
457
+ while (!isRootDirectory(norm)) {
458
+ if (await isHiddenImpl(norm, nativeFn2)) {
459
+ return true;
460
+ }
461
+ norm = dirname3(norm);
462
+ }
463
+ return false;
464
+ }
465
+ function createHiddenPosixPath(pathname, hidden) {
466
+ const norm = normalizePath(pathname);
467
+ if (norm == null) {
468
+ throw new Error("Invalid pathname: " + JSON.stringify(pathname));
469
+ }
470
+ const dir = dirname3(norm);
471
+ const srcBase = basename(norm).replace(/^\./, "");
472
+ const dest = join2(dir, (hidden ? "." : "") + srcBase);
473
+ return dest;
474
+ }
475
+ async function setHiddenPosix(pathname, hidden) {
476
+ if (LocalSupport.dotPrefix) {
477
+ const dest = createHiddenPosixPath(pathname, hidden);
478
+ if (pathname !== dest) await rename(pathname, dest);
479
+ return dest;
480
+ }
481
+ throw new Error("Unsupported platform");
482
+ }
483
+ function isPosixHidden(pathname) {
484
+ if (!LocalSupport.dotPrefix) return false;
485
+ const b = basename(pathname);
486
+ return b.startsWith(".") && b !== "." && b !== "..";
487
+ }
488
+ async function isSystemHidden(pathname, nativeFn2) {
489
+ if (!LocalSupport.systemFlag) {
490
+ return false;
491
+ }
492
+ if (isWindows && isRootDirectory(pathname)) {
493
+ return false;
494
+ }
495
+ return await canStatAsync(pathname) && await (await nativeFn2()).isHidden(pathname);
496
+ }
497
+ async function getHiddenMetadataImpl(pathname, nativeFn2) {
498
+ const norm = normalizePath(pathname);
499
+ if (norm == null) {
500
+ throw new Error("Invalid pathname: " + JSON.stringify(pathname));
501
+ }
502
+ const dotPrefix = isPosixHidden(norm);
503
+ const systemFlag = await isSystemHidden(norm, nativeFn2);
504
+ return {
505
+ hidden: dotPrefix || systemFlag,
506
+ dotPrefix,
507
+ systemFlag,
508
+ supported: LocalSupport
509
+ };
510
+ }
511
+ async function setHiddenImpl(pathname, hide, method, nativeFn2) {
512
+ let norm = normalizePath(pathname);
513
+ if (norm == null) {
514
+ throw new Error("Invalid pathname: " + JSON.stringify(pathname));
515
+ }
516
+ if (method === "dotPrefix" && !LocalSupport.dotPrefix) {
517
+ throw new Error("Dot prefix hiding is not supported on this platform");
518
+ }
519
+ if (method === "systemFlag" && !LocalSupport.systemFlag) {
520
+ throw new Error("System flag hiding is not supported on this platform");
521
+ }
522
+ try {
523
+ await statAsync(norm);
524
+ } catch (cause) {
525
+ throw new WrappedError("setHidden()", { cause });
526
+ }
527
+ if (isWindows && isRootDirectory(norm)) {
528
+ throw new Error("Cannot hide root directory on Windows");
529
+ }
530
+ const actions = {
531
+ dotPrefix: false,
532
+ systemFlag: false
533
+ };
534
+ let acted = false;
535
+ if (LocalSupport.dotPrefix && ["auto", "all", "dotPrefix"].includes(method)) {
536
+ if (isPosixHidden(norm) !== hide) {
537
+ norm = await setHiddenPosix(norm, hide);
538
+ actions.dotPrefix = true;
539
+ }
540
+ acted = true;
541
+ }
542
+ if (LocalSupport.systemFlag && (["all", "systemFlag"].includes(method) || !acted && method === "auto")) {
543
+ await (await nativeFn2()).setHidden(norm, hide);
544
+ actions.systemFlag = true;
545
+ }
546
+ return { pathname: norm, actions };
547
+ }
548
+
549
+ // src/options.ts
550
+ import { availableParallelism as availableParallelism2 } from "os";
551
+ var TimeoutMsDefault = 5e3;
552
+ var SystemPathPatternsDefault = [
553
+ "/boot",
554
+ "/boot/efi",
555
+ "/dev",
556
+ "/dev/**",
557
+ "/proc/**",
558
+ "/run",
559
+ "/run/credentials/**",
560
+ "/run/lock",
561
+ "/run/snapd/**",
562
+ "/run/user/*/doc",
563
+ "/run/user/*/gvfs",
564
+ "/snap/**",
565
+ "/sys/**",
566
+ "/tmp",
567
+ "/var/tmp",
568
+ // we aren't including /tmp/**, as some people temporarily mount volumes there, like /tmp/project.
569
+ "**/#snapshot",
570
+ // Synology and Kubernetes volume snapshots
571
+ // windows for linux:
572
+ "/mnt/wslg/distro",
573
+ "/mnt/wslg/doc",
574
+ "/mnt/wslg/versions.txt",
575
+ "/usr/lib/wsl/drivers",
576
+ // MacOS stuff:
577
+ "/private/var/vm",
578
+ // macOS swap
579
+ "/System/Volumes/Hardware",
580
+ "/System/Volumes/iSCPreboot",
581
+ "/System/Volumes/Preboot",
582
+ "/System/Volumes/Recovery",
583
+ "/System/Volumes/Reserved",
584
+ "/System/Volumes/Update",
585
+ "/System/Volumes/VM",
586
+ "/System/Volumes/xarts"
587
+ ];
588
+ var SystemFsTypesDefault = [
589
+ "autofs",
590
+ "binfmt_misc",
591
+ "cgroup",
592
+ "cgroup2",
593
+ "configfs",
594
+ "debugfs",
595
+ "devpts",
596
+ "devtmpfs",
597
+ "efivarfs",
598
+ "fusectl",
599
+ "fuse.snapfuse",
600
+ "hugetlbfs",
601
+ "mqueue",
602
+ "none",
603
+ "proc",
604
+ "pstore",
605
+ "rootfs",
606
+ "securityfs",
607
+ "snap*",
608
+ "squashfs",
609
+ "sysfs",
610
+ "tmpfs"
611
+ ];
612
+ var LinuxMountTablePathsDefault = [
613
+ "/proc/self/mounts",
614
+ "/proc/mounts",
615
+ "/etc/mtab"
616
+ ];
617
+ var IncludeSystemVolumesDefault = isWindows;
618
+ var OptionsDefault = {
619
+ timeoutMs: TimeoutMsDefault,
620
+ maxConcurrency: availableParallelism2(),
621
+ systemPathPatterns: [...SystemPathPatternsDefault],
622
+ systemFsTypes: [...SystemFsTypesDefault],
623
+ linuxMountTablePaths: [...LinuxMountTablePathsDefault],
624
+ includeSystemVolumes: IncludeSystemVolumesDefault
625
+ };
626
+ function optionsWithDefaults(overrides = {}) {
627
+ if (!isObject(overrides)) {
628
+ throw new TypeError(
629
+ "options(): expected an object, got " + typeof overrides + ": " + JSON.stringify(overrides)
630
+ );
631
+ }
632
+ return {
633
+ ...OptionsDefault,
634
+ ...compactValues(overrides)
635
+ };
636
+ }
637
+
638
+ // src/string_enum.ts
639
+ function stringEnum(...o) {
640
+ const set = new Set(o);
641
+ const dict = {};
642
+ for (const key of o) {
643
+ dict[key] = key;
644
+ }
645
+ return {
646
+ ...dict,
647
+ values: Object.freeze([...set]),
648
+ size: set.size,
649
+ get: (s) => s != null && set.has(s) ? s : void 0
650
+ };
651
+ }
652
+
653
+ // src/volume_health_status.ts
654
+ var VolumeHealthStatuses = stringEnum(
655
+ "healthy",
656
+ "timeout",
657
+ "inaccessible",
658
+ "disconnected",
659
+ "unknown"
660
+ );
661
+ async function directoryStatus(dir, timeoutMs, canReaddirImpl = canReaddir) {
662
+ try {
663
+ if (await canReaddirImpl(dir, timeoutMs)) {
664
+ return { status: VolumeHealthStatuses.healthy };
665
+ }
666
+ } catch (error) {
667
+ debug("[directoryStatus] %s: %s", dir, error);
668
+ let status = VolumeHealthStatuses.unknown;
669
+ if (error instanceof TimeoutError) {
670
+ status = VolumeHealthStatuses.timeout;
671
+ } else if (isObject(error) && error instanceof Error && "code" in error) {
672
+ if (error.code === "EPERM" || error.code === "EACCES") {
673
+ status = VolumeHealthStatuses.inaccessible;
674
+ }
675
+ }
676
+ return { status, error: toError(error) };
677
+ }
678
+ return { status: VolumeHealthStatuses.unknown };
679
+ }
680
+
681
+ // src/linux/dev_disk.ts
682
+ import { readdir, readlink } from "fs/promises";
683
+ import { join as join3, resolve as resolve3 } from "path";
684
+ async function getUuidFromDevDisk(devicePath) {
685
+ try {
686
+ const result = await getBasenameLinkedTo(
687
+ "/dev/disk/by-uuid",
688
+ resolve3(devicePath)
689
+ );
690
+ debug("[getUuidFromDevDisk] result: %o", result);
691
+ return result;
692
+ } catch (error) {
693
+ debug("[getUuidFromDevDisk] failed: " + error);
694
+ return;
695
+ }
696
+ }
697
+ async function getLabelFromDevDisk(devicePath) {
698
+ try {
699
+ const result = await getBasenameLinkedTo(
700
+ "/dev/disk/by-label",
701
+ resolve3(devicePath)
702
+ );
703
+ debug("[getLabelFromDevDisk] result: %o", result);
704
+ return result;
705
+ } catch (error) {
706
+ debug("[getLabelFromDevDisk] failed: " + error);
707
+ return;
708
+ }
709
+ }
710
+ async function getBasenameLinkedTo(linkDir, linkPath) {
711
+ for await (const ea of readLinks(linkDir)) {
712
+ if (ea.linkTarget === linkPath) {
713
+ return decodeEscapeSequences(ea.dirent.name);
714
+ }
715
+ }
716
+ return;
717
+ }
718
+ async function* readLinks(directory) {
719
+ for (const dirent of await readdir(directory, { withFileTypes: true })) {
720
+ if (dirent.isSymbolicLink()) {
721
+ try {
722
+ const linkTarget = resolve3(
723
+ directory,
724
+ await readlink(join3(directory, dirent.name))
725
+ );
726
+ yield { dirent, linkTarget };
727
+ } catch {
728
+ }
729
+ }
730
+ }
731
+ }
732
+
733
+ // src/linux/mount_points.ts
734
+ import { readFile } from "fs/promises";
735
+
736
+ // src/mount_point.ts
737
+ function isMountPoint(obj) {
738
+ return isObject(obj) && "mountPoint" in obj && isNotBlank(obj.mountPoint);
739
+ }
740
+
741
+ // src/remote_info.ts
742
+ function isRemoteInfo(obj) {
743
+ if (!isObject(obj)) return false;
744
+ const { remoteHost, remoteShare } = obj;
745
+ return isNotBlank(remoteHost) && isNotBlank(remoteShare);
746
+ }
747
+ var NETWORK_FS_TYPE_ARRAY = [
748
+ "9p",
749
+ "afp",
750
+ "afs",
751
+ "beegfs",
752
+ "ceph",
753
+ "cifs",
754
+ "ftp",
755
+ "fuse",
756
+ "gfs2",
757
+ "glusterfs",
758
+ "lustre",
759
+ "ncpfs",
760
+ "nfs",
761
+ "nfs4",
762
+ "smb",
763
+ "smbfs",
764
+ "sshfs",
765
+ "webdav"
766
+ ];
767
+ var NETWORK_FS_TYPES = new Set(NETWORK_FS_TYPE_ARRAY);
768
+ var FS_TYPE_ALIASES = /* @__PURE__ */ new Map([
769
+ ["nfs1", "nfs"],
770
+ ["nfs2", "nfs"],
771
+ ["nfs3", "nfs"],
772
+ ["nfs4", "nfs4"],
773
+ ["fuse.sshfs", "sshfs"],
774
+ ["sshfs.fuse", "sshfs"],
775
+ ["davfs2", "webdav"],
776
+ ["davfs", "webdav"],
777
+ ["cifs.smb", "cifs"],
778
+ ["smbfs", "cifs"],
779
+ ["cephfs", "ceph"],
780
+ ["fuse.ceph", "ceph"],
781
+ ["fuse.cephfs", "ceph"],
782
+ ["rbd", "ceph"],
783
+ ["fuse.glusterfs", "glusterfs"]
784
+ ]);
785
+ function normalizeFsType(fstype) {
786
+ const norm = toS(fstype).toLowerCase().replace(/:$/, "");
787
+ return FS_TYPE_ALIASES.get(norm) ?? norm;
788
+ }
789
+ function isRemoteFsType(fstype) {
790
+ return isNotBlank(fstype) && NETWORK_FS_TYPES.has(normalizeFsType(fstype));
791
+ }
792
+ function parseURL(s) {
793
+ try {
794
+ return isBlank(s) ? void 0 : new URL(s);
795
+ } catch {
796
+ return;
797
+ }
798
+ }
799
+ function extractRemoteInfo(fsSpec) {
800
+ if (fsSpec == null || isBlank(fsSpec)) return;
801
+ if (isWindows) {
802
+ fsSpec = fsSpec.replace(/\\/g, "/");
803
+ }
804
+ const url = parseURL(fsSpec);
805
+ if (url?.protocol === "file:") {
806
+ return {
807
+ remote: false,
808
+ uri: fsSpec
809
+ };
810
+ }
811
+ const patterns2 = [
812
+ {
813
+ // CIFS/SMB pattern: //hostname/share or //user@host/share
814
+ regex: /^\/\/(?:(?<remoteUser>[^/@]+)@)?(?<remoteHost>[^/@]+)\/(?<remoteShare>.+)$/
815
+ },
816
+ {
817
+ // sshfs pattern: sshfs#USER@HOST:REMOTE_PATH
818
+ regex: /^(?:(?<protocol>\w+)#)?(?<remoteUser>[^@]+)@(?<remoteHost>[^:]+):(?<remoteShare>.+)$/
819
+ },
820
+ {
821
+ // NFS pattern: hostname:/share
822
+ protocol: "nfs",
823
+ regex: /^(?<remoteHost>[^:]+):\/(?!\/)(?<remoteShare>.+)$/
824
+ }
825
+ ];
826
+ for (const { protocol, regex } of patterns2) {
827
+ const o = compactValues({
828
+ protocol,
829
+ remote: true,
830
+ ...fsSpec.match(regex)?.groups ?? {}
831
+ });
832
+ if (isRemoteInfo(o)) {
833
+ debug("[extractRemoteInfo] matched pattern: %o", o);
834
+ return o;
835
+ }
836
+ }
837
+ try {
838
+ const parsed = new URL(fsSpec);
839
+ if (parsed != null) {
840
+ debug("[extractRemoteInfo] parsed URL: %o", parsed);
841
+ const fstype = normalizeFsType(parsed.protocol);
842
+ if (!isRemoteFsType(fstype)) {
843
+ return {
844
+ uri: fsSpec,
845
+ remote: false
846
+ };
847
+ } else {
848
+ return compactValues({
849
+ uri: fsSpec,
850
+ protocol: fstype,
851
+ remote: true,
852
+ remoteUser: parsed.username,
853
+ remoteHost: parsed.hostname,
854
+ // URL pathname includes leading slash:
855
+ remoteShare: parsed.pathname.replace(/^\//, "")
856
+ });
857
+ }
858
+ }
859
+ } catch {
860
+ }
861
+ return;
862
+ }
863
+
864
+ // src/glob.ts
865
+ var cache = /* @__PURE__ */ new Map();
866
+ function compileGlob(patterns2) {
867
+ if (patterns2 == null || patterns2.length === 0) {
868
+ return NeverMatchRE;
869
+ }
870
+ const patternsKey = JSON.stringify(patterns2);
871
+ {
872
+ const prior = cache.get(patternsKey);
873
+ if (prior != null) {
874
+ return prior;
875
+ }
876
+ }
877
+ const sorted = patterns2.slice().filter(isNotBlank).sort();
878
+ const sortedKey = JSON.stringify(sorted);
879
+ {
880
+ const prior = cache.get(sortedKey);
881
+ if (prior != null) {
882
+ cache.set(patternsKey, prior);
883
+ return prior;
884
+ }
885
+ }
886
+ const result = _compileGlob(sorted);
887
+ if (cache.size > 256) {
888
+ cache.clear();
889
+ }
890
+ cache.set(patternsKey, result);
891
+ cache.set(sortedKey, result);
892
+ return result;
893
+ }
894
+ function _compileGlob(patterns2) {
895
+ const regexPatterns = patterns2.map((pattern) => {
896
+ let regex = "";
897
+ let i = 0;
898
+ while (i < pattern.length) {
899
+ if (pattern[i] === "*" && pattern[i + 1] === "*") {
900
+ regex += ".*";
901
+ i += 2;
902
+ if (pattern[i] === "/") {
903
+ i++;
904
+ }
905
+ continue;
906
+ }
907
+ if (pattern[i] === "*") {
908
+ regex += "[^/]*";
909
+ i++;
910
+ continue;
911
+ }
912
+ if (pattern[i] === "?") {
913
+ regex += "[^/]";
914
+ i++;
915
+ continue;
916
+ }
917
+ if (pattern[i] === ".") {
918
+ regex += "\\.";
919
+ i++;
920
+ continue;
921
+ }
922
+ if (pattern[i] === "/") {
923
+ if (i === pattern.length - 1) {
924
+ regex += "(?:/|$)";
925
+ i++;
926
+ continue;
927
+ } else if (isWindows) {
928
+ regex += "[\\/\\\\]";
929
+ i++;
930
+ continue;
931
+ }
932
+ }
933
+ if (/[+^${}()|[\]\\]/.test(pattern[i])) {
934
+ regex += "\\" + pattern[i];
935
+ i++;
936
+ continue;
937
+ }
938
+ regex += pattern[i];
939
+ i++;
940
+ }
941
+ return regex;
942
+ });
943
+ const final = regexPatterns.filter((ea) => ea.length > 0);
944
+ return final.length === 0 ? (
945
+ // Empty pattern matches nothing
946
+ NeverMatchRE
947
+ ) : new RegExp(`^(?:${final.join("|")})$`, "i");
948
+ }
949
+ var NeverMatchRE = /(?!)/;
950
+
951
+ // src/system_volume.ts
952
+ function isSystemVolume(mountPoint, fstype, config = {}) {
953
+ if (isWindows) {
954
+ const systemDrive = normalizePath(process.env["SystemDrive"]);
955
+ if (systemDrive != null && mountPoint === systemDrive) {
956
+ debug("[isSystemVolume] %s is the Windows system drive", mountPoint);
957
+ return true;
958
+ }
959
+ }
960
+ const isSystemFsType = isNotBlank(fstype) && (config.systemFsTypes ?? SystemFsTypesDefault).includes(
961
+ fstype
962
+ );
963
+ const hasSystemPath = compileGlob(
964
+ config.systemPathPatterns ?? SystemPathPatternsDefault
965
+ ).test(mountPoint);
966
+ const result = isSystemFsType || hasSystemPath;
967
+ debug("[isSystemVolume]", {
968
+ mountPoint,
969
+ fstype,
970
+ result,
971
+ isSystemFsType,
972
+ hasSystemPath
973
+ });
974
+ return result;
975
+ }
976
+ function assignSystemVolume(mp, config) {
977
+ const result = isSystemVolume(mp.mountPoint, mp.fstype, config);
978
+ if (isWindows) {
979
+ mp.isSystemVolume ??= result;
980
+ } else {
981
+ mp.isSystemVolume = result;
982
+ }
983
+ }
984
+
985
+ // src/linux/mtab.ts
986
+ function mountEntryToMountPoint(entry) {
987
+ const mountPoint = normalizePosixPath(entry.fs_file);
988
+ const fstype = toNotBlank(entry.fs_vfstype) ?? toNotBlank(entry.fs_spec);
989
+ return mountPoint == null || fstype == null ? void 0 : {
990
+ mountPoint,
991
+ fstype
992
+ };
993
+ }
994
+ function mountEntryToPartialVolumeMetadata(entry, options = {}) {
995
+ return {
996
+ mountPoint: entry.fs_file,
997
+ fstype: entry.fs_vfstype,
998
+ mountFrom: entry.fs_spec,
999
+ isSystemVolume: isSystemVolume(entry.fs_file, entry.fs_vfstype, options),
1000
+ remote: false,
1001
+ // < default to false, but it may be overridden by extractRemoteInfo
1002
+ ...extractRemoteInfo(entry.fs_spec)
1003
+ };
1004
+ }
1005
+ function parseMtab(content) {
1006
+ const entries = [];
1007
+ const lines = content.split("\n");
1008
+ for (const line of lines) {
1009
+ if (isBlank(line) || line.trim().startsWith("#")) {
1010
+ continue;
1011
+ }
1012
+ const fields = line.trim().match(/(?:[^\s\\]|\\.)+/g)?.map(decodeEscapeSequences);
1013
+ if (!fields || fields.length < 3) {
1014
+ continue;
1015
+ }
1016
+ const fs_file = normalizePosixPath(fields[1]);
1017
+ if (fs_file != null) {
1018
+ entries.push({
1019
+ fs_spec: fields[0],
1020
+ // normalizeLinuxPath DOES NOT resolve()!
1021
+ fs_file,
1022
+ fs_vfstype: fields[2],
1023
+ fs_mntops: fields[3],
1024
+ fs_freq: toInt(fields[4]),
1025
+ fs_passno: toInt(fields[5])
1026
+ });
1027
+ }
1028
+ }
1029
+ return entries;
1030
+ }
1031
+
1032
+ // src/linux/mount_points.ts
1033
+ async function getLinuxMountPoints(native, opts) {
1034
+ const o = optionsWithDefaults(opts);
1035
+ const raw = [];
1036
+ try {
1037
+ const arr = await (await native()).getGioMountPoints?.();
1038
+ debug("[getLinuxMountPoints] GIO mount points: %o", arr);
1039
+ if (arr != null) raw.push(...arr);
1040
+ } catch (error) {
1041
+ debug("Failed to get GIO mount points: %s", error);
1042
+ }
1043
+ let cause;
1044
+ for (const input of o.linuxMountTablePaths) {
1045
+ try {
1046
+ const mtabContent = await readFile(input, "utf8");
1047
+ const arr = parseMtab(mtabContent).map((ea) => mountEntryToMountPoint(ea)).filter((ea) => ea != null);
1048
+ debug("[getLinuxMountPoints] %s mount points: %o", input, arr);
1049
+ if (arr.length > 0) {
1050
+ raw.push(...arr);
1051
+ break;
1052
+ }
1053
+ } catch (error) {
1054
+ cause ??= toError(error);
1055
+ }
1056
+ }
1057
+ const byMountPoint = /* @__PURE__ */ new Map();
1058
+ for (const ea of raw) {
1059
+ const prior = byMountPoint.get(ea.mountPoint);
1060
+ const merged = { ...compactValues(prior), ...compactValues(ea) };
1061
+ if (isMountPoint(merged)) {
1062
+ byMountPoint.set(merged.mountPoint, merged);
1063
+ }
1064
+ }
1065
+ if (byMountPoint.size === 0) {
1066
+ throw new WrappedError(
1067
+ `Failed to find any mount points (tried: ${JSON.stringify(o.linuxMountTablePaths)})`,
1068
+ { cause }
1069
+ );
1070
+ }
1071
+ const results = [...byMountPoint.values()];
1072
+ debug("[getLinuxMountPoints] %o", {
1073
+ results: results.map((ea) => ea.mountPoint)
1074
+ });
1075
+ return results;
1076
+ }
1077
+ async function getLinuxMtabMetadata(mountPoint, opts) {
1078
+ let caughtError;
1079
+ const inputs = optionsWithDefaults(opts).linuxMountTablePaths;
1080
+ for (const input of inputs) {
1081
+ try {
1082
+ const mtabContent = await readFile(input, "utf8");
1083
+ for (const ea of parseMtab(mtabContent)) {
1084
+ if (ea.fs_file === mountPoint) {
1085
+ return ea;
1086
+ }
1087
+ }
1088
+ } catch (error) {
1089
+ caughtError ??= toError(error);
1090
+ }
1091
+ }
1092
+ throw new WrappedError(
1093
+ `Failed to find mount point ${mountPoint} in an linuxMountTablePaths (tried: ${JSON.stringify(inputs)})`,
1094
+ caughtError
1095
+ );
1096
+ }
1097
+
1098
+ // src/unc.ts
1099
+ function parseUNCPath(path2) {
1100
+ if (path2 == null || isBlank(path2) || !isString(path2)) {
1101
+ return;
1102
+ }
1103
+ if (!path2.startsWith("\\\\") && !path2.startsWith("//")) {
1104
+ return;
1105
+ }
1106
+ const isForwardSlash = path2.startsWith("//");
1107
+ const slashChar = isForwardSlash ? "/" : "\\";
1108
+ const parts = path2.slice(2).split(slashChar);
1109
+ if (parts.length < 2) {
1110
+ return;
1111
+ }
1112
+ const [remoteHost, remoteShare] = parts;
1113
+ if (remoteHost == null || isBlank(remoteHost) || remoteShare == null || isBlank(remoteShare)) {
1114
+ return;
1115
+ }
1116
+ const invalidChars = /[<>:"|?*]/;
1117
+ if (invalidChars.test(remoteHost) || invalidChars.test(remoteShare)) {
1118
+ return;
1119
+ }
1120
+ const wrongSlash = isForwardSlash ? "\\" : "/";
1121
+ if (path2.includes(wrongSlash)) {
1122
+ return;
1123
+ }
1124
+ return { remoteHost, remoteShare, remote: true };
1125
+ }
1126
+
1127
+ // src/uuid.ts
1128
+ var uuidRegex = /[a-z0-9][a-z0-9-]{7,}/i;
1129
+ function extractUUID(uuid) {
1130
+ return toS(uuid).match(uuidRegex)?.[0];
1131
+ }
1132
+
1133
+ // src/array.ts
1134
+ function uniqBy(arr, keyFn) {
1135
+ const seen = /* @__PURE__ */ new Set();
1136
+ return arr.filter((item) => {
1137
+ const key = keyFn(item);
1138
+ if (key == null || seen.has(key)) return false;
1139
+ seen.add(key);
1140
+ return true;
1141
+ });
1142
+ }
1143
+
1144
+ // src/volume_mount_points.ts
1145
+ async function getVolumeMountPointsImpl(opts, nativeFn2) {
1146
+ const p = _getVolumeMountPoints(opts, nativeFn2);
1147
+ return isWindows ? p : withTimeout({ desc: "getVolumeMountPoints", ...opts, promise: p });
1148
+ }
1149
+ async function _getVolumeMountPoints(o, nativeFn2) {
1150
+ debug("[getVolumeMountPoints] gathering mount points with options: %o", o);
1151
+ const raw = await (isWindows || isMacOS ? (async () => {
1152
+ debug("[getVolumeMountPoints] using native implementation");
1153
+ const points = await (await nativeFn2()).getVolumeMountPoints(o);
1154
+ debug(
1155
+ "[getVolumeMountPoints] native returned %d mount points",
1156
+ points.length
1157
+ );
1158
+ return points;
1159
+ })() : getLinuxMountPoints(nativeFn2, o));
1160
+ debug("[getVolumeMountPoints] raw mount points: %o", raw);
1161
+ const compacted = raw.map((ea) => compactValues(ea)).filter((ea) => isNotBlank(ea.mountPoint));
1162
+ for (const ea of compacted) {
1163
+ assignSystemVolume(ea, o);
1164
+ }
1165
+ const filtered = o.includeSystemVolumes ? compacted : compacted.filter((ea) => !ea.isSystemVolume);
1166
+ const uniq = uniqBy(filtered, (ea) => toNotBlank(ea.mountPoint));
1167
+ debug("[getVolumeMountPoints] found %d unique mount points", uniq.length);
1168
+ const results = sortObjectsByLocale(uniq, (ea) => ea.mountPoint);
1169
+ debug(
1170
+ "[getVolumeMountPoints] getting status for %d mount points",
1171
+ results.length
1172
+ );
1173
+ await mapConcurrent({
1174
+ maxConcurrency: o.maxConcurrency,
1175
+ items: results.filter(
1176
+ // trust but verify
1177
+ (ea) => isBlank(ea.status) || ea.status === "healthy"
1178
+ ),
1179
+ fn: async (mp) => {
1180
+ debug("[getVolumeMountPoints] checking status of %s", mp.mountPoint);
1181
+ mp.status = (await directoryStatus(mp.mountPoint, o.timeoutMs)).status;
1182
+ debug(
1183
+ "[getVolumeMountPoints] status for %s: %s",
1184
+ mp.mountPoint,
1185
+ mp.status
1186
+ );
1187
+ }
1188
+ });
1189
+ debug(
1190
+ "[getVolumeMountPoints] completed with %d mount points",
1191
+ results.length
1192
+ );
1193
+ return results;
1194
+ }
1195
+
1196
+ // src/volume_metadata.ts
1197
+ async function getVolumeMetadataImpl(o, nativeFn2) {
1198
+ if (isBlank(o.mountPoint)) {
1199
+ throw new TypeError(
1200
+ "Invalid mountPoint: got " + JSON.stringify(o.mountPoint)
1201
+ );
1202
+ }
1203
+ const p = _getVolumeMetadata(o, nativeFn2);
1204
+ return isWindows ? p : withTimeout({
1205
+ desc: "getVolumeMetadata()",
1206
+ timeoutMs: o.timeoutMs,
1207
+ promise: p
1208
+ });
1209
+ }
1210
+ async function _getVolumeMetadata(o, nativeFn2) {
1211
+ o = optionsWithDefaults(o);
1212
+ const norm = normalizePath(o.mountPoint);
1213
+ if (norm == null) {
1214
+ throw new Error("Invalid mountPoint: " + JSON.stringify(o.mountPoint));
1215
+ }
1216
+ o.mountPoint = norm;
1217
+ debug(
1218
+ "[getVolumeMetadata] starting metadata collection for %s",
1219
+ o.mountPoint
1220
+ );
1221
+ debug("[getVolumeMetadata] options: %o", o);
1222
+ const { status, error } = await directoryStatus(o.mountPoint, o.timeoutMs);
1223
+ if (status !== VolumeHealthStatuses.healthy) {
1224
+ debug("[getVolumeMetadata] directoryStatus error: %s", error);
1225
+ throw error ?? new Error("Volume not healthy: " + status);
1226
+ }
1227
+ debug("[getVolumeMetadata] readdir status: %s", status);
1228
+ let remote = false;
1229
+ let mtabInfo;
1230
+ let device;
1231
+ if (isLinux) {
1232
+ debug("[getVolumeMetadata] collecting Linux mtab info");
1233
+ try {
1234
+ const m = await getLinuxMtabMetadata(o.mountPoint, o);
1235
+ mtabInfo = mountEntryToPartialVolumeMetadata(m, o);
1236
+ debug("[getVolumeMetadata] mtab info: %o", mtabInfo);
1237
+ if (mtabInfo.remote) {
1238
+ remote = true;
1239
+ }
1240
+ if (isNotBlank(m.fs_spec)) {
1241
+ device = m.fs_spec;
1242
+ }
1243
+ } catch (err) {
1244
+ debug("[getVolumeMetadata] failed to get mtab info: " + err);
1245
+ }
1246
+ }
1247
+ if (isNotBlank(device)) {
1248
+ o.device = device;
1249
+ debug("[getVolumeMetadata] using device: %s", device);
1250
+ }
1251
+ debug("[getVolumeMetadata] requesting native metadata");
1252
+ const metadata = await (await nativeFn2()).getVolumeMetadata(o);
1253
+ debug("[getVolumeMetadata] native metadata: %o", metadata);
1254
+ const remoteInfo = mtabInfo ?? extractRemoteInfo(metadata.uri) ?? extractRemoteInfo(metadata.mountFrom) ?? (isWindows ? parseUNCPath(o.mountPoint) : void 0);
1255
+ debug("[getVolumeMetadata] extracted remote info: %o", remoteInfo);
1256
+ remote ||= isRemoteFsType(metadata.fstype) || (remoteInfo?.remote ?? metadata.remote ?? false);
1257
+ debug("[getVolumeMetadata] assembling: %o", {
1258
+ status,
1259
+ mtabInfo,
1260
+ remoteInfo,
1261
+ metadata,
1262
+ mountPoint: o.mountPoint,
1263
+ remote
1264
+ });
1265
+ const result = compactValues({
1266
+ status,
1267
+ // < let the implementation's status win by having this first
1268
+ ...compactValues(remoteInfo),
1269
+ ...compactValues(metadata),
1270
+ ...compactValues(mtabInfo),
1271
+ mountPoint: o.mountPoint,
1272
+ remote
1273
+ });
1274
+ if (isLinux && isNotBlank(device)) {
1275
+ result.uuid ??= await getUuidFromDevDisk(device) ?? "";
1276
+ result.label ??= await getLabelFromDevDisk(device) ?? "";
1277
+ }
1278
+ assignSystemVolume(result, o);
1279
+ result.uuid = extractUUID(result.uuid) ?? result.uuid ?? "";
1280
+ debug("[getVolumeMetadata] final result for %s: %o", o.mountPoint, result);
1281
+ return compactValues(result);
1282
+ }
1283
+ async function getAllVolumeMetadataImpl(opts, nativeFn2) {
1284
+ const o = optionsWithDefaults(opts);
1285
+ debug("[getAllVolumeMetadata] starting with options: %o", o);
1286
+ const arr = await getVolumeMountPointsImpl(o, nativeFn2);
1287
+ debug("[getAllVolumeMetadata] found %d mount points", arr.length);
1288
+ const unhealthyMountPoints = arr.filter(
1289
+ (ea) => ea.status != null && ea.status !== VolumeHealthStatuses.healthy
1290
+ ).map((ea) => ({
1291
+ mountPoint: ea.mountPoint,
1292
+ error: new WrappedError("volume not healthy: " + ea.status, {
1293
+ name: "Skipped"
1294
+ })
1295
+ }));
1296
+ const includeSystemVolumes = opts?.includeSystemVolumes ?? IncludeSystemVolumesDefault;
1297
+ const systemMountPoints = includeSystemVolumes ? [] : arr.filter((ea) => ea.isSystemVolume).map((ea) => ({
1298
+ mountPoint: ea.mountPoint,
1299
+ error: new WrappedError("system volume", { name: "Skipped" })
1300
+ }));
1301
+ const healthy = arr.filter(
1302
+ (ea) => ea.status == null || ea.status === VolumeHealthStatuses.healthy
1303
+ );
1304
+ debug("[getAllVolumeMetadata] ", {
1305
+ allMountPoints: arr.map((ea) => ea.mountPoint),
1306
+ healthyMountPoints: healthy.map((ea) => ea.mountPoint)
1307
+ });
1308
+ debug(
1309
+ "[getAllVolumeMetadata] processing %d healthy volumes with max concurrency %d",
1310
+ healthy.length,
1311
+ o.maxConcurrency
1312
+ );
1313
+ const results = await mapConcurrent({
1314
+ maxConcurrency: o.maxConcurrency,
1315
+ items: opts?.includeSystemVolumes ?? IncludeSystemVolumesDefault ? healthy : healthy.filter((ea) => !ea.isSystemVolume),
1316
+ fn: async (mp) => getVolumeMetadataImpl({ ...mp, ...o }, nativeFn2).catch((error) => ({
1317
+ mountPoint: mp.mountPoint,
1318
+ error
1319
+ }))
1320
+ });
1321
+ debug("[getAllVolumeMetadata] completed processing all volumes");
1322
+ return arr.map(
1323
+ (result) => results.find((ea) => ea.mountPoint === result.mountPoint) ?? unhealthyMountPoints.find(
1324
+ (ea) => ea.mountPoint === result.mountPoint
1325
+ ) ?? systemMountPoints.find((ea) => ea.mountPoint === result.mountPoint) ?? {
1326
+ ...result,
1327
+ error: new WrappedError("Mount point metadata not retrieved", {
1328
+ name: "NotApplicableError"
1329
+ })
1330
+ }
1331
+ );
1332
+ }
1333
+
1334
+ // src/index.ts
1335
+ var nativeFn = defer2(async () => {
1336
+ const start = Date.now();
1337
+ try {
1338
+ const dirname4 = _dirname();
1339
+ const dir = await findAncestorDir(dirname4, "binding.gyp");
1340
+ if (dir == null) {
1341
+ throw new Error(
1342
+ "Could not find bindings.gyp in any ancestor directory of " + dirname4
1343
+ );
1344
+ }
1345
+ const bindings = NodeGypBuild(dir);
1346
+ bindings.setDebugLogging(isDebugEnabled());
1347
+ bindings.setDebugPrefix(debugLogContext() + ":native");
1348
+ return bindings;
1349
+ } catch (error) {
1350
+ debug("Loading native bindings failed: %s", error);
1351
+ throw error;
1352
+ } finally {
1353
+ debug(`Native bindings took %d ms to load`, Date.now() - start);
1354
+ }
1355
+ });
1356
+ function getVolumeMountPoints(opts) {
1357
+ return getVolumeMountPointsImpl(optionsWithDefaults(opts), nativeFn);
1358
+ }
1359
+ function getVolumeMetadata(mountPoint, opts) {
1360
+ return getVolumeMetadataImpl(
1361
+ { ...optionsWithDefaults(opts), mountPoint },
1362
+ nativeFn
1363
+ );
1364
+ }
1365
+ function getAllVolumeMetadata(opts) {
1366
+ return getAllVolumeMetadataImpl(optionsWithDefaults(opts), nativeFn);
1367
+ }
1368
+ function isHidden(pathname) {
1369
+ return isHiddenImpl(pathname, nativeFn);
1370
+ }
1371
+ function isHiddenRecursive(pathname) {
1372
+ return isHiddenRecursiveImpl(pathname, nativeFn);
1373
+ }
1374
+ function getHiddenMetadata(pathname) {
1375
+ return getHiddenMetadataImpl(pathname, nativeFn);
1376
+ }
1377
+ function setHidden(pathname, hidden, method = "auto") {
1378
+ return setHiddenImpl(pathname, hidden, method, nativeFn);
1379
+ }
1380
+ export {
1381
+ IncludeSystemVolumesDefault,
1382
+ LinuxMountTablePathsDefault,
1383
+ OptionsDefault,
1384
+ SystemFsTypesDefault,
1385
+ SystemPathPatternsDefault,
1386
+ TimeoutMsDefault,
1387
+ VolumeHealthStatuses,
1388
+ getAllVolumeMetadata,
1389
+ getHiddenMetadata,
1390
+ getVolumeMetadata,
1391
+ getVolumeMountPoints,
1392
+ isHidden,
1393
+ isHiddenRecursive,
1394
+ optionsWithDefaults,
1395
+ setHidden
1396
+ };
1397
+ //# sourceMappingURL=index.mjs.map