@harves/nx-node-esm-plugin
Version:
Node executor including ESM module resolution for buildable libraries within Nx workspaces.
157 lines (156 loc) • 9.01 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const devkit_1 = require("@nx/devkit");
const buildable_libs_utils_1 = require("./buildable-libs-utils");
const node_utils_1 = require("./node-utils");
const create_task_graph_1 = require("nx/src/tasks-runner/create-task-graph");
const chalk = require("chalk");
const run_commands_utils_1 = require("./run-commands-utils");
const utils_1 = require("nx/src/tasks-runner/utils");
const path_1 = require("path");
const package_json_utils_1 = require("./package-json-utils");
const load_env_vars_1 = require("./load-env-vars");
/**
* Build the node-runner library; this is only necessary during
* development (building off source).
*
* @param context
*/
function performNodeRunnerLibBuild(context) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
var _a, e_1, _b, _c;
try {
for (var _d = true, _e = tslib_1.__asyncValues(yield (0, devkit_1.runExecutor)({ project: 'node-runner', target: 'build', configuration: 'production' }, {
// watch: opts.watch,
}, context)), _f; _f = yield _e.next(), _a = _f.done, !_a; _d = true) {
_c = _f.value;
_d = false;
const output = _c;
if (!output.success) {
throw new Error('Could not compile node-runner library');
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (!_d && !_a && (_b = _e.return)) yield _b.call(_e);
}
finally { if (e_1) throw e_1.error; }
}
});
}
function runExecutorFunc(options, context) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o;
if (process.env.NX_LOAD_DOT_ENV_FILES !== 'false') {
yield (0, load_env_vars_1.loadEnvVars)(options.envFile);
}
const target = (0, devkit_1.parseTargetString)(context.targetName, context);
const buildTarget = (0, devkit_1.parseTargetString)(options.buildTarget, context);
/*
* Two parts:
* 1. Dependencies - collect libs from task graph.
*
* 2. File to run; options
* - `fileToRunMode` === `packageJson`
* - `fileToRunMode` === `specified` via `fileToRun` property
* - `fileToRunMode` === `fromBuildTarget` via `getFileToRun()` as per `@nx/js:node`
*/
const taskGraph = (0, create_task_graph_1.createTaskGraph)(context.projectGraph, {}, [buildTarget.project], [buildTarget.target], buildTarget.configuration, {});
const deps = (0, buildable_libs_utils_1.calculateDependenciesFromTaskGraph)(taskGraph, context.projectGraph, context.root, buildTarget.project, buildTarget.target, buildTarget.configuration);
const mappings = {};
for (const d of deps.dependencies) {
if (d.node.type === 'app' ||
d.node.type === 'e2e' ||
d.node.type === 'lib') {
const project = context.projectGraph.nodes[d.node.name];
const target = {
project: d.node.name,
target: d.target,
configuration: buildTarget.configuration,
};
const targetOptions = (0, devkit_1.readTargetOptions)(target, context);
let outputPath = (_a = targetOptions.outputPath) !== null && _a !== void 0 ? _a : (_c = (_b = project.data.targets[d.target]) === null || _b === void 0 ? void 0 : _b.outputs) === null || _c === void 0 ? void 0 : _c[0];
if (outputPath) {
outputPath = (0, utils_1.interpolate)(outputPath, {
projectName: project.name,
projectRoot: project.data.root,
workspaceRoot: '',
});
outputPath = (0, path_1.join)(context.root, outputPath);
}
mappings[d.name] = outputPath;
}
}
if (Object.keys(mappings).length < 1) {
devkit_1.logger.warn(`${(0, devkit_1.targetToTargetString)(target)}: buildTarget ${chalk.bold((0, devkit_1.targetToTargetString)(buildTarget))} has no dependencies. Is this correct?`);
}
let fileToRun;
if (options.fileToRun) {
fileToRun = options.fileToRun;
fileToRun = fileToRun ? (0, path_1.resolve)(context.root, fileToRun) : fileToRun;
if (!fileToRun || !(0, package_json_utils_1.fileExists)(fileToRun)) {
devkit_1.logger.error(`File to run mode is 'specified' and bad fileToRun '${fileToRun}' was provided`);
return { success: false };
}
if (options.fileToRunMode && options.fileToRunMode !== 'specified') {
devkit_1.logger.warn(`A fileToRun was specified but fileToRunMode '${chalk.bold(options.fileToRunMode)}' as specifed (ignoring)`);
}
}
else {
// resolve `buildTarget` project details
const project = context.projectGraph.nodes[buildTarget.project];
const buildTargetExecutor = (_d = project.data.targets[buildTarget.target]) === null || _d === void 0 ? void 0 : _d.executor;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const buildOptions = Object.assign(Object.assign(Object.assign({}, (0, devkit_1.readTargetOptions)(buildTarget, context)), ((_e = options.buildTargetOptions) !== null && _e !== void 0 ? _e : {})), { target: buildTarget.target });
if (options.fileToRunMode === 'fromBuildTarget' ||
options.fileToRunMode === undefined) {
fileToRun = (0, node_utils_1.fileToRunCorrectPath)((0, node_utils_1.getFileToRun)(context, project, buildOptions, buildTargetExecutor));
}
else if (options.fileToRunMode === 'packageJson') {
// based on part of the getFileToRun() logic
const rawOutputPath = (_f = buildOptions === null || buildOptions === void 0 ? void 0 : buildOptions.outputPath) !== null && _f !== void 0 ? _f : (_h = (_g = project.data.targets[buildOptions.target]) === null || _g === void 0 ? void 0 : _g.outputs) === null || _h === void 0 ? void 0 : _h[0];
if (!rawOutputPath) {
devkit_1.logger.error(`File to run mode is 'specified' but no fileToRun was provided`);
devkit_1.logger.error(`Build option ${chalk.bold('outputPath')} not set for ${chalk.bold(project.name)}. Cannot determine output path.`);
return { success: false };
}
const outputPath = (0, utils_1.interpolate)(rawOutputPath, {
projectName: project.name,
projectRoot: project.data.root,
workspaceRoot: '',
});
fileToRun = (0, package_json_utils_1.resolveFileToRunFromPackageJson)((0, path_1.join)(context.root, outputPath));
if (!fileToRun) {
// error logged in resolveFileToRunFromPackageJson()
return { success: false };
}
}
else {
devkit_1.logger.error(`File to run mode is 'specified' but no fileToRun was provided`);
return { success: false };
}
}
devkit_1.logger.info(`NX Running node script ${fileToRun}`);
const relativeDirname = (0, path_1.relative)(context.root, __dirname);
const nodeRunner = relativeDirname === 'libs/nx-node-esm-plugin/src/executors/node'
? (0, path_1.join)(context.root, 'dist/libs/node-runner/src/lib/node-runner.mjs')
: (0, path_1.join)(__dirname, './node-runner/node-runner.mjs');
if (relativeDirname === 'libs/nx-node-esm-plugin/src/executors/node') {
yield performNodeRunnerLibBuild(context);
}
const result = yield (0, run_commands_utils_1.createProcess)({
command: nodeRunner,
args: [...((_j = options.args) !== null && _j !== void 0 ? _j : []), ...((_k = options.__unparsed__) !== null && _k !== void 0 ? _k : [])],
// prefix: 'xx> ',
// color: 'red',
}, (_l = options.color) !== null && _l !== void 0 ? _l : true, (0, run_commands_utils_1.calculateCwd)(options.cwd, context), Object.assign(Object.assign({}, ((_m = options.env) !== null && _m !== void 0 ? _m : {})), { NX_FILE_TO_RUN: fileToRun, NX_MAPPINGS: JSON.stringify(mappings), NX_MODULE_RESOLUTION_OVERRIDES: JSON.stringify((_o = options.moduleResolutionOverrides) !== null && _o !== void 0 ? _o : {}) }), true);
return {
success: result.success,
};
});
}
exports.default = runExecutorFunc;
//# sourceMappingURL=executor.js.map