Project Init

This commit is contained in:
Muluhabt
2026-05-29 15:23:46 +03:00
commit 2fbc557aac
67387 changed files with 6063341 additions and 0 deletions

22
node_modules/@nx/devkit/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2017-2026 Narwhal Technologies Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

68
node_modules/@nx/devkit/README.md generated vendored Normal file
View File

@@ -0,0 +1,68 @@
<p style="text-align: center;">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-dark.svg">
<img alt="Nx - Smart Monorepos · Fast Builds" src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-light.svg" width="100%">
</picture>
</p>
<div style="text-align: center;">
[![CircleCI](https://circleci.com/gh/nrwl/nx.svg?style=svg)](https://circleci.com/gh/nrwl/nx)
[![License](https://img.shields.io/npm/l/@nx/workspace.svg?style=flat-square)]()
[![NPM Version](https://badge.fury.io/js/nx.svg)](https://www.npmjs.com/package/nx)
[![Semantic Release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)]()
[![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
[![Join the chat at https://gitter.im/nrwl-nx/community](https://badges.gitter.im/nrwl-nx/community.svg)](https://gitter.im/nrwl-nx/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
[![Join us on the Official Nx Discord Server](https://img.shields.io/discord/1143497901675401286?label=discord)](https://go.nx.dev/community)
</div>
<hr>
# Nx: Smart Monorepos · Fast Builds
Get to green PRs in half the time. Nx optimizes your builds, scales your CI, and fixes failed PRs. Built for developers and AI agents.
This package contains a set of utilities for creating Nx plugins.
## Getting Started
### Creating an Nx Workspace
**Using `npx`**
```bash
npx create-nx-workspace
```
**Using `npm init`**
```bash
npm init nx-workspace
```
**Using `yarn create`**
```bash
yarn create nx-workspace
```
### Adding Nx to an Existing Repository
Run:
```bash
npx nx@latest init
```
## Documentation & Resources
- [Nx.Dev: Documentation, Guides, Tutorials](https://nx.dev)
- [Intro to Nx](https://nx.dev/getting-started/intro)
- [Official Nx YouTube Channel](https://www.youtube.com/@NxDevtools)
- [Blog Posts About Nx](https://nx.dev/blog)
<p style="text-align: center;"><a href="https://nx.dev/#learning-materials" target="_blank" rel="noreferrer"><img src="https://raw.githubusercontent.com/nrwl/nx/master/images/nx-courses-and-videos.svg"
width="100%" alt="Nx - Smart Monorepos · Fast Builds"></a></p>

15
node_modules/@nx/devkit/assets.json generated vendored Normal file
View File

@@ -0,0 +1,15 @@
{
"outDir": "dist/packages/devkit",
"assets": [
{
"glob": "**/files/**"
},
{
"glob": "**/files/**/.gitkeep"
},
{
"glob": "src/**/schema.d.ts"
},
"LICENSE"
]
}

15
node_modules/@nx/devkit/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,15 @@
/**
* The Nx Devkit is the underlying technology used to customize Nx to support
* different technologies and custom use-cases. It contains many utility
* functions for reading and writing files, updating configuration,
* working with Abstract Syntax Trees(ASTs), and more.
*
* As with most things in Nx, the core of Nx Devkit is very simple.
* It only uses language primitives and immutable objects
* (the tree being the only exception).
*
* @module @nx/devkit
*/
export * from 'nx/src/devkit-exports';
export * from './public-api';
//# sourceMappingURL=index.d.ts.map

1
node_modules/@nx/devkit/index.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../packages/devkit/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,cAAc,uBAAuB,CAAC;AACtC,cAAc,cAAc,CAAC"}

17
node_modules/@nx/devkit/index.js generated vendored Normal file
View File

@@ -0,0 +1,17 @@
"use strict";
/**
* The Nx Devkit is the underlying technology used to customize Nx to support
* different technologies and custom use-cases. It contains many utility
* functions for reading and writing files, updating configuration,
* working with Abstract Syntax Trees(ASTs), and more.
*
* As with most things in Nx, the core of Nx Devkit is very simple.
* It only uses language primitives and immutable objects
* (the tree being the only exception).
*
* @module @nx/devkit
*/
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("nx/src/devkit-exports"), exports);
tslib_1.__exportStar(require("./public-api"), exports);

4
node_modules/@nx/devkit/internal.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
export { signalToCode, createProjectRootMappingsFromProjectConfigurations, PluginCache, safeWriteFileCache, } from 'nx/src/devkit-internals';
export { AggregatedLog } from './src/generators/plugin-migrations/aggregate-log-util';
export { loadConfigFile, clearRequireCache } from './src/utils/config-utils';
//# sourceMappingURL=internal.d.ts.map

1
node_modules/@nx/devkit/internal.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"internal.d.ts","sourceRoot":"","sources":["../../../packages/devkit/internal.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,YAAY,EACZ,kDAAkD,EAClD,WAAW,EACX,kBAAkB,GACnB,MAAM,yBAAyB,CAAC;AAEjC,OAAO,EAAE,aAAa,EAAE,MAAM,uDAAuD,CAAC;AACtF,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC"}

13
node_modules/@nx/devkit/internal.js generated vendored Normal file
View File

@@ -0,0 +1,13 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.clearRequireCache = exports.loadConfigFile = exports.AggregatedLog = exports.safeWriteFileCache = exports.PluginCache = exports.createProjectRootMappingsFromProjectConfigurations = exports.signalToCode = void 0;
var devkit_internals_1 = require("nx/src/devkit-internals");
Object.defineProperty(exports, "signalToCode", { enumerable: true, get: function () { return devkit_internals_1.signalToCode; } });
Object.defineProperty(exports, "createProjectRootMappingsFromProjectConfigurations", { enumerable: true, get: function () { return devkit_internals_1.createProjectRootMappingsFromProjectConfigurations; } });
Object.defineProperty(exports, "PluginCache", { enumerable: true, get: function () { return devkit_internals_1.PluginCache; } });
Object.defineProperty(exports, "safeWriteFileCache", { enumerable: true, get: function () { return devkit_internals_1.safeWriteFileCache; } });
var aggregate_log_util_1 = require("./src/generators/plugin-migrations/aggregate-log-util");
Object.defineProperty(exports, "AggregatedLog", { enumerable: true, get: function () { return aggregate_log_util_1.AggregatedLog; } });
var config_utils_1 = require("./src/utils/config-utils");
Object.defineProperty(exports, "loadConfigFile", { enumerable: true, get: function () { return config_utils_1.loadConfigFile; } });
Object.defineProperty(exports, "clearRequireCache", { enumerable: true, get: function () { return config_utils_1.clearRequireCache; } });

5
node_modules/@nx/devkit/migrations.json generated vendored Normal file
View File

@@ -0,0 +1,5 @@
{
"generators": {},
"packageJsonUpdates": {},
"version": "0.1"
}

5
node_modules/@nx/devkit/ngcli-adapter.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
/**
* @category Ng CLI Adapter
*/
export { wrapAngularDevkitSchematic, mockSchematicsForTesting, NxScopedHost, } from 'nx/src/adapter/ngcli-adapter';
//# sourceMappingURL=ngcli-adapter.d.ts.map

1
node_modules/@nx/devkit/ngcli-adapter.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"ngcli-adapter.d.ts","sourceRoot":"","sources":["../../../packages/devkit/ngcli-adapter.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EACL,0BAA0B,EAC1B,wBAAwB,EACxB,YAAY,GACb,MAAM,8BAA8B,CAAC"}

11
node_modules/@nx/devkit/ngcli-adapter.js generated vendored Normal file
View File

@@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.NxScopedHost = exports.mockSchematicsForTesting = exports.wrapAngularDevkitSchematic = void 0;
/**
* @category Ng CLI Adapter
*/
// eslint-disable-next-line @typescript-eslint/no-restricted-imports
var ngcli_adapter_1 = require("nx/src/adapter/ngcli-adapter");
Object.defineProperty(exports, "wrapAngularDevkitSchematic", { enumerable: true, get: function () { return ngcli_adapter_1.wrapAngularDevkitSchematic; } });
Object.defineProperty(exports, "mockSchematicsForTesting", { enumerable: true, get: function () { return ngcli_adapter_1.mockSchematicsForTesting; } });
Object.defineProperty(exports, "NxScopedHost", { enumerable: true, get: function () { return ngcli_adapter_1.NxScopedHost; } });

53
node_modules/@nx/devkit/package.json generated vendored Normal file
View File

@@ -0,0 +1,53 @@
{
"name": "@nx/devkit",
"version": "22.7.5",
"private": false,
"description": "The Nx Devkit is used to customize Nx for different technologies and use cases. It contains many utility functions for reading and writing files, updating configuration, working with Abstract Syntax Trees(ASTs), and more. Learn more about [extending Nx by leveraging the Nx Devkit](https://nx.dev/extending-nx/intro/getting-started) on our docs.",
"repository": {
"type": "git",
"url": "https://github.com/nrwl/nx.git",
"directory": "packages/devkit"
},
"keywords": [
"Monorepo",
"Angular",
"React",
"Web",
"Node",
"Nest",
"Jest",
"Cypress",
"CLI"
],
"main": "./index.js",
"type": "commonjs",
"types": "./index.d.ts",
"author": "Victor Savkin",
"license": "MIT",
"bugs": {
"url": "https://github.com/nrwl/nx/issues"
},
"homepage": "https://nx.dev",
"dependencies": {
"@zkochan/js-yaml": "0.0.7",
"ejs": "5.0.1",
"tslib": "^2.3.0",
"semver": "^7.6.3",
"yargs-parser": "21.1.1",
"minimatch": "10.2.5",
"enquirer": "~2.3.6"
},
"devDependencies": {
"jest": "30.3.0",
"nx": "22.7.5"
},
"peerDependencies": {
"nx": ">= 21 <= 23 || ^22.0.0-0"
},
"publishConfig": {
"access": "public"
},
"nx-migrations": {
"migrations": "./migrations.json"
}
}

14
node_modules/@nx/devkit/project.json generated vendored Normal file
View File

@@ -0,0 +1,14 @@
{
"name": "devkit",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "packages/devkit",
"projectType": "library",
"targets": {
"build": {
"outputs": ["{workspaceRoot}/dist/packages/devkit/README.md"],
"command": "node ./scripts/copy-readme.js devkit",
"inputs": ["copyReadme"],
"dependsOn": ["^build", "build-base"]
}
}
}

79
node_modules/@nx/devkit/public-api.d.ts generated vendored Normal file
View File

@@ -0,0 +1,79 @@
/**
* Note to developers: STOP! This is the Public API of @nx/devkit.
* @nx/devkit should be compatible with versions of Nx 1 major version prior.
* This is so that plugins can use the latest @nx/devkit while their users may use versions +/- 1 of Nx.
*
* 1. Try hard to not add to this API to reduce the surface area we need to maintain.
* 2. Do not add newly created paths from the nx package to this file as they will not be available in older versions of Nx.
* a. We might need to duplicate code instead of importing from nx until all supported versions of nx contain the file.
*/
/**
* @category Generators
*/
export { formatFiles } from './src/generators/format-files';
/**
* @category Generators
*/
export { generateFiles, OverwriteStrategy, } from './src/generators/generate-files';
/**
* @category Generators
*/
export { toJS, ToJSOptions } from './src/generators/to-js';
/**
* @category Generators
*/
export { updateTsConfigsToJs } from './src/generators/update-ts-configs-to-js';
/**
* @category Generators
*/
export { runTasksInSerial } from './src/generators/run-tasks-in-serial';
/**
* @category Generators
*/
export { visitNotIgnoredFiles } from './src/generators/visit-not-ignored-files';
export { parseTargetString, targetToTargetString, } from './src/executors/parse-target-string';
/**
* @category Executors
*/
export { readTargetOptions } from './src/executors/read-target-options';
/**
* @category Utils
*/
export { addDependenciesToPackageJson, removeDependenciesFromPackageJson, ensurePackage, getDependencyVersionFromPackageJson, NX_VERSION, } from './src/utils/package-json';
/**
* @category Utils
*/
export { installPackagesTask } from './src/tasks/install-packages-task';
/**
* @category Utils
*/
export { names } from './src/utils/names';
/**
* @category Utils
*/
export { getWorkspaceLayout, extractLayoutDirectory, } from './src/utils/get-workspace-layout';
/**
* @category Utils
*/
export type { StringChange, StringDeletion, StringInsertion, } from './src/utils/string-change';
/**
* @category Utils
*/
export { applyChangesToString, ChangeType } from './src/utils/string-change';
/**
* @category Utils
*/
export { offsetFromRoot } from './src/utils/offset-from-root';
/**
* @category Utils
*/
export { convertNxGenerator } from './src/utils/invoke-nx-generator';
/**
* @category Utils
*/
export { convertNxExecutor } from './src/utils/convert-nx-executor';
/**
* @category Utils
*/
export { moveFilesToNewDirectory } from './src/utils/move-dir';
//# sourceMappingURL=public-api.d.ts.map

1
node_modules/@nx/devkit/public-api.d.ts.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"public-api.d.ts","sourceRoot":"","sources":["../../../packages/devkit/public-api.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAEH;;GAEG;AACH,OAAO,EAAE,WAAW,EAAE,MAAM,+BAA+B,CAAC;AAE5D;;GAEG;AACH,OAAO,EACL,aAAa,EACb,iBAAiB,GAClB,MAAM,iCAAiC,CAAC;AAEzC;;GAEG;AACH,OAAO,EAAE,IAAI,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAE3D;;GAEG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,0CAA0C,CAAC;AAE/E;;GAEG;AACH,OAAO,EAAE,gBAAgB,EAAE,MAAM,sCAAsC,CAAC;AAExE;;GAEG;AACH,OAAO,EAAE,oBAAoB,EAAE,MAAM,0CAA0C,CAAC;AAEhF,OAAO,EACL,iBAAiB,EACjB,oBAAoB,GACrB,MAAM,qCAAqC,CAAC;AAE7C;;GAEG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,qCAAqC,CAAC;AAExE;;GAEG;AACH,OAAO,EACL,4BAA4B,EAC5B,iCAAiC,EACjC,aAAa,EACb,mCAAmC,EACnC,UAAU,GACX,MAAM,0BAA0B,CAAC;AAElC;;GAEG;AACH,OAAO,EAAE,mBAAmB,EAAE,MAAM,mCAAmC,CAAC;AAExE;;GAEG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,mBAAmB,CAAC;AAE1C;;GAEG;AACH,OAAO,EACL,kBAAkB,EAClB,sBAAsB,GACvB,MAAM,kCAAkC,CAAC;AAE1C;;GAEG;AACH,YAAY,EACV,YAAY,EACZ,cAAc,EACd,eAAe,GAChB,MAAM,2BAA2B,CAAC;AAEnC;;GAEG;AACH,OAAO,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAE7E;;GAEG;AACH,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAE9D;;GAEG;AACH,OAAO,EAAE,kBAAkB,EAAE,MAAM,iCAAiC,CAAC;AAErE;;GAEG;AACH,OAAO,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AAEpE;;GAEG;AACH,OAAO,EAAE,uBAAuB,EAAE,MAAM,sBAAsB,CAAC"}

102
node_modules/@nx/devkit/public-api.js generated vendored Normal file
View File

@@ -0,0 +1,102 @@
"use strict";
/**
* Note to developers: STOP! This is the Public API of @nx/devkit.
* @nx/devkit should be compatible with versions of Nx 1 major version prior.
* This is so that plugins can use the latest @nx/devkit while their users may use versions +/- 1 of Nx.
*
* 1. Try hard to not add to this API to reduce the surface area we need to maintain.
* 2. Do not add newly created paths from the nx package to this file as they will not be available in older versions of Nx.
* a. We might need to duplicate code instead of importing from nx until all supported versions of nx contain the file.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.moveFilesToNewDirectory = exports.convertNxExecutor = exports.convertNxGenerator = exports.offsetFromRoot = exports.ChangeType = exports.applyChangesToString = exports.extractLayoutDirectory = exports.getWorkspaceLayout = exports.names = exports.installPackagesTask = exports.NX_VERSION = exports.getDependencyVersionFromPackageJson = exports.ensurePackage = exports.removeDependenciesFromPackageJson = exports.addDependenciesToPackageJson = exports.readTargetOptions = exports.targetToTargetString = exports.parseTargetString = exports.visitNotIgnoredFiles = exports.runTasksInSerial = exports.updateTsConfigsToJs = exports.toJS = exports.OverwriteStrategy = exports.generateFiles = exports.formatFiles = void 0;
/**
* @category Generators
*/
var format_files_1 = require("./src/generators/format-files");
Object.defineProperty(exports, "formatFiles", { enumerable: true, get: function () { return format_files_1.formatFiles; } });
/**
* @category Generators
*/
var generate_files_1 = require("./src/generators/generate-files");
Object.defineProperty(exports, "generateFiles", { enumerable: true, get: function () { return generate_files_1.generateFiles; } });
Object.defineProperty(exports, "OverwriteStrategy", { enumerable: true, get: function () { return generate_files_1.OverwriteStrategy; } });
/**
* @category Generators
*/
var to_js_1 = require("./src/generators/to-js");
Object.defineProperty(exports, "toJS", { enumerable: true, get: function () { return to_js_1.toJS; } });
/**
* @category Generators
*/
var update_ts_configs_to_js_1 = require("./src/generators/update-ts-configs-to-js");
Object.defineProperty(exports, "updateTsConfigsToJs", { enumerable: true, get: function () { return update_ts_configs_to_js_1.updateTsConfigsToJs; } });
/**
* @category Generators
*/
var run_tasks_in_serial_1 = require("./src/generators/run-tasks-in-serial");
Object.defineProperty(exports, "runTasksInSerial", { enumerable: true, get: function () { return run_tasks_in_serial_1.runTasksInSerial; } });
/**
* @category Generators
*/
var visit_not_ignored_files_1 = require("./src/generators/visit-not-ignored-files");
Object.defineProperty(exports, "visitNotIgnoredFiles", { enumerable: true, get: function () { return visit_not_ignored_files_1.visitNotIgnoredFiles; } });
var parse_target_string_1 = require("./src/executors/parse-target-string");
Object.defineProperty(exports, "parseTargetString", { enumerable: true, get: function () { return parse_target_string_1.parseTargetString; } });
Object.defineProperty(exports, "targetToTargetString", { enumerable: true, get: function () { return parse_target_string_1.targetToTargetString; } });
/**
* @category Executors
*/
var read_target_options_1 = require("./src/executors/read-target-options");
Object.defineProperty(exports, "readTargetOptions", { enumerable: true, get: function () { return read_target_options_1.readTargetOptions; } });
/**
* @category Utils
*/
var package_json_1 = require("./src/utils/package-json");
Object.defineProperty(exports, "addDependenciesToPackageJson", { enumerable: true, get: function () { return package_json_1.addDependenciesToPackageJson; } });
Object.defineProperty(exports, "removeDependenciesFromPackageJson", { enumerable: true, get: function () { return package_json_1.removeDependenciesFromPackageJson; } });
Object.defineProperty(exports, "ensurePackage", { enumerable: true, get: function () { return package_json_1.ensurePackage; } });
Object.defineProperty(exports, "getDependencyVersionFromPackageJson", { enumerable: true, get: function () { return package_json_1.getDependencyVersionFromPackageJson; } });
Object.defineProperty(exports, "NX_VERSION", { enumerable: true, get: function () { return package_json_1.NX_VERSION; } });
/**
* @category Utils
*/
var install_packages_task_1 = require("./src/tasks/install-packages-task");
Object.defineProperty(exports, "installPackagesTask", { enumerable: true, get: function () { return install_packages_task_1.installPackagesTask; } });
/**
* @category Utils
*/
var names_1 = require("./src/utils/names");
Object.defineProperty(exports, "names", { enumerable: true, get: function () { return names_1.names; } });
/**
* @category Utils
*/
var get_workspace_layout_1 = require("./src/utils/get-workspace-layout");
Object.defineProperty(exports, "getWorkspaceLayout", { enumerable: true, get: function () { return get_workspace_layout_1.getWorkspaceLayout; } });
Object.defineProperty(exports, "extractLayoutDirectory", { enumerable: true, get: function () { return get_workspace_layout_1.extractLayoutDirectory; } });
/**
* @category Utils
*/
var string_change_1 = require("./src/utils/string-change");
Object.defineProperty(exports, "applyChangesToString", { enumerable: true, get: function () { return string_change_1.applyChangesToString; } });
Object.defineProperty(exports, "ChangeType", { enumerable: true, get: function () { return string_change_1.ChangeType; } });
/**
* @category Utils
*/
var offset_from_root_1 = require("./src/utils/offset-from-root");
Object.defineProperty(exports, "offsetFromRoot", { enumerable: true, get: function () { return offset_from_root_1.offsetFromRoot; } });
/**
* @category Utils
*/
var invoke_nx_generator_1 = require("./src/utils/invoke-nx-generator");
Object.defineProperty(exports, "convertNxGenerator", { enumerable: true, get: function () { return invoke_nx_generator_1.convertNxGenerator; } });
/**
* @category Utils
*/
var convert_nx_executor_1 = require("./src/utils/convert-nx-executor");
Object.defineProperty(exports, "convertNxExecutor", { enumerable: true, get: function () { return convert_nx_executor_1.convertNxExecutor; } });
/**
* @category Utils
*/
var move_dir_1 = require("./src/utils/move-dir");
Object.defineProperty(exports, "moveFilesToNewDirectory", { enumerable: true, get: function () { return move_dir_1.moveFilesToNewDirectory; } });

View File

@@ -0,0 +1,39 @@
import { ExecutorContext, ProjectGraph, Target } from 'nx/src/devkit-exports';
/**
* Parses a target string into {project, target, configuration}
*
* Examples:
* ```typescript
* parseTargetString("proj:test", graph) // returns { project: "proj", target: "test" }
* parseTargetString("proj:test:production", graph) // returns { project: "proj", target: "test", configuration: "production" }
* ```
*
* @param targetString - target reference
*/
export declare function parseTargetString(targetString: string, projectGraph: ProjectGraph): Target;
/**
* Parses a target string into {project, target, configuration}. Passing a full
* {@link ExecutorContext} enables the targetString to reference the current project.
*
* Examples:
* ```typescript
* parseTargetString("test", executorContext) // returns { project: "proj", target: "test" }
* parseTargetString("proj:test", executorContext) // returns { project: "proj", target: "test" }
* parseTargetString("proj:test:production", executorContext) // returns { project: "proj", target: "test", configuration: "production" }
* ```
*/
export declare function parseTargetString(targetString: string, ctx: ExecutorContext): Target;
/**
* Returns a string in the format "project:target[:configuration]" for the target
*
* @param target - target object
*
* Examples:
*
* ```typescript
* targetToTargetString({ project: "proj", target: "test" }) // returns "proj:test"
* targetToTargetString({ project: "proj", target: "test", configuration: "production" }) // returns "proj:test:production"
* ```
*/
export declare function targetToTargetString({ project, target, configuration, }: Target): string;
//# sourceMappingURL=parse-target-string.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"parse-target-string.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/executors/parse-target-string.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,eAAe,EACf,YAAY,EAEZ,MAAM,EACP,MAAM,uBAAuB,CAAC;AAG/B;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,YAAY,EAAE,MAAM,EACpB,YAAY,EAAE,YAAY,GACzB,MAAM,CAAC;AACV;;;;;;;;;;GAUG;AACH,wBAAgB,iBAAiB,CAC/B,YAAY,EAAE,MAAM,EACpB,GAAG,EAAE,eAAe,GACnB,MAAM,CAAC;AAiDV;;;;;;;;;;;GAWG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,OAAO,EACP,MAAM,EACN,aAAa,GACd,EAAE,MAAM,GAAG,MAAM,CAIjB"}

View File

@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseTargetString = parseTargetString;
exports.targetToTargetString = targetToTargetString;
const devkit_exports_1 = require("nx/src/devkit-exports");
const devkit_internals_1 = require("nx/src/devkit-internals");
function parseTargetString(targetString, projectGraphOrCtx) {
let projectGraph = projectGraphOrCtx && 'projectGraph' in projectGraphOrCtx
? projectGraphOrCtx.projectGraph
: projectGraphOrCtx;
if (!projectGraph) {
try {
projectGraph = (0, devkit_exports_1.readCachedProjectGraph)();
}
catch (e) {
projectGraph = { nodes: {} };
}
}
const [maybeProject] = (0, devkit_internals_1.splitByColons)(targetString);
if (!projectGraph.nodes[maybeProject] &&
projectGraphOrCtx &&
'projectName' in projectGraphOrCtx &&
maybeProject !== projectGraphOrCtx.projectName) {
targetString = `${projectGraphOrCtx.projectName}:${targetString}`;
}
const currentProject = projectGraphOrCtx && 'projectName' in projectGraphOrCtx
? projectGraphOrCtx.projectName
: undefined;
const [project, target, configuration] = (0, devkit_internals_1.splitTarget)(targetString, projectGraph, { currentProject });
if (!project || !target) {
throw new Error(`Invalid Target String: ${targetString}`);
}
return {
project,
target,
configuration,
};
}
/**
* Returns a string in the format "project:target[:configuration]" for the target
*
* @param target - target object
*
* Examples:
*
* ```typescript
* targetToTargetString({ project: "proj", target: "test" }) // returns "proj:test"
* targetToTargetString({ project: "proj", target: "test", configuration: "production" }) // returns "proj:test:production"
* ```
*/
function targetToTargetString({ project, target, configuration, }) {
return `${project}:${target.indexOf(':') > -1 ? `"${target}"` : target}${configuration !== undefined ? ':' + configuration : ''}`;
}

View File

@@ -0,0 +1,8 @@
import type { ExecutorContext, Target } from 'nx/src/devkit-exports';
/**
* Reads and combines options for a given target.
*
* Works as if you invoked the target yourself without passing any command lint overrides.
*/
export declare function readTargetOptions<T = any>({ project, target, configuration }: Target, context: ExecutorContext): T;
//# sourceMappingURL=read-target-options.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"read-target-options.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/executors/read-target-options.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,uBAAuB,CAAC;AASrE;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,CAAC,GAAG,GAAG,EACvC,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,EAAE,MAAM,EAC1C,OAAO,EAAE,eAAe,GACvB,CAAC,CAsCH"}

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.readTargetOptions = readTargetOptions;
const path_1 = require("path");
const devkit_internals_1 = require("nx/src/devkit-internals");
/**
* Reads and combines options for a given target.
*
* Works as if you invoked the target yourself without passing any command lint overrides.
*/
function readTargetOptions({ project, target, configuration }, context) {
const projectConfiguration = context.projectsConfigurations.projects[project];
if (!projectConfiguration) {
throw new Error(`Unable to find project ${project}`);
}
const targetConfiguration = projectConfiguration.targets[target];
if (!targetConfiguration) {
throw new Error(`Unable to find target ${target} for project ${project}`);
}
const [nodeModule, executorName] = (0, devkit_internals_1.parseExecutor)(targetConfiguration.executor);
const { schema } = (0, devkit_internals_1.getExecutorInformation)(nodeModule, executorName, context.root, context.projectsConfigurations?.projects);
const defaultProject = (0, devkit_internals_1.calculateDefaultProjectName)(context.cwd, context.root, { version: 2, projects: context.projectsConfigurations.projects }, context.nxJsonConfiguration);
return (0, devkit_internals_1.combineOptionsForExecutor)({}, configuration ?? targetConfiguration.defaultConfiguration ?? '', targetConfiguration, schema, defaultProject, (0, path_1.relative)(context.root, context.cwd));
}

View File

@@ -0,0 +1,55 @@
import { type Tree } from 'nx/src/devkit-exports';
export type ArtifactGenerationOptions = {
path: string;
name?: string;
fileExtension?: string;
suffix?: string;
suffixSeparator?: string;
allowedFileExtensions?: string[];
/**
* @deprecated Provide the full file path including the file extension in the `path` option. This option will be removed in Nx v21.
*/
js?: boolean;
/**
* @deprecated Provide the full file path including the file extension in the `path` option. This option will be removed in Nx v21.
*/
jsOptionName?: string;
};
export type FileExtensionType = 'js' | 'ts' | 'other';
export type NameAndDirectoryOptions = {
/**
* Normalized artifact name.
*/
artifactName: string;
/**
* Normalized directory path where the artifact will be generated.
*/
directory: string;
/**
* Normalized file name of the artifact without the extension.
*/
fileName: string;
/**
* Normalized file extension.
*/
fileExtension: string;
/**
* Normalized file extension type.
*/
fileExtensionType: FileExtensionType;
/**
* Normalized full file path of the artifact.
*/
filePath: string;
/**
* Project name where the artifact will be generated.
*/
project: string;
};
export declare function determineArtifactNameAndDirectoryOptions(tree: Tree, options: ArtifactGenerationOptions): Promise<NameAndDirectoryOptions>;
export declare function getRelativeCwd(): string;
/**
* Function for setting cwd during testing
*/
export declare function setCwd(path: string): void;
//# sourceMappingURL=artifact-name-and-directory-utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"artifact-name-and-directory-utils.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/artifact-name-and-directory-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,IAAI,EACV,MAAM,uBAAuB,CAAC;AAe/B,MAAM,MAAM,yBAAyB,GAAG;IACtC,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,qBAAqB,CAAC,EAAE,MAAM,EAAE,CAAC;IACjC;;OAEG;IACH,EAAE,CAAC,EAAE,OAAO,CAAC;IACb;;OAEG;IACH,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,iBAAiB,GAAG,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC;AACtD,MAAM,MAAM,uBAAuB,GAAG;IACpC;;OAEG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;OAEG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,aAAa,EAAE,MAAM,CAAC;IACtB;;OAEG;IACH,iBAAiB,EAAE,iBAAiB,CAAC;IACrC;;OAEG;IACH,QAAQ,EAAE,MAAM,CAAC;IACjB;;OAEG;IACH,OAAO,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF,wBAAsB,wCAAwC,CAC5D,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,yBAAyB,GACjC,OAAO,CAAC,uBAAuB,CAAC,CASlC;AAqFD,wBAAgB,cAAc,IAAI,MAAM,CAEvC;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAEzC"}

View File

@@ -0,0 +1,123 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.determineArtifactNameAndDirectoryOptions = determineArtifactNameAndDirectoryOptions;
exports.getRelativeCwd = getRelativeCwd;
exports.setCwd = setCwd;
const devkit_exports_1 = require("nx/src/devkit-exports");
const devkit_internals_1 = require("nx/src/devkit-internals");
const path_1 = require("path");
const DEFAULT_ALLOWED_JS_FILE_EXTENSIONS = ['js', 'cjs', 'mjs', 'jsx'];
const DEFAULT_ALLOWED_TS_FILE_EXTENSIONS = ['ts', 'cts', 'mts', 'tsx'];
const DEFAULT_ALLOWED_FILE_EXTENSIONS = [
...DEFAULT_ALLOWED_JS_FILE_EXTENSIONS,
...DEFAULT_ALLOWED_TS_FILE_EXTENSIONS,
'vue',
];
async function determineArtifactNameAndDirectoryOptions(tree, options) {
const normalizedOptions = getNameAndDirectoryOptions(tree, options);
validateResolvedProject(normalizedOptions.project, normalizedOptions.directory);
return normalizedOptions;
}
function getNameAndDirectoryOptions(tree, options) {
const path = options.path
? (0, devkit_exports_1.normalizePath)(options.path.replace(/^\.?\//, ''))
: undefined;
let { name: extractedName, directory } = extractNameAndDirectoryFromPath(path);
const relativeCwd = getRelativeCwd();
// append the directory to the current working directory if it doesn't start with it
if (directory !== relativeCwd && !directory.startsWith(`${relativeCwd}/`)) {
directory = (0, devkit_exports_1.joinPathFragments)(relativeCwd, directory);
}
const project = findProjectFromPath(tree, directory);
let fileName = extractedName;
let fileExtension = options.fileExtension ?? 'ts';
const allowedFileExtensions = options.allowedFileExtensions ?? DEFAULT_ALLOWED_FILE_EXTENSIONS;
const fileExtensionRegex = new RegExp(`\\.(${allowedFileExtensions.join('|')})$`);
const fileExtensionMatch = fileName.match(fileExtensionRegex);
if (fileExtensionMatch) {
fileExtension = fileExtensionMatch[1];
fileName = fileName.replace(fileExtensionRegex, '');
extractedName = fileName;
}
else if (options.suffix) {
fileName = `${fileName}${options.suffixSeparator ?? '.'}${options.suffix}`;
}
const filePath = (0, devkit_exports_1.joinPathFragments)(directory, `${fileName}.${fileExtension}`);
const fileExtensionType = getFileExtensionType(fileExtension);
validateFileExtension(fileExtension, allowedFileExtensions, options.js, options.jsOptionName);
return {
artifactName: options.name ?? extractedName,
directory,
fileName,
fileExtension,
fileExtensionType,
filePath,
project,
};
}
function validateResolvedProject(project, normalizedDirectory) {
if (project) {
return;
}
throw new Error(`The provided directory resolved relative to the current working directory "${normalizedDirectory}" does not exist under any project root. ` +
`Please make sure to navigate to a location or provide a directory that exists under a project root.`);
}
function findProjectFromPath(tree, path) {
const projectConfigurations = {};
const projects = (0, devkit_exports_1.getProjects)(tree);
for (const [projectName, project] of projects) {
projectConfigurations[projectName] = project;
}
const projectRootMappings = (0, devkit_internals_1.createProjectRootMappingsFromProjectConfigurations)(projectConfigurations);
return (0, devkit_internals_1.findProjectForPath)(path, projectRootMappings);
}
function getRelativeCwd() {
return (0, devkit_exports_1.normalizePath)((0, path_1.relative)(devkit_exports_1.workspaceRoot, getCwd()));
}
/**
* Function for setting cwd during testing
*/
function setCwd(path) {
process.env.INIT_CWD = (0, path_1.join)(devkit_exports_1.workspaceRoot, path);
}
function getCwd() {
return process.env.INIT_CWD?.startsWith(devkit_exports_1.workspaceRoot)
? process.env.INIT_CWD
: process.cwd();
}
function extractNameAndDirectoryFromPath(path) {
// Remove trailing slash
path = path.replace(/\/$/, '');
const parsedPath = (0, devkit_exports_1.normalizePath)(path).split('/');
const name = parsedPath.pop();
const directory = parsedPath.join('/');
return { name, directory };
}
function getFileExtensionType(fileExtension) {
if (DEFAULT_ALLOWED_JS_FILE_EXTENSIONS.includes(fileExtension)) {
return 'js';
}
if (DEFAULT_ALLOWED_TS_FILE_EXTENSIONS.includes(fileExtension)) {
return 'ts';
}
return 'other';
}
function validateFileExtension(fileExtension, allowedFileExtensions, js, jsOptionName) {
const fileExtensionType = getFileExtensionType(fileExtension);
if (!allowedFileExtensions.includes(fileExtension)) {
throw new Error(`The provided file path has an extension (.${fileExtension}) that is not supported by this generator.
The supported extensions are: ${allowedFileExtensions
.map((ext) => `.${ext}`)
.join(', ')}.`);
}
if (js !== undefined) {
jsOptionName = jsOptionName ?? 'js';
if (js && fileExtensionType === 'ts') {
throw new Error(`The provided file path has an extension (.${fileExtension}) that conflicts with the provided "--${jsOptionName}" option.`);
}
if (!js && fileExtensionType === 'js') {
throw new Error(`The provided file path has an extension (.${fileExtension}) that conflicts with the provided "--${jsOptionName}" option.`);
}
}
return fileExtensionType;
}

View File

@@ -0,0 +1,24 @@
import { type Tree } from 'nx/src/devkit-exports';
interface E2EWebServerDefaultValues {
defaultServeTargetName: string;
defaultServeStaticTargetName: string;
defaultE2EWebServerAddress: string;
defaultE2ECiBaseUrl: string;
defaultE2EPort: number;
}
interface E2EWebServerPluginOptions {
plugin: string;
configFilePath: string;
serveTargetName: string;
serveStaticTargetName: string;
}
export interface E2EWebServerDetails {
e2eWebServerAddress: string;
e2eWebServerCommand: string;
e2eCiWebServerCommand: string;
e2eCiBaseUrl: string;
e2eDevServerTarget: string;
}
export declare function getE2EWebServerInfo(tree: Tree, projectName: string, pluginOptions: E2EWebServerPluginOptions, defaultValues: E2EWebServerDefaultValues, isPluginBeingAdded: boolean): Promise<E2EWebServerDetails>;
export {};
//# sourceMappingURL=e2e-web-server-info-utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"e2e-web-server-info-utils.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/e2e-web-server-info-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,IAAI,EAIV,MAAM,uBAAuB,CAAC;AAI/B,UAAU,yBAAyB;IACjC,sBAAsB,EAAE,MAAM,CAAC;IAC/B,4BAA4B,EAAE,MAAM,CAAC;IACrC,0BAA0B,EAAE,MAAM,CAAC;IACnC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,cAAc,EAAE,MAAM,CAAC;CACxB;AAED,UAAU,yBAAyB;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,EAAE,MAAM,CAAC;IACvB,eAAe,EAAE,MAAM,CAAC;IACxB,qBAAqB,EAAE,MAAM,CAAC;CAC/B;AAED,MAAM,WAAW,mBAAmB;IAClC,mBAAmB,EAAE,MAAM,CAAC;IAC5B,mBAAmB,EAAE,MAAM,CAAC;IAC5B,qBAAqB,EAAE,MAAM,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,kBAAkB,EAAE,MAAM,CAAC;CAC5B;AAED,wBAAsB,mBAAmB,CACvC,IAAI,EAAE,IAAI,EACV,WAAW,EAAE,MAAM,EACnB,aAAa,EAAE,yBAAyB,EACxC,aAAa,EAAE,yBAAyB,EACxC,kBAAkB,EAAE,OAAO,GAC1B,OAAO,CAAC,mBAAmB,CAAC,CAmB9B"}

View File

@@ -0,0 +1,55 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getE2EWebServerInfo = getE2EWebServerInfo;
const devkit_exports_1 = require("nx/src/devkit-exports");
const find_plugin_for_config_file_1 = require("../utils/find-plugin-for-config-file");
async function getE2EWebServerInfo(tree, projectName, pluginOptions, defaultValues, isPluginBeingAdded) {
const pm = (0, devkit_exports_1.getPackageManagerCommand)((0, devkit_exports_1.detectPackageManager)(tree.root));
if (isPluginBeingAdded) {
return await getE2EWebServerInfoForPlugin(tree, projectName, pluginOptions, defaultValues, pm);
}
else {
return {
e2eWebServerAddress: defaultValues.defaultE2EWebServerAddress,
e2eWebServerCommand: `${pm.exec} nx run ${projectName}:${defaultValues.defaultServeTargetName}`,
e2eCiWebServerCommand: `${pm.exec} nx run ${projectName}:${defaultValues.defaultServeStaticTargetName}`,
e2eCiBaseUrl: defaultValues.defaultE2ECiBaseUrl,
e2eDevServerTarget: `${projectName}:${defaultValues.defaultServeTargetName}`,
};
}
}
async function getE2EWebServerInfoForPlugin(tree, projectName, pluginOptions, defaultValues, pm) {
const foundPlugin = await (0, find_plugin_for_config_file_1.findPluginForConfigFile)(tree, pluginOptions.plugin, pluginOptions.configFilePath);
if (!foundPlugin ||
typeof foundPlugin === 'string' ||
!foundPlugin?.options) {
return {
e2eWebServerAddress: defaultValues.defaultE2EWebServerAddress,
e2eWebServerCommand: `${pm.exec} nx run ${projectName}:${defaultValues.defaultServeTargetName}`,
e2eCiWebServerCommand: `${pm.exec} nx run ${projectName}:${defaultValues.defaultServeStaticTargetName}`,
e2eCiBaseUrl: defaultValues.defaultE2ECiBaseUrl,
e2eDevServerTarget: `${projectName}:${defaultValues.defaultServeTargetName}`,
};
}
const nxJson = (0, devkit_exports_1.readNxJson)(tree);
let e2ePort = defaultValues.defaultE2EPort ?? 4200;
if (nxJson.targetDefaults?.[foundPlugin.options[pluginOptions.serveTargetName] ??
defaultValues.defaultServeTargetName] &&
nxJson.targetDefaults?.[foundPlugin.options[pluginOptions.serveTargetName] ??
defaultValues.defaultServeTargetName].options?.port) {
e2ePort =
nxJson.targetDefaults?.[foundPlugin.options[pluginOptions.serveTargetName] ??
defaultValues.defaultServeTargetName].options?.port;
}
const e2eWebServerAddress = defaultValues.defaultE2EWebServerAddress.replace(/:\d+/, `:${e2ePort}`);
return {
e2eWebServerAddress,
e2eWebServerCommand: `${pm.exec} nx run ${projectName}:${foundPlugin.options[pluginOptions.serveTargetName] ??
defaultValues.defaultServeTargetName}`,
e2eCiWebServerCommand: `${pm.exec} nx run ${projectName}:${foundPlugin.options[pluginOptions.serveStaticTargetName] ??
defaultValues.defaultServeStaticTargetName}`,
e2eCiBaseUrl: defaultValues.defaultE2ECiBaseUrl,
e2eDevServerTarget: `${projectName}:${foundPlugin.options[pluginOptions.serveTargetName] ??
defaultValues.defaultServeTargetName}`,
};
}

View File

@@ -0,0 +1,21 @@
import { ProjectGraph, Tree } from 'nx/src/devkit-exports';
type CallBack<T> = (currentValue: T, project: string, target: string, configuration?: string) => void;
/**
* Calls a function for each different options that an executor is configured with
*/
export declare function forEachExecutorOptions<Options>(tree: Tree,
/**
* Name of the executor to update options for
*/
executorName: string,
/**
* Callback that is called for each options configured for a builder
*/
callback: CallBack<Options>): void;
/**
* Calls a function for each different options that an executor is configured with via the project graph
* this is helpful when you need to get the expaned configuration options from the nx.json
**/
export declare function forEachExecutorOptionsInGraph<Options>(graph: ProjectGraph, executorName: string, callback: CallBack<Options>): void;
export {};
//# sourceMappingURL=executor-options-utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"executor-options-utils.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/executor-options-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,YAAY,EACZ,IAAI,EACL,MAAM,uBAAuB,CAAC;AAE/B,KAAK,QAAQ,CAAC,CAAC,IAAI,CACjB,YAAY,EAAE,CAAC,EACf,OAAO,EAAE,MAAM,EACf,MAAM,EAAE,MAAM,EACd,aAAa,CAAC,EAAE,MAAM,KACnB,IAAI,CAAC;AAEV;;GAEG;AACH,wBAAgB,sBAAsB,CAAC,OAAO,EAC5C,IAAI,EAAE,IAAI;AACV;;GAEG;AACH,YAAY,EAAE,MAAM;AACpB;;GAEG;AACH,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,GAC1B,IAAI,CAEN;AAED;;;IAGI;AACJ,wBAAgB,6BAA6B,CAAC,OAAO,EACnD,KAAK,EAAE,YAAY,EACnB,YAAY,EAAE,MAAM,EACpB,QAAQ,EAAE,QAAQ,CAAC,OAAO,CAAC,GAC1B,IAAI,CAKN"}

View File

@@ -0,0 +1,45 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.forEachExecutorOptions = forEachExecutorOptions;
exports.forEachExecutorOptionsInGraph = forEachExecutorOptionsInGraph;
const devkit_exports_1 = require("nx/src/devkit-exports");
/**
* Calls a function for each different options that an executor is configured with
*/
function forEachExecutorOptions(tree,
/**
* Name of the executor to update options for
*/
executorName,
/**
* Callback that is called for each options configured for a builder
*/
callback) {
forEachProjectConfig((0, devkit_exports_1.getProjects)(tree), executorName, callback);
}
/**
* Calls a function for each different options that an executor is configured with via the project graph
* this is helpful when you need to get the expaned configuration options from the nx.json
**/
function forEachExecutorOptionsInGraph(graph, executorName, callback) {
const projects = new Map();
Object.values(graph.nodes).forEach((p) => projects.set(p.name, p.data));
forEachProjectConfig(projects, executorName, callback);
}
function forEachProjectConfig(projects, executorName, callback) {
for (const [projectName, project] of projects) {
for (const [targetName, target] of Object.entries(project.targets || {})) {
if (executorName !== target.executor) {
continue;
}
callback(target.options ?? {}, projectName, targetName);
if (!target.configurations) {
continue;
}
Object.entries(target.configurations).forEach(([configName, options]) => {
callback(options, projectName, targetName, configName);
});
}
}
}
// TODO: add a method for updating options

View File

@@ -0,0 +1,19 @@
import { Tree } from 'nx/src/devkit-exports';
/**
* Formats all the created or updated files using Prettier
* @param tree - the file system tree
* @param options - options for the formatFiles function
*
* @remarks
* Set the environment variable `NX_SKIP_FORMAT` to `true` to skip Prettier
* formatting. This is useful for repositories that use alternative formatters
* like Biome, dprint, or have custom formatting requirements.
*
* Note: `NX_SKIP_FORMAT` only skips Prettier formatting. TSConfig path sorting
* (controlled by `sortRootTsconfigPaths` option or `NX_FORMAT_SORT_TSCONFIG_PATHS`)
* will still occur.
*/
export declare function formatFiles(tree: Tree, options?: {
sortRootTsconfigPaths?: boolean;
}): Promise<void>;
//# sourceMappingURL=format-files.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"format-files.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/format-files.ts"],"names":[],"mappings":"AAAA,OAAO,EAAY,IAAI,EAAa,MAAM,uBAAuB,CAAC;AAQlE;;;;;;;;;;;;;GAaG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,IAAI,EACV,OAAO,GAAE;IACP,qBAAqB,CAAC,EAAE,OAAO,CAAC;CAC5B,GACL,OAAO,CAAC,IAAI,CAAC,CAmEf"}

117
node_modules/@nx/devkit/src/generators/format-files.js generated vendored Normal file
View File

@@ -0,0 +1,117 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatFiles = formatFiles;
const tslib_1 = require("tslib");
const devkit_exports_1 = require("nx/src/devkit-exports");
const devkit_internals_1 = require("nx/src/devkit-internals");
const path = tslib_1.__importStar(require("path"));
/**
* Formats all the created or updated files using Prettier
* @param tree - the file system tree
* @param options - options for the formatFiles function
*
* @remarks
* Set the environment variable `NX_SKIP_FORMAT` to `true` to skip Prettier
* formatting. This is useful for repositories that use alternative formatters
* like Biome, dprint, or have custom formatting requirements.
*
* Note: `NX_SKIP_FORMAT` only skips Prettier formatting. TSConfig path sorting
* (controlled by `sortRootTsconfigPaths` option or `NX_FORMAT_SORT_TSCONFIG_PATHS`)
* will still occur.
*/
async function formatFiles(tree, options = {}) {
options.sortRootTsconfigPaths ??=
process.env.NX_FORMAT_SORT_TSCONFIG_PATHS === 'true';
if (options.sortRootTsconfigPaths) {
sortTsConfig(tree);
}
// Skip Prettier formatting if NX_SKIP_FORMAT is set
// This is checked after tsconfig sorting since sorting is a separate concern
if (process.env.NX_SKIP_FORMAT === 'true') {
return;
}
let prettier;
try {
prettier = await Promise.resolve().then(() => tslib_1.__importStar(require('prettier')));
/**
* Even after we discovered prettier in node_modules, we need to be sure that the user is intentionally using prettier
* before proceeding to format with it.
*/
if (!(0, devkit_internals_1.isUsingPrettierInTree)(tree)) {
return;
}
}
catch { }
if (!prettier)
return;
const files = new Set(tree.listChanges().filter((file) => file.type !== 'DELETE'));
const changedPrettierInTree = getChangedPrettierConfigInTree(tree);
await Promise.all(Array.from(files).map(async (file) => {
try {
const systemPath = path.join(tree.root, file.path);
const resolvedOptions = await prettier.resolveConfig(systemPath, {
editorconfig: true,
});
const options = {
...resolvedOptions,
...changedPrettierInTree,
filepath: systemPath,
};
if (file.path.endsWith('.swcrc')) {
options.parser = 'json';
}
const support = await prettier.getFileInfo(systemPath, options);
if (support.ignored || !support.inferredParser) {
return;
}
tree.write(file.path, await prettier.format(file.content.toString('utf-8'), options));
}
catch (e) {
console.warn(`Could not format ${file.path}. Error: "${e.message}"`);
}
}));
}
function sortTsConfig(tree) {
try {
const tsConfigPath = getRootTsConfigPath(tree);
if (!tsConfigPath) {
return;
}
const tsconfig = (0, devkit_exports_1.readJson)(tree, tsConfigPath);
if (!tsconfig.compilerOptions?.paths) {
// no paths to sort
return;
}
(0, devkit_exports_1.writeJson)(tree, tsConfigPath, {
...tsconfig,
compilerOptions: {
...tsconfig.compilerOptions,
paths: (0, devkit_internals_1.sortObjectByKeys)(tsconfig.compilerOptions.paths),
},
});
}
catch (e) {
// catch noop
}
}
function getRootTsConfigPath(tree) {
for (const path of ['tsconfig.base.json', 'tsconfig.json']) {
if (tree.exists(path)) {
return path;
}
}
return null;
}
function getChangedPrettierConfigInTree(tree) {
if (tree.listChanges().find((file) => file.path === '.prettierrc')) {
try {
return (0, devkit_exports_1.readJson)(tree, '.prettierrc');
}
catch {
return null;
}
}
else {
return null;
}
}

View File

@@ -0,0 +1,45 @@
import { type Tree } from 'nx/src/devkit-exports';
/**
* Specify what should be done when a file is generated but already exists on the system
*/
export declare enum OverwriteStrategy {
Overwrite = "overwrite",
KeepExisting = "keepExisting",
ThrowIfExisting = "throwIfExisting"
}
/**
* Options for the generateFiles function
*/
export interface GenerateFilesOptions {
/**
* Specify what should be done when a file is generated but already exists on the system
*/
overwriteStrategy?: OverwriteStrategy;
}
/**
* Generates a folder of files based on provided templates.
*
* While doing so it performs two substitutions:
* - Substitutes segments of file names surrounded by __
* - Uses ejs to substitute values in templates
*
* Examples:
* ```typescript
* generateFiles(tree, path.join(__dirname , 'files'), './tools/scripts', {tmpl: '', name: 'myscript'})
* ```
* This command will take all the files from the `files` directory next to the place where the command is invoked from.
* It will replace all `__tmpl__` with '' and all `__name__` with 'myscript' in the file names, and will replace all
* `<%= name %>` with `myscript` in the files themselves.
* `tmpl: ''` is a common pattern. With it you can name files like this: `index.ts__tmpl__`, so your editor
* doesn't get confused about incorrect TypeScript files.
*
* @param tree - the file system tree
* @param srcFolder - the source folder of files (absolute path)
* @param target - the target folder (relative to the tree root)
* @param substitutions - an object of key-value pairs
* @param options - See {@link GenerateFilesOptions}
*/
export declare function generateFiles(tree: Tree, srcFolder: string, target: string, substitutions: {
[k: string]: any;
}, options?: GenerateFilesOptions): void;
//# sourceMappingURL=generate-files.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"generate-files.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/generate-files.ts"],"names":[],"mappings":"AAIA,OAAO,EAAU,KAAK,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAE1D;;GAEG;AACH,oBAAY,iBAAiB;IAC3B,SAAS,cAAc;IACvB,YAAY,iBAAiB;IAC7B,eAAe,oBAAoB;CACpC;AAED;;GAEG;AACH,MAAM,WAAW,oBAAoB;IACnC;;OAEG;IACH,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;CACvC;AAGD;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,aAAa,EAAE;IAAE,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAAA;CAAE,EACnC,OAAO,GAAE,oBAER,GACA,IAAI,CAmDN"}

View File

@@ -0,0 +1,115 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.OverwriteStrategy = void 0;
exports.generateFiles = generateFiles;
const tslib_1 = require("tslib");
const fs_1 = require("fs");
const path = tslib_1.__importStar(require("path"));
const binary_extensions_1 = require("../utils/binary-extensions");
const devkit_exports_1 = require("nx/src/devkit-exports");
/**
* Specify what should be done when a file is generated but already exists on the system
*/
var OverwriteStrategy;
(function (OverwriteStrategy) {
OverwriteStrategy["Overwrite"] = "overwrite";
OverwriteStrategy["KeepExisting"] = "keepExisting";
OverwriteStrategy["ThrowIfExisting"] = "throwIfExisting";
})(OverwriteStrategy || (exports.OverwriteStrategy = OverwriteStrategy = {}));
// TODO(v24): use the version from nx/src/generators/utils
/**
* Generates a folder of files based on provided templates.
*
* While doing so it performs two substitutions:
* - Substitutes segments of file names surrounded by __
* - Uses ejs to substitute values in templates
*
* Examples:
* ```typescript
* generateFiles(tree, path.join(__dirname , 'files'), './tools/scripts', {tmpl: '', name: 'myscript'})
* ```
* This command will take all the files from the `files` directory next to the place where the command is invoked from.
* It will replace all `__tmpl__` with '' and all `__name__` with 'myscript' in the file names, and will replace all
* `<%= name %>` with `myscript` in the files themselves.
* `tmpl: ''` is a common pattern. With it you can name files like this: `index.ts__tmpl__`, so your editor
* doesn't get confused about incorrect TypeScript files.
*
* @param tree - the file system tree
* @param srcFolder - the source folder of files (absolute path)
* @param target - the target folder (relative to the tree root)
* @param substitutions - an object of key-value pairs
* @param options - See {@link GenerateFilesOptions}
*/
function generateFiles(tree, srcFolder, target, substitutions, options = {
overwriteStrategy: OverwriteStrategy.Overwrite,
}) {
options ??= {};
options.overwriteStrategy ??= OverwriteStrategy.Overwrite;
const ejs = require('ejs');
const files = allFilesInDir(srcFolder);
if (files.length === 0) {
throw new Error(`generateFiles: No files found in "${srcFolder}". Are you sure you specified the correct path?`);
}
else {
files.forEach((filePath) => {
let newContent;
const computedPath = computePath(srcFolder, target, filePath, substitutions);
if (tree.exists(computedPath)) {
if (options.overwriteStrategy === OverwriteStrategy.KeepExisting) {
return;
}
else if (options.overwriteStrategy === OverwriteStrategy.ThrowIfExisting) {
throw new Error(`Generated file already exists, not allowed by overwrite strategy in generator (${computedPath})`);
}
// else: file should be overwritten, so just fall through to file generation
}
if ((0, binary_extensions_1.isBinaryPath)(filePath)) {
newContent = (0, fs_1.readFileSync)(filePath);
}
else {
const template = (0, fs_1.readFileSync)(filePath, 'utf-8');
try {
newContent = ejs.render(template, substitutions, {
filename: filePath,
});
}
catch (e) {
devkit_exports_1.logger.error(`Error in ${filePath.replace(`${tree.root}/`, '')}:`);
throw e;
}
}
tree.write(computedPath, newContent);
});
}
}
function computePath(srcFolder, target, filePath, substitutions) {
const relativeFromSrcFolder = path.relative(srcFolder, filePath);
let computedPath = path.join(target, relativeFromSrcFolder);
if (computedPath.endsWith('.template')) {
computedPath = computedPath.substring(0, computedPath.length - 9);
}
Object.entries(substitutions).forEach(([propertyName, value]) => {
computedPath = computedPath.split(`__${propertyName}__`).join(value);
});
return computedPath;
}
function allFilesInDir(parent) {
let res = [];
try {
(0, fs_1.readdirSync)(parent).forEach((c) => {
const child = path.join(parent, c);
try {
const s = (0, fs_1.statSync)(child);
if (!s.isDirectory()) {
res.push(child);
}
else if (s.isDirectory()) {
res = [...res, ...allFilesInDir(child)];
}
}
catch { }
});
}
catch { }
return res;
}

View File

@@ -0,0 +1,28 @@
interface AggregateLogOptions {
project: string;
log: string;
executorName: string;
}
interface AggregateLogItem {
log: string;
projects: Set<string>;
}
/**
* @example
* // Instantiate a new object
* const migrationLogs = new AggregatedLog();
*
* // Add logs
* migrationLogs.addLog({executorName: '@nx/vite:build', project: 'app1', log: 'Migrate X manually'});
*
* // Flush all logs
* migrationLogs.flushLogs()
*/
export declare class AggregatedLog {
logs: Map<string, Map<string, AggregateLogItem>>;
addLog({ project, log, executorName }: AggregateLogOptions): void;
reset(): void;
flushLogs(): void;
}
export {};
//# sourceMappingURL=aggregate-log-util.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"aggregate-log-util.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/generators/plugin-migrations/aggregate-log-util.ts"],"names":[],"mappings":"AAEA,UAAU,mBAAmB;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,GAAG,EAAE,MAAM,CAAC;IACZ,YAAY,EAAE,MAAM,CAAC;CACtB;AAED,UAAU,gBAAgB;IACxB,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;CACvB;AAED;;;;;;;;;;GAUG;AACH,qBAAa,aAAa;IACxB,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,GAAG,CAAC,MAAM,EAAE,gBAAgB,CAAC,CAAC,CAAa;IAE7D,MAAM,CAAC,EAAE,OAAO,EAAE,GAAG,EAAE,YAAY,EAAE,EAAE,mBAAmB,GAAG,IAAI;IAcjE,KAAK,IAAI,IAAI;IAIb,SAAS,IAAI,IAAI;CAwBlB"}

View File

@@ -0,0 +1,54 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AggregatedLog = void 0;
const devkit_exports_1 = require("nx/src/devkit-exports");
/**
* @example
* // Instantiate a new object
* const migrationLogs = new AggregatedLog();
*
* // Add logs
* migrationLogs.addLog({executorName: '@nx/vite:build', project: 'app1', log: 'Migrate X manually'});
*
* // Flush all logs
* migrationLogs.flushLogs()
*/
class AggregatedLog {
constructor() {
this.logs = new Map();
}
addLog({ project, log, executorName }) {
if (!this.logs.has(executorName)) {
this.logs.set(executorName, new Map());
}
const executorLogs = this.logs.get(executorName);
if (!executorLogs.has(log)) {
executorLogs.set(log, { log, projects: new Set([project]) });
}
else {
const logItem = executorLogs.get(log);
logItem.projects.add(project);
}
}
reset() {
this.logs.clear();
}
flushLogs() {
if (this.logs.size === 0) {
return;
}
let fullLog = '';
for (const executorName of this.logs.keys()) {
fullLog = `${fullLog}${devkit_exports_1.output.bold(`Encountered the following while migrating '${executorName}':\r\n`)}`;
for (const logItem of this.logs.get(executorName).values()) {
fullLog = `${fullLog}${logItem.log}\r\n`;
fullLog = `${fullLog} ${devkit_exports_1.output.bold(`Affected Projects`)}\r\n`;
fullLog = `${fullLog} ${Array.from(logItem.projects.values()).join(`\r\n `)}`;
fullLog = `${fullLog}\r\n`;
}
}
devkit_exports_1.logger.warn(fullLog);
this.reset();
}
}
exports.AggregatedLog = AggregatedLog;

View File

@@ -0,0 +1,31 @@
import type { ProjectConfiguration } from 'nx/src/config/workspace-json-project-json';
import { type CreateNodesV2, type ProjectGraph, type TargetConfiguration, type Tree } from 'nx/src/devkit-exports';
import { logger as devkitLogger } from 'nx/src/devkit-exports';
export type InferredTargetConfiguration = TargetConfiguration & {
name: string;
};
type PostTargetTransformer = (targetConfiguration: TargetConfiguration, tree: Tree, projectDetails: {
projectName: string;
root: string;
}, inferredTargetConfiguration: InferredTargetConfiguration) => TargetConfiguration | Promise<TargetConfiguration>;
type SkipTargetFilter = (targetOptions: Record<string, unknown>, projectConfiguration: ProjectConfiguration) => false | string;
type SkipProjectFilter = (projectConfiguration: ProjectConfiguration) => false | string;
export declare class NoTargetsToMigrateError extends Error {
constructor();
}
export declare function migrateProjectExecutorsToPlugin<T>(tree: Tree, projectGraph: ProjectGraph, pluginPath: string, createNodesV2: CreateNodesV2<T>, defaultPluginOptions: T, migrations: Array<{
executors: string[];
targetPluginOptionMapper: (targetName: string) => Partial<T>;
postTargetTransformer: PostTargetTransformer;
skipProjectFilter?: SkipProjectFilter;
skipTargetFilter?: SkipTargetFilter;
}>, specificProjectToMigrate?: string, logger?: typeof devkitLogger): Promise<Map<string, Record<string, string>>>;
export declare function migrateProjectExecutorsToPluginV1<T>(tree: Tree, projectGraph: ProjectGraph, pluginPath: string, createNodes: CreateNodesV2<T>, defaultPluginOptions: T, migrations: Array<{
executors: string[];
targetPluginOptionMapper: (targetName: string) => Partial<T>;
postTargetTransformer: PostTargetTransformer;
skipProjectFilter?: SkipProjectFilter;
skipTargetFilter?: SkipTargetFilter;
}>, specificProjectToMigrate?: string): Promise<Map<string, Record<string, string>>>;
export {};
//# sourceMappingURL=executor-to-plugin-migrator.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"executor-to-plugin-migrator.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/generators/plugin-migrations/executor-to-plugin-migrator.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAEV,oBAAoB,EACrB,MAAM,2CAA2C,CAAC;AACnD,OAAO,EAKL,KAAK,aAAa,EAGlB,KAAK,YAAY,EACjB,KAAK,mBAAmB,EACxB,KAAK,IAAI,EACV,MAAM,uBAAuB,CAAC;AAY/B,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,uBAAuB,CAAC;AAE/D,MAAM,MAAM,2BAA2B,GAAG,mBAAmB,GAAG;IAC9D,IAAI,EAAE,MAAM,CAAC;CACd,CAAC;AAEF,KAAK,qBAAqB,GAAG,CAC3B,mBAAmB,EAAE,mBAAmB,EACxC,IAAI,EAAE,IAAI,EACV,cAAc,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EACrD,2BAA2B,EAAE,2BAA2B,KACrD,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAAC;AACxD,KAAK,gBAAgB,GAAG,CACtB,aAAa,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACtC,oBAAoB,EAAE,oBAAoB,KACvC,KAAK,GAAG,MAAM,CAAC;AACpB,KAAK,iBAAiB,GAAG,CACvB,oBAAoB,EAAE,oBAAoB,KACvC,KAAK,GAAG,MAAM,CAAC;AAqSpB,qBAAa,uBAAwB,SAAQ,KAAK;;CAIjD;AAED,wBAAsB,+BAA+B,CAAC,CAAC,EACrD,IAAI,EAAE,IAAI,EACV,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,MAAM,EAClB,aAAa,EAAE,aAAa,CAAC,CAAC,CAAC,EAC/B,oBAAoB,EAAE,CAAC,EACvB,UAAU,EAAE,KAAK,CAAC;IAChB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,wBAAwB,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;IAC7D,qBAAqB,EAAE,qBAAqB,CAAC;IAC7C,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACrC,CAAC,EACF,wBAAwB,CAAC,EAAE,MAAM,EACjC,MAAM,CAAC,EAAE,OAAO,YAAY,GAC3B,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAc9C;AAED,wBAAsB,iCAAiC,CAAC,CAAC,EACvD,IAAI,EAAE,IAAI,EACV,YAAY,EAAE,YAAY,EAC1B,UAAU,EAAE,MAAM,EAClB,WAAW,EAAE,aAAa,CAAC,CAAC,CAAC,EAC7B,oBAAoB,EAAE,CAAC,EACvB,UAAU,EAAE,KAAK,CAAC;IAChB,SAAS,EAAE,MAAM,EAAE,CAAC;IACpB,wBAAwB,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;IAC7D,qBAAqB,EAAE,qBAAqB,CAAC;IAC7C,iBAAiB,CAAC,EAAE,iBAAiB,CAAC;IACtC,gBAAgB,CAAC,EAAE,gBAAgB,CAAC;CACrC,CAAC,EACF,wBAAwB,CAAC,EAAE,MAAM,GAChC,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC,CAa9C"}

View File

@@ -0,0 +1,353 @@
"use strict";
var _ExecutorToPluginMigrator_instances, _ExecutorToPluginMigrator_projectGraph, _ExecutorToPluginMigrator_executor, _ExecutorToPluginMigrator_pluginPath, _ExecutorToPluginMigrator_pluginOptionsBuilder, _ExecutorToPluginMigrator_postTargetTransformer, _ExecutorToPluginMigrator_skipTargetFilter, _ExecutorToPluginMigrator_skipProjectFilter, _ExecutorToPluginMigrator_specificProjectToMigrate, _ExecutorToPluginMigrator_logger, _ExecutorToPluginMigrator_nxJson, _ExecutorToPluginMigrator_targetDefaultsForExecutor, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, _ExecutorToPluginMigrator_createNodes, _ExecutorToPluginMigrator_createNodesV2, _ExecutorToPluginMigrator_createNodesResultsForTargets, _ExecutorToPluginMigrator_skippedProjects, _ExecutorToPluginMigrator_init, _ExecutorToPluginMigrator_migrateTarget, _ExecutorToPluginMigrator_migrateProject, _ExecutorToPluginMigrator_mergeInputs, _ExecutorToPluginMigrator_getTargetAndProjectsToMigrate, _ExecutorToPluginMigrator_getTargetDefaultsForExecutor, _ExecutorToPluginMigrator_getCreatedTargetForProjectRoot, _ExecutorToPluginMigrator_getCreateNodesResults;
Object.defineProperty(exports, "__esModule", { value: true });
exports.NoTargetsToMigrateError = void 0;
exports.migrateProjectExecutorsToPlugin = migrateProjectExecutorsToPlugin;
exports.migrateProjectExecutorsToPluginV1 = migrateProjectExecutorsToPluginV1;
const tslib_1 = require("tslib");
const minimatch_1 = require("minimatch");
const node_assert_1 = require("node:assert");
const posix_1 = require("node:path/posix");
const devkit_exports_1 = require("nx/src/devkit-exports");
const devkit_internals_1 = require("nx/src/devkit-internals");
const executor_options_utils_1 = require("../executor-options-utils");
const plugin_migration_utils_1 = require("./plugin-migration-utils");
const devkit_exports_2 = require("nx/src/devkit-exports");
class ExecutorToPluginMigrator {
constructor(tree, projectGraph, executor, pluginPath, pluginOptionsBuilder, postTargetTransformer, createNodes, createNodesV2, specificProjectToMigrate, filters, logger) {
_ExecutorToPluginMigrator_instances.add(this);
_ExecutorToPluginMigrator_projectGraph.set(this, void 0);
_ExecutorToPluginMigrator_executor.set(this, void 0);
_ExecutorToPluginMigrator_pluginPath.set(this, void 0);
_ExecutorToPluginMigrator_pluginOptionsBuilder.set(this, void 0);
_ExecutorToPluginMigrator_postTargetTransformer.set(this, void 0);
_ExecutorToPluginMigrator_skipTargetFilter.set(this, void 0);
_ExecutorToPluginMigrator_skipProjectFilter.set(this, void 0);
_ExecutorToPluginMigrator_specificProjectToMigrate.set(this, void 0);
_ExecutorToPluginMigrator_logger.set(this, void 0);
_ExecutorToPluginMigrator_nxJson.set(this, void 0);
_ExecutorToPluginMigrator_targetDefaultsForExecutor.set(this, void 0);
_ExecutorToPluginMigrator_targetAndProjectsToMigrate.set(this, void 0);
_ExecutorToPluginMigrator_createNodes.set(this, void 0);
_ExecutorToPluginMigrator_createNodesV2.set(this, void 0);
_ExecutorToPluginMigrator_createNodesResultsForTargets.set(this, void 0);
_ExecutorToPluginMigrator_skippedProjects.set(this, void 0);
this.tree = tree;
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_projectGraph, projectGraph, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_executor, executor, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_pluginPath, pluginPath, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_pluginOptionsBuilder, pluginOptionsBuilder, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_postTargetTransformer, postTargetTransformer, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_createNodes, createNodes, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_createNodesV2, createNodesV2, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_specificProjectToMigrate, specificProjectToMigrate, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_skipProjectFilter, filters?.skipProjectFilter ?? ((...args) => false), "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_skipTargetFilter, filters?.skipTargetFilter ?? ((...args) => false), "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_logger, logger ?? devkit_exports_2.logger, "f");
}
async run() {
await tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_init).call(this);
if (tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").size > 0) {
for (const targetName of tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").keys()) {
await tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_migrateTarget).call(this, targetName);
}
}
return tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f");
}
}
_ExecutorToPluginMigrator_projectGraph = new WeakMap(), _ExecutorToPluginMigrator_executor = new WeakMap(), _ExecutorToPluginMigrator_pluginPath = new WeakMap(), _ExecutorToPluginMigrator_pluginOptionsBuilder = new WeakMap(), _ExecutorToPluginMigrator_postTargetTransformer = new WeakMap(), _ExecutorToPluginMigrator_skipTargetFilter = new WeakMap(), _ExecutorToPluginMigrator_skipProjectFilter = new WeakMap(), _ExecutorToPluginMigrator_specificProjectToMigrate = new WeakMap(), _ExecutorToPluginMigrator_logger = new WeakMap(), _ExecutorToPluginMigrator_nxJson = new WeakMap(), _ExecutorToPluginMigrator_targetDefaultsForExecutor = new WeakMap(), _ExecutorToPluginMigrator_targetAndProjectsToMigrate = new WeakMap(), _ExecutorToPluginMigrator_createNodes = new WeakMap(), _ExecutorToPluginMigrator_createNodesV2 = new WeakMap(), _ExecutorToPluginMigrator_createNodesResultsForTargets = new WeakMap(), _ExecutorToPluginMigrator_skippedProjects = new WeakMap(), _ExecutorToPluginMigrator_instances = new WeakSet(), _ExecutorToPluginMigrator_init = async function _ExecutorToPluginMigrator_init() {
const nxJson = (0, devkit_exports_1.readNxJson)(this.tree);
nxJson.plugins ??= [];
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_nxJson, nxJson, "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, new Map(), "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_createNodesResultsForTargets, new Map(), "f");
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_skippedProjects, new Set(), "f");
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_getTargetDefaultsForExecutor).call(this);
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_getTargetAndProjectsToMigrate).call(this);
await tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_getCreateNodesResults).call(this);
}, _ExecutorToPluginMigrator_migrateTarget = async function _ExecutorToPluginMigrator_migrateTarget(targetName) {
for (const projectName of tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").get(targetName)) {
await tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_migrateProject).call(this, projectName, targetName);
}
}, _ExecutorToPluginMigrator_migrateProject = async function _ExecutorToPluginMigrator_migrateProject(projectName, targetName) {
const projectFromGraph = tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_projectGraph, "f").nodes[projectName];
const projectConfig = (0, devkit_exports_1.readProjectConfiguration)(this.tree, projectName);
const createdTarget = tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_getCreatedTargetForProjectRoot).call(this, targetName, projectFromGraph.data.root);
let projectTarget = projectConfig.targets[targetName];
projectTarget = (0, devkit_internals_1.mergeTargetConfigurations)(projectTarget, tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetDefaultsForExecutor, "f"));
delete projectTarget.executor;
(0, plugin_migration_utils_1.deleteMatchingProperties)(projectTarget, createdTarget);
if (projectTarget.inputs && createdTarget.inputs) {
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_instances, "m", _ExecutorToPluginMigrator_mergeInputs).call(this, projectTarget, createdTarget);
}
projectTarget = await tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_postTargetTransformer, "f").call(this, projectTarget, this.tree, { projectName, root: projectFromGraph.data.root }, { ...createdTarget, name: targetName });
if (projectTarget.options &&
Object.keys(projectTarget.options).length === 0) {
delete projectTarget.options;
}
if (Object.keys(projectTarget).length > 0) {
projectConfig.targets[targetName] = projectTarget;
}
else {
delete projectConfig.targets[targetName];
}
if (!projectConfig['// targets']) {
projectConfig['// targets'] =
`to see all targets run: nx show project ${projectName} --web`;
}
(0, devkit_exports_1.updateProjectConfiguration)(this.tree, projectName, projectConfig);
}, _ExecutorToPluginMigrator_mergeInputs = function _ExecutorToPluginMigrator_mergeInputs(target, inferredTarget) {
const isInputInferred = (input) => {
return inferredTarget.inputs.some((inferredInput) => {
try {
(0, node_assert_1.deepStrictEqual)(input, inferredInput);
return true;
}
catch {
return false;
}
});
};
if (target.inputs.every(isInputInferred)) {
delete target.inputs;
return;
}
const inferredTargetExternalDependencyInput = inferredTarget.inputs.find((i) => typeof i !== 'string' && 'externalDependencies' in i);
if (!inferredTargetExternalDependencyInput) {
// plugins should normally have an externalDependencies input, but if it
// doesn't, there's nothing to merge
return;
}
const targetExternalDependencyInput = target.inputs.find((i) => typeof i !== 'string' && 'externalDependencies' in i);
if (!targetExternalDependencyInput) {
// the target doesn't have an externalDependencies input, so we can just
// add the inferred one
target.inputs.push(inferredTargetExternalDependencyInput);
}
else {
// the target has an externalDependencies input, so we need to merge them
targetExternalDependencyInput.externalDependencies = Array.from(new Set([
...targetExternalDependencyInput.externalDependencies,
...inferredTargetExternalDependencyInput.externalDependencies,
]));
}
}, _ExecutorToPluginMigrator_getTargetAndProjectsToMigrate = function _ExecutorToPluginMigrator_getTargetAndProjectsToMigrate() {
(0, executor_options_utils_1.forEachExecutorOptions)(this.tree, tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_executor, "f"), (options, projectName, targetName, configurationName) => {
if (tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_skippedProjects, "f").has(projectName) || configurationName) {
return;
}
if (tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_specificProjectToMigrate, "f") &&
projectName !== tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_specificProjectToMigrate, "f")) {
return;
}
const skipProjectReason = tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_skipProjectFilter, "f").call(this, tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_projectGraph, "f").nodes[projectName].data);
if (skipProjectReason) {
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_skippedProjects, "f").add(projectName);
const errorMsg = `The "${projectName}" project cannot be migrated. ${skipProjectReason}`;
if (tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_specificProjectToMigrate, "f")) {
throw new Error(errorMsg);
}
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_logger, "f").warn(errorMsg);
return;
}
const skipTargetReason = tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_skipTargetFilter, "f").call(this, options, tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_projectGraph, "f").nodes[projectName].data);
if (skipTargetReason) {
const errorMsg = `The ${targetName} target on project "${projectName}" cannot be migrated. ${skipTargetReason}`;
if (tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_specificProjectToMigrate, "f")) {
throw new Error(errorMsg);
}
else {
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_logger, "f").warn(errorMsg);
}
return;
}
if (tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").has(targetName)) {
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").get(targetName).add(projectName);
}
else {
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").set(targetName, new Set([projectName]));
}
});
}, _ExecutorToPluginMigrator_getTargetDefaultsForExecutor = function _ExecutorToPluginMigrator_getTargetDefaultsForExecutor() {
tslib_1.__classPrivateFieldSet(this, _ExecutorToPluginMigrator_targetDefaultsForExecutor, structuredClone(tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_nxJson, "f").targetDefaults?.[tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_executor, "f")]), "f");
}, _ExecutorToPluginMigrator_getCreatedTargetForProjectRoot = function _ExecutorToPluginMigrator_getCreatedTargetForProjectRoot(targetName, projectRoot) {
const entry = Object.entries(tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_createNodesResultsForTargets, "f").get(targetName)?.projects ?? {}).find(([root]) => root === projectRoot);
if (!entry) {
throw new Error(`The nx plugin did not find a project inside ${projectRoot}. File an issue at https://github.com/nrwl/nx with information about your project structure.`);
}
const createdProject = entry[1];
const createdTarget = structuredClone(createdProject.targets[targetName]);
delete createdTarget.command;
delete createdTarget.options?.cwd;
return createdTarget;
}, _ExecutorToPluginMigrator_getCreateNodesResults = async function _ExecutorToPluginMigrator_getCreateNodesResults() {
if (tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").size === 0) {
return;
}
global.NX_GRAPH_CREATION = true;
try {
for (const targetName of tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_targetAndProjectsToMigrate, "f").keys()) {
const result = await getCreateNodesResultsForPlugin(this.tree, {
plugin: tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_pluginPath, "f"),
options: tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_pluginOptionsBuilder, "f").call(this, targetName),
}, tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_pluginPath, "f"), tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_createNodes, "f"), tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_createNodesV2, "f"), tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_nxJson, "f"));
tslib_1.__classPrivateFieldGet(this, _ExecutorToPluginMigrator_createNodesResultsForTargets, "f").set(targetName, result);
}
}
finally {
global.NX_GRAPH_CREATION = false;
}
};
class NoTargetsToMigrateError extends Error {
constructor() {
super('Could not find any targets to migrate.');
}
}
exports.NoTargetsToMigrateError = NoTargetsToMigrateError;
async function migrateProjectExecutorsToPlugin(tree, projectGraph, pluginPath, createNodesV2, defaultPluginOptions, migrations, specificProjectToMigrate, logger) {
const projects = await migrateProjects(tree, projectGraph, pluginPath, undefined, createNodesV2, defaultPluginOptions, migrations, specificProjectToMigrate, logger);
return projects;
}
async function migrateProjectExecutorsToPluginV1(tree, projectGraph, pluginPath, createNodes, defaultPluginOptions, migrations, specificProjectToMigrate) {
const projects = await migrateProjects(tree, projectGraph, pluginPath, createNodes, undefined, defaultPluginOptions, migrations, specificProjectToMigrate);
return projects;
}
async function migrateProjects(tree, projectGraph, pluginPath, createNodes, createNodesV2, defaultPluginOptions, migrations, specificProjectToMigrate, logger) {
const projects = new Map();
const spinner = devkit_internals_1.globalSpinner.start(`Calculating migration scope...`, pluginPath);
for (const migration of migrations) {
for (const executor of migration.executors) {
const migrator = new ExecutorToPluginMigrator(tree, projectGraph, executor, pluginPath, migration.targetPluginOptionMapper, migration.postTargetTransformer, createNodes, createNodesV2, specificProjectToMigrate, {
skipProjectFilter: migration.skipProjectFilter,
skipTargetFilter: migration.skipTargetFilter,
}, logger);
const result = await migrator.run();
// invert the result to have a map of projects to their targets
for (const [target, projectList] of result.entries()) {
for (const project of projectList) {
if (!projects.has(project)) {
projects.set(project, {});
}
projects.set(project, {
...projects.get(project),
...migration.targetPluginOptionMapper(target),
});
}
}
}
}
// apply default options
for (const [project, pluginOptions] of projects.entries()) {
projects.set(project, {
...defaultPluginOptions,
...pluginOptions,
});
}
await addPluginRegistrations(tree, projects, pluginPath, createNodes, createNodesV2, defaultPluginOptions, projectGraph, spinner);
spinner.succeed(`Migrated configuration for ${projects.size} project(s).\n`);
return projects;
}
async function addPluginRegistrations(tree, projects, pluginPath, createNodes, createNodesV2, defaultPluginOptions, projectGraph, spinner) {
const nxJson = (0, devkit_exports_1.readNxJson)(tree);
// collect createNodes results for each project before adding the plugins
const createNodesResults = new Map();
global.NX_GRAPH_CREATION = true;
try {
let index = 0;
for (const [project, options] of projects.entries()) {
index++;
spinner.updateText(`${index}/${projects.size} - Parsing "${project}" configuration...`);
const projectConfigs = await getCreateNodesResultsForPlugin(tree, { plugin: pluginPath, options }, pluginPath, createNodes, createNodesV2, nxJson);
createNodesResults.set(project, projectConfigs);
}
}
finally {
global.NX_GRAPH_CREATION = false;
}
const arePluginIncludesRequired = async (project, pluginConfiguration) => {
global.NX_GRAPH_CREATION = true;
let result;
try {
result = await getCreateNodesResultsForPlugin(tree, pluginConfiguration, pluginPath, createNodes, createNodesV2, nxJson);
}
finally {
global.NX_GRAPH_CREATION = false;
}
const originalResults = createNodesResults.get(project);
return !deepEqual(originalResults, result);
};
let index = 0;
for (const [project, options] of projects.entries()) {
index++;
spinner.updateText(`${index}/${projects.size} - Applying "${project}" configuration...`);
const existingPlugin = nxJson.plugins?.find((plugin) => typeof plugin !== 'string' &&
plugin.plugin === pluginPath &&
Object.keys(options).every((key) => plugin.options[key] === options[key] ||
(plugin.options[key] === undefined &&
options[key] === defaultPluginOptions[key])));
const projectIncludeGlob = projectGraph.nodes[project].data.root === '.'
? '*'
: (0, posix_1.join)(projectGraph.nodes[project].data.root, '**/*');
if (!existingPlugin) {
nxJson.plugins ??= [];
const plugin = {
plugin: pluginPath,
options,
include: [projectIncludeGlob],
};
if (!(await arePluginIncludesRequired(project, plugin))) {
delete plugin.include;
}
nxJson.plugins.push(plugin);
}
else if (existingPlugin.include) {
if (!existingPlugin.include.some((include) => (0, minimatch_1.minimatch)(projectIncludeGlob, include, { dot: true }))) {
existingPlugin.include.push(projectIncludeGlob);
if (!(await arePluginIncludesRequired(project, existingPlugin))) {
delete existingPlugin.include;
}
}
}
}
spinner.updateText(`Migrations done`);
(0, devkit_exports_1.updateNxJson)(tree, nxJson);
}
async function getCreateNodesResultsForPlugin(tree, pluginConfiguration, pluginPath, createNodes, createNodesV2, nxJson) {
let projectConfigs;
try {
const plugin = new devkit_internals_1.LoadedNxPlugin({ createNodes, createNodesV2, name: pluginPath }, pluginConfiguration);
projectConfigs = await (0, devkit_internals_1.retrieveProjectConfigurations)([plugin], tree.root, nxJson);
}
catch (e) {
if (e instanceof devkit_internals_1.ProjectConfigurationsError) {
projectConfigs = e.partialProjectConfigurationsResult;
}
else {
throw e;
}
}
return projectConfigs;
}
// Checks if two objects are structurely equal, without caring
// about the order of the keys.
function deepEqual(a, b, logKey = '') {
const aKeys = Object.keys(a);
const bKeys = new Set(Object.keys(b));
if (aKeys.length !== bKeys.size) {
return false;
}
for (const key of aKeys) {
if (!bKeys.has(key)) {
return false;
}
if (typeof a[key] === 'object' && typeof b[key] === 'object') {
if (!deepEqual(a[key], b[key], logKey + '.' + key)) {
return false;
}
}
else if (a[key] !== b[key]) {
return false;
}
}
return true;
}

