This commit is contained in:
Sayak Mukhopadhyay 2022-12-27 16:41:12 +05:30 committed by GitHub
commit 768feb38f7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
8 changed files with 1139 additions and 1025 deletions

View File

@ -138,6 +138,7 @@ If the runner is not able to access github.com, any Nodejs versions requested du
8. [Publishing to npmjs and GPR with npm](docs/advanced-usage.md#publish-to-npmjs-and-gpr-with-npm) 8. [Publishing to npmjs and GPR with npm](docs/advanced-usage.md#publish-to-npmjs-and-gpr-with-npm)
9. [Publishing to npmjs and GPR with yarn](docs/advanced-usage.md#publish-to-npmjs-and-gpr-with-yarn) 9. [Publishing to npmjs and GPR with yarn](docs/advanced-usage.md#publish-to-npmjs-and-gpr-with-yarn)
10. [Using private packages](docs/advanced-usage.md#use-private-packages) 10. [Using private packages](docs/advanced-usage.md#use-private-packages)
11. [Enabling Corepack](docs/advanced-usage.md#enabling-corepack)
## License ## License

View File

@ -1253,6 +1253,44 @@ describe('setup-node', () => {
} }
); );
}); });
describe('corepack flag', () => {
it('use corepack if specified', async () => {
inputs['corepack'] = 'true';
await main.run();
expect(getExecOutputSpy).toHaveBeenCalledWith(
'corepack',
['enable'],
expect.anything()
);
});
it('use corepack with given package manager', async () => {
inputs['corepack'] = 'npm';
await main.run();
expect(getExecOutputSpy).toHaveBeenCalledWith(
'corepack',
['enable', 'npm'],
expect.anything()
);
});
it('use corepack with multiple package managers', async () => {
inputs['corepack'] = 'npm yarn';
await main.run();
expect(getExecOutputSpy).toHaveBeenCalledWith(
'corepack',
['enable', 'npm', 'yarn'],
expect.anything()
);
});
it('fails to use corepack with an invalid package manager', async () => {
await expect(im.enableCorepack('npm turbo')).rejects.toThrowError(
`One or more of the specified package managers [ npm turbo ] are not supported by corepack`
);
});
});
}); });
describe('helper methods', () => { describe('helper methods', () => {

View File

@ -25,6 +25,9 @@ inputs:
description: 'Used to specify a package manager for caching in the default directory. Supported values: npm, yarn, pnpm.' description: 'Used to specify a package manager for caching in the default directory. Supported values: npm, yarn, pnpm.'
cache-dependency-path: cache-dependency-path:
description: 'Used to specify the path to a dependency file: package-lock.json, yarn.lock, etc. Supports wildcards or a list of file names for caching multiple dependencies.' description: 'Used to specify the path to a dependency file: package-lock.json, yarn.lock, etc. Supports wildcards or a list of file names for caching multiple dependencies.'
corepack:
description: 'Used to specify whether to enable Corepack. Set to true to enable all package managers or set it to one or more package manager names (separate package manager names by a space. Supported package manager names: npm, yarn, pnpm.'
default: 'false'
# TODO: add input to control forcing to pull from cloud or dist. # TODO: add input to control forcing to pull from cloud or dist.
# escape valve for someone having issues or needing the absolute latest which isn't cached yet # escape valve for someone having issues or needing the absolute latest which isn't cached yet
outputs: outputs:

View File

@ -61018,74 +61018,74 @@ exports.fromPromise = function (fn) {
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const cache = __importStar(__nccwpck_require__(7799)); const cache = __importStar(__nccwpck_require__(7799));
const fs_1 = __importDefault(__nccwpck_require__(7147)); const fs_1 = __importDefault(__nccwpck_require__(7147));
const constants_1 = __nccwpck_require__(9042); const constants_1 = __nccwpck_require__(9042);
const cache_utils_1 = __nccwpck_require__(1678); const cache_utils_1 = __nccwpck_require__(1678);
// Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in // Catch and log any unhandled exceptions. These exceptions can leak out of the uploadChunk method in
// @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to // @actions/toolkit when a failed upload closes the file descriptor causing any in-process reads to
// throw an uncaught exception. Instead of failing this action, just warn. // throw an uncaught exception. Instead of failing this action, just warn.
process.on('uncaughtException', e => { process.on('uncaughtException', e => {
const warningPrefix = '[warning]'; const warningPrefix = '[warning]';
core.info(`${warningPrefix}${e.message}`); core.info(`${warningPrefix}${e.message}`);
}); });
function run() { function run() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try { try {
const cacheLock = core.getInput('cache'); const cacheLock = core.getInput('cache');
yield cachePackages(cacheLock); yield cachePackages(cacheLock);
} }
catch (error) { catch (error) {
core.setFailed(error.message); core.setFailed(error.message);
} }
}); });
} }
exports.run = run; exports.run = run;
const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { const cachePackages = (packageManager) => __awaiter(void 0, void 0, void 0, function* () {
const state = core.getState(constants_1.State.CacheMatchedKey); const state = core.getState(constants_1.State.CacheMatchedKey);
const primaryKey = core.getState(constants_1.State.CachePrimaryKey); const primaryKey = core.getState(constants_1.State.CachePrimaryKey);
const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager);
if (!packageManagerInfo) { if (!packageManagerInfo) {
core.debug(`Caching for '${packageManager}' is not supported`); core.debug(`Caching for '${packageManager}' is not supported`);
return; return;
} }
const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager);
if (!fs_1.default.existsSync(cachePath)) { if (!fs_1.default.existsSync(cachePath)) {
throw new Error(`Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}`); throw new Error(`Cache folder path is retrieved for ${packageManager} but doesn't exist on disk: ${cachePath}`);
} }
if (primaryKey === state) { if (primaryKey === state) {
core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`); core.info(`Cache hit occurred on the primary key ${primaryKey}, not saving cache.`);
return; return;
} }
const cacheId = yield cache.saveCache([cachePath], primaryKey); const cacheId = yield cache.saveCache([cachePath], primaryKey);
if (cacheId == -1) { if (cacheId == -1) {
return; return;
} }
core.info(`Cache saved with the key: ${primaryKey}`); core.info(`Cache saved with the key: ${primaryKey}`);
}); });
run(); run();
/***/ }), /***/ }),
@ -61094,107 +61094,107 @@ run();
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514)); const exec = __importStar(__nccwpck_require__(1514));
const cache = __importStar(__nccwpck_require__(7799)); const cache = __importStar(__nccwpck_require__(7799));
exports.supportedPackageManagers = { exports.supportedPackageManagers = {
npm: { npm: {
lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'],
getCacheFolderCommand: 'npm config get cache' getCacheFolderCommand: 'npm config get cache'
}, },
pnpm: { pnpm: {
lockFilePatterns: ['pnpm-lock.yaml'], lockFilePatterns: ['pnpm-lock.yaml'],
getCacheFolderCommand: 'pnpm store path --silent' getCacheFolderCommand: 'pnpm store path --silent'
}, },
yarn1: { yarn1: {
lockFilePatterns: ['yarn.lock'], lockFilePatterns: ['yarn.lock'],
getCacheFolderCommand: 'yarn cache dir' getCacheFolderCommand: 'yarn cache dir'
}, },
yarn2: { yarn2: {
lockFilePatterns: ['yarn.lock'], lockFilePatterns: ['yarn.lock'],
getCacheFolderCommand: 'yarn config get cacheFolder' getCacheFolderCommand: 'yarn config get cacheFolder'
} }
}; };
exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () {
let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true });
if (exitCode) { if (exitCode) {
stderr = !stderr.trim() stderr = !stderr.trim()
? `The '${toolCommand}' command failed with exit code: ${exitCode}` ? `The '${toolCommand}' command failed with exit code: ${exitCode}`
: stderr; : stderr;
throw new Error(stderr); throw new Error(stderr);
} }
return stdout.trim(); return stdout.trim();
}); });
const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () {
const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`);
if (!stdOut) { if (!stdOut) {
throw new Error(`Could not retrieve version of ${packageManager}`); throw new Error(`Could not retrieve version of ${packageManager}`);
} }
return stdOut; return stdOut;
}); });
exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () {
if (packageManager === 'npm') { if (packageManager === 'npm') {
return exports.supportedPackageManagers.npm; return exports.supportedPackageManagers.npm;
} }
else if (packageManager === 'pnpm') { else if (packageManager === 'pnpm') {
return exports.supportedPackageManagers.pnpm; return exports.supportedPackageManagers.pnpm;
} }
else if (packageManager === 'yarn') { else if (packageManager === 'yarn') {
const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); const yarnVersion = yield getPackageManagerVersion('yarn', '--version');
core.debug(`Consumed yarn version is ${yarnVersion}`); core.debug(`Consumed yarn version is ${yarnVersion}`);
if (yarnVersion.startsWith('1.')) { if (yarnVersion.startsWith('1.')) {
return exports.supportedPackageManagers.yarn1; return exports.supportedPackageManagers.yarn1;
} }
else { else {
return exports.supportedPackageManagers.yarn2; return exports.supportedPackageManagers.yarn2;
} }
} }
else { else {
return null; return null;
} }
}); });
exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () {
const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand);
if (!stdOut) { if (!stdOut) {
throw new Error(`Could not get cache folder path for ${packageManager}`); throw new Error(`Could not get cache folder path for ${packageManager}`);
} }
core.debug(`${packageManager} path is ${stdOut}`); core.debug(`${packageManager} path is ${stdOut}`);
return stdOut.trim(); return stdOut.trim();
}); });
function isGhes() { function isGhes() {
const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM';
} }
exports.isGhes = isGhes; exports.isGhes = isGhes;
function isCacheFeatureAvailable() { function isCacheFeatureAvailable() {
if (cache.isFeatureAvailable()) if (cache.isFeatureAvailable())
return true; return true;
if (isGhes()) { if (isGhes()) {
core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.');
return false; return false;
} }
core.warning('The runner was not able to contact the cache service. Caching will be skipped'); core.warning('The runner was not able to contact the cache service. Caching will be skipped');
return false; return false;
} }
exports.isCacheFeatureAvailable = isCacheFeatureAvailable; exports.isCacheFeatureAvailable = isCacheFeatureAvailable;
/***/ }), /***/ }),
@ -61203,23 +61203,23 @@ exports.isCacheFeatureAvailable = isCacheFeatureAvailable;
/***/ ((__unused_webpack_module, exports) => { /***/ ((__unused_webpack_module, exports) => {
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
var LockType; var LockType;
(function (LockType) { (function (LockType) {
LockType["Npm"] = "npm"; LockType["Npm"] = "npm";
LockType["Pnpm"] = "pnpm"; LockType["Pnpm"] = "pnpm";
LockType["Yarn"] = "yarn"; LockType["Yarn"] = "yarn";
})(LockType = exports.LockType || (exports.LockType = {})); })(LockType = exports.LockType || (exports.LockType = {}));
var State; var State;
(function (State) { (function (State) {
State["CachePrimaryKey"] = "CACHE_KEY"; State["CachePrimaryKey"] = "CACHE_KEY";
State["CacheMatchedKey"] = "CACHE_RESULT"; State["CacheMatchedKey"] = "CACHE_RESULT";
})(State = exports.State || (exports.State = {})); })(State = exports.State || (exports.State = {}));
var Outputs; var Outputs;
(function (Outputs) { (function (Outputs) {
Outputs["CacheHit"] = "cache-hit"; Outputs["CacheHit"] = "cache-hit";
})(Outputs = exports.Outputs || (exports.Outputs = {})); })(Outputs = exports.Outputs || (exports.Outputs = {}));
/***/ }), /***/ }),

