UNPKG

@alexaegis/workspace-tools

Version:

Tools for working with javascript workspaces

56 lines (55 loc) 2.3 kB
import { existsSync } from "node:fs"; import { normalize, join } from "node:path"; import { normalizeCwdOption, normalizeDirectoryDepthOption } from "@alexaegis/fs"; const normalizeCollectFileDirnamesUpDirectoryTreeOptions = (options) => { return { ...normalizeCwdOption(options), ...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 = normalize(options.cwd); if (packageJsonCollection.length < options.maxPackages && resultCollection.length < options.maxResults && existsSync(join(path, fileName))) { resultCollection.unshift(path); } if (packageJsonCollection.length < options.maxPackages && existsSync(join(path, PACKAGE_JSON_NAME))) { packageJsonCollection.unshift(path); } const parentPath = 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]; }; export { NODE_MODULES_DIRECTORY_NAME as N, PACKAGE_JSON_NAME as P, PNPM_WORKSPACE_FILE_NAME as a, PACKAGE_JSON_DEPENDENCY_FIELDS as b, collectFileDirnamePathsUpDirectoryTree as c, getWorkspaceRoot as g, normalizeCollectFileDirnamesUpDirectoryTreeOptions as n };