View File

@@ -0,0 +1,64 @@
import { type TargetConfiguration } from 'nx/src/devkit-exports';
/**
* Iterate through the current target in the project.json and its options comparing it to the target created by the Plugin itself
* Delete matching properties from current target.
*
* _Note: Deletes by reference_
*
* @example
* // Run the plugin to get all the projects
* const { projects } = await createNodes[1](
* playwrightConfigPath,
* { targetName, ciTargetName: 'e2e-ci' },
* { workspaceRoot: tree.root, nxJsonConfiguration, configFiles }
* );
*
* // Find the project that matches the one that is being migrated
* const createdProject = Object.entries(projects ?? {}).find(
* ([root]) => root === projectFromGraph.data.root
* )[1];
*
* // Get the created TargetConfiguration for the target being migrated
* const createdTarget: TargetConfiguration<RunCommandsOptions> =
* createdProject.targets[targetName];
*
* // Delete specific run-commands options
* delete createdTarget.command;
* delete createdTarget.options?.cwd;
*
* // Get the TargetConfiguration for the target being migrated from project.json
* const projectConfig = readProjectConfiguration(tree, projectName);
* let targetToMigrate = projectConfig.targets[targetName];
*
* // Merge the target defaults for the executor to the target being migrated
* target = mergeTargetConfigurations(targetToMigrate, targetDefaultsForExecutor);
*
* // Delete executor and any additional options that are no longer necessary
* delete target.executor;
* delete target.options?.config;
*
* // Run deleteMatchingProperties to delete further options that match what the plugin creates
* deleteMatchingProperties(target, createdTarget);
*
* // Delete the target if it is now empty, otherwise, set it to the updated TargetConfiguration
* if (Object.keys(target).length > 0) {
* projectConfig.targets[targetName] = target;
* } else {
* delete projectConfig.targets[targetName];
* }
*
* updateProjectConfiguration(tree, projectName, projectConfig);
*
* @param targetToMigrate The target from project.json
* @param createdTarget The target created by the Plugin
*/
export declare function deleteMatchingProperties(targetToMigrate: object, createdTarget: object): void;
export declare function processTargetOutputs(target: TargetConfiguration, renamedOutputOptions: Array<{
newName: string;
oldName: string;
}>, inferredTarget: TargetConfiguration, projectDetails: {
projectName: string;
projectRoot: string;
}): void;
export declare function toProjectRelativePath(path: string, projectRoot: string): string;
//# sourceMappingURL=plugin-migration-utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"plugin-migration-utils.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/generators/plugin-migrations/plugin-migration-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAAiB,KAAK,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAGhF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AACH,wBAAgB,wBAAwB,CACtC,eAAe,EAAE,MAAM,EACvB,aAAa,EAAE,MAAM,GACpB,IAAI,CAwBN;AAED,wBAAgB,oBAAoB,CAClC,MAAM,EAAE,mBAAmB,EAC3B,oBAAoB,EAAE,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,EACjE,cAAc,EAAE,mBAAmB,EACnC,cAAc,EAAE;IAAE,WAAW,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,CAAA;CAAE,GAC3D,IAAI,CAsCN;AAED,wBAAgB,qBAAqB,CACnC,IAAI,EAAE,MAAM,EACZ,WAAW,EAAE,MAAM,GAClB,MAAM,CAaR"}