1699
dist/setup/index.js vendored
View File

@ -72914,60 +72914,60 @@ function wrappy (fn, cb) {
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict"; "use strict";
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const fs = __importStar(__nccwpck_require__(7147)); const fs = __importStar(__nccwpck_require__(7147));
const os = __importStar(__nccwpck_require__(2037)); const os = __importStar(__nccwpck_require__(2037));
const path = __importStar(__nccwpck_require__(1017)); const path = __importStar(__nccwpck_require__(1017));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const github = __importStar(__nccwpck_require__(5438)); const github = __importStar(__nccwpck_require__(5438));
function configAuthentication(registryUrl, alwaysAuth) { function configAuthentication(registryUrl, alwaysAuth) {
const npmrc = path.resolve(process.env['RUNNER_TEMP'] || process.cwd(), '.npmrc'); const npmrc = path.resolve(process.env['RUNNER_TEMP'] || process.cwd(), '.npmrc');
if (!registryUrl.endsWith('/')) { if (!registryUrl.endsWith('/')) {
registryUrl += '/'; registryUrl += '/';
} }
writeRegistryToFile(registryUrl, npmrc, alwaysAuth); writeRegistryToFile(registryUrl, npmrc, alwaysAuth);
} }
exports.configAuthentication = configAuthentication; exports.configAuthentication = configAuthentication;
function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) { function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) {
let scope = core.getInput('scope'); let scope = core.getInput('scope');
if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) { if (!scope && registryUrl.indexOf('npm.pkg.github.com') > -1) {
scope = github.context.repo.owner; scope = github.context.repo.owner;
} }
if (scope && scope[0] != '@') { if (scope && scope[0] != '@') {
scope = '@' + scope; scope = '@' + scope;
} }
if (scope) { if (scope) {
scope = scope.toLowerCase() + ':'; scope = scope.toLowerCase() + ':';
} }
core.debug(`Setting auth in ${fileLocation}`); core.debug(`Setting auth in ${fileLocation}`);
let newContents = ''; let newContents = '';
if (fs.existsSync(fileLocation)) { if (fs.existsSync(fileLocation)) {
const curContents = fs.readFileSync(fileLocation, 'utf8'); const curContents = fs.readFileSync(fileLocation, 'utf8');
curContents.split(os.EOL).forEach((line) => { curContents.split(os.EOL).forEach((line) => {
// Add current contents unless they are setting the registry // Add current contents unless they are setting the registry
if (!line.toLowerCase().startsWith(`${scope}registry`)) { if (!line.toLowerCase().startsWith(`${scope}registry`)) {
newContents += line + os.EOL; newContents += line + os.EOL;
} }
}); });
} }
// Remove http: or https: from front of registry. // Remove http: or https: from front of registry.
const authString = registryUrl.replace(/(^\w+:|^)/, '') + ':_authToken=${NODE_AUTH_TOKEN}'; const authString = registryUrl.replace(/(^\w+:|^)/, '') + ':_authToken=${NODE_AUTH_TOKEN}';
const registryString = `${scope}registry=${registryUrl}`; const registryString = `${scope}registry=${registryUrl}`;
const alwaysAuthString = `always-auth=${alwaysAuth}`; const alwaysAuthString = `always-auth=${alwaysAuth}`;
newContents += `${authString}${os.EOL}${registryString}${os.EOL}${alwaysAuthString}`; newContents += `${authString}${os.EOL}${registryString}${os.EOL}${alwaysAuthString}`;
fs.writeFileSync(fileLocation, newContents); fs.writeFileSync(fileLocation, newContents);
core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation); core.exportVariable('NPM_CONFIG_USERCONFIG', fileLocation);
// Export empty node_auth_token if didn't exist so npm doesn't complain about not being able to find it // Export empty node_auth_token if didn't exist so npm doesn't complain about not being able to find it
core.exportVariable('NODE_AUTH_TOKEN', process.env.NODE_AUTH_TOKEN || 'XXXXX-XXXXX-XXXXX-XXXXX'); core.exportVariable('NODE_AUTH_TOKEN', process.env.NODE_AUTH_TOKEN || 'XXXXX-XXXXX-XXXXX-XXXXX');
} }
/***/ }), /***/ }),
@ -72976,70 +72976,70 @@ function writeRegistryToFile(registryUrl, fileLocation, alwaysAuth) {
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const cache = __importStar(__nccwpck_require__(7799)); const cache = __importStar(__nccwpck_require__(7799));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const glob = __importStar(__nccwpck_require__(8090)); const glob = __importStar(__nccwpck_require__(8090));
const path_1 = __importDefault(__nccwpck_require__(1017)); const path_1 = __importDefault(__nccwpck_require__(1017));
const fs_1 = __importDefault(__nccwpck_require__(7147)); const fs_1 = __importDefault(__nccwpck_require__(7147));
const constants_1 = __nccwpck_require__(9042); const constants_1 = __nccwpck_require__(9042);
const cache_utils_1 = __nccwpck_require__(1678); const cache_utils_1 = __nccwpck_require__(1678);
exports.restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () { exports.restoreCache = (packageManager, cacheDependencyPath) => __awaiter(void 0, void 0, void 0, function* () {
const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager); const packageManagerInfo = yield cache_utils_1.getPackageManagerInfo(packageManager);
if (!packageManagerInfo) { if (!packageManagerInfo) {
throw new Error(`Caching for '${packageManager}' is not supported`); throw new Error(`Caching for '${packageManager}' is not supported`);
} }
const platform = process.env.RUNNER_OS; const platform = process.env.RUNNER_OS;
const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager); const cachePath = yield cache_utils_1.getCacheDirectoryPath(packageManagerInfo, packageManager);
const lockFilePath = cacheDependencyPath const lockFilePath = cacheDependencyPath
? cacheDependencyPath ? cacheDependencyPath
: findLockFile(packageManagerInfo); : findLockFile(packageManagerInfo);
const fileHash = yield glob.hashFiles(lockFilePath); const fileHash = yield glob.hashFiles(lockFilePath);
if (!fileHash) { if (!fileHash) {
throw new Error('Some specified paths were not resolved, unable to cache dependencies.'); throw new Error('Some specified paths were not resolved, unable to cache dependencies.');
} }
const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`; const primaryKey = `node-cache-${platform}-${packageManager}-${fileHash}`;
core.debug(`primary key is ${primaryKey}`); core.debug(`primary key is ${primaryKey}`);
core.saveState(constants_1.State.CachePrimaryKey, primaryKey); core.saveState(constants_1.State.CachePrimaryKey, primaryKey);
const cacheKey = yield cache.restoreCache([cachePath], primaryKey); const cacheKey = yield cache.restoreCache([cachePath], primaryKey);
core.setOutput('cache-hit', Boolean(cacheKey)); core.setOutput('cache-hit', Boolean(cacheKey));
if (!cacheKey) { if (!cacheKey) {
core.info(`${packageManager} cache is not found`); core.info(`${packageManager} cache is not found`);
return; return;
} }
core.saveState(constants_1.State.CacheMatchedKey, cacheKey); core.saveState(constants_1.State.CacheMatchedKey, cacheKey);
core.info(`Cache restored from key: ${cacheKey}`); core.info(`Cache restored from key: ${cacheKey}`);
}); });
const findLockFile = (packageManager) => { const findLockFile = (packageManager) => {
let lockFiles = packageManager.lockFilePatterns; let lockFiles = packageManager.lockFilePatterns;
const workspace = process.env.GITHUB_WORKSPACE; const workspace = process.env.GITHUB_WORKSPACE;
const rootContent = fs_1.default.readdirSync(workspace); const rootContent = fs_1.default.readdirSync(workspace);
const lockFile = lockFiles.find(item => rootContent.includes(item)); const lockFile = lockFiles.find(item => rootContent.includes(item));
if (!lockFile) { if (!lockFile) {
throw new Error(`Dependencies lock file is not found in ${workspace}. Supported file patterns: ${lockFiles.toString()}`); throw new Error(`Dependencies lock file is not found in ${workspace}. Supported file patterns: ${lockFiles.toString()}`);
} }
return path_1.default.join(workspace, lockFile); return path_1.default.join(workspace, lockFile);
}; };
/***/ }), /***/ }),
@ -73048,107 +73048,107 @@ const findLockFile = (packageManager) => {
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514)); const exec = __importStar(__nccwpck_require__(1514));
const cache = __importStar(__nccwpck_require__(7799)); const cache = __importStar(__nccwpck_require__(7799));
exports.supportedPackageManagers = { exports.supportedPackageManagers = {
npm: { npm: {
lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'], lockFilePatterns: ['package-lock.json', 'npm-shrinkwrap.json', 'yarn.lock'],
getCacheFolderCommand: 'npm config get cache' getCacheFolderCommand: 'npm config get cache'
}, },
pnpm: { pnpm: {
lockFilePatterns: ['pnpm-lock.yaml'], lockFilePatterns: ['pnpm-lock.yaml'],
getCacheFolderCommand: 'pnpm store path --silent' getCacheFolderCommand: 'pnpm store path --silent'
}, },
yarn1: { yarn1: {
lockFilePatterns: ['yarn.lock'], lockFilePatterns: ['yarn.lock'],
getCacheFolderCommand: 'yarn cache dir' getCacheFolderCommand: 'yarn cache dir'
}, },
yarn2: { yarn2: {
lockFilePatterns: ['yarn.lock'], lockFilePatterns: ['yarn.lock'],
getCacheFolderCommand: 'yarn config get cacheFolder' getCacheFolderCommand: 'yarn config get cacheFolder'
} }
}; };
exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () { exports.getCommandOutput = (toolCommand) => __awaiter(void 0, void 0, void 0, function* () {
let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true }); let { stdout, stderr, exitCode } = yield exec.getExecOutput(toolCommand, undefined, { ignoreReturnCode: true });
if (exitCode) { if (exitCode) {
stderr = !stderr.trim() stderr = !stderr.trim()
? `The '${toolCommand}' command failed with exit code: ${exitCode}` ? `The '${toolCommand}' command failed with exit code: ${exitCode}`
: stderr; : stderr;
throw new Error(stderr); throw new Error(stderr);
} }
return stdout.trim(); return stdout.trim();
}); });
const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () { const getPackageManagerVersion = (packageManager, command) => __awaiter(void 0, void 0, void 0, function* () {
const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`); const stdOut = yield exports.getCommandOutput(`${packageManager} ${command}`);
if (!stdOut) { if (!stdOut) {
throw new Error(`Could not retrieve version of ${packageManager}`); throw new Error(`Could not retrieve version of ${packageManager}`);
} }
return stdOut; return stdOut;
}); });
exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () { exports.getPackageManagerInfo = (packageManager) => __awaiter(void 0, void 0, void 0, function* () {
if (packageManager === 'npm') { if (packageManager === 'npm') {
return exports.supportedPackageManagers.npm; return exports.supportedPackageManagers.npm;
} }
else if (packageManager === 'pnpm') { else if (packageManager === 'pnpm') {
return exports.supportedPackageManagers.pnpm; return exports.supportedPackageManagers.pnpm;
} }
else if (packageManager === 'yarn') { else if (packageManager === 'yarn') {
const yarnVersion = yield getPackageManagerVersion('yarn', '--version'); const yarnVersion = yield getPackageManagerVersion('yarn', '--version');
core.debug(`Consumed yarn version is ${yarnVersion}`); core.debug(`Consumed yarn version is ${yarnVersion}`);
if (yarnVersion.startsWith('1.')) { if (yarnVersion.startsWith('1.')) {
return exports.supportedPackageManagers.yarn1; return exports.supportedPackageManagers.yarn1;
} }
else { else {
return exports.supportedPackageManagers.yarn2; return exports.supportedPackageManagers.yarn2;
} }
} }
else { else {
return null; return null;
} }
}); });
exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () { exports.getCacheDirectoryPath = (packageManagerInfo, packageManager) => __awaiter(void 0, void 0, void 0, function* () {
const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand); const stdOut = yield exports.getCommandOutput(packageManagerInfo.getCacheFolderCommand);
if (!stdOut) { if (!stdOut) {
throw new Error(`Could not get cache folder path for ${packageManager}`); throw new Error(`Could not get cache folder path for ${packageManager}`);
} }
core.debug(`${packageManager} path is ${stdOut}`); core.debug(`${packageManager} path is ${stdOut}`);
return stdOut.trim(); return stdOut.trim();
}); });
function isGhes() { function isGhes() {
const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com'); const ghUrl = new URL(process.env['GITHUB_SERVER_URL'] || 'https://github.com');
return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM'; return ghUrl.hostname.toUpperCase() !== 'GITHUB.COM';
} }
exports.isGhes = isGhes; exports.isGhes = isGhes;
function isCacheFeatureAvailable() { function isCacheFeatureAvailable() {
if (cache.isFeatureAvailable()) if (cache.isFeatureAvailable())
return true; return true;
if (isGhes()) { if (isGhes()) {
core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.'); core.warning('Cache action is only supported on GHES version >= 3.5. If you are on version >=3.5 Please check with GHES admin if Actions cache service is enabled or not.');
return false; return false;
} }
core.warning('The runner was not able to contact the cache service. Caching will be skipped'); core.warning('The runner was not able to contact the cache service. Caching will be skipped');
return false; return false;
} }
exports.isCacheFeatureAvailable = isCacheFeatureAvailable; exports.isCacheFeatureAvailable = isCacheFeatureAvailable;
/***/ }), /***/ }),
@ -73157,23 +73157,23 @@ exports.isCacheFeatureAvailable = isCacheFeatureAvailable;
/***/ ((__unused_webpack_module, exports) => { /***/ ((__unused_webpack_module, exports) => {
"use strict"; "use strict";
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
var LockType; var LockType;
(function (LockType) { (function (LockType) {
LockType["Npm"] = "npm"; LockType["Npm"] = "npm";
LockType["Pnpm"] = "pnpm"; LockType["Pnpm"] = "pnpm";
LockType["Yarn"] = "yarn"; LockType["Yarn"] = "yarn";
})(LockType = exports.LockType || (exports.LockType = {})); })(LockType = exports.LockType || (exports.LockType = {}));
var State; var State;
(function (State) { (function (State) {
State["CachePrimaryKey"] = "CACHE_KEY"; State["CachePrimaryKey"] = "CACHE_KEY";
State["CacheMatchedKey"] = "CACHE_RESULT"; State["CacheMatchedKey"] = "CACHE_RESULT";
})(State = exports.State || (exports.State = {})); })(State = exports.State || (exports.State = {}));
var Outputs; var Outputs;
(function (Outputs) { (function (Outputs) {
Outputs["CacheHit"] = "cache-hit"; Outputs["CacheHit"] = "cache-hit";
})(Outputs = exports.Outputs || (exports.Outputs = {})); })(Outputs = exports.Outputs || (exports.Outputs = {}));
/***/ }), /***/ }),
@ -73182,477 +73182,496 @@ var Outputs;
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const os_1 = __importDefault(__nccwpck_require__(2037)); const os_1 = __importDefault(__nccwpck_require__(2037));
const assert = __importStar(__nccwpck_require__(9491)); const assert = __importStar(__nccwpck_require__(9491));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const hc = __importStar(__nccwpck_require__(9925)); const hc = __importStar(__nccwpck_require__(9925));
const io = __importStar(__nccwpck_require__(7436)); const io = __importStar(__nccwpck_require__(7436));
const tc = __importStar(__nccwpck_require__(7784)); const tc = __importStar(__nccwpck_require__(7784));
const path = __importStar(__nccwpck_require__(1017)); const exec = __importStar(__nccwpck_require__(1514));
const semver = __importStar(__nccwpck_require__(5911)); const path = __importStar(__nccwpck_require__(1017));
const fs_1 = __importDefault(__nccwpck_require__(7147)); const semver = __importStar(__nccwpck_require__(5911));
function getNode(versionSpec, stable, checkLatest, auth, arch = os_1.default.arch()) { const fs_1 = __importDefault(__nccwpck_require__(7147));
return __awaiter(this, void 0, void 0, function* () { function getNode(versionSpec, stable, checkLatest, auth, arch = os_1.default.arch()) {
// Store manifest data to avoid multiple calls return __awaiter(this, void 0, void 0, function* () {
let manifest; // Store manifest data to avoid multiple calls
let nodeVersions; let manifest;
let isNightly = versionSpec.includes('nightly'); let nodeVersions;
let osPlat = os_1.default.platform(); let isNightly = versionSpec.includes('nightly');
let osArch = translateArchToDistUrl(arch); let osPlat = os_1.default.platform();
if (isLtsAlias(versionSpec)) { let osArch = translateArchToDistUrl(arch);
core.info('Attempt to resolve LTS alias from manifest...'); if (isLtsAlias(versionSpec)) {
// No try-catch since it's not possible to resolve LTS alias without manifest core.info('Attempt to resolve LTS alias from manifest...');
manifest = yield getManifest(auth); // No try-catch since it's not possible to resolve LTS alias without manifest
versionSpec = resolveLtsAliasFromManifest(versionSpec, stable, manifest); manifest = yield getManifest(auth);
} versionSpec = resolveLtsAliasFromManifest(versionSpec, stable, manifest);
if (isLatestSyntax(versionSpec)) { }
nodeVersions = yield getVersionsFromDist(versionSpec); if (isLatestSyntax(versionSpec)) {
versionSpec = yield queryDistForMatch(versionSpec, arch, nodeVersions); nodeVersions = yield getVersionsFromDist(versionSpec);
core.info(`getting latest node version...`); versionSpec = yield queryDistForMatch(versionSpec, arch, nodeVersions);
} core.info(`getting latest node version...`);
if (isNightly && checkLatest) { }
nodeVersions = yield getVersionsFromDist(versionSpec); if (isNightly && checkLatest) {
versionSpec = yield queryDistForMatch(versionSpec, arch, nodeVersions); nodeVersions = yield getVersionsFromDist(versionSpec);
} versionSpec = yield queryDistForMatch(versionSpec, arch, nodeVersions);
if (checkLatest && !isNightly) { }
core.info('Attempt to resolve the latest version from manifest...'); if (checkLatest && !isNightly) {
const resolvedVersion = yield resolveVersionFromManifest(versionSpec, stable, auth, osArch, manifest); core.info('Attempt to resolve the latest version from manifest...');
if (resolvedVersion) { const resolvedVersion = yield resolveVersionFromManifest(versionSpec, stable, auth, osArch, manifest);
versionSpec = resolvedVersion; if (resolvedVersion) {
core.info(`Resolved as '${versionSpec}'`); versionSpec = resolvedVersion;
} core.info(`Resolved as '${versionSpec}'`);
else { }
core.info(`Failed to resolve version ${versionSpec} from manifest`); else {
} core.info(`Failed to resolve version ${versionSpec} from manifest`);
} }
// check cache }
let toolPath; // check cache
if (isNightly) { let toolPath;
const nightlyVersion = findNightlyVersionInHostedToolcache(versionSpec, osArch); if (isNightly) {
toolPath = nightlyVersion && tc.find('node', nightlyVersion, osArch); const nightlyVersion = findNightlyVersionInHostedToolcache(versionSpec, osArch);
} toolPath = nightlyVersion && tc.find('node', nightlyVersion, osArch);
else { }
toolPath = tc.find('node', versionSpec, osArch); else {
} toolPath = tc.find('node', versionSpec, osArch);
// If not found in cache, download }
if (toolPath) { // If not found in cache, download
core.info(`Found in cache @ ${toolPath}`); if (toolPath) {
} core.info(`Found in cache @ ${toolPath}`);
else { }
core.info(`Attempting to download ${versionSpec}...`); else {
let downloadPath = ''; core.info(`Attempting to download ${versionSpec}...`);
let info = null; let downloadPath = '';
// let info = null;
// Try download from internal distribution (popular versions only) //
// // Try download from internal distribution (popular versions only)
try { //
info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest); try {
if (info) { info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest);
core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); if (info) {
downloadPath = yield tc.downloadTool(info.downloadUrl, undefined, auth); core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`);
} downloadPath = yield tc.downloadTool(info.downloadUrl, undefined, auth);
else { }
core.info('Not found in manifest. Falling back to download directly from Node'); else {
} core.info('Not found in manifest. Falling back to download directly from Node');
} }
catch (err) { }
// Rate limit? catch (err) {
if (err instanceof tc.HTTPError && // Rate limit?
(err.httpStatusCode === 403 || err.httpStatusCode === 429)) { if (err instanceof tc.HTTPError &&
core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`); (err.httpStatusCode === 403 || err.httpStatusCode === 429)) {
} core.info(`Received HTTP status code ${err.httpStatusCode}. This usually indicates the rate limit has been exceeded`);
else { }
core.info(err.message); else {
} core.info(err.message);
core.debug(err.stack); }
core.info('Falling back to download directly from Node'); core.debug(err.stack);
} core.info('Falling back to download directly from Node');
// }
// Download from nodejs.org //
// // Download from nodejs.org
if (!downloadPath) { //
info = yield getInfoFromDist(versionSpec, arch, nodeVersions); if (!downloadPath) {
if (!info) { info = yield getInfoFromDist(versionSpec, arch, nodeVersions);
throw new Error(`Unable to find Node version '${versionSpec}' for platform ${osPlat} and architecture ${osArch}.`); if (!info) {
} throw new Error(`Unable to find Node version '${versionSpec}' for platform ${osPlat} and architecture ${osArch}.`);
core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`); }
try { core.info(`Acquiring ${info.resolvedVersion} - ${info.arch} from ${info.downloadUrl}`);
downloadPath = yield tc.downloadTool(info.downloadUrl); try {
} downloadPath = yield tc.downloadTool(info.downloadUrl);
catch (err) { }
if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { catch (err) {
return yield acquireNodeFromFallbackLocation(info.resolvedVersion, info.arch); if (err instanceof tc.HTTPError && err.httpStatusCode == 404) {
} return yield acquireNodeFromFallbackLocation(info.resolvedVersion, info.arch);
throw err; }
} throw err;
} }
// }
// Extract //
// // Extract
core.info('Extracting ...'); //
let extPath; core.info('Extracting ...');
info = info || {}; // satisfy compiler, never null when reaches here let extPath;
if (osPlat == 'win32') { info = info || {}; // satisfy compiler, never null when reaches here
let _7zPath = path.join(__dirname, '../..', 'externals', '7zr.exe'); if (osPlat == 'win32') {
extPath = yield tc.extract7z(downloadPath, undefined, _7zPath); let _7zPath = path.join(__dirname, '../..', 'externals', '7zr.exe');
// 7z extracts to folder matching file name extPath = yield tc.extract7z(downloadPath, undefined, _7zPath);
let nestedPath = path.join(extPath, path.basename(info.fileName, '.7z')); // 7z extracts to folder matching file name
if (fs_1.default.existsSync(nestedPath)) { let nestedPath = path.join(extPath, path.basename(info.fileName, '.7z'));
extPath = nestedPath; if (fs_1.default.existsSync(nestedPath)) {
} extPath = nestedPath;
} }
else { }
extPath = yield tc.extractTar(downloadPath, undefined, [ else {
'xz', extPath = yield tc.extractTar(downloadPath, undefined, [
'--strip', 'xz',
'1' '--strip',
]); '1'
} ]);
// }
// Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded //
// // Install into the local tool cache - node extracts with a root folder that matches the fileName downloaded
core.info('Adding to the cache ...'); //
toolPath = yield tc.cacheDir(extPath, 'node', info.resolvedVersion, info.arch); core.info('Adding to the cache ...');
core.info('Done'); toolPath = yield tc.cacheDir(extPath, 'node', info.resolvedVersion, info.arch);
} core.info('Done');
// }
// a tool installer initimately knows details about the layout of that tool //
// for example, node binary is in the bin folder after the extract on Mac/Linux. // a tool installer initimately knows details about the layout of that tool
// layouts could change by version, by platform etc... but that's the tool installers job // for example, node binary is in the bin folder after the extract on Mac/Linux.
// // layouts could change by version, by platform etc... but that's the tool installers job
if (osPlat != 'win32') { //
toolPath = path.join(toolPath, 'bin'); if (osPlat != 'win32') {
} toolPath = path.join(toolPath, 'bin');
// }
// prepend the tools path. instructs the agent to prepend for future tasks //
core.addPath(toolPath); // prepend the tools path. instructs the agent to prepend for future tasks
}); core.addPath(toolPath);
} });
exports.getNode = getNode; }
function findNightlyVersionInHostedToolcache(versionsSpec, osArch) { exports.getNode = getNode;
const foundAllVersions = tc.findAllVersions('node', osArch); function findNightlyVersionInHostedToolcache(versionsSpec, osArch) {
const version = evaluateVersions(foundAllVersions, versionsSpec); const foundAllVersions = tc.findAllVersions('node', osArch);
return version; const version = evaluateVersions(foundAllVersions, versionsSpec);
} return version;
function isLtsAlias(versionSpec) { }
return versionSpec.startsWith('lts/'); function isLtsAlias(versionSpec) {
} return versionSpec.startsWith('lts/');
function getManifest(auth) { }
core.debug('Getting manifest from actions/node-versions@main'); function getManifest(auth) {
return tc.getManifestFromRepo('actions', 'node-versions', auth, 'main'); core.debug('Getting manifest from actions/node-versions@main');
} return tc.getManifestFromRepo('actions', 'node-versions', auth, 'main');
function resolveLtsAliasFromManifest(versionSpec, stable, manifest) { }
var _a; function resolveLtsAliasFromManifest(versionSpec, stable, manifest) {
const alias = (_a = versionSpec.split('lts/')[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase(); var _a;
if (!alias) { const alias = (_a = versionSpec.split('lts/')[1]) === null || _a === void 0 ? void 0 : _a.toLowerCase();
throw new Error(`Unable to parse LTS alias for Node version '${versionSpec}'`); if (!alias) {
} throw new Error(`Unable to parse LTS alias for Node version '${versionSpec}'`);
core.debug(`LTS alias '${alias}' for Node version '${versionSpec}'`); }
// Supported formats are `lts/<alias>`, `lts/*`, and `lts/-n`. Where asterisk means highest possible LTS and -n means the nth-highest. core.debug(`LTS alias '${alias}' for Node version '${versionSpec}'`);
const n = Number(alias); // Supported formats are `lts/<alias>`, `lts/*`, and `lts/-n`. Where asterisk means highest possible LTS and -n means the nth-highest.
const aliases = Object.fromEntries(manifest const n = Number(alias);
.filter(x => x.lts && x.stable === stable) const aliases = Object.fromEntries(manifest
.map(x => [x.lts.toLowerCase(), x]) .filter(x => x.lts && x.stable === stable)
.reverse()); .map(x => [x.lts.toLowerCase(), x])
const numbered = Object.values(aliases); .reverse());
const release = alias === '*' const numbered = Object.values(aliases);
? numbered[numbered.length - 1] const release = alias === '*'
: n < 0 ? numbered[numbered.length - 1]
? numbered[numbered.length - 1 + n] : n < 0
: aliases[alias]; ? numbered[numbered.length - 1 + n]
if (!release) { : aliases[alias];
throw new Error(`Unable to find LTS release '${alias}' for Node version '${versionSpec}'.`); if (!release) {
} throw new Error(`Unable to find LTS release '${alias}' for Node version '${versionSpec}'.`);
core.debug(`Found LTS release '${release.version}' for Node version '${versionSpec}'`); }
return release.version.split('.')[0]; core.debug(`Found LTS release '${release.version}' for Node version '${versionSpec}'`);
} return release.version.split('.')[0];
function getInfoFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os_1.default.arch()), manifest) { }
return __awaiter(this, void 0, void 0, function* () { function getInfoFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os_1.default.arch()), manifest) {
let info = null; return __awaiter(this, void 0, void 0, function* () {
if (!manifest) { let info = null;
core.debug('No manifest cached'); if (!manifest) {
manifest = yield getManifest(auth); core.debug('No manifest cached');
} manifest = yield getManifest(auth);
const rel = yield tc.findFromManifest(versionSpec, stable, manifest, osArch); }
if (rel && rel.files.length > 0) { const rel = yield tc.findFromManifest(versionSpec, stable, manifest, osArch);
info = {}; if (rel && rel.files.length > 0) {
info.resolvedVersion = rel.version; info = {};
info.arch = rel.files[0].arch; info.resolvedVersion = rel.version;
info.downloadUrl = rel.files[0].download_url; info.arch = rel.files[0].arch;
info.fileName = rel.files[0].filename; info.downloadUrl = rel.files[0].download_url;
} info.fileName = rel.files[0].filename;
return info; }
}); return info;
} });
function getInfoFromDist(versionSpec, arch = os_1.default.arch(), nodeVersions) { }
return __awaiter(this, void 0, void 0, function* () { function getInfoFromDist(versionSpec, arch = os_1.default.arch(), nodeVersions) {
let osPlat = os_1.default.platform(); return __awaiter(this, void 0, void 0, function* () {
let osArch = translateArchToDistUrl(arch); let osPlat = os_1.default.platform();
let version = yield queryDistForMatch(versionSpec, arch, nodeVersions); let osArch = translateArchToDistUrl(arch);
if (!version) { let version = yield queryDistForMatch(versionSpec, arch, nodeVersions);
return null; if (!version) {
} return null;
// }
// Download - a tool installer intimately knows how to get the tool (and construct urls) //
// // Download - a tool installer intimately knows how to get the tool (and construct urls)
version = semver.clean(version) || ''; //
let fileName = osPlat == 'win32' version = semver.clean(version) || '';
? `node-v${version}-win-${osArch}` let fileName = osPlat == 'win32'
: `node-v${version}-${osPlat}-${osArch}`; ? `node-v${version}-win-${osArch}`
let urlFileName = osPlat == 'win32' ? `${fileName}.7z` : `${fileName}.tar.gz`; : `node-v${version}-${osPlat}-${osArch}`;
const initialUrl = getNodejsDistUrl(versionSpec); let urlFileName = osPlat == 'win32' ? `${fileName}.7z` : `${fileName}.tar.gz`;
const url = `${initialUrl}/v${version}/${urlFileName}`; const initialUrl = getNodejsDistUrl(versionSpec);
return { const url = `${initialUrl}/v${version}/${urlFileName}`;
downloadUrl: url, return {
resolvedVersion: version, downloadUrl: url,
arch: arch, resolvedVersion: version,
fileName: fileName arch: arch,
}; fileName: fileName
}); };
} });
function resolveVersionFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os_1.default.arch()), manifest) { }
return __awaiter(this, void 0, void 0, function* () { function resolveVersionFromManifest(versionSpec, stable, auth, osArch = translateArchToDistUrl(os_1.default.arch()), manifest) {
try { return __awaiter(this, void 0, void 0, function* () {
const info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest); try {
return info === null || info === void 0 ? void 0 : info.resolvedVersion; const info = yield getInfoFromManifest(versionSpec, stable, auth, osArch, manifest);
} return info === null || info === void 0 ? void 0 : info.resolvedVersion;
catch (err) { }
core.info('Unable to resolve version from manifest...'); catch (err) {
core.debug(err.message); core.info('Unable to resolve version from manifest...');
} core.debug(err.message);
}); }
} });
function evaluateNightlyVersions(versions, versionSpec) { }
let version = ''; function evaluateNightlyVersions(versions, versionSpec) {
let range; let version = '';
const [raw, prerelease] = versionSpec.split('-'); let range;
const isValidVersion = semver.valid(raw); const [raw, prerelease] = versionSpec.split('-');
const rawVersion = isValidVersion ? raw : semver.coerce(raw); const isValidVersion = semver.valid(raw);
if (rawVersion) { const rawVersion = isValidVersion ? raw : semver.coerce(raw);
if (prerelease !== 'nightly') { if (rawVersion) {
range = `${rawVersion}-${prerelease.replace('nightly', 'nightly.')}`; if (prerelease !== 'nightly') {
} range = `${rawVersion}-${prerelease.replace('nightly', 'nightly.')}`;
else { }
range = `${semver.validRange(`^${rawVersion}-0`)}-0`; else {
} range = `${semver.validRange(`^${rawVersion}-0`)}-0`;
} }
if (range) { }
versions.sort(semver.rcompare); if (range) {
for (const currentVersion of versions) { versions.sort(semver.rcompare);
const satisfied = semver.satisfies(currentVersion.replace('-nightly', '-nightly.'), range, { includePrerelease: true }) && currentVersion.includes('nightly'); for (const currentVersion of versions) {
if (satisfied) { const satisfied = semver.satisfies(currentVersion.replace('-nightly', '-nightly.'), range, { includePrerelease: true }) && currentVersion.includes('nightly');
version = currentVersion; if (satisfied) {
break; version = currentVersion;
} break;
} }
} }
if (version) { }
core.debug(`matched: ${version}`); if (version) {
} core.debug(`matched: ${version}`);
else { }
core.debug('match not found'); else {
} core.debug('match not found');
return version; }
} return version;
// TODO - should we just export this from @actions/tool-cache? Lifted directly from there }
function evaluateVersions(versions, versionSpec) { // TODO - should we just export this from @actions/tool-cache? Lifted directly from there
let version = ''; function evaluateVersions(versions, versionSpec) {
core.debug(`evaluating ${versions.length} versions`); let version = '';
if (versionSpec.includes('nightly')) { core.debug(`evaluating ${versions.length} versions`);
return evaluateNightlyVersions(versions, versionSpec); if (versionSpec.includes('nightly')) {
} return evaluateNightlyVersions(versions, versionSpec);
versions = versions.sort(semver.rcompare); }
for (let i = versions.length - 1; i >= 0; i--) { versions = versions.sort(semver.rcompare);
const potential = versions[i]; for (let i = versions.length - 1; i >= 0; i--) {
const satisfied = semver.satisfies(potential, versionSpec); const potential = versions[i];
if (satisfied) { const satisfied = semver.satisfies(potential, versionSpec);
version = potential; if (satisfied) {
break; version = potential;
} break;
} }
if (version) { }
core.debug(`matched: ${version}`); if (version) {
} core.debug(`matched: ${version}`);
else { }
core.debug('match not found'); else {
} core.debug('match not found');
return version; }
} return version;
function getNodejsDistUrl(version) { }
const prerelease = semver.prerelease(version); function getNodejsDistUrl(version) {
if (version.includes('nightly')) { const prerelease = semver.prerelease(version);
return 'https://nodejs.org/download/nightly'; if (version.includes('nightly')) {
} return 'https://nodejs.org/download/nightly';
else if (prerelease) { }
return 'https://nodejs.org/download/rc'; else if (prerelease) {
} return 'https://nodejs.org/download/rc';
return 'https://nodejs.org/dist'; }
} return 'https://nodejs.org/dist';
exports.getNodejsDistUrl = getNodejsDistUrl; }
function queryDistForMatch(versionSpec, arch = os_1.default.arch(), nodeVersions) { exports.getNodejsDistUrl = getNodejsDistUrl;
return __awaiter(this, void 0, void 0, function* () { function queryDistForMatch(versionSpec, arch = os_1.default.arch(), nodeVersions) {
let osPlat = os_1.default.platform(); return __awaiter(this, void 0, void 0, function* () {
let osArch = translateArchToDistUrl(arch); let osPlat = os_1.default.platform();
// node offers a json list of versions let osArch = translateArchToDistUrl(arch);
let dataFileName; // node offers a json list of versions
switch (osPlat) { let dataFileName;
case 'linux': switch (osPlat) {
dataFileName = `linux-${osArch}`; case 'linux':
break; dataFileName = `linux-${osArch}`;
case 'darwin': break;
dataFileName = `osx-${osArch}-tar`; case 'darwin':
break; dataFileName = `osx-${osArch}-tar`;
case 'win32': break;
dataFileName = `win-${osArch}-exe`; case 'win32':
break; dataFileName = `win-${osArch}-exe`;
default: break;
throw new Error(`Unexpected OS '${osPlat}'`); default:
} throw new Error(`Unexpected OS '${osPlat}'`);
if (!nodeVersions) { }
core.debug('No dist manifest cached'); if (!nodeVersions) {
nodeVersions = yield getVersionsFromDist(versionSpec); core.debug('No dist manifest cached');
} nodeVersions = yield getVersionsFromDist(versionSpec);
let versions = []; }
if (isLatestSyntax(versionSpec)) { let versions = [];
core.info(`getting latest node version...`); if (isLatestSyntax(versionSpec)) {
return nodeVersions[0].version; core.info(`getting latest node version...`);
} return nodeVersions[0].version;
nodeVersions.forEach((nodeVersion) => { }
// ensure this version supports your os and platform nodeVersions.forEach((nodeVersion) => {
if (nodeVersion.files.indexOf(dataFileName) >= 0) { // ensure this version supports your os and platform
versions.push(nodeVersion.version); if (nodeVersion.files.indexOf(dataFileName) >= 0) {
} versions.push(nodeVersion.version);
}); }
// get the latest version that matches the version spec });
let version = evaluateVersions(versions, versionSpec); // get the latest version that matches the version spec
return version; let version = evaluateVersions(versions, versionSpec);
}); return version;
} });
function getVersionsFromDist(versionSpec) { }
return __awaiter(this, void 0, void 0, function* () { function getVersionsFromDist(versionSpec) {
const initialUrl = getNodejsDistUrl(versionSpec); return __awaiter(this, void 0, void 0, function* () {
const dataUrl = `${initialUrl}/index.json`; const initialUrl = getNodejsDistUrl(versionSpec);
let httpClient = new hc.HttpClient('setup-node', [], { const dataUrl = `${initialUrl}/index.json`;
allowRetries: true, let httpClient = new hc.HttpClient('setup-node', [], {
maxRetries: 3 allowRetries: true,
}); maxRetries: 3
let response = yield httpClient.getJson(dataUrl); });
return response.result || []; let response = yield httpClient.getJson(dataUrl);
}); return response.result || [];
} });
exports.getVersionsFromDist = getVersionsFromDist; }
// For non LTS versions of Node, the files we need (for Windows) are sometimes located exports.getVersionsFromDist = getVersionsFromDist;
// in a different folder than they normally are for other versions. // For non LTS versions of Node, the files we need (for Windows) are sometimes located
// Normally the format is similar to: https://nodejs.org/dist/v5.10.1/node-v5.10.1-win-x64.7z // in a different folder than they normally are for other versions.
// In this case, there will be two files located at: // Normally the format is similar to: https://nodejs.org/dist/v5.10.1/node-v5.10.1-win-x64.7z
// /dist/v5.10.1/win-x64/node.exe // In this case, there will be two files located at:
// /dist/v5.10.1/win-x64/node.lib // /dist/v5.10.1/win-x64/node.exe
// If this is not the structure, there may also be two files located at: // /dist/v5.10.1/win-x64/node.lib
// /dist/v0.12.18/node.exe // If this is not the structure, there may also be two files located at:
// /dist/v0.12.18/node.lib // /dist/v0.12.18/node.exe
// This method attempts to download and cache the resources from these alternative locations. // /dist/v0.12.18/node.lib
// Note also that the files are normally zipped but in this case they are just an exe // This method attempts to download and cache the resources from these alternative locations.
// and lib file in a folder, not zipped. // Note also that the files are normally zipped but in this case they are just an exe
function acquireNodeFromFallbackLocation(version, arch = os_1.default.arch()) { // and lib file in a folder, not zipped.
return __awaiter(this, void 0, void 0, function* () { function acquireNodeFromFallbackLocation(version, arch = os_1.default.arch()) {
const initialUrl = getNodejsDistUrl(version); return __awaiter(this, void 0, void 0, function* () {
let osPlat = os_1.default.platform(); const initialUrl = getNodejsDistUrl(version);
let osArch = translateArchToDistUrl(arch); let osPlat = os_1.default.platform();
// Create temporary folder to download in to let osArch = translateArchToDistUrl(arch);
const tempDownloadFolder = 'temp_' + Math.floor(Math.random() * 2000000000); // Create temporary folder to download in to
const tempDirectory = process.env['RUNNER_TEMP'] || ''; const tempDownloadFolder = 'temp_' + Math.floor(Math.random() * 2000000000);
assert.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined'); const tempDirectory = process.env['RUNNER_TEMP'] || '';
const tempDir = path.join(tempDirectory, tempDownloadFolder); assert.ok(tempDirectory, 'Expected RUNNER_TEMP to be defined');
yield io.mkdirP(tempDir); const tempDir = path.join(tempDirectory, tempDownloadFolder);
let exeUrl; yield io.mkdirP(tempDir);
let libUrl; let exeUrl;
try { let libUrl;
exeUrl = `${initialUrl}/v${version}/win-${osArch}/node.exe`; try {
libUrl = `${initialUrl}/v${version}/win-${osArch}/node.lib`; exeUrl = `${initialUrl}/v${version}/win-${osArch}/node.exe`;
core.info(`Downloading only node binary from ${exeUrl}`); libUrl = `${initialUrl}/v${version}/win-${osArch}/node.lib`;
const exePath = yield tc.downloadTool(exeUrl); core.info(`Downloading only node binary from ${exeUrl}`);
yield io.cp(exePath, path.join(tempDir, 'node.exe')); const exePath = yield tc.downloadTool(exeUrl);
const libPath = yield tc.downloadTool(libUrl); yield io.cp(exePath, path.join(tempDir, 'node.exe'));
yield io.cp(libPath, path.join(tempDir, 'node.lib')); const libPath = yield tc.downloadTool(libUrl);
} yield io.cp(libPath, path.join(tempDir, 'node.lib'));
catch (err) { }
if (err instanceof tc.HTTPError && err.httpStatusCode == 404) { catch (err) {
exeUrl = `${initialUrl}/v${version}/node.exe`; if (err instanceof tc.HTTPError && err.httpStatusCode == 404) {
libUrl = `${initialUrl}/v${version}/node.lib`; exeUrl = `${initialUrl}/v${version}/node.exe`;
const exePath = yield tc.downloadTool(exeUrl); libUrl = `${initialUrl}/v${version}/node.lib`;
yield io.cp(exePath, path.join(tempDir, 'node.exe')); const exePath = yield tc.downloadTool(exeUrl);
const libPath = yield tc.downloadTool(libUrl); yield io.cp(exePath, path.join(tempDir, 'node.exe'));
yield io.cp(libPath, path.join(tempDir, 'node.lib')); const libPath = yield tc.downloadTool(libUrl);
} yield io.cp(libPath, path.join(tempDir, 'node.lib'));
else { }
throw err; else {
} throw err;
} }
let toolPath = yield tc.cacheDir(tempDir, 'node', version, arch); }
core.addPath(toolPath); let toolPath = yield tc.cacheDir(tempDir, 'node', version, arch);
return toolPath; core.addPath(toolPath);
}); return toolPath;
} });
// os.arch does not always match the relative download url, e.g. }
// os.arch == 'arm' != node-v12.13.1-linux-armv7l.tar.gz // os.arch does not always match the relative download url, e.g.
// All other currently supported architectures match, e.g.: // os.arch == 'arm' != node-v12.13.1-linux-armv7l.tar.gz
// os.arch = arm64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-arm64.tar.gz // All other currently supported architectures match, e.g.:
// os.arch = x64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-x64.tar.gz // os.arch = arm64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-arm64.tar.gz
function translateArchToDistUrl(arch) { // os.arch = x64 => https://nodejs.org/dist/v{VERSION}/node-v{VERSION}-{OS}-x64.tar.gz
switch (arch) { function translateArchToDistUrl(arch) {
case 'arm': switch (arch) {
return 'armv7l'; case 'arm':
default: return 'armv7l';
return arch; default:
} return arch;
} }
function parseNodeVersionFile(contents) { }
var _a, _b, _c; function parseNodeVersionFile(contents) {
let nodeVersion; var _a, _b, _c;
// Try parsing the file as an NPM `package.json` file. let nodeVersion;
try { // Try parsing the file as an NPM `package.json` file.
nodeVersion = (_a = JSON.parse(contents).volta) === null || _a === void 0 ? void 0 : _a.node; try {
if (!nodeVersion) nodeVersion = (_a = JSON.parse(contents).volta) === null || _a === void 0 ? void 0 : _a.node;
nodeVersion = (_b = JSON.parse(contents).engines) === null || _b === void 0 ? void 0 : _b.node; if (!nodeVersion)
} nodeVersion = (_b = JSON.parse(contents).engines) === null || _b === void 0 ? void 0 : _b.node;
catch (_d) { }
core.info('Node version file is not JSON file'); catch (_d) {
} core.info('Node version file is not JSON file');
if (!nodeVersion) { }
const found = contents.match(/^(?:nodejs\s+)?v?(?<version>[^\s]+)$/m); if (!nodeVersion) {
nodeVersion = (_c = found === null || found === void 0 ? void 0 : found.groups) === null || _c === void 0 ? void 0 : _c.version; const found = contents.match(/^(?:nodejs\s+)?v?(?<version>[^\s]+)$/m);
} nodeVersion = (_c = found === null || found === void 0 ? void 0 : found.groups) === null || _c === void 0 ? void 0 : _c.version;
// In the case of an unknown format, }
// return as is and evaluate the version separately. // In the case of an unknown format,
if (!nodeVersion) // return as is and evaluate the version separately.
nodeVersion = contents.trim(); if (!nodeVersion)
return nodeVersion; nodeVersion = contents.trim();
} return nodeVersion;
exports.parseNodeVersionFile = parseNodeVersionFile; }
function isLatestSyntax(versionSpec) { exports.parseNodeVersionFile = parseNodeVersionFile;
return ['current', 'latest', 'node'].includes(versionSpec); function isLatestSyntax(versionSpec) {
} return ['current', 'latest', 'node'].includes(versionSpec);
}
function enableCorepack(input) {
return __awaiter(this, void 0, void 0, function* () {
let corepackArgs = ['enable'];
if (input.length > 0 && input !== 'false') {
if (input !== 'true') {
const packageManagers = input.split(' ');
if (!packageManagers.every(pm => ['npm', 'yarn', 'pnpm'].includes(pm))) {
throw new Error(`One or more of the specified package managers [ ${input} ] are not supported by corepack`);
}
corepackArgs.push(...packageManagers);
}
yield exec.getExecOutput('corepack', corepackArgs, {
ignoreReturnCode: true
});
}
});
}
exports.enableCorepack = enableCorepack;
/***/ }), /***/ }),
@ -73661,134 +73680,136 @@ function isLatestSyntax(versionSpec) {
/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) {
"use strict"; "use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) { return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next()); step((generator = generator.apply(thisArg, _arguments || [])).next());
}); });
}; };
var __importStar = (this && this.__importStar) || function (mod) { var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod; if (mod && mod.__esModule) return mod;
var result = {}; var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod; result["default"] = mod;
return result; return result;
}; };
var __importDefault = (this && this.__importDefault) || function (mod) { var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod }; return (mod && mod.__esModule) ? mod : { "default": mod };
}; };
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const core = __importStar(__nccwpck_require__(2186)); const core = __importStar(__nccwpck_require__(2186));
const exec = __importStar(__nccwpck_require__(1514)); const exec = __importStar(__nccwpck_require__(1514));
const installer = __importStar(__nccwpck_require__(2574)); const installer = __importStar(__nccwpck_require__(2574));
const fs_1 = __importDefault(__nccwpck_require__(7147)); const fs_1 = __importDefault(__nccwpck_require__(7147));
const auth = __importStar(__nccwpck_require__(7573)); const auth = __importStar(__nccwpck_require__(7573));
const path = __importStar(__nccwpck_require__(1017)); const path = __importStar(__nccwpck_require__(1017));
const cache_restore_1 = __nccwpck_require__(9517); const cache_restore_1 = __nccwpck_require__(9517);
const cache_utils_1 = __nccwpck_require__(1678); const cache_utils_1 = __nccwpck_require__(1678);
const os_1 = __importDefault(__nccwpck_require__(2037)); const os_1 = __importDefault(__nccwpck_require__(2037));
function run() { function run() {
return __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
try { try {
// //
// Version is optional. If supplied, install / use from the tool cache // Version is optional. If supplied, install / use from the tool cache
// If not supplied then task is still used to setup proxy, auth, etc... // If not supplied then task is still used to setup proxy, auth, etc...
// //
const version = resolveVersionInput(); const version = resolveVersionInput();
let arch = core.getInput('architecture'); let arch = core.getInput('architecture');
const cache = core.getInput('cache'); const cache = core.getInput('cache');
// if architecture supplied but node-version is not // if architecture supplied but node-version is not
// if we don't throw a warning, the already installed x64 node will be used which is not probably what user meant. // if we don't throw a warning, the already installed x64 node will be used which is not probably what user meant.
if (arch && !version) { if (arch && !version) {
core.warning('`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed. To fix this, provide `architecture` in combination with `node-version`'); core.warning('`architecture` is provided but `node-version` is missing. In this configuration, the version/architecture of Node will not be changed. To fix this, provide `architecture` in combination with `node-version`');
} }
if (!arch) { if (!arch) {
arch = os_1.default.arch(); arch = os_1.default.arch();
} }
if (version) { if (version) {
const token = core.getInput('token'); const token = core.getInput('token');
const auth = !token ? undefined : `token ${token}`; const auth = !token ? undefined : `token ${token}`;
const stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE'; const stable = (core.getInput('stable') || 'true').toUpperCase() === 'TRUE';
const checkLatest = (core.getInput('check-latest') || 'false').toUpperCase() === 'TRUE'; const checkLatest = (core.getInput('check-latest') || 'false').toUpperCase() === 'TRUE';
yield installer.getNode(version, stable, checkLatest, auth, arch); yield installer.getNode(version, stable, checkLatest, auth, arch);
} }
yield printEnvDetailsAndSetOutput(); yield printEnvDetailsAndSetOutput();
const registryUrl = core.getInput('registry-url'); const registryUrl = core.getInput('registry-url');
const alwaysAuth = core.getInput('always-auth'); const alwaysAuth = core.getInput('always-auth');
if (registryUrl) { if (registryUrl) {
auth.configAuthentication(registryUrl, alwaysAuth); auth.configAuthentication(registryUrl, alwaysAuth);
} }
if (cache && cache_utils_1.isCacheFeatureAvailable()) { const corepack = core.getInput('corepack') || 'false';
const cacheDependencyPath = core.getInput('cache-dependency-path'); yield installer.enableCorepack(corepack);
yield cache_restore_1.restoreCache(cache, cacheDependencyPath); if (cache && cache_utils_1.isCacheFeatureAvailable()) {
} const cacheDependencyPath = core.getInput('cache-dependency-path');
const matchersPath = path.join(__dirname, '../..', '.github'); yield cache_restore_1.restoreCache(cache, cacheDependencyPath);
core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`); }
core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}`); const matchersPath = path.join(__dirname, '../..', '.github');
core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-compact.json')}`); core.info(`##[add-matcher]${path.join(matchersPath, 'tsc.json')}`);
} core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-stylish.json')}`);
catch (err) { core.info(`##[add-matcher]${path.join(matchersPath, 'eslint-compact.json')}`);
core.setFailed(err.message); }
} catch (err) {
}); core.setFailed(err.message);
} }
exports.run = run; });
function resolveVersionInput() { }
let version = core.getInput('node-version'); exports.run = run;
const versionFileInput = core.getInput('node-version-file'); function resolveVersionInput() {
if (version && versionFileInput) { let version = core.getInput('node-version');
core.warning('Both node-version and node-version-file inputs are specified, only node-version will be used'); const versionFileInput = core.getInput('node-version-file');
} if (version && versionFileInput) {
if (version) { core.warning('Both node-version and node-version-file inputs are specified, only node-version will be used');
return version; }
} if (version) {
if (versionFileInput) { return version;
const versionFilePath = path.join(process.env.GITHUB_WORKSPACE, versionFileInput); }
if (!fs_1.default.existsSync(versionFilePath)) { if (versionFileInput) {
throw new Error(`The specified node version file at: ${versionFilePath} does not exist`); const versionFilePath = path.join(process.env.GITHUB_WORKSPACE, versionFileInput);
} if (!fs_1.default.existsSync(versionFilePath)) {
version = installer.parseNodeVersionFile(fs_1.default.readFileSync(versionFilePath, 'utf8')); throw new Error(`The specified node version file at: ${versionFilePath} does not exist`);
core.info(`Resolved ${versionFileInput} as ${version}`); }
} version = installer.parseNodeVersionFile(fs_1.default.readFileSync(versionFilePath, 'utf8'));
return version; core.info(`Resolved ${versionFileInput} as ${version}`);
} }
function printEnvDetailsAndSetOutput() { return version;
return __awaiter(this, void 0, void 0, function* () { }
core.startGroup('Environment details'); function printEnvDetailsAndSetOutput() {
const promises = ['node', 'npm', 'yarn'].map((tool) => __awaiter(this, void 0, void 0, function* () { return __awaiter(this, void 0, void 0, function* () {
const output = yield getToolVersion(tool, ['--version']); core.startGroup('Environment details');
if (tool === 'node') { const promises = ['node', 'npm', 'yarn'].map((tool) => __awaiter(this, void 0, void 0, function* () {
core.setOutput(`${tool}-version`, output); const output = yield getToolVersion(tool, ['--version']);
} if (tool === 'node') {
core.info(`${tool}: ${output}`); core.setOutput(`${tool}-version`, output);
})); }
yield Promise.all(promises); core.info(`${tool}: ${output}`);
core.endGroup(); }));
}); yield Promise.all(promises);
} core.endGroup();
exports.printEnvDetailsAndSetOutput = printEnvDetailsAndSetOutput; });
function getToolVersion(tool, options) { }
return __awaiter(this, void 0, void 0, function* () { exports.printEnvDetailsAndSetOutput = printEnvDetailsAndSetOutput;
try { function getToolVersion(tool, options) {
const { stdout, stderr, exitCode } = yield exec.getExecOutput(tool, options, { return __awaiter(this, void 0, void 0, function* () {
ignoreReturnCode: true, try {
silent: true const { stdout, stderr, exitCode } = yield exec.getExecOutput(tool, options, {
}); ignoreReturnCode: true,
if (exitCode > 0) { silent: true
core.warning(`[warning]${stderr}`); });
return ''; if (exitCode > 0) {
} core.warning(`[warning]${stderr}`);
return stdout.trim(); return '';
} }
catch (err) { return stdout.trim();
return ''; }
} catch (err) {
}); return '';
} }
});
}
/***/ }), /***/ }),
@ -74044,10 +74065,10 @@ var __webpack_exports__ = {};
(() => { (() => {
"use strict"; "use strict";
var exports = __webpack_exports__; var exports = __webpack_exports__;
Object.defineProperty(exports, "__esModule", ({ value: true })); Object.defineProperty(exports, "__esModule", ({ value: true }));
const main_1 = __nccwpck_require__(399); const main_1 = __nccwpck_require__(399);
main_1.run(); main_1.run();
})(); })();

