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