View File

@@ -0,0 +1,154 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.deleteMatchingProperties = deleteMatchingProperties;
exports.processTargetOutputs = processTargetOutputs;
exports.toProjectRelativePath = toProjectRelativePath;
const posix_1 = require("node:path/posix");
const devkit_exports_1 = require("nx/src/devkit-exports");
const devkit_internals_1 = require("nx/src/devkit-internals");
/**
* Iterate through the current target in the project.json and its options comparing it to the target created by the Plugin itself
* Delete matching properties from current target.
*
* _Note: Deletes by reference_
*
* @example
* // Run the plugin to get all the projects
* const { projects } = await createNodes[1](
* playwrightConfigPath,
* { targetName, ciTargetName: 'e2e-ci' },
* { workspaceRoot: tree.root, nxJsonConfiguration, configFiles }
* );
*
* // Find the project that matches the one that is being migrated
* const createdProject = Object.entries(projects ?? {}).find(
* ([root]) => root === projectFromGraph.data.root
* )[1];
*
* // Get the created TargetConfiguration for the target being migrated
* const createdTarget: TargetConfiguration<RunCommandsOptions> =
* createdProject.targets[targetName];
*
* // Delete specific run-commands options
* delete createdTarget.command;
* delete createdTarget.options?.cwd;
*
* // Get the TargetConfiguration for the target being migrated from project.json
* const projectConfig = readProjectConfiguration(tree, projectName);
* let targetToMigrate = projectConfig.targets[targetName];
*
* // Merge the target defaults for the executor to the target being migrated
* target = mergeTargetConfigurations(targetToMigrate, targetDefaultsForExecutor);
*
* // Delete executor and any additional options that are no longer necessary
* delete target.executor;
* delete target.options?.config;
*
* // Run deleteMatchingProperties to delete further options that match what the plugin creates
* deleteMatchingProperties(target, createdTarget);
*
* // Delete the target if it is now empty, otherwise, set it to the updated TargetConfiguration
* if (Object.keys(target).length > 0) {
* projectConfig.targets[targetName] = target;
* } else {
* delete projectConfig.targets[targetName];
* }
*
* updateProjectConfiguration(tree, projectName, projectConfig);
*
* @param targetToMigrate The target from project.json
* @param createdTarget The target created by the Plugin
*/
function deleteMatchingProperties(targetToMigrate, createdTarget) {
for (const key in targetToMigrate) {
if (Array.isArray(targetToMigrate[key])) {
if (targetToMigrate[key].every((v) => createdTarget[key]?.includes(v)) &&
targetToMigrate[key].length === createdTarget[key]?.length) {
delete targetToMigrate[key];
}
}
else if (typeof targetToMigrate[key] === 'object' &&
typeof createdTarget[key] === 'object') {
deleteMatchingProperties(targetToMigrate[key], createdTarget[key]);
}
else if (targetToMigrate[key] === createdTarget[key]) {
delete targetToMigrate[key];
}
if (typeof targetToMigrate[key] === 'object' &&
Object.keys(targetToMigrate[key]).length === 0) {
delete targetToMigrate[key];
}
}
}
function processTargetOutputs(target, renamedOutputOptions, inferredTarget, projectDetails) {
const interpolatedInferredOutputs = (inferredTarget.outputs ?? []).map((output) => (0, devkit_internals_1.interpolate)(output, {
workspaceRoot: '',
projectRoot: projectDetails.projectRoot,
projectName: projectDetails.projectName,
}));
const targetOutputs = (target.outputs ?? []).map((output) => updateOutput(output, renamedOutputOptions));
const interpolatedOutputs = targetOutputs.map((output) => (0, devkit_internals_1.interpolate)(output, {
workspaceRoot: '',
projectRoot: projectDetails.projectRoot,
projectName: projectDetails.projectName,
}));
const shouldDelete = interpolatedOutputs.every((output) => interpolatedInferredOutputs.includes(output));
if (shouldDelete) {
// all existing outputs are already inferred
delete target.outputs;
return;
}
// move extra inferred outputs to the target outputs
for (let i = 0; i < interpolatedInferredOutputs.length; i++) {
if (!interpolatedOutputs.includes(interpolatedInferredOutputs[i])) {
targetOutputs.push(inferredTarget.outputs[i]);
interpolatedOutputs.push(interpolatedInferredOutputs[i]);
}
}
target.outputs = targetOutputs;
}
function toProjectRelativePath(path, projectRoot) {
if (projectRoot === '.') {
// workspace and project root are the same, we add a leading './' which is
// required by some tools (e.g. Jest)
return path.startsWith('.') ? path : `./${path}`;
}
const relativePath = (0, posix_1.relative)((0, posix_1.resolve)(devkit_exports_1.workspaceRoot, projectRoot), (0, posix_1.resolve)(devkit_exports_1.workspaceRoot, path));
return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
}
function updateOutputRenamingOption(output, option, previousName) {
const newOptionToken = `{options.${option}}`;
const oldOptionToken = `{options.${previousName}}`;
if (!output.startsWith('{workspaceRoot}') &&
!output.startsWith('{projectRoot}')) {
return `{projectRoot}/${output.replace(oldOptionToken, newOptionToken)}`;
}
if (output.startsWith('{workspaceRoot}') &&
!output.startsWith('{workspaceRoot}/{projectRoot}')) {
return output
.replace('{workspaceRoot}', '{projectRoot}')
.replace(oldOptionToken, newOptionToken);
}
return output.replace(oldOptionToken, newOptionToken);
}
function updateOutput(output, renamedOutputOptions) {
if (!/{options\..*}/.test(output)) {
// output does not contain any option tokens
return output;
}
for (const { newName, oldName } of renamedOutputOptions) {
const optionToken = `{options.${oldName}}`;
if (output.includes(optionToken)) {
return updateOutputRenamingOption(output, newName, oldName);
}
}
if (!output.startsWith('{workspaceRoot}') &&
!output.startsWith('{projectRoot}')) {
return `{projectRoot}/${output}`;
}
if (output.startsWith('{workspaceRoot}') &&
!output.startsWith('{workspaceRoot}/{projectRoot}')) {
return output.replace('{workspaceRoot}', '{projectRoot}');
}
return output;
}

