@nx/js 16.4.0-beta.1 → 16.4.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/executors.json +1 -0
  2. package/generators.json +12 -0
  3. package/package.json +6 -5
  4. package/plugins/jest/local-registry.d.ts +1 -0
  5. package/plugins/jest/local-registry.js +4 -0
  6. package/src/executors/node/node.impl.js +57 -7
  7. package/src/executors/tsc/lib/batch/build-task-info-per-tsconfig-map.d.ts +4 -0
  8. package/src/executors/tsc/lib/batch/build-task-info-per-tsconfig-map.js +54 -0
  9. package/src/executors/tsc/lib/batch/generate-temp-tsconfig.d.ts +3 -0
  10. package/src/executors/tsc/lib/batch/generate-temp-tsconfig.js +52 -0
  11. package/src/executors/tsc/lib/batch/get-task-options.d.ts +3 -0
  12. package/src/executors/tsc/lib/batch/get-task-options.js +24 -0
  13. package/src/executors/tsc/lib/batch/index.d.ts +8 -0
  14. package/src/executors/tsc/lib/batch/index.js +11 -0
  15. package/src/executors/tsc/lib/batch/normalize-tasks-options.d.ts +3 -0
  16. package/src/executors/tsc/lib/batch/normalize-tasks-options.js +14 -0
  17. package/src/executors/tsc/lib/batch/types.d.ts +12 -0
  18. package/src/executors/tsc/lib/batch/types.js +2 -0
  19. package/src/executors/tsc/lib/batch/typescript-compilation.d.ts +7 -0
  20. package/src/executors/tsc/lib/batch/typescript-compilation.js +195 -0
  21. package/src/executors/tsc/lib/batch/typescript-diagnostic-reporters.d.ts +4 -0
  22. package/src/executors/tsc/lib/batch/typescript-diagnostic-reporters.js +44 -0
  23. package/src/executors/tsc/lib/batch/watch.d.ts +3 -0
  24. package/src/executors/tsc/lib/batch/watch.js +63 -0
  25. package/src/executors/tsc/lib/get-custom-transformers-factory.d.ts +3 -0
  26. package/src/executors/tsc/lib/get-custom-transformers-factory.js +13 -0
  27. package/src/executors/tsc/lib/index.d.ts +2 -0
  28. package/src/executors/tsc/lib/index.js +5 -0
  29. package/src/executors/tsc/lib/normalize-options.d.ts +2 -0
  30. package/src/executors/tsc/lib/normalize-options.js +32 -0
  31. package/src/executors/tsc/tsc.batch-impl.d.ts +4 -0
  32. package/src/executors/tsc/tsc.batch-impl.js +47 -0
  33. package/src/executors/tsc/tsc.impl.d.ts +0 -1
  34. package/src/executors/tsc/tsc.impl.js +4 -39
  35. package/src/executors/verdaccio/verdaccio.impl.d.ts +1 -0
  36. package/src/executors/verdaccio/verdaccio.impl.js +25 -22
  37. package/src/generators/library/library.js +2 -10
  38. package/src/generators/library/schema.json +7 -6
  39. package/src/generators/setup-build/generator.d.ts +5 -0
  40. package/src/generators/setup-build/generator.js +133 -0
  41. package/src/generators/setup-build/schema.d.ts +7 -0
  42. package/src/generators/setup-build/schema.json +42 -0
  43. package/src/generators/setup-verdaccio/files/config.yml +1 -1
  44. package/src/generators/setup-verdaccio/generator.js +5 -1
  45. package/src/index.d.ts +1 -0
  46. package/src/index.js +1 -0
  47. package/src/plugins/jest/start-local-registry.d.ts +12 -0
  48. package/src/plugins/jest/start-local-registry.js +61 -0
  49. package/src/utils/add-babel-inputs.d.ts +1 -0
  50. package/src/utils/add-babel-inputs.js +2 -0
  51. package/src/utils/add-local-registry-scripts.d.ts +5 -0
  52. package/src/utils/add-local-registry-scripts.js +57 -0
  53. package/src/utils/assets/copy-assets-handler.d.ts +5 -1
  54. package/src/utils/assets/copy-assets-handler.js +34 -23
  55. package/src/utils/inline.d.ts +1 -1
  56. package/src/utils/inline.js +3 -3
  57. package/src/utils/minimal-publish-script.js +2 -5
  58. package/src/utils/schema.d.ts +3 -2
  59. package/src/utils/swc/add-swc-config.d.ts +1 -1
