All files / lib/internal/fs utils.js

96.57% Statements 930/963
96.4% Branches 268/278
100% Functions 39/39
96.57% Lines 930/963

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 96436x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 82x 82x 12x 12x 82x 82x 36x 104143x 104143x 19x 19x 19x 104143x 36x 36x 36x 50481x 50481x 50481x 36x 36x 49704x 49704x 36x 36x 274x 274x 36x 36x 42x 42x 36x 36x 42x 42x 36x 36x 42x 42x 36x 36x 42x 42x 36x 36x 42x 42x 36x 36x 36x 36x 16x 16x 16x 36x 36x 36x 288x 36x 36x 252x 70x 252x 252x 36x 2438x 2438x 2438x 2438x 2438x 2438x 36x 36x 36x 18x 18x 18x     18x 18x 2x 2x 2x 16x 18x 12x 12x 4x 18x 2x 2x 2x 2x 2x 18x 36x 200x 200x 200x 7x 7x 7x 7x 19x 19x 9x 9x 9x 9x 9x 9x 9x 1x 1x 1x 8x 8x       8x 8x 4x 4x 8x 19x 10x 10x 19x 7x 2x 2x 200x 193x 193x 50007x 50007x 193x 193x 200x 36x 50457x 50457x 281x 4x 4x 4x 4x 1x 1x 1x 3x 3x       3x 3x 281x 277x 277x 50457x 5x 5x 50171x 50171x 50171x 50457x 36x 128607x 128607x 23683x 23683x 104924x 128603x 43232x 43232x 43232x 128607x 8x 8x 104916x 104916x 106256x 104898x 127562x 18x 18x 104896x 128607x 36x 36x 36x 36x 507288x 507288x 1607x 1607x 1607x 1607x 507287x             507288x 36x 36x 36x 36x 171688x 171688x 171688x 171688x 171688x 171688x 171688x 171513x 171513x 175x 175x 175x 175x 175x 175x 256x     175x 36x 36x 357x 357x 357x 357x 357x                           357x 36x 36x 20034x 20034x 20034x 20034x 20034x 20034x 20034x 20034x 20034x 20034x 20034x 20034x 20034x 36x 36x 7713x 36x 36x 36x 1566x 36x 36x 36x 44x 36x 36x 36x 44x 36x 36x 36x 452x 36x 36x 36x 29x 36x 36x 36x 31x 36x 36x 36x 36x 36x 36x 73984x 73984x 73984x 36x 4120x 4120x 4120x 36x 36x 36x 36x 36x 36x 36x 36x 80136x 80136x 80136x 80136x 36x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 1031x 36x 36x 36x 36x 36x 1098x 1098x     1098x 36x 36x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 19003x 36x 36x 36x 36x 36x 36x 36x 36x 36x 8781x 8781x     8781x 36x 36x 36x 36x 36x 36x 36x 19526x 19526x 1030x 1030x 1030x 1030x 1030x 1030x 1030x 1030x 1030x 1030x 1030x 18496x 18496x 18496x 18496x 18496x 18496x 18496x 18496x 18496x 18496x 19526x 36x 60402x 60402x 10x 10x 10x 60392x 60402x 6560x 6560x 53832x 53832x 54023x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 60402x 22x 22x 60402x 36x 36x 356x 356x 267x 267x 30x 30x 267x 5x 5x 267x 230x 267x 2x 267x 267x 354x 36x 36x 36x 281x 281x 281x 10x 10x 281x 45x 15x 15x 30x 30x 231x 222x 222x 222x 4x 281x 36x 36x 36x 216983x 1x 1x 216983x 3x 3x 216983x 2x 2x 2x 216983x 36x 36x 36x 36x 59280x 4x 4x 59276x 59279x 7x 7x 59269x 59278x 5x 5x 59264x 59264x 59280x 36x 36x 36x 171976x 303x 303x 171673x 171673x 171673x 171976x 175x 175x 36x 36x 36x 109997x 109997x 109997x 36x 36x 36x 333584x 1x 1x 333583x 333583x 333583x 333583x 36x 36x 36x 60x 60x 40x 60x 78x 78x 78x 32x 32x 36x 36x 36x 36x 15x 15x 15x 15x 1x 1x 1x 1x 15x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 76x 76x 62x 62x 62x 62x 62x 62x 62x 62x 76x 1x 1x 76x 4x 4x 48x 36x 36x 36x 38x 38x 38x 38x 38x 13x 1x 1x 12x 12x 25x 38x 2x 2x 23x 38x 10x 10x 10x 10x 10x 10x 10x 10x 13x 38x 36x 36x 36x 734x 734x 734x 734x 28x 28x 28x 28x 2x 2x 20x 28x 2x 2x 2x 2x 2x 2x 2x 2x 28x 708x 708x 36x 36x 36x 21x 21x 7x 7x 7x 7x 7x 7x 7x 7x 21x 36x 36x 36x 2670x 2670x 781x 781x 781x 781x 781x 781x 781x 781x 781x 36x 36x 36x 299x 299x 299x 299x 225x 225x 225x 299x 74x 74x 299x 213x 213x 299x 59x 59x 76x 15x 15x 12x 12x 36x 36x 36x 1923x 1875x 1875x 48x 48x 71x 1923x 1923x 19x 1923x 2x 2x 46x 46x 46x 46x 46x 46x 36x 36x 36x 262x 90x 90x 90x 90x 90x 90x 36x 36x 36x 216857x 216767x 216857x 42x 12x 12x 12x 12x 90x 48x 48x 48x 48x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x 36x  
'use strict';
 