View File

@@ -0,0 +1,42 @@
import { type ProjectType, type Tree } from 'nx/src/devkit-exports';
export type ProjectGenerationOptions = {
directory: string;
name?: string;
projectType: ProjectType;
importPath?: string;
rootProject?: boolean;
};
export type ProjectNameAndRootOptions = {
/**
* Normalized full project name, including scope if name was provided with
* scope (e.g., `@scope/name`)
*/
projectName: string;
/**
* Normalized project root, including the layout directory if configured.
*/
projectRoot: string;
names: {
/**
* Normalized project name without scope. It's meant to be used when
* generating file names that contain the project name.
*/
projectFileName: string;
/**
* Normalized project name without scope or directory. It's meant to be used
* when generating shorter file names that contain the project name.
*/
projectSimpleName: string;
};
/**
* Normalized import path for the project.
*/
importPath: string;
};
export declare function determineProjectNameAndRootOptions(tree: Tree, options: ProjectGenerationOptions): Promise<ProjectNameAndRootOptions>;
export declare function resolveImportPath(tree: Tree, projectName: string, projectRoot: string): string;
export declare function ensureRootProjectName(options: {
directory: string;
name?: string;
}, projectType: 'application' | 'library'): Promise<void>;
//# sourceMappingURL=project-name-and-root-utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"project-name-and-root-utils.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/project-name-and-root-utils.ts"],"names":[],"mappings":"AACA,OAAO,EAGL,KAAK,WAAW,EAEhB,KAAK,IAAI,EAEV,MAAM,uBAAuB,CAAC;AAG/B,MAAM,MAAM,wBAAwB,GAAG;IACrC,SAAS,EAAE,MAAM,CAAC;IAClB,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,WAAW,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,OAAO,CAAC;CACvB,CAAC;AAEF,MAAM,MAAM,yBAAyB,GAAG;IACtC;;;OAGG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB;;OAEG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE;QACL;;;WAGG;QACH,eAAe,EAAE,MAAM,CAAC;QACxB;;;WAGG;QACH,iBAAiB,EAAE,MAAM,CAAC;KAC3B,CAAC;IACF;;OAEG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB,CAAC;AAEF,wBAAsB,kCAAkC,CACtD,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,wBAAwB,GAChC,OAAO,CAAC,yBAAyB,CAAC,CAiEpC;AAED,wBAAgB,iBAAiB,CAC/B,IAAI,EAAE,IAAI,EACV,WAAW,EAAE,MAAM,EACnB,WAAW,EAAE,MAAM,GAClB,MAAM,CAcR;AAED,wBAAsB,qBAAqB,CACzC,OAAO,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,EAC7C,WAAW,EAAE,aAAa,GAAG,SAAS,GACrC,OAAO,CAAC,IAAI,CAAC,CASf"}