@@ -0,0 +1,44 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.formatWatchStatusReport = exports.formatSolutionBuilderStatusReport = exports.formatDiagnosticReport = void 0;
4
+ const ts = require("typescript");
5
+ // adapted from TS default diagnostic reporter
6
+ function formatDiagnosticReport(diagnostic, host) {
7
+ const diagnostics = new Array(1);
8
+ diagnostics[0] = diagnostic;
9
+ const formattedDiagnostic = '\n' +
10
+ ts.formatDiagnosticsWithColorAndContext(diagnostics, host) +
11
+ host.getNewLine();
12
+ diagnostics[0] = undefined;
13
+ return formattedDiagnostic;
14
+ }
15
+ exports.formatDiagnosticReport = formatDiagnosticReport;
16
+ // adapted from TS default solution builder status reporter
17
+ function formatSolutionBuilderStatusReport(diagnostic) {
18
+ let formattedDiagnostic = `[${formatColorAndReset(getLocaleTimeString(), ForegroundColorEscapeSequences.Grey)}] `;
19
+ formattedDiagnostic += `${ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine)}${ts.sys.newLine + ts.sys.newLine}`;
20
+ return formattedDiagnostic;
21
+ }
22
+ exports.formatSolutionBuilderStatusReport = formatSolutionBuilderStatusReport;
23
+ // adapted from TS default watch status reporter
24
+ function formatWatchStatusReport(diagnostic, newLine) {
25
+ let output = `[${formatColorAndReset(getLocaleTimeString(), ForegroundColorEscapeSequences.Grey)}] `;
26
+ output += `${ts.flattenDiagnosticMessageText(diagnostic.messageText, ts.sys.newLine)}${newLine + newLine}`;
27
+ return output;
28
+ }
29
+ exports.formatWatchStatusReport = formatWatchStatusReport;
30
+ function formatColorAndReset(text, formatStyle) {
31
+ const resetEscapeSequence = '\u001b[0m';
32
+ return formatStyle + text + resetEscapeSequence;
33
+ }
34
+ function getLocaleTimeString() {
35
+ return new Date().toLocaleTimeString();
36
+ }
37
+ var ForegroundColorEscapeSequences;
38
+ (function (ForegroundColorEscapeSequences) {
39
+ ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
40
+ ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
41
+ ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
42
+ ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
43
+ ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
44
+ })(ForegroundColorEscapeSequences || (ForegroundColorEscapeSequences = {}));
@@ -0,0 +1,3 @@
1
+ import type { TaskInfo } from './types';
2
+ export declare function watchTaskProjectsPackageJsonFileChanges(taskInfos: TaskInfo[], callback: (changedTaskInfos: TaskInfo[]) => void): Promise<() => void>;
3
+ export declare function watchTaskProjectsFileChangesForAssets(taskInfos: TaskInfo[]): Promise<() => void>;
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.watchTaskProjectsFileChangesForAssets = exports.watchTaskProjectsPackageJsonFileChanges = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const devkit_1 = require("@nx/devkit");
6
+ const client_1 = require("nx/src/daemon/client/client");
7
+ const path_1 = require("path");
8
+ function watchTaskProjectsPackageJsonFileChanges(taskInfos, callback) {
9
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
10
+ const projects = [];
11
+ const packageJsonTaskInfoMap = new Map();
12
+ taskInfos.forEach((t) => {
13
+ projects.push(t.context.projectName);
14
+ packageJsonTaskInfoMap.set((0, path_1.join)(t.options.projectRoot, 'package.json'), t);
15
+ });
16
+ const unregisterFileWatcher = yield client_1.daemonClient.registerFileWatcher({ watchProjects: projects }, (err, data) => {
17
+ var _a;
18
+ if (err === 'closed') {
19
+ devkit_1.logger.error(`Watch error: Daemon closed the connection`);
20
+ process.exit(1);
21
+ }
22
+ else if (err) {
23
+ devkit_1.logger.error(`Watch error: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : 'Unknown'}`);
24
+ }
25
+ else {
26
+ const changedTasks = [];
27
+ data.changedFiles.forEach((file) => {
28
+ if (packageJsonTaskInfoMap.has(file.path)) {
29
+ changedTasks.push(packageJsonTaskInfoMap.get(file.path));
30
+ }
31
+ });
32
+ if (changedTasks.length) {
33
+ callback(changedTasks);
34
+ }
35
+ }
36
+ });
37
+ return () => unregisterFileWatcher();
38
+ });
39
+ }
40
+ exports.watchTaskProjectsPackageJsonFileChanges = watchTaskProjectsPackageJsonFileChanges;
41
+ function watchTaskProjectsFileChangesForAssets(taskInfos) {
42
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
43
+ const unregisterFileWatcher = yield client_1.daemonClient.registerFileWatcher({
44
+ watchProjects: taskInfos.map((t) => t.context.projectName),
45
+ includeDependentProjects: true,
46
+ includeGlobalWorkspaceFiles: true,
47
+ }, (err, data) => {
48
+ var _a;
49
+ if (err === 'closed') {
50
+ devkit_1.logger.error(`Watch error: Daemon closed the connection`);
51
+ process.exit(1);
52
+ }
53
+ else if (err) {
54
+ devkit_1.logger.error(`Watch error: ${(_a = err === null || err === void 0 ? void 0 : err.message) !== null && _a !== void 0 ? _a : 'Unknown'}`);
55
+ }
56
+ else {
57
+ taskInfos.forEach((t) => t.assetsHandler.processWatchEvents(data.changedFiles));
58
+ }
59
+ });
60
+ return () => unregisterFileWatcher();
61
+ });
62
+ }
63
+ exports.watchTaskProjectsFileChangesForAssets = watchTaskProjectsFileChangesForAssets;
@@ -0,0 +1,3 @@
1
+ import * as ts from 'typescript';
2
+ import type { TransformerEntry } from '../../../utils/typescript/types';
3
+ export declare function getCustomTrasformersFactory(transformers: TransformerEntry[]): (program: ts.Program) => ts.CustomTransformers;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getCustomTrasformersFactory = void 0;
4
+ const load_ts_transformers_1 = require("../../../utils/typescript/load-ts-transformers");
5
+ function getCustomTrasformersFactory(transformers) {
6
+ const { compilerPluginHooks } = (0, load_ts_transformers_1.loadTsTransformers)(transformers);
7
+ return (program) => ({
8
+ before: compilerPluginHooks.beforeHooks.map((hook) => hook(program)),
9
+ after: compilerPluginHooks.afterHooks.map((hook) => hook(program)),
10
+ afterDeclarations: compilerPluginHooks.afterDeclarationsHooks.map((hook) => hook(program)),
11
+ });
12
+ }
13
+ exports.getCustomTrasformersFactory = getCustomTrasformersFactory;
@@ -0,0 +1,2 @@
1
+ export * from './get-custom-transformers-factory';
2
+ export * from './normalize-options';
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ const tslib_1 = require("tslib");
4
+ tslib_1.__exportStar(require("./get-custom-transformers-factory"), exports);
5
+ tslib_1.__exportStar(require("./normalize-options"), exports);
@@ -0,0 +1,2 @@
1
+ import type { ExecutorOptions, NormalizedExecutorOptions } from '../../../utils/schema';
2
+ export declare function normalizeOptions(options: ExecutorOptions, contextRoot: string, sourceRoot: string, projectRoot: string): NormalizedExecutorOptions;
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeOptions = void 0;
4
+ const path_1 = require("path");
5
+ const assets_1 = require("../../../utils/assets/assets");
6
+ function normalizeOptions(options, contextRoot, sourceRoot, projectRoot) {
7
+ const outputPath = (0, path_1.join)(contextRoot, options.outputPath);
8
+ const rootDir = options.rootDir
9
+ ? (0, path_1.join)(contextRoot, options.rootDir)
10
+ : (0, path_1.join)(contextRoot, projectRoot);
11
+ if (options.watch == null) {
12
+ options.watch = false;
13
+ }
14
+ // TODO: put back when inlining story is more stable
15
+ // if (options.external == null) {
16
+ // options.external = 'all';
17
+ // } else if (Array.isArray(options.external) && options.external.length === 0) {
18
+ // options.external = 'none';
19
+ // }
20
+ if (Array.isArray(options.external) && options.external.length > 0) {
21
+ const firstItem = options.external[0];
22
+ if (firstItem === 'all' || firstItem === 'none') {
23
+ options.external = firstItem;
24
+ }
25
+ }
26
+ const files = (0, assets_1.assetGlobsToFiles)(options.assets, contextRoot, outputPath);
27
+ return Object.assign(Object.assign({}, options), { root: contextRoot, sourceRoot,
28
+ projectRoot,
29
+ files,
30
+ outputPath, tsConfig: (0, path_1.join)(contextRoot, options.tsConfig), rootDir, mainOutputPath: (0, path_1.resolve)(outputPath, options.main.replace(`${projectRoot}/`, '').replace('.ts', '.js')) });
31
+ }
32
+ exports.normalizeOptions = normalizeOptions;
@@ -0,0 +1,4 @@
1
+ import type { ExecutorContext, TaskGraph } from '@nx/devkit';
2
+ import type { ExecutorOptions } from '../../utils/schema';
3
+ export declare function tscBatchExecutor(taskGraph: TaskGraph, inputs: Record<string, ExecutorOptions>, overrides: ExecutorOptions, context: ExecutorContext): AsyncGenerator<import("../../../../../build/packages/nx/src/tasks-runner/batch/batch-messages").BatchResults, any, undefined>;
4
+ export default tscBatchExecutor;
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.tscBatchExecutor = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const fs_1 = require("fs");
6
+ const update_package_json_1 = require("../../utils/package-json/update-package-json");
7
+ const batch_1 = require("./lib/batch");
8
+ function tscBatchExecutor(taskGraph, inputs, overrides, context) {
9
+ return tslib_1.__asyncGenerator(this, arguments, function* tscBatchExecutor_1() {
10
+ const tasksOptions = (0, batch_1.normalizeTasksOptions)(inputs, context);
11
+ let shouldWatch = false;
12
+ Object.values(tasksOptions).forEach((taskOptions) => {
13
+ if (taskOptions.clean) {
14
+ (0, fs_1.rmSync)(taskOptions.outputPath, { force: true, recursive: true });
15
+ }
16
+ if (taskOptions.watch) {
17
+ shouldWatch = true;
18
+ }
19
+ });
20
+ const tsConfigTaskInfoMap = {};
21
+ (0, batch_1.buildTaskInfoPerTsConfigMap)(tsConfigTaskInfoMap, tasksOptions, context, Object.keys(taskGraph.tasks), shouldWatch);
22
+ const typescriptCompilation = (0, batch_1.compileBatchTypescript)(tsConfigTaskInfoMap, taskGraph, shouldWatch, (taskInfo) => {
23
+ taskInfo.assetsHandler.processAllAssetsOnceSync();
24
+ (0, update_package_json_1.updatePackageJson)(taskInfo.options, taskInfo.context, taskInfo.projectGraphNode, taskInfo.buildableProjectNodeDependencies);
25
+ });
26
+ if (shouldWatch) {
27
+ const taskInfos = Object.values(tsConfigTaskInfoMap);
28
+ const watchAssetsChangesDisposer = yield tslib_1.__await((0, batch_1.watchTaskProjectsFileChangesForAssets)(taskInfos));
29
+ const watchProjectsChangesDisposer = yield tslib_1.__await((0, batch_1.watchTaskProjectsPackageJsonFileChanges)(taskInfos, (changedTaskInfos) => {
30
+ for (const t of changedTaskInfos) {
31
+ (0, update_package_json_1.updatePackageJson)(t.options, t.context, t.projectGraphNode, t.buildableProjectNodeDependencies);
32
+ }
33
+ }));
34
+ const handleTermination = (exitCode) => tslib_1.__awaiter(this, void 0, void 0, function* () {
35
+ yield typescriptCompilation.close();
36
+ watchAssetsChangesDisposer();
37
+ watchProjectsChangesDisposer();
38
+ process.exit(exitCode);
39
+ });
40
+ process.on('SIGINT', () => handleTermination(128 + 2));
41
+ process.on('SIGTERM', () => handleTermination(128 + 15));
42
+ }
43
+ return yield tslib_1.__await(yield tslib_1.__await(yield* tslib_1.__asyncDelegator(tslib_1.__asyncValues(typescriptCompilation.iterator))));
44
+ });
45
+ }
46
+ exports.tscBatchExecutor = tscBatchExecutor;
47
+ exports.default = tscBatchExecutor;
@@ -1,7 +1,6 @@
1
1
  import { ExecutorContext } from '@nx/devkit';