const {
  ArrayIsArray,
  BigInt,
  Date,
  DateNow,
  DatePrototypeGetTime,
  ErrorCaptureStackTrace,
  FunctionPrototypeCall,
  Number,
  NumberIsFinite,
  NumberIsInteger,
  MathMin,
  MathRound,
  ObjectIs,
  ObjectPrototypeHasOwnProperty,
  ObjectSetPrototypeOf,
  ReflectApply,
  ReflectOwnKeys,
  RegExpPrototypeSymbolReplace,
  StringPrototypeEndsWith,
  StringPrototypeIncludes,
  Symbol,
  TypedArrayPrototypeIncludes,
} = primordials;
 
const { Buffer } = require('buffer');
const {
  codes: {
    ERR_FS_EISDIR,
    ERR_FS_INVALID_SYMLINK_TYPE,
    ERR_INCOMPATIBLE_OPTION_PAIR,
    ERR_INVALID_ARG_TYPE,
    ERR_INVALID_ARG_VALUE,
    ERR_OUT_OF_RANGE
  },
  hideStackFrames,
  uvException
} = require('internal/errors');
const {
  isArrayBufferView,
  isBigInt64Array,
  isDate,
  isUint8Array,
} = require('internal/util/types');
const {
  kEmptyObject,
  once,
} = require('internal/util');
const { toPathIfFileURL } = require('internal/url');
const {
  validateAbortSignal,
  validateBoolean,
  validateFunction,
  validateInt32,
  validateInteger,
  validateObject,
  validateUint32,
} = require('internal/validators');
const pathModule = require('path');
const kType = Symbol('type');
const kStats = Symbol('stats');
const assert = require('internal/assert');
 
const {
  fs: {
    F_OK = 0,
    W_OK = 0,
    R_OK = 0,
    X_OK = 0,
    COPYFILE_EXCL,
    COPYFILE_FICLONE,
    COPYFILE_FICLONE_FORCE,
    O_APPEND,
    O_CREAT,
    O_EXCL,
    O_RDONLY,
    O_RDWR,
    O_SYNC,
    O_TRUNC,
    O_WRONLY,
    S_IFBLK,
    S_IFCHR,
    S_IFDIR,
    S_IFIFO,
    S_IFLNK,
    S_IFMT,
    S_IFREG,
    S_IFSOCK,
    UV_FS_SYMLINK_DIR,
    UV_FS_SYMLINK_JUNCTION,
    UV_DIRENT_UNKNOWN,
    UV_DIRENT_FILE,
    UV_DIRENT_DIR,
    UV_DIRENT_LINK,
    UV_DIRENT_FIFO,
    UV_DIRENT_SOCKET,
    UV_DIRENT_CHAR,
    UV_DIRENT_BLOCK
  },
  os: {
    errno: {
      EISDIR
    }
  }
} = internalBinding('constants');
 
// The access modes can be any of F_OK, R_OK, W_OK or X_OK. Some might not be
// available on specific systems. They can be used in combination as well
// (F_OK | R_OK | W_OK | X_OK).
const kMinimumAccessMode = MathMin(F_OK, W_OK, R_OK, X_OK);
const kMaximumAccessMode = F_OK | W_OK | R_OK | X_OK;
 
const kDefaultCopyMode = 0;
// The copy modes can be any of COPYFILE_EXCL, COPYFILE_FICLONE or
// COPYFILE_FICLONE_FORCE. They can be used in combination as well
// (COPYFILE_EXCL | COPYFILE_FICLONE | COPYFILE_FICLONE_FORCE).
const kMinimumCopyMode = MathMin(
  kDefaultCopyMode,
  COPYFILE_EXCL,
  COPYFILE_FICLONE,
  COPYFILE_FICLONE_FORCE
);
const kMaximumCopyMode = COPYFILE_EXCL |
                         COPYFILE_FICLONE |
                         COPYFILE_FICLONE_FORCE;
 