View File

@@ -0,0 +1,134 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.determineProjectNameAndRootOptions = determineProjectNameAndRootOptions;
exports.resolveImportPath = resolveImportPath;
exports.ensureRootProjectName = ensureRootProjectName;
const enquirer_1 = require("enquirer");
const devkit_exports_1 = require("nx/src/devkit-exports");
const path_1 = require("path");
async function determineProjectNameAndRootOptions(tree, options) {
// root projects must provide name option
if (options.directory === '.' && !options.name) {
throw new Error(`When generating a root project, you must also specify the name option.`);
}
const directory = (0, devkit_exports_1.normalizePath)(options.directory);
const name = options.name ??
directory.match(/(@[^@/]+(\/[^@/]+)+)/)?.[1] ??
directory.substring(directory.lastIndexOf('/') + 1);
validateOptions(options.name, name, options.directory);
let projectSimpleName;
let projectFileName;
if (name.startsWith('@')) {
const [_scope, ...rest] = name.split('/');
projectFileName = rest.join('-');
projectSimpleName = rest.pop();
}
else {
projectSimpleName = name;
projectFileName = name;
}
let projectRoot;
const relativeCwd = getRelativeCwd();
if (directory) {
// append the directory to the current working directory if it doesn't start with it
if (directory === relativeCwd || directory.startsWith(`${relativeCwd}/`)) {
projectRoot = directory;
}
else {
projectRoot = (0, devkit_exports_1.joinPathFragments)(relativeCwd, directory);
}
}
else if (options.rootProject) {
projectRoot = '.';
}
else {
projectRoot = relativeCwd;
// append the project name to the current working directory if it doesn't end with it
if (!relativeCwd.endsWith(name)) {
projectRoot = (0, devkit_exports_1.joinPathFragments)(relativeCwd, name);
}
}
if (projectRoot.startsWith('..')) {
throw new Error(`The resolved project root "${projectRoot}" is outside of the workspace root "${devkit_exports_1.workspaceRoot}".`);
}
const importPath = options.importPath ?? resolveImportPath(tree, name, projectRoot);
return {
projectName: name,
names: {
projectSimpleName,
projectFileName,
},
importPath,
projectRoot,
};
}
function resolveImportPath(tree, projectName, projectRoot) {
let importPath;
if (projectName.startsWith('@')) {
importPath = projectName;
}
else {
const npmScope = getNpmScope(tree);
importPath =
projectRoot === '.'
? ((0, devkit_exports_1.readJson)(tree, 'package.json').name ??
getImportPath(npmScope, projectName))
: getImportPath(npmScope, projectName);
}
return importPath;
}
async function ensureRootProjectName(options, projectType) {
if (!options.name && options.directory === '.' && getRelativeCwd() === '') {
const result = await (0, enquirer_1.prompt)({
type: 'input',
name: 'name',
message: `What do you want to name the ${projectType}?`,
});
options.name = result.name;
}
}
function validateOptions(providedName, derivedName, directory) {
/**
* The provided name and the derived name from the provided directory must match one of two cases:
*
* 1. Valid npm package names (e.g., '@scope/name' or 'name').
* 2. Names starting with a letter and can contain any character except whitespace and ':'.
*
* The second case is to support the legacy behavior (^[a-zA-Z].*$) with the difference
* that it doesn't allow the ":" character. It was wrong to allow it because it would
* conflict with the notation for tasks.
*/
const pattern = '(?:^@[a-zA-Z0-9-*~][a-zA-Z0-9-*._~]*\\/[a-zA-Z0-9-~][a-zA-Z0-9-._~]*|^[a-zA-Z][^:]*)$';
const validationRegex = new RegExp(pattern);
if (providedName) {
if (!validationRegex.test(providedName)) {
throw new Error(`The name should match the pattern "${pattern}". The provided value "${providedName}" does not match.`);
}
}
else if (!validationRegex.test(derivedName)) {
throw new Error(`The derived name from the provided directory should match the pattern "${pattern}". The derived name "${derivedName}" from the provided value "${directory}" does not match.`);
}
}
function getImportPath(npmScope, name) {
return npmScope ? `${npmScope === '@' ? '' : '@'}${npmScope}/${name}` : name;
}
function getNpmScope(tree) {
const { name } = tree.exists('package.json')
? (0, devkit_exports_1.readJson)(tree, 'package.json')
: { name: null };
return name?.startsWith('@') ? name.split('/')[0].substring(1) : undefined;
}
/**
* When running a script with the package manager (e.g. `npm run`), the package manager will
* traverse the directory tree upwards until it finds a `package.json` and will set `process.cwd()`
* to the folder where it found it. The actual working directory is stored in the INIT_CWD
* environment variable (see here: https://docs.npmjs.com/cli/v9/commands/npm-run-script#description).
*/
function getCwd() {
return process.env.INIT_CWD?.startsWith(devkit_exports_1.workspaceRoot)
? process.env.INIT_CWD
: process.cwd();
}
function getRelativeCwd() {
return (0, devkit_exports_1.normalizePath)((0, path_1.relative)(devkit_exports_1.workspaceRoot, getCwd())).replace(/\/$/, '');
}

