UNPKG

85.8 kBJavaScriptView Raw
1"use strict";
2var __extends = (this && this.__extends) || (function () {
3 var extendStatics = function (d, b) {
4 extendStatics = Object.setPrototypeOf ||
5 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
6 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
7 return extendStatics(d, b);
8 };
9 return function (d, b) {
10 if (typeof b !== "function" && b !== null)
11 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
12 extendStatics(d, b);
13 function __() { this.constructor = d; }
14 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
15 };
16})();
17var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
18 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
19 if (ar || !(i in from)) {
20 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
21 ar[i] = from[i];
22 }
23 }
24 return to.concat(ar || Array.prototype.slice.call(from));
25};
26Object.defineProperty(exports, "__esModule", { value: true });
27exports.FSWatcher = exports.StatWatcher = exports.Volume = exports.toUnixTimestamp = exports.bufferToEncoding = exports.dataToBuffer = exports.dataToStr = exports.pathToSteps = exports.filenameToSteps = exports.pathToFilename = exports.flagsToNumber = exports.FLAGS = void 0;
28var pathModule = require("path");
29var node_1 = require("./node");
30var Stats_1 = require("./Stats");
31var Dirent_1 = require("./Dirent");
32var buffer_1 = require("./internal/buffer");
33var setImmediate_1 = require("./setImmediate");
34var process_1 = require("./process");
35var setTimeoutUnref_1 = require("./setTimeoutUnref");
36var stream_1 = require("stream");
37var constants_1 = require("./constants");
38var events_1 = require("events");
39var encoding_1 = require("./encoding");
40var errors = require("./internal/errors");
41var util = require("util");
42var promises_1 = require("./promises");
43var resolveCrossPlatform = pathModule.resolve;
44var O_RDONLY = constants_1.constants.O_RDONLY, O_WRONLY = constants_1.constants.O_WRONLY, O_RDWR = constants_1.constants.O_RDWR, O_CREAT = constants_1.constants.O_CREAT, O_EXCL = constants_1.constants.O_EXCL, O_TRUNC = constants_1.constants.O_TRUNC, O_APPEND = constants_1.constants.O_APPEND, O_SYNC = constants_1.constants.O_SYNC, O_DIRECTORY = constants_1.constants.O_DIRECTORY, F_OK = constants_1.constants.F_OK, COPYFILE_EXCL = constants_1.constants.COPYFILE_EXCL, COPYFILE_FICLONE_FORCE = constants_1.constants.COPYFILE_FICLONE_FORCE;
45var _a = pathModule.posix ? pathModule.posix : pathModule, sep = _a.sep, relative = _a.relative, join = _a.join, dirname = _a.dirname;
46var isWin = process_1.default.platform === 'win32';
47var kMinPoolSpace = 128;
48// const kMaxLength = require('buffer').kMaxLength;
49// ---------------------------------------- Error messages
50// TODO: Use `internal/errors.js` in the future.
51var ERRSTR = {
52 PATH_STR: 'path must be a string or Buffer',
53 // FD: 'file descriptor must be a unsigned 32-bit integer',
54 FD: 'fd must be a file descriptor',
55 MODE_INT: 'mode must be an int',
56 CB: 'callback must be a function',
57 UID: 'uid must be an unsigned int',
58 GID: 'gid must be an unsigned int',
59 LEN: 'len must be an integer',
60 ATIME: 'atime must be an integer',
61 MTIME: 'mtime must be an integer',
62 PREFIX: 'filename prefix is required',
63 BUFFER: 'buffer must be an instance of Buffer or StaticBuffer',
64 OFFSET: 'offset must be an integer',
65 LENGTH: 'length must be an integer',
66 POSITION: 'position must be an integer',
67};
68var ERRSTR_OPTS = function (tipeof) { return "Expected options to be either an object or a string, but got " + tipeof + " instead"; };
69// const ERRSTR_FLAG = flag => `Unknown file open flag: ${flag}`;
70var ENOENT = 'ENOENT';
71var EBADF = 'EBADF';
72var EINVAL = 'EINVAL';
73var EPERM = 'EPERM';
74var EPROTO = 'EPROTO';
75var EEXIST = 'EEXIST';
76var ENOTDIR = 'ENOTDIR';
77var EMFILE = 'EMFILE';
78var EACCES = 'EACCES';
79var EISDIR = 'EISDIR';
80var ENOTEMPTY = 'ENOTEMPTY';
81var ENOSYS = 'ENOSYS';
82var ERR_FS_EISDIR = 'ERR_FS_EISDIR';
83function formatError(errorCode, func, path, path2) {
84 if (func === void 0) { func = ''; }
85 if (path === void 0) { path = ''; }
86 if (path2 === void 0) { path2 = ''; }
87 var pathFormatted = '';
88 if (path)
89 pathFormatted = " '" + path + "'";
90 if (path2)
91 pathFormatted += " -> '" + path2 + "'";
92 switch (errorCode) {
93 case ENOENT:
94 return "ENOENT: no such file or directory, " + func + pathFormatted;
95 case EBADF:
96 return "EBADF: bad file descriptor, " + func + pathFormatted;
97 case EINVAL:
98 return "EINVAL: invalid argument, " + func + pathFormatted;
99 case EPERM:
100 return "EPERM: operation not permitted, " + func + pathFormatted;
101 case EPROTO:
102 return "EPROTO: protocol error, " + func + pathFormatted;
103 case EEXIST:
104 return "EEXIST: file already exists, " + func + pathFormatted;
105 case ENOTDIR:
106 return "ENOTDIR: not a directory, " + func + pathFormatted;
107 case EISDIR:
108 return "EISDIR: illegal operation on a directory, " + func + pathFormatted;
109 case EACCES:
110 return "EACCES: permission denied, " + func + pathFormatted;
111 case ENOTEMPTY:
112 return "ENOTEMPTY: directory not empty, " + func + pathFormatted;
113 case EMFILE:
114 return "EMFILE: too many open files, " + func + pathFormatted;
115 case ENOSYS:
116 return "ENOSYS: function not implemented, " + func + pathFormatted;
117 case ERR_FS_EISDIR:
118 return "[ERR_FS_EISDIR]: Path is a directory: " + func + " returned EISDIR (is a directory) " + path;
119 default:
120 return errorCode + ": error occurred, " + func + pathFormatted;
121 }
122}
123function createError(errorCode, func, path, path2, Constructor) {
124 if (func === void 0) { func = ''; }
125 if (path === void 0) { path = ''; }
126 if (path2 === void 0) { path2 = ''; }
127 if (Constructor === void 0) { Constructor = Error; }
128 var error = new Constructor(formatError(errorCode, func, path, path2));
129 error.code = errorCode;
130 return error;
131}
132// ---------------------------------------- Flags
133// List of file `flags` as defined by Node.
134var FLAGS;
135(function (FLAGS) {
136 // Open file for reading. An exception occurs if the file does not exist.
137 FLAGS[FLAGS["r"] = O_RDONLY] = "r";
138 // Open file for reading and writing. An exception occurs if the file does not exist.
139 FLAGS[FLAGS["r+"] = O_RDWR] = "r+";
140 // Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache.
141 FLAGS[FLAGS["rs"] = O_RDONLY | O_SYNC] = "rs";
142 FLAGS[FLAGS["sr"] = FLAGS.rs] = "sr";
143 // Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution.
144 FLAGS[FLAGS["rs+"] = O_RDWR | O_SYNC] = "rs+";
145 FLAGS[FLAGS["sr+"] = FLAGS['rs+']] = "sr+";
146 // Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
147 FLAGS[FLAGS["w"] = O_WRONLY | O_CREAT | O_TRUNC] = "w";
148 // Like 'w' but fails if path exists.
149 FLAGS[FLAGS["wx"] = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL] = "wx";
150 FLAGS[FLAGS["xw"] = FLAGS.wx] = "xw";
151 // Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
152 FLAGS[FLAGS["w+"] = O_RDWR | O_CREAT | O_TRUNC] = "w+";
153 // Like 'w+' but fails if path exists.
154 FLAGS[FLAGS["wx+"] = O_RDWR | O_CREAT | O_TRUNC | O_EXCL] = "wx+";
155 FLAGS[FLAGS["xw+"] = FLAGS['wx+']] = "xw+";
156 // Open file for appending. The file is created if it does not exist.
157 FLAGS[FLAGS["a"] = O_WRONLY | O_APPEND | O_CREAT] = "a";
158 // Like 'a' but fails if path exists.
159 FLAGS[FLAGS["ax"] = O_WRONLY | O_APPEND | O_CREAT | O_EXCL] = "ax";
160 FLAGS[FLAGS["xa"] = FLAGS.ax] = "xa";
161 // Open file for reading and appending. The file is created if it does not exist.
162 FLAGS[FLAGS["a+"] = O_RDWR | O_APPEND | O_CREAT] = "a+";
163 // Like 'a+' but fails if path exists.
164 FLAGS[FLAGS["ax+"] = O_RDWR | O_APPEND | O_CREAT | O_EXCL] = "ax+";
165 FLAGS[FLAGS["xa+"] = FLAGS['ax+']] = "xa+";
166})(FLAGS = exports.FLAGS || (exports.FLAGS = {}));
167function flagsToNumber(flags) {
168 if (typeof flags === 'number')
169 return flags;
170 if (typeof flags === 'string') {
171 var flagsNum = FLAGS[flags];
172 if (typeof flagsNum !== 'undefined')
173 return flagsNum;
174 }
175 // throw new TypeError(formatError(ERRSTR_FLAG(flags)));
176 throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags);
177}
178exports.flagsToNumber = flagsToNumber;
179// ---------------------------------------- Options
180function getOptions(defaults, options) {
181 var opts;
182 if (!options)
183 return defaults;
184 else {
185 var tipeof = typeof options;
186 switch (tipeof) {
187 case 'string':
188 opts = Object.assign({}, defaults, { encoding: options });
189 break;
190 case 'object':
191 opts = Object.assign({}, defaults, options);
192 break;
193 default:
194 throw TypeError(ERRSTR_OPTS(tipeof));
195 }
196 }
197 if (opts.encoding !== 'buffer')
198 (0, encoding_1.assertEncoding)(opts.encoding);
199 return opts;
200}
201function optsGenerator(defaults) {
202 return function (options) { return getOptions(defaults, options); };
203}
204function validateCallback(callback) {
205 if (typeof callback !== 'function')
206 throw TypeError(ERRSTR.CB);
207 return callback;
208}
209function optsAndCbGenerator(getOpts) {
210 return function (options, callback) {
211 return typeof options === 'function' ? [getOpts(), options] : [getOpts(options), validateCallback(callback)];
212 };
213}
214var optsDefaults = {
215 encoding: 'utf8',
216};
217var getDefaultOpts = optsGenerator(optsDefaults);
218var getDefaultOptsAndCb = optsAndCbGenerator(getDefaultOpts);
219var readFileOptsDefaults = {
220 flag: 'r',
221};
222var getReadFileOptions = optsGenerator(readFileOptsDefaults);
223var writeFileDefaults = {
224 encoding: 'utf8',
225 mode: 438 /* DEFAULT */,
226 flag: FLAGS[FLAGS.w],
227};
228var getWriteFileOptions = optsGenerator(writeFileDefaults);
229var appendFileDefaults = {
230 encoding: 'utf8',
231 mode: 438 /* DEFAULT */,
232 flag: FLAGS[FLAGS.a],
233};
234var getAppendFileOpts = optsGenerator(appendFileDefaults);
235var getAppendFileOptsAndCb = optsAndCbGenerator(getAppendFileOpts);
236var realpathDefaults = optsDefaults;
237var getRealpathOptions = optsGenerator(realpathDefaults);
238var getRealpathOptsAndCb = optsAndCbGenerator(getRealpathOptions);
239var mkdirDefaults = {
240 mode: 511 /* DIR */,
241 recursive: false,
242};
243var getMkdirOptions = function (options) {
244 if (typeof options === 'number')
245 return Object.assign({}, mkdirDefaults, { mode: options });
246 return Object.assign({}, mkdirDefaults, options);
247};
248var rmdirDefaults = {
249 recursive: false,
250};
251var getRmdirOptions = function (options) {
252 return Object.assign({}, rmdirDefaults, options);
253};
254var getRmOpts = optsGenerator(optsDefaults);
255var getRmOptsAndCb = optsAndCbGenerator(getRmOpts);
256var readdirDefaults = {
257 encoding: 'utf8',
258 withFileTypes: false,
259};
260var getReaddirOptions = optsGenerator(readdirDefaults);
261var getReaddirOptsAndCb = optsAndCbGenerator(getReaddirOptions);
262var statDefaults = {
263 bigint: false,
264};
265var getStatOptions = function (options) {
266 if (options === void 0) { options = {}; }
267 return Object.assign({}, statDefaults, options);
268};
269var getStatOptsAndCb = function (options, callback) {
270 return typeof options === 'function' ? [getStatOptions(), options] : [getStatOptions(options), validateCallback(callback)];
271};
272// ---------------------------------------- Utility functions
273function getPathFromURLPosix(url) {
274 if (url.hostname !== '') {
275 throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process_1.default.platform);
276 }
277 var pathname = url.pathname;
278 for (var n = 0; n < pathname.length; n++) {
279 if (pathname[n] === '%') {
280 var third = pathname.codePointAt(n + 2) | 0x20;
281 if (pathname[n + 1] === '2' && third === 102) {
282 throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters');
283 }
284 }
285 }
286 return decodeURIComponent(pathname);
287}
288function pathToFilename(path) {
289 if (typeof path !== 'string' && !buffer_1.Buffer.isBuffer(path)) {
290 try {
291 if (!(path instanceof require('url').URL))
292 throw new TypeError(ERRSTR.PATH_STR);
293 }
294 catch (err) {
295 throw new TypeError(ERRSTR.PATH_STR);
296 }
297 path = getPathFromURLPosix(path);
298 }
299 var pathString = String(path);
300 nullCheck(pathString);
301 // return slash(pathString);
302 return pathString;
303}
304exports.pathToFilename = pathToFilename;
305var resolve = function (filename, base) {
306 if (base === void 0) { base = process_1.default.cwd(); }
307 return resolveCrossPlatform(base, filename);
308};
309if (isWin) {
310 var _resolve_1 = resolve;
311 var unixify_1 = require('fs-monkey/lib/correctPath').unixify;
312 resolve = function (filename, base) { return unixify_1(_resolve_1(filename, base)); };
313}
314function filenameToSteps(filename, base) {
315 var fullPath = resolve(filename, base);
316 var fullPathSansSlash = fullPath.substr(1);
317 if (!fullPathSansSlash)
318 return [];
319 return fullPathSansSlash.split(sep);
320}
321exports.filenameToSteps = filenameToSteps;
322function pathToSteps(path) {
323 return filenameToSteps(pathToFilename(path));
324}
325exports.pathToSteps = pathToSteps;
326function dataToStr(data, encoding) {
327 if (encoding === void 0) { encoding = encoding_1.ENCODING_UTF8; }
328 if (buffer_1.Buffer.isBuffer(data))
329 return data.toString(encoding);
330 else if (data instanceof Uint8Array)
331 return (0, buffer_1.bufferFrom)(data).toString(encoding);
332 else
333 return String(data);
334}
335exports.dataToStr = dataToStr;
336function dataToBuffer(data, encoding) {
337 if (encoding === void 0) { encoding = encoding_1.ENCODING_UTF8; }
338 if (buffer_1.Buffer.isBuffer(data))
339 return data;
340 else if (data instanceof Uint8Array)
341 return (0, buffer_1.bufferFrom)(data);
342 else
343 return (0, buffer_1.bufferFrom)(String(data), encoding);
344}
345exports.dataToBuffer = dataToBuffer;
346function bufferToEncoding(buffer, encoding) {
347 if (!encoding || encoding === 'buffer')
348 return buffer;
349 else
350 return buffer.toString(encoding);
351}
352exports.bufferToEncoding = bufferToEncoding;
353function nullCheck(path, callback) {
354 if (('' + path).indexOf('\u0000') !== -1) {
355 var er = new Error('Path must be a string without null bytes');
356 er.code = ENOENT;
357 if (typeof callback !== 'function')
358 throw er;
359 process_1.default.nextTick(callback, er);
360 return false;
361 }
362 return true;
363}
364function _modeToNumber(mode, def) {
365 if (typeof mode === 'number')
366 return mode;
367 if (typeof mode === 'string')
368 return parseInt(mode, 8);
369 if (def)
370 return modeToNumber(def);
371 return undefined;
372}
373function modeToNumber(mode, def) {
374 var result = _modeToNumber(mode, def);
375 if (typeof result !== 'number' || isNaN(result))
376 throw new TypeError(ERRSTR.MODE_INT);
377 return result;
378}
379function isFd(path) {
380 return path >>> 0 === path;
381}
382function validateFd(fd) {
383 if (!isFd(fd))
384 throw TypeError(ERRSTR.FD);
385}
386// converts Date or number to a fractional UNIX timestamp
387function toUnixTimestamp(time) {
388 // tslint:disable-next-line triple-equals
389 if (typeof time === 'string' && +time == time) {
390 return +time;
391 }
392 if (time instanceof Date) {
393 return time.getTime() / 1000;
394 }
395 if (isFinite(time)) {
396 if (time < 0) {
397 return Date.now() / 1000;
398 }
399 return time;
400 }
401 throw new Error('Cannot parse time: ' + time);
402}
403exports.toUnixTimestamp = toUnixTimestamp;
404function validateUid(uid) {
405 if (typeof uid !== 'number')
406 throw TypeError(ERRSTR.UID);
407}
408function validateGid(gid) {
409 if (typeof gid !== 'number')
410 throw TypeError(ERRSTR.GID);
411}
412function flattenJSON(nestedJSON) {
413 var flatJSON = {};
414 function flatten(pathPrefix, node) {
415 for (var path in node) {
416 var contentOrNode = node[path];
417 var joinedPath = join(pathPrefix, path);
418 if (typeof contentOrNode === 'string') {
419 flatJSON[joinedPath] = contentOrNode;
420 }
421 else if (typeof contentOrNode === 'object' && contentOrNode !== null && Object.keys(contentOrNode).length > 0) {
422 // empty directories need an explicit entry and therefore get handled in `else`, non-empty ones are implicitly considered
423 flatten(joinedPath, contentOrNode);
424 }
425 else {
426 // without this branch null, empty-object or non-object entries would not be handled in the same way
427 // by both fromJSON() and fromNestedJSON()
428 flatJSON[joinedPath] = null;
429 }
430 }
431 }
432 flatten('', nestedJSON);
433 return flatJSON;
434}
435/**
436 * `Volume` represents a file system.
437 */
438var Volume = /** @class */ (function () {
439 function Volume(props) {
440 if (props === void 0) { props = {}; }
441 // I-node number counter.
442 this.ino = 0;
443 // A mapping for i-node numbers to i-nodes (`Node`);
444 this.inodes = {};
445 // List of released i-node numbers, for reuse.
446 this.releasedInos = [];
447 // A mapping for file descriptors to `File`s.
448 this.fds = {};
449 // A list of reusable (opened and closed) file descriptors, that should be
450 // used first before creating a new file descriptor.
451 this.releasedFds = [];
452 // Max number of open files.
453 this.maxFiles = 10000;
454 // Current number of open files.
455 this.openFiles = 0;
456 this.promisesApi = (0, promises_1.default)(this);
457 this.statWatchers = {};
458 this.props = Object.assign({ Node: node_1.Node, Link: node_1.Link, File: node_1.File }, props);
459 var root = this.createLink();
460 root.setNode(this.createNode(true));
461 var self = this; // tslint:disable-line no-this-assignment
462 this.StatWatcher = /** @class */ (function (_super) {
463 __extends(StatWatcher, _super);
464 function StatWatcher() {
465 return _super.call(this, self) || this;
466 }
467 return StatWatcher;
468 }(StatWatcher));
469 var _ReadStream = FsReadStream;
470 this.ReadStream = /** @class */ (function (_super) {
471 __extends(class_1, _super);
472 function class_1() {
473 var args = [];
474 for (var _i = 0; _i < arguments.length; _i++) {
475 args[_i] = arguments[_i];
476 }
477 return _super.apply(this, __spreadArray([self], args, false)) || this;
478 }
479 return class_1;
480 }(_ReadStream));
481 var _WriteStream = FsWriteStream;
482 this.WriteStream = /** @class */ (function (_super) {
483 __extends(class_2, _super);
484 function class_2() {
485 var args = [];
486 for (var _i = 0; _i < arguments.length; _i++) {
487 args[_i] = arguments[_i];
488 }
489 return _super.apply(this, __spreadArray([self], args, false)) || this;
490 }
491 return class_2;
492 }(_WriteStream));
493 this.FSWatcher = /** @class */ (function (_super) {
494 __extends(FSWatcher, _super);
495 function FSWatcher() {
496 return _super.call(this, self) || this;
497 }
498 return FSWatcher;
499 }(FSWatcher));
500 // root.setChild('.', root);
501 // root.getNode().nlink++;
502 // root.setChild('..', root);
503 // root.getNode().nlink++;
504 this.root = root;
505 }
506 Volume.fromJSON = function (json, cwd) {
507 var vol = new Volume();
508 vol.fromJSON(json, cwd);
509 return vol;
510 };
511 Volume.fromNestedJSON = function (json, cwd) {
512 var vol = new Volume();
513 vol.fromNestedJSON(json, cwd);
514 return vol;
515 };
516 Object.defineProperty(Volume.prototype, "promises", {
517 get: function () {
518 if (this.promisesApi === null)
519 throw new Error('Promise is not supported in this environment.');
520 return this.promisesApi;
521 },
522 enumerable: false,
523 configurable: true
524 });
525 Volume.prototype.createLink = function (parent, name, isDirectory, perm) {
526 if (isDirectory === void 0) { isDirectory = false; }
527 if (!parent) {
528 return new this.props.Link(this, null, '');
529 }
530 if (!name) {
531 throw new Error('createLink: name cannot be empty');
532 }
533 return parent.createChild(name, this.createNode(isDirectory, perm));
534 };
535 Volume.prototype.deleteLink = function (link) {
536 var parent = link.parent;
537 if (parent) {
538 parent.deleteChild(link);
539 return true;
540 }
541 return false;
542 };
543 Volume.prototype.newInoNumber = function () {
544 var releasedFd = this.releasedInos.pop();
545 if (releasedFd)
546 return releasedFd;
547 else {
548 this.ino = (this.ino + 1) % 0xffffffff;
549 return this.ino;
550 }
551 };
552 Volume.prototype.newFdNumber = function () {
553 var releasedFd = this.releasedFds.pop();
554 return typeof releasedFd === 'number' ? releasedFd : Volume.fd--;
555 };
556 Volume.prototype.createNode = function (isDirectory, perm) {
557 if (isDirectory === void 0) { isDirectory = false; }
558 var node = new this.props.Node(this.newInoNumber(), perm);
559 if (isDirectory)
560 node.setIsDirectory();
561 this.inodes[node.ino] = node;
562 return node;
563 };
564 Volume.prototype.getNode = function (ino) {
565 return this.inodes[ino];
566 };
567 Volume.prototype.deleteNode = function (node) {
568 node.del();
569 delete this.inodes[node.ino];
570 this.releasedInos.push(node.ino);
571 };
572 // Generates 6 character long random string, used by `mkdtemp`.
573 Volume.prototype.genRndStr = function () {
574 var str = (Math.random() + 1).toString(36).substr(2, 6);
575 if (str.length === 6)
576 return str;
577 else
578 return this.genRndStr();
579 };
580 // Returns a `Link` (hard link) referenced by path "split" into steps.
581 Volume.prototype.getLink = function (steps) {
582 return this.root.walk(steps);
583 };
584 // Just link `getLink`, but throws a correct user error, if link to found.
585 Volume.prototype.getLinkOrThrow = function (filename, funcName) {
586 var steps = filenameToSteps(filename);
587 var link = this.getLink(steps);
588 if (!link)
589 throw createError(ENOENT, funcName, filename);
590 return link;
591 };
592 // Just like `getLink`, but also dereference/resolves symbolic links.
593 Volume.prototype.getResolvedLink = function (filenameOrSteps) {
594 var steps = typeof filenameOrSteps === 'string' ? filenameToSteps(filenameOrSteps) : filenameOrSteps;
595 var link = this.root;
596 var i = 0;
597 while (i < steps.length) {
598 var step = steps[i];
599 link = link.getChild(step);
600 if (!link)
601 return null;
602 var node = link.getNode();
603 if (node.isSymlink()) {
604 steps = node.symlink.concat(steps.slice(i + 1));
605 link = this.root;
606 i = 0;
607 continue;
608 }
609 i++;
610 }
611 return link;
612 };
613 // Just like `getLinkOrThrow`, but also dereference/resolves symbolic links.
614 Volume.prototype.getResolvedLinkOrThrow = function (filename, funcName) {
615 var link = this.getResolvedLink(filename);
616 if (!link)
617 throw createError(ENOENT, funcName, filename);
618 return link;
619 };
620 Volume.prototype.resolveSymlinks = function (link) {
621 // let node: Node = link.getNode();
622 // while(link && node.isSymlink()) {
623 // link = this.getLink(node.symlink);
624 // if(!link) return null;
625 // node = link.getNode();
626 // }
627 // return link;
628 return this.getResolvedLink(link.steps.slice(1));
629 };
630 // Just like `getLinkOrThrow`, but also verifies that the link is a directory.
631 Volume.prototype.getLinkAsDirOrThrow = function (filename, funcName) {
632 var link = this.getLinkOrThrow(filename, funcName);
633 if (!link.getNode().isDirectory())
634 throw createError(ENOTDIR, funcName, filename);
635 return link;
636 };
637 // Get the immediate parent directory of the link.
638 Volume.prototype.getLinkParent = function (steps) {
639 return this.root.walk(steps, steps.length - 1);
640 };
641 Volume.prototype.getLinkParentAsDirOrThrow = function (filenameOrSteps, funcName) {
642 var steps = filenameOrSteps instanceof Array ? filenameOrSteps : filenameToSteps(filenameOrSteps);
643 var link = this.getLinkParent(steps);
644 if (!link)
645 throw createError(ENOENT, funcName, sep + steps.join(sep));
646 if (!link.getNode().isDirectory())
647 throw createError(ENOTDIR, funcName, sep + steps.join(sep));
648 return link;
649 };
650 Volume.prototype.getFileByFd = function (fd) {
651 return this.fds[String(fd)];
652 };
653 Volume.prototype.getFileByFdOrThrow = function (fd, funcName) {
654 if (!isFd(fd))
655 throw TypeError(ERRSTR.FD);
656 var file = this.getFileByFd(fd);
657 if (!file)
658 throw createError(EBADF, funcName);
659 return file;
660 };
661 /**
662 * @todo This is not used anymore. Remove.
663 */
664 /*
665 private getNodeByIdOrCreate(id: TFileId, flags: number, perm: number): Node {
666 if (typeof id === 'number') {
667 const file = this.getFileByFd(id);
668 if (!file) throw Error('File nto found');
669 return file.node;
670 } else {
671 const steps = pathToSteps(id as PathLike);
672 let link = this.getLink(steps);
673 if (link) return link.getNode();
674
675 // Try creating a node if not found.
676 if (flags & O_CREAT) {
677 const dirLink = this.getLinkParent(steps);
678 if (dirLink) {
679 const name = steps[steps.length - 1];
680 link = this.createLink(dirLink, name, false, perm);
681 return link.getNode();
682 }
683 }
684
685 throw createError(ENOENT, 'getNodeByIdOrCreate', pathToFilename(id));
686 }
687 }
688 */
689 Volume.prototype.wrapAsync = function (method, args, callback) {
690 var _this = this;
691 validateCallback(callback);
692 (0, setImmediate_1.default)(function () {
693 var result;
694 try {
695 result = method.apply(_this, args);
696 }
697 catch (err) {
698 callback(err);
699 return;
700 }
701 callback(null, result);
702 });
703 };
704 Volume.prototype._toJSON = function (link, json, path) {
705 var _a;
706 if (link === void 0) { link = this.root; }
707 if (json === void 0) { json = {}; }
708 var isEmpty = true;
709 var children = link.children;
710 if (link.getNode().isFile()) {
711 children = (_a = {}, _a[link.getName()] = link.parent.getChild(link.getName()), _a);
712 link = link.parent;
713 }
714 for (var name_1 in children) {
715 isEmpty = false;
716 var child = link.getChild(name_1);
717 if (!child) {
718 throw new Error('_toJSON: unexpected undefined');
719 }
720 var node = child.getNode();
721 if (node.isFile()) {
722 var filename = child.getPath();
723 if (path)
724 filename = relative(path, filename);
725 json[filename] = node.getString();
726 }
727 else if (node.isDirectory()) {
728 this._toJSON(child, json, path);
729 }
730 }
731 var dirPath = link.getPath();
732 if (path)
733 dirPath = relative(path, dirPath);
734 if (dirPath && isEmpty) {
735 json[dirPath] = null;
736 }
737 return json;
738 };
739 Volume.prototype.toJSON = function (paths, json, isRelative) {
740 if (json === void 0) { json = {}; }
741 if (isRelative === void 0) { isRelative = false; }
742 var links = [];
743 if (paths) {
744 if (!(paths instanceof Array))
745 paths = [paths];
746 for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
747 var path = paths_1[_i];
748 var filename = pathToFilename(path);
749 var link = this.getResolvedLink(filename);
750 if (!link)
751 continue;
752 links.push(link);
753 }
754 }
755 else {
756 links.push(this.root);
757 }
758 if (!links.length)
759 return json;
760 for (var _a = 0, links_1 = links; _a < links_1.length; _a++) {
761 var link = links_1[_a];
762 this._toJSON(link, json, isRelative ? link.getPath() : '');
763 }
764 return json;
765 };
766 Volume.prototype.fromJSON = function (json, cwd) {
767 if (cwd === void 0) { cwd = process_1.default.cwd(); }
768 for (var filename in json) {
769 var data = json[filename];
770 filename = resolve(filename, cwd);
771 if (typeof data === 'string') {
772 var dir = dirname(filename);
773 this.mkdirpBase(dir, 511 /* DIR */);
774 this.writeFileSync(filename, data);
775 }
776 else {
777 this.mkdirpBase(filename, 511 /* DIR */);
778 }
779 }
780 };
781 Volume.prototype.fromNestedJSON = function (json, cwd) {
782 this.fromJSON(flattenJSON(json), cwd);
783 };
784 Volume.prototype.reset = function () {
785 this.ino = 0;
786 this.inodes = {};
787 this.releasedInos = [];
788 this.fds = {};
789 this.releasedFds = [];
790 this.openFiles = 0;
791 this.root = this.createLink();
792 this.root.setNode(this.createNode(true));
793 };
794 // Legacy interface
795 Volume.prototype.mountSync = function (mountpoint, json) {
796 this.fromJSON(json, mountpoint);
797 };
798 Volume.prototype.openLink = function (link, flagsNum, resolveSymlinks) {
799 if (resolveSymlinks === void 0) { resolveSymlinks = true; }
800 if (this.openFiles >= this.maxFiles) {
801 // Too many open files.
802 throw createError(EMFILE, 'open', link.getPath());
803 }
804 // Resolve symlinks.
805 var realLink = link;
806 if (resolveSymlinks)
807 realLink = this.resolveSymlinks(link);
808 if (!realLink)
809 throw createError(ENOENT, 'open', link.getPath());
810 var node = realLink.getNode();
811 // Check whether node is a directory
812 if (node.isDirectory()) {
813 if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY)
814 throw createError(EISDIR, 'open', link.getPath());
815 }
816 else {
817 if (flagsNum & O_DIRECTORY)
818 throw createError(ENOTDIR, 'open', link.getPath());
819 }
820 // Check node permissions
821 if (!(flagsNum & O_WRONLY)) {
822 if (!node.canRead()) {
823 throw createError(EACCES, 'open', link.getPath());
824 }
825 }
826 if (flagsNum & O_RDWR) {
827 }
828 var file = new this.props.File(link, node, flagsNum, this.newFdNumber());
829 this.fds[file.fd] = file;
830 this.openFiles++;
831 if (flagsNum & O_TRUNC)
832 file.truncate();
833 return file;
834 };
835 Volume.prototype.openFile = function (filename, flagsNum, modeNum, resolveSymlinks) {
836 if (resolveSymlinks === void 0) { resolveSymlinks = true; }
837 var steps = filenameToSteps(filename);
838 var link = resolveSymlinks ? this.getResolvedLink(steps) : this.getLink(steps);
839 // Try creating a new file, if it does not exist.
840 if (!link && flagsNum & O_CREAT) {
841 // const dirLink: Link = this.getLinkParent(steps);
842 var dirLink = this.getResolvedLink(steps.slice(0, steps.length - 1));
843 // if(!dirLink) throw createError(ENOENT, 'open', filename);
844 if (!dirLink)
845 throw createError(ENOENT, 'open', sep + steps.join(sep));
846 if (flagsNum & O_CREAT && typeof modeNum === 'number') {
847 link = this.createLink(dirLink, steps[steps.length - 1], false, modeNum);
848 }
849 }
850 if (link)
851 return this.openLink(link, flagsNum, resolveSymlinks);
852 throw createError(ENOENT, 'open', filename);
853 };
854 Volume.prototype.openBase = function (filename, flagsNum, modeNum, resolveSymlinks) {
855 if (resolveSymlinks === void 0) { resolveSymlinks = true; }
856 var file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks);
857 if (!file)
858 throw createError(ENOENT, 'open', filename);
859 return file.fd;
860 };
861 Volume.prototype.openSync = function (path, flags, mode) {
862 if (mode === void 0) { mode = 438 /* DEFAULT */; }
863 // Validate (1) mode; (2) path; (3) flags - in that order.
864 var modeNum = modeToNumber(mode);
865 var fileName = pathToFilename(path);
866 var flagsNum = flagsToNumber(flags);
867 return this.openBase(fileName, flagsNum, modeNum);
868 };
869 Volume.prototype.open = function (path, flags, a, b) {
870 var mode = a;
871 var callback = b;
872 if (typeof a === 'function') {
873 mode = 438 /* DEFAULT */;
874 callback = a;
875 }
876 mode = mode || 438 /* DEFAULT */;
877 var modeNum = modeToNumber(mode);
878 var fileName = pathToFilename(path);
879 var flagsNum = flagsToNumber(flags);
880 this.wrapAsync(this.openBase, [fileName, flagsNum, modeNum], callback);
881 };
882 Volume.prototype.closeFile = function (file) {
883 if (!this.fds[file.fd])
884 return;
885 this.openFiles--;
886 delete this.fds[file.fd];
887 this.releasedFds.push(file.fd);
888 };
889 Volume.prototype.closeSync = function (fd) {
890 validateFd(fd);
891 var file = this.getFileByFdOrThrow(fd, 'close');
892 this.closeFile(file);
893 };
894 Volume.prototype.close = function (fd, callback) {
895 validateFd(fd);
896 this.wrapAsync(this.closeSync, [fd], callback);
897 };
898 Volume.prototype.openFileOrGetById = function (id, flagsNum, modeNum) {
899 if (typeof id === 'number') {
900 var file = this.fds[id];
901 if (!file)
902 throw createError(ENOENT);
903 return file;
904 }
905 else {
906 return this.openFile(pathToFilename(id), flagsNum, modeNum);
907 }
908 };
909 Volume.prototype.readBase = function (fd, buffer, offset, length, position) {
910 var file = this.getFileByFdOrThrow(fd);
911 return file.read(buffer, Number(offset), Number(length), position);
912 };
913 Volume.prototype.readSync = function (fd, buffer, offset, length, position) {
914 validateFd(fd);
915 return this.readBase(fd, buffer, offset, length, position);
916 };
917 Volume.prototype.read = function (fd, buffer, offset, length, position, callback) {
918 var _this = this;
919 validateCallback(callback);
920 // This `if` branch is from Node.js
921 if (length === 0) {
922 return process_1.default.nextTick(function () {
923 if (callback)
924 callback(null, 0, buffer);
925 });
926 }
927 (0, setImmediate_1.default)(function () {
928 try {
929 var bytes = _this.readBase(fd, buffer, offset, length, position);
930 callback(null, bytes, buffer);
931 }
932 catch (err) {
933 callback(err);
934 }
935 });
936 };
937 Volume.prototype.readFileBase = function (id, flagsNum, encoding) {
938 var result;
939 var isUserFd = typeof id === 'number';
940 var userOwnsFd = isUserFd && isFd(id);
941 var fd;
942 if (userOwnsFd)
943 fd = id;
944 else {
945 var filename = pathToFilename(id);
946 var steps = filenameToSteps(filename);
947 var link = this.getResolvedLink(steps);
948 if (link) {
949 var node = link.getNode();
950 if (node.isDirectory())
951 throw createError(EISDIR, 'open', link.getPath());
952 }
953 fd = this.openSync(id, flagsNum);
954 }
955 try {
956 result = bufferToEncoding(this.getFileByFdOrThrow(fd).getBuffer(), encoding);
957 }
958 finally {
959 if (!userOwnsFd) {
960 this.closeSync(fd);
961 }
962 }
963 return result;
964 };
965 Volume.prototype.readFileSync = function (file, options) {
966 var opts = getReadFileOptions(options);
967 var flagsNum = flagsToNumber(opts.flag);
968 return this.readFileBase(file, flagsNum, opts.encoding);
969 };
970 Volume.prototype.readFile = function (id, a, b) {
971 var _a = optsAndCbGenerator(getReadFileOptions)(a, b), opts = _a[0], callback = _a[1];
972 var flagsNum = flagsToNumber(opts.flag);
973 this.wrapAsync(this.readFileBase, [id, flagsNum, opts.encoding], callback);
974 };
975 Volume.prototype.writeBase = function (fd, buf, offset, length, position) {
976 var file = this.getFileByFdOrThrow(fd, 'write');
977 return file.write(buf, offset, length, position);
978 };
979 Volume.prototype.writeSync = function (fd, a, b, c, d) {
980 validateFd(fd);
981 var encoding;
982 var offset;
983 var length;
984 var position;
985 var isBuffer = typeof a !== 'string';
986 if (isBuffer) {
987 offset = (b || 0) | 0;
988 length = c;
989 position = d;
990 }
991 else {
992 position = b;
993 encoding = c;
994 }
995 var buf = dataToBuffer(a, encoding);
996 if (isBuffer) {
997 if (typeof length === 'undefined') {
998 length = buf.length;
999 }
1000 }
1001 else {
1002 offset = 0;
1003 length = buf.length;
1004 }
1005 return this.writeBase(fd, buf, offset, length, position);
1006 };
1007 Volume.prototype.write = function (fd, a, b, c, d, e) {
1008 var _this = this;
1009 validateFd(fd);
1010 var offset;
1011 var length;
1012 var position;
1013 var encoding;
1014 var callback;
1015 var tipa = typeof a;
1016 var tipb = typeof b;
1017 var tipc = typeof c;
1018 var tipd = typeof d;
1019 if (tipa !== 'string') {
1020 if (tipb === 'function') {
1021 callback = b;
1022 }
1023 else if (tipc === 'function') {
1024 offset = b | 0;
1025 callback = c;
1026 }
1027 else if (tipd === 'function') {
1028 offset = b | 0;
1029 length = c;
1030 callback = d;
1031 }
1032 else {
1033 offset = b | 0;
1034 length = c;
1035 position = d;
1036 callback = e;
1037 }
1038 }
1039 else {
1040 if (tipb === 'function') {
1041 callback = b;
1042 }
1043 else if (tipc === 'function') {
1044 position = b;
1045 callback = c;
1046 }
1047 else if (tipd === 'function') {
1048 position = b;
1049 encoding = c;
1050 callback = d;
1051 }
1052 }
1053 var buf = dataToBuffer(a, encoding);
1054 if (tipa !== 'string') {
1055 if (typeof length === 'undefined')
1056 length = buf.length;
1057 }
1058 else {
1059 offset = 0;
1060 length = buf.length;
1061 }
1062 var cb = validateCallback(callback);
1063 (0, setImmediate_1.default)(function () {
1064 try {
1065 var bytes = _this.writeBase(fd, buf, offset, length, position);
1066 if (tipa !== 'string') {
1067 cb(null, bytes, buf);
1068 }
1069 else {
1070 cb(null, bytes, a);
1071 }
1072 }
1073 catch (err) {
1074 cb(err);
1075 }
1076 });
1077 };
1078 Volume.prototype.writeFileBase = function (id, buf, flagsNum, modeNum) {
1079 // console.log('writeFileBase', id, buf, flagsNum, modeNum);
1080 // const node = this.getNodeByIdOrCreate(id, flagsNum, modeNum);
1081 // node.setBuffer(buf);
1082 var isUserFd = typeof id === 'number';
1083 var fd;
1084 if (isUserFd)
1085 fd = id;
1086 else {
1087 fd = this.openBase(pathToFilename(id), flagsNum, modeNum);
1088 // fd = this.openSync(id as PathLike, flagsNum, modeNum);
1089 }
1090 var offset = 0;
1091 var length = buf.length;
1092 var position = flagsNum & O_APPEND ? undefined : 0;
1093 try {
1094 while (length > 0) {
1095 var written = this.writeSync(fd, buf, offset, length, position);
1096 offset += written;
1097 length -= written;
1098 if (position !== undefined)
1099 position += written;
1100 }
1101 }
1102 finally {
1103 if (!isUserFd)
1104 this.closeSync(fd);
1105 }
1106 };
1107 Volume.prototype.writeFileSync = function (id, data, options) {
1108 var opts = getWriteFileOptions(options);
1109 var flagsNum = flagsToNumber(opts.flag);
1110 var modeNum = modeToNumber(opts.mode);
1111 var buf = dataToBuffer(data, opts.encoding);
1112 this.writeFileBase(id, buf, flagsNum, modeNum);
1113 };
1114 Volume.prototype.writeFile = function (id, data, a, b) {
1115 var options = a;
1116 var callback = b;
1117 if (typeof a === 'function') {
1118 options = writeFileDefaults;
1119 callback = a;
1120 }
1121 var cb = validateCallback(callback);
1122 var opts = getWriteFileOptions(options);
1123 var flagsNum = flagsToNumber(opts.flag);
1124 var modeNum = modeToNumber(opts.mode);
1125 var buf = dataToBuffer(data, opts.encoding);
1126 this.wrapAsync(this.writeFileBase, [id, buf, flagsNum, modeNum], cb);
1127 };
1128 Volume.prototype.linkBase = function (filename1, filename2) {
1129 var steps1 = filenameToSteps(filename1);
1130 var link1 = this.getLink(steps1);
1131 if (!link1)
1132 throw createError(ENOENT, 'link', filename1, filename2);
1133 var steps2 = filenameToSteps(filename2);
1134 // Check new link directory exists.
1135 var dir2 = this.getLinkParent(steps2);
1136 if (!dir2)
1137 throw createError(ENOENT, 'link', filename1, filename2);
1138 var name = steps2[steps2.length - 1];
1139 // Check if new file already exists.
1140 if (dir2.getChild(name))
1141 throw createError(EEXIST, 'link', filename1, filename2);
1142 var node = link1.getNode();
1143 node.nlink++;
1144 dir2.createChild(name, node);
1145 };
1146 Volume.prototype.copyFileBase = function (src, dest, flags) {
1147 var buf = this.readFileSync(src);
1148 if (flags & COPYFILE_EXCL) {
1149 if (this.existsSync(dest)) {
1150 throw createError(EEXIST, 'copyFile', src, dest);
1151 }
1152 }
1153 if (flags & COPYFILE_FICLONE_FORCE) {
1154 throw createError(ENOSYS, 'copyFile', src, dest);
1155 }
1156 this.writeFileBase(dest, buf, FLAGS.w, 438 /* DEFAULT */);
1157 };
1158 Volume.prototype.copyFileSync = function (src, dest, flags) {
1159 var srcFilename = pathToFilename(src);
1160 var destFilename = pathToFilename(dest);
1161 return this.copyFileBase(srcFilename, destFilename, (flags || 0) | 0);
1162 };
1163 Volume.prototype.copyFile = function (src, dest, a, b) {
1164 var srcFilename = pathToFilename(src);
1165 var destFilename = pathToFilename(dest);
1166 var flags;
1167 var callback;
1168 if (typeof a === 'function') {
1169 flags = 0;
1170 callback = a;
1171 }
1172 else {
1173 flags = a;
1174 callback = b;
1175 }
1176 validateCallback(callback);
1177 this.wrapAsync(this.copyFileBase, [srcFilename, destFilename, flags], callback);
1178 };
1179 Volume.prototype.linkSync = function (existingPath, newPath) {
1180 var existingPathFilename = pathToFilename(existingPath);
1181 var newPathFilename = pathToFilename(newPath);
1182 this.linkBase(existingPathFilename, newPathFilename);
1183 };
1184 Volume.prototype.link = function (existingPath, newPath, callback) {
1185 var existingPathFilename = pathToFilename(existingPath);
1186 var newPathFilename = pathToFilename(newPath);
1187 this.wrapAsync(this.linkBase, [existingPathFilename, newPathFilename], callback);
1188 };
1189 Volume.prototype.unlinkBase = function (filename) {
1190 var steps = filenameToSteps(filename);
1191 var link = this.getLink(steps);
1192 if (!link)
1193 throw createError(ENOENT, 'unlink', filename);
1194 // TODO: Check if it is file, dir, other...
1195 if (link.length)
1196 throw Error('Dir not empty...');
1197 this.deleteLink(link);
1198 var node = link.getNode();
1199 node.nlink--;
1200 // When all hard links to i-node are deleted, remove the i-node, too.
1201 if (node.nlink <= 0) {
1202 this.deleteNode(node);
1203 }
1204 };
1205 Volume.prototype.unlinkSync = function (path) {
1206 var filename = pathToFilename(path);
1207 this.unlinkBase(filename);
1208 };
1209 Volume.prototype.unlink = function (path, callback) {
1210 var filename = pathToFilename(path);
1211 this.wrapAsync(this.unlinkBase, [filename], callback);
1212 };
1213 Volume.prototype.symlinkBase = function (targetFilename, pathFilename) {
1214 var pathSteps = filenameToSteps(pathFilename);
1215 // Check if directory exists, where we about to create a symlink.
1216 var dirLink = this.getLinkParent(pathSteps);
1217 if (!dirLink)
1218 throw createError(ENOENT, 'symlink', targetFilename, pathFilename);
1219 var name = pathSteps[pathSteps.length - 1];
1220 // Check if new file already exists.
1221 if (dirLink.getChild(name))
1222 throw createError(EEXIST, 'symlink', targetFilename, pathFilename);
1223 // Create symlink.
1224 var symlink = dirLink.createChild(name);
1225 symlink.getNode().makeSymlink(filenameToSteps(targetFilename));
1226 return symlink;
1227 };
1228 // `type` argument works only on Windows.
1229 Volume.prototype.symlinkSync = function (target, path, type) {
1230 var targetFilename = pathToFilename(target);
1231 var pathFilename = pathToFilename(path);
1232 this.symlinkBase(targetFilename, pathFilename);
1233 };
1234 Volume.prototype.symlink = function (target, path, a, b) {
1235 var callback = validateCallback(typeof a === 'function' ? a : b);
1236 var targetFilename = pathToFilename(target);
1237 var pathFilename = pathToFilename(path);
1238 this.wrapAsync(this.symlinkBase, [targetFilename, pathFilename], callback);
1239 };
1240 Volume.prototype.realpathBase = function (filename, encoding) {
1241 var steps = filenameToSteps(filename);
1242 var realLink = this.getResolvedLink(steps);
1243 if (!realLink)
1244 throw createError(ENOENT, 'realpath', filename);
1245 return (0, encoding_1.strToEncoding)(realLink.getPath(), encoding);
1246 };
1247 Volume.prototype.realpathSync = function (path, options) {
1248 return this.realpathBase(pathToFilename(path), getRealpathOptions(options).encoding);
1249 };
1250 Volume.prototype.realpath = function (path, a, b) {
1251 var _a = getRealpathOptsAndCb(a, b), opts = _a[0], callback = _a[1];
1252 var pathFilename = pathToFilename(path);
1253 this.wrapAsync(this.realpathBase, [pathFilename, opts.encoding], callback);
1254 };
1255 Volume.prototype.lstatBase = function (filename, bigint) {
1256 if (bigint === void 0) { bigint = false; }
1257 var link = this.getLink(filenameToSteps(filename));
1258 if (!link)
1259 throw createError(ENOENT, 'lstat', filename);
1260 return Stats_1.default.build(link.getNode(), bigint);
1261 };
1262 Volume.prototype.lstatSync = function (path, options) {
1263 return this.lstatBase(pathToFilename(path), getStatOptions(options).bigint);
1264 };
1265 Volume.prototype.lstat = function (path, a, b) {
1266 var _a = getStatOptsAndCb(a, b), opts = _a[0], callback = _a[1];
1267 this.wrapAsync(this.lstatBase, [pathToFilename(path), opts.bigint], callback);
1268 };
1269 Volume.prototype.statBase = function (filename, bigint) {
1270 if (bigint === void 0) { bigint = false; }
1271 var link = this.getResolvedLink(filenameToSteps(filename));
1272 if (!link)
1273 throw createError(ENOENT, 'stat', filename);
1274 return Stats_1.default.build(link.getNode(), bigint);
1275 };
1276 Volume.prototype.statSync = function (path, options) {
1277 return this.statBase(pathToFilename(path), getStatOptions(options).bigint);
1278 };
1279 Volume.prototype.stat = function (path, a, b) {
1280 var _a = getStatOptsAndCb(a, b), opts = _a[0], callback = _a[1];
1281 this.wrapAsync(this.statBase, [pathToFilename(path), opts.bigint], callback);
1282 };
1283 Volume.prototype.fstatBase = function (fd, bigint) {
1284 if (bigint === void 0) { bigint = false; }
1285 var file = this.getFileByFd(fd);
1286 if (!file)
1287 throw createError(EBADF, 'fstat');
1288 return Stats_1.default.build(file.node, bigint);
1289 };
1290 Volume.prototype.fstatSync = function (fd, options) {
1291 return this.fstatBase(fd, getStatOptions(options).bigint);
1292 };
1293 Volume.prototype.fstat = function (fd, a, b) {
1294 var _a = getStatOptsAndCb(a, b), opts = _a[0], callback = _a[1];
1295 this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback);
1296 };
1297 Volume.prototype.renameBase = function (oldPathFilename, newPathFilename) {
1298 var link = this.getLink(filenameToSteps(oldPathFilename));
1299 if (!link)
1300 throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
1301 // TODO: Check if it is directory, if non-empty, we cannot move it, right?
1302 var newPathSteps = filenameToSteps(newPathFilename);
1303 // Check directory exists for the new location.
1304 var newPathDirLink = this.getLinkParent(newPathSteps);
1305 if (!newPathDirLink)
1306 throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
1307 // TODO: Also treat cases with directories and symbolic links.
1308 // TODO: See: http://man7.org/linux/man-pages/man2/rename.2.html
1309 // Remove hard link from old folder.
1310 var oldLinkParent = link.parent;
1311 if (oldLinkParent) {
1312 oldLinkParent.deleteChild(link);
1313 }
1314 // Rename should overwrite the new path, if that exists.
1315 var name = newPathSteps[newPathSteps.length - 1];
1316 link.steps = __spreadArray(__spreadArray([], newPathDirLink.steps, true), [name], false);
1317 newPathDirLink.setChild(link.getName(), link);
1318 };
1319 Volume.prototype.renameSync = function (oldPath, newPath) {
1320 var oldPathFilename = pathToFilename(oldPath);
1321 var newPathFilename = pathToFilename(newPath);
1322 this.renameBase(oldPathFilename, newPathFilename);
1323 };
1324 Volume.prototype.rename = function (oldPath, newPath, callback) {
1325 var oldPathFilename = pathToFilename(oldPath);
1326 var newPathFilename = pathToFilename(newPath);
1327 this.wrapAsync(this.renameBase, [oldPathFilename, newPathFilename], callback);
1328 };
1329 Volume.prototype.existsBase = function (filename) {
1330 return !!this.statBase(filename);
1331 };
1332 Volume.prototype.existsSync = function (path) {
1333 try {
1334 return this.existsBase(pathToFilename(path));
1335 }
1336 catch (err) {
1337 return false;
1338 }
1339 };
1340 Volume.prototype.exists = function (path, callback) {
1341 var _this = this;
1342 var filename = pathToFilename(path);
1343 if (typeof callback !== 'function')
1344 throw Error(ERRSTR.CB);
1345 (0, setImmediate_1.default)(function () {
1346 try {
1347 callback(_this.existsBase(filename));
1348 }
1349 catch (err) {
1350 callback(false);
1351 }
1352 });
1353 };
1354 Volume.prototype.accessBase = function (filename, mode) {
1355 var link = this.getLinkOrThrow(filename, 'access');
1356 // TODO: Verify permissions
1357 };
1358 Volume.prototype.accessSync = function (path, mode) {
1359 if (mode === void 0) { mode = F_OK; }
1360 var filename = pathToFilename(path);
1361 mode = mode | 0;
1362 this.accessBase(filename, mode);
1363 };
1364 Volume.prototype.access = function (path, a, b) {
1365 var mode = F_OK;
1366 var callback;
1367 if (typeof a !== 'function') {
1368 mode = a | 0; // cast to number
1369 callback = validateCallback(b);
1370 }
1371 else {
1372 callback = a;
1373 }
1374 var filename = pathToFilename(path);
1375 this.wrapAsync(this.accessBase, [filename, mode], callback);
1376 };
1377 Volume.prototype.appendFileSync = function (id, data, options) {
1378 if (options === void 0) { options = appendFileDefaults; }
1379 var opts = getAppendFileOpts(options);
1380 // force append behavior when using a supplied file descriptor
1381 if (!opts.flag || isFd(id))
1382 opts.flag = 'a';
1383 this.writeFileSync(id, data, opts);
1384 };
1385 Volume.prototype.appendFile = function (id, data, a, b) {
1386 var _a = getAppendFileOptsAndCb(a, b), opts = _a[0], callback = _a[1];
1387 // force append behavior when using a supplied file descriptor
1388 if (!opts.flag || isFd(id))
1389 opts.flag = 'a';
1390 this.writeFile(id, data, opts, callback);
1391 };
1392 Volume.prototype.readdirBase = function (filename, options) {
1393 var steps = filenameToSteps(filename);
1394 var link = this.getResolvedLink(steps);
1395 if (!link)
1396 throw createError(ENOENT, 'readdir', filename);
1397 var node = link.getNode();
1398 if (!node.isDirectory())
1399 throw createError(ENOTDIR, 'scandir', filename);
1400 if (options.withFileTypes) {
1401 var list_1 = [];
1402 for (var name_2 in link.children) {
1403 var child = link.getChild(name_2);
1404 if (!child) {
1405 continue;
1406 }
1407 list_1.push(Dirent_1.default.build(child, options.encoding));
1408 }
1409 if (!isWin && options.encoding !== 'buffer')
1410 list_1.sort(function (a, b) {
1411 if (a.name < b.name)
1412 return -1;
1413 if (a.name > b.name)
1414 return 1;
1415 return 0;
1416 });
1417 return list_1;
1418 }
1419 var list = [];
1420 for (var name_3 in link.children) {
1421 list.push((0, encoding_1.strToEncoding)(name_3, options.encoding));
1422 }
1423 if (!isWin && options.encoding !== 'buffer')
1424 list.sort();
1425 return list;
1426 };
1427 Volume.prototype.readdirSync = function (path, options) {
1428 var opts = getReaddirOptions(options);
1429 var filename = pathToFilename(path);
1430 return this.readdirBase(filename, opts);
1431 };
1432 Volume.prototype.readdir = function (path, a, b) {
1433 var _a = getReaddirOptsAndCb(a, b), options = _a[0], callback = _a[1];
1434 var filename = pathToFilename(path);
1435 this.wrapAsync(this.readdirBase, [filename, options], callback);
1436 };
1437 Volume.prototype.readlinkBase = function (filename, encoding) {
1438 var link = this.getLinkOrThrow(filename, 'readlink');
1439 var node = link.getNode();
1440 if (!node.isSymlink())
1441 throw createError(EINVAL, 'readlink', filename);
1442 var str = sep + node.symlink.join(sep);
1443 return (0, encoding_1.strToEncoding)(str, encoding);
1444 };
1445 Volume.prototype.readlinkSync = function (path, options) {
1446 var opts = getDefaultOpts(options);
1447 var filename = pathToFilename(path);
1448 return this.readlinkBase(filename, opts.encoding);
1449 };
1450 Volume.prototype.readlink = function (path, a, b) {
1451 var _a = getDefaultOptsAndCb(a, b), opts = _a[0], callback = _a[1];
1452 var filename = pathToFilename(path);
1453 this.wrapAsync(this.readlinkBase, [filename, opts.encoding], callback);
1454 };
1455 Volume.prototype.fsyncBase = function (fd) {
1456 this.getFileByFdOrThrow(fd, 'fsync');
1457 };
1458 Volume.prototype.fsyncSync = function (fd) {
1459 this.fsyncBase(fd);
1460 };
1461 Volume.prototype.fsync = function (fd, callback) {
1462 this.wrapAsync(this.fsyncBase, [fd], callback);
1463 };
1464 Volume.prototype.fdatasyncBase = function (fd) {
1465 this.getFileByFdOrThrow(fd, 'fdatasync');
1466 };
1467 Volume.prototype.fdatasyncSync = function (fd) {
1468 this.fdatasyncBase(fd);
1469 };
1470 Volume.prototype.fdatasync = function (fd, callback) {
1471 this.wrapAsync(this.fdatasyncBase, [fd], callback);
1472 };
1473 Volume.prototype.ftruncateBase = function (fd, len) {
1474 var file = this.getFileByFdOrThrow(fd, 'ftruncate');
1475 file.truncate(len);
1476 };
1477 Volume.prototype.ftruncateSync = function (fd, len) {
1478 this.ftruncateBase(fd, len);
1479 };
1480 Volume.prototype.ftruncate = function (fd, a, b) {
1481 var len = typeof a === 'number' ? a : 0;
1482 var callback = validateCallback(typeof a === 'number' ? b : a);
1483 this.wrapAsync(this.ftruncateBase, [fd, len], callback);
1484 };
1485 Volume.prototype.truncateBase = function (path, len) {
1486 var fd = this.openSync(path, 'r+');
1487 try {
1488 this.ftruncateSync(fd, len);
1489 }
1490 finally {
1491 this.closeSync(fd);
1492 }
1493 };
1494 Volume.prototype.truncateSync = function (id, len) {
1495 if (isFd(id))
1496 return this.ftruncateSync(id, len);
1497 this.truncateBase(id, len);
1498 };
1499 Volume.prototype.truncate = function (id, a, b) {
1500 var len = typeof a === 'number' ? a : 0;
1501 var callback = validateCallback(typeof a === 'number' ? b : a);
1502 if (isFd(id))
1503 return this.ftruncate(id, len, callback);
1504 this.wrapAsync(this.truncateBase, [id, len], callback);
1505 };
1506 Volume.prototype.futimesBase = function (fd, atime, mtime) {
1507 var file = this.getFileByFdOrThrow(fd, 'futimes');
1508 var node = file.node;
1509 node.atime = new Date(atime * 1000);
1510 node.mtime = new Date(mtime * 1000);
1511 };
1512 Volume.prototype.futimesSync = function (fd, atime, mtime) {
1513 this.futimesBase(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime));
1514 };
1515 Volume.prototype.futimes = function (fd, atime, mtime, callback) {
1516 this.wrapAsync(this.futimesBase, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
1517 };
1518 Volume.prototype.utimesBase = function (filename, atime, mtime) {
1519 var fd = this.openSync(filename, 'r+');
1520 try {
1521 this.futimesBase(fd, atime, mtime);
1522 }
1523 finally {
1524 this.closeSync(fd);
1525 }
1526 };
1527 Volume.prototype.utimesSync = function (path, atime, mtime) {
1528 this.utimesBase(pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime));
1529 };
1530 Volume.prototype.utimes = function (path, atime, mtime, callback) {
1531 this.wrapAsync(this.utimesBase, [pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
1532 };
1533 Volume.prototype.mkdirBase = function (filename, modeNum) {
1534 var steps = filenameToSteps(filename);
1535 // This will throw if user tries to create root dir `fs.mkdirSync('/')`.
1536 if (!steps.length) {
1537 throw createError(EEXIST, 'mkdir', filename);
1538 }
1539 var dir = this.getLinkParentAsDirOrThrow(filename, 'mkdir');
1540 // Check path already exists.
1541 var name = steps[steps.length - 1];
1542 if (dir.getChild(name))
1543 throw createError(EEXIST, 'mkdir', filename);
1544 dir.createChild(name, this.createNode(true, modeNum));
1545 };
1546 /**
1547 * Creates directory tree recursively.
1548 * @param filename
1549 * @param modeNum
1550 */
1551 Volume.prototype.mkdirpBase = function (filename, modeNum) {
1552 var steps = filenameToSteps(filename);
1553 var link = this.root;
1554 for (var i = 0; i < steps.length; i++) {
1555 var step = steps[i];
1556 if (!link.getNode().isDirectory())
1557 throw createError(ENOTDIR, 'mkdir', link.getPath());
1558 var child = link.getChild(step);
1559 if (child) {
1560 if (child.getNode().isDirectory())
1561 link = child;
1562 else
1563 throw createError(ENOTDIR, 'mkdir', child.getPath());
1564 }
1565 else {
1566 link = link.createChild(step, this.createNode(true, modeNum));
1567 }
1568 }
1569 };
1570 Volume.prototype.mkdirSync = function (path, options) {
1571 var opts = getMkdirOptions(options);
1572 var modeNum = modeToNumber(opts.mode, 511);
1573 var filename = pathToFilename(path);
1574 if (opts.recursive)
1575 this.mkdirpBase(filename, modeNum);
1576 else
1577 this.mkdirBase(filename, modeNum);
1578 };
1579 Volume.prototype.mkdir = function (path, a, b) {
1580 var opts = getMkdirOptions(a);
1581 var callback = validateCallback(typeof a === 'function' ? a : b);
1582 var modeNum = modeToNumber(opts.mode, 511);
1583 var filename = pathToFilename(path);
1584 if (opts.recursive)
1585 this.wrapAsync(this.mkdirpBase, [filename, modeNum], callback);
1586 else
1587 this.wrapAsync(this.mkdirBase, [filename, modeNum], callback);
1588 };
1589 // legacy interface
1590 Volume.prototype.mkdirpSync = function (path, mode) {
1591 this.mkdirSync(path, { mode: mode, recursive: true });
1592 };
1593 Volume.prototype.mkdirp = function (path, a, b) {
1594 var mode = typeof a === 'function' ? undefined : a;
1595 var callback = validateCallback(typeof a === 'function' ? a : b);
1596 this.mkdir(path, { mode: mode, recursive: true }, callback);
1597 };
1598 Volume.prototype.mkdtempBase = function (prefix, encoding, retry) {
1599 if (retry === void 0) { retry = 5; }
1600 var filename = prefix + this.genRndStr();
1601 try {
1602 this.mkdirBase(filename, 511 /* DIR */);
1603 return (0, encoding_1.strToEncoding)(filename, encoding);
1604 }
1605 catch (err) {
1606 if (err.code === EEXIST) {
1607 if (retry > 1)
1608 return this.mkdtempBase(prefix, encoding, retry - 1);
1609 else
1610 throw Error('Could not create temp dir.');
1611 }
1612 else
1613 throw err;
1614 }
1615 };
1616 Volume.prototype.mkdtempSync = function (prefix, options) {
1617 var encoding = getDefaultOpts(options).encoding;
1618 if (!prefix || typeof prefix !== 'string')
1619 throw new TypeError('filename prefix is required');
1620 nullCheck(prefix);
1621 return this.mkdtempBase(prefix, encoding);
1622 };
1623 Volume.prototype.mkdtemp = function (prefix, a, b) {
1624 var _a = getDefaultOptsAndCb(a, b), encoding = _a[0].encoding, callback = _a[1];
1625 if (!prefix || typeof prefix !== 'string')
1626 throw new TypeError('filename prefix is required');
1627 if (!nullCheck(prefix))
1628 return;
1629 this.wrapAsync(this.mkdtempBase, [prefix, encoding], callback);
1630 };
1631 Volume.prototype.rmdirBase = function (filename, options) {
1632 var opts = getRmdirOptions(options);
1633 var link = this.getLinkAsDirOrThrow(filename, 'rmdir');
1634 // Check directory is empty.
1635 if (link.length && !opts.recursive)
1636 throw createError(ENOTEMPTY, 'rmdir', filename);
1637 this.deleteLink(link);
1638 };
1639 Volume.prototype.rmdirSync = function (path, options) {
1640 this.rmdirBase(pathToFilename(path), options);
1641 };
1642 Volume.prototype.rmdir = function (path, a, b) {
1643 var opts = getRmdirOptions(a);
1644 var callback = validateCallback(typeof a === 'function' ? a : b);
1645 this.wrapAsync(this.rmdirBase, [pathToFilename(path), opts], callback);
1646 };
1647 Volume.prototype.rmBase = function (filename, options) {
1648 if (options === void 0) { options = {}; }
1649 var link = this.getResolvedLink(filename);
1650 if (!link) {
1651 // "stat" is used to match Node's native error message.
1652 if (!options.force)
1653 throw createError(ENOENT, 'stat', filename);
1654 return;
1655 }
1656 if (link.getNode().isDirectory()) {
1657 if (!options.recursive) {
1658 throw createError(ERR_FS_EISDIR, 'rm', filename);
1659 }
1660 }
1661 this.deleteLink(link);
1662 };
1663 Volume.prototype.rmSync = function (path, options) {
1664 this.rmBase(pathToFilename(path), options);
1665 };
1666 Volume.prototype.rm = function (path, a, b) {
1667 var _a = getRmOptsAndCb(a, b), opts = _a[0], callback = _a[1];
1668 this.wrapAsync(this.rmBase, [pathToFilename(path), opts], callback);
1669 };
1670 Volume.prototype.fchmodBase = function (fd, modeNum) {
1671 var file = this.getFileByFdOrThrow(fd, 'fchmod');
1672 file.chmod(modeNum);
1673 };
1674 Volume.prototype.fchmodSync = function (fd, mode) {
1675 this.fchmodBase(fd, modeToNumber(mode));
1676 };
1677 Volume.prototype.fchmod = function (fd, mode, callback) {
1678 this.wrapAsync(this.fchmodBase, [fd, modeToNumber(mode)], callback);
1679 };
1680 Volume.prototype.chmodBase = function (filename, modeNum) {
1681 var fd = this.openSync(filename, 'r+');
1682 try {
1683 this.fchmodBase(fd, modeNum);
1684 }
1685 finally {
1686 this.closeSync(fd);
1687 }
1688 };
1689 Volume.prototype.chmodSync = function (path, mode) {
1690 var modeNum = modeToNumber(mode);
1691 var filename = pathToFilename(path);
1692 this.chmodBase(filename, modeNum);
1693 };
1694 Volume.prototype.chmod = function (path, mode, callback) {
1695 var modeNum = modeToNumber(mode);
1696 var filename = pathToFilename(path);
1697 this.wrapAsync(this.chmodBase, [filename, modeNum], callback);
1698 };
1699 Volume.prototype.lchmodBase = function (filename, modeNum) {
1700 var fd = this.openBase(filename, O_RDWR, 0, false);
1701 try {
1702 this.fchmodBase(fd, modeNum);
1703 }
1704 finally {
1705 this.closeSync(fd);
1706 }
1707 };
1708 Volume.prototype.lchmodSync = function (path, mode) {
1709 var modeNum = modeToNumber(mode);
1710 var filename = pathToFilename(path);
1711 this.lchmodBase(filename, modeNum);
1712 };
1713 Volume.prototype.lchmod = function (path, mode, callback) {
1714 var modeNum = modeToNumber(mode);
1715 var filename = pathToFilename(path);
1716 this.wrapAsync(this.lchmodBase, [filename, modeNum], callback);
1717 };
1718 Volume.prototype.fchownBase = function (fd, uid, gid) {
1719 this.getFileByFdOrThrow(fd, 'fchown').chown(uid, gid);
1720 };
1721 Volume.prototype.fchownSync = function (fd, uid, gid) {
1722 validateUid(uid);
1723 validateGid(gid);
1724 this.fchownBase(fd, uid, gid);
1725 };
1726 Volume.prototype.fchown = function (fd, uid, gid, callback) {
1727 validateUid(uid);
1728 validateGid(gid);
1729 this.wrapAsync(this.fchownBase, [fd, uid, gid], callback);
1730 };
1731 Volume.prototype.chownBase = function (filename, uid, gid) {
1732 var link = this.getResolvedLinkOrThrow(filename, 'chown');
1733 var node = link.getNode();
1734 node.chown(uid, gid);
1735 // if(node.isFile() || node.isSymlink()) {
1736 //
1737 // } else if(node.isDirectory()) {
1738 //
1739 // } else {
1740 // TODO: What do we do here?
1741 // }
1742 };
1743 Volume.prototype.chownSync = function (path, uid, gid) {
1744 validateUid(uid);
1745 validateGid(gid);
1746 this.chownBase(pathToFilename(path), uid, gid);
1747 };
1748 Volume.prototype.chown = function (path, uid, gid, callback) {
1749 validateUid(uid);
1750 validateGid(gid);
1751 this.wrapAsync(this.chownBase, [pathToFilename(path), uid, gid], callback);
1752 };
1753 Volume.prototype.lchownBase = function (filename, uid, gid) {
1754 this.getLinkOrThrow(filename, 'lchown')
1755 .getNode()
1756 .chown(uid, gid);
1757 };
1758 Volume.prototype.lchownSync = function (path, uid, gid) {
1759 validateUid(uid);
1760 validateGid(gid);
1761 this.lchownBase(pathToFilename(path), uid, gid);
1762 };
1763 Volume.prototype.lchown = function (path, uid, gid, callback) {
1764 validateUid(uid);
1765 validateGid(gid);
1766 this.wrapAsync(this.lchownBase, [pathToFilename(path), uid, gid], callback);
1767 };
1768 Volume.prototype.watchFile = function (path, a, b) {
1769 var filename = pathToFilename(path);
1770 var options = a;
1771 var listener = b;
1772 if (typeof options === 'function') {
1773 listener = a;
1774 options = null;
1775 }
1776 if (typeof listener !== 'function') {
1777 throw Error('"watchFile()" requires a listener function');
1778 }
1779 var interval = 5007;
1780 var persistent = true;
1781 if (options && typeof options === 'object') {
1782 if (typeof options.interval === 'number')
1783 interval = options.interval;
1784 if (typeof options.persistent === 'boolean')
1785 persistent = options.persistent;
1786 }
1787 var watcher = this.statWatchers[filename];
1788 if (!watcher) {
1789 watcher = new this.StatWatcher();
1790 watcher.start(filename, persistent, interval);
1791 this.statWatchers[filename] = watcher;
1792 }
1793 watcher.addListener('change', listener);
1794 return watcher;
1795 };
1796 Volume.prototype.unwatchFile = function (path, listener) {
1797 var filename = pathToFilename(path);
1798 var watcher = this.statWatchers[filename];
1799 if (!watcher)
1800 return;
1801 if (typeof listener === 'function') {
1802 watcher.removeListener('change', listener);
1803 }
1804 else {
1805 watcher.removeAllListeners('change');
1806 }
1807 if (watcher.listenerCount('change') === 0) {
1808 watcher.stop();
1809 delete this.statWatchers[filename];
1810 }
1811 };
1812 Volume.prototype.createReadStream = function (path, options) {
1813 return new this.ReadStream(path, options);
1814 };
1815 Volume.prototype.createWriteStream = function (path, options) {
1816 return new this.WriteStream(path, options);
1817 };
1818 // watch(path: PathLike): FSWatcher;
1819 // watch(path: PathLike, options?: IWatchOptions | string): FSWatcher;
1820 Volume.prototype.watch = function (path, options, listener) {
1821 var filename = pathToFilename(path);
1822 var givenOptions = options;
1823 if (typeof options === 'function') {
1824 listener = options;
1825 givenOptions = null;
1826 }
1827 // tslint:disable-next-line prefer-const
1828 var _a = getDefaultOpts(givenOptions), persistent = _a.persistent, recursive = _a.recursive, encoding = _a.encoding;
1829 if (persistent === undefined)
1830 persistent = true;
1831 if (recursive === undefined)
1832 recursive = false;
1833 var watcher = new this.FSWatcher();
1834 watcher.start(filename, persistent, recursive, encoding);
1835 if (listener) {
1836 watcher.addListener('change', listener);
1837 }
1838 return watcher;
1839 };
1840 /**
1841 * Global file descriptor counter. UNIX file descriptors start from 0 and go sequentially
1842 * up, so here, in order not to conflict with them, we choose some big number and descrease
1843 * the file descriptor of every new opened file.
1844 * @type {number}
1845 * @todo This should not be static, right?
1846 */
1847 Volume.fd = 0x7fffffff;
1848 return Volume;
1849}());
1850exports.Volume = Volume;
1851function emitStop(self) {
1852 self.emit('stop');
1853}
1854var StatWatcher = /** @class */ (function (_super) {
1855 __extends(StatWatcher, _super);
1856 function StatWatcher(vol) {
1857 var _this = _super.call(this) || this;
1858 _this.onInterval = function () {
1859 try {
1860 var stats = _this.vol.statSync(_this.filename);
1861 if (_this.hasChanged(stats)) {
1862 _this.emit('change', stats, _this.prev);
1863 _this.prev = stats;
1864 }
1865 }
1866 finally {
1867 _this.loop();
1868 }
1869 };
1870 _this.vol = vol;
1871 return _this;
1872 }
1873 StatWatcher.prototype.loop = function () {
1874 this.timeoutRef = this.setTimeout(this.onInterval, this.interval);
1875 };
1876 StatWatcher.prototype.hasChanged = function (stats) {
1877 // if(!this.prev) return false;
1878 if (stats.mtimeMs > this.prev.mtimeMs)
1879 return true;
1880 if (stats.nlink !== this.prev.nlink)
1881 return true;
1882 return false;
1883 };
1884 StatWatcher.prototype.start = function (path, persistent, interval) {
1885 if (persistent === void 0) { persistent = true; }
1886 if (interval === void 0) { interval = 5007; }
1887 this.filename = pathToFilename(path);
1888 this.setTimeout = persistent ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global) : setTimeoutUnref_1.default;
1889 this.interval = interval;
1890 this.prev = this.vol.statSync(this.filename);
1891 this.loop();
1892 };
1893 StatWatcher.prototype.stop = function () {
1894 clearTimeout(this.timeoutRef);
1895 process_1.default.nextTick(emitStop, this);
1896 };
1897 return StatWatcher;
1898}(events_1.EventEmitter));
1899exports.StatWatcher = StatWatcher;
1900var pool;
1901function allocNewPool(poolSize) {
1902 pool = (0, buffer_1.bufferAllocUnsafe)(poolSize);
1903 pool.used = 0;
1904}
1905util.inherits(FsReadStream, stream_1.Readable);
1906exports.ReadStream = FsReadStream;
1907function FsReadStream(vol, path, options) {
1908 if (!(this instanceof FsReadStream))
1909 return new FsReadStream(vol, path, options);
1910 this._vol = vol;
1911 // a little bit bigger buffer and water marks by default
1912 options = Object.assign({}, getOptions(options, {}));
1913 if (options.highWaterMark === undefined)
1914 options.highWaterMark = 64 * 1024;
1915 stream_1.Readable.call(this, options);
1916 this.path = pathToFilename(path);
1917 this.fd = options.fd === undefined ? null : options.fd;
1918 this.flags = options.flags === undefined ? 'r' : options.flags;
1919 this.mode = options.mode === undefined ? 438 : options.mode;
1920 this.start = options.start;
1921 this.end = options.end;
1922 this.autoClose = options.autoClose === undefined ? true : options.autoClose;
1923 this.pos = undefined;
1924 this.bytesRead = 0;
1925 if (this.start !== undefined) {
1926 if (typeof this.start !== 'number') {
1927 throw new TypeError('"start" option must be a Number');
1928 }
1929 if (this.end === undefined) {
1930 this.end = Infinity;
1931 }
1932 else if (typeof this.end !== 'number') {
1933 throw new TypeError('"end" option must be a Number');
1934 }
1935 if (this.start > this.end) {
1936 throw new Error('"start" option must be <= "end" option');
1937 }
1938 this.pos = this.start;
1939 }
1940 if (typeof this.fd !== 'number')
1941 this.open();
1942 this.on('end', function () {
1943 if (this.autoClose) {
1944 if (this.destroy)
1945 this.destroy();
1946 }
1947 });
1948}
1949FsReadStream.prototype.open = function () {
1950 var self = this; // tslint:disable-line no-this-assignment
1951 this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
1952 if (er) {
1953 if (self.autoClose) {
1954 if (self.destroy)
1955 self.destroy();
1956 }
1957 self.emit('error', er);
1958 return;
1959 }
1960 self.fd = fd;
1961 self.emit('open', fd);
1962 // start the flow of data.
1963 self.read();
1964 });
1965};
1966FsReadStream.prototype._read = function (n) {
1967 if (typeof this.fd !== 'number') {
1968 return this.once('open', function () {
1969 this._read(n);
1970 });
1971 }
1972 if (this.destroyed)
1973 return;
1974 if (!pool || pool.length - pool.used < kMinPoolSpace) {
1975 // discard the old pool.
1976 allocNewPool(this._readableState.highWaterMark);
1977 }
1978 // Grab another reference to the pool in the case that while we're
1979 // in the thread pool another read() finishes up the pool, and
1980 // allocates a new one.
1981 var thisPool = pool;
1982 var toRead = Math.min(pool.length - pool.used, n);
1983 var start = pool.used;
1984 if (this.pos !== undefined)
1985 toRead = Math.min(this.end - this.pos + 1, toRead);
1986 // already read everything we were supposed to read!
1987 // treat as EOF.
1988 if (toRead <= 0)
1989 return this.push(null);
1990 // the actual read.
1991 var self = this; // tslint:disable-line no-this-assignment
1992 this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread);
1993 // move the pool positions, and internal position for reading.
1994 if (this.pos !== undefined)
1995 this.pos += toRead;
1996 pool.used += toRead;
1997 function onread(er, bytesRead) {
1998 if (er) {
1999 if (self.autoClose && self.destroy) {
2000 self.destroy();
2001 }
2002 self.emit('error', er);
2003 }
2004 else {
2005 var b = null;
2006 if (bytesRead > 0) {
2007 self.bytesRead += bytesRead;
2008 b = thisPool.slice(start, start + bytesRead);
2009 }
2010 self.push(b);
2011 }
2012 }
2013};
2014FsReadStream.prototype._destroy = function (err, cb) {
2015 this.close(function (err2) {
2016 cb(err || err2);
2017 });
2018};
2019FsReadStream.prototype.close = function (cb) {
2020 var _this = this;
2021 if (cb)
2022 this.once('close', cb);
2023 if (this.closed || typeof this.fd !== 'number') {
2024 if (typeof this.fd !== 'number') {
2025 this.once('open', closeOnOpen);
2026 return;
2027 }
2028 return process_1.default.nextTick(function () { return _this.emit('close'); });
2029 }
2030 this.closed = true;
2031 this._vol.close(this.fd, function (er) {
2032 if (er)
2033 _this.emit('error', er);
2034 else
2035 _this.emit('close');
2036 });
2037 this.fd = null;
2038};
2039// needed because as it will be called with arguments
2040// that does not match this.close() signature
2041function closeOnOpen(fd) {
2042 this.close();
2043}
2044util.inherits(FsWriteStream, stream_1.Writable);
2045exports.WriteStream = FsWriteStream;
2046function FsWriteStream(vol, path, options) {
2047 if (!(this instanceof FsWriteStream))
2048 return new FsWriteStream(vol, path, options);
2049 this._vol = vol;
2050 options = Object.assign({}, getOptions(options, {}));
2051 stream_1.Writable.call(this, options);
2052 this.path = pathToFilename(path);
2053 this.fd = options.fd === undefined ? null : options.fd;
2054 this.flags = options.flags === undefined ? 'w' : options.flags;
2055 this.mode = options.mode === undefined ? 438 : options.mode;
2056 this.start = options.start;
2057 this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
2058 this.pos = undefined;
2059 this.bytesWritten = 0;
2060 if (this.start !== undefined) {
2061 if (typeof this.start !== 'number') {
2062 throw new TypeError('"start" option must be a Number');
2063 }
2064 if (this.start < 0) {
2065 throw new Error('"start" must be >= zero');
2066 }
2067 this.pos = this.start;
2068 }
2069 if (options.encoding)
2070 this.setDefaultEncoding(options.encoding);
2071 if (typeof this.fd !== 'number')
2072 this.open();
2073 // dispose on finish.
2074 this.once('finish', function () {
2075 if (this.autoClose) {
2076 this.close();
2077 }
2078 });
2079}
2080FsWriteStream.prototype.open = function () {
2081 this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
2082 if (er) {
2083 if (this.autoClose && this.destroy) {
2084 this.destroy();
2085 }
2086 this.emit('error', er);
2087 return;
2088 }
2089 this.fd = fd;
2090 this.emit('open', fd);
2091 }.bind(this));
2092};
2093FsWriteStream.prototype._write = function (data, encoding, cb) {
2094 if (!(data instanceof buffer_1.Buffer))
2095 return this.emit('error', new Error('Invalid data'));
2096 if (typeof this.fd !== 'number') {
2097 return this.once('open', function () {
2098 this._write(data, encoding, cb);
2099 });
2100 }
2101 var self = this; // tslint:disable-line no-this-assignment
2102 this._vol.write(this.fd, data, 0, data.length, this.pos, function (er, bytes) {
2103 if (er) {
2104 if (self.autoClose && self.destroy) {
2105 self.destroy();
2106 }
2107 return cb(er);
2108 }
2109 self.bytesWritten += bytes;
2110 cb();
2111 });
2112 if (this.pos !== undefined)
2113 this.pos += data.length;
2114};
2115FsWriteStream.prototype._writev = function (data, cb) {
2116 if (typeof this.fd !== 'number') {
2117 return this.once('open', function () {
2118 this._writev(data, cb);
2119 });
2120 }
2121 var self = this; // tslint:disable-line no-this-assignment
2122 var len = data.length;
2123 var chunks = new Array(len);
2124 var size = 0;
2125 for (var i = 0; i < len; i++) {
2126 var chunk = data[i].chunk;
2127 chunks[i] = chunk;
2128 size += chunk.length;
2129 }
2130 var buf = buffer_1.Buffer.concat(chunks);
2131 this._vol.write(this.fd, buf, 0, buf.length, this.pos, function (er, bytes) {
2132 if (er) {
2133 if (self.destroy)
2134 self.destroy();
2135 return cb(er);
2136 }
2137 self.bytesWritten += bytes;
2138 cb();
2139 });
2140 if (this.pos !== undefined)
2141 this.pos += size;
2142};
2143FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy;
2144FsWriteStream.prototype.close = FsReadStream.prototype.close;
2145// There is no shutdown() for files.
2146FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end;
2147// ---------------------------------------- FSWatcher
2148var FSWatcher = /** @class */ (function (_super) {
2149 __extends(FSWatcher, _super);
2150 function FSWatcher(vol) {
2151 var _this = _super.call(this) || this;
2152 _this._filename = '';
2153 _this._filenameEncoded = '';
2154 // _persistent: boolean = true;
2155 _this._recursive = false;
2156 _this._encoding = encoding_1.ENCODING_UTF8;
2157 _this._onNodeChange = function () {
2158 _this._emit('change');
2159 };
2160 _this._onParentChild = function (link) {
2161 if (link.getName() === _this._getName()) {
2162 _this._emit('rename');
2163 }
2164 };
2165 _this._emit = function (type) {
2166 _this.emit('change', type, _this._filenameEncoded);
2167 };
2168 _this._persist = function () {
2169 _this._timer = setTimeout(_this._persist, 1e6);
2170 };
2171 _this._vol = vol;
2172 return _this;
2173 // TODO: Emit "error" messages when watching.
2174 // this._handle.onchange = function(status, eventType, filename) {
2175 // if (status < 0) {
2176 // self._handle.close();
2177 // const error = !filename ?
2178 // errnoException(status, 'Error watching file for changes:') :
2179 // errnoException(status, `Error watching file ${filename} for changes:`);
2180 // error.filename = filename;
2181 // self.emit('error', error);
2182 // } else {
2183 // self.emit('change', eventType, filename);
2184 // }
2185 // };
2186 }
2187 FSWatcher.prototype._getName = function () {
2188 return this._steps[this._steps.length - 1];
2189 };
2190 FSWatcher.prototype.start = function (path, persistent, recursive, encoding) {
2191 if (persistent === void 0) { persistent = true; }
2192 if (recursive === void 0) { recursive = false; }
2193 if (encoding === void 0) { encoding = encoding_1.ENCODING_UTF8; }
2194 this._filename = pathToFilename(path);
2195 this._steps = filenameToSteps(this._filename);
2196 this._filenameEncoded = (0, encoding_1.strToEncoding)(this._filename);
2197 // this._persistent = persistent;
2198 this._recursive = recursive;
2199 this._encoding = encoding;
2200 try {
2201 this._link = this._vol.getLinkOrThrow(this._filename, 'FSWatcher');
2202 }
2203 catch (err) {
2204 var error = new Error("watch " + this._filename + " " + err.code);
2205 error.code = err.code;
2206 error.errno = err.code;
2207 throw error;
2208 }
2209 this._link.getNode().on('change', this._onNodeChange);
2210 this._link.on('child:add', this._onNodeChange);
2211 this._link.on('child:delete', this._onNodeChange);
2212 var parent = this._link.parent;
2213 if (parent) {
2214 // parent.on('child:add', this._onParentChild);
2215 parent.setMaxListeners(parent.getMaxListeners() + 1);
2216 parent.on('child:delete', this._onParentChild);
2217 }
2218 if (persistent)
2219 this._persist();
2220 };
2221 FSWatcher.prototype.close = function () {
2222 clearTimeout(this._timer);
2223 this._link.getNode().removeListener('change', this._onNodeChange);
2224 var parent = this._link.parent;
2225 if (parent) {
2226 // parent.removeListener('child:add', this._onParentChild);
2227 parent.removeListener('child:delete', this._onParentChild);
2228 }
2229 };
2230 return FSWatcher;
2231}(events_1.EventEmitter));
2232exports.FSWatcher = FSWatcher;