View File

@ -358,3 +358,32 @@ NOTE: As per https://github.com/actions/setup-node/issues/49 you cannot use `sec
### always-auth input ### always-auth input
The always-auth input sets `always-auth=true` in .npmrc file. With this option set [npm](https://docs.npmjs.com/cli/v6/using-npm/config#always-auth)/yarn sends the authentication credentials when making a request to the registries. The always-auth input sets `always-auth=true` in .npmrc file. With this option set [npm](https://docs.npmjs.com/cli/v6/using-npm/config#always-auth)/yarn sends the authentication credentials when making a request to the registries.
## Enabling Corepack
You can enable [Corepack](https://github.com/nodejs/corepack) by using the `corepack` input. This will enable Corepack. You can then use `pnpm` and `yarn` commands in your project.
```yaml
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16.x'
corepack: true
- name: Install dependencies
run: yarn install --immutable
```
You can also pass package manager names instead if you want to enable corepack for specific package managers only.
```yaml
steps:
- uses: actions/checkout@v3
- uses: actions/setup-node@v3
with:
node-version: '16.x'
corepack: yarn pnpm
- name: Install dependencies
run: yarn install --immutable
```
This option by default is `false` as Corepack is still in experimental phase.

View File

@ -4,6 +4,7 @@ import * as core from '@actions/core';
import * as hc from '@actions/http-client'; import * as hc from '@actions/http-client';
import * as io from '@actions/io'; import * as io from '@actions/io';
import * as tc from '@actions/tool-cache'; import * as tc from '@actions/tool-cache';
import * as exec from '@actions/exec';
import * as path from 'path'; import * as path from 'path';
import * as semver from 'semver'; import * as semver from 'semver';
import fs from 'fs'; import fs from 'fs';
@ -604,3 +605,21 @@ export function parseNodeVersionFile(contents: string): string {
function isLatestSyntax(versionSpec): boolean { function isLatestSyntax(versionSpec): boolean {
return ['current', 'latest', 'node'].includes(versionSpec); return ['current', 'latest', 'node'].includes(versionSpec);
} }
export async function enableCorepack(input: string): Promise<void> {
let corepackArgs = ['enable'];
if (input.length > 0 && input !== 'false') {
if (input !== 'true') {
const packageManagers = input.split(' ');
if (!packageManagers.every(pm => ['npm', 'yarn', 'pnpm'].includes(pm))) {
throw new Error(
`One or more of the specified package managers [ ${input} ] are not supported by corepack`
);
}
corepackArgs.push(...packageManagers);
}
await exec.getExecOutput('corepack', corepackArgs, {
ignoreReturnCode: true
});
}
}

View File

@ -49,6 +49,9 @@ export async function run() {
auth.configAuthentication(registryUrl, alwaysAuth); auth.configAuthentication(registryUrl, alwaysAuth);
} }
const corepack = core.getInput('corepack') || 'false';
await installer.enableCorepack(corepack);
if (cache && isCacheFeatureAvailable()) { if (cache && isCacheFeatureAvailable()) {
const cacheDependencyPath = core.getInput('cache-dependency-path'); const cacheDependencyPath = core.getInput('cache-dependency-path');
await restoreCache(cache, cacheDependencyPath); await restoreCache(cache, cacheDependencyPath);