3
node_modules/@nx/devkit/src/generators/prompt.d.ts generated vendored Normal file
View File

@@ -0,0 +1,3 @@
import { prompt } from 'enquirer';
export declare function promptWhenInteractive<T>(questions: Parameters<typeof prompt>[0], defaultValue: T): Promise<T>;
//# sourceMappingURL=prompt.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"prompt.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/prompt.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAC;AAGlC,wBAAsB,qBAAqB,CAAC,CAAC,EAC3C,SAAS,EAAE,UAAU,CAAC,OAAO,MAAM,CAAC,CAAC,CAAC,CAAC,EACvC,YAAY,EAAE,CAAC,GACd,OAAO,CAAC,CAAC,CAAC,CAMZ"}

14
node_modules/@nx/devkit/src/generators/prompt.js generated vendored Normal file
View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.promptWhenInteractive = promptWhenInteractive;
const enquirer_1 = require("enquirer");
const devkit_internals_1 = require("nx/src/devkit-internals");
async function promptWhenInteractive(questions, defaultValue) {
if (!isInteractive()) {
return defaultValue;
}
return await (0, enquirer_1.prompt)(questions);
}
function isInteractive() {
return (!(0, devkit_internals_1.isCI)() && !!process.stdout.isTTY && process.env.NX_INTERACTIVE === 'true');
}

View File

@@ -0,0 +1,8 @@
import type { GeneratorCallback } from 'nx/src/devkit-exports';
/**
* Run tasks in serial
*
* @param tasks The tasks to run in serial.
*/
export declare function runTasksInSerial(...tasks: GeneratorCallback[]): GeneratorCallback;
//# sourceMappingURL=run-tasks-in-serial.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"run-tasks-in-serial.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/run-tasks-in-serial.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,uBAAuB,CAAC;AAE/D;;;;GAIG;AACH,wBAAgB,gBAAgB,CAC9B,GAAG,KAAK,EAAE,iBAAiB,EAAE,GAC5B,iBAAiB,CAMnB"}

View File

@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.runTasksInSerial = runTasksInSerial;
/**
* Run tasks in serial
*
* @param tasks The tasks to run in serial.
*/
function runTasksInSerial(...tasks) {
return async () => {
for (const task of tasks) {
await task();
}
};
}

View File

@@ -0,0 +1,4 @@
import { type TargetConfiguration, type Tree } from 'nx/src/devkit-exports';
export declare function addBuildTargetDefaults(tree: Tree, executorName: string, buildTargetName?: string, extraInputs?: TargetConfiguration['inputs']): void;
export declare function addE2eCiTargetDefaults(tree: Tree, e2ePlugin: string, buildTarget: string, pathToE2EConfigFile: string): Promise<void>;
//# sourceMappingURL=target-defaults-utils.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"target-defaults-utils.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/target-defaults-utils.ts"],"names":[],"mappings":"AAAA,OAAO,EAGL,KAAK,mBAAmB,EACxB,KAAK,IAAI,EAGV,MAAM,uBAAuB,CAAC;AAG/B,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,IAAI,EACV,YAAY,EAAE,MAAM,EACpB,eAAe,SAAU,EACzB,WAAW,GAAE,mBAAmB,CAAC,QAAQ,CAAM,GAC9C,IAAI,CAcN;AAED,wBAAsB,sBAAsB,CAC1C,IAAI,EAAE,IAAI,EACV,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,MAAM,EACnB,mBAAmB,EAAE,MAAM,GAC1B,OAAO,CAAC,IAAI,CAAC,CAgEf"}

View File

@@ -0,0 +1,100 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.addBuildTargetDefaults = addBuildTargetDefaults;
exports.addE2eCiTargetDefaults = addE2eCiTargetDefaults;
const devkit_exports_1 = require("nx/src/devkit-exports");
const devkit_internals_1 = require("nx/src/devkit-internals");
function addBuildTargetDefaults(tree, executorName, buildTargetName = 'build', extraInputs = []) {
const nxJson = (0, devkit_exports_1.readNxJson)(tree);
nxJson.targetDefaults ??= {};
nxJson.targetDefaults[executorName] ??= {
cache: true,
dependsOn: [`^${buildTargetName}`],
inputs: [
...(nxJson.namedInputs && 'production' in nxJson.namedInputs
? ['production', '^production']
: ['default', '^default']),
...extraInputs,
],
};
(0, devkit_exports_1.updateNxJson)(tree, nxJson);
}
async function addE2eCiTargetDefaults(tree, e2ePlugin, buildTarget, pathToE2EConfigFile) {
const nxJson = (0, devkit_exports_1.readNxJson)(tree);
if (!nxJson.plugins) {
return;
}
const e2ePluginRegistrations = nxJson.plugins.filter((p) => typeof p === 'string' ? p === e2ePlugin : p.plugin === e2ePlugin);
if (!e2ePluginRegistrations.length) {
return;
}
const resolvedE2ePlugin = await Promise.resolve(`${e2ePlugin}`).then(s => __importStar(require(s)));
const e2ePluginGlob = resolvedE2ePlugin.createNodesV2?.[0] ?? resolvedE2ePlugin.createNodes?.[0];
let foundPluginForApplication;
for (let i = 0; i < e2ePluginRegistrations.length; i++) {
let candidatePluginForApplication = e2ePluginRegistrations[i];
if (typeof candidatePluginForApplication === 'string') {
foundPluginForApplication = candidatePluginForApplication;
break;
}
const matchingConfigFiles = (0, devkit_internals_1.findMatchingConfigFiles)([pathToE2EConfigFile], e2ePluginGlob, candidatePluginForApplication.include, candidatePluginForApplication.exclude);
if (matchingConfigFiles.length) {
foundPluginForApplication = candidatePluginForApplication;
break;
}
}
if (!foundPluginForApplication) {
return;
}
const ciTargetName = typeof foundPluginForApplication === 'string'
? 'e2e-ci'
: (foundPluginForApplication.options?.ciTargetName ?? 'e2e-ci');
const ciTargetNameGlob = `${ciTargetName}--**/**`;
nxJson.targetDefaults ??= {};
const e2eCiTargetDefaults = nxJson.targetDefaults[ciTargetNameGlob];
if (!e2eCiTargetDefaults) {
nxJson.targetDefaults[ciTargetNameGlob] = {
dependsOn: [buildTarget],
};
}
else {
e2eCiTargetDefaults.dependsOn ??= [];
if (!e2eCiTargetDefaults.dependsOn.includes(buildTarget)) {
e2eCiTargetDefaults.dependsOn.push(buildTarget);
}
}
(0, devkit_exports_1.updateNxJson)(tree, nxJson);
}