// Most platforms don't allow reads or writes >= 2 GiB.
// See https://github.com/libuv/libuv/pull/1501.
const kIoMaxLength = 2 ** 31 - 1;
 
// Use 64kb in case the file type is not a regular file and thus do not know the
// actual file size. Increasing the value further results in more frequent over
// allocation for small files and consumes CPU time and memory that should be
// used else wise.
// Use up to 512kb per read otherwise to partition reading big files to prevent
// blocking other threads in case the available threads are all in use.
const kReadFileUnknownBufferLength = 64 * 1024;
const kReadFileBufferLength = 512 * 1024;
 
const kWriteFileMaxChunkSize = 512 * 1024;
 
const kMaxUserId = 2 ** 32 - 1;
 
const isWindows = process.platform === 'win32';
 
let fs;
function lazyLoadFs() {
  if (!fs) {
    fs = require('fs');
  }
  return fs;
}
 
function assertEncoding(encoding) {
  if (encoding && !Buffer.isEncoding(encoding)) {
    const reason = 'is invalid encoding';
    throw new ERR_INVALID_ARG_VALUE(encoding, 'encoding', reason);
  }
}
 
class Dirent {
  constructor(name, type) {
    this.name = name;
    this[kType] = type;
  }
 
  isDirectory() {
    return this[kType] === UV_DIRENT_DIR;
  }
 
  isFile() {
    return this[kType] === UV_DIRENT_FILE;
  }
 
  isBlockDevice() {
    return this[kType] === UV_DIRENT_BLOCK;
  }
 
  isCharacterDevice() {
    return this[kType] === UV_DIRENT_CHAR;
  }
 
  isSymbolicLink() {
    return this[kType] === UV_DIRENT_LINK;
  }
 
  isFIFO() {
    return this[kType] === UV_DIRENT_FIFO;
  }
 
  isSocket() {
    return this[kType] === UV_DIRENT_SOCKET;
  }
}
 
class DirentFromStats extends Dirent {
  constructor(name, stats) {
    super(name, null);
    this[kStats] = stats;
  }
}
 
for (const name of ReflectOwnKeys(Dirent.prototype)) {
  if (name === 'constructor') {
    continue;
  }
  DirentFromStats.prototype[name] = function() {
    return this[kStats][name]();
  };
}
 
function copyObject(source) {
  const target = {};
  for (const key in source)
    target[key] = source[key];
  return target;
}
 
const bufferSep = Buffer.from(pathModule.sep);
 
function join(path, name) {
  if ((typeof path === 'string' || isUint8Array(path)) &&
      name === undefined) {
    return path;
  }
 
  if (typeof path === 'string' && isUint8Array(name)) {
    const pathBuffer = Buffer.from(pathModule.join(path, pathModule.sep));
    return Buffer.concat([pathBuffer, name]);
  }
 
  if (typeof path === 'string' && typeof name === 'string') {
    return pathModule.join(path, name);
  }
 
  if (isUint8Array(path) && isUint8Array(name)) {
    return Buffer.concat([path, bufferSep, name]);
  }
 
  throw new ERR_INVALID_ARG_TYPE(
    'path', ['string', 'Buffer'], path);
}
 
function getDirents(path, { 0: names, 1: types }, callback) {
  let i;
  if (typeof callback === 'function') {
    const len = names.length;
    let toFinish = 0;
    callback = once(callback);
    for (i = 0; i < len; i++) {
      const type = types[i];
      if (type === UV_DIRENT_UNKNOWN) {
        const name = names[i];
        const idx = i;
        toFinish++;
        let filepath;
        try {
          filepath = join(path, name);
        } catch (err) {
          callback(err);
          return;
        }
        lazyLoadFs().lstat(filepath, (err, stats) => {
          if (err) {
            callback(err);
            return;
          }
          names[idx] = new DirentFromStats(name, stats);
          if (--toFinish === 0) {
            callback(null, names);
          }
        });
      } else {
        names[i] = new Dirent(names[i], types[i]);
      }
    }
    if (toFinish === 0) {
      callback(null, names);
    }
  } else {
    const len = names.length;
    for (i = 0; i < len; i++) {
      names[i] = getDirent(path, names[i], types[i]);
    }
    return names;
  }
}
 
