volume.js 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249
  1. "use strict";
  2. var __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. })();
  17. var __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. };
  26. Object.defineProperty(exports, "__esModule", { value: true });
  27. exports.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;
  28. var pathModule = require("path");
  29. var node_1 = require("./node");
  30. var Stats_1 = require("./Stats");
  31. var Dirent_1 = require("./Dirent");
  32. var buffer_1 = require("./internal/buffer");
  33. var setImmediate_1 = require("./setImmediate");
  34. var process_1 = require("./process");
  35. var setTimeoutUnref_1 = require("./setTimeoutUnref");
  36. var stream_1 = require("stream");
  37. var constants_1 = require("./constants");
  38. var events_1 = require("events");
  39. var encoding_1 = require("./encoding");
  40. var errors = require("./internal/errors");
  41. var util = require("util");
  42. var promises_1 = require("./promises");
  43. var resolveCrossPlatform = pathModule.resolve;
  44. var 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;
  45. var _a = pathModule.posix ? pathModule.posix : pathModule, sep = _a.sep, relative = _a.relative, join = _a.join, dirname = _a.dirname;
  46. var isWin = process_1.default.platform === 'win32';
  47. var kMinPoolSpace = 128;
  48. // const kMaxLength = require('buffer').kMaxLength;
  49. // ---------------------------------------- Error messages
  50. // TODO: Use `internal/errors.js` in the future.
  51. var 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. };
  68. var ERRSTR_OPTS = function (tipeof) { return "Expected options to be either an object or a string, but got ".concat(tipeof, " instead"); };
  69. // const ERRSTR_FLAG = flag => `Unknown file open flag: ${flag}`;
  70. var ENOENT = 'ENOENT';
  71. var EBADF = 'EBADF';
  72. var EINVAL = 'EINVAL';
  73. var EPERM = 'EPERM';
  74. var EPROTO = 'EPROTO';
  75. var EEXIST = 'EEXIST';
  76. var ENOTDIR = 'ENOTDIR';
  77. var EMFILE = 'EMFILE';
  78. var EACCES = 'EACCES';
  79. var EISDIR = 'EISDIR';
  80. var ENOTEMPTY = 'ENOTEMPTY';
  81. var ENOSYS = 'ENOSYS';
  82. var ERR_FS_EISDIR = 'ERR_FS_EISDIR';
  83. function 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 = " '".concat(path, "'");
  90. if (path2)
  91. pathFormatted += " -> '".concat(path2, "'");
  92. switch (errorCode) {
  93. case ENOENT:
  94. return "ENOENT: no such file or directory, ".concat(func).concat(pathFormatted);
  95. case EBADF:
  96. return "EBADF: bad file descriptor, ".concat(func).concat(pathFormatted);
  97. case EINVAL:
  98. return "EINVAL: invalid argument, ".concat(func).concat(pathFormatted);
  99. case EPERM:
  100. return "EPERM: operation not permitted, ".concat(func).concat(pathFormatted);
  101. case EPROTO:
  102. return "EPROTO: protocol error, ".concat(func).concat(pathFormatted);
  103. case EEXIST:
  104. return "EEXIST: file already exists, ".concat(func).concat(pathFormatted);
  105. case ENOTDIR:
  106. return "ENOTDIR: not a directory, ".concat(func).concat(pathFormatted);
  107. case EISDIR:
  108. return "EISDIR: illegal operation on a directory, ".concat(func).concat(pathFormatted);
  109. case EACCES:
  110. return "EACCES: permission denied, ".concat(func).concat(pathFormatted);
  111. case ENOTEMPTY:
  112. return "ENOTEMPTY: directory not empty, ".concat(func).concat(pathFormatted);
  113. case EMFILE:
  114. return "EMFILE: too many open files, ".concat(func).concat(pathFormatted);
  115. case ENOSYS:
  116. return "ENOSYS: function not implemented, ".concat(func).concat(pathFormatted);
  117. case ERR_FS_EISDIR:
  118. return "[ERR_FS_EISDIR]: Path is a directory: ".concat(func, " returned EISDIR (is a directory) ").concat(path);
  119. default:
  120. return "".concat(errorCode, ": error occurred, ").concat(func).concat(pathFormatted);
  121. }
  122. }
  123. function 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.
  134. var 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 = {}));
  167. function 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. }
  178. exports.flagsToNumber = flagsToNumber;
  179. // ---------------------------------------- Options
  180. function 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. }
  201. function optsGenerator(defaults) {
  202. return function (options) { return getOptions(defaults, options); };
  203. }
  204. function validateCallback(callback) {
  205. if (typeof callback !== 'function')
  206. throw TypeError(ERRSTR.CB);
  207. return callback;
  208. }
  209. function optsAndCbGenerator(getOpts) {
  210. return function (options, callback) {
  211. return typeof options === 'function' ? [getOpts(), options] : [getOpts(options), validateCallback(callback)];
  212. };
  213. }
  214. var optsDefaults = {
  215. encoding: 'utf8',
  216. };
  217. var getDefaultOpts = optsGenerator(optsDefaults);
  218. var getDefaultOptsAndCb = optsAndCbGenerator(getDefaultOpts);
  219. var readFileOptsDefaults = {
  220. flag: 'r',
  221. };
  222. var getReadFileOptions = optsGenerator(readFileOptsDefaults);
  223. var writeFileDefaults = {
  224. encoding: 'utf8',
  225. mode: 438 /* DEFAULT */,
  226. flag: FLAGS[FLAGS.w],
  227. };
  228. var getWriteFileOptions = optsGenerator(writeFileDefaults);
  229. var appendFileDefaults = {
  230. encoding: 'utf8',
  231. mode: 438 /* DEFAULT */,
  232. flag: FLAGS[FLAGS.a],
  233. };
  234. var getAppendFileOpts = optsGenerator(appendFileDefaults);
  235. var getAppendFileOptsAndCb = optsAndCbGenerator(getAppendFileOpts);
  236. var realpathDefaults = optsDefaults;
  237. var getRealpathOptions = optsGenerator(realpathDefaults);
  238. var getRealpathOptsAndCb = optsAndCbGenerator(getRealpathOptions);
  239. var mkdirDefaults = {
  240. mode: 511 /* DIR */,
  241. recursive: false,
  242. };
  243. var getMkdirOptions = function (options) {
  244. if (typeof options === 'number')
  245. return Object.assign({}, mkdirDefaults, { mode: options });
  246. return Object.assign({}, mkdirDefaults, options);
  247. };
  248. var rmdirDefaults = {
  249. recursive: false,
  250. };
  251. var getRmdirOptions = function (options) {
  252. return Object.assign({}, rmdirDefaults, options);
  253. };
  254. var getRmOpts = optsGenerator(optsDefaults);
  255. var getRmOptsAndCb = optsAndCbGenerator(getRmOpts);
  256. var readdirDefaults = {
  257. encoding: 'utf8',
  258. withFileTypes: false,
  259. };
  260. var getReaddirOptions = optsGenerator(readdirDefaults);
  261. var getReaddirOptsAndCb = optsAndCbGenerator(getReaddirOptions);
  262. var statDefaults = {
  263. bigint: false,
  264. };
  265. var getStatOptions = function (options) {
  266. if (options === void 0) { options = {}; }
  267. return Object.assign({}, statDefaults, options);
  268. };
  269. var getStatOptsAndCb = function (options, callback) {
  270. return typeof options === 'function' ? [getStatOptions(), options] : [getStatOptions(options), validateCallback(callback)];
  271. };
  272. // ---------------------------------------- Utility functions
  273. function 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. }
  288. function 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. }
  304. exports.pathToFilename = pathToFilename;
  305. var resolve = function (filename, base) {
  306. if (base === void 0) { base = process_1.default.cwd(); }
  307. return resolveCrossPlatform(base, filename);
  308. };
  309. if (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. }
  314. function 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. }
  321. exports.filenameToSteps = filenameToSteps;
  322. function pathToSteps(path) {
  323. return filenameToSteps(pathToFilename(path));
  324. }
  325. exports.pathToSteps = pathToSteps;
  326. function 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. }
  335. exports.dataToStr = dataToStr;
  336. function 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. }
  345. exports.dataToBuffer = dataToBuffer;
  346. function bufferToEncoding(buffer, encoding) {
  347. if (!encoding || encoding === 'buffer')
  348. return buffer;
  349. else
  350. return buffer.toString(encoding);
  351. }
  352. exports.bufferToEncoding = bufferToEncoding;
  353. function 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. }
  364. function _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. }
  373. function 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. }
  379. function isFd(path) {
  380. return path >>> 0 === path;
  381. }
  382. function validateFd(fd) {
  383. if (!isFd(fd))
  384. throw TypeError(ERRSTR.FD);
  385. }
  386. // converts Date or number to a fractional UNIX timestamp
  387. function 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. }
  403. exports.toUnixTimestamp = toUnixTimestamp;
  404. function validateUid(uid) {
  405. if (typeof uid !== 'number')
  406. throw TypeError(ERRSTR.UID);
  407. }
  408. function validateGid(gid) {
  409. if (typeof gid !== 'number')
  410. throw TypeError(ERRSTR.GID);
  411. }
  412. function 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. */
  438. var 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. // Try creating a node if not found.
  675. if (flags & O_CREAT) {
  676. const dirLink = this.getLinkParent(steps);
  677. if (dirLink) {
  678. const name = steps[steps.length - 1];
  679. link = this.createLink(dirLink, name, false, perm);
  680. return link.getNode();
  681. }
  682. }
  683. throw createError(ENOENT, 'getNodeByIdOrCreate', pathToFilename(id));
  684. }
  685. }
  686. */
  687. Volume.prototype.wrapAsync = function (method, args, callback) {
  688. var _this = this;
  689. validateCallback(callback);
  690. (0, setImmediate_1.default)(function () {
  691. var result;
  692. try {
  693. result = method.apply(_this, args);
  694. }
  695. catch (err) {
  696. callback(err);
  697. return;
  698. }
  699. callback(null, result);
  700. });
  701. };
  702. Volume.prototype._toJSON = function (link, json, path) {
  703. var _a;
  704. if (link === void 0) { link = this.root; }
  705. if (json === void 0) { json = {}; }
  706. var isEmpty = true;
  707. var children = link.children;
  708. if (link.getNode().isFile()) {
  709. children = (_a = {}, _a[link.getName()] = link.parent.getChild(link.getName()), _a);
  710. link = link.parent;
  711. }
  712. for (var name_1 in children) {
  713. isEmpty = false;
  714. var child = link.getChild(name_1);
  715. if (!child) {
  716. throw new Error('_toJSON: unexpected undefined');
  717. }
  718. var node = child.getNode();
  719. if (node.isFile()) {
  720. var filename = child.getPath();
  721. if (path)
  722. filename = relative(path, filename);
  723. json[filename] = node.getString();
  724. }
  725. else if (node.isDirectory()) {
  726. this._toJSON(child, json, path);
  727. }
  728. }
  729. var dirPath = link.getPath();
  730. if (path)
  731. dirPath = relative(path, dirPath);
  732. if (dirPath && isEmpty) {
  733. json[dirPath] = null;
  734. }
  735. return json;
  736. };
  737. Volume.prototype.toJSON = function (paths, json, isRelative) {
  738. if (json === void 0) { json = {}; }
  739. if (isRelative === void 0) { isRelative = false; }
  740. var links = [];
  741. if (paths) {
  742. if (!(paths instanceof Array))
  743. paths = [paths];
  744. for (var _i = 0, paths_1 = paths; _i < paths_1.length; _i++) {
  745. var path = paths_1[_i];
  746. var filename = pathToFilename(path);
  747. var link = this.getResolvedLink(filename);
  748. if (!link)
  749. continue;
  750. links.push(link);
  751. }
  752. }
  753. else {
  754. links.push(this.root);
  755. }
  756. if (!links.length)
  757. return json;
  758. for (var _a = 0, links_1 = links; _a < links_1.length; _a++) {
  759. var link = links_1[_a];
  760. this._toJSON(link, json, isRelative ? link.getPath() : '');
  761. }
  762. return json;
  763. };
  764. Volume.prototype.fromJSON = function (json, cwd) {
  765. if (cwd === void 0) { cwd = process_1.default.cwd(); }
  766. for (var filename in json) {
  767. var data = json[filename];
  768. filename = resolve(filename, cwd);
  769. if (typeof data === 'string') {
  770. var dir = dirname(filename);
  771. this.mkdirpBase(dir, 511 /* DIR */);
  772. this.writeFileSync(filename, data);
  773. }
  774. else {
  775. this.mkdirpBase(filename, 511 /* DIR */);
  776. }
  777. }
  778. };
  779. Volume.prototype.fromNestedJSON = function (json, cwd) {
  780. this.fromJSON(flattenJSON(json), cwd);
  781. };
  782. Volume.prototype.reset = function () {
  783. this.ino = 0;
  784. this.inodes = {};
  785. this.releasedInos = [];
  786. this.fds = {};
  787. this.releasedFds = [];
  788. this.openFiles = 0;
  789. this.root = this.createLink();
  790. this.root.setNode(this.createNode(true));
  791. };
  792. // Legacy interface
  793. Volume.prototype.mountSync = function (mountpoint, json) {
  794. this.fromJSON(json, mountpoint);
  795. };
  796. Volume.prototype.openLink = function (link, flagsNum, resolveSymlinks) {
  797. if (resolveSymlinks === void 0) { resolveSymlinks = true; }
  798. if (this.openFiles >= this.maxFiles) {
  799. // Too many open files.
  800. throw createError(EMFILE, 'open', link.getPath());
  801. }
  802. // Resolve symlinks.
  803. var realLink = link;
  804. if (resolveSymlinks)
  805. realLink = this.resolveSymlinks(link);
  806. if (!realLink)
  807. throw createError(ENOENT, 'open', link.getPath());
  808. var node = realLink.getNode();
  809. // Check whether node is a directory
  810. if (node.isDirectory()) {
  811. if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY)
  812. throw createError(EISDIR, 'open', link.getPath());
  813. }
  814. else {
  815. if (flagsNum & O_DIRECTORY)
  816. throw createError(ENOTDIR, 'open', link.getPath());
  817. }
  818. // Check node permissions
  819. if (!(flagsNum & O_WRONLY)) {
  820. if (!node.canRead()) {
  821. throw createError(EACCES, 'open', link.getPath());
  822. }
  823. }
  824. if (flagsNum & O_RDWR) {
  825. }
  826. var file = new this.props.File(link, node, flagsNum, this.newFdNumber());
  827. this.fds[file.fd] = file;
  828. this.openFiles++;
  829. if (flagsNum & O_TRUNC)
  830. file.truncate();
  831. return file;
  832. };
  833. Volume.prototype.openFile = function (filename, flagsNum, modeNum, resolveSymlinks) {
  834. if (resolveSymlinks === void 0) { resolveSymlinks = true; }
  835. var steps = filenameToSteps(filename);
  836. var link = resolveSymlinks ? this.getResolvedLink(steps) : this.getLink(steps);
  837. // Try creating a new file, if it does not exist.
  838. if (!link && flagsNum & O_CREAT) {
  839. // const dirLink: Link = this.getLinkParent(steps);
  840. var dirLink = this.getResolvedLink(steps.slice(0, steps.length - 1));
  841. // if(!dirLink) throw createError(ENOENT, 'open', filename);
  842. if (!dirLink)
  843. throw createError(ENOENT, 'open', sep + steps.join(sep));
  844. if (flagsNum & O_CREAT && typeof modeNum === 'number') {
  845. link = this.createLink(dirLink, steps[steps.length - 1], false, modeNum);
  846. }
  847. }
  848. if (link)
  849. return this.openLink(link, flagsNum, resolveSymlinks);
  850. throw createError(ENOENT, 'open', filename);
  851. };
  852. Volume.prototype.openBase = function (filename, flagsNum, modeNum, resolveSymlinks) {
  853. if (resolveSymlinks === void 0) { resolveSymlinks = true; }
  854. var file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks);
  855. if (!file)
  856. throw createError(ENOENT, 'open', filename);
  857. return file.fd;
  858. };
  859. Volume.prototype.openSync = function (path, flags, mode) {
  860. if (mode === void 0) { mode = 438 /* DEFAULT */; }
  861. // Validate (1) mode; (2) path; (3) flags - in that order.
  862. var modeNum = modeToNumber(mode);
  863. var fileName = pathToFilename(path);
  864. var flagsNum = flagsToNumber(flags);
  865. return this.openBase(fileName, flagsNum, modeNum);
  866. };
  867. Volume.prototype.open = function (path, flags, a, b) {
  868. var mode = a;
  869. var callback = b;
  870. if (typeof a === 'function') {
  871. mode = 438 /* DEFAULT */;
  872. callback = a;
  873. }
  874. mode = mode || 438 /* DEFAULT */;
  875. var modeNum = modeToNumber(mode);
  876. var fileName = pathToFilename(path);
  877. var flagsNum = flagsToNumber(flags);
  878. this.wrapAsync(this.openBase, [fileName, flagsNum, modeNum], callback);
  879. };
  880. Volume.prototype.closeFile = function (file) {
  881. if (!this.fds[file.fd])
  882. return;
  883. this.openFiles--;
  884. delete this.fds[file.fd];
  885. this.releasedFds.push(file.fd);
  886. };
  887. Volume.prototype.closeSync = function (fd) {
  888. validateFd(fd);
  889. var file = this.getFileByFdOrThrow(fd, 'close');
  890. this.closeFile(file);
  891. };
  892. Volume.prototype.close = function (fd, callback) {
  893. validateFd(fd);
  894. this.wrapAsync(this.closeSync, [fd], callback);
  895. };
  896. Volume.prototype.openFileOrGetById = function (id, flagsNum, modeNum) {
  897. if (typeof id === 'number') {
  898. var file = this.fds[id];
  899. if (!file)
  900. throw createError(ENOENT);
  901. return file;
  902. }
  903. else {
  904. return this.openFile(pathToFilename(id), flagsNum, modeNum);
  905. }
  906. };
  907. Volume.prototype.readBase = function (fd, buffer, offset, length, position) {
  908. var file = this.getFileByFdOrThrow(fd);
  909. return file.read(buffer, Number(offset), Number(length), position);
  910. };
  911. Volume.prototype.readSync = function (fd, buffer, offset, length, position) {
  912. validateFd(fd);
  913. return this.readBase(fd, buffer, offset, length, position);
  914. };
  915. Volume.prototype.read = function (fd, buffer, offset, length, position, callback) {
  916. var _this = this;
  917. validateCallback(callback);
  918. // This `if` branch is from Node.js
  919. if (length === 0) {
  920. return process_1.default.nextTick(function () {
  921. if (callback)
  922. callback(null, 0, buffer);
  923. });
  924. }
  925. (0, setImmediate_1.default)(function () {
  926. try {
  927. var bytes = _this.readBase(fd, buffer, offset, length, position);
  928. callback(null, bytes, buffer);
  929. }
  930. catch (err) {
  931. callback(err);
  932. }
  933. });
  934. };
  935. Volume.prototype.readFileBase = function (id, flagsNum, encoding) {
  936. var result;
  937. var isUserFd = typeof id === 'number';
  938. var userOwnsFd = isUserFd && isFd(id);
  939. var fd;
  940. if (userOwnsFd)
  941. fd = id;
  942. else {
  943. var filename = pathToFilename(id);
  944. var steps = filenameToSteps(filename);
  945. var link = this.getResolvedLink(steps);
  946. if (link) {
  947. var node = link.getNode();
  948. if (node.isDirectory())
  949. throw createError(EISDIR, 'open', link.getPath());
  950. }
  951. fd = this.openSync(id, flagsNum);
  952. }
  953. try {
  954. result = bufferToEncoding(this.getFileByFdOrThrow(fd).getBuffer(), encoding);
  955. }
  956. finally {
  957. if (!userOwnsFd) {
  958. this.closeSync(fd);
  959. }
  960. }
  961. return result;
  962. };
  963. Volume.prototype.readFileSync = function (file, options) {
  964. var opts = getReadFileOptions(options);
  965. var flagsNum = flagsToNumber(opts.flag);
  966. return this.readFileBase(file, flagsNum, opts.encoding);
  967. };
  968. Volume.prototype.readFile = function (id, a, b) {
  969. var _a = optsAndCbGenerator(getReadFileOptions)(a, b), opts = _a[0], callback = _a[1];
  970. var flagsNum = flagsToNumber(opts.flag);
  971. this.wrapAsync(this.readFileBase, [id, flagsNum, opts.encoding], callback);
  972. };
  973. Volume.prototype.writeBase = function (fd, buf, offset, length, position) {
  974. var file = this.getFileByFdOrThrow(fd, 'write');
  975. return file.write(buf, offset, length, position);
  976. };
  977. Volume.prototype.writeSync = function (fd, a, b, c, d) {
  978. validateFd(fd);
  979. var encoding;
  980. var offset;
  981. var length;
  982. var position;
  983. var isBuffer = typeof a !== 'string';
  984. if (isBuffer) {
  985. offset = (b || 0) | 0;
  986. length = c;
  987. position = d;
  988. }
  989. else {
  990. position = b;
  991. encoding = c;
  992. }
  993. var buf = dataToBuffer(a, encoding);
  994. if (isBuffer) {
  995. if (typeof length === 'undefined') {
  996. length = buf.length;
  997. }
  998. }
  999. else {
  1000. offset = 0;
  1001. length = buf.length;
  1002. }
  1003. return this.writeBase(fd, buf, offset, length, position);
  1004. };
  1005. Volume.prototype.write = function (fd, a, b, c, d, e) {
  1006. var _this = this;
  1007. validateFd(fd);
  1008. var offset;
  1009. var length;
  1010. var position;
  1011. var encoding;
  1012. var callback;
  1013. var tipa = typeof a;
  1014. var tipb = typeof b;
  1015. var tipc = typeof c;
  1016. var tipd = typeof d;
  1017. if (tipa !== 'string') {
  1018. if (tipb === 'function') {
  1019. callback = b;
  1020. }
  1021. else if (tipc === 'function') {
  1022. offset = b | 0;
  1023. callback = c;
  1024. }
  1025. else if (tipd === 'function') {
  1026. offset = b | 0;
  1027. length = c;
  1028. callback = d;
  1029. }
  1030. else {
  1031. offset = b | 0;
  1032. length = c;
  1033. position = d;
  1034. callback = e;
  1035. }
  1036. }
  1037. else {
  1038. if (tipb === 'function') {
  1039. callback = b;
  1040. }
  1041. else if (tipc === 'function') {
  1042. position = b;
  1043. callback = c;
  1044. }
  1045. else if (tipd === 'function') {
  1046. position = b;
  1047. encoding = c;
  1048. callback = d;
  1049. }
  1050. }
  1051. var buf = dataToBuffer(a, encoding);
  1052. if (tipa !== 'string') {
  1053. if (typeof length === 'undefined')
  1054. length = buf.length;
  1055. }
  1056. else {
  1057. offset = 0;
  1058. length = buf.length;
  1059. }
  1060. var cb = validateCallback(callback);
  1061. (0, setImmediate_1.default)(function () {
  1062. try {
  1063. var bytes = _this.writeBase(fd, buf, offset, length, position);
  1064. if (tipa !== 'string') {
  1065. cb(null, bytes, buf);
  1066. }
  1067. else {
  1068. cb(null, bytes, a);
  1069. }
  1070. }
  1071. catch (err) {
  1072. cb(err);
  1073. }
  1074. });
  1075. };
  1076. Volume.prototype.writeFileBase = function (id, buf, flagsNum, modeNum) {
  1077. // console.log('writeFileBase', id, buf, flagsNum, modeNum);
  1078. // const node = this.getNodeByIdOrCreate(id, flagsNum, modeNum);
  1079. // node.setBuffer(buf);
  1080. var isUserFd = typeof id === 'number';
  1081. var fd;
  1082. if (isUserFd)
  1083. fd = id;
  1084. else {
  1085. fd = this.openBase(pathToFilename(id), flagsNum, modeNum);
  1086. // fd = this.openSync(id as PathLike, flagsNum, modeNum);
  1087. }
  1088. var offset = 0;
  1089. var length = buf.length;
  1090. var position = flagsNum & O_APPEND ? undefined : 0;
  1091. try {
  1092. while (length > 0) {
  1093. var written = this.writeSync(fd, buf, offset, length, position);
  1094. offset += written;
  1095. length -= written;
  1096. if (position !== undefined)
  1097. position += written;
  1098. }
  1099. }
  1100. finally {
  1101. if (!isUserFd)
  1102. this.closeSync(fd);
  1103. }
  1104. };
  1105. Volume.prototype.writeFileSync = function (id, data, options) {
  1106. var opts = getWriteFileOptions(options);
  1107. var flagsNum = flagsToNumber(opts.flag);
  1108. var modeNum = modeToNumber(opts.mode);
  1109. var buf = dataToBuffer(data, opts.encoding);
  1110. this.writeFileBase(id, buf, flagsNum, modeNum);
  1111. };
  1112. Volume.prototype.writeFile = function (id, data, a, b) {
  1113. var options = a;
  1114. var callback = b;
  1115. if (typeof a === 'function') {
  1116. options = writeFileDefaults;
  1117. callback = a;
  1118. }
  1119. var cb = validateCallback(callback);
  1120. var opts = getWriteFileOptions(options);
  1121. var flagsNum = flagsToNumber(opts.flag);
  1122. var modeNum = modeToNumber(opts.mode);
  1123. var buf = dataToBuffer(data, opts.encoding);
  1124. this.wrapAsync(this.writeFileBase, [id, buf, flagsNum, modeNum], cb);
  1125. };
  1126. Volume.prototype.linkBase = function (filename1, filename2) {
  1127. var steps1 = filenameToSteps(filename1);
  1128. var link1 = this.getLink(steps1);
  1129. if (!link1)
  1130. throw createError(ENOENT, 'link', filename1, filename2);
  1131. var steps2 = filenameToSteps(filename2);
  1132. // Check new link directory exists.
  1133. var dir2 = this.getLinkParent(steps2);
  1134. if (!dir2)
  1135. throw createError(ENOENT, 'link', filename1, filename2);
  1136. var name = steps2[steps2.length - 1];
  1137. // Check if new file already exists.
  1138. if (dir2.getChild(name))
  1139. throw createError(EEXIST, 'link', filename1, filename2);
  1140. var node = link1.getNode();
  1141. node.nlink++;
  1142. dir2.createChild(name, node);
  1143. };
  1144. Volume.prototype.copyFileBase = function (src, dest, flags) {
  1145. var buf = this.readFileSync(src);
  1146. if (flags & COPYFILE_EXCL) {
  1147. if (this.existsSync(dest)) {
  1148. throw createError(EEXIST, 'copyFile', src, dest);
  1149. }
  1150. }
  1151. if (flags & COPYFILE_FICLONE_FORCE) {
  1152. throw createError(ENOSYS, 'copyFile', src, dest);
  1153. }
  1154. this.writeFileBase(dest, buf, FLAGS.w, 438 /* DEFAULT */);
  1155. };
  1156. Volume.prototype.copyFileSync = function (src, dest, flags) {
  1157. var srcFilename = pathToFilename(src);
  1158. var destFilename = pathToFilename(dest);
  1159. return this.copyFileBase(srcFilename, destFilename, (flags || 0) | 0);
  1160. };
  1161. Volume.prototype.copyFile = function (src, dest, a, b) {
  1162. var srcFilename = pathToFilename(src);
  1163. var destFilename = pathToFilename(dest);
  1164. var flags;
  1165. var callback;
  1166. if (typeof a === 'function') {
  1167. flags = 0;
  1168. callback = a;
  1169. }
  1170. else {
  1171. flags = a;
  1172. callback = b;
  1173. }
  1174. validateCallback(callback);
  1175. this.wrapAsync(this.copyFileBase, [srcFilename, destFilename, flags], callback);
  1176. };
  1177. Volume.prototype.linkSync = function (existingPath, newPath) {
  1178. var existingPathFilename = pathToFilename(existingPath);
  1179. var newPathFilename = pathToFilename(newPath);
  1180. this.linkBase(existingPathFilename, newPathFilename);
  1181. };
  1182. Volume.prototype.link = function (existingPath, newPath, callback) {
  1183. var existingPathFilename = pathToFilename(existingPath);
  1184. var newPathFilename = pathToFilename(newPath);
  1185. this.wrapAsync(this.linkBase, [existingPathFilename, newPathFilename], callback);
  1186. };
  1187. Volume.prototype.unlinkBase = function (filename) {
  1188. var steps = filenameToSteps(filename);
  1189. var link = this.getLink(steps);
  1190. if (!link)
  1191. throw createError(ENOENT, 'unlink', filename);
  1192. // TODO: Check if it is file, dir, other...
  1193. if (link.length)
  1194. throw Error('Dir not empty...');
  1195. this.deleteLink(link);
  1196. var node = link.getNode();
  1197. node.nlink--;
  1198. // When all hard links to i-node are deleted, remove the i-node, too.
  1199. if (node.nlink <= 0) {
  1200. this.deleteNode(node);
  1201. }
  1202. };
  1203. Volume.prototype.unlinkSync = function (path) {
  1204. var filename = pathToFilename(path);
  1205. this.unlinkBase(filename);
  1206. };
  1207. Volume.prototype.unlink = function (path, callback) {
  1208. var filename = pathToFilename(path);
  1209. this.wrapAsync(this.unlinkBase, [filename], callback);
  1210. };
  1211. Volume.prototype.symlinkBase = function (targetFilename, pathFilename) {
  1212. var pathSteps = filenameToSteps(pathFilename);
  1213. // Check if directory exists, where we about to create a symlink.
  1214. var dirLink = this.getLinkParent(pathSteps);
  1215. if (!dirLink)
  1216. throw createError(ENOENT, 'symlink', targetFilename, pathFilename);
  1217. var name = pathSteps[pathSteps.length - 1];
  1218. // Check if new file already exists.
  1219. if (dirLink.getChild(name))
  1220. throw createError(EEXIST, 'symlink', targetFilename, pathFilename);
  1221. // Create symlink.
  1222. var symlink = dirLink.createChild(name);
  1223. symlink.getNode().makeSymlink(filenameToSteps(targetFilename));
  1224. return symlink;
  1225. };
  1226. // `type` argument works only on Windows.
  1227. Volume.prototype.symlinkSync = function (target, path, type) {
  1228. var targetFilename = pathToFilename(target);
  1229. var pathFilename = pathToFilename(path);
  1230. this.symlinkBase(targetFilename, pathFilename);
  1231. };
  1232. Volume.prototype.symlink = function (target, path, a, b) {
  1233. var callback = validateCallback(typeof a === 'function' ? a : b);
  1234. var targetFilename = pathToFilename(target);
  1235. var pathFilename = pathToFilename(path);
  1236. this.wrapAsync(this.symlinkBase, [targetFilename, pathFilename], callback);
  1237. };
  1238. Volume.prototype.realpathBase = function (filename, encoding) {
  1239. var steps = filenameToSteps(filename);
  1240. var realLink = this.getResolvedLink(steps);
  1241. if (!realLink)
  1242. throw createError(ENOENT, 'realpath', filename);
  1243. return (0, encoding_1.strToEncoding)(realLink.getPath(), encoding);
  1244. };
  1245. Volume.prototype.realpathSync = function (path, options) {
  1246. return this.realpathBase(pathToFilename(path), getRealpathOptions(options).encoding);
  1247. };
  1248. Volume.prototype.realpath = function (path, a, b) {
  1249. var _a = getRealpathOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1250. var pathFilename = pathToFilename(path);
  1251. this.wrapAsync(this.realpathBase, [pathFilename, opts.encoding], callback);
  1252. };
  1253. Volume.prototype.lstatBase = function (filename, bigint, throwIfNoEntry) {
  1254. if (bigint === void 0) { bigint = false; }
  1255. if (throwIfNoEntry === void 0) { throwIfNoEntry = false; }
  1256. var link = this.getLink(filenameToSteps(filename));
  1257. if (link) {
  1258. return Stats_1.default.build(link.getNode(), bigint);
  1259. }
  1260. else if (!throwIfNoEntry) {
  1261. return undefined;
  1262. }
  1263. else {
  1264. throw createError(ENOENT, 'lstat', filename);
  1265. }
  1266. };
  1267. Volume.prototype.lstatSync = function (path, options) {
  1268. var _a = getStatOptions(options), _b = _a.throwIfNoEntry, throwIfNoEntry = _b === void 0 ? true : _b, _c = _a.bigint, bigint = _c === void 0 ? false : _c;
  1269. return this.lstatBase(pathToFilename(path), bigint, throwIfNoEntry);
  1270. };
  1271. Volume.prototype.lstat = function (path, a, b) {
  1272. var _a = getStatOptsAndCb(a, b), _b = _a[0], _c = _b.throwIfNoEntry, throwIfNoEntry = _c === void 0 ? true : _c, _d = _b.bigint, bigint = _d === void 0 ? false : _d, callback = _a[1];
  1273. this.wrapAsync(this.lstatBase, [pathToFilename(path), bigint, throwIfNoEntry], callback);
  1274. };
  1275. Volume.prototype.statBase = function (filename, bigint, throwIfNoEntry) {
  1276. if (bigint === void 0) { bigint = false; }
  1277. if (throwIfNoEntry === void 0) { throwIfNoEntry = true; }
  1278. var link = this.getResolvedLink(filenameToSteps(filename));
  1279. if (link) {
  1280. return Stats_1.default.build(link.getNode(), bigint);
  1281. }
  1282. else if (!throwIfNoEntry) {
  1283. return undefined;
  1284. }
  1285. else {
  1286. throw createError(ENOENT, 'stat', filename);
  1287. }
  1288. };
  1289. Volume.prototype.statSync = function (path, options) {
  1290. var _a = getStatOptions(options), _b = _a.bigint, bigint = _b === void 0 ? true : _b, _c = _a.throwIfNoEntry, throwIfNoEntry = _c === void 0 ? true : _c;
  1291. return this.statBase(pathToFilename(path), bigint, throwIfNoEntry);
  1292. };
  1293. Volume.prototype.stat = function (path, a, b) {
  1294. var _a = getStatOptsAndCb(a, b), _b = _a[0], _c = _b.bigint, bigint = _c === void 0 ? false : _c, _d = _b.throwIfNoEntry, throwIfNoEntry = _d === void 0 ? true : _d, callback = _a[1];
  1295. this.wrapAsync(this.statBase, [pathToFilename(path), bigint, throwIfNoEntry], callback);
  1296. };
  1297. Volume.prototype.fstatBase = function (fd, bigint) {
  1298. if (bigint === void 0) { bigint = false; }
  1299. var file = this.getFileByFd(fd);
  1300. if (!file)
  1301. throw createError(EBADF, 'fstat');
  1302. return Stats_1.default.build(file.node, bigint);
  1303. };
  1304. Volume.prototype.fstatSync = function (fd, options) {
  1305. return this.fstatBase(fd, getStatOptions(options).bigint);
  1306. };
  1307. Volume.prototype.fstat = function (fd, a, b) {
  1308. var _a = getStatOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1309. this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback);
  1310. };
  1311. Volume.prototype.renameBase = function (oldPathFilename, newPathFilename) {
  1312. var link = this.getLink(filenameToSteps(oldPathFilename));
  1313. if (!link)
  1314. throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
  1315. // TODO: Check if it is directory, if non-empty, we cannot move it, right?
  1316. var newPathSteps = filenameToSteps(newPathFilename);
  1317. // Check directory exists for the new location.
  1318. var newPathDirLink = this.getLinkParent(newPathSteps);
  1319. if (!newPathDirLink)
  1320. throw createError(ENOENT, 'rename', oldPathFilename, newPathFilename);
  1321. // TODO: Also treat cases with directories and symbolic links.
  1322. // TODO: See: http://man7.org/linux/man-pages/man2/rename.2.html
  1323. // Remove hard link from old folder.
  1324. var oldLinkParent = link.parent;
  1325. if (oldLinkParent) {
  1326. oldLinkParent.deleteChild(link);
  1327. }
  1328. // Rename should overwrite the new path, if that exists.
  1329. var name = newPathSteps[newPathSteps.length - 1];
  1330. link.name = name;
  1331. link.steps = __spreadArray(__spreadArray([], newPathDirLink.steps, true), [name], false);
  1332. newPathDirLink.setChild(link.getName(), link);
  1333. };
  1334. Volume.prototype.renameSync = function (oldPath, newPath) {
  1335. var oldPathFilename = pathToFilename(oldPath);
  1336. var newPathFilename = pathToFilename(newPath);
  1337. this.renameBase(oldPathFilename, newPathFilename);
  1338. };
  1339. Volume.prototype.rename = function (oldPath, newPath, callback) {
  1340. var oldPathFilename = pathToFilename(oldPath);
  1341. var newPathFilename = pathToFilename(newPath);
  1342. this.wrapAsync(this.renameBase, [oldPathFilename, newPathFilename], callback);
  1343. };
  1344. Volume.prototype.existsBase = function (filename) {
  1345. return !!this.statBase(filename);
  1346. };
  1347. Volume.prototype.existsSync = function (path) {
  1348. try {
  1349. return this.existsBase(pathToFilename(path));
  1350. }
  1351. catch (err) {
  1352. return false;
  1353. }
  1354. };
  1355. Volume.prototype.exists = function (path, callback) {
  1356. var _this = this;
  1357. var filename = pathToFilename(path);
  1358. if (typeof callback !== 'function')
  1359. throw Error(ERRSTR.CB);
  1360. (0, setImmediate_1.default)(function () {
  1361. try {
  1362. callback(_this.existsBase(filename));
  1363. }
  1364. catch (err) {
  1365. callback(false);
  1366. }
  1367. });
  1368. };
  1369. Volume.prototype.accessBase = function (filename, mode) {
  1370. var link = this.getLinkOrThrow(filename, 'access');
  1371. // TODO: Verify permissions
  1372. };
  1373. Volume.prototype.accessSync = function (path, mode) {
  1374. if (mode === void 0) { mode = F_OK; }
  1375. var filename = pathToFilename(path);
  1376. mode = mode | 0;
  1377. this.accessBase(filename, mode);
  1378. };
  1379. Volume.prototype.access = function (path, a, b) {
  1380. var mode = F_OK;
  1381. var callback;
  1382. if (typeof a !== 'function') {
  1383. mode = a | 0; // cast to number
  1384. callback = validateCallback(b);
  1385. }
  1386. else {
  1387. callback = a;
  1388. }
  1389. var filename = pathToFilename(path);
  1390. this.wrapAsync(this.accessBase, [filename, mode], callback);
  1391. };
  1392. Volume.prototype.appendFileSync = function (id, data, options) {
  1393. if (options === void 0) { options = appendFileDefaults; }
  1394. var opts = getAppendFileOpts(options);
  1395. // force append behavior when using a supplied file descriptor
  1396. if (!opts.flag || isFd(id))
  1397. opts.flag = 'a';
  1398. this.writeFileSync(id, data, opts);
  1399. };
  1400. Volume.prototype.appendFile = function (id, data, a, b) {
  1401. var _a = getAppendFileOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1402. // force append behavior when using a supplied file descriptor
  1403. if (!opts.flag || isFd(id))
  1404. opts.flag = 'a';
  1405. this.writeFile(id, data, opts, callback);
  1406. };
  1407. Volume.prototype.readdirBase = function (filename, options) {
  1408. var steps = filenameToSteps(filename);
  1409. var link = this.getResolvedLink(steps);
  1410. if (!link)
  1411. throw createError(ENOENT, 'readdir', filename);
  1412. var node = link.getNode();
  1413. if (!node.isDirectory())
  1414. throw createError(ENOTDIR, 'scandir', filename);
  1415. if (options.withFileTypes) {
  1416. var list_1 = [];
  1417. for (var name_2 in link.children) {
  1418. var child = link.getChild(name_2);
  1419. if (!child) {
  1420. continue;
  1421. }
  1422. list_1.push(Dirent_1.default.build(child, options.encoding));
  1423. }
  1424. if (!isWin && options.encoding !== 'buffer')
  1425. list_1.sort(function (a, b) {
  1426. if (a.name < b.name)
  1427. return -1;
  1428. if (a.name > b.name)
  1429. return 1;
  1430. return 0;
  1431. });
  1432. return list_1;
  1433. }
  1434. var list = [];
  1435. for (var name_3 in link.children) {
  1436. list.push((0, encoding_1.strToEncoding)(name_3, options.encoding));
  1437. }
  1438. if (!isWin && options.encoding !== 'buffer')
  1439. list.sort();
  1440. return list;
  1441. };
  1442. Volume.prototype.readdirSync = function (path, options) {
  1443. var opts = getReaddirOptions(options);
  1444. var filename = pathToFilename(path);
  1445. return this.readdirBase(filename, opts);
  1446. };
  1447. Volume.prototype.readdir = function (path, a, b) {
  1448. var _a = getReaddirOptsAndCb(a, b), options = _a[0], callback = _a[1];
  1449. var filename = pathToFilename(path);
  1450. this.wrapAsync(this.readdirBase, [filename, options], callback);
  1451. };
  1452. Volume.prototype.readlinkBase = function (filename, encoding) {
  1453. var link = this.getLinkOrThrow(filename, 'readlink');
  1454. var node = link.getNode();
  1455. if (!node.isSymlink())
  1456. throw createError(EINVAL, 'readlink', filename);
  1457. var str = sep + node.symlink.join(sep);
  1458. return (0, encoding_1.strToEncoding)(str, encoding);
  1459. };
  1460. Volume.prototype.readlinkSync = function (path, options) {
  1461. var opts = getDefaultOpts(options);
  1462. var filename = pathToFilename(path);
  1463. return this.readlinkBase(filename, opts.encoding);
  1464. };
  1465. Volume.prototype.readlink = function (path, a, b) {
  1466. var _a = getDefaultOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1467. var filename = pathToFilename(path);
  1468. this.wrapAsync(this.readlinkBase, [filename, opts.encoding], callback);
  1469. };
  1470. Volume.prototype.fsyncBase = function (fd) {
  1471. this.getFileByFdOrThrow(fd, 'fsync');
  1472. };
  1473. Volume.prototype.fsyncSync = function (fd) {
  1474. this.fsyncBase(fd);
  1475. };
  1476. Volume.prototype.fsync = function (fd, callback) {
  1477. this.wrapAsync(this.fsyncBase, [fd], callback);
  1478. };
  1479. Volume.prototype.fdatasyncBase = function (fd) {
  1480. this.getFileByFdOrThrow(fd, 'fdatasync');
  1481. };
  1482. Volume.prototype.fdatasyncSync = function (fd) {
  1483. this.fdatasyncBase(fd);
  1484. };
  1485. Volume.prototype.fdatasync = function (fd, callback) {
  1486. this.wrapAsync(this.fdatasyncBase, [fd], callback);
  1487. };
  1488. Volume.prototype.ftruncateBase = function (fd, len) {
  1489. var file = this.getFileByFdOrThrow(fd, 'ftruncate');
  1490. file.truncate(len);
  1491. };
  1492. Volume.prototype.ftruncateSync = function (fd, len) {
  1493. this.ftruncateBase(fd, len);
  1494. };
  1495. Volume.prototype.ftruncate = function (fd, a, b) {
  1496. var len = typeof a === 'number' ? a : 0;
  1497. var callback = validateCallback(typeof a === 'number' ? b : a);
  1498. this.wrapAsync(this.ftruncateBase, [fd, len], callback);
  1499. };
  1500. Volume.prototype.truncateBase = function (path, len) {
  1501. var fd = this.openSync(path, 'r+');
  1502. try {
  1503. this.ftruncateSync(fd, len);
  1504. }
  1505. finally {
  1506. this.closeSync(fd);
  1507. }
  1508. };
  1509. Volume.prototype.truncateSync = function (id, len) {
  1510. if (isFd(id))
  1511. return this.ftruncateSync(id, len);
  1512. this.truncateBase(id, len);
  1513. };
  1514. Volume.prototype.truncate = function (id, a, b) {
  1515. var len = typeof a === 'number' ? a : 0;
  1516. var callback = validateCallback(typeof a === 'number' ? b : a);
  1517. if (isFd(id))
  1518. return this.ftruncate(id, len, callback);
  1519. this.wrapAsync(this.truncateBase, [id, len], callback);
  1520. };
  1521. Volume.prototype.futimesBase = function (fd, atime, mtime) {
  1522. var file = this.getFileByFdOrThrow(fd, 'futimes');
  1523. var node = file.node;
  1524. node.atime = new Date(atime * 1000);
  1525. node.mtime = new Date(mtime * 1000);
  1526. };
  1527. Volume.prototype.futimesSync = function (fd, atime, mtime) {
  1528. this.futimesBase(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime));
  1529. };
  1530. Volume.prototype.futimes = function (fd, atime, mtime, callback) {
  1531. this.wrapAsync(this.futimesBase, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  1532. };
  1533. Volume.prototype.utimesBase = function (filename, atime, mtime) {
  1534. var fd = this.openSync(filename, 'r+');
  1535. try {
  1536. this.futimesBase(fd, atime, mtime);
  1537. }
  1538. finally {
  1539. this.closeSync(fd);
  1540. }
  1541. };
  1542. Volume.prototype.utimesSync = function (path, atime, mtime) {
  1543. this.utimesBase(pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime));
  1544. };
  1545. Volume.prototype.utimes = function (path, atime, mtime, callback) {
  1546. this.wrapAsync(this.utimesBase, [pathToFilename(path), toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  1547. };
  1548. Volume.prototype.mkdirBase = function (filename, modeNum) {
  1549. var steps = filenameToSteps(filename);
  1550. // This will throw if user tries to create root dir `fs.mkdirSync('/')`.
  1551. if (!steps.length) {
  1552. throw createError(EEXIST, 'mkdir', filename);
  1553. }
  1554. var dir = this.getLinkParentAsDirOrThrow(filename, 'mkdir');
  1555. // Check path already exists.
  1556. var name = steps[steps.length - 1];
  1557. if (dir.getChild(name))
  1558. throw createError(EEXIST, 'mkdir', filename);
  1559. dir.createChild(name, this.createNode(true, modeNum));
  1560. };
  1561. /**
  1562. * Creates directory tree recursively.
  1563. * @param filename
  1564. * @param modeNum
  1565. */
  1566. Volume.prototype.mkdirpBase = function (filename, modeNum) {
  1567. var steps = filenameToSteps(filename);
  1568. var link = this.root;
  1569. for (var i = 0; i < steps.length; i++) {
  1570. var step = steps[i];
  1571. if (!link.getNode().isDirectory())
  1572. throw createError(ENOTDIR, 'mkdir', link.getPath());
  1573. var child = link.getChild(step);
  1574. if (child) {
  1575. if (child.getNode().isDirectory())
  1576. link = child;
  1577. else
  1578. throw createError(ENOTDIR, 'mkdir', child.getPath());
  1579. }
  1580. else {
  1581. link = link.createChild(step, this.createNode(true, modeNum));
  1582. }
  1583. }
  1584. };
  1585. Volume.prototype.mkdirSync = function (path, options) {
  1586. var opts = getMkdirOptions(options);
  1587. var modeNum = modeToNumber(opts.mode, 511);
  1588. var filename = pathToFilename(path);
  1589. if (opts.recursive)
  1590. this.mkdirpBase(filename, modeNum);
  1591. else
  1592. this.mkdirBase(filename, modeNum);
  1593. };
  1594. Volume.prototype.mkdir = function (path, a, b) {
  1595. var opts = getMkdirOptions(a);
  1596. var callback = validateCallback(typeof a === 'function' ? a : b);
  1597. var modeNum = modeToNumber(opts.mode, 511);
  1598. var filename = pathToFilename(path);
  1599. if (opts.recursive)
  1600. this.wrapAsync(this.mkdirpBase, [filename, modeNum], callback);
  1601. else
  1602. this.wrapAsync(this.mkdirBase, [filename, modeNum], callback);
  1603. };
  1604. // legacy interface
  1605. Volume.prototype.mkdirpSync = function (path, mode) {
  1606. this.mkdirSync(path, { mode: mode, recursive: true });
  1607. };
  1608. Volume.prototype.mkdirp = function (path, a, b) {
  1609. var mode = typeof a === 'function' ? undefined : a;
  1610. var callback = validateCallback(typeof a === 'function' ? a : b);
  1611. this.mkdir(path, { mode: mode, recursive: true }, callback);
  1612. };
  1613. Volume.prototype.mkdtempBase = function (prefix, encoding, retry) {
  1614. if (retry === void 0) { retry = 5; }
  1615. var filename = prefix + this.genRndStr();
  1616. try {
  1617. this.mkdirBase(filename, 511 /* DIR */);
  1618. return (0, encoding_1.strToEncoding)(filename, encoding);
  1619. }
  1620. catch (err) {
  1621. if (err.code === EEXIST) {
  1622. if (retry > 1)
  1623. return this.mkdtempBase(prefix, encoding, retry - 1);
  1624. else
  1625. throw Error('Could not create temp dir.');
  1626. }
  1627. else
  1628. throw err;
  1629. }
  1630. };
  1631. Volume.prototype.mkdtempSync = function (prefix, options) {
  1632. var encoding = getDefaultOpts(options).encoding;
  1633. if (!prefix || typeof prefix !== 'string')
  1634. throw new TypeError('filename prefix is required');
  1635. nullCheck(prefix);
  1636. return this.mkdtempBase(prefix, encoding);
  1637. };
  1638. Volume.prototype.mkdtemp = function (prefix, a, b) {
  1639. var _a = getDefaultOptsAndCb(a, b), encoding = _a[0].encoding, callback = _a[1];
  1640. if (!prefix || typeof prefix !== 'string')
  1641. throw new TypeError('filename prefix is required');
  1642. if (!nullCheck(prefix))
  1643. return;
  1644. this.wrapAsync(this.mkdtempBase, [prefix, encoding], callback);
  1645. };
  1646. Volume.prototype.rmdirBase = function (filename, options) {
  1647. var opts = getRmdirOptions(options);
  1648. var link = this.getLinkAsDirOrThrow(filename, 'rmdir');
  1649. // Check directory is empty.
  1650. if (link.length && !opts.recursive)
  1651. throw createError(ENOTEMPTY, 'rmdir', filename);
  1652. this.deleteLink(link);
  1653. };
  1654. Volume.prototype.rmdirSync = function (path, options) {
  1655. this.rmdirBase(pathToFilename(path), options);
  1656. };
  1657. Volume.prototype.rmdir = function (path, a, b) {
  1658. var opts = getRmdirOptions(a);
  1659. var callback = validateCallback(typeof a === 'function' ? a : b);
  1660. this.wrapAsync(this.rmdirBase, [pathToFilename(path), opts], callback);
  1661. };
  1662. Volume.prototype.rmBase = function (filename, options) {
  1663. if (options === void 0) { options = {}; }
  1664. var link = this.getResolvedLink(filename);
  1665. if (!link) {
  1666. // "stat" is used to match Node's native error message.
  1667. if (!options.force)
  1668. throw createError(ENOENT, 'stat', filename);
  1669. return;
  1670. }
  1671. if (link.getNode().isDirectory()) {
  1672. if (!options.recursive) {
  1673. throw createError(ERR_FS_EISDIR, 'rm', filename);
  1674. }
  1675. }
  1676. this.deleteLink(link);
  1677. };
  1678. Volume.prototype.rmSync = function (path, options) {
  1679. this.rmBase(pathToFilename(path), options);
  1680. };
  1681. Volume.prototype.rm = function (path, a, b) {
  1682. var _a = getRmOptsAndCb(a, b), opts = _a[0], callback = _a[1];
  1683. this.wrapAsync(this.rmBase, [pathToFilename(path), opts], callback);
  1684. };
  1685. Volume.prototype.fchmodBase = function (fd, modeNum) {
  1686. var file = this.getFileByFdOrThrow(fd, 'fchmod');
  1687. file.chmod(modeNum);
  1688. };
  1689. Volume.prototype.fchmodSync = function (fd, mode) {
  1690. this.fchmodBase(fd, modeToNumber(mode));
  1691. };
  1692. Volume.prototype.fchmod = function (fd, mode, callback) {
  1693. this.wrapAsync(this.fchmodBase, [fd, modeToNumber(mode)], callback);
  1694. };
  1695. Volume.prototype.chmodBase = function (filename, modeNum) {
  1696. var fd = this.openSync(filename, 'r+');
  1697. try {
  1698. this.fchmodBase(fd, modeNum);
  1699. }
  1700. finally {
  1701. this.closeSync(fd);
  1702. }
  1703. };
  1704. Volume.prototype.chmodSync = function (path, mode) {
  1705. var modeNum = modeToNumber(mode);
  1706. var filename = pathToFilename(path);
  1707. this.chmodBase(filename, modeNum);
  1708. };
  1709. Volume.prototype.chmod = function (path, mode, callback) {
  1710. var modeNum = modeToNumber(mode);
  1711. var filename = pathToFilename(path);
  1712. this.wrapAsync(this.chmodBase, [filename, modeNum], callback);
  1713. };
  1714. Volume.prototype.lchmodBase = function (filename, modeNum) {
  1715. var fd = this.openBase(filename, O_RDWR, 0, false);
  1716. try {
  1717. this.fchmodBase(fd, modeNum);
  1718. }
  1719. finally {
  1720. this.closeSync(fd);
  1721. }
  1722. };
  1723. Volume.prototype.lchmodSync = function (path, mode) {
  1724. var modeNum = modeToNumber(mode);
  1725. var filename = pathToFilename(path);
  1726. this.lchmodBase(filename, modeNum);
  1727. };
  1728. Volume.prototype.lchmod = function (path, mode, callback) {
  1729. var modeNum = modeToNumber(mode);
  1730. var filename = pathToFilename(path);
  1731. this.wrapAsync(this.lchmodBase, [filename, modeNum], callback);
  1732. };
  1733. Volume.prototype.fchownBase = function (fd, uid, gid) {
  1734. this.getFileByFdOrThrow(fd, 'fchown').chown(uid, gid);
  1735. };
  1736. Volume.prototype.fchownSync = function (fd, uid, gid) {
  1737. validateUid(uid);
  1738. validateGid(gid);
  1739. this.fchownBase(fd, uid, gid);
  1740. };
  1741. Volume.prototype.fchown = function (fd, uid, gid, callback) {
  1742. validateUid(uid);
  1743. validateGid(gid);
  1744. this.wrapAsync(this.fchownBase, [fd, uid, gid], callback);
  1745. };
  1746. Volume.prototype.chownBase = function (filename, uid, gid) {
  1747. var link = this.getResolvedLinkOrThrow(filename, 'chown');
  1748. var node = link.getNode();
  1749. node.chown(uid, gid);
  1750. // if(node.isFile() || node.isSymlink()) {
  1751. //
  1752. // } else if(node.isDirectory()) {
  1753. //
  1754. // } else {
  1755. // TODO: What do we do here?
  1756. // }
  1757. };
  1758. Volume.prototype.chownSync = function (path, uid, gid) {
  1759. validateUid(uid);
  1760. validateGid(gid);
  1761. this.chownBase(pathToFilename(path), uid, gid);
  1762. };
  1763. Volume.prototype.chown = function (path, uid, gid, callback) {
  1764. validateUid(uid);
  1765. validateGid(gid);
  1766. this.wrapAsync(this.chownBase, [pathToFilename(path), uid, gid], callback);
  1767. };
  1768. Volume.prototype.lchownBase = function (filename, uid, gid) {
  1769. this.getLinkOrThrow(filename, 'lchown')
  1770. .getNode()
  1771. .chown(uid, gid);
  1772. };
  1773. Volume.prototype.lchownSync = function (path, uid, gid) {
  1774. validateUid(uid);
  1775. validateGid(gid);
  1776. this.lchownBase(pathToFilename(path), uid, gid);
  1777. };
  1778. Volume.prototype.lchown = function (path, uid, gid, callback) {
  1779. validateUid(uid);
  1780. validateGid(gid);
  1781. this.wrapAsync(this.lchownBase, [pathToFilename(path), uid, gid], callback);
  1782. };
  1783. Volume.prototype.watchFile = function (path, a, b) {
  1784. var filename = pathToFilename(path);
  1785. var options = a;
  1786. var listener = b;
  1787. if (typeof options === 'function') {
  1788. listener = a;
  1789. options = null;
  1790. }
  1791. if (typeof listener !== 'function') {
  1792. throw Error('"watchFile()" requires a listener function');
  1793. }
  1794. var interval = 5007;
  1795. var persistent = true;
  1796. if (options && typeof options === 'object') {
  1797. if (typeof options.interval === 'number')
  1798. interval = options.interval;
  1799. if (typeof options.persistent === 'boolean')
  1800. persistent = options.persistent;
  1801. }
  1802. var watcher = this.statWatchers[filename];
  1803. if (!watcher) {
  1804. watcher = new this.StatWatcher();
  1805. watcher.start(filename, persistent, interval);
  1806. this.statWatchers[filename] = watcher;
  1807. }
  1808. watcher.addListener('change', listener);
  1809. return watcher;
  1810. };
  1811. Volume.prototype.unwatchFile = function (path, listener) {
  1812. var filename = pathToFilename(path);
  1813. var watcher = this.statWatchers[filename];
  1814. if (!watcher)
  1815. return;
  1816. if (typeof listener === 'function') {
  1817. watcher.removeListener('change', listener);
  1818. }
  1819. else {
  1820. watcher.removeAllListeners('change');
  1821. }
  1822. if (watcher.listenerCount('change') === 0) {
  1823. watcher.stop();
  1824. delete this.statWatchers[filename];
  1825. }
  1826. };
  1827. Volume.prototype.createReadStream = function (path, options) {
  1828. return new this.ReadStream(path, options);
  1829. };
  1830. Volume.prototype.createWriteStream = function (path, options) {
  1831. return new this.WriteStream(path, options);
  1832. };
  1833. // watch(path: PathLike): FSWatcher;
  1834. // watch(path: PathLike, options?: IWatchOptions | string): FSWatcher;
  1835. Volume.prototype.watch = function (path, options, listener) {
  1836. var filename = pathToFilename(path);
  1837. var givenOptions = options;
  1838. if (typeof options === 'function') {
  1839. listener = options;
  1840. givenOptions = null;
  1841. }
  1842. // tslint:disable-next-line prefer-const
  1843. var _a = getDefaultOpts(givenOptions), persistent = _a.persistent, recursive = _a.recursive, encoding = _a.encoding;
  1844. if (persistent === undefined)
  1845. persistent = true;
  1846. if (recursive === undefined)
  1847. recursive = false;
  1848. var watcher = new this.FSWatcher();
  1849. watcher.start(filename, persistent, recursive, encoding);
  1850. if (listener) {
  1851. watcher.addListener('change', listener);
  1852. }
  1853. return watcher;
  1854. };
  1855. /**
  1856. * Global file descriptor counter. UNIX file descriptors start from 0 and go sequentially
  1857. * up, so here, in order not to conflict with them, we choose some big number and descrease
  1858. * the file descriptor of every new opened file.
  1859. * @type {number}
  1860. * @todo This should not be static, right?
  1861. */
  1862. Volume.fd = 0x7fffffff;
  1863. return Volume;
  1864. }());
  1865. exports.Volume = Volume;
  1866. function emitStop(self) {
  1867. self.emit('stop');
  1868. }
  1869. var StatWatcher = /** @class */ (function (_super) {
  1870. __extends(StatWatcher, _super);
  1871. function StatWatcher(vol) {
  1872. var _this = _super.call(this) || this;
  1873. _this.onInterval = function () {
  1874. try {
  1875. var stats = _this.vol.statSync(_this.filename);
  1876. if (_this.hasChanged(stats)) {
  1877. _this.emit('change', stats, _this.prev);
  1878. _this.prev = stats;
  1879. }
  1880. }
  1881. finally {
  1882. _this.loop();
  1883. }
  1884. };
  1885. _this.vol = vol;
  1886. return _this;
  1887. }
  1888. StatWatcher.prototype.loop = function () {
  1889. this.timeoutRef = this.setTimeout(this.onInterval, this.interval);
  1890. };
  1891. StatWatcher.prototype.hasChanged = function (stats) {
  1892. // if(!this.prev) return false;
  1893. if (stats.mtimeMs > this.prev.mtimeMs)
  1894. return true;
  1895. if (stats.nlink !== this.prev.nlink)
  1896. return true;
  1897. return false;
  1898. };
  1899. StatWatcher.prototype.start = function (path, persistent, interval) {
  1900. if (persistent === void 0) { persistent = true; }
  1901. if (interval === void 0) { interval = 5007; }
  1902. this.filename = pathToFilename(path);
  1903. this.setTimeout = persistent ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global) : setTimeoutUnref_1.default;
  1904. this.interval = interval;
  1905. this.prev = this.vol.statSync(this.filename);
  1906. this.loop();
  1907. };
  1908. StatWatcher.prototype.stop = function () {
  1909. clearTimeout(this.timeoutRef);
  1910. process_1.default.nextTick(emitStop, this);
  1911. };
  1912. return StatWatcher;
  1913. }(events_1.EventEmitter));
  1914. exports.StatWatcher = StatWatcher;
  1915. var pool;
  1916. function allocNewPool(poolSize) {
  1917. pool = (0, buffer_1.bufferAllocUnsafe)(poolSize);
  1918. pool.used = 0;
  1919. }
  1920. util.inherits(FsReadStream, stream_1.Readable);
  1921. exports.ReadStream = FsReadStream;
  1922. function FsReadStream(vol, path, options) {
  1923. if (!(this instanceof FsReadStream))
  1924. return new FsReadStream(vol, path, options);
  1925. this._vol = vol;
  1926. // a little bit bigger buffer and water marks by default
  1927. options = Object.assign({}, getOptions(options, {}));
  1928. if (options.highWaterMark === undefined)
  1929. options.highWaterMark = 64 * 1024;
  1930. stream_1.Readable.call(this, options);
  1931. this.path = pathToFilename(path);
  1932. this.fd = options.fd === undefined ? null : options.fd;
  1933. this.flags = options.flags === undefined ? 'r' : options.flags;
  1934. this.mode = options.mode === undefined ? 438 : options.mode;
  1935. this.start = options.start;
  1936. this.end = options.end;
  1937. this.autoClose = options.autoClose === undefined ? true : options.autoClose;
  1938. this.pos = undefined;
  1939. this.bytesRead = 0;
  1940. if (this.start !== undefined) {
  1941. if (typeof this.start !== 'number') {
  1942. throw new TypeError('"start" option must be a Number');
  1943. }
  1944. if (this.end === undefined) {
  1945. this.end = Infinity;
  1946. }
  1947. else if (typeof this.end !== 'number') {
  1948. throw new TypeError('"end" option must be a Number');
  1949. }
  1950. if (this.start > this.end) {
  1951. throw new Error('"start" option must be <= "end" option');
  1952. }
  1953. this.pos = this.start;
  1954. }
  1955. if (typeof this.fd !== 'number')
  1956. this.open();
  1957. this.on('end', function () {
  1958. if (this.autoClose) {
  1959. if (this.destroy)
  1960. this.destroy();
  1961. }
  1962. });
  1963. }
  1964. FsReadStream.prototype.open = function () {
  1965. var self = this; // tslint:disable-line no-this-assignment
  1966. this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
  1967. if (er) {
  1968. if (self.autoClose) {
  1969. if (self.destroy)
  1970. self.destroy();
  1971. }
  1972. self.emit('error', er);
  1973. return;
  1974. }
  1975. self.fd = fd;
  1976. self.emit('open', fd);
  1977. // start the flow of data.
  1978. self.read();
  1979. });
  1980. };
  1981. FsReadStream.prototype._read = function (n) {
  1982. if (typeof this.fd !== 'number') {
  1983. return this.once('open', function () {
  1984. this._read(n);
  1985. });
  1986. }
  1987. if (this.destroyed)
  1988. return;
  1989. if (!pool || pool.length - pool.used < kMinPoolSpace) {
  1990. // discard the old pool.
  1991. allocNewPool(this._readableState.highWaterMark);
  1992. }
  1993. // Grab another reference to the pool in the case that while we're
  1994. // in the thread pool another read() finishes up the pool, and
  1995. // allocates a new one.
  1996. var thisPool = pool;
  1997. var toRead = Math.min(pool.length - pool.used, n);
  1998. var start = pool.used;
  1999. if (this.pos !== undefined)
  2000. toRead = Math.min(this.end - this.pos + 1, toRead);
  2001. // already read everything we were supposed to read!
  2002. // treat as EOF.
  2003. if (toRead <= 0)
  2004. return this.push(null);
  2005. // the actual read.
  2006. var self = this; // tslint:disable-line no-this-assignment
  2007. this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread);
  2008. // move the pool positions, and internal position for reading.
  2009. if (this.pos !== undefined)
  2010. this.pos += toRead;
  2011. pool.used += toRead;
  2012. function onread(er, bytesRead) {
  2013. if (er) {
  2014. if (self.autoClose && self.destroy) {
  2015. self.destroy();
  2016. }
  2017. self.emit('error', er);
  2018. }
  2019. else {
  2020. var b = null;
  2021. if (bytesRead > 0) {
  2022. self.bytesRead += bytesRead;
  2023. b = thisPool.slice(start, start + bytesRead);
  2024. }
  2025. self.push(b);
  2026. }
  2027. }
  2028. };
  2029. FsReadStream.prototype._destroy = function (err, cb) {
  2030. this.close(function (err2) {
  2031. cb(err || err2);
  2032. });
  2033. };
  2034. FsReadStream.prototype.close = function (cb) {
  2035. var _this = this;
  2036. if (cb)
  2037. this.once('close', cb);
  2038. if (this.closed || typeof this.fd !== 'number') {
  2039. if (typeof this.fd !== 'number') {
  2040. this.once('open', closeOnOpen);
  2041. return;
  2042. }
  2043. return process_1.default.nextTick(function () { return _this.emit('close'); });
  2044. }
  2045. this.closed = true;
  2046. this._vol.close(this.fd, function (er) {
  2047. if (er)
  2048. _this.emit('error', er);
  2049. else
  2050. _this.emit('close');
  2051. });
  2052. this.fd = null;
  2053. };
  2054. // needed because as it will be called with arguments
  2055. // that does not match this.close() signature
  2056. function closeOnOpen(fd) {
  2057. this.close();
  2058. }
  2059. util.inherits(FsWriteStream, stream_1.Writable);
  2060. exports.WriteStream = FsWriteStream;
  2061. function FsWriteStream(vol, path, options) {
  2062. if (!(this instanceof FsWriteStream))
  2063. return new FsWriteStream(vol, path, options);
  2064. this._vol = vol;
  2065. options = Object.assign({}, getOptions(options, {}));
  2066. stream_1.Writable.call(this, options);
  2067. this.path = pathToFilename(path);
  2068. this.fd = options.fd === undefined ? null : options.fd;
  2069. this.flags = options.flags === undefined ? 'w' : options.flags;
  2070. this.mode = options.mode === undefined ? 438 : options.mode;
  2071. this.start = options.start;
  2072. this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
  2073. this.pos = undefined;
  2074. this.bytesWritten = 0;
  2075. if (this.start !== undefined) {
  2076. if (typeof this.start !== 'number') {
  2077. throw new TypeError('"start" option must be a Number');
  2078. }
  2079. if (this.start < 0) {
  2080. throw new Error('"start" must be >= zero');
  2081. }
  2082. this.pos = this.start;
  2083. }
  2084. if (options.encoding)
  2085. this.setDefaultEncoding(options.encoding);
  2086. if (typeof this.fd !== 'number')
  2087. this.open();
  2088. // dispose on finish.
  2089. this.once('finish', function () {
  2090. if (this.autoClose) {
  2091. this.close();
  2092. }
  2093. });
  2094. }
  2095. FsWriteStream.prototype.open = function () {
  2096. this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
  2097. if (er) {
  2098. if (this.autoClose && this.destroy) {
  2099. this.destroy();
  2100. }
  2101. this.emit('error', er);
  2102. return;
  2103. }
  2104. this.fd = fd;
  2105. this.emit('open', fd);
  2106. }.bind(this));
  2107. };
  2108. FsWriteStream.prototype._write = function (data, encoding, cb) {
  2109. if (!(data instanceof buffer_1.Buffer))
  2110. return this.emit('error', new Error('Invalid data'));
  2111. if (typeof this.fd !== 'number') {
  2112. return this.once('open', function () {
  2113. this._write(data, encoding, cb);
  2114. });
  2115. }
  2116. var self = this; // tslint:disable-line no-this-assignment
  2117. this._vol.write(this.fd, data, 0, data.length, this.pos, function (er, bytes) {
  2118. if (er) {
  2119. if (self.autoClose && self.destroy) {
  2120. self.destroy();
  2121. }
  2122. return cb(er);
  2123. }
  2124. self.bytesWritten += bytes;
  2125. cb();
  2126. });
  2127. if (this.pos !== undefined)
  2128. this.pos += data.length;
  2129. };
  2130. FsWriteStream.prototype._writev = function (data, cb) {
  2131. if (typeof this.fd !== 'number') {
  2132. return this.once('open', function () {
  2133. this._writev(data, cb);
  2134. });
  2135. }
  2136. var self = this; // tslint:disable-line no-this-assignment
  2137. var len = data.length;
  2138. var chunks = new Array(len);
  2139. var size = 0;
  2140. for (var i = 0; i < len; i++) {
  2141. var chunk = data[i].chunk;
  2142. chunks[i] = chunk;
  2143. size += chunk.length;
  2144. }
  2145. var buf = buffer_1.Buffer.concat(chunks);
  2146. this._vol.write(this.fd, buf, 0, buf.length, this.pos, function (er, bytes) {
  2147. if (er) {
  2148. if (self.destroy)
  2149. self.destroy();
  2150. return cb(er);
  2151. }
  2152. self.bytesWritten += bytes;
  2153. cb();
  2154. });
  2155. if (this.pos !== undefined)
  2156. this.pos += size;
  2157. };
  2158. FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy;
  2159. FsWriteStream.prototype.close = FsReadStream.prototype.close;
  2160. // There is no shutdown() for files.
  2161. FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end;
  2162. // ---------------------------------------- FSWatcher
  2163. var FSWatcher = /** @class */ (function (_super) {
  2164. __extends(FSWatcher, _super);
  2165. function FSWatcher(vol) {
  2166. var _this = _super.call(this) || this;
  2167. _this._filename = '';
  2168. _this._filenameEncoded = '';
  2169. // _persistent: boolean = true;
  2170. _this._recursive = false;
  2171. _this._encoding = encoding_1.ENCODING_UTF8;
  2172. _this._onNodeChange = function () {
  2173. _this._emit('change');
  2174. };
  2175. _this._onParentChild = function (link) {
  2176. if (link.getName() === _this._getName()) {
  2177. _this._emit('rename');
  2178. }
  2179. };
  2180. _this._emit = function (type) {
  2181. _this.emit('change', type, _this._filenameEncoded);
  2182. };
  2183. _this._persist = function () {
  2184. _this._timer = setTimeout(_this._persist, 1e6);
  2185. };
  2186. _this._vol = vol;
  2187. return _this;
  2188. // TODO: Emit "error" messages when watching.
  2189. // this._handle.onchange = function(status, eventType, filename) {
  2190. // if (status < 0) {
  2191. // self._handle.close();
  2192. // const error = !filename ?
  2193. // errnoException(status, 'Error watching file for changes:') :
  2194. // errnoException(status, `Error watching file ${filename} for changes:`);
  2195. // error.filename = filename;
  2196. // self.emit('error', error);
  2197. // } else {
  2198. // self.emit('change', eventType, filename);
  2199. // }
  2200. // };
  2201. }
  2202. FSWatcher.prototype._getName = function () {
  2203. return this._steps[this._steps.length - 1];
  2204. };
  2205. FSWatcher.prototype.start = function (path, persistent, recursive, encoding) {
  2206. if (persistent === void 0) { persistent = true; }
  2207. if (recursive === void 0) { recursive = false; }
  2208. if (encoding === void 0) { encoding = encoding_1.ENCODING_UTF8; }
  2209. this._filename = pathToFilename(path);
  2210. this._steps = filenameToSteps(this._filename);
  2211. this._filenameEncoded = (0, encoding_1.strToEncoding)(this._filename);
  2212. // this._persistent = persistent;
  2213. this._recursive = recursive;
  2214. this._encoding = encoding;
  2215. try {
  2216. this._link = this._vol.getLinkOrThrow(this._filename, 'FSWatcher');
  2217. }
  2218. catch (err) {
  2219. var error = new Error("watch ".concat(this._filename, " ").concat(err.code));
  2220. error.code = err.code;
  2221. error.errno = err.code;
  2222. throw error;
  2223. }
  2224. this._link.getNode().on('change', this._onNodeChange);
  2225. this._link.on('child:add', this._onNodeChange);
  2226. this._link.on('child:delete', this._onNodeChange);
  2227. var parent = this._link.parent;
  2228. if (parent) {
  2229. // parent.on('child:add', this._onParentChild);
  2230. parent.setMaxListeners(parent.getMaxListeners() + 1);
  2231. parent.on('child:delete', this._onParentChild);
  2232. }
  2233. if (persistent)
  2234. this._persist();
  2235. };
  2236. FSWatcher.prototype.close = function () {
  2237. clearTimeout(this._timer);
  2238. this._link.getNode().removeListener('change', this._onNodeChange);
  2239. var parent = this._link.parent;
  2240. if (parent) {
  2241. // parent.removeListener('child:add', this._onParentChild);
  2242. parent.removeListener('child:delete', this._onParentChild);
  2243. }
  2244. };
  2245. return FSWatcher;
  2246. }(events_1.EventEmitter));
  2247. exports.FSWatcher = FSWatcher;