2
2
  import type { TypeScriptCompilationOptions } from '@nx/workspace/src/utilities/typescript/compilation';
3
3
  import { ExecutorOptions, NormalizedExecutorOptions } from '../../utils/schema';
4
- export declare function normalizeOptions(options: ExecutorOptions, contextRoot: string, sourceRoot: string, projectRoot: string): NormalizedExecutorOptions;
5
4
  export declare function createTypeScriptCompilationOptions(normalizedOptions: NormalizedExecutorOptions, context: ExecutorContext): TypeScriptCompilationOptions;
6
5
  export declare function tscExecutor(_options: ExecutorOptions, context: ExecutorContext): AsyncGenerator<import("../../utils/typescript/compile-typescript-files").TypescriptCompilationResult, any, undefined>;
7
6
  export default tscExecutor;
@@ -1,51 +1,16 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.tscExecutor = exports.createTypeScriptCompilationOptions = exports.normalizeOptions = void 0;
3
+ exports.tscExecutor = exports.createTypeScriptCompilationOptions = void 0;
4
4
  const tslib_1 = require("tslib");
5
- const assets_1 = require("../../utils/assets/assets");
6
- const path_1 = require("path");
7
5
  const copy_assets_handler_1 = require("../../utils/assets/copy-assets-handler");
