UNPKG

@alexaegis/workspace-tools

Version:

Tools for working with javascript workspaces

55 lines (54 loc) 2.54 kB
"use strict"; const node_fs = require("node:fs"); const node_path = require("node:path"); const fs = require("@alexaegis/fs"); const normalizeCollectFileDirnamesUpDirectoryTreeOptions = (options) => { return { ...fs.normalizeCwdOption(options), ...fs.normalizeDirectoryDepthOption(options), maxPackages: options?.maxPackages ?? 2, maxResults: options?.maxResults ?? Number.POSITIVE_INFINITY }; }; const PACKAGE_JSON_NAME = "package.json"; const PNPM_WORKSPACE_FILE_NAME = "pnpm-workspace.yaml"; const NODE_MODULES_DIRECTORY_NAME = "node_modules"; const PACKAGE_JSON_DEPENDENCY_FIELDS = [ "dependencies", "devDependencies", "optionalDependencies", "peerDependencies" ]; const collectFileDirnamePathsUpDirectoryTree = (fileName, rawOptions) => { const options = normalizeCollectFileDirnamesUpDirectoryTreeOptions(rawOptions); return collectFileDirnamePathsUpDirectoryTreeInternal(fileName, options, [], []); }; const collectFileDirnamePathsUpDirectoryTreeInternal = (fileName, options, resultCollection, packageJsonCollection) => { const path = node_path.normalize(options.cwd); if (packageJsonCollection.length < options.maxPackages && resultCollection.length < options.maxResults && node_fs.existsSync(node_path.join(path, fileName))) { resultCollection.unshift(path); } if (packageJsonCollection.length < options.maxPackages && node_fs.existsSync(node_path.join(path, PACKAGE_JSON_NAME))) { packageJsonCollection.unshift(path); } const parentPath = node_path.join(path, ".."); if (parentPath !== path && options.depth > 0 && packageJsonCollection.length < options.maxPackages && resultCollection.length < options.maxResults) { return collectFileDirnamePathsUpDirectoryTreeInternal( fileName, { ...options, depth: options.depth - 1, cwd: parentPath }, resultCollection, packageJsonCollection ); } return resultCollection; }; const getWorkspaceRoot = (rawOptions) => { return collectFileDirnamePathsUpDirectoryTree(PACKAGE_JSON_NAME, rawOptions)[0]; }; exports.NODE_MODULES_DIRECTORY_NAME = NODE_MODULES_DIRECTORY_NAME; exports.PACKAGE_JSON_DEPENDENCY_FIELDS = PACKAGE_JSON_DEPENDENCY_FIELDS; exports.PACKAGE_JSON_NAME = PACKAGE_JSON_NAME; exports.PNPM_WORKSPACE_FILE_NAME = PNPM_WORKSPACE_FILE_NAME; exports.collectFileDirnamePathsUpDirectoryTree = collectFileDirnamePathsUpDirectoryTree; exports.getWorkspaceRoot = getWorkspaceRoot; exports.normalizeCollectFileDirnamesUpDirectoryTreeOptions = normalizeCollectFileDirnamesUpDirectoryTreeOptions;