volume.js 69 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.FSWatcher = exports.StatWatcher = exports.Volume = void 0;
  4. exports.pathToSteps = pathToSteps;
  5. exports.dataToStr = dataToStr;
  6. exports.toUnixTimestamp = toUnixTimestamp;
  7. const path_1 = require("@jsonjoy.com/fs-node-builtins/lib/path");
  8. const fs_core_1 = require("@jsonjoy.com/fs-core");
  9. const util_1 = require("@jsonjoy.com/fs-core/lib/util");
  10. const Stats_1 = require("./Stats");
  11. const Dirent_1 = require("./Dirent");
  12. const StatFs_1 = require("./StatFs");
  13. const buffer_1 = require("@jsonjoy.com/fs-node-builtins/lib/internal/buffer");
  14. const setTimeoutUnref_1 = require("@jsonjoy.com/fs-node-utils/lib/setTimeoutUnref");
  15. const stream_1 = require("@jsonjoy.com/fs-node-builtins/lib/stream");
  16. const fs_node_utils_1 = require("@jsonjoy.com/fs-node-utils");
  17. const events_1 = require("@jsonjoy.com/fs-node-builtins/lib/events");
  18. const FileHandle_1 = require("./FileHandle");
  19. const util_2 = require("@jsonjoy.com/fs-node-builtins/lib/util");
  20. const FsPromises_1 = require("./FsPromises");
  21. const fs_print_1 = require("@jsonjoy.com/fs-print");
  22. const fsSnapshot = require("@jsonjoy.com/fs-snapshot");
  23. const fs_node_utils_2 = require("@jsonjoy.com/fs-node-utils");
  24. const errors = require("@jsonjoy.com/fs-node-builtins/lib/internal/errors");
  25. const options_1 = require("./options");
  26. const util_3 = require("./util");
  27. const Dir_1 = require("./Dir");
  28. const resolveCrossPlatform = path_1.resolve;
  29. const { O_SYMLINK, F_OK, R_OK, W_OK, X_OK, COPYFILE_EXCL, COPYFILE_FICLONE_FORCE } = fs_node_utils_1.constants;
  30. const pathSep = path_1.posix ? path_1.posix.sep : path_1.sep;
  31. const pathRelative = path_1.posix ? path_1.posix.relative : path_1.relative;
  32. const pathJoin = path_1.posix ? path_1.posix.join : path_1.join;
  33. const pathDirname = path_1.posix ? path_1.posix.dirname : path_1.dirname;
  34. const pathNormalize = path_1.posix ? path_1.posix.normalize : path_1.normalize;
  35. // ------------------------------------------------------------------ Constants
  36. const kMinPoolSpace = 128;
  37. // ---------------------------------------------------------- Utility functions
  38. function pathToSteps(path) {
  39. return (0, fs_core_1.filenameToSteps)((0, util_3.pathToFilename)(path));
  40. }
  41. function dataToStr(data, encoding = fs_node_utils_1.ENCODING_UTF8) {
  42. if (buffer_1.Buffer.isBuffer(data))
  43. return data.toString(encoding);
  44. else if (data instanceof Uint8Array)
  45. return (0, buffer_1.bufferFrom)(data).toString(encoding);
  46. else
  47. return String(data);
  48. }
  49. // converts Date or number to a fractional UNIX timestamp
  50. function toUnixTimestamp(time) {
  51. // tslint:disable-next-line triple-equals
  52. if (typeof time === 'string' && +time == time) {
  53. return +time;
  54. }
  55. if (time instanceof Date) {
  56. return time.getTime() / 1000;
  57. }
  58. if (isFinite(time)) {
  59. if (time < 0) {
  60. return Date.now() / 1000;
  61. }
  62. return time;
  63. }
  64. throw new Error('Cannot parse time: ' + time);
  65. }
  66. function validateUid(uid) {
  67. if (typeof uid !== 'number')
  68. throw TypeError(fs_node_utils_2.ERRSTR.UID);
  69. }
  70. function validateGid(gid) {
  71. if (typeof gid !== 'number')
  72. throw TypeError(fs_node_utils_2.ERRSTR.GID);
  73. }
  74. /**
  75. * `Volume` represents a file system.
  76. */
  77. class Volume {
  78. get promises() {
  79. if (this.promisesApi === null)
  80. throw new Error('Promise is not supported in this environment.');
  81. return this.promisesApi;
  82. }
  83. constructor(_core = new fs_core_1.Superblock()) {
  84. this._core = _core;
  85. this.promisesApi = new FsPromises_1.FsPromises(this, FileHandle_1.FileHandle);
  86. this.openSync = (path, flags, mode = 438 /* MODE.DEFAULT */) => {
  87. // Validate (1) mode; (2) path; (3) flags - in that order.
  88. const modeNum = (0, util_3.modeToNumber)(mode);
  89. const fileName = (0, util_3.pathToFilename)(path);
  90. const flagsNum = (0, util_3.flagsToNumber)(flags);
  91. return this._core.open(fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK));
  92. };
  93. this.open = (path, flags, a, b) => {
  94. let mode = a;
  95. let callback = b;
  96. if (typeof a === 'function') {
  97. mode = 438 /* MODE.DEFAULT */;
  98. callback = a;
  99. }
  100. mode = mode || 438 /* MODE.DEFAULT */;
  101. const modeNum = (0, util_3.modeToNumber)(mode);
  102. const fileName = (0, util_3.pathToFilename)(path);
  103. const flagsNum = (0, util_3.flagsToNumber)(flags);
  104. this.wrapAsync(this._core.open, [fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK)], callback);
  105. };
  106. this.closeSync = (fd) => {
  107. this._core.close(fd);
  108. };
  109. this.close = (fd, callback) => {
  110. (0, fs_core_1.validateFd)(fd);
  111. const file = this._core.getFileByFdOrThrow(fd, 'close');
  112. this.wrapAsync(this._core.close, [file.fd], callback);
  113. };
  114. this.readSync = (fd, buffer, offset, length, position) => {
  115. (0, fs_core_1.validateFd)(fd);
  116. return this._core.read(fd, buffer, offset, length, position);
  117. };
  118. this.read = (fd, buffer, offset, length, position, callback) => {
  119. (0, util_3.validateCallback)(callback);
  120. if (length === 0) {
  121. // This `if` branch is from Node.js
  122. return queueMicrotask(() => {
  123. if (callback)
  124. callback(null, 0, buffer);
  125. });
  126. }
  127. Promise.resolve().then(() => {
  128. try {
  129. const bytes = this._core.read(fd, buffer, offset, length, position);
  130. callback(null, bytes, buffer);
  131. }
  132. catch (err) {
  133. callback(err);
  134. }
  135. });
  136. };
  137. this.readv = (fd, buffers, a, b) => {
  138. let position = a;
  139. let callback = b;
  140. if (typeof a === 'function')
  141. [position, callback] = [null, a];
  142. (0, util_3.validateCallback)(callback);
  143. Promise.resolve().then(() => {
  144. try {
  145. const bytes = this._core.readv(fd, buffers, position);
  146. callback(null, bytes, buffers);
  147. }
  148. catch (err) {
  149. callback(err);
  150. }
  151. });
  152. };
  153. this.readvSync = (fd, buffers, position) => {
  154. (0, fs_core_1.validateFd)(fd);
  155. return this._core.readv(fd, buffers, position ?? null);
  156. };
  157. this._readfile = (id, flagsNum, encoding) => {
  158. let result;
  159. const isUserFd = typeof id === 'number';
  160. const userOwnsFd = isUserFd && (0, fs_core_1.isFd)(id);
  161. let fd;
  162. if (userOwnsFd)
  163. fd = id;
  164. else {
  165. const filename = (0, util_3.pathToFilename)(id);
  166. // Check if original path had trailing slash (indicates directory intent)
  167. const originalPath = String(id);
  168. const hasTrailingSlash = originalPath.length > 1 && originalPath.endsWith('/');
  169. const link = this._core.getResolvedLinkOrThrow(filename, 'open');
  170. const node = link.getNode();
  171. if (node.isDirectory())
  172. throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'open', link.getPath());
  173. // If path had trailing slash but resolved to a file, throw ENOTDIR
  174. if (hasTrailingSlash && node.isFile()) {
  175. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'open', originalPath);
  176. }
  177. fd = this.openSync(id, flagsNum);
  178. }
  179. try {
  180. result = (0, util_3.bufferToEncoding)(this._core.getFileByFdOrThrow(fd).getBuffer(), encoding);
  181. }
  182. finally {
  183. if (!userOwnsFd) {
  184. this.closeSync(fd);
  185. }
  186. }
  187. return result;
  188. };
  189. this.readFileSync = (file, options) => {
  190. const opts = (0, options_1.getReadFileOptions)(options);
  191. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  192. return this._readfile(file, flagsNum, opts.encoding);
  193. };
  194. this.readFile = (id, a, b) => {
  195. const [opts, callback] = (0, options_1.optsAndCbGenerator)(options_1.getReadFileOptions)(a, b);
  196. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  197. this.wrapAsync(this._readfile, [id, flagsNum, opts.encoding], callback);
  198. };
  199. this.writeSync = (fd, a, b, c, d) => {
  200. const [, buf, offset, length, position] = (0, util_3.getWriteSyncArgs)(fd, a, b, c, d);
  201. return this._write(fd, buf, offset, length, position);
  202. };
  203. this.write = (fd, a, b, c, d, e) => {
  204. const [, asStr, buf, offset, length, position, cb] = (0, util_3.getWriteArgs)(fd, a, b, c, d, e);
  205. Promise.resolve().then(() => {
  206. try {
  207. const bytes = this._write(fd, buf, offset, length, position);
  208. if (!asStr) {
  209. cb(null, bytes, buf);
  210. }
  211. else {
  212. cb(null, bytes, a);
  213. }
  214. }
  215. catch (err) {
  216. cb(err);
  217. }
  218. });
  219. };
  220. this.writev = (fd, buffers, a, b) => {
  221. let position = a;
  222. let callback = b;
  223. if (typeof a === 'function')
  224. [position, callback] = [null, a];
  225. (0, util_3.validateCallback)(callback);
  226. Promise.resolve().then(() => {
  227. try {
  228. const bytes = this.writevBase(fd, buffers, position);
  229. callback(null, bytes, buffers);
  230. }
  231. catch (err) {
  232. callback(err);
  233. }
  234. });
  235. };
  236. this.writevSync = (fd, buffers, position) => {
  237. (0, fs_core_1.validateFd)(fd);
  238. return this.writevBase(fd, buffers, position ?? null);
  239. };
  240. this.writeFileSync = (id, data, options) => {
  241. const opts = (0, options_1.getWriteFileOptions)(options);
  242. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  243. const modeNum = (0, util_3.modeToNumber)(opts.mode);
  244. const buf = (0, fs_core_1.dataToBuffer)(data, opts.encoding);
  245. this._core.writeFile(id, buf, flagsNum, modeNum);
  246. };
  247. this.writeFile = (id, data, a, b) => {
  248. let options = a;
  249. let callback = b;
  250. if (typeof a === 'function')
  251. [options, callback] = [options_1.writeFileDefaults, a];
  252. const cb = (0, util_3.validateCallback)(callback);
  253. const opts = (0, options_1.getWriteFileOptions)(options);
  254. const flagsNum = (0, util_3.flagsToNumber)(opts.flag);
  255. const modeNum = (0, util_3.modeToNumber)(opts.mode);
  256. const buf = (0, fs_core_1.dataToBuffer)(data, opts.encoding);
  257. this.wrapAsync(this._core.writeFile, [id, buf, flagsNum, modeNum], cb);
  258. };
  259. this.copyFileSync = (src, dest, flags) => {
  260. const srcFilename = (0, util_3.pathToFilename)(src);
  261. const destFilename = (0, util_3.pathToFilename)(dest);
  262. return this._copyFile(srcFilename, destFilename, (flags || 0) | 0);
  263. };
  264. this.copyFile = (src, dest, a, b) => {
  265. const srcFilename = (0, util_3.pathToFilename)(src);
  266. const destFilename = (0, util_3.pathToFilename)(dest);
  267. let flags;
  268. let callback;
  269. if (typeof a === 'function')
  270. [flags, callback] = [0, a];
  271. else
  272. [flags, callback] = [a, b];
  273. (0, util_3.validateCallback)(callback);
  274. this.wrapAsync(this._copyFile, [srcFilename, destFilename, flags], callback);
  275. };
  276. this._cp = (src, dest, options) => {
  277. if (options.filter && !options.filter(src, dest))
  278. return;
  279. const srcStat = options.dereference ? this.statSync(src) : this.lstatSync(src);
  280. let destStat = null;
  281. try {
  282. destStat = this.lstatSync(dest);
  283. }
  284. catch (err) {
  285. if (err.code !== 'ENOENT') {
  286. throw err;
  287. }
  288. }
  289. // Check if src and dest are the same (both exist and have same inode)
  290. if (destStat && srcStat.ino === destStat.ino && srcStat.dev === destStat.dev)
  291. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src, dest);
  292. // Check type compatibility
  293. if (destStat) {
  294. if (srcStat.isDirectory() && !destStat.isDirectory())
  295. throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'cp', src, dest);
  296. if (!srcStat.isDirectory() && destStat.isDirectory())
  297. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'cp', src, dest);
  298. }
  299. // Check if trying to copy directory to subdirectory of itself
  300. if (srcStat.isDirectory() && this.isSrcSubdir(src, dest))
  301. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src, dest);
  302. ENDURE_PARENT_DIR_EXISTS: {
  303. const parent = pathDirname(dest);
  304. if (!this.existsSync(parent))
  305. this.mkdirSync(parent, { recursive: true });
  306. }
  307. // Handle different file types
  308. if (srcStat.isDirectory()) {
  309. if (!options.recursive)
  310. throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'cp', src);
  311. this.cpDirSync(srcStat, destStat, src, dest, options);
  312. }
  313. else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) {
  314. this.cpFileSync(srcStat, destStat, src, dest, options);
  315. }
  316. else if (srcStat.isSymbolicLink() && !options.dereference) {
  317. // Only handle as symlink if not dereferencing
  318. this.cpSymlinkSync(destStat, src, dest, options);
  319. }
  320. else {
  321. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src);
  322. }
  323. };
  324. this.linkSync = (existingPath, newPath) => {
  325. const existingPathFilename = (0, util_3.pathToFilename)(existingPath);
  326. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  327. this._core.link(existingPathFilename, newPathFilename);
  328. };
  329. this.link = (existingPath, newPath, callback) => {
  330. const existingPathFilename = (0, util_3.pathToFilename)(existingPath);
  331. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  332. this.wrapAsync(this._core.link, [existingPathFilename, newPathFilename], callback);
  333. };
  334. this.unlinkSync = (path) => {
  335. const filename = (0, util_3.pathToFilename)(path);
  336. this._core.unlink(filename);
  337. };
  338. this.unlink = (path, callback) => {
  339. const filename = (0, util_3.pathToFilename)(path);
  340. this.wrapAsync(this._core.unlink, [filename], callback);
  341. };
  342. /**
  343. * `type` argument works only on Windows.
  344. * @param target
  345. * @param path
  346. * @param type
  347. */
  348. this.symlinkSync = (target, path, type) => {
  349. const targetFilename = (0, util_3.pathToFilename)(target);
  350. const pathFilename = (0, util_3.pathToFilename)(path);
  351. this._core.symlink(targetFilename, pathFilename);
  352. };
  353. this.symlink = (target, path, a, b) => {
  354. const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b);
  355. const targetFilename = (0, util_3.pathToFilename)(target);
  356. const pathFilename = (0, util_3.pathToFilename)(path);
  357. this.wrapAsync(this._core.symlink, [targetFilename, pathFilename], callback);
  358. };
  359. this._lstat = (filename, bigint = false, throwIfNoEntry = false) => {
  360. let link;
  361. try {
  362. link = this._core.getLinkOrThrow(filename, 'lstat');
  363. }
  364. catch (err) {
  365. if (err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && !throwIfNoEntry)
  366. return undefined;
  367. else
  368. throw err;
  369. }
  370. return Stats_1.default.build(link.getNode(), bigint);
  371. };
  372. this.lstatSync = (path, options) => {
  373. const { throwIfNoEntry = true, bigint = false } = (0, options_1.getStatOptions)(options);
  374. return this._lstat((0, util_3.pathToFilename)(path), bigint, throwIfNoEntry);
  375. };
  376. this.renameSync = (oldPath, newPath) => {
  377. const oldPathFilename = (0, util_3.pathToFilename)(oldPath);
  378. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  379. this._core.rename(oldPathFilename, newPathFilename);
  380. };
  381. this.rename = (oldPath, newPath, callback) => {
  382. const oldPathFilename = (0, util_3.pathToFilename)(oldPath);
  383. const newPathFilename = (0, util_3.pathToFilename)(newPath);
  384. this.wrapAsync(this._core.rename, [oldPathFilename, newPathFilename], callback);
  385. };
  386. this.existsSync = (path) => {
  387. try {
  388. return this._exists((0, util_3.pathToFilename)(path)).ok;
  389. }
  390. catch (err) {
  391. return false;
  392. }
  393. };
  394. this.exists = (path, callback) => {
  395. const filename = (0, util_3.pathToFilename)(path);
  396. if (typeof callback !== 'function')
  397. throw Error(fs_node_utils_2.ERRSTR.CB);
  398. Promise.resolve().then(() => {
  399. try {
  400. callback(this._exists(filename).ok);
  401. }
  402. catch (err) {
  403. callback(false);
  404. }
  405. });
  406. };
  407. this.accessSync = (path, mode = F_OK) => {
  408. const filename = (0, util_3.pathToFilename)(path);
  409. mode = mode | 0;
  410. this._access(filename, mode);
  411. };
  412. this.access = (path, a, b) => {
  413. let mode = F_OK;
  414. let callback;
  415. if (typeof a !== 'function')
  416. [mode, callback] = [a | 0, (0, util_3.validateCallback)(b)];
  417. else
  418. callback = a;
  419. const filename = (0, util_3.pathToFilename)(path);
  420. this.wrapAsync(this._access, [filename, mode], callback);
  421. };
  422. this.appendFileSync = (id, data, options) => {
  423. const opts = (0, options_1.getAppendFileOpts)(options);
  424. // Force append behavior when using a supplied file descriptor.
  425. if (!opts.flag || (0, fs_core_1.isFd)(id))
  426. opts.flag = 'a';
  427. this.writeFileSync(id, data, opts);
  428. };
  429. this.appendFile = (id, data, a, b) => {
  430. const [opts, callback] = (0, options_1.getAppendFileOptsAndCb)(a, b);
  431. // Force append behavior when using a supplied file descriptor.
  432. if (!opts.flag || (0, fs_core_1.isFd)(id))
  433. opts.flag = 'a';
  434. this.writeFile(id, data, opts, callback);
  435. };
  436. this._readdir = (filename, options) => {
  437. const steps = (0, fs_core_1.filenameToSteps)(filename);
  438. const link = this._core.getResolvedLinkOrThrow(filename, 'scandir');
  439. const node = link.getNode();
  440. if (!node.isDirectory())
  441. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'scandir', filename);
  442. // Check we have permissions
  443. if (!node.canRead())
  444. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'scandir', filename);
  445. const list = []; // output list
  446. for (const name of link.children.keys()) {
  447. const child = link.getChild(name);
  448. if (!child || name === '.' || name === '..')
  449. continue;
  450. list.push(Dirent_1.default.build(child, options.encoding));
  451. // recursion
  452. if (options.recursive && child.children.size) {
  453. const recurseOptions = { ...options, recursive: true, withFileTypes: true };
  454. const childList = this._readdir(child.getPath(), recurseOptions);
  455. list.push(...childList);
  456. }
  457. }
  458. if (!util_1.isWin && options.encoding !== 'buffer')
  459. list.sort((a, b) => {
  460. if (a.name < b.name)
  461. return -1;
  462. if (a.name > b.name)
  463. return 1;
  464. return 0;
  465. });
  466. if (options.withFileTypes)
  467. return list;
  468. let filename2 = filename;
  469. if (util_1.isWin)
  470. filename2 = filename2.replace(/\\/g, '/');
  471. return list.map(dirent => {
  472. if (options.recursive) {
  473. let fullPath = pathJoin(dirent.parentPath, dirent.name.toString());
  474. if (util_1.isWin) {
  475. fullPath = fullPath.replace(/\\/g, '/');
  476. }
  477. return fullPath.replace(filename2 + path_1.posix.sep, '');
  478. }
  479. return dirent.name;
  480. });
  481. };
  482. this.readdirSync = (path, options) => {
  483. const opts = (0, options_1.getReaddirOptions)(options);
  484. const filename = (0, util_3.pathToFilename)(path);
  485. return this._readdir(filename, opts);
  486. };
  487. this.readdir = (path, a, b) => {
  488. const [options, callback] = (0, options_1.getReaddirOptsAndCb)(a, b);
  489. const filename = (0, util_3.pathToFilename)(path);
  490. this.wrapAsync(this._readdir, [filename, options], callback);
  491. };
  492. this._readlink = (filename, encoding) => {
  493. const link = this._core.getLinkOrThrow(filename, 'readlink');
  494. const node = link.getNode();
  495. if (!node.isSymlink())
  496. throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'readlink', filename);
  497. return (0, fs_node_utils_1.strToEncoding)(node.symlink, encoding);
  498. };
  499. this.readlinkSync = (path, options) => {
  500. const opts = (0, options_1.getDefaultOpts)(options);
  501. const filename = (0, util_3.pathToFilename)(path);
  502. return this._readlink(filename, opts.encoding);
  503. };
  504. this.readlink = (path, a, b) => {
  505. const [opts, callback] = (0, options_1.getDefaultOptsAndCb)(a, b);
  506. const filename = (0, util_3.pathToFilename)(path);
  507. this.wrapAsync(this._readlink, [filename, opts.encoding], callback);
  508. };
  509. this._fsync = (fd) => {
  510. this._core.getFileByFdOrThrow(fd, 'fsync');
  511. };
  512. this.fsyncSync = (fd) => {
  513. this._fsync(fd);
  514. };
  515. this.fsync = (fd, callback) => {
  516. this.wrapAsync(this._fsync, [fd], callback);
  517. };
  518. this._fdatasync = (fd) => {
  519. this._core.getFileByFdOrThrow(fd, 'fdatasync');
  520. };
  521. this.fdatasyncSync = (fd) => {
  522. this._fdatasync(fd);
  523. };
  524. this.fdatasync = (fd, callback) => {
  525. this.wrapAsync(this._fdatasync, [fd], callback);
  526. };
  527. this._ftruncate = (fd, len) => {
  528. this._core.ftruncate(fd, len);
  529. };
  530. this.ftruncateSync = (fd, len) => {
  531. this._ftruncate(fd, len);
  532. };
  533. this.ftruncate = (fd, a, b) => {
  534. const len = typeof a === 'number' ? a : 0;
  535. const callback = (0, util_3.validateCallback)(typeof a === 'number' ? b : a);
  536. this.wrapAsync(this._ftruncate, [fd, len], callback);
  537. };
  538. this._truncate = (path, len) => {
  539. const fd = this.openSync(path, 'r+');
  540. try {
  541. this.ftruncateSync(fd, len);
  542. }
  543. finally {
  544. this.closeSync(fd);
  545. }
  546. };
  547. /**
  548. * `id` should be a file descriptor or a path. `id` as file descriptor will
  549. * not be supported soon.
  550. */
  551. this.truncateSync = (id, len) => {
  552. if ((0, fs_core_1.isFd)(id))
  553. return this.ftruncateSync(id, len);
  554. this._truncate(id, len);
  555. };
  556. this.truncate = (id, a, b) => {
  557. const len = typeof a === 'number' ? a : 0;
  558. const callback = (0, util_3.validateCallback)(typeof a === 'number' ? b : a);
  559. if ((0, fs_core_1.isFd)(id))
  560. return this.ftruncate(id, len, callback);
  561. this.wrapAsync(this._truncate, [id, len], callback);
  562. };
  563. this._futimes = (fd, atime, mtime) => {
  564. this._core.futimes(fd, atime, mtime);
  565. };
  566. this.futimesSync = (fd, atime, mtime) => {
  567. this._futimes(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime));
  568. };
  569. this.futimes = (fd, atime, mtime, callback) => {
  570. this.wrapAsync(this._futimes, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback);
  571. };
  572. this._utimes = (filename, atime, mtime, followSymlinks = true) => {
  573. this._core.utimes(filename, atime, mtime, followSymlinks);
  574. };
  575. this.utimesSync = (path, atime, mtime) => {
  576. this._utimes((0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), true);
  577. };
  578. this.utimes = (path, atime, mtime, callback) => {
  579. this.wrapAsync(this._utimes, [(0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), true], callback);
  580. };
  581. this.lutimesSync = (path, atime, mtime) => {
  582. this._utimes((0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), false);
  583. };
  584. this.lutimes = (path, atime, mtime, callback) => {
  585. this.wrapAsync(this._utimes, [(0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), false], callback);
  586. };
  587. this.mkdirSync = (path, options) => {
  588. const opts = (0, options_1.getMkdirOptions)(options);
  589. const modeNum = (0, util_3.modeToNumber)(opts.mode, 0o777);
  590. const filename = (0, util_3.pathToFilename)(path);
  591. if (opts.recursive)
  592. return this._core.mkdirp(filename, modeNum);
  593. this._core.mkdir(filename, modeNum);
  594. };
  595. this.mkdir = (path, a, b) => {
  596. const opts = (0, options_1.getMkdirOptions)(a);
  597. const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b);
  598. const modeNum = (0, util_3.modeToNumber)(opts.mode, 0o777);
  599. const filename = (0, util_3.pathToFilename)(path);
  600. if (opts.recursive)
  601. this.wrapAsync(this._core.mkdirp, [filename, modeNum], callback);
  602. else
  603. this.wrapAsync(this._core.mkdir, [filename, modeNum], callback);
  604. };
  605. this._mkdtemp = (prefix, encoding, retry = 5) => {
  606. const filename = prefix + (0, util_3.genRndStr6)();
  607. try {
  608. this._core.mkdir(filename, 511 /* MODE.DIR */);
  609. return (0, fs_node_utils_1.strToEncoding)(filename, encoding);
  610. }
  611. catch (err) {
  612. if (err.code === "EEXIST" /* ERROR_CODE.EEXIST */) {
  613. if (retry > 1)
  614. return this._mkdtemp(prefix, encoding, retry - 1);
  615. else
  616. throw Error('Could not create temp dir.');
  617. }
  618. else
  619. throw err;
  620. }
  621. };
  622. this.mkdtempSync = (prefix, options) => {
  623. const { encoding } = (0, options_1.getDefaultOpts)(options);
  624. if (!prefix || typeof prefix !== 'string')
  625. throw new TypeError('filename prefix is required');
  626. (0, util_3.nullCheck)(prefix);
  627. return this._mkdtemp(prefix, encoding);
  628. };
  629. this.mkdtemp = (prefix, a, b) => {
  630. const [{ encoding }, callback] = (0, options_1.getDefaultOptsAndCb)(a, b);
  631. if (!prefix || typeof prefix !== 'string')
  632. throw new TypeError('filename prefix is required');
  633. if (!(0, util_3.nullCheck)(prefix))
  634. return;
  635. this.wrapAsync(this._mkdtemp, [prefix, encoding], callback);
  636. };
  637. this.rmdirSync = (path, options) => {
  638. const opts = (0, options_1.getRmdirOptions)(options);
  639. this._core.rmdir((0, util_3.pathToFilename)(path), opts.recursive);
  640. };
  641. this.rmdir = (path, a, b) => {
  642. const opts = (0, options_1.getRmdirOptions)(a);
  643. const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b);
  644. this.wrapAsync(this._core.rmdir, [(0, util_3.pathToFilename)(path), opts.recursive], callback);
  645. };
  646. this.rmSync = (path, options) => {
  647. this._core.rm((0, util_3.pathToFilename)(path), options?.force, options?.recursive);
  648. };
  649. this.rm = (path, a, b) => {
  650. const [opts, callback] = (0, options_1.getRmOptsAndCb)(a, b);
  651. this.wrapAsync(this._core.rm, [(0, util_3.pathToFilename)(path), opts?.force, opts?.recursive], callback);
  652. };
  653. this._fchmod = (fd, modeNum) => {
  654. this._core.fchmod(fd, modeNum);
  655. };
  656. this.fchmodSync = (fd, mode) => {
  657. this._fchmod(fd, (0, util_3.modeToNumber)(mode));
  658. };
  659. this.fchmod = (fd, mode, callback) => {
  660. this.wrapAsync(this._fchmod, [fd, (0, util_3.modeToNumber)(mode)], callback);
  661. };
  662. this._chmod = (filename, modeNum, followSymlinks = true) => {
  663. if (followSymlinks) {
  664. this._core.chmod(filename, modeNum);
  665. }
  666. else {
  667. this._core.lchmod(filename, modeNum);
  668. }
  669. };
  670. this.chmodSync = (path, mode) => {
  671. const modeNum = (0, util_3.modeToNumber)(mode);
  672. const filename = (0, util_3.pathToFilename)(path);
  673. this._chmod(filename, modeNum, true);
  674. };
  675. this.chmod = (path, mode, callback) => {
  676. const modeNum = (0, util_3.modeToNumber)(mode);
  677. const filename = (0, util_3.pathToFilename)(path);
  678. this.wrapAsync(this._chmod, [filename, modeNum], callback);
  679. };
  680. this._lchmod = (filename, modeNum) => {
  681. this._core.lchmod(filename, modeNum);
  682. };
  683. this.lchmodSync = (path, mode) => {
  684. const modeNum = (0, util_3.modeToNumber)(mode);
  685. const filename = (0, util_3.pathToFilename)(path);
  686. this._lchmod(filename, modeNum);
  687. };
  688. this.lchmod = (path, mode, callback) => {
  689. const modeNum = (0, util_3.modeToNumber)(mode);
  690. const filename = (0, util_3.pathToFilename)(path);
  691. this.wrapAsync(this._lchmod, [filename, modeNum], callback);
  692. };
  693. this._fchown = (fd, uid, gid) => {
  694. this._core.fchown(fd, uid, gid);
  695. };
  696. this.fchownSync = (fd, uid, gid) => {
  697. validateUid(uid);
  698. validateGid(gid);
  699. this._fchown(fd, uid, gid);
  700. };
  701. this.fchown = (fd, uid, gid, callback) => {
  702. validateUid(uid);
  703. validateGid(gid);
  704. this.wrapAsync(this._fchown, [fd, uid, gid], callback);
  705. };
  706. this._chown = (filename, uid, gid) => {
  707. this._core.chown(filename, uid, gid);
  708. };
  709. this.chownSync = (path, uid, gid) => {
  710. validateUid(uid);
  711. validateGid(gid);
  712. this._chown((0, util_3.pathToFilename)(path), uid, gid);
  713. };
  714. this.chown = (path, uid, gid, callback) => {
  715. validateUid(uid);
  716. validateGid(gid);
  717. this.wrapAsync(this._chown, [(0, util_3.pathToFilename)(path), uid, gid], callback);
  718. };
  719. this._lchown = (filename, uid, gid) => {
  720. this._core.lchown(filename, uid, gid);
  721. };
  722. this.lchownSync = (path, uid, gid) => {
  723. validateUid(uid);
  724. validateGid(gid);
  725. this._lchown((0, util_3.pathToFilename)(path), uid, gid);
  726. };
  727. this.lchown = (path, uid, gid, callback) => {
  728. validateUid(uid);
  729. validateGid(gid);
  730. this.wrapAsync(this._lchown, [(0, util_3.pathToFilename)(path), uid, gid], callback);
  731. };
  732. this.statWatchers = {};
  733. this.cpSync = (src, dest, options) => {
  734. const srcFilename = (0, util_3.pathToFilename)(src);
  735. const destFilename = (0, util_3.pathToFilename)(dest);
  736. const opts_ = {
  737. dereference: options?.dereference ?? false,
  738. errorOnExist: options?.errorOnExist ?? false,
  739. filter: options?.filter,
  740. force: options?.force ?? true,
  741. mode: options?.mode ?? 0,
  742. preserveTimestamps: options?.preserveTimestamps ?? false,
  743. recursive: options?.recursive ?? false,
  744. verbatimSymlinks: options?.verbatimSymlinks ?? false,
  745. };
  746. return this._cp(srcFilename, destFilename, opts_);
  747. };
  748. this.cp = (src, dest, a, b) => {
  749. const srcFilename = (0, util_3.pathToFilename)(src);
  750. const destFilename = (0, util_3.pathToFilename)(dest);
  751. let options;
  752. let callback;
  753. if (typeof a === 'function')
  754. [options, callback] = [{}, a];
  755. else
  756. [options, callback] = [a || {}, b];
  757. (0, util_3.validateCallback)(callback);
  758. const opts_ = {
  759. dereference: options?.dereference ?? false,
  760. errorOnExist: options?.errorOnExist ?? false,
  761. filter: options?.filter,
  762. force: options?.force ?? true,
  763. mode: options?.mode ?? 0,
  764. preserveTimestamps: options?.preserveTimestamps ?? false,
  765. recursive: options?.recursive ?? false,
  766. verbatimSymlinks: options?.verbatimSymlinks ?? false,
  767. };
  768. this.wrapAsync(this._cp, [srcFilename, destFilename, opts_], callback);
  769. };
  770. this.openAsBlob = async (path, options) => {
  771. const filename = (0, util_3.pathToFilename)(path);
  772. let link;
  773. try {
  774. link = this._core.getResolvedLinkOrThrow(filename, 'open');
  775. }
  776. catch (error) {
  777. // Convert ENOENT to Node.js-compatible error for openAsBlob
  778. if (error && typeof error === 'object' && error.code === 'ENOENT') {
  779. const nodeError = new errors.TypeError('ERR_INVALID_ARG_VALUE');
  780. throw nodeError;
  781. }
  782. throw error;
  783. }
  784. const node = link.getNode();
  785. // Note: Node.js allows opening directories as blobs, so we don't throw EISDIR
  786. const buffer = node.getBuffer();
  787. const type = options?.type || '';
  788. return new Blob([buffer], { type });
  789. };
  790. this.glob = (pattern, ...args) => {
  791. const [options, callback] = args.length === 1 ? [{}, args[0]] : [args[0], args[1]];
  792. this.wrapAsync(this._globSync, [pattern, options || {}], callback);
  793. };
  794. this.globSync = (pattern, options = {}) => {
  795. return this._globSync(pattern, options);
  796. };
  797. this._globSync = (pattern, options = {}) => {
  798. const { globSync } = require('./glob');
  799. return globSync(this, pattern, options);
  800. };
  801. this._opendir = (filename, options) => {
  802. const link = this._core.getResolvedLinkOrThrow(filename, 'scandir');
  803. const node = link.getNode();
  804. if (!node.isDirectory())
  805. throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'scandir', filename);
  806. return new Dir_1.Dir(link, options);
  807. };
  808. this.opendirSync = (path, options) => {
  809. const opts = (0, options_1.getOpendirOptions)(options);
  810. const filename = (0, util_3.pathToFilename)(path);
  811. return this._opendir(filename, opts);
  812. };
  813. this.opendir = (path, a, b) => {
  814. const [options, callback] = (0, options_1.getOpendirOptsAndCb)(a, b);
  815. const filename = (0, util_3.pathToFilename)(path);
  816. this.wrapAsync(this._opendir, [filename, options], callback);
  817. };
  818. const self = this; // tslint:disable-line no-this-assignment
  819. this.StatWatcher = class extends StatWatcher {
  820. constructor() {
  821. super(self);
  822. }
  823. };
  824. const _ReadStream = FsReadStream;
  825. this.ReadStream = class extends _ReadStream {
  826. constructor(...args) {
  827. super(self, ...args);
  828. }
  829. };
  830. const _WriteStream = FsWriteStream;
  831. this.WriteStream = class extends _WriteStream {
  832. constructor(...args) {
  833. super(self, ...args);
  834. }
  835. };
  836. this.FSWatcher = class extends FSWatcher {
  837. constructor() {
  838. super(self);
  839. }
  840. };
  841. const _realpath = (filename, encoding) => {
  842. const realLink = this._core.getResolvedLinkOrThrow(filename, 'realpath');
  843. return (0, fs_node_utils_1.strToEncoding)(realLink.getPath() || '/', encoding);
  844. };
  845. const realpathImpl = (path, a, b) => {
  846. const [opts, callback] = (0, options_1.getRealpathOptsAndCb)(a, b);
  847. const pathFilename = (0, util_3.pathToFilename)(path);
  848. self.wrapAsync(_realpath, [pathFilename, opts.encoding], callback);
  849. };
  850. const realpathSyncImpl = (path, options) => _realpath((0, util_3.pathToFilename)(path), (0, options_1.getRealpathOptions)(options).encoding);
  851. this.realpath = realpathImpl;
  852. this.realpath.native = realpathImpl;
  853. this.realpathSync = realpathSyncImpl;
  854. this.realpathSync.native = realpathSyncImpl;
  855. }
  856. wrapAsync(method, args, callback) {
  857. (0, util_3.validateCallback)(callback);
  858. Promise.resolve().then(() => {
  859. let result;
  860. try {
  861. result = method.apply(this, args);
  862. }
  863. catch (err) {
  864. callback(err);
  865. return;
  866. }
  867. callback(null, result);
  868. });
  869. }
  870. reset() {
  871. this._core.reset();
  872. }
  873. toJSON(paths, json = {}, isRelative = false, asBuffer = false) {
  874. return this._core.toJSON(paths, json, isRelative, asBuffer);
  875. }
  876. fromJSON(json, cwd) {
  877. return this._core.fromJSON(json, cwd);
  878. }
  879. fromNestedJSON(json, cwd) {
  880. return this._core.fromNestedJSON(json, cwd);
  881. }
  882. // Legacy interface
  883. mountSync(mountpoint, json) {
  884. this._core.fromJSON(json, mountpoint);
  885. }
  886. _write(fd, buf, offset, length, position) {
  887. return this._core.write(fd, buf, offset, length, position);
  888. }
  889. writevBase(fd, buffers, position) {
  890. this._core.getFileByFdOrThrow(fd);
  891. let p = position ?? undefined;
  892. if (p === -1) {
  893. p = undefined;
  894. }
  895. let bytesWritten = 0;
  896. for (const buffer of buffers) {
  897. const nodeBuf = buffer_1.Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength);
  898. const bytes = this._core.write(fd, nodeBuf, 0, nodeBuf.byteLength, p ?? null);
  899. p = undefined;
  900. bytesWritten += bytes;
  901. if (bytes < nodeBuf.byteLength)
  902. break;
  903. }
  904. return bytesWritten;
  905. }
  906. _copyFile(src, dest, flags) {
  907. const buf = this.readFileSync(src);
  908. if (flags & COPYFILE_EXCL && this.existsSync(dest))
  909. throw (0, util_3.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'copyFile', src, dest);
  910. if (flags & COPYFILE_FICLONE_FORCE)
  911. throw (0, util_3.createError)("ENOSYS" /* ERROR_CODE.ENOSYS */, 'copyFile', src, dest);
  912. this._core.writeFile(dest, buf, fs_node_utils_2.FLAGS.w, 438 /* MODE.DEFAULT */);
  913. }
  914. isSrcSubdir(src, dest) {
  915. try {
  916. const normalizedSrc = pathNormalize(src.startsWith('/') ? src : '/' + src);
  917. const normalizedDest = pathNormalize(dest.startsWith('/') ? dest : '/' + dest);
  918. if (normalizedSrc === normalizedDest)
  919. return true;
  920. // Check if dest is under src by using relative path
  921. // If dest is under src, the relative path from src to dest won't start with '..'
  922. const relativePath = pathRelative(normalizedSrc, normalizedDest);
  923. // If relative path is empty or doesn't start with '..', dest is under src
  924. return relativePath === '' || (!relativePath.startsWith('..') && !(0, path_1.isAbsolute)(relativePath));
  925. }
  926. catch (error) {
  927. // If path operations fail, assume it's safe (don't block the copy)
  928. return false;
  929. }
  930. }
  931. cpFileSync(srcStat, destStat, src, dest, options) {
  932. if (destStat) {
  933. if (options.errorOnExist)
  934. throw (0, util_3.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'cp', dest);
  935. if (!options.force)
  936. return;
  937. this.unlinkSync(dest);
  938. }
  939. // Copy the file
  940. this.copyFileSync(src, dest, options.mode);
  941. // Preserve timestamps if requested
  942. if (options.preserveTimestamps)
  943. this.utimesSync(dest, srcStat.atime, srcStat.mtime);
  944. // Set file mode
  945. this.chmodSync(dest, Number(srcStat.mode));
  946. }
  947. cpDirSync(srcStat, destStat, src, dest, options) {
  948. if (!destStat) {
  949. this.mkdirSync(dest);
  950. }
  951. // Read directory contents
  952. const entries = this.readdirSync(src);
  953. for (const entry of entries) {
  954. const srcItem = pathJoin(src, String(entry));
  955. const destItem = pathJoin(dest, String(entry));
  956. // Apply filter to each item
  957. if (options.filter && !options.filter(srcItem, destItem)) {
  958. continue;
  959. }
  960. this._cp(srcItem, destItem, options);
  961. }
  962. // Set directory mode
  963. this.chmodSync(dest, Number(srcStat.mode));
  964. }
  965. cpSymlinkSync(destStat, src, dest, options) {
  966. let linkTarget = String(this.readlinkSync(src));
  967. if (!options.verbatimSymlinks && !(0, path_1.isAbsolute)(linkTarget))
  968. linkTarget = resolveCrossPlatform(pathDirname(src), linkTarget);
  969. if (destStat)
  970. this.unlinkSync(dest);
  971. this.symlinkSync(linkTarget, dest);
  972. }
  973. lstat(path, a, b) {
  974. const [{ throwIfNoEntry = true, bigint = false }, callback] = (0, options_1.getStatOptsAndCb)(a, b);
  975. this.wrapAsync(this._lstat, [(0, util_3.pathToFilename)(path), bigint, throwIfNoEntry], callback);
  976. }
  977. _stat(filename, bigint = false, throwIfNoEntry = true) {
  978. const result = this._core.getResolvedLinkResult(filename, 'stat');
  979. if (result.ok) {
  980. return (0, fs_core_1.Ok)(Stats_1.default.build(result.value.getNode(), bigint));
  981. }
  982. if (result.err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && !throwIfNoEntry) {
  983. return (0, fs_core_1.Ok)(undefined);
  984. }
  985. else {
  986. return result;
  987. }
  988. }
  989. _statOrThrow(filename, bigint = false, throwIfNoEntry = true) {
  990. const result = this._stat(filename, bigint, throwIfNoEntry);
  991. if (result.ok) {
  992. return result.value;
  993. }
  994. else {
  995. throw result.err.toError();
  996. }
  997. }
  998. statSync(path, options) {
  999. const { bigint = true, throwIfNoEntry = true } = (0, options_1.getStatOptions)(options);
  1000. const result = this._stat((0, util_3.pathToFilename)(path), bigint, throwIfNoEntry);
  1001. if (result.ok) {
  1002. return result.value;
  1003. }
  1004. else {
  1005. throw result.err.toError();
  1006. }
  1007. }
  1008. stat(path, a, b) {
  1009. const [{ bigint = false, throwIfNoEntry = true }, callback] = (0, options_1.getStatOptsAndCb)(a, b);
  1010. this.wrapAsync(this._statOrThrow, [(0, util_3.pathToFilename)(path), bigint, throwIfNoEntry], callback);
  1011. }
  1012. fstatBase(fd, bigint = false) {
  1013. const file = this._core.getFileByFd(fd);
  1014. if (!file)
  1015. throw (0, util_3.createError)("EBADF" /* ERROR_CODE.EBADF */, 'fstat');
  1016. return Stats_1.default.build(file.node, bigint);
  1017. }
  1018. fstatSync(fd, options) {
  1019. return this.fstatBase(fd, (0, options_1.getStatOptions)(options).bigint);
  1020. }
  1021. fstat(fd, a, b) {
  1022. const [opts, callback] = (0, options_1.getStatOptsAndCb)(a, b);
  1023. this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback);
  1024. }
  1025. _exists(filename) {
  1026. const result = this._stat(filename);
  1027. return result.ok ? (0, fs_core_1.Ok)(true) : result;
  1028. }
  1029. _access(filename, mode) {
  1030. const link = this._core.getResolvedLinkOrThrow(filename, 'access');
  1031. const node = link.getNode();
  1032. // F_OK (0) just checks for existence, which we already confirmed above
  1033. if (mode === F_OK) {
  1034. return;
  1035. }
  1036. // Check read permission
  1037. if (mode & R_OK && !node.canRead()) {
  1038. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename);
  1039. }
  1040. // Check write permission
  1041. if (mode & W_OK && !node.canWrite()) {
  1042. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename);
  1043. }
  1044. // Check execute permission
  1045. if (mode & X_OK && !node.canExecute()) {
  1046. throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename);
  1047. }
  1048. }
  1049. watchFile(path, a, b) {
  1050. const filename = (0, util_3.pathToFilename)(path);
  1051. let options = a;
  1052. let listener = b;
  1053. if (typeof options === 'function') {
  1054. listener = a;
  1055. options = null;
  1056. }
  1057. if (typeof listener !== 'function') {
  1058. throw new TypeError('The "listener" argument must be of type function. Received ' + typeof listener);
  1059. }
  1060. let interval = 5007;
  1061. let persistent = true;
  1062. let bigint = false;
  1063. if (options && typeof options === 'object') {
  1064. if (options.interval !== undefined) {
  1065. if (typeof options.interval !== 'number')
  1066. throw new TypeError('The "options.interval" property must be of type number. Received ' + typeof options.interval);
  1067. if (!Number.isInteger(options.interval) || options.interval < 0 || options.interval > 0xffffffff)
  1068. throw new RangeError('The value of "options.interval" is out of range. ' +
  1069. `It must be an integer >= 0 && <= 4294967295. Received ${options.interval}`);
  1070. interval = options.interval;
  1071. }
  1072. if (typeof options.persistent === 'boolean')
  1073. persistent = options.persistent;
  1074. if (typeof options.bigint === 'boolean')
  1075. bigint = options.bigint;
  1076. }
  1077. let watcher = this.statWatchers[filename];
  1078. if (!watcher) {
  1079. watcher = new this.StatWatcher();
  1080. watcher.start(filename, persistent, interval, bigint);
  1081. this.statWatchers[filename] = watcher;
  1082. }
  1083. watcher.addListener('change', listener);
  1084. return watcher;
  1085. }
  1086. unwatchFile(path, listener) {
  1087. const filename = (0, util_3.pathToFilename)(path);
  1088. const watcher = this.statWatchers[filename];
  1089. if (!watcher)
  1090. return;
  1091. if (typeof listener === 'function') {
  1092. watcher.removeListener('change', listener);
  1093. }
  1094. else {
  1095. watcher.removeAllListeners('change');
  1096. }
  1097. if (watcher.listenerCount('change') === 0) {
  1098. watcher.stop();
  1099. delete this.statWatchers[filename];
  1100. }
  1101. }
  1102. createReadStream(path, options) {
  1103. return new this.ReadStream(path, options);
  1104. }
  1105. createWriteStream(path, options) {
  1106. return new this.WriteStream(path, options);
  1107. }
  1108. watch(path, options, listener) {
  1109. const filename = (0, util_3.pathToFilename)(path);
  1110. let givenOptions = options;
  1111. if (typeof options === 'function') {
  1112. listener = options;
  1113. givenOptions = null;
  1114. }
  1115. // tslint:disable-next-line prefer-const
  1116. let { persistent, recursive, encoding, signal, throwIfNoEntry, ignore } = (0, options_1.getDefaultOpts)(givenOptions);
  1117. if (persistent === undefined)
  1118. persistent = true;
  1119. if (recursive === undefined)
  1120. recursive = false;
  1121. const watcher = new this.FSWatcher();
  1122. try {
  1123. watcher.start(filename, persistent, recursive, encoding, ignore);
  1124. }
  1125. catch (err) {
  1126. if (throwIfNoEntry === false && err.code === 'ENOENT')
  1127. return watcher;
  1128. throw err;
  1129. }
  1130. if (listener) {
  1131. watcher.addListener('change', listener);
  1132. }
  1133. if (signal) {
  1134. if (signal.aborted) {
  1135. watcher.close();
  1136. }
  1137. else {
  1138. const onAbort = () => watcher.close();
  1139. signal.addEventListener('abort', onAbort, { once: true });
  1140. watcher.once('close', () => signal.removeEventListener('abort', onAbort));
  1141. }
  1142. }
  1143. return watcher;
  1144. }
  1145. _statfs(filename, bigint = false) {
  1146. // Verify the path exists to match Node.js behavior
  1147. this._core.getResolvedLinkOrThrow(filename, 'statfs');
  1148. return StatFs_1.default.build(this._core, bigint);
  1149. }
  1150. statfsSync(path, options) {
  1151. const { bigint = false } = (0, options_1.getStatfsOptions)(options);
  1152. return this._statfs((0, util_3.pathToFilename)(path), bigint);
  1153. }
  1154. statfs(path, a, b) {
  1155. const [{ bigint = false }, callback] = (0, options_1.getStatfsOptsAndCb)(a, b);
  1156. this.wrapAsync(this._statfs, [(0, util_3.pathToFilename)(path), bigint], callback);
  1157. }
  1158. // ---------------------------------------------------------------- Tree View
  1159. toTree(opts = { separator: path_1.sep }) {
  1160. return (0, fs_print_1.toTreeSync)(this, opts);
  1161. }
  1162. // ---------------------------------------------------------------- Snapshots
  1163. toSnapshot(path = '/') {
  1164. return fsSnapshot.toSnapshotSync({ fs: this, path });
  1165. }
  1166. fromSnapshot(snapshot, path = '/') {
  1167. return fsSnapshot.fromSnapshotSync(snapshot, { fs: this, path });
  1168. }
  1169. toBinarySnapshot(path = '/') {
  1170. return fsSnapshot.toBinarySnapshotSync({ fs: this, path });
  1171. }
  1172. fromBinarySnapshot(binary, path = '/') {
  1173. return fsSnapshot.fromBinarySnapshotSync(binary, { fs: this, path });
  1174. }
  1175. toJsonSnapshot(path = '/') {
  1176. const uint8 = fsSnapshot.toJsonSnapshotSync({ fs: this, path });
  1177. return buffer_1.Buffer.from(uint8).toString('utf8');
  1178. }
  1179. fromJsonSnapshot(json, path = '/') {
  1180. const uint8 = new Uint8Array(buffer_1.Buffer.from(json, 'utf8'));
  1181. return fsSnapshot.fromJsonSnapshotSync(uint8, { fs: this, path });
  1182. }
  1183. }
  1184. exports.Volume = Volume;
  1185. Volume.fromJSON = (json, cwd, opts) => new Volume(fs_core_1.Superblock.fromJSON(json, cwd, opts));
  1186. Volume.fromNestedJSON = (json, cwd, opts) => new Volume(fs_core_1.Superblock.fromNestedJSON(json, cwd, opts));
  1187. function emitStop(self) {
  1188. self.emit('stop');
  1189. }
  1190. /** All-zero stats passed to `watchFile` listeners when the file is missing, like in Node.js. */
  1191. function buildZeroStats(bigint) {
  1192. const stats = new Stats_1.default();
  1193. const zero = bigint ? BigInt(0) : 0;
  1194. const epoch = new Date(0);
  1195. stats.uid = zero;
  1196. stats.gid = zero;
  1197. stats.rdev = zero;
  1198. stats.blksize = zero;
  1199. stats.ino = zero;
  1200. stats.size = zero;
  1201. stats.blocks = zero;
  1202. stats.atime = epoch;
  1203. stats.mtime = epoch;
  1204. stats.ctime = epoch;
  1205. stats.birthtime = epoch;
  1206. stats.atimeMs = zero;
  1207. stats.mtimeMs = zero;
  1208. stats.ctimeMs = zero;
  1209. stats.birthtimeMs = zero;
  1210. if (bigint) {
  1211. stats.atimeNs = zero;
  1212. stats.mtimeNs = zero;
  1213. stats.ctimeNs = zero;
  1214. stats.birthtimeNs = zero;
  1215. }
  1216. stats.dev = zero;
  1217. stats.mode = zero;
  1218. stats.nlink = zero;
  1219. return stats;
  1220. }
  1221. class StatWatcher extends events_1.EventEmitter {
  1222. constructor(vol) {
  1223. super();
  1224. this.bigint = false;
  1225. this.fileExists = false;
  1226. this.stopped = false;
  1227. this.onInterval = () => {
  1228. if (this.stopped)
  1229. return;
  1230. const stats = this.statSafe();
  1231. if (stats) {
  1232. if (!this.fileExists) {
  1233. // Reappearance: `prev` is the stats from before the file disappeared, not the zeroed stats.
  1234. this.fileExists = true;
  1235. const prev = this.prev;
  1236. this.prev = stats;
  1237. this.emit('change', stats, prev);
  1238. }
  1239. else if (this.hasChanged(stats)) {
  1240. const prev = this.prev;
  1241. this.prev = stats;
  1242. this.emit('change', stats, prev);
  1243. }
  1244. }
  1245. else if (this.fileExists) {
  1246. // Disappearance is reported once, with zeroed current stats, `prev`
  1247. // keeps the last real stats for the eventual reappearance event.
  1248. this.fileExists = false;
  1249. this.emit('change', buildZeroStats(this.bigint), this.prev);
  1250. }
  1251. this.loop();
  1252. };
  1253. this.vol = vol;
  1254. }
  1255. loop() {
  1256. clearTimeout(this.timeoutRef);
  1257. this.timeoutRef = this.setTimeout(this.onInterval, this.interval);
  1258. }
  1259. hasChanged(stats) {
  1260. const prev = this.prev;
  1261. return (stats.mtimeMs !== prev.mtimeMs ||
  1262. stats.ctimeMs !== prev.ctimeMs ||
  1263. stats.size !== prev.size ||
  1264. stats.ino !== prev.ino ||
  1265. stats.mode !== prev.mode ||
  1266. stats.uid !== prev.uid ||
  1267. stats.gid !== prev.gid ||
  1268. stats.nlink !== prev.nlink);
  1269. }
  1270. statSafe() {
  1271. try {
  1272. return (this.bigint ? this.vol.statSync(this.filename, { bigint: true }) : this.vol.statSync(this.filename));
  1273. }
  1274. catch {
  1275. return null;
  1276. }
  1277. }
  1278. start(path, persistent = true, interval = 5007, bigint = false) {
  1279. this.filename = (0, util_3.pathToFilename)(path);
  1280. this.setTimeout = persistent
  1281. ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global)
  1282. : setTimeoutUnref_1.default;
  1283. this.interval = interval;
  1284. this.bigint = bigint;
  1285. const stats = this.statSafe();
  1286. if (stats) {
  1287. this.prev = stats;
  1288. this.fileExists = true;
  1289. }
  1290. else {
  1291. // Watching a missing path does not throw, the listener is called once
  1292. // with zeroed stats, then again when the file is created.
  1293. this.prev = buildZeroStats(bigint);
  1294. this.fileExists = false;
  1295. queueMicrotask(() => {
  1296. if (!this.stopped)
  1297. this.emit('change', this.prev, this.prev);
  1298. });
  1299. }
  1300. this.loop();
  1301. }
  1302. stop() {
  1303. this.stopped = true;
  1304. clearTimeout(this.timeoutRef);
  1305. queueMicrotask(() => {
  1306. emitStop.call(this, this);
  1307. });
  1308. }
  1309. /**
  1310. * Keep the event loop alive while the watcher is active. Polling continues
  1311. * either way; this only controls whether the process is kept running.
  1312. */
  1313. ref() {
  1314. this.setTimeout = setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : global);
  1315. const ref = this.timeoutRef;
  1316. if (ref && typeof ref === 'object' && typeof ref.ref === 'function')
  1317. ref.ref();
  1318. return this;
  1319. }
  1320. /** Let the process exit while the watcher is active. Polling continues. */
  1321. unref() {
  1322. this.setTimeout = setTimeoutUnref_1.default;
  1323. const ref = this.timeoutRef;
  1324. if (ref && typeof ref === 'object' && typeof ref.unref === 'function')
  1325. ref.unref();
  1326. return this;
  1327. }
  1328. }
  1329. exports.StatWatcher = StatWatcher;
  1330. /* tslint:disable no-var-keyword prefer-const */
  1331. // ---------------------------------------- ReadStream
  1332. var pool;
  1333. function allocNewPool(poolSize) {
  1334. pool = (0, buffer_1.bufferAllocUnsafe)(poolSize);
  1335. pool.used = 0;
  1336. }
  1337. (0, util_2.inherits)(FsReadStream, stream_1.Readable);
  1338. exports.ReadStream = FsReadStream;
  1339. function FsReadStream(vol, path, options) {
  1340. if (!(this instanceof FsReadStream))
  1341. return new FsReadStream(vol, path, options);
  1342. this._vol = vol;
  1343. // a little bit bigger buffer and water marks by default
  1344. options = Object.assign({}, (0, options_1.getOptions)(options, {}));
  1345. if (options.highWaterMark === undefined)
  1346. options.highWaterMark = 64 * 1024;
  1347. stream_1.Readable.call(this, options);
  1348. this.path = (0, util_3.pathToFilename)(path);
  1349. this._fileHandle = options.fd && typeof options.fd !== 'number' ? options.fd : null;
  1350. this.fd = options.fd === undefined ? null : typeof options.fd !== 'number' ? options.fd.fd : options.fd;
  1351. this.flags = options.flags === undefined ? 'r' : options.flags;
  1352. this.mode = options.mode === undefined ? 0o666 : options.mode;
  1353. this.start = options.start;
  1354. this.end = options.end;
  1355. this.autoClose = options.autoClose === undefined ? true : options.autoClose;
  1356. this.pos = undefined;
  1357. this.bytesRead = 0;
  1358. if (this.start !== undefined) {
  1359. if (typeof this.start !== 'number') {
  1360. throw new TypeError('"start" option must be a Number');
  1361. }
  1362. if (this.end === undefined) {
  1363. this.end = Infinity;
  1364. }
  1365. else if (typeof this.end !== 'number') {
  1366. throw new TypeError('"end" option must be a Number');
  1367. }
  1368. if (this.start > this.end) {
  1369. throw new Error('"start" option must be <= "end" option');
  1370. }
  1371. this.pos = this.start;
  1372. }
  1373. if (typeof this.fd !== 'number')
  1374. this.open();
  1375. this.on('end', function () {
  1376. if (this.autoClose) {
  1377. if (this.destroy)
  1378. this.destroy();
  1379. }
  1380. });
  1381. }
  1382. FsReadStream.prototype.open = function () {
  1383. var self = this; // tslint:disable-line no-this-assignment
  1384. this._vol.open(this.path, this.flags, this.mode, (er, fd) => {
  1385. if (er) {
  1386. if (self.autoClose) {
  1387. if (self.destroy)
  1388. self.destroy();
  1389. }
  1390. self.emit('error', er);
  1391. return;
  1392. }
  1393. self.fd = fd;
  1394. self.emit('open', fd);
  1395. // start the flow of data.
  1396. self.read();
  1397. });
  1398. };
  1399. FsReadStream.prototype._read = function (n) {
  1400. if (typeof this.fd !== 'number') {
  1401. return this.once('open', function () {
  1402. this._read(n);
  1403. });
  1404. }
  1405. if (this.destroyed)
  1406. return;
  1407. if (!pool || pool.length - pool.used < kMinPoolSpace) {
  1408. // discard the old pool.
  1409. allocNewPool(this._readableState.highWaterMark);
  1410. }
  1411. // Grab another reference to the pool in the case that while we're
  1412. // in the thread pool another read() finishes up the pool, and
  1413. // allocates a new one.
  1414. var thisPool = pool;
  1415. var toRead = Math.min(pool.length - pool.used, n);
  1416. var start = pool.used;
  1417. if (this.pos !== undefined)
  1418. toRead = Math.min(this.end - this.pos + 1, toRead);
  1419. // already read everything we were supposed to read!
  1420. // treat as EOF.
  1421. if (toRead <= 0)
  1422. return this.push(null);
  1423. // the actual read.
  1424. var self = this; // tslint:disable-line no-this-assignment
  1425. this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread);
  1426. // move the pool positions, and internal position for reading.
  1427. if (this.pos !== undefined)
  1428. this.pos += toRead;
  1429. pool.used += toRead;
  1430. function onread(er, bytesRead) {
  1431. if (er) {
  1432. if (self.autoClose && self.destroy) {
  1433. self.destroy();
  1434. }
  1435. self.emit('error', er);
  1436. }
  1437. else {
  1438. var b = null;
  1439. if (bytesRead > 0) {
  1440. self.bytesRead += bytesRead;
  1441. b = thisPool.slice(start, start + bytesRead);
  1442. }
  1443. self.push(b);
  1444. }
  1445. }
  1446. };
  1447. FsReadStream.prototype._destroy = function (err, cb) {
  1448. this.close(err2 => {
  1449. cb(err || err2);
  1450. });
  1451. };
  1452. FsReadStream.prototype.close = function (cb) {
  1453. if (cb)
  1454. this.once('close', cb);
  1455. if (this.closed || typeof this.fd !== 'number') {
  1456. if (typeof this.fd !== 'number') {
  1457. this.once('open', closeOnOpen);
  1458. return;
  1459. }
  1460. return queueMicrotask(() => this.emit('close'));
  1461. }
  1462. // Since Node 18, there is only a getter for '.closed'.
  1463. // The first branch mimics other setters from Readable.
  1464. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/readable.js#L1243
  1465. if (typeof this._readableState?.closed === 'boolean') {
  1466. this._readableState.closed = true;
  1467. }
  1468. else {
  1469. this.closed = true;
  1470. }
  1471. if (this._fileHandle) {
  1472. this._fileHandle.close().then(() => this.emit('close'), er => this.emit('error', er));
  1473. }
  1474. else {
  1475. this._vol.close(this.fd, er => {
  1476. if (er)
  1477. this.emit('error', er);
  1478. else
  1479. this.emit('close');
  1480. });
  1481. }
  1482. this.fd = null;
  1483. };
  1484. // needed because as it will be called with arguments
  1485. // that does not match this.close() signature
  1486. function closeOnOpen(fd) {
  1487. this.close();
  1488. }
  1489. (0, util_2.inherits)(FsWriteStream, stream_1.Writable);
  1490. exports.WriteStream = FsWriteStream;
  1491. function FsWriteStream(vol, path, options) {
  1492. if (!(this instanceof FsWriteStream))
  1493. return new FsWriteStream(vol, path, options);
  1494. this._vol = vol;
  1495. options = Object.assign({}, (0, options_1.getOptions)(options, {}));
  1496. stream_1.Writable.call(this, options);
  1497. this.path = (0, util_3.pathToFilename)(path);
  1498. this._fileHandle = options.fd && typeof options.fd !== 'number' ? options.fd : null;
  1499. this.fd = options.fd === undefined ? null : typeof options.fd !== 'number' ? options.fd.fd : options.fd;
  1500. this.flags = options.flags === undefined ? 'w' : options.flags;
  1501. this.mode = options.mode === undefined ? 0o666 : options.mode;
  1502. this.start = options.start;
  1503. this.autoClose = options.autoClose === undefined ? true : !!options.autoClose;
  1504. this.pos = undefined;
  1505. this.bytesWritten = 0;
  1506. this.pending = true;
  1507. if (this.start !== undefined) {
  1508. if (typeof this.start !== 'number') {
  1509. throw new TypeError('"start" option must be a Number');
  1510. }
  1511. if (this.start < 0) {
  1512. throw new Error('"start" must be >= zero');
  1513. }
  1514. this.pos = this.start;
  1515. }
  1516. if (options.encoding)
  1517. this.setDefaultEncoding(options.encoding);
  1518. if (typeof this.fd !== 'number')
  1519. this.open();
  1520. // dispose on finish.
  1521. this.once('finish', function () {
  1522. if (this.autoClose) {
  1523. this.close();
  1524. }
  1525. });
  1526. }
  1527. FsWriteStream.prototype.open = function () {
  1528. this._vol.open(this.path, this.flags, this.mode, function (er, fd) {
  1529. if (er) {
  1530. if (this.autoClose && this.destroy) {
  1531. this.destroy();
  1532. }
  1533. this.emit('error', er);
  1534. return;
  1535. }
  1536. this.fd = fd;
  1537. this.pending = false;
  1538. this.emit('open', fd);
  1539. }.bind(this));
  1540. };
  1541. FsWriteStream.prototype._write = function (data, encoding, cb) {
  1542. if (!(data instanceof buffer_1.Buffer || data instanceof Uint8Array))
  1543. return this.emit('error', new Error('Invalid data'));
  1544. if (typeof this.fd !== 'number') {
  1545. return this.once('open', function () {
  1546. this._write(data, encoding, cb);
  1547. });
  1548. }
  1549. var self = this; // tslint:disable-line no-this-assignment
  1550. this._vol.write(this.fd, data, 0, data.length, this.pos, (er, bytes) => {
  1551. if (er) {
  1552. if (self.autoClose && self.destroy) {
  1553. self.destroy();
  1554. }
  1555. return cb(er);
  1556. }
  1557. self.bytesWritten += bytes;
  1558. cb();
  1559. });
  1560. if (this.pos !== undefined)
  1561. this.pos += data.length;
  1562. };
  1563. FsWriteStream.prototype._writev = function (data, cb) {
  1564. if (typeof this.fd !== 'number') {
  1565. return this.once('open', function () {
  1566. this._writev(data, cb);
  1567. });
  1568. }
  1569. const self = this; // tslint:disable-line no-this-assignment
  1570. const len = data.length;
  1571. const chunks = new Array(len);
  1572. var size = 0;
  1573. for (var i = 0; i < len; i++) {
  1574. var chunk = data[i].chunk;
  1575. chunks[i] = chunk;
  1576. size += chunk.length;
  1577. }
  1578. const buf = buffer_1.Buffer.concat(chunks);
  1579. this._vol.write(this.fd, buf, 0, buf.length, this.pos, (er, bytes) => {
  1580. if (er) {
  1581. if (self.destroy)
  1582. self.destroy();
  1583. return cb(er);
  1584. }
  1585. self.bytesWritten += bytes;
  1586. cb();
  1587. });
  1588. if (this.pos !== undefined)
  1589. this.pos += size;
  1590. };
  1591. FsWriteStream.prototype.close = function (cb) {
  1592. if (cb)
  1593. this.once('close', cb);
  1594. if (this.closed || typeof this.fd !== 'number') {
  1595. if (typeof this.fd !== 'number') {
  1596. this.once('open', closeOnOpen);
  1597. return;
  1598. }
  1599. return queueMicrotask(() => this.emit('close'));
  1600. }
  1601. // Since Node 18, there is only a getter for '.closed'.
  1602. // The first branch mimics other setters from Writable.
  1603. // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/writable.js#L766
  1604. if (typeof this._writableState?.closed === 'boolean') {
  1605. this._writableState.closed = true;
  1606. }
  1607. else {
  1608. this.closed = true;
  1609. }
  1610. if (this._fileHandle) {
  1611. this._fileHandle.close().then(() => this.emit('close'), er => this.emit('error', er));
  1612. }
  1613. else {
  1614. this._vol.close(this.fd, er => {
  1615. if (er)
  1616. this.emit('error', er);
  1617. else
  1618. this.emit('close');
  1619. });
  1620. }
  1621. this.fd = null;
  1622. };
  1623. FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy;
  1624. // There is no shutdown() for files.
  1625. FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end;
  1626. // ---------------------------------------- FSWatcher
  1627. class FSWatcher extends events_1.EventEmitter {
  1628. constructor(vol) {
  1629. super();
  1630. this._filename = '';
  1631. this._filenameEncoded = '';
  1632. this._recursive = false;
  1633. this._encoding = fs_node_utils_1.ENCODING_UTF8;
  1634. this._closed = false;
  1635. this._onEvent = (event) => {
  1636. switch (event.type) {
  1637. case 0 /* FsEventType.CREATE */:
  1638. case 1 /* FsEventType.DELETE */:
  1639. this._emit('rename', event.steps);
  1640. break;
  1641. case 4 /* FsEventType.MOVE */:
  1642. if (event.oldSteps)
  1643. this._emit('rename', event.oldSteps);
  1644. this._emit('rename', event.steps);
  1645. break;
  1646. case 2 /* FsEventType.MODIFY */:
  1647. case 3 /* FsEventType.ATTRIB */:
  1648. this._emit('change', event.steps);
  1649. break;
  1650. }
  1651. };
  1652. this._persist = () => {
  1653. this._timer = setTimeout(this._persist, 1e6);
  1654. };
  1655. this._vol = vol;
  1656. }
  1657. _emit(type, relativeSteps) {
  1658. const filename = relativeSteps.length ? relativeSteps.join(pathSep) : this._watcher.link.getName();
  1659. if (this._ignore && this._ignore(filename))
  1660. return;
  1661. this.emit('change', type, (0, fs_node_utils_1.strToEncoding)(filename, this._encoding));
  1662. }
  1663. /**
  1664. * Keep the event loop alive while the watcher is active. All watchers are
  1665. * ref'ed by default (unless started with `persistent: false`). No-op when
  1666. * already ref'ed, closed, or never started.
  1667. */
  1668. ref() {
  1669. if (this._watcher && !this._closed && !this._timer)
  1670. this._persist();
  1671. return this;
  1672. }
  1673. /**
  1674. * Let the process exit while the watcher is active. Events are still
  1675. * delivered. No-op when already unref'ed.
  1676. */
  1677. unref() {
  1678. clearTimeout(this._timer);
  1679. this._timer = undefined;
  1680. return this;
  1681. }
  1682. start(path, persistent = true, recursive = false, encoding = fs_node_utils_1.ENCODING_UTF8, ignore) {
  1683. this._filename = (0, util_3.pathToFilename)(path);
  1684. this._steps = (0, fs_core_1.filenameToSteps)(this._filename);
  1685. this._filenameEncoded = (0, fs_node_utils_1.strToEncoding)(this._filename);
  1686. this._recursive = recursive;
  1687. this._encoding = encoding;
  1688. this._ignore = ignore === undefined ? undefined : (0, fs_node_utils_1.watchIgnoreToMatcher)(ignore);
  1689. try {
  1690. this._watcher = new fs_core_1.CoreWatcher(this._vol._core, this._filename, { recursive });
  1691. }
  1692. catch (err) {
  1693. const error = new Error(`watch ${this._filename} ${err.code}`);
  1694. error.code = err.code;
  1695. error.errno = err.code;
  1696. throw error;
  1697. }
  1698. this._link = this._watcher.link;
  1699. this._watcher.changes.listen(this._onEvent);
  1700. if (persistent)
  1701. this._persist();
  1702. }
  1703. close() {
  1704. clearTimeout(this._timer);
  1705. this._timer = undefined;
  1706. if (!this._watcher || this._closed)
  1707. return;
  1708. this._closed = true;
  1709. this._watcher.close();
  1710. queueMicrotask(() => this.emit('close'));
  1711. }
  1712. }
  1713. exports.FSWatcher = FSWatcher;
  1714. //# sourceMappingURL=volume.js.map