13
node_modules/@nx/devkit/src/generators/to-js.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import type { Tree } from 'nx/src/devkit-exports';
import type { ModuleKind, ScriptTarget } from 'typescript';
export type ToJSOptions = {
extension?: '.js' | '.mjs' | '.cjs';
module?: ModuleKind;
target?: ScriptTarget;
useJsx?: boolean;
};
/**
* Rename and transpile any new typescript files created to javascript files
*/
export declare function toJS(tree: Tree, options?: ToJSOptions): void;
//# sourceMappingURL=to-js.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"to-js.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/to-js.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAClD,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAI3D,MAAM,MAAM,WAAW,GAAG;IACxB,SAAS,CAAC,EAAE,KAAK,GAAG,MAAM,GAAG,MAAM,CAAC;IACpC,MAAM,CAAC,EAAE,UAAU,CAAC;IACpB,MAAM,CAAC,EAAE,YAAY,CAAC;IACtB,MAAM,CAAC,EAAE,OAAO,CAAC;CAClB,CAAC;AAEF;;GAEG;AACH,wBAAgB,IAAI,CAAC,IAAI,EAAE,IAAI,EAAE,OAAO,CAAC,EAAE,WAAW,GAAG,IAAI,CA+B5D"}

29
node_modules/@nx/devkit/src/generators/to-js.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toJS = toJS;
const versions_1 = require("../utils/versions");
const package_json_1 = require("../utils/package-json");
/**
* Rename and transpile any new typescript files created to javascript files
*/
function toJS(tree, options) {
const { JsxEmit, ScriptTarget, transpile, ModuleKind } = (0, package_json_1.ensurePackage)('typescript', versions_1.typescriptVersion);
for (const c of tree.listChanges()) {
if ((c.path.endsWith('.ts') || c.path.endsWith('tsx')) &&
c.type === 'CREATE') {
tree.write(c.path, transpile(c.content.toString('utf-8'), {
allowJs: true,
jsx: JsxEmit.Preserve,
target: options?.target ?? ScriptTarget.ESNext,
module: options?.module ?? ModuleKind.ESNext,
}));
tree.rename(c.path, c.path.replace(/\.ts$/, options?.extension ?? '.js'));
if (options?.useJsx) {
tree.rename(c.path, c.path.replace(/\.tsx$/, '.jsx'));
}
else {
tree.rename(c.path, c.path.replace(/\.tsx$/, options?.extension ?? '.js'));
}
}
}
}

View File

@@ -0,0 +1,2 @@
export declare function insertImport(): void;
//# sourceMappingURL=insert-import.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"insert-import.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/generators/typescript/insert-import.ts"],"names":[],"mappings":"AAAA,wBAAgB,YAAY,IAAI,IAAI,CAAG"}

View File

@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertImport = insertImport;
function insertImport() { }

View File

@@ -0,0 +1,2 @@
export declare function insertImport(): void;
//# sourceMappingURL=insert-statement.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"insert-statement.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/generators/typescript/insert-statement.ts"],"names":[],"mappings":"AAAA,wBAAgB,YAAY,IAAI,IAAI,CAAG"}

View File

@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.insertImport = insertImport;
function insertImport() { }

View File

@@ -0,0 +1,5 @@
import { Tree } from 'nx/src/devkit-exports';
export declare function updateTsConfigsToJs(tree: Tree, options: {
projectRoot: string;
}): void;
//# sourceMappingURL=update-ts-configs-to-js.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"update-ts-configs-to-js.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/update-ts-configs-to-js.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAc,MAAM,uBAAuB,CAAC;AAEzD,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,IAAI,EACV,OAAO,EAAE;IAAE,WAAW,EAAE,MAAM,CAAA;CAAE,GAC/B,IAAI,CA0CN"}

View File

@@ -0,0 +1,42 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateTsConfigsToJs = updateTsConfigsToJs;
const devkit_exports_1 = require("nx/src/devkit-exports");
function updateTsConfigsToJs(tree, options) {
let updateConfigPath = null;
const paths = {
tsConfig: `${options.projectRoot}/tsconfig.json`,
tsConfigLib: `${options.projectRoot}/tsconfig.lib.json`,
tsConfigApp: `${options.projectRoot}/tsconfig.app.json`,
};
(0, devkit_exports_1.updateJson)(tree, paths.tsConfig, (json) => {
if (json.compilerOptions) {
json.compilerOptions.allowJs = true;
}
else {
json.compilerOptions = { allowJs: true };
}
return json;
});
if (tree.exists(paths.tsConfigLib)) {
updateConfigPath = paths.tsConfigLib;
}
if (tree.exists(paths.tsConfigApp)) {
updateConfigPath = paths.tsConfigApp;
}
if (updateConfigPath) {
(0, devkit_exports_1.updateJson)(tree, updateConfigPath, (json) => {
json.include = uniq([...(json.include ?? []), 'src/**/*.js']);
json.exclude = uniq([
...(json.exclude ?? []),
'src/**/*.spec.js',
'src/**/*.test.js',
]);
return json;
});
}
else {
throw new Error(`project is missing tsconfig.lib.json or tsconfig.app.json`);
}
}
const uniq = (value) => [...new Set(value)];

View File

@@ -0,0 +1,6 @@
import type { Tree } from 'nx/src/devkit-exports';
/**
* Utility to act on all files in a tree that are not ignored by git.
*/
export declare function visitNotIgnoredFiles(tree: Tree, dirPath: string, visitor: (path: string) => void): void;
//# sourceMappingURL=visit-not-ignored-files.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"visit-not-ignored-files.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/generators/visit-not-ignored-files.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,MAAM,uBAAuB,CAAC;AAIlD;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,IAAI,EAAE,IAAI,EACV,OAAO,EAAE,MAAkB,EAC3B,OAAO,EAAE,CAAC,IAAI,EAAE,MAAM,KAAK,IAAI,GAC9B,IAAI,CAiBN"}

View File

@@ -0,0 +1,30 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.visitNotIgnoredFiles = visitNotIgnoredFiles;
const devkit_internals_1 = require("nx/src/devkit-internals");
const path_1 = require("path");
/**
* Utility to act on all files in a tree that are not ignored by git.
*/
function visitNotIgnoredFiles(tree, dirPath = tree.root, visitor) {
const ig = (0, devkit_internals_1.getIgnoreObjectForTree)(tree);
dirPath = normalizePathRelativeToRoot(dirPath, tree.root);
if (dirPath !== '' && ig?.ignores(dirPath)) {
return;
}
for (const child of tree.children(dirPath)) {
const fullPath = (0, path_1.join)(dirPath, child);
if (ig?.ignores(fullPath)) {
continue;
}
if (tree.isFile(fullPath)) {
visitor(fullPath);
}
else {
visitNotIgnoredFiles(tree, fullPath, visitor);
}
}
}
function normalizePathRelativeToRoot(path, root) {
return (0, path_1.relative)(root, (0, path_1.join)(root, path)).split(path_1.sep).join('/');
}

View File

@@ -0,0 +1,11 @@
import { PackageManager, Tree } from 'nx/src/devkit-exports';
/**
* Runs `npm install` or `yarn install`. It will skip running the install if
* `package.json` hasn't changed at all or it hasn't changed since the last invocation.
*
* @param tree - the file system tree
* @param ensureInstall - ensure install runs even if `package.json` hasn't changed,
* unless install already ran this generator cycle.
*/
export declare function installPackagesTask(tree: Tree, ensureInstall?: boolean, cwd?: string, packageManager?: PackageManager): void;
//# sourceMappingURL=install-packages-task.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"install-packages-task.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/tasks/install-packages-task.ts"],"names":[],"mappings":"AAGA,OAAO,EAIL,cAAc,EACd,IAAI,EACL,MAAM,uBAAuB,CAAC;AAE/B;;;;;;;GAOG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,IAAI,EACV,aAAa,GAAE,OAAe,EAC9B,GAAG,GAAE,MAAW,EAChB,cAAc,GAAE,cAA2D,GAC1E,IAAI,CAmCN"}

View File

@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.installPackagesTask = installPackagesTask;
const child_process_1 = require("child_process");
const path_1 = require("path");
const devkit_exports_1 = require("nx/src/devkit-exports");
/**
* Runs `npm install` or `yarn install`. It will skip running the install if
* `package.json` hasn't changed at all or it hasn't changed since the last invocation.
*
* @param tree - the file system tree
* @param ensureInstall - ensure install runs even if `package.json` hasn't changed,
* unless install already ran this generator cycle.
*/
function installPackagesTask(tree, ensureInstall = false, cwd = '', packageManager = (0, devkit_exports_1.detectPackageManager)((0, path_1.join)(tree.root, cwd))) {
const packageJsonPath = (0, devkit_exports_1.joinPathFragments)(cwd, 'package.json');
const packageJsonChanged = tree
.listChanges()
.some((f) => f.path === packageJsonPath);
if (!packageJsonChanged && !ensureInstall) {
return;
}
const packageJsonValue = tree.read(packageJsonPath, 'utf-8');
const storedPackageJsonValue = global['__packageJsonInstallCache__'];
const installAlreadyRan = storedPackageJsonValue != null;
const packageJsonDiffers = storedPackageJsonValue != packageJsonValue;
if (packageJsonDiffers || (ensureInstall && !installAlreadyRan)) {
global['__packageJsonInstallCache__'] = packageJsonValue;
const pmc = (0, devkit_exports_1.getPackageManagerCommand)(packageManager);
const execSyncOptions = {
cwd: (0, path_1.join)(tree.root, cwd),
stdio: process.env.NX_GENERATE_QUIET === 'true' ? 'ignore' : 'inherit',
windowsHide: true,
};
// ensure local registry from process is not interfering with the install
// when we start the process from temp folder the local registry would override the custom registry
if (process.env.npm_config_registry &&
process.env.npm_config_registry.match(/^https:\/\/registry\.(npmjs\.org|yarnpkg\.com)/)) {
delete process.env.npm_config_registry;
}
(0, child_process_1.execSync)(pmc.install, execSyncOptions);
}
}

14
node_modules/@nx/devkit/src/utils/add-plugin.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { CreateNodesV2, ProjectGraph, Tree } from 'nx/src/devkit-exports';
/**
* Iterates through various forms of plugin options to find the one which does not conflict with the current graph
*/
export declare function addPlugin<PluginOptions>(tree: Tree, graph: ProjectGraph, pluginName: string, createNodesTuple: CreateNodesV2<PluginOptions>, options: Partial<Record<keyof PluginOptions, PluginOptions[keyof PluginOptions][]>>, shouldUpdatePackageJsonScripts: boolean): Promise<void>;
/**
* @deprecated Use `addPlugin` instead
* Iterates through various forms of plugin options to find the one which does not conflict with the current graph
*/
export declare function addPluginV1<PluginOptions>(tree: Tree, graph: ProjectGraph, pluginName: string, createNodesTuple: CreateNodesV2<PluginOptions>, options: Partial<Record<keyof PluginOptions, PluginOptions[keyof PluginOptions][]>>, shouldUpdatePackageJsonScripts: boolean): Promise<void>;
export declare function generateCombinations<T>(input: Record<string, T[]>): Record<string, T>[];
//# sourceMappingURL=add-plugin.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"add-plugin.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/utils/add-plugin.ts"],"names":[],"mappings":"AAKA,OAAO,EACL,aAAa,EAEb,YAAY,EAGZ,IAAI,EAGL,MAAM,uBAAuB,CAAC;AAQ/B;;;GAGG;AACH,wBAAsB,SAAS,CAAC,aAAa,EAC3C,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,YAAY,EACnB,UAAU,EAAE,MAAM,EAClB,gBAAgB,EAAE,aAAa,CAAC,aAAa,CAAC,EAC9C,OAAO,EAAE,OAAO,CACd,MAAM,CAAC,MAAM,aAAa,EAAE,aAAa,CAAC,MAAM,aAAa,CAAC,EAAE,CAAC,CAClE,EACD,8BAA8B,EAAE,OAAO,GACtC,OAAO,CAAC,IAAI,CAAC,CAmBf;AAED;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,aAAa,EAC7C,IAAI,EAAE,IAAI,EACV,KAAK,EAAE,YAAY,EACnB,UAAU,EAAE,MAAM,EAClB,gBAAgB,EAAE,aAAa,CAAC,aAAa,CAAC,EAC9C,OAAO,EAAE,OAAO,CACd,MAAM,CAAC,MAAM,aAAa,EAAE,aAAa,CAAC,MAAM,aAAa,CAAC,EAAE,CAAC,CAClE,EACD,8BAA8B,EAAE,OAAO,GACtC,OAAO,CAAC,IAAI,CAAC,CAmBf;AAoUD,wBAAgB,oBAAoB,CAAC,CAAC,EACpC,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,CAAC,GACzB,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,EAAE,CAarB"}

291
node_modules/@nx/devkit/src/utils/add-plugin.js generated vendored Normal file
View File

@@ -0,0 +1,291 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.addPlugin = addPlugin;
exports.addPluginV1 = addPluginV1;
exports.generateCombinations = generateCombinations;
const tslib_1 = require("tslib");
const yargs_parser_1 = tslib_1.__importDefault(require("yargs-parser"));
const devkit_exports_1 = require("nx/src/devkit-exports");
const devkit_internals_1 = require("nx/src/devkit-internals");
/**
* Iterates through various forms of plugin options to find the one which does not conflict with the current graph
*/
async function addPlugin(tree, graph, pluginName, createNodesTuple, options, shouldUpdatePackageJsonScripts) {
return _addPluginInternal(tree, graph, pluginName, (pluginOptions) => new devkit_internals_1.LoadedNxPlugin({
name: pluginName,
createNodesV2: createNodesTuple,
}, {
plugin: pluginName,
options: pluginOptions,
}), options, shouldUpdatePackageJsonScripts);
}
/**
* @deprecated Use `addPlugin` instead
* Iterates through various forms of plugin options to find the one which does not conflict with the current graph
*/
async function addPluginV1(tree, graph, pluginName, createNodesTuple, options, shouldUpdatePackageJsonScripts) {
return _addPluginInternal(tree, graph, pluginName, (pluginOptions) => new devkit_internals_1.LoadedNxPlugin({
name: pluginName,
createNodes: createNodesTuple,
}, {
plugin: pluginName,
options: pluginOptions,
}), options, shouldUpdatePackageJsonScripts);
}
async function _addPluginInternal(tree, graph, pluginName, pluginFactory, options, shouldUpdatePackageJsonScripts) {
const graphNodes = Object.values(graph.nodes);
const nxJson = (0, devkit_exports_1.readNxJson)(tree);
let pluginOptions;
let projConfigs;
if (Object.keys(options).length > 0) {
const combinations = generateCombinations(options);
optionsLoop: for (const _pluginOptions of combinations) {
pluginOptions = _pluginOptions;
nxJson.plugins ??= [];
if (nxJson.plugins.some((p) => typeof p === 'string'
? p === pluginName
: p.plugin === pluginName && !p.include)) {
// Plugin has already been added
return;
}
global.NX_GRAPH_CREATION = true;
try {
projConfigs = await (0, devkit_internals_1.retrieveProjectConfigurations)([pluginFactory(pluginOptions)], tree.root, nxJson);
}
catch (e) {
// Errors are okay for this because we're only running 1 plugin
if ((0, devkit_internals_1.isProjectConfigurationsError)(e)) {
projConfigs = e.partialProjectConfigurationsResult;
// ignore errors from projects with no name
if (!e.errors.every(devkit_internals_1.isProjectsWithNoNameError)) {
throw e;
}
}
else {
throw e;
}
}
global.NX_GRAPH_CREATION = false;
for (const projConfig of Object.values(projConfigs.projects)) {
const node = graphNodes.find((node) => node.data.root === projConfig.root);
if (!node) {
continue;
}
for (const targetName in projConfig.targets) {
if (node.data.targets[targetName]) {
// Conflicting Target Name, check the next one
pluginOptions = null;
continue optionsLoop;
}
}
}
break;
}
}
else {
// If the plugin does not take in options, we add the plugin with empty options.
nxJson.plugins ??= [];
pluginOptions = {};
global.NX_GRAPH_CREATION = true;
try {
projConfigs = await (0, devkit_internals_1.retrieveProjectConfigurations)([pluginFactory(pluginOptions)], tree.root, nxJson);
}
catch (e) {
// Errors are okay for this because we're only running 1 plugin
if ((0, devkit_internals_1.isProjectConfigurationsError)(e)) {
projConfigs = e.partialProjectConfigurationsResult;
// ignore errors from projects with no name
if (!e.errors.every(devkit_internals_1.isProjectsWithNoNameError)) {
throw e;
}
}
else {
throw e;
}
}
global.NX_GRAPH_CREATION = false;
}
if (!pluginOptions) {
throw new Error('Could not add the plugin in a way which does not conflict with existing targets. Please report this error at: https://github.com/nrwl/nx/issues/new/choose');
}
nxJson.plugins.push({
plugin: pluginName,
options: pluginOptions,
});
(0, devkit_exports_1.updateNxJson)(tree, nxJson);
if (shouldUpdatePackageJsonScripts) {
updatePackageScripts(tree, projConfigs);
}
}
function updatePackageScripts(tree, projectConfigurations) {
for (const projectConfig of Object.values(projectConfigurations.projects)) {
const projectRoot = projectConfig.root;
processProject(tree, projectRoot, projectConfig);
}
}
function processProject(tree, projectRoot, projectConfiguration) {
const packageJsonPath = `${projectRoot}/package.json`;
if (!tree.exists(packageJsonPath)) {
return;
}
const packageJson = (0, devkit_exports_1.readJson)(tree, packageJsonPath);
if (!packageJson.scripts || !Object.keys(packageJson.scripts).length) {
return;
}
const targetCommands = getInferredTargetCommands(projectConfiguration);
if (!targetCommands.length) {
return;
}
let hasChanges = false;
targetCommands.sort((a, b) => b.command.split(/\s/).length - a.command.split(/\s/).length);
for (const targetCommand of targetCommands) {
const { command, target, configuration } = targetCommand;
const targetCommandRegex = new RegExp(`(?<=^|&)((?: )*(?:[^&\\r\\n\\s]+ )*)(${command})((?: [^&\\r\\n\\s]+)*(?: )*)(?=$|&)`, 'g');
for (const scriptName of Object.keys(packageJson.scripts)) {
const script = packageJson.scripts[scriptName];
// quick check for exact match within the script
if (targetCommandRegex.test(script)) {
packageJson.scripts[scriptName] = script.replace(targetCommandRegex, configuration
? `$1nx ${target} --configuration=${configuration}$3`
: `$1nx ${target}$3`);
hasChanges = true;
}
else {
/**
* Parse script and command to handle the following:
* - if command doesn't match script => don't replace
* - if command has more args => don't replace
* - if command has same args, regardless of order => replace removing args
* - if command has less args or with different value => replace leaving args
*/
const parsedCommand = (0, yargs_parser_1.default)(command, {
configuration: { 'strip-dashed': true },
});
// this assumes there are no positional args in the command, everything is a command or subcommand
const commandCommand = parsedCommand._.join(' ');
const commandRegex = new RegExp(`(?<=^|&)((?: )*(?:[^&\\r\\n\\s]+ )*)(${commandCommand})((?: [^&\\r\\n\\s]+)*( )*)(?=$|&)`, 'g');
const matches = script.match(commandRegex);
if (!matches) {
// the command doesn't match the script, don't replace
continue;
}
for (const match of matches) {
// parse the matched command within the script
const parsedScript = (0, yargs_parser_1.default)(match, {
configuration: { 'strip-dashed': true },
});
let hasArgsWithDifferentValues = false;
let scriptHasExtraArgs = false;
let commandHasExtraArgs = false;
for (const [key, value] of Object.entries(parsedCommand)) {
if (key === '_') {
continue;
}
if (parsedScript[key] === undefined) {
commandHasExtraArgs = true;
break;
}
if (parsedScript[key] !== value) {
hasArgsWithDifferentValues = true;
}
}
if (commandHasExtraArgs) {
// the command has extra args, don't replace
continue;
}
for (const key of Object.keys(parsedScript)) {
if (key === '_') {
continue;
}
if (!parsedCommand[key]) {
scriptHasExtraArgs = true;
break;
}
}
if (!hasArgsWithDifferentValues && !scriptHasExtraArgs) {
// they are the same, replace with the command removing the args
const script = packageJson.scripts[scriptName];
packageJson.scripts[scriptName] = script.replace(match, match.replace(commandRegex, configuration
? `$1nx ${target} --configuration=${configuration}$4`
: `$1nx ${target}$4`));
hasChanges = true;
}
else {
// there are different args or the script has extra args, replace with the command leaving the args
packageJson.scripts[scriptName] = packageJson.scripts[scriptName].replace(match, match.replace(commandRegex, configuration
? `$1nx ${target} --configuration=${configuration}$3`
: `$1nx ${target}$3`));
hasChanges = true;
}
}
}
}
}
if (hasChanges) {
(0, devkit_exports_1.writeJson)(tree, packageJsonPath, packageJson);
}
}
function getInferredTargetCommands(project) {
const targetCommands = [];
for (const [targetName, target] of Object.entries(project.targets ?? {})) {
if (target.command) {
targetCommands.push({ command: target.command, target: targetName });
}
else if (target.executor === 'nx:run-commands' &&
target.options?.command) {
targetCommands.push({
command: target.options.command,
target: targetName,
});
}
if (!target.configurations) {
continue;
}
for (const [configurationName, configuration] of Object.entries(target.configurations)) {
if (configuration.command) {
targetCommands.push({
command: configuration.command,
target: targetName,
configuration: configurationName,
});
}
else if (target.executor === 'nx:run-commands' &&
configuration.options?.command) {
targetCommands.push({
command: configuration.options.command,
target: targetName,
configuration: configurationName,
});
}
}
}
return targetCommands;
}
function generateCombinations(input) {
// This is reversed so that combinations have the first defined property updated first
const keys = Object.keys(input).reverse();
return _generateCombinations(Object.values(input).reverse()).map((combination) => {
const result = {};
combination.reverse().forEach((combo, i) => {
result[keys[keys.length - i - 1]] = combo;
});
return result;
});
}
/**
* Generate all possible combinations of a 2-dimensional array.
*
* Useful for generating all possible combinations of options for a plugin
*/
function _generateCombinations(input) {
if (input.length === 0) {
return [[]];
}
else {
const [first, ...rest] = input;
const partialCombinations = _generateCombinations(rest);
return first.flatMap((value) => partialCombinations.map((combination) => [value, ...combination]));
}
}