function getDirent(path, name, type, callback) {
  if (typeof callback === 'function') {
    if (type === UV_DIRENT_UNKNOWN) {
      let filepath;
      try {
        filepath = join(path, name);
      } catch (err) {
        callback(err);
        return;
      }
      lazyLoadFs().lstat(filepath, (err, stats) => {
        if (err) {
          callback(err);
          return;
        }
        callback(null, new DirentFromStats(name, stats));
      });
    } else {
      callback(null, new Dirent(name, type));
    }
  } else if (type === UV_DIRENT_UNKNOWN) {
    const stats = lazyLoadFs().lstatSync(join(path, name));
    return new DirentFromStats(name, stats);
  } else {
    return new Dirent(name, type);
  }
}
 
function getOptions(options, defaultOptions = kEmptyObject) {
  if (options == null || typeof options === 'function') {
    return defaultOptions;
  }
 
  if (typeof options === 'string') {
    defaultOptions = { ...defaultOptions };
    defaultOptions.encoding = options;
    options = defaultOptions;
  } else if (typeof options !== 'object') {
    throw new ERR_INVALID_ARG_TYPE('options', ['string', 'Object'], options);
  }
 
  if (options.encoding !== 'buffer')
    assertEncoding(options.encoding);
 
  if (options.signal !== undefined) {
    validateAbortSignal(options.signal, 'options.signal');
  }
  return options;
}
 
/**
 * @param {InternalFSBinding.FSSyncContext} ctx
 */
function handleErrorFromBinding(ctx) {
  if (ctx.errno !== undefined) {  // libuv error numbers
    const err = uvException(ctx);
    ErrorCaptureStackTrace(err, handleErrorFromBinding);
    throw err;
  }
  if (ctx.error !== undefined) {  // Errors created in C++ land.
    // TODO(joyeecheung): currently, ctx.error are encoding errors
    // usually caused by memory problems. We need to figure out proper error
    // code(s) for this.
    ErrorCaptureStackTrace(ctx.error, handleErrorFromBinding);
    throw ctx.error;
  }
}
 
// Check if the path contains null types if it is a string nor Uint8Array,
// otherwise return silently.
const nullCheck = hideStackFrames((path, propName, throwError = true) => {
  const pathIsString = typeof path === 'string';
  const pathIsUint8Array = isUint8Array(path);
 
  // We can only perform meaningful checks on strings and Uint8Arrays.
  if ((!pathIsString && !pathIsUint8Array) ||
      (pathIsString && !StringPrototypeIncludes(path, '\u0000')) ||
      (pathIsUint8Array && !TypedArrayPrototypeIncludes(path, 0))) {
    return;
  }
 
  const err = new ERR_INVALID_ARG_VALUE(
    propName,
    path,
    'must be a string or Uint8Array without null bytes'
  );
  if (throwError) {
    throw err;
  }
  return err;
});
 
