/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ import "web-streams-polyfill/polyfill"; import { basename, dirname, isAbsolute, join } from "path"; import { resolveManifest, initSync, Nassun, NodeMaintainer, Package, Entry, } from "@vscode/ts-package-manager/node-maintainer/node_maintainer.js"; import wasmModule from "@vscode/ts-package-manager/node-maintainer/node_maintainer_bg.wasm"; //@ts-ignore wasmModule().then((m) => initSync(m)); export interface OrogeneFileSystem { readDirectory(path: string): Promise; removeDirectory( path: string, options?: { recursive?: boolean }, ): Promise; deleteFile?(path: string): Promise; createDirectory(path: string): Promise; writeFile( path: string, content: string | Uint8Array, options?: { encoding?: "utf8"; mode?: number }, ): Promise; directoryExists(path: string): Promise; readFile(path: string, encoding?: string): Promise; } export interface InstallProjectOpts { addPackages?: string[]; removePackages?: string[]; packageType?: PackageType; pkgJson?: string; npmLock?: string; kdlLock?: string; } export enum PackageType { Dependency = "dependencies", DevDependency = "devDependencies", OptionalDependency = "optionalDependencies", PeerDependency = "peerDependencies", } // This is the subset of ts.server.System that we actually need. export interface FileSystem { readDirectory( path: string, extensions?: readonly string[], exclude?: readonly string[], include?: readonly string[], depth?: number, ): Promise; deleteFile?(path: string): Promise; createDirectory(path: string): Promise; writeFile( path: string, data: string, writeByteOrderMark?: boolean, ): Promise; directoryExists(path: string): Promise; readFile(path: string, encoding?: "utf8"): Promise; } // The meta file is placed in `node_modules/.meta.json` and records what // packages have actually been installed. interface MetaFile { packages?: Record; } interface DependencyDetails { version: string; overridden: boolean; } // Define the interface for the main JSON structure interface NpmTree { version: string; name: string; dependencies: Record; } export class PackageManager { private readonly nassun: Nassun = new Nassun({}); constructor(private readonly fs: OrogeneFileSystem) {} async resolveProject(root: string, opts: InstallProjectOpts = {}) { if (opts.addPackages || opts.removePackages) { await this.updateJson(join(root, "package.json"), opts); } console.time(`dependency resolution: ${root}`); const maintainer = await this.resolveMaintainer(root, opts); console.timeEnd(`dependency resolution: ${root}`); return new ResolvedProject(this.fs, maintainer, root); } private async updateJson( packageJsonPath: string, opts: InstallProjectOpts = {}, ) { const packageType = opts.packageType ?? PackageType.Dependency; const corgis = await Promise.all( (opts.addPackages ?? []).map(async (pkg) => this.nassun.corgiMetadata(pkg), ), ); let pkgJson; try { pkgJson = await this.readJson(packageJsonPath); } catch (e) { console.error("failed to read package.json", e); pkgJson = {}; } for (const packageName of opts.removePackages ?? []) { delete pkgJson.dependencies?.[packageName]; delete pkgJson.devDependencies?.[packageName]; delete pkgJson.optionalDependencies?.[packageName]; delete pkgJson.peerDependencies?.[packageName]; } for (const corgi of corgis) { console.log("corgi", corgi); //this.nassun.resolve(corgi) if (!pkgJson[packageType]) { pkgJson[packageType] = {}; } if (corgi.name && corgi.version) { pkgJson[packageType][corgi.name] = `^${corgi.version}`; } } const stringified = JSON.stringify(pkgJson, undefined, 2); console.log("writing package.json", stringified); this.fs.writeFile(packageJsonPath, stringified); } private async resolveMaintainer( root: string, opts: InstallProjectOpts, ): Promise { const pkgJson = opts.pkgJson || (await this.fs.readFile(join(root, "package.json"), "utf8")) || "{}"; console.log("pkgJson from resolve maintaener", pkgJson); return resolveManifest(JSON.parse(pkgJson.trim()), {}); } /** * What it says on the tin. Reads a JSON file from the given path. Throws * if the file doesn't exist (as opposed to returning `undefined`, like * fs.readFile does). */ private async readJson(path: string): Promise { const data = await this.fs.readFile(path); if (!data) { throw new Error("Failed to read file: " + path); } return JSON.parse(data.trim()); } } export class ResolvedProject { private readonly prefix: string; private readonly metaPath: string; constructor( private readonly fs: OrogeneFileSystem, private readonly maintainer: NodeMaintainer, private readonly root: string, private readonly logger = console, ) { this.prefix = join(root, "node_modules"); this.metaPath = join(this.prefix, ".meta.json"); } /** * Synchronizes the project's node_modules directory with the current resolved dependencies, pruning any extraneous ones. */ async restore() { await this.pruneExtraneous(); await this.extractMissing(); // this.writeLockfile(); } /** * Extracts a package at the given path. If a package has already been * extracted to that location, it will be replaced. * * @param path to a package */ async restorePackageAt(path: string): Promise { this.checkPath(path); const metaData = await this.fs.readFile(this.metaPath); const meta: MetaFile = JSON.parse(metaData || "{}"); if (!meta.packages) { meta.packages = {}; } const projRoot = this.getProjectRoot(path); if (!projRoot) { throw new Error("Project root must not be null"); } const pkgPath = packagePath(path); const pkg = this.packageAtPath(path.slice(projRoot.length)); if (!pkg) { throw new Error(`No package.json found at ${path}`); } if ( pkg && pkgPath && meta.packages?.[pkgPath.slice(this.prefix.length)]?.resolved === pkg.resolved ) { // Already installed and synced. No need to do anything else! return; } this.fs.removeDirectory(pkgPath, { recursive: true }); try { // NB(zkat): load-bearing `await`. We need to await here because // otherwise we'll have a use-after-free error when extracting the // package entries. await this.extractPackageTo(pkg, pkgPath); meta.packages[pkgPath.slice(this.prefix.length)] = { name: pkg.name, resolved: pkg.resolved, }; } finally { pkg.free(); } this.fs.removeDirectory(this.metaPath, { recursive: true }); await this.fs.writeFile(this.metaPath, JSON.stringify(meta, null, 2), { encoding: "utf8", }); await this.writeLockfile(); } //TODO: make sure we dont prune fluent when not applicable /** * Deletes/prunes files and directories that aren't expected to be there * by the currently-calculated tree. Extraneous calculation happens based on the contents of `.meta.json` * @returns */ async pruneExtraneous(): Promise { const meta = JSON.parse((await this.fs.readFile(this.metaPath)) || "{}"); if (!(await this.fs.directoryExists(this.prefix))) { return; } for await (const entryPath of walkDir(this.fs, this.prefix)) { // Ignore if: // - nested node module // - not package.json (only process each dependency once) // TODO: Find way to delete all errant files (everything that isnt a package should be removed) const pkgPath = packagePath(entryPath); const subPath = pkgPath.slice(this.prefix.length); const pkg = this.packageAtPath(subPath); if ( !entryPath.endsWith("package.json") || entryPath.indexOf("node_modules") !== entryPath.lastIndexOf("node_modules") ) { continue; } try { if (!pkg) { // delete dir -> not a dependency, errant dir in node_modules this.fs.removeDirectory(pkgPath, { recursive: true }); } else { const pkgNameFromPath = subPath.substring(1); if (meta.packages?.[pkgNameFromPath]?.resolved === pkg.resolved) { // Woohoo! Package is good, we move on } else { // delete dir -> dependency doesnt match this.fs.removeDirectory(pkgPath, { recursive: true }); } } } finally { pkg?.free(); } } } private packageAtPath(path: string): Package | undefined { return this.maintainer.packageAtPath(path); } private getProjectRoot(path: string): string | undefined { const pkgPath = path.match(/(^.*\/)node_modules/); return pkgPath?.[1]; } private checkPath(path: string) { if (!path.startsWith(this.root)) { throw new Error(`Path ${path} is not in project root ${this.root}`); } if (!isAbsolute(path)) { throw new Error(`Path ${path} is not absolute`); } } private async extractPackageTo(pkg: Package, pkgPath: string): Promise { const mkdirCache = new Set(); await mkdirp(mkdirCache, this.fs, pkgPath); // Clean up the directory, in case it already exists, but leave // node_modules alone to avoid clobbering other packages. for (const file of await this.fs.readDirectory(pkgPath)) { if (basename(file) === "node_modules") { continue; } this.fs.removeDirectory(file, { recursive: true }); } const entries = >await pkg.entries(); const reader = entries.getReader(); // eslint-disable-next-line no-constant-condition while (true) { const { done, value: entry } = await reader.read(); if (done) { break; } // Strip the first level of a package, just like NPM does. const entryPath = join(pkgPath, entry.path.replace(/^([^/]*\/)?/, "")); // We simulate directories based on files we find. await mkdirp(mkdirCache, this.fs, dirname(entryPath)); // Types are registered here: // https://www.gnu.org/software/tar/manual/html_node/Standard.html. // You can get these numbers by just doing `'5'.codePointAt(0)`, // but we may as well hard-code the three values we actually care // about here. if (entry.type === 53) { // '5' == 53 == directory await mkdirp(mkdirCache, this.fs, entryPath); await drainStream(entry.contents); } else if (entry.type === 0 || entry.type === 48) { // '0' == 48 or '\x00' == 0 == regular file const data = await streamToArrayBuffer(entry.contents, entry.size); await this.fs.writeFile(entryPath, data); } else { // Anything else, we throw away, but we have to make sure to // drain any contents before we can continue reading the // tarball. await drainStream(entry.contents); } } } private async extractMissing() { const meta = ( JSON.parse( (await this.fs.readFile(this.metaPath)) || '{ "packages": {} }', ) ); const installedPackages: { [key: string]: boolean } = {}; await this.maintainer.forEachPackage(async (pkg: Package, path: string) => { const fullPath = join(this.prefix, path); const handlePkg = async (pkg: Package, fullPath: string) => { if (!(await this.fs.directoryExists(fullPath))) { if (!installedPackages[pkg.resolved]) { this.logger.log(`installed ${pkg.name} from ${pkg.resolved}`); installedPackages[pkg.resolved] = true; } await this.extractPackageTo(pkg, fullPath); } }; await handlePkg(pkg, fullPath) .catch((e) => console.error(e)) .finally(() => { const { packages } = meta; if (packages) { packages[path] = { name: pkg.name, resolved: pkg.resolved, }; } pkg.free(); }); }); this.fs.removeDirectory(this.metaPath, { recursive: true }); await this.fs.writeFile(this.metaPath, JSON.stringify(meta, null, 2), { encoding: "utf8", }); } private async writeLockfile() { await this.fs.writeFile( join(this.root, "package-lock.kdl"), this.maintainer.toKdl(), { encoding: "utf8" }, ); } } //---- Utils /** * Given a full path to a particular file, presumably inside a package, * this returns the path of the package containing that file. * @param path the full file path to the file. * @returns the subpath of the package itself */ export function packagePath(path: string): string { return path.replace( /(^.*\/node_modules\/(?:@[^/]+\/)?[^/]+)\/?(?!node_modules\/).*/, "$1", ); } async function drainStream(stream: ReadableStream): Promise { const reader = stream.getReader(); // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-line no-constant-condition const { done } = await reader.read(); if (done) { break; } } return reader.closed; } async function streamToArrayBuffer( stream: ReadableStream, length: number, ): Promise { const result = new Uint8Array(length); const reader = stream.getReader(); let idx = 0; // eslint-disable-next-line no-constant-condition while (true) { // eslint-disable-line no-constant-condition const { done, value } = await reader.read(); if (done) { break; } result.set(value, idx); idx += value.length; } return result; } async function* walkDir(fs: OrogeneFileSystem, path: string) { let contents = await fs.readDirectory(path); while (contents.length) { const entry = contents.shift() as string; const entryPath = join(path, entry); if (await fs.directoryExists(entryPath)) { contents = (await fs.readDirectory(entryPath)) .map((e) => join(entry, e)) .concat(contents); } yield entryPath; } } async function mkdirp(cache: Set, fs: OrogeneFileSystem, path: string) { const paths = path.split("/"); let dir = "/"; for (const next of paths) { const joined = join(dir, next); if (!cache.has(joined) && !(await fs.directoryExists(joined))) { await fs.createDirectory(joined); cache.add(joined); } dir = joined; } }