View File

@@ -0,0 +1,4 @@
export declare function combineAsyncIterables<T = any>(..._iterators: {
0: AsyncIterable<T>;
} & AsyncIterable<T>[]): AsyncGenerator<T>;
//# sourceMappingURL=combine-async-iterables.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"combine-async-iterables.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/utils/async-iterable/combine-async-iterables.ts"],"names":[],"mappings":"AAAA,wBAAuB,qBAAqB,CAAC,CAAC,GAAG,GAAG,EAClD,GAAG,UAAU,EAAE;IAAE,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,CAAA;CAAE,GAAG,aAAa,CAAC,CAAC,CAAC,EAAE,GAC1D,cAAc,CAAC,CAAC,CAAC,CA8CnB"}

View File

@@ -0,0 +1,59 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.combineAsyncIterables = combineAsyncIterables;
async function* combineAsyncIterables(..._iterators) {
// Convert iterables into iterators with next, return, throws methods.
// If it's already an iterator, keep it.
const iterators = _iterators.map((it) => {
if (typeof it['next'] === 'function') {
return it;
}
else {
return (async function* wrapped() {
for await (const val of it) {
yield val;
}
})();
}
});
let [options] = iterators;
if (typeof options.next === 'function') {
options = Object.create(null);
}
else {
iterators.shift();
}
const getNextAsyncIteratorValue = getNextAsyncIteratorFactory(options);
const asyncIteratorsValues = new Map(iterators.map((it, idx) => [idx, getNextAsyncIteratorValue(it, idx)]));
try {
do {
const { iterator, index } = await Promise.race(asyncIteratorsValues.values());
if (iterator.done) {
asyncIteratorsValues.delete(index);
}
else {
yield iterator.value;
asyncIteratorsValues.set(index, getNextAsyncIteratorValue(iterators[index], index));
}
} while (asyncIteratorsValues.size > 0);
}
finally {
for (const [index, iterator] of asyncIteratorsValues.entries())
if (iterator?.['return'] !== null)
iterator['return']?.();
}
}
function getNextAsyncIteratorFactory(options) {
return async (asyncIterator, index) => {
try {
const iterator = await asyncIterator.next();
return { index, iterator };
}
catch (err) {
if (options.errorCallback) {
options.errorCallback(err, index);
}
return Promise.reject(err);
}
};
}

View File

@@ -0,0 +1,8 @@
export interface AsyncPushCallbacks<T> {
next: (value: T) => void;
done: () => void;
error: (err: unknown) => void;
registerCleanup?: (cb: () => void | Promise<void>) => void;
}
export declare function createAsyncIterable<T = unknown>(listener: (ls: AsyncPushCallbacks<T>) => void): AsyncIterable<T>;
//# sourceMappingURL=create-async-iterable.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"create-async-iterable.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/utils/async-iterable/create-async-iterable.ts"],"names":[],"mappings":"AAAA,MAAM,WAAW,kBAAkB,CAAC,CAAC;IACnC,IAAI,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,CAAC;IACzB,IAAI,EAAE,MAAM,IAAI,CAAC;IACjB,KAAK,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,CAAC;IAC9B,eAAe,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,KAAK,IAAI,CAAC;CAC5D;AAED,wBAAgB,mBAAmB,CAAC,CAAC,GAAG,OAAO,EAC7C,QAAQ,EAAE,CAAC,EAAE,EAAE,kBAAkB,CAAC,CAAC,CAAC,KAAK,IAAI,GAC5C,aAAa,CAAC,CAAC,CAAC,CAmElB"}

View File

@@ -0,0 +1,67 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createAsyncIterable = createAsyncIterable;
function createAsyncIterable(listener) {
let done = false;
let error = null;
let cleanup;
const pushQueue = [];
const pullQueue = [];
return {
[Symbol.asyncIterator]() {
listener({
next: (value) => {
if (done || error)
return;
if (pullQueue.length > 0) {
pullQueue.shift()?.[0]({ value, done: false });
}
else {
pushQueue.push(value);
}
},
error: (err) => {
if (done || error)
return;
if (pullQueue.length > 0) {
pullQueue.shift()?.[1](err);
}
error = err;
},
done: () => {
if (pullQueue.length > 0) {
pullQueue.shift()?.[0]({ value: undefined, done: true });
}
done = true;
},
registerCleanup: (cb) => {
cleanup = cb;
},
});
return {
next() {
return new Promise((resolve, reject) => {
if (pushQueue.length > 0) {
resolve({ value: pushQueue.shift(), done: false });
}
else if (done) {
resolve({ value: undefined, done: true });
}
else if (error) {
reject(error);
}
else {
pullQueue.push([resolve, reject]);
}
});
},
async return() {
if (cleanup) {
await cleanup();
}
return { value: undefined, done: true };
},
};
},
};
}

View File

@@ -0,0 +1,5 @@
export * from './create-async-iterable';
export * from './combine-async-iterables';
export * from './map-async-iteratable';
export * from './tap-async-iteratable';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/utils/async-iterable/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,wBAAwB,CAAC;AACvC,cAAc,wBAAwB,CAAC"}

View File

@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
tslib_1.__exportStar(require("./create-async-iterable"), exports);
tslib_1.__exportStar(require("./combine-async-iterables"), exports);
tslib_1.__exportStar(require("./map-async-iteratable"), exports);
tslib_1.__exportStar(require("./tap-async-iteratable"), exports);

View File

@@ -0,0 +1,2 @@
export declare function mapAsyncIterable<T = any, I = any, O = any>(data: AsyncIterable<T> | AsyncIterableIterator<T>, transform: (input: I, index?: number, data?: AsyncIterable<T> | AsyncIterableIterator<T>) => O): AsyncIterable<O> | AsyncIterableIterator<O>;
//# sourceMappingURL=map-async-iteratable.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"map-async-iteratable.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/utils/async-iterable/map-async-iteratable.ts"],"names":[],"mappings":"AAAA,wBAAuB,gBAAgB,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAC/D,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,qBAAqB,CAAC,CAAC,CAAC,EACjD,SAAS,EAAE,CACT,KAAK,EAAE,CAAC,EACR,KAAK,CAAC,EAAE,MAAM,EACd,IAAI,CAAC,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,qBAAqB,CAAC,CAAC,CAAC,KAC/C,CAAC,GACL,aAAa,CAAC,CAAC,CAAC,GAAG,qBAAqB,CAAC,CAAC,CAAC,CAc7C"}

View File

@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.mapAsyncIterable = mapAsyncIterable;
async function* mapAsyncIterable(data, transform) {
async function* f() {
const generator = data[Symbol.asyncIterator] || data[Symbol.iterator];
const iterator = generator.call(data);
let index = 0;
let item = await iterator.next();
while (!item.done) {
yield await transform(await item.value, index, data);
index++;
item = await iterator.next();
}
}
return yield* f();
}

View File

@@ -0,0 +1,2 @@
export declare function tapAsyncIterable<T = any, I = any, O = any>(data: AsyncIterable<T> | AsyncIterableIterator<T>, fn: (input: I) => void): AsyncIterable<T> | AsyncIterableIterator<T>;
//# sourceMappingURL=tap-async-iteratable.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"tap-async-iteratable.d.ts","sourceRoot":"","sources":["../../../../../../packages/devkit/src/utils/async-iterable/tap-async-iteratable.ts"],"names":[],"mappings":"AAEA,wBAAuB,gBAAgB,CAAC,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAAE,CAAC,GAAG,GAAG,EAC/D,IAAI,EAAE,aAAa,CAAC,CAAC,CAAC,GAAG,qBAAqB,CAAC,CAAC,CAAC,EACjD,EAAE,EAAE,CAAC,KAAK,EAAE,CAAC,KAAK,IAAI,GACrB,aAAa,CAAC,CAAC,CAAC,GAAG,qBAAqB,CAAC,CAAC,CAAC,CAK7C"}

View File

@@ -0,0 +1,10 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.tapAsyncIterable = tapAsyncIterable;
const map_async_iteratable_1 = require("./map-async-iteratable");
async function* tapAsyncIterable(data, fn) {
return yield* (0, map_async_iteratable_1.mapAsyncIterable)(data, (x) => {
fn(x);
return x;
});
}

View File

@@ -0,0 +1,2 @@
export declare function isBinaryPath(path: string): boolean;
//# sourceMappingURL=binary-extensions.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"binary-extensions.d.ts","sourceRoot":"","sources":["../../../../../packages/devkit/src/utils/binary-extensions.ts"],"names":[],"mappings":"AAoRA,wBAAgB,YAAY,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAElD"}

280
node_modules/@nx/devkit/src/utils/binary-extensions.js generated vendored Normal file
View File

@@ -0,0 +1,280 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.isBinaryPath = isBinaryPath;
const path_1 = require("path");
const binaryExtensions = new Set([
// types originally from https://github.com/sindresorhus/binary-extensions/blob/40e44b510d87a63dcf42300bc8fbcb105f45a61c/binary-extensions.json
'.3dm',
'.3ds',
'.3g2',
'.3gp',
'.7z',
'.a',
'.aac',
'.adp',
'.ai',
'.aif',
'.aiff',
'.als',
'.alz',
'.ape',
'.apk',
'.appimage',
'.ar',
'.arj',
'.asf',
'.au',
'.avi',
'.bak',
'.baml',
'.bh',
'.bin',
'.bk',
'.bmp',
'.btif',
'.bz2',
'.bzip2',
'.cab',
'.caf',
'.cgm',
'.class',
'.cmx',
'.cpio',
'.cr2',
'.cur',
'.dat',
'.dcm',
'.deb',
'.dex',
'.djvu',
'.dll',
'.dmg',
'.dng',
'.doc',
'.docm',
'.docx',
'.dot',
'.dotm',
'.dra',
'.DS_Store',
'.dsk',
'.dts',
'.dtshd',
'.dvb',
'.dwg',
'.dxf',
'.ecelp4800',
'.ecelp7470',
'.ecelp9600',
'.egg',
'.eol',
'.eot',
'.epub',
'.exe',
'.f4v',
'.fbs',
'.fh',
'.fla',
'.flac',
'.flatpak',
'.fli',
'.flv',
'.fpx',
'.fst',
'.fvt',
'.g3',
'.gh',
'.gif',
'.glb',
'.graffle',
'.gz',
'.gzip',
'.h261',
'.h263',
'.h264',
'.icns',
'.ico',
'.ief',
'.img',
'.ipa',
'.iso',
'.jar',
'.jpeg',
'.jpg',
'.jpgv',
'.jpm',
'.jxr',
'.key',
'.keystore',
'.ktx',
'.lha',
'.lib',
'.lvp',
'.lz',
'.lzh',
'.lzma',
'.lzo',
'.m3u',
'.m4a',
'.m4v',
'.mar',
'.mdi',
'.mht',
'.mid',
'.midi',
'.mj2',
'.mka',
'.mkv',
'.mmr',
'.mng',
'.mobi',
'.mov',
'.movie',
'.mp3',
'.mp4',
'.mp4a',
'.mpeg',
'.mpg',
'.mpga',
'.msi',
'.mxu',
'.nef',
'.npx',
'.npy',
'.numbers',
'.nupkg',
'.o',
'.odp',
'.ods',
'.odt',
'.oga',
'.ogg',
'.ogv',
'.otf',
'.ott',
'.pages',
'.pbm',
'.pbf',
'.pcx',
'.pdb',
'.pdf',
'.pea',
'.pgm',
'.pic',
'.pkg',
'.plist',
'.png',
'.pnm',
'.pot',
'.potm',
'.potx',
'.ppa',
'.ppam',
'.ppm',
'.pps',
'.ppsm',
'.ppsx',
'.ppt',
'.pptm',
'.pptx',
'.psd',
'.pxd',
'.pxz',
'.pya',
'.pyc',
'.pyo',
'.pyv',
'.qt',
'.rar',
'.ras',
'.raw',
'.resources',
'.rgb',
'.rip',
'.riv',
'.rlc',
'.rmf',
'.rmvb',
'.rpm',
'.rtf',
'.rz',
'.s3m',
'.s7z',
'.scpt',
'.sgi',
'.shar',
'.snap',
'.sil',
'.sketch',
'.slk',
'.smv',
'.snk',
'.so',
'.stl',
'.suo',
'.sub',
'.swf',
'.tar',
'.tbz',
'.tbz2',
'.tga',
'.tgz',
'.thmx',
'.tif',
'.tiff',
'.tlz',
'.ttc',
'.ttf',
'.txz',
'.udf',
'.uvh',
'.uvi',
'.uvm',
'.uvp',
'.uvs',
'.uvu',
'.viv',
'.vob',
'.war',
'.wav',
'.wax',
'.wbmp',
'.wdp',
'.weba',
'.webm',
'.webp',
'.whl',
'.wim',
'.wm',
'.wma',
'.wmv',
'.wmx',
'.woff',
'.woff2',
'.wrm',
'.wvx',
'.xbm',
'.xif',
'.xla',
'.xlam',
'.xls',
'.xlsb',
'.xlsm',
'.xlsx',
'.xlt',
'.xltm',
'.xltx',
'.xm',
'.xmind',
'.xpi',
'.xpm',
'.xwd',
'.xz',
'.z',
'.zip',
'.zipx',
]);
// TODO(v24): use the version from nx/src/utils
function isBinaryPath(path) {
return binaryExtensions.has((0, path_1.extname)(path).toLowerCase());
}

View File

@@ -0,0 +1,4 @@
import { CreateNodesContextV2 } from 'nx/src/devkit-exports';
export declare function calculateHashForCreateNodes(projectRoot: string, options: object, context: CreateNodesContextV2, additionalGlobs?: string[]): Promise<string>;
export declare function calculateHashesForCreateNodes(projectRoots: string[], options: object, context: CreateNodesContextV2, additionalGlobs?: string[][]): Promise<string[]>;
//# sourceMappingURL=calculate-hash-for-create-nodes.d.ts.map

Some files were not shown because too many files have changed in this diff Show More