function preprocessSymlinkDestination(path, type, linkPath) {
  if (!isWindows) {
    // No preprocessing is needed on Unix.
    return path;
  }
  path = '' + path;
  if (type === 'junction') {
    // Junctions paths need to be absolute and \\?\-prefixed.
    // A relative target is relative to the link's parent directory.
    path = pathModule.resolve(linkPath, '..', path);
    return pathModule.toNamespacedPath(path);
  }
  if (pathModule.isAbsolute(path)) {
    // If the path is absolute, use the \\?\-prefix to enable long filenames
    return pathModule.toNamespacedPath(path);
  }
  // Windows symlinks don't tolerate forward slashes.
  return RegExpPrototypeSymbolReplace(/\//g, path, '\\');
}
 
// Constructor for file stats.
function StatsBase(dev, mode, nlink, uid, gid, rdev, blksize,
                   ino, size, blocks) {
  this.dev = dev;
  this.mode = mode;
  this.nlink = nlink;
  this.uid = uid;
  this.gid = gid;
  this.rdev = rdev;
  this.blksize = blksize;
  this.ino = ino;
  this.size = size;
  this.blocks = blocks;
}
 
StatsBase.prototype.isDirectory = function() {
  return this._checkModeProperty(S_IFDIR);
};
 
StatsBase.prototype.isFile = function() {
  return this._checkModeProperty(S_IFREG);
};
 
StatsBase.prototype.isBlockDevice = function() {
  return this._checkModeProperty(S_IFBLK);
};
 
StatsBase.prototype.isCharacterDevice = function() {
  return this._checkModeProperty(S_IFCHR);
};
 
StatsBase.prototype.isSymbolicLink = function() {
  return this._checkModeProperty(S_IFLNK);
};
 
StatsBase.prototype.isFIFO = function() {
  return this._checkModeProperty(S_IFIFO);
};
 
StatsBase.prototype.isSocket = function() {
  return this._checkModeProperty(S_IFSOCK);
};
 
const kNsPerMsBigInt = 10n ** 6n;
const kNsPerSecBigInt = 10n ** 9n;
const kMsPerSec = 10 ** 3;
const kNsPerMs = 10 ** 6;
function msFromTimeSpec(sec, nsec) {
  return sec * kMsPerSec + nsec / kNsPerMs;
}
 
function nsFromTimeSpecBigInt(sec, nsec) {
  return sec * kNsPerSecBigInt + nsec;
}
 
// The Date constructor performs Math.floor() on the absolute value
// of the timestamp: https://tc39.es/ecma262/#sec-timeclip
// Since there may be a precision loss when the timestamp is
// converted to a floating point number, we manually round
// the timestamp here before passing it to Date().
// Refs: https://github.com/nodejs/node/pull/12607
// Refs: https://github.com/nodejs/node/pull/43714
function dateFromMs(ms) {
  // Coercing to number, ms can be bigint
  return new Date(MathRound(Number(ms)));
}
 
function BigIntStats(dev, mode, nlink, uid, gid, rdev, blksize,
                     ino, size, blocks,
                     atimeNs, mtimeNs, ctimeNs, birthtimeNs) {
  ReflectApply(StatsBase, this, [dev, mode, nlink, uid, gid, rdev, blksize,
                                 ino, size, blocks]);
 
  this.atimeMs = atimeNs / kNsPerMsBigInt;
  this.mtimeMs = mtimeNs / kNsPerMsBigInt;
  this.ctimeMs = ctimeNs / kNsPerMsBigInt;
  this.birthtimeMs = birthtimeNs / kNsPerMsBigInt;
  this.atimeNs = atimeNs;
  this.mtimeNs = mtimeNs;
  this.ctimeNs = ctimeNs;
  this.birthtimeNs = birthtimeNs;
  this.atime = dateFromMs(this.atimeMs);
  this.mtime = dateFromMs(this.mtimeMs);
  this.ctime = dateFromMs(this.ctimeMs);
  this.birthtime = dateFromMs(this.birthtimeMs);
}
 
ObjectSetPrototypeOf(BigIntStats.prototype, StatsBase.prototype);
ObjectSetPrototypeOf(BigIntStats, StatsBase);
 
BigIntStats.prototype._checkModeProperty = function(property) {
  if (isWindows && (property === S_IFIFO || property === S_IFBLK ||
    property === S_IFSOCK)) {
    return false;  // Some types are not available on Windows
  }
  return (this.mode & BigInt(S_IFMT)) === BigInt(property);
};
 
function Stats(dev, mode, nlink, uid, gid, rdev, blksize,
               ino, size, blocks,
               atimeMs, mtimeMs, ctimeMs, birthtimeMs) {
  FunctionPrototypeCall(StatsBase, this, dev, mode, nlink, uid, gid, rdev,
                        blksize, ino, size, blocks);
  this.atimeMs = atimeMs;
  this.mtimeMs = mtimeMs;
  this.ctimeMs = ctimeMs;
  this.birthtimeMs = birthtimeMs;
  this.atime = dateFromMs(atimeMs);
  this.mtime = dateFromMs(mtimeMs);
  this.ctime = dateFromMs(ctimeMs);
  this.birthtime = dateFromMs(birthtimeMs);
}
 
ObjectSetPrototypeOf(Stats.prototype, StatsBase.prototype);
ObjectSetPrototypeOf(Stats, StatsBase);
 
// HACK: Workaround for https://github.com/standard-things/esm/issues/821.
// TODO(ronag): Remove this as soon as `esm` publishes a fixed version.
Stats.prototype.isFile = StatsBase.prototype.isFile;
 
Stats.prototype._checkModeProperty = function(property) {
  if (isWindows && (property === S_IFIFO || property === S_IFBLK ||
    property === S_IFSOCK)) {
    return false;  // Some types are not available on Windows
  }
  return (this.mode & S_IFMT) === property;
};
 
/**
 * @param {Float64Array | BigInt64Array} stats
 * @param {number} offset
 * @returns {BigIntStats | Stats}
 */
function getStatsFromBinding(stats, offset = 0) {
  if (isBigInt64Array(stats)) {
    return new BigIntStats(
      stats[0 + offset], stats[1 + offset], stats[2 + offset],
      stats[3 + offset], stats[4 + offset], stats[5 + offset],
      stats[6 + offset], stats[7 + offset], stats[8 + offset],
      stats[9 + offset],
      nsFromTimeSpecBigInt(stats[10 + offset], stats[11 + offset]),
      nsFromTimeSpecBigInt(stats[12 + offset], stats[13 + offset]),
      nsFromTimeSpecBigInt(stats[14 + offset], stats[15 + offset]),
      nsFromTimeSpecBigInt(stats[16 + offset], stats[17 + offset])
    );
  }
  return new Stats(
    stats[0 + offset], stats[1 + offset], stats[2 + offset],
    stats[3 + offset], stats[4 + offset], stats[5 + offset],
    stats[6 + offset], stats[7 + offset], stats[8 + offset],
    stats[9 + offset],
    msFromTimeSpec(stats[10 + offset], stats[11 + offset]),
    msFromTimeSpec(stats[12 + offset], stats[13 + offset]),
    msFromTimeSpec(stats[14 + offset], stats[15 + offset]),
    msFromTimeSpec(stats[16 + offset], stats[17 + offset])
  );
}
 
function stringToFlags(flags, name = 'flags') {
  if (typeof flags === 'number') {
    validateInt32(flags, name);
    return flags;
  }
 
  if (flags == null) {
    return O_RDONLY;
  }
 
  switch (flags) {
    case 'r' : return O_RDONLY;
    case 'rs' : // Fall through.
    case 'sr' : return O_RDONLY | O_SYNC;
    case 'r+' : return O_RDWR;
    case 'rs+' : // Fall through.
    case 'sr+' : return O_RDWR | O_SYNC;
 
    case 'w' : return O_TRUNC | O_CREAT | O_WRONLY;
    case 'wx' : // Fall through.
    case 'xw' : return O_TRUNC | O_CREAT | O_WRONLY | O_EXCL;
 
    case 'w+' : return O_TRUNC | O_CREAT | O_RDWR;
    case 'wx+': // Fall through.
    case 'xw+': return O_TRUNC | O_CREAT | O_RDWR | O_EXCL;
 
    case 'a' : return O_APPEND | O_CREAT | O_WRONLY;
    case 'ax' : // Fall through.
    case 'xa' : return O_APPEND | O_CREAT | O_WRONLY | O_EXCL;
    case 'as' : // Fall through.
    case 'sa' : return O_APPEND | O_CREAT | O_WRONLY | O_SYNC;
 
    case 'a+' : return O_APPEND | O_CREAT | O_RDWR;
    case 'ax+': // Fall through.
    case 'xa+': return O_APPEND | O_CREAT | O_RDWR | O_EXCL;
    case 'as+': // Fall through.
    case 'sa+': return O_APPEND | O_CREAT | O_RDWR | O_SYNC;
  }
 
  throw new ERR_INVALID_ARG_VALUE('flags', flags);
}
 
const stringToSymlinkType = hideStackFrames((type) => {
  let flags = 0;
  if (typeof type === 'string') {
    switch (type) {
      case 'dir':
        flags |= UV_FS_SYMLINK_DIR;
        break;
      case 'junction':
        flags |= UV_FS_SYMLINK_JUNCTION;
        break;
      case 'file':
        break;
      default:
        throw new ERR_FS_INVALID_SYMLINK_TYPE(type);
    }
  }
  return flags;
});
 
// converts Date or number to a fractional UNIX timestamp
function toUnixTimestamp(time, name = 'time') {
  // eslint-disable-next-line eqeqeq
  if (typeof time === 'string' && +time == time) {
    return +time;
  }
  if (NumberIsFinite(time)) {
    if (time < 0) {
      return DateNow() / 1000;
    }
    return time;
  }
  if (isDate(time)) {
    // Convert to 123.456 UNIX timestamp
    return DatePrototypeGetTime(time) / 1000;
  }
  throw new ERR_INVALID_ARG_TYPE(name, ['Date', 'Time in seconds'], time);
}
 
const validateOffsetLengthRead = hideStackFrames(
  (offset, length, bufferLength) => {
    if (offset < 0) {
      throw new ERR_OUT_OF_RANGE('offset', '>= 0', offset);
    }
    if (length < 0) {
      throw new ERR_OUT_OF_RANGE('length', '>= 0', length);
    }
    if (offset + length > bufferLength) {
      throw new ERR_OUT_OF_RANGE('length',
                                 `<= ${bufferLength - offset}`, length);
    }
  }
);
 
const validateOffsetLengthWrite = hideStackFrames(
  (offset, length, byteLength) => {
    if (offset > byteLength) {
      throw new ERR_OUT_OF_RANGE('offset', `<= ${byteLength}`, offset);
    }
 
    if (length > byteLength - offset) {
      throw new ERR_OUT_OF_RANGE('length', `<= ${byteLength - offset}`, length);
    }
 
    if (length < 0) {
      throw new ERR_OUT_OF_RANGE('length', '>= 0', length);
    }
 
    validateInt32(length, 'length', 0);
  }
);
 
const validatePath = hideStackFrames((path, propName = 'path') => {
  if (typeof path !== 'string' && !isUint8Array(path)) {
    throw new ERR_INVALID_ARG_TYPE(propName, ['string', 'Buffer', 'URL'], path);
  }
 
  const err = nullCheck(path, propName, false);
 
  if (err !== undefined) {
    throw err;
  }
});
 
const getValidatedPath = hideStackFrames((fileURLOrPath, propName = 'path') => {
  const path = toPathIfFileURL(fileURLOrPath);
  validatePath(path, propName);
  return path;
});
 
const getValidatedFd = hideStackFrames((fd, propName = 'fd') => {
  if (ObjectIs(fd, -0)) {
    return 0;
  }
 
  validateInt32(fd, propName, 0);
 
  return fd;
});
 
const validateBufferArray = hideStackFrames((buffers, propName = 'buffers') => {
  if (!ArrayIsArray(buffers))
    throw new ERR_INVALID_ARG_TYPE(propName, 'ArrayBufferView[]', buffers);
 
  for (let i = 0; i < buffers.length; i++) {
    if (!isArrayBufferView(buffers[i]))
      throw new ERR_INVALID_ARG_TYPE(propName, 'ArrayBufferView[]', buffers);
  }
 
  return buffers;
});
 
let nonPortableTemplateWarn = true;
 
function warnOnNonPortableTemplate(template) {
  // Template strings passed to the mkdtemp() family of functions should not
  // end with 'X' because they are handled inconsistently across platforms.
  if (nonPortableTemplateWarn && StringPrototypeEndsWith(template, 'X')) {
    process.emitWarning('mkdtemp() templates ending with X are not portable. ' +
                        'For details see: https://nodejs.org/api/fs.html');
    nonPortableTemplateWarn = false;
  }
}
 
const defaultCpOptions = {
  dereference: false,
  errorOnExist: false,
  filter: undefined,
  force: true,
  preserveTimestamps: false,
  recursive: false,
  verbatimSymlinks: false,
};
 
const defaultRmOptions = {
  recursive: false,
  force: false,
  retryDelay: 100,
  maxRetries: 0
};
 
const defaultRmdirOptions = {
  retryDelay: 100,
  maxRetries: 0,
  recursive: false,
};
 
const validateCpOptions = hideStackFrames((options) => {
  if (options === undefined)
    return { ...defaultCpOptions };
  validateObject(options, 'options');
  options = { ...defaultCpOptions, ...options };
  validateBoolean(options.dereference, 'options.dereference');
  validateBoolean(options.errorOnExist, 'options.errorOnExist');
  validateBoolean(options.force, 'options.force');
  validateBoolean(options.preserveTimestamps, 'options.preserveTimestamps');
  validateBoolean(options.recursive, 'options.recursive');
  validateBoolean(options.verbatimSymlinks, 'options.verbatimSymlinks');
  if (options.dereference === true && options.verbatimSymlinks === true) {
    throw new ERR_INCOMPATIBLE_OPTION_PAIR('dereference', 'verbatimSymlinks');
  }
  if (options.filter !== undefined) {
    validateFunction(options.filter, 'options.filter');
  }
  return options;
});
 
const validateRmOptions = hideStackFrames((path, options, expectDir, cb) => {
  options = validateRmdirOptions(options, defaultRmOptions);
  validateBoolean(options.force, 'options.force');
 
  lazyLoadFs().stat(path, (err, stats) => {
    if (err) {
      if (options.force && err.code === 'ENOENT') {
        return cb(null, options);
      }
      return cb(err, options);
    }
 
    if (expectDir && !stats.isDirectory()) {
      return cb(false);
    }
 
    if (stats.isDirectory() && !options.recursive) {
      return cb(new ERR_FS_EISDIR({
        code: 'EISDIR',
        message: 'is a directory',
        path,
        syscall: 'rm',
        errno: EISDIR
      }));
    }
    return cb(null, options);
  });
});
 
const validateRmOptionsSync = hideStackFrames((path, options, expectDir) => {
  options = validateRmdirOptions(options, defaultRmOptions);
  validateBoolean(options.force, 'options.force');
 
  if (!options.force || expectDir || !options.recursive) {
    const isDirectory = lazyLoadFs()
      .statSync(path, { throwIfNoEntry: !options.force })?.isDirectory();
 
    if (expectDir && !isDirectory) {
      return false;
    }
 
    if (isDirectory && !options.recursive) {
      throw new ERR_FS_EISDIR({
        code: 'EISDIR',
        message: 'is a directory',
        path,
        syscall: 'rm',
        errno: EISDIR
      });
    }
  }
 
  return options;
});
 
let recursiveRmdirWarned = process.noDeprecation;
function emitRecursiveRmdirWarning() {
  if (!recursiveRmdirWarned) {
    process.emitWarning(
      'In future versions of Node.js, fs.rmdir(path, { recursive: true }) ' +
      'will be removed. Use fs.rm(path, { recursive: true }) instead',
      'DeprecationWarning',
      'DEP0147'
    );
    recursiveRmdirWarned = true;
  }
}
 
const validateRmdirOptions = hideStackFrames(
  (options, defaults = defaultRmdirOptions) => {
    if (options === undefined)
      return defaults;
    validateObject(options, 'options');
 
    options = { ...defaults, ...options };
 
    validateBoolean(options.recursive, 'options.recursive');
    validateInt32(options.retryDelay, 'options.retryDelay', 0);
    validateUint32(options.maxRetries, 'options.maxRetries');
 
    return options;
  });
 
const getValidMode = hideStackFrames((mode, type) => {
  let min = kMinimumAccessMode;
  let max = kMaximumAccessMode;
  let def = F_OK;
  if (type === 'copyFile') {
    min = kMinimumCopyMode;
    max = kMaximumCopyMode;
    def = mode || kDefaultCopyMode;
  } else {
    assert(type === 'access');
  }
  if (mode == null) {
    return def;
  }
  if (NumberIsInteger(mode) && mode >= min && mode <= max) {
    return mode;
  }
  if (typeof mode !== 'number') {
    throw new ERR_INVALID_ARG_TYPE('mode', 'integer', mode);
  }
  throw new ERR_OUT_OF_RANGE(
    'mode', `an integer >= ${min} && <= ${max}`, mode);
});
 
const validateStringAfterArrayBufferView = hideStackFrames((buffer, name) => {
  if (typeof buffer === 'string') {
    return;
  }
 
  if (
    typeof buffer === 'object' &&
    buffer !== null &&
    typeof buffer.toString === 'function' &&
    ObjectPrototypeHasOwnProperty(buffer, 'toString')
  ) {
    return;
  }
 
  throw new ERR_INVALID_ARG_TYPE(
    name,
    ['string', 'Buffer', 'TypedArray', 'DataView'],
    buffer
  );
});
 
const validatePrimitiveStringAfterArrayBufferView = hideStackFrames((buffer, name) => {
  if (typeof buffer !== 'string') {
    throw new ERR_INVALID_ARG_TYPE(
      name,
      ['string', 'Buffer', 'TypedArray', 'DataView'],
      buffer
    );
  }
});
 
const validatePosition = hideStackFrames((position, name) => {
  if (typeof position === 'number') {
    validateInteger(position, 'position');
  } else if (typeof position === 'bigint') {
    if (!(position >= -(2n ** 63n) && position <= 2n ** 63n - 1n)) {
      throw new ERR_OUT_OF_RANGE('position',
                                 `>= ${-(2n ** 63n)} && <= ${2n ** 63n - 1n}`,
                                 position);
    }
  } else {
    throw new ERR_INVALID_ARG_TYPE('position',
                                   ['integer', 'bigint'],
                                   position);
  }
});
 
module.exports = {
  constants: {
    kIoMaxLength,
    kMaxUserId,
    kReadFileBufferLength,
    kReadFileUnknownBufferLength,
    kWriteFileMaxChunkSize,
  },
  assertEncoding,
  BigIntStats,  // for testing
  copyObject,
  Dirent,
  emitRecursiveRmdirWarning,
  getDirent,
  getDirents,
  getOptions,
  getValidatedFd,
  getValidatedPath,
  getValidMode,
  handleErrorFromBinding,
  nullCheck,
  preprocessSymlinkDestination,
  realpathCacheKey: Symbol('realpathCacheKey'),
  getStatsFromBinding,
  stringToFlags,
  stringToSymlinkType,
  Stats,
  toUnixTimestamp,
  validateBufferArray,
  validateCpOptions,
  validateOffsetLengthRead,
  validateOffsetLengthWrite,
  validatePath,
  validatePosition,
  validateRmOptions,
  validateRmOptionsSync,
  validateRmdirOptions,
  validateStringAfterArrayBufferView,
  validatePrimitiveStringAfterArrayBufferView,
  warnOnNonPortableTemplate
};