8
6
  const check_dependencies_1 = require("../../utils/check-dependencies");
9
7
  const compiler_helper_dependency_1 = require("../../utils/compiler-helper-dependency");
10
8
  const inline_1 = require("../../utils/inline");
11
9
  const update_package_json_1 = require("../../utils/package-json/update-package-json");
12
10
  const compile_typescript_files_1 = require("../../utils/typescript/compile-typescript-files");
13
- const load_ts_transformers_1 = require("../../utils/typescript/load-ts-transformers");
14
11
  const watch_for_single_file_changes_1 = require("../../utils/watch-for-single-file-changes");
15
- function normalizeOptions(options, contextRoot, sourceRoot, projectRoot) {
16
- const outputPath = (0, path_1.join)(contextRoot, options.outputPath);
17
- const rootDir = options.rootDir
18
- ? (0, path_1.join)(contextRoot, options.rootDir)
19
- : projectRoot;
20
- if (options.watch == null) {
21
- options.watch = false;
22
- }
23
- // TODO: put back when inlining story is more stable
24
- // if (options.external == null) {
25
- // options.external = 'all';
26
- // } else if (Array.isArray(options.external) && options.external.length === 0) {
27
- // options.external = 'none';
28
- // }
29
- if (Array.isArray(options.external) && options.external.length > 0) {
30
- const firstItem = options.external[0];
31
- if (firstItem === 'all' || firstItem === 'none') {
32
- options.external = firstItem;
33
- }
34
- }
35
- const files = (0, assets_1.assetGlobsToFiles)(options.assets, contextRoot, outputPath);
36
- return Object.assign(Object.assign({}, options), { root: contextRoot, sourceRoot,
37
- projectRoot,
38
- files,
39
- outputPath, tsConfig: (0, path_1.join)(contextRoot, options.tsConfig), rootDir, mainOutputPath: (0, path_1.resolve)(outputPath, options.main.replace(`${projectRoot}/`, '').replace('.ts', '.js')) });
40
- }
41
- exports.normalizeOptions = normalizeOptions;
12
+ const lib_1 = require("./lib");
42
13
  function createTypeScriptCompilationOptions(normalizedOptions, context) {
43
- const { compilerPluginHooks } = (0, load_ts_transformers_1.loadTsTransformers)(normalizedOptions.transformers);
44
- const getCustomTransformers = (program) => ({
45
- before: compilerPluginHooks.beforeHooks.map((hook) => hook(program)),
46
- after: compilerPluginHooks.afterHooks.map((hook) => hook(program)),
47
- afterDeclarations: compilerPluginHooks.afterDeclarationsHooks.map((hook) => hook(program)),
48
- });
49
14
  return {
50
15
  outputPath: normalizedOptions.outputPath,
51
16
  projectName: context.projectName,
@@ -54,14 +19,14 @@ function createTypeScriptCompilationOptions(normalizedOptions, context) {
54
19
  tsConfig: normalizedOptions.tsConfig,
55
20
  watch: normalizedOptions.watch,
56
21
  deleteOutputPath: normalizedOptions.clean,
57
- getCustomTransformers,
22
+ getCustomTransformers: (0, lib_1.getCustomTrasformersFactory)(normalizedOptions.transformers),
58
23
  };
59
24
  }
60
25
  exports.createTypeScriptCompilationOptions = createTypeScriptCompilationOptions;
61
26
  function tscExecutor(_options, context) {
62
27
  return tslib_1.__asyncGenerator(this, arguments, function* tscExecutor_1() {
63
28
  const { sourceRoot, root } = context.projectsConfigurations.projects[context.projectName];
64
- const options = normalizeOptions(_options, context.root, sourceRoot, root);
29
+ const options = (0, lib_1.normalizeOptions)(_options, context.root, sourceRoot, root);
65
30
  const { projectRoot, tmpTsConfig, target, dependencies } = (0, check_dependencies_1.checkDependencies)(context, _options.tsConfig);
66
31
  if (tmpTsConfig) {
67
32
  options.tsConfig = tmpTsConfig;
@@ -7,5 +7,6 @@ import { VerdaccioExecutorSchema } from './schema';
7
7
  */
8
8
  export declare function verdaccioExecutor(options: VerdaccioExecutorSchema, context: ExecutorContext): Promise<{
9
9
  success: boolean;
10
+ port: number;
10
11
  }>;
11
12
  export default verdaccioExecutor;
@@ -5,6 +5,8 @@ const tslib_1 = require("tslib");
5
5
  const devkit_1 = require("@nx/devkit");
6
6
  const fs_extra_1 = require("fs-extra");
7
7
  const child_process_1 = require("child_process");
8
+ const detectPort = require("detect-port");
9
+ const path_1 = require("path");
8
10
  let childProcess;
9
11
  /**
10
12
  * - set npm and yarn to use local registry
@@ -19,8 +21,12 @@ function verdaccioExecutor(options, context) {
19
21
  catch (e) {
20
22
  throw new Error('Verdaccio is not installed. Please run `npm install verdaccio` or `yarn add verdaccio`');
21
23
  }
22
- if (options.clear && options.storage && (0, fs_extra_1.existsSync)(options.storage)) {
23
- (0, fs_extra_1.removeSync)(options.storage);
24
+ if (options.storage) {
25
+ options.storage = (0, path_1.resolve)(context.root, options.storage);
26
+ if (options.clear && (0, fs_extra_1.existsSync)(options.storage)) {
27
+ (0, fs_extra_1.rmSync)(options.storage, { recursive: true, force: true });
28
+ console.log(`Cleared local registry storage folder ${options.storage}`);
29
+ }
24
30
  }
25
31
  const cleanupFunctions = options.location === 'none' ? [] : [setupNpm(options), setupYarn(options)];
26
32
  const processExitListener = (signal) => {
@@ -36,16 +42,23 @@ function verdaccioExecutor(options, context) {
36
42
  process.on('SIGINT', processExitListener);
37
43
  process.on('SIGHUP', processExitListener);
38
44
  try {
39
- yield startVerdaccio(options);
45
+ const port = yield detectPort(options.port);
46
+ if (port !== options.port) {
47
+ devkit_1.logger.info(`Port ${options.port} was occupied. Using port ${port}.`);
48
+ options.port = port;
49
+ }
50
+ yield startVerdaccio(options, context.root);
40
51
  }
41
52
  catch (e) {
42
- devkit_1.logger.error('Failed to start verdaccio: ' + e.toString());
53
+ devkit_1.logger.error('Failed to start verdaccio: ' + (e === null || e === void 0 ? void 0 : e.toString()));
43
54
  return {
44
55
  success: false,
56
+ port: options.port,
45
57
  };
46
58
  }
47
59
  return {
48
60
  success: true,
61
+ port: options.port,
49
62
  };
50
63
  });
51
64
  }
@@ -53,23 +66,13 @@ exports.verdaccioExecutor = verdaccioExecutor;
53
66
  /**
54
67
  * Fork the verdaccio process: https://verdaccio.org/docs/verdaccio-programmatically/#using-fork-from-child_process-module
55
68
  */
56
- function startVerdaccio(options) {
69
+ function startVerdaccio(options, workspaceRoot) {
57
70
  return new Promise((resolve, reject) => {
58
- childProcess = (0, child_process_1.fork)(require.resolve('verdaccio/bin/verdaccio'), createVerdaccioOptions(options), {
59
- env: Object.assign(Object.assign({}, process.env), { VERDACCIO_HANDLE_KILL_SIGNALS: 'true' }),
60
- stdio: ['inherit', 'pipe', 'pipe', 'ipc'],
61
- });
62
- childProcess.stdout.on('data', (data) => {
63
- process.stdout.write(data);
64
- });
65
- childProcess.stderr.on('data', (data) => {
66
- if (data.includes('VerdaccioWarning') ||
67
- data.includes('DeprecationWarning')) {
68
- process.stdout.write(data);
69
- }
70
- else {
71
- reject(data);
72
- }
71
+ childProcess = (0, child_process_1.fork)(require.resolve('verdaccio/bin/verdaccio'), createVerdaccioOptions(options, workspaceRoot), {
72
+ env: Object.assign(Object.assign(Object.assign({}, process.env), { VERDACCIO_HANDLE_KILL_SIGNALS: 'true' }), (options.storage
73
+ ? { VERDACCIO_STORAGE_PATH: options.storage }
74
+ : {})),
75
+ stdio: 'inherit',
73
76
  });
74
77
  childProcess.on('error', (err) => {
75
78
  reject(err);
@@ -87,13 +90,13 @@ function startVerdaccio(options) {
87
90
  });
88
91
  });
89
92
  }
90
- function createVerdaccioOptions(options) {
93
+ function createVerdaccioOptions(options, workspaceRoot) {
91
94
  const verdaccioArgs = [];
92
95
  if (options.port) {
93
96
  verdaccioArgs.push('--listen', options.port.toString());
94
97
  }
95
98
  if (options.config) {
96
- verdaccioArgs.push('--config', options.config);
99
+ verdaccioArgs.push('--config', (0, path_1.join)(workspaceRoot, options.config));
97
100
  }
98
101
  return verdaccioArgs;
99
102
  }
@@ -44,12 +44,10 @@ function projectGenerator(tree, schema, destinationDir, filesDir) {
44
44
  includeVitest: options.unitTestRunner === 'vitest',
45
45
  includeLib: true,
46
46
  skipFormat: true,
47
+ testEnvironment: options.testEnvironment,
47
48
  });
48
49
  tasks.push(viteTask);
49
50
  }
50
- if (options.bundler === 'rollup') {
51
- ensureBabelRootConfigExists(tree);
52
- }
53
51
  if (options.linter !== 'none') {
54
52
  const lintCallback = yield addLint(tree, options);
55
53
  tasks.push(lintCallback);
@@ -70,6 +68,7 @@ function projectGenerator(tree, schema, destinationDir, filesDir) {
70
68
  uiFramework: 'none',
71
69
  coverageProvider: 'c8',
72
70
  skipFormat: true,
71
+ testEnvironment: options.testEnvironment,
73
72
  });
74
73
  tasks.push(vitestTask);
75
74
  }
@@ -384,13 +383,6 @@ function getBuildExecutor(bundler) {
384
383
  return undefined;
385
384
  }
386
385
  }
387
- function ensureBabelRootConfigExists(tree) {
388
- if (tree.exists('babel.config.json'))
389
- return;
390
- (0, devkit_1.writeJson)(tree, 'babel.config.json', {
391
- babelrcRoots: ['*'],
392
- });
393
- }
394
386
  function getOutputPath(options, destinationDir) {
395
387
  const parts = ['dist'];
396
388
  if (destinationDir) {
@@ -56,12 +56,8 @@
56
56
  "testEnvironment": {
57
57
  "type": "string",
58
58
  "enum": ["jsdom", "node"],
59
- "description": "The test environment to use if unitTestRunner is set to jest.",
60
- "default": "jsdom"
61
- },
62
- "importPath": {
63
- "type": "string",
64
- "description": "The library name used to import it, like @myorg/my-awesome-lib."
59
+ "description": "The test environment to use if unitTestRunner is set to jest or vitest.",
60
+ "default": "node"
65
61
  },
66
62
  "pascalCaseFiles": {
67
63
  "type": "boolean",
@@ -85,6 +81,11 @@
85
81
  "description": "Generate a publishable library.",
86
82
  "x-priority": "important"
87
83
  },
84
+ "importPath": {
85
+ "type": "string",
86
+ "description": "The library name used to import it, like @myorg/my-awesome-lib. Required for publishable library.",
87
+ "x-priority": "important"
88
+ },
88
89
  "buildable": {
89
90
  "type": "boolean",
90
91
  "default": true,
@@ -0,0 +1,5 @@
1
+ import { type GeneratorCallback, type Tree } from '@nx/devkit';
2
+ import { SetupBuildGeneratorSchema } from './schema';
3
+ export declare function setupBuildGenerator(tree: Tree, options: SetupBuildGeneratorSchema): Promise<GeneratorCallback>;
4
+ export default setupBuildGenerator;
5
+ export declare const setupBuildSchematic: (generatorOptions: SetupBuildGeneratorSchema) => (tree: any, context: any) => Promise<any>;
@@ -0,0 +1,133 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.setupBuildSchematic = exports.setupBuildGenerator = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const devkit_1 = require("@nx/devkit");
6
+ const add_swc_config_1 = require("../../utils/swc/add-swc-config");
7
+ const add_swc_dependencies_1 = require("../../utils/swc/add-swc-dependencies");
8
+ const versions_1 = require("../../utils/versions");
9
+ function setupBuildGenerator(tree, options) {
10
+ var _a, _b, _c;
11
+ return tslib_1.__awaiter(this, void 0, void 0, function* () {
12
+ const tasks = [];
13
+ const project = (0, devkit_1.readProjectConfiguration)(tree, options.project);
14
+ const buildTarget = (_a = options.buildTarget) !== null && _a !== void 0 ? _a : 'build';
15
+ (_b = project.targets) !== null && _b !== void 0 ? _b : (project.targets = {});
16
+ let mainFile;
17
+ if (options.main) {
18
+ mainFile = options.main;
19
+ }
20
+ else {
21
+ const root = (_c = project.sourceRoot) !== null && _c !== void 0 ? _c : project.root;
22
+ for (const f of [
23
+ (0, devkit_1.joinPathFragments)(root, 'main.ts'),
24
+ (0, devkit_1.joinPathFragments)(root, 'main.js'),
25
+ (0, devkit_1.joinPathFragments)(root, 'index.ts'),
26
+ (0, devkit_1.joinPathFragments)(root, 'index.js'),
27
+ ]) {
28
+ if (tree.exists(f)) {
29
+ mainFile = f;
30
+ break;
31
+ }
32
+ }
33
+ }
34
+ if (!mainFile || !tree.exists(mainFile)) {
35
+ throw new Error(`Cannot locate a main file for ${options.project}. Please specify one using --main=<file-path>.`);
36
+ }
37
+ let tsConfigFile;
38
+ if (options.tsConfig) {
39
+ tsConfigFile = options.tsConfig;
40
+ }
41
+ else {
42
+ for (const f of [
43
+ 'tsconfig.lib.json',
44
+ 'tsconfig.app.json',
45
+ 'tsconfig.json',
46
+ ]) {
47
+ const candidate = (0, devkit_1.joinPathFragments)(project.root, f);
48
+ if (tree.exists(candidate)) {
49
+ tsConfigFile = candidate;
50
+ break;
51
+ }
52
+ }
53
+ }
54
+ if (!tsConfigFile || !tree.exists(tsConfigFile)) {
55
+ throw new Error(`Cannot locate a tsConfig file for ${options.project}. Please specify one using --tsConfig=<file-path>.`);
56
+ }
57
+ switch (options.bundler) {
58
+ case 'vite': {
59
+ const { viteConfigurationGenerator } = (0, devkit_1.ensurePackage)('@nx/vite', versions_1.nxVersion);
60
+ const task = yield viteConfigurationGenerator(tree, {
61
+ buildTarget: options.buildTarget,
62
+ project: options.project,
63
+ newProject: true,
64
+ uiFramework: 'none',
65
+ includeVitest: false,
66
+ includeLib: true,
67
+ skipFormat: true,
68
+ });
69
+ tasks.push(task);
70
+ break;
71
+ }
72
+ case 'esbuild': {
73
+ const { esbuildProjectGenerator } = (0, devkit_1.ensurePackage)('@nx/esbuild', versions_1.nxVersion);
74
+ const task = yield esbuildProjectGenerator(tree, {
75
+ main: mainFile,
76
+ buildTarget: options.buildTarget,
77
+ project: options.project,
78
+ skipFormat: true,
79
+ });
80
+ tasks.push(task);
81
+ break;
82
+ }
83
+ case 'rollup': {
84
+ const { rollupProjectGenerator } = (0, devkit_1.ensurePackage)('@nx/rollup', versions_1.nxVersion);
85
+ const task = yield rollupProjectGenerator(tree, {
86
+ buildTarget: options.buildTarget,
87
+ main: mainFile,
88
+ project: options.project,
89
+ skipFormat: true,
90
+ compiler: 'tsc',
91
+ });
92
+ tasks.push(task);
93
+ break;
94
+ }
95
+ case 'tsc': {
96
+ const outputPath = (0, devkit_1.joinPathFragments)('dist', project.root);
97
+ project.targets[buildTarget] = {
98
+ executor: `@nx/js:tsc`,
99
+ outputs: ['{options.outputPath}'],
100
+ options: {
101
+ outputPath,
102
+ main: mainFile,
103
+ tsConfig: tsConfigFile,
104
+ assets: [],
105
+ },
106
+ };
107
+ (0, devkit_1.updateProjectConfiguration)(tree, options.project, project);
108
+ break;
109
+ }
110
+ case 'swc': {
111
+ const outputPath = (0, devkit_1.joinPathFragments)('dist', project.root);
112
+ project.targets[buildTarget] = {
113
+ executor: `@nx/js:swc`,
114
+ outputs: ['{options.outputPath}'],
115
+ options: {
116
+ outputPath,
117
+ main: mainFile,
118
+ tsConfig: tsConfigFile,
119
+ assets: [],
120
+ },
121
+ };
122
+ (0, devkit_1.updateProjectConfiguration)(tree, options.project, project);
123
+ (0, add_swc_dependencies_1.addSwcDependencies)(tree);
124
+ (0, add_swc_config_1.addSwcConfig)(tree, project.root, 'es6');
125
+ }
126
+ }
127
+ yield (0, devkit_1.formatFiles)(tree);
128
+ return (0, devkit_1.runTasksInSerial)(...tasks);
129
+ });
130
+ }
131
+ exports.setupBuildGenerator = setupBuildGenerator;
132
+ exports.default = setupBuildGenerator;
133
+ exports.setupBuildSchematic = (0, devkit_1.convertNxGenerator)(setupBuildGenerator);
@@ -0,0 +1,7 @@
1
+ export interface SetupBuildGeneratorSchema {
2
+ project: string;
3
+ bundler: 'tsc' | 'swc' | 'vite' | 'rollup' | 'esbuild';
4
+ main?: string;
5
+ tsConfig?: string;
6
+ buildTarget?: string;
7
+ }