PHP WebShell
Текущая директория: /opt/BitGoJS/node_modules/nx/src/config
Просмотр файла: workspaces.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.renamePropertyWithStableKeys = exports.readTargetDefaultsForTarget = exports.mergeTargetConfigurations = exports.buildProjectsConfigurationsFromGlobs = exports.inferProjectFromNonStandardFile = exports.deduplicateProjectFiles = exports.globForProjectFiles = exports.getGlobPatternsFromPackageManagerWorkspaces = exports.getGlobPatternsFromPluginsAsync = exports.getGlobPatternsFromPlugins = exports.toProjectName = exports.Workspaces = void 0;
const tslib_1 = require("tslib");
const fast_glob_1 = require("fast-glob");
const fs_1 = require("fs");
const path = require("path");
const path_1 = require("path");
const perf_hooks_1 = require("perf_hooks");
const workspace_root_1 = require("../utils/workspace-root");
const fileutils_1 = require("../utils/fileutils");
const logger_1 = require("../utils/logger");
const nx_plugin_1 = require("../utils/nx-plugin");
const yaml = require("js-yaml");
const output_1 = require("../utils/output");
const path_2 = require("../utils/path");
const angular_json_1 = require("../adapter/angular-json");
const installation_directory_1 = require("../utils/installation-directory");
const ignore_1 = require("../utils/ignore");
const find_project_for_path_1 = require("../project-graph/utils/find-project-for-path");
class Workspaces {
constructor(root) {
this.root = root;
}
relativeCwd(cwd) {
return path.relative(this.root, cwd).replace(/\\/g, '/') || null;
}
calculateDefaultProjectName(cwd, { projects }, nxJson) {
var _a;
const relativeCwd = this.relativeCwd(cwd);
if (relativeCwd) {
const matchingProject = findMatchingProjectInCwd(projects, relativeCwd);
// We have found a project
if (matchingProject) {
// That is not at the root
if (projects[matchingProject].root !== '.' &&
projects[matchingProject].root !== '') {
return matchingProject;
// But its at the root, and NX_DEFAULT_PROJECT is set
}
else if (process.env.NX_DEFAULT_PROJECT) {
return process.env.NX_DEFAULT_PROJECT;
// Its root, and NX_DEFAULT_PROJECT is not set
}
else {
return matchingProject;
}
}
}
// There was no matching project in cwd.
return (_a = process.env.NX_DEFAULT_PROJECT) !== null && _a !== void 0 ? _a : nxJson === null || nxJson === void 0 ? void 0 : nxJson.defaultProject;
}
/**
* @deprecated
*/
readProjectsConfigurations(opts) {
if (this.cachedProjectsConfig &&
process.env.NX_CACHE_PROJECTS_CONFIG !== 'false') {
return this.cachedProjectsConfig;
}
const nxJson = this.readNxJson();
const projectsConfigurations = buildProjectsConfigurationsFromGlobs(nxJson, globForProjectFiles(this.root, (opts === null || opts === void 0 ? void 0 : opts._ignorePluginInference)
? []
: getGlobPatternsFromPlugins(nxJson, (0, installation_directory_1.getNxRequirePaths)(this.root), this.root), nxJson), (path) => (0, fileutils_1.readJsonFile)((0, path_1.join)(this.root, path)));
if ((0, angular_json_1.shouldMergeAngularProjects)(this.root, opts === null || opts === void 0 ? void 0 : opts._includeProjectsFromAngularJson)) {
projectsConfigurations.projects = (0, angular_json_1.mergeAngularJsonAndGlobProjects)(projectsConfigurations.projects);
}
this.cachedProjectsConfig = this.mergeTargetDefaultsIntoProjectDescriptions(projectsConfigurations, nxJson);
return this.cachedProjectsConfig;
}
/**
* Deprecated. Use readProjectsConfigurations
*/
readWorkspaceConfiguration(opts) {
const nxJson = this.readNxJson();
return Object.assign(Object.assign({}, this.readProjectsConfigurations(opts)), nxJson);
}
mergeTargetDefaultsIntoProjectDescriptions(config, nxJson) {
for (const proj of Object.values(config.projects)) {
if (proj.targets) {
for (const targetName of Object.keys(proj.targets)) {
const projectTargetDefinition = proj.targets[targetName];
const defaults = readTargetDefaultsForTarget(targetName, nxJson.targetDefaults, projectTargetDefinition.executor);
if (defaults) {
proj.targets[targetName] = mergeTargetConfigurations(proj, targetName, defaults);
}
}
}
}
return config;
}
isNxExecutor(nodeModule, executor) {
return !this.readExecutor(nodeModule, executor).isNgCompat;
}
isNxGenerator(collectionName, generatorName) {
return !this.readGenerator(collectionName, generatorName).isNgCompat;
}
readExecutor(nodeModule, executor) {
try {
const { executorsFilePath, executorConfig, isNgCompat } = this.readExecutorsJson(nodeModule, executor);
const executorsDir = path.dirname(executorsFilePath);
const schemaPath = path.join(executorsDir, executorConfig.schema || '');
const schema = normalizeExecutorSchema((0, fileutils_1.readJsonFile)(schemaPath));
const implementationFactory = this.getImplementationFactory(executorConfig.implementation, executorsDir);
const batchImplementationFactory = executorConfig.batchImplementation
? this.getImplementationFactory(executorConfig.batchImplementation, executorsDir)
: null;
const hasherFactory = executorConfig.hasher
? this.getImplementationFactory(executorConfig.hasher, executorsDir)
: null;
return {
schema,
implementationFactory,
batchImplementationFactory,
hasherFactory,
isNgCompat,
};
}
catch (e) {
throw new Error(`Unable to resolve ${nodeModule}:${executor}.\n${e.message}`);
}
}
readGenerator(collectionName, generatorName) {
var _a, _b, _c, _d;
try {
const { generatorsFilePath, generatorsJson, resolvedCollectionName, normalizedGeneratorName, } = this.readGeneratorsJson(collectionName, generatorName);
const generatorsDir = path.dirname(generatorsFilePath);
const generatorConfig = ((_a = generatorsJson.generators) === null || _a === void 0 ? void 0 : _a[normalizedGeneratorName]) ||
((_b = generatorsJson.schematics) === null || _b === void 0 ? void 0 : _b[normalizedGeneratorName]);
const isNgCompat = !((_c = generatorsJson.generators) === null || _c === void 0 ? void 0 : _c[normalizedGeneratorName]);
const schemaPath = path.join(generatorsDir, generatorConfig.schema || '');
const schema = (0, fileutils_1.readJsonFile)(schemaPath);
if (!schema.properties || typeof schema.properties !== 'object') {
schema.properties = {};
}
generatorConfig.implementation =
generatorConfig.implementation || generatorConfig.factory;
const implementationFactory = this.getImplementationFactory(generatorConfig.implementation, generatorsDir);
const normalizedGeneratorConfiguration = Object.assign(Object.assign({}, generatorConfig), { aliases: (_d = generatorConfig.aliases) !== null && _d !== void 0 ? _d : [], hidden: !!generatorConfig.hidden });
return {
resolvedCollectionName,
normalizedGeneratorName,
schema,
implementationFactory,
isNgCompat,
aliases: generatorConfig.aliases || [],
generatorConfiguration: normalizedGeneratorConfiguration,
};
}
catch (e) {
throw new Error(`Unable to resolve ${collectionName}:${generatorName}.\n${e.message}`);
}
}
hasNxJson() {
const nxJson = path.join(this.root, 'nx.json');
return (0, fs_1.existsSync)(nxJson);
}
readNxJson() {
const nxJson = path.join(this.root, 'nx.json');
if ((0, fs_1.existsSync)(nxJson)) {
const nxJsonConfiguration = (0, fileutils_1.readJsonFile)(nxJson);
if (nxJsonConfiguration.extends) {
const extendedNxJsonPath = require.resolve(nxJsonConfiguration.extends, {
paths: [(0, path_1.dirname)(nxJson)],
});
const baseNxJson = (0, fileutils_1.readJsonFile)(extendedNxJsonPath);
return this.mergeTargetDefaultsAndTargetDependencies(Object.assign(Object.assign({}, baseNxJson), nxJsonConfiguration));
}
else {
return this.mergeTargetDefaultsAndTargetDependencies(nxJsonConfiguration);
}
}
else {
try {
return this.mergeTargetDefaultsAndTargetDependencies((0, fileutils_1.readJsonFile)((0, path_1.join)(__dirname, '..', '..', 'presets', 'core.json')));
}
catch (e) {
return {};
}
}
}
mergeTargetDefaultsAndTargetDependencies(nxJson) {
if (!nxJson.targetDefaults) {
nxJson.targetDefaults = {};
}
if (nxJson.targetDependencies) {
for (const targetName of Object.keys(nxJson.targetDependencies)) {
if (!nxJson.targetDefaults[targetName]) {
nxJson.targetDefaults[targetName] = {};
}
if (!nxJson.targetDefaults[targetName].dependsOn) {
nxJson.targetDefaults[targetName].dependsOn = [];
}
nxJson.targetDefaults[targetName].dependsOn = [
...nxJson.targetDefaults[targetName].dependsOn,
...nxJson.targetDependencies[targetName],
];
}
}
return nxJson;
}
getImplementationFactory(implementation, directory) {
const [implementationModulePath, implementationExportName] = implementation.split('#');
return () => {
var _a;
const possibleModulePath = path.join(directory, implementationModulePath);
const validImplementations = ['', '.js', '.ts'].map((x) => possibleModulePath + x);
const modulePath = validImplementations.find((f) => (0, fs_1.existsSync)(f));
if ((0, path_1.extname)(modulePath) === '.ts') {
(0, nx_plugin_1.registerPluginTSTranspiler)();
}
const module = require(modulePath);
return implementationExportName
? module[implementationExportName]
: (_a = module.default) !== null && _a !== void 0 ? _a : module;
};
}
readExecutorsJson(nodeModule, executor) {
var _a, _b, _c, _d;
const { json: packageJson, path: packageJsonPath } = (0, nx_plugin_1.readPluginPackageJson)(nodeModule, this.resolvePaths());
const executorsFile = (_a = packageJson.executors) !== null && _a !== void 0 ? _a : packageJson.builders;
if (!executorsFile) {
throw new Error(`The "${nodeModule}" package does not support Nx executors.`);
}
const executorsFilePath = require.resolve(path.join(path.dirname(packageJsonPath), executorsFile));
const executorsJson = (0, fileutils_1.readJsonFile)(executorsFilePath);
const executorConfig = ((_b = executorsJson.executors) === null || _b === void 0 ? void 0 : _b[executor]) || ((_c = executorsJson.builders) === null || _c === void 0 ? void 0 : _c[executor]);
if (!executorConfig) {
throw new Error(`Cannot find executor '${executor}' in ${executorsFilePath}.`);
}
const isNgCompat = !((_d = executorsJson.executors) === null || _d === void 0 ? void 0 : _d[executor]);
return { executorsFilePath, executorConfig, isNgCompat };
}
readGeneratorsJson(collectionName, generator) {
var _a;
let generatorsFilePath;
if (collectionName.endsWith('.json')) {
generatorsFilePath = require.resolve(collectionName, {
paths: this.resolvePaths(),
});
}
else {
const { json: packageJson, path: packageJsonPath } = (0, nx_plugin_1.readPluginPackageJson)(collectionName, this.resolvePaths());
const generatorsFile = (_a = packageJson.generators) !== null && _a !== void 0 ? _a : packageJson.schematics;
if (!generatorsFile) {
throw new Error(`The "${collectionName}" package does not support Nx generators.`);
}
generatorsFilePath = require.resolve(path.join(path.dirname(packageJsonPath), generatorsFile));
}
const generatorsJson = (0, fileutils_1.readJsonFile)(generatorsFilePath);
let normalizedGeneratorName = findFullGeneratorName(generator, generatorsJson.generators) ||
findFullGeneratorName(generator, generatorsJson.schematics);
if (!normalizedGeneratorName) {
for (let parent of generatorsJson.extends || []) {
try {
return this.readGeneratorsJson(parent, generator);
}
catch (e) { }
}
throw new Error(`Cannot find generator '${generator}' in ${generatorsFilePath}.`);
}
return {
generatorsFilePath,
generatorsJson,
normalizedGeneratorName,
resolvedCollectionName: collectionName,
};
}
resolvePaths() {
return this.root ? [this.root, __dirname] : [__dirname];
}
}
exports.Workspaces = Workspaces;
function findMatchingProjectInCwd(projects, relativeCwd) {
const projectRootMappings = new Map();
for (const projectName of Object.keys(projects)) {
const { root } = projects[projectName];
projectRootMappings.set((0, find_project_for_path_1.normalizeProjectRoot)(root), projectName);
}
const matchingProject = (0, find_project_for_path_1.findProjectForPath)(relativeCwd, projectRootMappings);
return matchingProject;
}
function normalizeExecutorSchema(schema) {
var _a, _b;
const version = ((_a = schema.version) !== null && _a !== void 0 ? _a : (schema.version = 1));
return Object.assign({ version, outputCapture: ((_b = schema.outputCapture) !== null && _b !== void 0 ? _b : version < 2) ? 'direct-nodejs' : 'pipe', properties: !schema.properties || typeof schema.properties !== 'object'
? {}
: schema.properties }, schema);
}
function findFullGeneratorName(name, generators) {
if (generators) {
for (let [key, data] of Object.entries(generators)) {
if (key === name ||
(data.aliases && data.aliases.includes(name))) {
return key;
}
}
}
}
/**
* Pulled from toFileName in names from @nrwl/devkit.
* Todo: Should refactor, not duplicate.
*/
function toProjectName(fileName) {
const parts = (0, path_1.dirname)(fileName).split(/[\/\\]/g);
return parts[parts.length - 1].toLowerCase();
}
exports.toProjectName = toProjectName;
let projectGlobCache;
let projectGlobCacheKey;
/**
* @deprecated Use getGlobPatternsFromPluginsAsync instead.
*/
function getGlobPatternsFromPlugins(nxJson, paths, root = workspace_root_1.workspaceRoot) {
const plugins = (0, nx_plugin_1.loadNxPluginsSync)(nxJson === null || nxJson === void 0 ? void 0 : nxJson.plugins, paths, root);
const patterns = [];
for (const plugin of plugins) {
if (!plugin.projectFilePatterns) {
continue;
}
for (const filePattern of plugin.projectFilePatterns) {
patterns.push('**/' + filePattern);
}
}
return patterns;
}
exports.getGlobPatternsFromPlugins = getGlobPatternsFromPlugins;
function getGlobPatternsFromPluginsAsync(nxJson, paths, root = workspace_root_1.workspaceRoot) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const plugins = yield (0, nx_plugin_1.loadNxPlugins)(nxJson === null || nxJson === void 0 ? void 0 : nxJson.plugins, paths, root);
const patterns = [];
for (const plugin of plugins) {
if (!plugin.projectFilePatterns) {
continue;
}
for (const filePattern of plugin.projectFilePatterns) {
patterns.push('**/' + filePattern);
}
}
return patterns;
});
}
exports.getGlobPatternsFromPluginsAsync = getGlobPatternsFromPluginsAsync;
/**
* Get the package.json globs from package manager workspaces
*/
function getGlobPatternsFromPackageManagerWorkspaces(root) {
var _a, _b;
try {
const patterns = [];
const packageJson = (0, fileutils_1.readJsonFile)((0, path_1.join)(root, 'package.json'));
patterns.push(...normalizePatterns(Array.isArray(packageJson.workspaces)
? packageJson.workspaces
: (_b = (_a = packageJson.workspaces) === null || _a === void 0 ? void 0 : _a.packages) !== null && _b !== void 0 ? _b : []));
if ((0, fs_1.existsSync)((0, path_1.join)(root, 'pnpm-workspace.yaml'))) {
try {
const obj = yaml.load((0, fs_1.readFileSync)((0, path_1.join)(root, 'pnpm-workspace.yaml'), 'utf-8'));
patterns.push(...normalizePatterns(obj.packages || []));
}
catch (e) {
output_1.output.warn({
title: `${logger_1.NX_PREFIX} Unable to parse pnpm-workspace.yaml`,
bodyLines: [e.toString()],
});
}
}
if ((0, fs_1.existsSync)((0, path_1.join)(root, 'lerna.json'))) {
try {
const { packages } = (0, fileutils_1.readJsonFile)((0, path_1.join)(root, 'lerna.json'));
patterns.push(...normalizePatterns((packages === null || packages === void 0 ? void 0 : packages.length) > 0 ? packages : ['packages/*']));
}
catch (e) {
output_1.output.warn({
title: `${logger_1.NX_PREFIX} Unable to parse lerna.json`,
bodyLines: [e.toString()],
});
}
}
// Merge patterns from workspaces definitions
// TODO(@AgentEnder): update logic after better way to determine root project inclusion
// Include the root project
return packageJson.nx ? patterns.concat('package.json') : patterns;
}
catch (_c) { }
}
exports.getGlobPatternsFromPackageManagerWorkspaces = getGlobPatternsFromPackageManagerWorkspaces;
function normalizePatterns(patterns) {
return patterns.map((pattern) => removeRelativePath(pattern.endsWith('/package.json')
? pattern
: (0, path_2.joinPathFragments)(pattern, 'package.json')));
}
function removeRelativePath(pattern) {
return pattern.startsWith('./') ? pattern.substring(2) : pattern;
}
function globForProjectFiles(root, pluginsGlobPatterns, nxJson) {
// Deal w/ Caching
const cacheKey = [root, ...pluginsGlobPatterns].join(',');
if (process.env.NX_PROJECT_GLOB_CACHE !== 'false' &&
projectGlobCache &&
cacheKey === projectGlobCacheKey) {
return projectGlobCache;
}
projectGlobCacheKey = cacheKey;
const _globPatternsFromPackageManagerWorkspaces = getGlobPatternsFromPackageManagerWorkspaces(root);
const globPatternsFromPackageManagerWorkspaces = _globPatternsFromPackageManagerWorkspaces !== null && _globPatternsFromPackageManagerWorkspaces !== void 0 ? _globPatternsFromPackageManagerWorkspaces : [];
const globsToInclude = globPatternsFromPackageManagerWorkspaces.filter((glob) => !glob.startsWith('!'));
const globsToExclude = globPatternsFromPackageManagerWorkspaces
.filter((glob) => glob.startsWith('!'))
.map((glob) => glob.substring(1))
.map((glob) => (glob.startsWith('/') ? glob.substring(1) : glob));
const projectGlobPatterns = [
'project.json',
'**/project.json',
...globsToInclude,
];
projectGlobPatterns.push(...pluginsGlobPatterns);
const combinedProjectGlobPattern = '{' + projectGlobPatterns.join(',') + '}';
perf_hooks_1.performance.mark('start-glob-for-projects');
/**
* This configures the files and directories which we always want to ignore as part of file watching
* and which we know the location of statically (meaning irrespective of user configuration files).
* This has the advantage of being ignored directly within globSync
*
* Other ignored entries will need to be determined dynamically by reading and evaluating the user's
* .gitignore and .nxignore files below.
*/
const staticIgnores = [
'node_modules',
'**/node_modules',
'dist',
'.git',
...globsToExclude,
...(0, ignore_1.getIgnoredGlobs)(root, false),
];
/**
* TODO: This utility has been implemented multiple times across the Nx codebase,
* discuss whether it should be moved to a shared location.
*/
const opts = {
ignore: staticIgnores,
absolute: false,
cwd: root,
dot: true,
suppressErrors: true,
};
const globResults = (0, fast_glob_1.sync)(combinedProjectGlobPattern, opts);
projectGlobCache = deduplicateProjectFiles(globResults);
// TODO @vsavkin remove after Nx 16
if (projectGlobCache.length === 0 &&
_globPatternsFromPackageManagerWorkspaces === undefined &&
(nxJson === null || nxJson === void 0 ? void 0 : nxJson.extends) === 'nx/presets/npm.json') {
output_1.output.warn({
title: 'Nx could not find any projects. Check if you need to configure workspaces in package.json or pnpm-workspace.yaml',
});
}
perf_hooks_1.performance.mark('finish-glob-for-projects');
perf_hooks_1.performance.measure('glob-for-project-files', 'start-glob-for-projects', 'finish-glob-for-projects');
return projectGlobCache;
}
exports.globForProjectFiles = globForProjectFiles;
/**
* @description Loops through files and reduces them to 1 file per project.
* @param files Array of files that may represent projects
*/
function deduplicateProjectFiles(files) {
const filtered = new Map();
files.forEach((file) => {
const projectFolder = (0, path_1.dirname)(file);
const projectFile = (0, path_1.basename)(file);
if (filtered.has(projectFolder) && projectFile !== 'project.json')
return;
filtered.set(projectFolder, projectFile);
});
return Array.from(filtered.entries()).map(([folder, file]) => (0, path_1.join)(folder, file));
}
exports.deduplicateProjectFiles = deduplicateProjectFiles;
function buildProjectConfigurationFromPackageJson(path, packageJson, nxJson) {
var _a, _b, _c, _d;
const normalizedPath = path.split('\\').join('/');
const directory = (0, path_1.dirname)(normalizedPath);
let name = (_a = packageJson.name) !== null && _a !== void 0 ? _a : toProjectName(normalizedPath);
if (nxJson === null || nxJson === void 0 ? void 0 : nxJson.npmScope) {
const npmPrefix = `@${nxJson.npmScope}/`;
if (name.startsWith(npmPrefix)) {
name = name.replace(npmPrefix, '');
}
}
const projectType = ((_b = nxJson === null || nxJson === void 0 ? void 0 : nxJson.workspaceLayout) === null || _b === void 0 ? void 0 : _b.appsDir) != ((_c = nxJson === null || nxJson === void 0 ? void 0 : nxJson.workspaceLayout) === null || _c === void 0 ? void 0 : _c.libsDir) &&
((_d = nxJson === null || nxJson === void 0 ? void 0 : nxJson.workspaceLayout) === null || _d === void 0 ? void 0 : _d.appsDir) &&
directory.startsWith(nxJson.workspaceLayout.appsDir)
? 'application'
: 'library';
return {
root: directory,
sourceRoot: directory,
name,
projectType,
};
}
function inferProjectFromNonStandardFile(file) {
const directory = (0, path_1.dirname)(file).split('\\').join('/');
return {
name: toProjectName(file),
root: directory,
};
}
exports.inferProjectFromNonStandardFile = inferProjectFromNonStandardFile;
function buildProjectsConfigurationsFromGlobs(nxJson, projectFiles, // making this parameter allows devkit to pick up newly created projects
readJson = (string) => (0, fileutils_1.readJsonFile)(string) // making this an arg allows us to reuse in devkit
) {
const projects = {};
for (const file of projectFiles) {
const directory = (0, path_1.dirname)(file).split('\\').join('/');
const fileName = (0, path_1.basename)(file);
if (fileName === 'project.json') {
// Nx specific project configuration (`project.json` files) in the same
// directory as a package.json should overwrite the inferred package.json
// project configuration.
const configuration = readJson(file);
configuration.root = directory;
let name = configuration.name;
if (!configuration.name) {
name = toProjectName(file);
}
if (!projects[name]) {
projects[name] = configuration;
}
else {
logger_1.logger.warn(`Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.`);
}
}
else {
// We can infer projects from package.json files,
// if a package.json file is in a directory w/o a `project.json` file.
// this results in targets being inferred by Nx from package scripts,
// and the root / sourceRoot both being the directory.
if (fileName === 'package.json') {
const projectPackageJson = readJson(file);
const _a = buildProjectConfigurationFromPackageJson(file, projectPackageJson, nxJson), { name } = _a, config = tslib_1.__rest(_a, ["name"]);
if (!projects[name]) {
projects[name] = config;
}
else {
logger_1.logger.warn(`Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.`);
}
}
else {
// This project was created from an nx plugin.
// The only thing we know about the file is its location
const _b = inferProjectFromNonStandardFile(file), { name } = _b, config = tslib_1.__rest(_b, ["name"]);
if (!projects[name]) {
projects[name] = config;
}
else {
logger_1.logger.error(`Skipping project inferred from ${file} since project ${name} already exists.`);
throw new Error();
}
}
}
}
return {
version: 2,
projects: projects,
};
}
exports.buildProjectsConfigurationsFromGlobs = buildProjectsConfigurationsFromGlobs;
function mergeTargetConfigurations(projectConfiguration, target, targetDefaults) {
var _a, _b;
const targetConfiguration = (_a = projectConfiguration.targets) === null || _a === void 0 ? void 0 : _a[target];
if (!targetConfiguration) {
throw new Error(`Attempted to merge targetDefaults for ${projectConfiguration.name}.${target}, which doesn't exist.`);
}
const { configurations: defaultConfigurations, options: defaultOptions } = targetDefaults, defaults = tslib_1.__rest(targetDefaults, ["configurations", "options"]);
const result = Object.assign(Object.assign({}, defaults), targetConfiguration);
// Target is "compatible", e.g. executor is defined only once or is the same
// in both places. This means that it is likely safe to merge options
if (!targetDefaults.executor ||
!targetConfiguration.executor ||
targetDefaults.executor === targetConfiguration.executor) {
result.options = mergeOptions(defaultOptions, (_b = targetConfiguration.options) !== null && _b !== void 0 ? _b : {}, projectConfiguration, target);
result.configurations = mergeConfigurations(defaultConfigurations, targetConfiguration.configurations, projectConfiguration, target);
}
return result;
}
exports.mergeTargetConfigurations = mergeTargetConfigurations;
function mergeOptions(defaults, options, project, key) {
return Object.assign(Object.assign({}, resolvePathTokensInOptions(defaults, project, key)), options);
}
function mergeConfigurations(defaultConfigurations, projectDefinedConfigurations, project, targetName) {
const configurations = Object.assign({}, projectDefinedConfigurations);
for (const configuration in defaultConfigurations) {
configurations[configuration] = mergeOptions(defaultConfigurations[configuration], configurations[configuration], project, `${targetName}.${configuration}`);
}
return configurations;
}
function resolvePathTokensInOptions(object, project, key) {
const result = Array.isArray(object) ? [...object] : Object.assign({}, object);
for (let [opt, value] of Object.entries(object !== null && object !== void 0 ? object : {})) {
if (typeof value === 'string') {
if (value.startsWith('{workspaceRoot}/')) {
value = value.replace(/^\{workspaceRoot\}\//, '');
}
if (value.includes('{workspaceRoot}')) {
throw new Error(`${logger_1.NX_PREFIX} The {workspaceRoot} token is only valid at the beginning of an option. (${key})`);
}
value = value.replace('{projectRoot}', project.root);
result[opt] = value.replace('{projectName}', project.name);
}
else if (typeof value === 'object' && value) {
result[opt] = resolvePathTokensInOptions(value, project, [key, opt].join('.'));
}
}
return result;
}
function readTargetDefaultsForTarget(targetName, targetDefaults, executor) {
if (executor) {
// If an executor is defined in project.json, defaults should be read
// from the most specific key that matches that executor.
// e.g. If executor === run-commands, and the target is named build:
// Use, use nx:run-commands if it is present
// If not, use build if it is present.
const key = [executor, targetName].find((x) => targetDefaults === null || targetDefaults === void 0 ? void 0 : targetDefaults[x]);
return key ? targetDefaults === null || targetDefaults === void 0 ? void 0 : targetDefaults[key] : null;
}
else {
// If the executor is not defined, the only key we have is the target name.
return targetDefaults === null || targetDefaults === void 0 ? void 0 : targetDefaults[targetName];
}
}
exports.readTargetDefaultsForTarget = readTargetDefaultsForTarget;
// we have to do it this way to preserve the order of properties
// not to screw up the formatting
function renamePropertyWithStableKeys(obj, from, to) {
const copy = Object.assign({}, obj);
Object.keys(obj).forEach((k) => {
delete obj[k];
});
Object.keys(copy).forEach((k) => {
if (k === from) {
obj[to] = copy[k];
}
else {
obj[k] = copy[k];
}
});
}
exports.renamePropertyWithStableKeys = renamePropertyWithStableKeys;
//# sourceMappingURL=workspaces.js.mapВыполнить команду
Для локальной разработки. Не используйте в интернете!