UNPKG

dotnet-2.0.0

Version:

Platform agnostic installation of .NET Core runtime 2.0.0

797 lines (768 loc) 25.5 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const patch_moduleloader_1 = inline_patchmoduleloader(); const static_filesystem_1 = inline_staticfilesystem(); const common_1 = inline_common(); const fs_1 = require("fs"); const child_process = require("child_process"); const Module = require("module"); if (require.main === module) { const startpath = fs_1.realpathSync(module.filename); for (let i = 0; i < process.argv.length; i++) { if (fs_1.realpathSync(process.argv[i]) === startpath) { process.argv.splice(i, 1); while (i < process.argv.length && process.argv[i].startsWith("--load-module=")) { const staticModule = process.argv[i].split("=")[1]; process.argv.splice(i, 1); load(staticModule); } Module._load(process.argv[1], null, true); process._tickCallback(); break; } } } const possibilities = [ "node", "node.exe", process.execPath, process.argv[0] ]; function isNode(path) { return possibilities.indexOf(path) > -1 ? true : false; } function indexAfterStartsWith(command, text) { return command.startsWith(text) ? text.length : -1; } function startsWithNode(command) { if (command.charAt(0) == '"') { for (const each of possibilities) { const val = indexAfterStartsWith(command, `"${each}" `); if (val > -1) { return val; } } } else { for (const each of possibilities) { const val = indexAfterStartsWith(command, `${each} `); if (val > -1) { return val; } } } return -1; } function getInsertedArgs(loadedFileSystems) { return common_1.select(loadedFileSystems, (p, c) => `--load-module=${c}`); } function getInsertedArgString(loadedFileSystems) { return `${getInsertedArgs(loadedFileSystems).map(a => `"${a}"`).join(" ")}`; } function padStart(str, targetLength, padString = " ") { targetLength = targetLength >> 0; padString = String(padString || " "); if (str.length > targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); } return padString.slice(0, targetLength) + String(str); } } function padEnd(str, targetLength, padString = " ") { targetLength = targetLength >> 0; padString = String(padString || " "); if (str.length > targetLength) { return String(str); } else { targetLength = targetLength - str.length; if (targetLength > padString.length) { padString += padString.repeat(targetLength / padString.length); } return String(str) + padString.slice(0, targetLength); } } function list(staticModule) { const svs = new static_filesystem_1.StaticFilesystem(true); svs.load(staticModule); const dir = new Array(); const files = {}; for (const each of svs.entries) { const st = svs.statSync(each); if (!st.isFile()) { dir.push(`${padStart("<dir>", 12)} ${each}`); } else { files[each] = `${padStart(`${st.size}`, 12)} ${each}`; } } for (const each of dir.sort()) { console.log(each); } for (const each of Object.keys(files).sort()) { console.log(files[each]); } svs.shutdown(); } exports.list = list; function load(staticModule) { if (!require.undo) { const svs = new static_filesystem_1.StaticFilesystem(true); require.undo = patch_moduleloader_1.patchModuleLoader(svs); require.staticfilesystem = svs; const process_exit = process.exit; process.exit = (n => { svs.shutdown(); require.undo(); return process_exit(n); }); const fork = child_process.fork; const spawn = child_process.spawn; const exec = child_process.exec; const spawnSync = child_process.spawnSync; const execSync = child_process.execSync; child_process.fork = ((modulePath, args, options) => { if (args) { return fork(__filename, [ ...getInsertedArgs(svs.loadedFileSystems), modulePath, ...Array.isArray(args) ? args : [ args ] ], options); } else { return fork(__filename, args, options); } }); child_process.spawn = ((command, args, options) => { if (args && (Array.isArray(args) || typeof args !== "object") && isNode(command)) { return spawn(command, [ __filename, ...getInsertedArgs(svs.loadedFileSystems), ...Array.isArray(args) ? args : [ args ] ], options); } return spawn(command, args, options); }); child_process.spawnSync = ((command, args, options) => { if (args && (Array.isArray(args) || typeof args !== "object") && isNode(command)) { return spawnSync(command, [ __filename, ...getInsertedArgs(svs.loadedFileSystems), ...Array.isArray(args) ? args : [ args ] ], options); } return spawnSync(command, args, options); }); child_process.exec = ((command, options, callback) => { const pos = startsWithNode(command); if (pos > -1) { return exec(`${command.substring(0, pos)} "${__filename}" ${getInsertedArgString(svs.loadedFileSystems)} ${command.substring(pos)}`, options, callback); } return exec(command, options, callback); }); child_process.execSync = ((command, options) => { const pos = startsWithNode(command); if (pos > -1) { return execSync(`${command.substring(0, pos)} "${__filename}" ${getInsertedArgString(svs.loadedFileSystems)} ${command.substring(pos)}`, options); } return execSync(command, options); }); } require.staticfilesystem.load(staticModule); } exports.load = load; function unload(staticModule) { if (require.undo) { const svs = require.staticfilesystem; svs.unload(staticModule); } } exports.unload = unload; function inline_staticfilesystem() { var exports = {}; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const path_1 = require("path"); const os_1 = require("os"); const filesystem = require("fs"); const fs = Object.assign({}, filesystem); const common_1 = inline_common(); class StaticVolumeFile { constructor(sourcePath) { this.sourcePath = sourcePath; this.intBuffer = Buffer.alloc(common_1.INTSIZE); this.buf = Buffer.alloc(1024 * 16); this.index = {}; this.statData = Object.assign({}, fs.statSync(sourcePath), { isDirectory: () => false, isSymbolicLink: () => false, isBlockDevice: () => false, isCharacterDevice: () => false, isFile: () => false, isFIFO: () => false, isSocket: () => false, size: 0 }); this.fd = fs.openSync(sourcePath, "r"); let dataOffset = this.readInt(); let hashSize = this.readInt(); if (hashSize > this.buf.length) { this.buf = Buffer.alloc(hashSize); } this.readBuffer(this.buf, hashSize); this.hash = this.buf.toString("utf8", 0, hashSize); do { const nameSz = this.readInt(); if (nameSz == 0) { break; } const dataSz = this.readInt(); if (nameSz > this.buf.length) { this.buf = Buffer.alloc(nameSz); } this.readBuffer(this.buf, nameSz); const name = this.buf.toString("utf8", 0, nameSz); this.index[name] = Object.assign({}, this.statData, { ino: dataOffset, size: dataSz, blocks: 1, blksize: dataSz, isFile: () => true }); this.addParentFolders(name); dataOffset += dataSz; } while (true); } readBuffer(buffer, length) { return fs.readSync(this.fd, buffer, 0, length || buffer.length, null); } readInt() { fs.readSync(this.fd, this.intBuffer, 0, common_1.INTSIZE, null); return this.intBuffer.readIntBE(0, 6); } shutdown() { fs.closeSync(this.fd); this.index = {}; } addParentFolders(name) { const parent = path_1.dirname(name); if (parent && !this.index[parent]) { this.index[parent] = Object.assign({}, this.statData, { isDirectory: () => true }); return this.addParentFolders(parent); } } readFile(filepath, options) { const item = this.index[filepath]; if (item && item.isFile()) { const encoding = options ? typeof options === "string" ? options : typeof options === "object" ? options.encoding || "utf8" : "utf8" : "utf8"; if (this.buf.length < item.size) { this.buf = Buffer.alloc(item.size); } fs.readSync(this.fd, this.buf, 0, item.size, item.ino); return this.buf.toString(encoding, 0, item.size); } return undefined; } } exports.StaticVolumeFile = StaticVolumeFile; class StaticFilesystem { constructor(fallbackToDisk = false) { this.fallbackToDisk = fallbackToDisk; this.fileSystems = []; } NewError(code, method, filepath) { switch (code) { case os_1.constants.errno.ENOENT: return Object.assign({}, new Error(`ENOENT: no such file or directory, ${method} '${filepath}'`), { code: "ENOENT", path: filepath, errno: os_1.constants.errno.ENOENT }); case os_1.constants.errno.EISDIR: return Object.assign({}, new Error(`EISDIR: illegal operation on a directory, ${method} '${filepath}'`), { code: "EISDIR", path: filepath, errno: os_1.constants.errno.EISDIR }); } return Object.assign({}, new Error(`UNKNOWN: Error, ${method} '${filepath}'`), { code: "UNKNOWN", path: filepath, errno: -1e4 }); } shutdown() { for (const fsystem of this.fileSystems) { fsystem.shutdown(); } } get hashes() { const result = new Array(); for (const fsystem of this.fileSystems) { result.push(fsystem.hash); } return result; } load(sourcePath) { sourcePath = path_1.resolve(sourcePath); for (let i = 0; i < this.fileSystems.length; i++) { if (this.fileSystems[i].sourcePath === sourcePath) { return this; } } this.fileSystems.push(new StaticVolumeFile(sourcePath)); return this; } get loadedFileSystems() { const result = new Array(); for (const fsystem of this.fileSystems) { result.push(fsystem.sourcePath); } return result; } unload(sourcePath) { sourcePath = path_1.resolve(sourcePath); for (let i = 0; i < this.fileSystems.length; i++) { if (this.fileSystems[i].sourcePath === sourcePath) { this.fileSystems[i].shutdown(); this.fileSystems.splice(i, 1); } } return this; } get entries() { const result = new Array(); for (const fsystem of this.fileSystems) { result.push(...Object.keys(fsystem.index)); } return result; } readFileSync(filepath, options) { const targetPath = common_1.unixifyPath(filepath); for (const fsystem of this.fileSystems) { const result = fsystem.readFile(targetPath, options); if (result != undefined) { return result; } } if (this.fallbackToDisk) { return fs.readFileSync(filepath, options); } throw this.NewError(os_1.constants.errno.ENOENT, "readFileSync", filepath); } realpathSync(filepath) { const targetPath = common_1.unixifyPath(filepath); for (const fsystem of this.fileSystems) { if (fsystem.index[targetPath]) { return targetPath; } } return fs.realpathSync(filepath); } statSync(filepath) { const targetPath = common_1.unixifyPath(filepath); for (const fsystem of this.fileSystems) { const result = fsystem.index[targetPath]; if (result) { return result; } } if (this.fallbackToDisk) { return fs.statSync(filepath); } throw this.NewError(os_1.constants.errno.ENOENT, "statSync", filepath); } } exports.StaticFilesystem = StaticFilesystem; return exports; } function inline_common() { var exports = {}; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const crypto_1 = require("crypto"); exports.isWindows = process.platform === "win32"; const path_1 = require("path"); const child_process_1 = require("child_process"); const filesystem = require("fs"); const fs = Object.assign({}, filesystem); function readdir(path) { return new Promise((r, j) => fs.readdir(path, (err, files) => err ? j(err) : r(files))); } exports.readdir = readdir; function stat(path) { return new Promise((r, j) => fs.stat(path, (err, files) => err ? j(err) : r(files))); } exports.stat = stat; function lstat(path) { return new Promise((r, j) => fs.lstat(path, (err, files) => err ? j(err) : r(files))); } exports.lstat = lstat; function open(path, flags, mode) { return new Promise((r, j) => fs.open(path, flags, mode, (err, descrpitor) => err ? j(err) : r(descrpitor))); } exports.open = open; function close(fd) { return new Promise((r, j) => fs.close(fd, err => err ? j(err) : r())); } exports.close = close; function write(fd, buffer, offset, length, position) { return new Promise((r, j) => fs.write(fd, buffer, offset || 0, length || buffer.length, position || undefined, (err, written, buf) => err ? j(err) : r(written))); } exports.write = write; function read(fd, buffer, offset, length, position) { return new Promise((r, j) => fs.read(fd, buffer, offset, length, position || null, (err, bytes, buffer) => err ? j(err) : r(bytes))); } exports.read = read; function readFile(path, options) { return new Promise((r, j) => fs.readFile(path, options, (err, data) => err ? j(err) : r(data))); } exports.readFile = readFile; function execute(command, options) { return new Promise((r, j) => { child_process_1.exec(command, options, (error, stdout, stderr) => { r({ stdout: stdout, stderr: stderr, error: error, code: error ? error.code : 0 }); }); }); } exports.execute = execute; function fs_mkdir(path) { return new Promise((r, j) => fs.mkdir(path, err => err ? j(err) : r())); } function fs_unlink(path) { return new Promise((r, j) => fs.unlink(path, err => err ? j(err) : r())); } function fs_rmdir(path) { return new Promise((r, j) => fs.rmdir(path, err => err ? j(err) : r())); } function rename(oldPath, newPath) { return new Promise((r, j) => fs.rename(oldPath, newPath, err => err ? j(err) : r())); } exports.rename = rename; function writeFile(filename, content) { return new Promise((r, j) => fs.writeFile(filename, content, err => err ? j(err) : r())); } exports.writeFile = writeFile; async function copyFile(source, target) { await mkdir(path_1.dirname(target)); return await new Promise((resolve, reject) => { var rd = fs.createReadStream(source); rd.on("error", rejectCleanup); var wr = fs.createWriteStream(target); wr.on("error", rejectCleanup); function rejectCleanup(err) { rd.destroy(); wr.end(); reject(err); } wr.on("finish", () => { rd.close(); wr.close(); resolve(); }); rd.pipe(wr); }); } exports.copyFile = copyFile; exports.exists = (path => new Promise((r, j) => fs.stat(path, (err, stats) => err ? r(false) : r(true)))); async function isDirectory(dirPath) { try { if (await exports.exists(dirPath)) { return (await lstat(dirPath)).isDirectory(); } } catch (e) {} return false; } exports.isDirectory = isDirectory; async function isFile(filePath) { try { if (await exports.exists(filePath)) { return !(await lstat(filePath)).isDirectory(); } } catch (e) {} return false; } exports.isFile = isFile; async function rmdir(dirPath) { if (!await exports.exists(dirPath)) { return; } if (!await isDirectory(dirPath)) { throw new Error(dirPath); } if (process.cwd() === path_1.normalize(dirPath)) { process.chdir(`${dirPath}/..`); } const files = await readdir(dirPath); if (files.length) { const awaiter = new Array(); try { for (const file of files) { try { const p = path_1.join(dirPath, file); if (await isDirectory(p)) { awaiter.push(rmdir(p)); } else { awaiter.push(fs_unlink(p).catch(() => {})); } } catch (e) {} } } finally { await Promise.all(awaiter); } } try { await fs_rmdir(dirPath); } catch (e) { if (await isDirectory(dirPath)) { throw new Error(`UnableToRemoveException ${dirPath}`); } } } exports.rmdir = rmdir; async function rmFile(filePath) { if (!exports.exists(filePath)) { return; } if (await isDirectory(filePath)) { throw new Error(`PathIsNotFileException : ${filePath}`); } try { await fs_unlink(filePath); } catch (e) { if (await exports.exists(filePath)) { throw new Error(`UnableToRemoveException : filePath`); } } } exports.rmFile = rmFile; async function mkdir(dirPath) { if (!await isDirectory(dirPath)) { const p = path_1.normalize(dirPath + "/"); const parent = path_1.dirname(dirPath); if (!await isDirectory(parent)) { if (p != parent) { await mkdir(parent); } } try { await fs_mkdir(p); } catch (e) { if (!await isDirectory(p)) { throw new Error(e); } } } } exports.mkdir = mkdir; exports.INTSIZE = 6; function _unixifyPath(filepath) { if (filepath && typeof filepath === "string") { return filepath.replace(/^\\\\\?\\(.):\\/, "$1:\\").replace(/[\\\/]+/g, "/").replace(/^([a-zA-Z]+:|\.\/)/, "").replace(/(.+?)\/$/, "$1"); } return filepath; } function _isWindowsPath(filepath) { if (filepath && filepath.length >= 3) { if (filepath.charCodeAt(0) === 92 && filepath.charCodeAt(1) === 92) { return true; } if (filepath.charCodeAt(1) == 58 && filepath.charCodeAt(2) === 92) { var code = filepath.charCodeAt(0); return code >= 65 && code <= 90 || code >= 97 && code <= 122; } } return false; } exports.unixifyPath = exports.isWindows ? _unixifyPath : p => p; exports.isWindowsPath = exports.isWindows ? _isWindowsPath : p => p; function calculateHash(content) { return crypto_1.createHash("sha256").update(JSON.stringify(content)).digest("base64"); } exports.calculateHash = calculateHash; function select(array, callbackfn) { return array.reduce((p, c, i, a) => { p.push(callbackfn(p, c, i, a)); return p; }, new Array()); } exports.select = select; return exports; } function inline_patchmoduleloader() { var exports = {}; "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const fs_1 = require("fs"); const common_1 = inline_common(); const path_1 = require("path"); const makeLong = require("path")._makeLong || path_1.resolve; function stripBOM(content) { return content && content.charCodeAt(0) === 65279 ? content.slice(1) : content; } function unixifyVolume(volume) { return common_1.isWindows ? { readFileSync: (path, options) => volume.readFileSync(common_1.unixifyPath(path), options), realpathSync: (path, options) => volume.realpathSync(common_1.unixifyPath(path)), statSync: path => volume.statSync(common_1.unixifyPath(path)) } : volume; } function patchModuleLoader(volume, enablePathNormalization = false, Module = require("module")) { const backup = Object.assign({}, Module); const preserveSymlinks = false; const statcache = {}; const packageMainCache = {}; if (enablePathNormalization) { volume = unixifyVolume(volume); } function internalModuleReadFile(path) { try { return volume.readFileSync(path, "utf8"); } catch (_a) {} return undefined; } function internalModuleStat(filename) { try { return volume.statSync(filename).isDirectory() ? 1 : 0; } catch (_a) {} return -2; } function stat(filename) { filename = makeLong(filename); const result = statcache[filename]; return result !== undefined ? result : statcache[filename] = internalModuleStat(filename); } function readPackage(requestPath) { const entry = packageMainCache[requestPath]; if (entry) { return entry; } const jsonPath = path_1.resolve(requestPath, "package.json"); const json = internalModuleReadFile(makeLong(jsonPath)); if (json === undefined) { return false; } let pkg; try { pkg = packageMainCache[requestPath] = JSON.parse(json).main; } catch (e) { e.path = jsonPath; e.message = "Error parsing " + jsonPath + ": " + e.message; throw e; } return pkg; } function tryFile(requestPath, isMain) { if (preserveSymlinks && !isMain) { return stat(requestPath) === 0 ? path_1.resolve(requestPath) : undefined; } return stat(requestPath) === 0 ? volume.realpathSync(requestPath) : undefined; } function tryExtensions(p, exts, isMain) { for (let i = 0; i < exts.length; i++) { const filename = tryFile(p + exts[i], isMain); if (filename) { return filename; } } return undefined; } function tryPackage(requestPath, exts, isMain) { let pkg = readPackage(requestPath); if (pkg) { let filename = path_1.resolve(requestPath, pkg); return tryFile(filename, isMain) || tryExtensions(filename, exts, isMain) || tryExtensions(path_1.resolve(filename, "index"), exts, isMain); } return undefined; } Module._extensions[".js"] = ((module, filename) => { if (stat(filename) == 0) { module._compile(stripBOM(volume.readFileSync(filename, "utf8")), filename); } else if (Module._fallback) { module._compile(stripBOM(fs_1.readFileSync(filename, "utf8")), filename); } }); Module._extensions[".json"] = ((module, filename) => { if (stat(filename) == 0) { try { module.exports = JSON.parse(stripBOM(volume.readFileSync(filename, "utf8"))); } catch (err) { throw Object.assign({}, err, { message: filename + ": " + err.message }); } } else if (Module._fallback) { try { module.exports = JSON.parse(stripBOM(fs_1.readFileSync(filename, "utf8"))); } catch (err) { throw Object.assign({}, err, { message: filename + ": " + err.message }); } } }); Module._findPath = ((request, paths, isMain) => { const result = Module._alternateFindPath(request, paths, isMain); return !result && Module._fallback ? Module._originalFindPath(request, paths, isMain) : result; }); Module._originalFindPath = Module._findPath; Module._alternateFindPath = ((request, paths, isMain) => { if (!request) { return false; } if (path_1.isAbsolute(request)) { paths = [ "" ]; } else if (!paths || paths.length === 0) { return false; } const cacheKey = request + "\0" + (paths.length === 1 ? paths[0] : paths.join("\0")); const entry = Module._pathCache[cacheKey]; if (entry) { return entry; } const trailingSlash = request.charCodeAt(request.length - 1) === 47; for (const curPath of paths) { if (curPath && stat(curPath) < 1) { continue; } let basePath = path_1.resolve(curPath, request); let rc = stat(basePath); if (rc < 0 && common_1.isWindowsPath(basePath)) { let correctedPath = common_1.unixifyPath(basePath); rc = stat(correctedPath); if (rc >= 0) { basePath = correctedPath; } } let filename; const exts = Object.keys(Module._extensions); if (!trailingSlash) { switch (rc) { case 0: filename = preserveSymlinks && !isMain ? path_1.resolve(basePath) : volume.realpathSync(basePath); break; case 1: filename = tryPackage(basePath, exts, isMain); break; } if (!filename) { filename = tryExtensions(basePath, exts, isMain); } } if (!filename && rc === 1) { filename = tryPackage(basePath, exts, isMain) || tryExtensions(path_1.resolve(basePath, "index"), exts, isMain); } if (filename) { Module._pathCache[cacheKey] = filename; return filename; } } return false; }); return () => { Module._extensions[".js"] = backup._extensions[".js"]; Module._extensions[".json"] = backup._extensions[".json"]; Module._findPath = backup._findPath; }; } exports.patchModuleLoader = patchModuleLoader; return exports; }