From 52c27b76dca84d4a3b80ffa6e9696d666a94a61f Mon Sep 17 00:00:00 2001 From: Marika Marszalkowski Date: Tue, 10 Sep 2024 18:32:53 +0200 Subject: [PATCH] use command --- .../changesets-fixed-version-bump/index.js | 8185 ++++++++--------- .../changesets-fixed-version-bump/index.ts | 4 +- 2 files changed, 4080 insertions(+), 4109 deletions(-) diff --git a/.github/actions/changesets-fixed-version-bump/index.js b/.github/actions/changesets-fixed-version-bump/index.js index 3d37e3354f..49be0069e6 100644 --- a/.github/actions/changesets-fixed-version-bump/index.js +++ b/.github/actions/changesets-fixed-version-bump/index.js @@ -1,80 +1,6 @@ /******/ (() => { // webpackBootstrap /******/ var __webpack_modules__ = ({ -/***/ 8865: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable jsdoc/require-jsdoc */ -const path_1 = __nccwpck_require__(71017); -const util_1 = __nccwpck_require__(76786); -const core_1 = __nccwpck_require__(37117); -const execa_1 = __importStar(__nccwpck_require__(30580)); -const git_1 = __nccwpck_require__(23321); -const util_2 = __nccwpck_require__(50914); -async function bump() { - // before bump - const version = await (0, util_2.getNextVersion)(); - process.env.NEXT_PACKAGE_VERSION = version; - const beforeBumpScript = (0, core_1.getInput)('before-bump'); - if (beforeBumpScript) { - (0, execa_1.command)(beforeBumpScript); - } - await updateRootPackageJson(version); - // TODO: what if I use pnpm? either pass the command or package manager? - (0, execa_1.default)('yarn changeset version'); - // after bump - const afterBumpScript = (0, core_1.getInput)('after-bump'); - if (afterBumpScript) { - (0, execa_1.command)(afterBumpScript); - } - await commitAndTag(version).catch(err => { - (0, core_1.error)(err); - process.exit(1); - }); -} -async function updateRootPackageJson(version) { - await (0, util_2.transformFile)((0, path_1.resolve)('package.json'), packageJson => (0, util_1.formatJson)({ - ...JSON.parse(packageJson), - version: `${version}` - })); -} -async function commitAndTag(version) { - const cwd = process.cwd(); - await (0, git_1.add)('-A', cwd); - await (0, git_1.commit)(`v${version}`, cwd); - await (0, git_1.tag)(`v${version}`, cwd); -} -bump(); - - -/***/ }), - /***/ 50914: /***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { @@ -90,7 +16,7 @@ exports.transformFile = transformFile; exports.getNextVersion = getNextVersion; const promises_1 = __nccwpck_require__(73292); const fs_1 = __nccwpck_require__(57147); -const get_release_plan_1 = __importDefault(__nccwpck_require__(69256)); +const get_release_plan_1 = __importDefault(__nccwpck_require__(49180)); const semver_1 = __nccwpck_require__(77546); function getPackageVersion(pathToRootPackageJson) { const packageJson = (0, fs_1.readFileSync)(pathToRootPackageJson || 'package.json', 'utf8'); @@ -128,4262 +54,4601 @@ async function getNextVersion() { /***/ }), -/***/ 29548: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 3624: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; + Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(22037)); -const utils_1 = __nccwpck_require__(87472); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } -} -function escapeData(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return utils_1.toCommandValue(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map -/***/ }), +var errors = __nccwpck_require__(76249); +var getDependentsGraph = __nccwpck_require__(54721); +var shouldSkipPackage = __nccwpck_require__(57193); +var semverParse = __nccwpck_require__(58257); +var semverGt = __nccwpck_require__(93473); +var semverSatisfies = __nccwpck_require__(81495); +var semverInc = __nccwpck_require__(25009); -/***/ 37117: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } -"use strict"; +var semverParse__default = /*#__PURE__*/_interopDefault(semverParse); +var semverGt__default = /*#__PURE__*/_interopDefault(semverGt); +var semverSatisfies__default = /*#__PURE__*/_interopDefault(semverSatisfies); +var semverInc__default = /*#__PURE__*/_interopDefault(semverInc); -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(29548); -const file_command_1 = __nccwpck_require__(92469); -const utils_1 = __nccwpck_require__(87472); -const os = __importStar(__nccwpck_require__(22037)); -const path = __importStar(__nccwpck_require__(71017)); -const oidc_utils_1 = __nccwpck_require__(65172); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = utils_1.toCommandValue(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); - } - command_1.issueCommand('set-env', { name }, convertedVal); + } else { + obj[key] = value; + } + + return obj; } -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - command_1.issueCommand('add-mask', {}, secret); + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; } -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - file_command_1.issueFileCommand('PATH', inputPath); + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - else { - command_1.issueCommand('add-path', {}, inputPath); + } + + return target; +} + +function getHighestReleaseType(releases) { + if (releases.length === 0) { + throw new Error(`Large internal Changesets error when calculating highest release type in the set of releases. Please contact the maintainers`); + } + + let highestReleaseType = "none"; + + for (let release of releases) { + switch (release.type) { + case "major": + return "major"; + + case "minor": + highestReleaseType = "minor"; + break; + + case "patch": + if (highestReleaseType === "none") { + highestReleaseType = "patch"; + } + + break; } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; + } + + return highestReleaseType; } -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); +function getCurrentHighestVersion(packageGroup, packagesByName) { + let highestVersion; + + for (let pkgName of packageGroup) { + let pkg = packagesByName.get(pkgName); + + if (!pkg) { + console.error(`FATAL ERROR IN CHANGESETS! We were unable to version for package group: ${pkgName} in package group: ${packageGroup.toString()}`); + throw new Error(`fatal: could not resolve linked packages`); } - if (options && options.trimWhitespace === false) { - return val; + + if (highestVersion === undefined || semverGt__default["default"](pkg.packageJson.version, highestVersion)) { + highestVersion = pkg.packageJson.version; } - return val.trim(); + } + + return highestVersion; } -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - if (options && options.trimWhitespace === false) { - return inputs; + +/* + WARNING: + Important note for understanding how this package works: + + We are doing some kind of wacky things with manipulating the objects within the + releases array, despite the fact that this was passed to us as an argument. We are + aware that this is generally bad practice, but have decided to to this here as + we control the entire flow of releases. + + We could solve this by inlining this function, or by returning a deep-cloned then + modified array, but we decided both of those are worse than this solution. +*/ + +function applyLinks(releases, packagesByName, linked) { + let updated = false; // We do this for each set of linked packages + + for (let linkedPackages of linked) { + // First we filter down to all the relevant releases for one set of linked packages + let releasingLinkedPackages = [...releases.values()].filter(release => linkedPackages.includes(release.name) && release.type !== "none"); // If we proceed any further we do extra work with calculating highestVersion for things that might + // not need one, as they only have workspace based packages + + if (releasingLinkedPackages.length === 0) continue; + let highestReleaseType = getHighestReleaseType(releasingLinkedPackages); + let highestVersion = getCurrentHighestVersion(linkedPackages, packagesByName); // Finally, we update the packages so all of them are on the highest version + + for (let linkedPackage of releasingLinkedPackages) { + if (linkedPackage.type !== highestReleaseType) { + updated = true; + linkedPackage.type = highestReleaseType; + } + + if (linkedPackage.oldVersion !== highestVersion) { + updated = true; + linkedPackage.oldVersion = highestVersion; + } } - return inputs.map(input => input.trim()); + } + + return updated; } -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); + +function incrementVersion(release, preInfo) { + if (release.type === "none") { + return release.oldVersion; + } + + let version = semverInc__default["default"](release.oldVersion, release.type); + + if (preInfo !== undefined && preInfo.state.mode !== "exit") { + let preVersion = preInfo.preVersions.get(release.name); + + if (preVersion === undefined) { + throw new errors.InternalError(`preVersion for ${release.name} does not exist when preState is defined`); + } // why are we adding this ourselves rather than passing 'pre' + versionType to semver.inc? + // because semver.inc with prereleases is confusing and this seems easier + + + version += `-${preInfo.state.tag}.${preVersion}`; + } + + return version; } -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - const filePath = process.env['GITHUB_OUTPUT'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + +/* + WARNING: + Important note for understanding how this package works: + + We are doing some kind of wacky things with manipulating the objects within the + releases array, despite the fact that this was passed to us as an argument. We are + aware that this is generally bad practice, but have decided to to this here as + we control the entire flow of releases. + + We could solve this by inlining this function, or by returning a deep-cloned then + modified array, but we decided both of those are worse than this solution. +*/ +function determineDependents({ + releases, + packagesByName, + dependencyGraph, + preInfo, + config +}) { + let updated = false; // NOTE this is intended to be called recursively + + let pkgsToSearch = [...releases.values()]; + + while (pkgsToSearch.length > 0) { + // nextRelease is our dependency, think of it as "avatar" + const nextRelease = pkgsToSearch.shift(); + if (!nextRelease) continue; // pkgDependents will be a list of packages that depend on nextRelease ie. ['avatar-group', 'comment'] + + const pkgDependents = dependencyGraph.get(nextRelease.name); + + if (!pkgDependents) { + throw new Error(`Error in determining dependents - could not find package in repository: ${nextRelease.name}`); } - process.stdout.write(os.EOL); - command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - command_1.issue('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - command_1.issueCommand('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - command_1.issue('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - command_1.issue('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); + + pkgDependents.map(dependent => { + let type; + const dependentPackage = packagesByName.get(dependent); + if (!dependentPackage) throw new Error("Dependency map is incorrect"); + + if (shouldSkipPackage.shouldSkipPackage(dependentPackage, { + ignore: config.ignore, + allowPrivatePackages: config.privatePackages.version + })) { + type = "none"; + } else { + const dependencyVersionRanges = getDependencyVersionRanges(dependentPackage.packageJson, nextRelease); + + for (const { + depType, + versionRange + } of dependencyVersionRanges) { + if (nextRelease.type === "none") { + continue; + } else if (shouldBumpMajor({ + dependent, + depType, + versionRange, + releases, + nextRelease, + preInfo, + onlyUpdatePeerDependentsWhenOutOfRange: config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.onlyUpdatePeerDependentsWhenOutOfRange + })) { + type = "major"; + } else if ((!releases.has(dependent) || releases.get(dependent).type === "none") && (config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.updateInternalDependents === "always" || !semverSatisfies__default["default"](incrementVersion(nextRelease, preInfo), versionRange))) { + switch (depType) { + case "dependencies": + case "optionalDependencies": + case "peerDependencies": + if (type !== "major" && type !== "minor") { + type = "patch"; + } + + break; + + case "devDependencies": + { + // We don't need a version bump if the package is only in the devDependencies of the dependent package + if (type !== "major" && type !== "minor" && type !== "patch") { + type = "none"; + } + } + } + } } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - const filePath = process.env['GITHUB_STATE'] || ''; - if (filePath) { - return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); - } - command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); + } + + if (releases.has(dependent) && releases.get(dependent).type === type) { + type = undefined; + } + + return { + name: dependent, + type, + pkgJSON: dependentPackage.packageJson + }; + }).filter(dependentItem => !!dependentItem.type).forEach(({ + name, + type, + pkgJSON + }) => { + // At this point, we know if we are making a change + updated = true; + const existing = releases.get(name); // For things that are being given a major bump, we check if we have already + // added them here. If we have, we update the existing item instead of pushing it on to search. + // It is safe to not add it to pkgsToSearch because it should have already been searched at the + // largest possible bump type. + + if (existing && type === "major" && existing.type !== "major") { + existing.type = "major"; + pkgsToSearch.push(existing); + } else { + let newDependent = { + name, + type, + oldVersion: pkgJSON.version, + changesets: [] + }; + pkgsToSearch.push(newDependent); + releases.set(name, newDependent); + } }); + } + + return updated; } -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(38452); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(38452); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(66890); -Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); -Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); -Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); -//# sourceMappingURL=core.js.map +/* + Returns an array of objects in the shape { depType: DependencyType, versionRange: string } + The array can contain more than one elements in case a dependency appears in multiple + dependency lists. For example, a package that is both a peerDepenency and a devDependency. +*/ -/***/ }), +function getDependencyVersionRanges(dependentPkgJSON, dependencyRelease) { + const DEPENDENCY_TYPES = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; + const dependencyVersionRanges = []; -/***/ 92469: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + for (const type of DEPENDENCY_TYPES) { + var _dependentPkgJSON$typ; -"use strict"; + const versionRange = (_dependentPkgJSON$typ = dependentPkgJSON[type]) === null || _dependentPkgJSON$typ === void 0 ? void 0 : _dependentPkgJSON$typ[dependencyRelease.name]; + if (!versionRange) continue; -// For internal use, subject to change. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const fs = __importStar(__nccwpck_require__(57147)); -const os = __importStar(__nccwpck_require__(22037)); -const uuid_1 = __nccwpck_require__(77041); -const utils_1 = __nccwpck_require__(87472); -function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); + if (versionRange.startsWith("workspace:")) { + dependencyVersionRanges.push({ + depType: type, + versionRange: // intentionally keep other workspace ranges untouched + // this has to be fixed but this should only be done when adding appropriate tests + versionRange === "workspace:*" ? // workspace:* actually means the current exact version, and not a wildcard similar to a reguler * range + dependencyRelease.oldVersion : versionRange.replace(/^workspace:/, "") + }); + } else { + dependencyVersionRanges.push({ + depType: type, + versionRange + }); } - fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { - encoding: 'utf8' - }); + } + + return dependencyVersionRanges; } -exports.issueFileCommand = issueFileCommand; -function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${uuid_1.v4()}`; - const convertedValue = utils_1.toCommandValue(value); - // These should realistically never happen, but just in case someone finds a - // way to exploit uuid generation let's not allow keys or values that contain - // the delimiter. - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; + +function shouldBumpMajor({ + dependent, + depType, + versionRange, + releases, + nextRelease, + preInfo, + onlyUpdatePeerDependentsWhenOutOfRange +}) { + // we check if it is a peerDependency because if it is, our dependent bump type might need to be major. + return depType === "peerDependencies" && nextRelease.type !== "none" && nextRelease.type !== "patch" && ( // 1. If onlyUpdatePeerDependentsWhenOutOfRange set to true, bump major if the version is leaving the range. + // 2. If onlyUpdatePeerDependentsWhenOutOfRange set to false, bump major regardless whether or not the version is leaving the range. + !onlyUpdatePeerDependentsWhenOutOfRange || !semverSatisfies__default["default"](incrementVersion(nextRelease, preInfo), versionRange)) && ( // bump major only if the dependent doesn't already has a major release. + !releases.has(dependent) || releases.has(dependent) && releases.get(dependent).type !== "major"); } -exports.prepareKeyValueMessage = prepareKeyValueMessage; -//# sourceMappingURL=file-command.js.map -/***/ }), +// This function takes in changesets and returns one release per +function flattenReleases(changesets, packagesByName, config) { + let releases = new Map(); + changesets.forEach(changeset => { + changeset.releases // Filter out skipped packages because they should not trigger a release + // If their dependencies need updates, they will be added to releases by `determineDependents()` with release type `none` + .filter(({ + name + }) => !shouldSkipPackage.shouldSkipPackage(packagesByName.get(name), { + ignore: config.ignore, + allowPrivatePackages: config.privatePackages.version + })).forEach(({ + name, + type + }) => { + let release = releases.get(name); + let pkg = packagesByName.get(name); -/***/ 65172: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + if (!pkg) { + throw new Error(`"${changeset.id}" changeset mentions a release for a package "${name}" but such a package could not be found.`); + } -"use strict"; + if (!release) { + release = { + name, + type, + oldVersion: pkg.packageJson.version, + changesets: [changeset.id] + }; + } else { + if (type === "major" || (release.type === "patch" || release.type === "none") && (type === "minor" || type === "patch")) { + release.type = type; + } // Check whether the bumpType will change + // If the bumpType has changed recalc newVersion + // push new changeset to releases -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); + + release.changesets.push(changeset.id); + } + + releases.set(name, release); }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(87301); -const auth_1 = __nccwpck_require__(99873); -const core_1 = __nccwpck_require__(37117); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); - } - return runtimeUrl; - } - static getCall(id_token_url) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; - }); - } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - core_1.debug(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - core_1.setSecret(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } - }); - } + }); + return releases; } -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map -/***/ }), +function matchFixedConstraint(releases, packagesByName, config) { + let updated = false; -/***/ 66890: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + for (let fixedPackages of config.fixed) { + let releasingFixedPackages = [...releases.values()].filter(release => fixedPackages.includes(release.name) && release.type !== "none"); + if (releasingFixedPackages.length === 0) continue; + let highestReleaseType = getHighestReleaseType(releasingFixedPackages); + let highestVersion = getCurrentHighestVersion(fixedPackages, packagesByName); // Finally, we update the packages so all of them are on the highest version -"use strict"; + for (let pkgName of fixedPackages) { + if (shouldSkipPackage.shouldSkipPackage(packagesByName.get(pkgName), { + ignore: config.ignore, + allowPrivatePackages: config.privatePackages.version + })) { + continue; + } -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(71017)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; -/** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. - * - * @param pth The path to platformize. - * @return string The platform-specific path. - */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); -} -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map - -/***/ }), - -/***/ 38452: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - -"use strict"; + let release = releases.get(pkgName); -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(22037); -const fs_1 = __nccwpck_require__(57147); -const { access, appendFile, writeFile } = fs_1.promises; -exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; -exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; -class Summary { - constructor() { - this._buffer = ''; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); + if (!release) { + updated = true; + releases.set(pkgName, { + name: pkgName, + type: highestReleaseType, + oldVersion: highestVersion, + changesets: [] }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); - } -} -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map - -/***/ }), - -/***/ 87472: -/***/ ((__unused_webpack_module, exports) => { + continue; + } -"use strict"; + if (release.type !== highestReleaseType) { + updated = true; + release.type = highestReleaseType; + } -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandProperties = exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -/** - * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 - */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; + if (release.oldVersion !== highestVersion) { + updated = true; + release.oldVersion = highestVersion; + } } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; + } + + return updated; } -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map -/***/ }), +function getPreVersion(version) { + let parsed = semverParse__default["default"](version); + let preVersion = parsed.prerelease[1] === undefined ? -1 : parsed.prerelease[1]; -/***/ 77041: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (typeof preVersion !== "number") { + throw new errors.InternalError("preVersion is not a number"); + } -"use strict"; + preVersion++; + return preVersion; +} +function getSnapshotSuffix(template, snapshotParameters) { + let snapshotRefDate = new Date(); + const placeholderValues = { + commit: snapshotParameters.commit, + tag: snapshotParameters.tag, + timestamp: snapshotRefDate.getTime().toString(), + datetime: snapshotRefDate.toISOString().replace(/\.\d{3}Z$/, "").replace(/[^\d]/g, "") + }; // We need a special handling because we need to handle a case where `--snapshot` is used without any template, + // and the resulting version needs to be composed without a tag. -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "NIL", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "version", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -Object.defineProperty(exports, "validate", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "stringify", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "parse", ({ - enumerable: true, - get: function () { - return _parse.default; + if (!template) { + return [placeholderValues.tag, placeholderValues.datetime].filter(Boolean).join("-"); } -})); -var _v = _interopRequireDefault(__nccwpck_require__(96415)); + const placeholders = Object.keys(placeholderValues); -var _v2 = _interopRequireDefault(__nccwpck_require__(45410)); + if (!template.includes(`{tag}`) && placeholderValues.tag !== undefined) { + throw new Error(`Failed to compose snapshot version: "{tag}" placeholder is missing, but the snapshot parameter is defined (value: '${placeholderValues.tag}')`); + } -var _v3 = _interopRequireDefault(__nccwpck_require__(24100)); + return placeholders.reduce((prev, key) => { + return prev.replace(new RegExp(`\\{${key}\\}`, "g"), () => { + const value = placeholderValues[key]; -var _v4 = _interopRequireDefault(__nccwpck_require__(2796)); + if (value === undefined) { + throw new Error(`Failed to compose snapshot version: "{${key}}" placeholder is used without having a value defined!`); + } -var _nil = _interopRequireDefault(__nccwpck_require__(79259)); + return value; + }); + }, template); +} -var _version = _interopRequireDefault(__nccwpck_require__(44056)); +function getSnapshotVersion(release, preInfo, useCalculatedVersion, snapshotSuffix) { + if (release.type === "none") { + return release.oldVersion; + } + /** + * Using version as 0.0.0 so that it does not hinder with other version release + * For example; + * if user has a regular pre-release at 1.0.0-beta.0 and then you had a snapshot pre-release at 1.0.0-canary-git-hash + * and a consumer is using the range ^1.0.0-beta, most people would expect that range to resolve to 1.0.0-beta.0 + * but it'll actually resolve to 1.0.0-canary-hash. Using 0.0.0 solves this problem because it won't conflict with other versions. + * + * You can set `snapshot.useCalculatedVersion` flag to true to use calculated versions if you don't care about the above problem. + */ -var _validate = _interopRequireDefault(__nccwpck_require__(3705)); -var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); + const baseVersion = useCalculatedVersion ? incrementVersion(release, preInfo) : `0.0.0`; + return `${baseVersion}-${snapshotSuffix}`; +} -var _parse = _interopRequireDefault(__nccwpck_require__(75670)); +function getNewVersion(release, preInfo) { + if (release.type === "none") { + return release.oldVersion; + } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + return incrementVersion(release, preInfo); +} -/***/ }), - -/***/ 57627: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function assembleReleasePlan(changesets, packages, config, // intentionally not using an optional parameter here so the result of `readPreState` has to be passed in here +preState, // snapshot: undefined -> not using snaphot +// snapshot: { tag: undefined } -> --snapshot (empty tag) +// snapshot: { tag: "canary" } -> --snapshot canary +snapshot) { + // TODO: remove `refined*` in the next major version of this package + // just use `config` and `snapshot` parameters directly, typed as: `config: Config, snapshot?: SnapshotReleaseParameters` + const refinedConfig = config.snapshot ? config : _objectSpread2(_objectSpread2({}, config), {}, { + snapshot: { + prereleaseTemplate: null, + useCalculatedVersion: config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.useCalculatedVersionForSnapshots + } + }); + const refinedSnapshot = typeof snapshot === "string" ? { + tag: snapshot + } : typeof snapshot === "boolean" ? { + tag: undefined + } : snapshot; + let packagesByName = new Map(packages.packages.map(x => [x.packageJson.name, x])); + const relevantChangesets = getRelevantChangesets(changesets, packagesByName, refinedConfig, preState); + const preInfo = getPreInfo(changesets, packagesByName, refinedConfig, preState); // releases is, at this point a list of all packages we are going to releases, + // flattened down to one release per package, having a reference back to their + // changesets, and with a calculated new versions -"use strict"; + let releases = flattenReleases(relevantChangesets, packagesByName, refinedConfig); + let dependencyGraph = getDependentsGraph.getDependentsGraph(packages, { + bumpVersionsWithWorkspaceProtocolOnly: refinedConfig.bumpVersionsWithWorkspaceProtocolOnly + }); + let releasesValidated = false; + while (releasesValidated === false) { + // The map passed in to determineDependents will be mutated + let dependentAdded = determineDependents({ + releases, + packagesByName, + dependencyGraph, + preInfo, + config: refinedConfig + }); // `releases` might get mutated here -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + let fixedConstraintUpdated = matchFixedConstraint(releases, packagesByName, refinedConfig); + let linksUpdated = applyLinks(releases, packagesByName, refinedConfig.linked); + releasesValidated = !linksUpdated && !dependentAdded && !fixedConstraintUpdated; + } -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); + if ((preInfo === null || preInfo === void 0 ? void 0 : preInfo.state.mode) === "exit") { + for (let pkg of packages.packages) { + // If a package had a prerelease, but didn't trigger a version bump in the regular release, + // we want to give it a patch release. + // Detailed explanation at https://github.com/changesets/changesets/pull/382#discussion_r434434182 + if (preInfo.preVersions.get(pkg.packageJson.name) !== 0) { + const existingRelease = releases.get(pkg.packageJson.name); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (!existingRelease) { + releases.set(pkg.packageJson.name, { + name: pkg.packageJson.name, + type: "patch", + oldVersion: pkg.packageJson.version, + changesets: [] + }); + } else if (existingRelease.type === "none" && !shouldSkipPackage.shouldSkipPackage(pkg, { + ignore: refinedConfig.ignore, + allowPrivatePackages: refinedConfig.privatePackages.version + })) { + existingRelease.type = "patch"; + } + } + } + } // Caching the snapshot version here and use this if it is snapshot release -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _crypto.default.createHash('md5').update(bytes).digest(); + const snapshotSuffix = refinedSnapshot && getSnapshotSuffix(refinedConfig.snapshot.prereleaseTemplate, refinedSnapshot); + return { + changesets: relevantChangesets, + releases: [...releases.values()].map(incompleteRelease => { + return _objectSpread2(_objectSpread2({}, incompleteRelease), {}, { + newVersion: snapshotSuffix ? getSnapshotVersion(incompleteRelease, preInfo, refinedConfig.snapshot.useCalculatedVersion, snapshotSuffix) : getNewVersion(incompleteRelease, preInfo) + }); + }), + preState: preInfo === null || preInfo === void 0 ? void 0 : preInfo.state + }; } -var _default = md5; -exports["default"] = _default; +function getRelevantChangesets(changesets, packagesByName, config, preState) { + for (const changeset of changesets) { + // Using the following 2 arrays to decide whether a changeset + // contains both skipped and not skipped packages + const skippedPackages = []; + const notSkippedPackages = []; -/***/ }), + for (const release of changeset.releases) { + if (shouldSkipPackage.shouldSkipPackage(packagesByName.get(release.name), { + ignore: config.ignore, + allowPrivatePackages: config.privatePackages.version + })) { + skippedPackages.push(release.name); + } else { + notSkippedPackages.push(release.name); + } + } -/***/ 79259: -/***/ ((__unused_webpack_module, exports) => { + if (skippedPackages.length > 0 && notSkippedPackages.length > 0) { + throw new Error(`Found mixed changeset ${changeset.id}\n` + `Found ignored packages: ${skippedPackages.join(" ")}\n` + `Found not ignored packages: ${notSkippedPackages.join(" ")}\n` + "Mixed changesets that contain both ignored and not ignored packages are not allowed"); + } + } -"use strict"; + if (preState && preState.mode !== "exit") { + let usedChangesetIds = new Set(preState.changesets); + return changesets.filter(changeset => !usedChangesetIds.has(changeset.id)); + } + return changesets; +} -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = '00000000-0000-0000-0000-000000000000'; -exports["default"] = _default; +function getHighestPreVersion(packageGroup, packagesByName) { + let highestPreVersion = 0; -/***/ }), + for (let pkg of packageGroup) { + highestPreVersion = Math.max(getPreVersion(packagesByName.get(pkg).packageJson.version), highestPreVersion); + } -/***/ 75670: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return highestPreVersion; +} -"use strict"; +function getPreInfo(changesets, packagesByName, config, preState) { + if (preState === undefined) { + return; + } + let updatedPreState = _objectSpread2(_objectSpread2({}, preState), {}, { + changesets: changesets.map(changeset => changeset.id), + initialVersions: _objectSpread2({}, preState.initialVersions) + }); -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + for (const [, pkg] of packagesByName) { + if (updatedPreState.initialVersions[pkg.packageJson.name] === undefined) { + updatedPreState.initialVersions[pkg.packageJson.name] = pkg.packageJson.version; + } + } // Populate preVersion + // preVersion is the map between package name and its next pre version number. -var _validate = _interopRequireDefault(__nccwpck_require__(3705)); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + let preVersions = new Map(); -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); + for (const [, pkg] of packagesByName) { + preVersions.set(pkg.packageJson.name, getPreVersion(pkg.packageJson.version)); } - let v; - const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; // Parse ........-####-....-....-............ + for (let fixedGroup of config.fixed) { + let highestPreVersion = getHighestPreVersion(fixedGroup, packagesByName); - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; // Parse ........-....-####-....-............ + for (let fixedPackage of fixedGroup) { + preVersions.set(fixedPackage, highestPreVersion); + } + } - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; // Parse ........-....-....-####-............ + for (let linkedGroup of config.linked) { + let highestPreVersion = getHighestPreVersion(linkedGroup, packagesByName); - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + for (let linkedPackage of linkedGroup) { + preVersions.set(linkedPackage, highestPreVersion); + } + } - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; + return { + state: updatedPreState, + preVersions + }; } -var _default = parse; -exports["default"] = _default; - -/***/ }), - -/***/ 31315: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - +exports["default"] = assembleReleasePlan; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; -exports["default"] = _default; /***/ }), -/***/ 20397: +/***/ 37168: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; - -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate +Object.defineProperty(exports, "__esModule", ({ value: true })); -let poolPtr = rnds8Pool.length; +var fs = __nccwpck_require__(41621); +var path = __nccwpck_require__(71017); +var micromatch = __nccwpck_require__(39015); +var errors = __nccwpck_require__(76249); +var logger = __nccwpck_require__(11376); +var getDependentsGraph = __nccwpck_require__(54721); -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _crypto.default.randomFillSync(rnds8Pool); +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } - poolPtr = 0; +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); } - - return rnds8Pool.slice(poolPtr, poolPtr += 16); + n["default"] = e; + return Object.freeze(n); } -/***/ }), - -/***/ 88224: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; +var fs__namespace = /*#__PURE__*/_interopNamespace(fs); +var path__default = /*#__PURE__*/_interopDefault(path); +var micromatch__default = /*#__PURE__*/_interopDefault(micromatch); +var packageJson = { + name: "@changesets/config", + version: "3.0.3", + description: "Utilities for reading and parsing Changeset's config", + main: "dist/changesets-config.cjs.js", + module: "dist/changesets-config.esm.js", + exports: { + ".": { + types: { + "import": "./dist/changesets-config.cjs.mjs", + "default": "./dist/changesets-config.cjs.js" + }, + module: "./dist/changesets-config.esm.js", + "import": "./dist/changesets-config.cjs.mjs", + "default": "./dist/changesets-config.cjs.js" + }, + "./package.json": "./package.json" + }, + license: "MIT", + repository: "https://github.com/changesets/changesets/tree/main/packages/config", + files: [ + "dist", + "schema.json" + ], + dependencies: { + "@changesets/errors": "^0.2.0", + "@changesets/get-dependents-graph": "^2.1.2", + "@changesets/logger": "^0.1.1", + "@changesets/types": "^6.0.0", + "@manypkg/get-packages": "^1.1.3", + "fs-extra": "^7.0.1", + micromatch: "^4.0.2" + }, + devDependencies: { + "@changesets/test-utils": "*", + "@types/micromatch": "^4.0.1", + "jest-in-case": "^1.0.2", + outdent: "^0.5.0" + } +}; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +let defaultWrittenConfig = { + $schema: `https://unpkg.com/@changesets/config@${packageJson.version}/schema.json`, + changelog: "@changesets/cli/changelog", + commit: false, + fixed: [], + linked: [], + access: "restricted", + baseBranch: "master", + updateInternalDependencies: "patch", + ignore: [] +}; -var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); +function flatten(arr) { + return [].concat(...arr); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function getNormalizedChangelogOption(thing) { + if (thing === false) { + return false; + } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); + if (typeof thing === "string") { + return [thing, null]; } - return _crypto.default.createHash('sha1').update(bytes).digest(); + return thing; } -var _default = sha1; -exports["default"] = _default; - -/***/ }), - -/***/ 13538: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function getNormalizedCommitOption(thing) { + if (thing === false) { + return false; + } -"use strict"; + if (thing === true) { + return ["@changesets/cli/commit", { + skipCI: "version" + }]; + } + if (typeof thing === "string") { + return [thing, null]; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + return thing; +} -var _validate = _interopRequireDefault(__nccwpck_require__(3705)); +function getUnmatchedPatterns(listOfPackageNamesOrGlob, pkgNames) { + return listOfPackageNamesOrGlob.filter(pkgNameOrGlob => !pkgNames.some(pkgName => micromatch__default["default"].isMatch(pkgName, pkgNameOrGlob))); +} -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const havePackageGroupsCorrectShape = pkgGroups => { + return isArray(pkgGroups) && pkgGroups.every(arr => isArray(arr) && arr.every(pkgName => typeof pkgName === "string")); +}; // TODO: it might be possible to remove this if improvements to `Array.isArray` ever land +// related thread: github.com/microsoft/TypeScript/issues/36554 -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).substr(1)); +function isArray(arg) { + return Array.isArray(arg); } -function stringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields +let read = async (cwd, packages) => { + let json = await fs__namespace.readJSON(path__default["default"].join(cwd, ".changeset", "config.json")); + return parse(json, packages); +}; +let parse = (json, packages) => { + var _json$changedFilePatt, _json$snapshot$prerel, _json$snapshot, _json$snapshot2, _json$___experimental, _json$___experimental2, _json$___experimental3, _json$___experimental4, _json$privatePackages, _json$privatePackages2; - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); + let messages = []; + let pkgNames = packages.packages.map(({ + packageJson + }) => packageJson.name); + + if (json.changelog !== undefined && json.changelog !== false && typeof json.changelog !== "string" && !(isArray(json.changelog) && json.changelog.length === 2 && typeof json.changelog[0] === "string")) { + messages.push(`The \`changelog\` option is set as ${JSON.stringify(json.changelog, null, 2)} when the only valid values are undefined, false, a module path(e.g. "@changesets/cli/changelog" or "./some-module") or a tuple with a module path and config for the changelog generator(e.g. ["@changesets/cli/changelog", { someOption: true }])`); } - return uuid; -} + let normalizedAccess = json.access; -var _default = stringify; -exports["default"] = _default; + if (json.access === "private") { + normalizedAccess = "restricted"; + logger.warn('The `access` option is set as "private", but this is actually not a valid value - the correct form is "restricted".'); + } -/***/ }), + if (normalizedAccess !== undefined && normalizedAccess !== "restricted" && normalizedAccess !== "public") { + messages.push(`The \`access\` option is set as ${JSON.stringify(normalizedAccess, null, 2)} when the only valid values are undefined, "public" or "restricted"`); + } -/***/ 96415: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (json.commit !== undefined && typeof json.commit !== "boolean" && typeof json.commit !== "string" && !(isArray(json.commit) && json.commit.length === 2 && typeof json.commit[0] === "string")) { + messages.push(`The \`commit\` option is set as ${JSON.stringify(json.commit, null, 2)} when the only valid values are undefined or a boolean or a module path (e.g. "@changesets/cli/commit" or "./some-module") or a tuple with a module path and config for the commit message generator (e.g. ["@changesets/cli/commit", { "skipCI": "version" }])`); + } -"use strict"; + if (json.baseBranch !== undefined && typeof json.baseBranch !== "string") { + messages.push(`The \`baseBranch\` option is set as ${JSON.stringify(json.baseBranch, null, 2)} but the \`baseBranch\` option can only be set as a string`); + } + if (json.changedFilePatterns !== undefined && (!isArray(json.changedFilePatterns) || !json.changedFilePatterns.every(pattern => typeof pattern === "string"))) { + messages.push(`The \`changedFilePatterns\` option is set as ${JSON.stringify(json.changedFilePatterns, null, 2)} but the \`changedFilePatterns\` option can only be set as an array of strings`); + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; + let fixed = []; -var _rng = _interopRequireDefault(__nccwpck_require__(20397)); + if (json.fixed !== undefined) { + if (!havePackageGroupsCorrectShape(json.fixed)) { + messages.push(`The \`fixed\` option is set as ${JSON.stringify(json.fixed, null, 2)} when the only valid values are undefined or an array of arrays of package names`); + } else { + let foundPkgNames = new Set(); + let duplicatedPkgNames = new Set(); -var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); + for (let fixedGroup of json.fixed) { + messages.push(...getUnmatchedPatterns(fixedGroup, pkgNames).map(pkgOrGlob => `The package or glob expression "${pkgOrGlob}" specified in the \`fixed\` option does not match any package in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.`)); + let expandedFixedGroup = micromatch__default["default"](pkgNames, fixedGroup); + fixed.push(expandedFixedGroup); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + for (let fixedPkgName of expandedFixedGroup) { + if (foundPkgNames.has(fixedPkgName)) { + duplicatedPkgNames.add(fixedPkgName); + } -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html -let _nodeId; + foundPkgNames.add(fixedPkgName); + } + } -let _clockseq; // Previous uuid creation time + if (duplicatedPkgNames.size) { + duplicatedPkgNames.forEach(pkgName => { + messages.push(`The package "${pkgName}" is defined in multiple sets of fixed packages. Packages can only be defined in a single set of fixed packages. If you are using glob expressions, make sure that they are valid according to https://www.npmjs.com/package/micromatch.`); + }); + } + } + } + let linked = []; -let _lastMSecs = 0; -let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + if (json.linked !== undefined) { + if (!havePackageGroupsCorrectShape(json.linked)) { + messages.push(`The \`linked\` option is set as ${JSON.stringify(json.linked, null, 2)} when the only valid values are undefined or an array of arrays of package names`); + } else { + let foundPkgNames = new Set(); + let duplicatedPkgNames = new Set(); -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node || _nodeId; - let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not - // specified. We do this lazily to minimize issues related to insufficient - // system entropy. See #189 + for (let linkedGroup of json.linked) { + messages.push(...getUnmatchedPatterns(linkedGroup, pkgNames).map(pkgOrGlob => `The package or glob expression "${pkgOrGlob}" specified in the \`linked\` option does not match any package in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.`)); + let expandedLinkedGroup = micromatch__default["default"](pkgNames, linkedGroup); + linked.push(expandedLinkedGroup); - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); + for (let linkedPkgName of expandedLinkedGroup) { + if (foundPkgNames.has(linkedPkgName)) { + duplicatedPkgNames.add(linkedPkgName); + } - if (node == null) { - // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) - node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + foundPkgNames.add(linkedPkgName); + } + } + + if (duplicatedPkgNames.size) { + duplicatedPkgNames.forEach(pkgName => { + messages.push(`The package "${pkgName}" is defined in multiple sets of linked packages. Packages can only be defined in a single set of linked packages. If you are using glob expressions, make sure that they are valid according to https://www.npmjs.com/package/micromatch.`); + }); + } } + } - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + const allFixedPackages = new Set(flatten(fixed)); + const allLinkedPackages = new Set(flatten(linked)); + allFixedPackages.forEach(pkgName => { + if (allLinkedPackages.has(pkgName)) { + messages.push(`The package "${pkgName}" can be found in both fixed and linked groups. A package can only be either fixed or linked.`); } - } // UUID timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so - // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - + }); - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock + if (json.updateInternalDependencies !== undefined && !["patch", "minor"].includes(json.updateInternalDependencies)) { + messages.push(`The \`updateInternalDependencies\` option is set as ${JSON.stringify(json.updateInternalDependencies, null, 2)} but can only be 'patch' or 'minor'`); + } - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) + if (json.ignore) { + if (!(isArray(json.ignore) && json.ignore.every(pkgName => typeof pkgName === "string"))) { + messages.push(`The \`ignore\` option is set as ${JSON.stringify(json.ignore, null, 2)} when the only valid values are undefined or an array of package names`); + } else { + messages.push(...getUnmatchedPatterns(json.ignore, pkgNames).map(pkgOrGlob => `The package or glob expression "${pkgOrGlob}" is specified in the \`ignore\` option but it is not found in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.`)); // Validate that all dependents of ignored packages are listed in the ignore list - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression + const dependentsGraph = getDependentsGraph.getDependentsGraph(packages); - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval + for (const ignoredPackage of json.ignore) { + const dependents = dependentsGraph.get(ignoredPackage) || []; + for (const dependent of dependents) { + if (!json.ignore.includes(dependent)) { + messages.push(`The package "${dependent}" depends on the ignored package "${ignoredPackage}", but "${dependent}" is not being ignored. Please add "${dependent}" to the \`ignore\` option.`); + } + } + } + } + } - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } // Per 4.2.1.2 Throw error if too many uuids are requested + const { + snapshot + } = json; + if (snapshot !== undefined) { + if (snapshot.useCalculatedVersion !== undefined && typeof snapshot.useCalculatedVersion !== "boolean") { + messages.push(`The \`snapshot.useCalculatedVersion\` option is set as ${JSON.stringify(snapshot.useCalculatedVersion, null, 2)} when the only valid values are undefined or a boolean`); + } - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + if (snapshot.prereleaseTemplate !== undefined && typeof snapshot.prereleaseTemplate !== "string") { + messages.push(`The \`snapshot.prereleaseTemplate\` option is set as ${JSON.stringify(snapshot.prereleaseTemplate, null, 2)} when the only valid values are undefined, or a template string.`); + } } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + if (json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH !== undefined) { + const { + onlyUpdatePeerDependentsWhenOutOfRange, + updateInternalDependents, + useCalculatedVersionForSnapshots + } = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH; - msecs += 12219292800000; // `time_low` + if (onlyUpdatePeerDependentsWhenOutOfRange !== undefined && typeof onlyUpdatePeerDependentsWhenOutOfRange !== "boolean") { + messages.push(`The \`onlyUpdatePeerDependentsWhenOutOfRange\` option is set as ${JSON.stringify(onlyUpdatePeerDependentsWhenOutOfRange, null, 2)} when the only valid values are undefined or a boolean`); + } - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; // `time_mid` + if (updateInternalDependents !== undefined && !["always", "out-of-range"].includes(updateInternalDependents)) { + messages.push(`The \`updateInternalDependents\` option is set as ${JSON.stringify(updateInternalDependents, null, 2)} but can only be 'always' or 'out-of-range'`); + } - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; // `time_high_and_version` + if (useCalculatedVersionForSnapshots && useCalculatedVersionForSnapshots !== undefined) { + console.warn(`Experimental flag "useCalculatedVersionForSnapshots" is deprecated since snapshot feature became stable. Please use "snapshot.useCalculatedVersion" instead.`); - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + if (typeof useCalculatedVersionForSnapshots !== "boolean") { + messages.push(`The \`useCalculatedVersionForSnapshots\` option is set as ${JSON.stringify(useCalculatedVersionForSnapshots, null, 2)} when the only valid values are undefined or a boolean`); + } + } + } - b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + if (messages.length) { + throw new errors.ValidationError(`Some errors occurred when validating the changesets config:\n` + messages.join("\n")); + } - b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + let config = { + changelog: getNormalizedChangelogOption(json.changelog === undefined ? defaultWrittenConfig.changelog : json.changelog), + access: normalizedAccess === undefined ? defaultWrittenConfig.access : normalizedAccess, + commit: getNormalizedCommitOption(json.commit === undefined ? defaultWrittenConfig.commit : json.commit), + fixed, + linked, + baseBranch: json.baseBranch === undefined ? defaultWrittenConfig.baseBranch : json.baseBranch, + changedFilePatterns: (_json$changedFilePatt = json.changedFilePatterns) !== null && _json$changedFilePatt !== void 0 ? _json$changedFilePatt : ["**"], + updateInternalDependencies: json.updateInternalDependencies === undefined ? defaultWrittenConfig.updateInternalDependencies : json.updateInternalDependencies, + ignore: json.ignore === undefined ? defaultWrittenConfig.ignore : micromatch__default["default"](pkgNames, json.ignore), + bumpVersionsWithWorkspaceProtocolOnly: json.bumpVersionsWithWorkspaceProtocolOnly === true, + snapshot: { + prereleaseTemplate: (_json$snapshot$prerel = (_json$snapshot = json.snapshot) === null || _json$snapshot === void 0 ? void 0 : _json$snapshot.prereleaseTemplate) !== null && _json$snapshot$prerel !== void 0 ? _json$snapshot$prerel : null, + useCalculatedVersion: ((_json$snapshot2 = json.snapshot) === null || _json$snapshot2 === void 0 ? void 0 : _json$snapshot2.useCalculatedVersion) !== undefined ? json.snapshot.useCalculatedVersion : ((_json$___experimental = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH) === null || _json$___experimental === void 0 ? void 0 : _json$___experimental.useCalculatedVersionForSnapshots) !== undefined ? (_json$___experimental2 = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH) === null || _json$___experimental2 === void 0 ? void 0 : _json$___experimental2.useCalculatedVersionForSnapshots : false + }, + ___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH: { + onlyUpdatePeerDependentsWhenOutOfRange: json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH === undefined || json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.onlyUpdatePeerDependentsWhenOutOfRange === undefined ? false : json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.onlyUpdatePeerDependentsWhenOutOfRange, + updateInternalDependents: (_json$___experimental3 = (_json$___experimental4 = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH) === null || _json$___experimental4 === void 0 ? void 0 : _json$___experimental4.updateInternalDependents) !== null && _json$___experimental3 !== void 0 ? _json$___experimental3 : "out-of-range" + }, + // TODO consider enabling this by default in the next major version + privatePackages: json.privatePackages === false ? { + tag: false, + version: false + } : json.privatePackages ? { + version: (_json$privatePackages = json.privatePackages.version) !== null && _json$privatePackages !== void 0 ? _json$privatePackages : true, + tag: (_json$privatePackages2 = json.privatePackages.tag) !== null && _json$privatePackages2 !== void 0 ? _json$privatePackages2 : false + } : { + version: true, + tag: false + } + }; - b[i++] = clockseq & 0xff; // `node` + if (config.privatePackages.version === false && config.privatePackages.tag === true) { + throw new errors.ValidationError(`The \`privatePackages.tag\` option is set to \`true\` but \`privatePackages.version\` is set to \`false\`. This is not allowed.`); + } - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; + return config; +}; +let fakePackage = { + dir: "", + packageJson: { + name: "", + version: "" } +}; +let defaultConfig = parse(defaultWrittenConfig, { + root: fakePackage, + tool: "root", + packages: [fakePackage] +}); - return buf || (0, _stringify.default)(b); -} +exports.defaultConfig = defaultConfig; +exports.defaultWrittenConfig = defaultWrittenConfig; +exports.parse = parse; +exports.read = read; -var _default = v1; -exports["default"] = _default; /***/ }), -/***/ 45410: +/***/ 54721: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); -var _v = _interopRequireDefault(__nccwpck_require__(42504)); +var Range = __nccwpck_require__(25287); +var pc = __nccwpck_require__(88276); -var _md = _interopRequireDefault(__nccwpck_require__(57627)); +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var Range__default = /*#__PURE__*/_interopDefault(Range); +var pc__default = /*#__PURE__*/_interopDefault(pc); -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = v3; -exports["default"] = _default; +// This is a modified version of the graph-getting in bolt +const DEPENDENCY_TYPES = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; -/***/ }), +const getAllDependencies = (config, ignoreDevDependencies) => { + const allDependencies = new Map(); -/***/ 42504: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (const type of DEPENDENCY_TYPES) { + const deps = config[type]; + if (!deps) continue; -"use strict"; + for (const name of Object.keys(deps)) { + const depRange = deps[name]; + if (type === "devDependencies" && (ignoreDevDependencies || depRange.startsWith("link:") || depRange.startsWith("file:"))) { + continue; + } -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = _default; -exports.URL = exports.DNS = void 0; + allDependencies.set(name, depRange); + } + } -var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); + return allDependencies; +}; -var _parse = _interopRequireDefault(__nccwpck_require__(75670)); +const isProtocolRange = range => range.indexOf(":") !== -1; -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const getValidRange = potentialRange => { + if (isProtocolRange(potentialRange)) { + return null; + } -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape + try { + return new Range__default["default"](potentialRange); + } catch (_unused) { + return null; + } +}; - const bytes = []; +function getDependencyGraph(packages, { + ignoreDevDependencies = false, + bumpVersionsWithWorkspaceProtocolOnly = false +} = {}) { + const graph = new Map(); + let valid = true; + const packagesByName = { + [packages.root.packageJson.name]: packages.root + }; + const queue = [packages.root]; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); + for (const pkg of packages.packages) { + queue.push(pkg); + packagesByName[pkg.packageJson.name] = pkg; } - return bytes; -} - -const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -exports.DNS = DNS; -const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -exports.URL = URL; + for (const pkg of queue) { + const { + name + } = pkg.packageJson; + const dependencies = []; + const allDependencies = getAllDependencies(pkg.packageJson, ignoreDevDependencies); -function _default(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - if (typeof value === 'string') { - value = stringToBytes(value); - } + for (let [depName, depRange] of allDependencies) { + const match = packagesByName[depName]; + if (!match) continue; + const expected = match.packageJson.version; + const usesWorkspaceRange = depRange.startsWith("workspace:"); - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } + if (usesWorkspaceRange) { + depRange = depRange.replace(/^workspace:/, ""); - if (namespace.length !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` + if (depRange === "*" || depRange === "^" || depRange === "~") { + dependencies.push(depName); + continue; + } + } else if (bumpVersionsWithWorkspaceProtocolOnly) { + continue; + } + const range = getValidRange(depRange); - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; + if (range && !range.test(expected) || isProtocolRange(depRange)) { + valid = false; + console.error(`Package ${pc__default["default"].cyan(`"${name}"`)} must depend on the current version of ${pc__default["default"].cyan(`"${depName}"`)}: ${pc__default["default"].green(`"${expected}"`)} vs ${pc__default["default"].red(`"${depRange}"`)}`); + continue; + } // `depRange` could have been a tag and if a tag has been used there might have been a reason for that + // we should not count this as a local monorepro dependant - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; + if (!range) { + continue; } - return buf; + dependencies.push(depName); } - return (0, _stringify.default)(bytes); - } // Function#name is not settable on some platforms (#270) - + graph.set(name, { + pkg, + dependencies + }); + } - try { - generateUUID.name = name; // eslint-disable-next-line no-empty - } catch (err) {} // For CommonJS default export support + return { + graph, + valid + }; +} +function getDependentsGraph(packages, opts) { + const graph = new Map(); + const { + graph: dependencyGraph + } = getDependencyGraph(packages, opts); + const dependentsLookup = { + [packages.root.packageJson.name]: { + pkg: packages.root, + dependents: [] + } + }; + packages.packages.forEach(pkg => { + dependentsLookup[pkg.packageJson.name] = { + pkg, + dependents: [] + }; + }); + packages.packages.forEach(pkg => { + const dependent = pkg.packageJson.name; + const valFromDependencyGraph = dependencyGraph.get(dependent); - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; + if (valFromDependencyGraph) { + const dependencies = valFromDependencyGraph.dependencies; + dependencies.forEach(dependency => { + dependentsLookup[dependency].dependents.push(dependent); + }); + } + }); + Object.keys(dependentsLookup).forEach(key => { + graph.set(key, dependentsLookup[key]); + }); + const simplifiedDependentsGraph = new Map(); + graph.forEach((pkgInfo, pkgName) => { + simplifiedDependentsGraph.set(pkgName, pkgInfo.dependents); + }); + return simplifiedDependentsGraph; } +exports.getDependentsGraph = getDependentsGraph; + + /***/ }), -/***/ 24100: +/***/ 49180: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); -var _rng = _interopRequireDefault(__nccwpck_require__(20397)); +var assembleReleasePlan = __nccwpck_require__(3624); +var readChangesets = __nccwpck_require__(8492); +var config = __nccwpck_require__(37168); +var getPackages = __nccwpck_require__(54393); +var pre = __nccwpck_require__(80428); -var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var assembleReleasePlan__default = /*#__PURE__*/_interopDefault(assembleReleasePlan); +var readChangesets__default = /*#__PURE__*/_interopDefault(readChangesets); -function v4(options, buf, offset) { - options = options || {}; +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } - const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + return obj; +} +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } - if (buf) { - offset = offset || 0; + return keys; +} - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - return buf; + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } } - return (0, _stringify.default)(rnds); + return target; } -var _default = v4; -exports["default"] = _default; +async function getReleasePlan(cwd, sinceRef, passedConfig) { + const packages = await getPackages.getPackages(cwd); + const preState = await pre.readPreState(cwd); + const readConfig = await config.read(cwd, packages); + const config$1 = passedConfig ? _objectSpread2(_objectSpread2({}, readConfig), passedConfig) : readConfig; + const changesets = await readChangesets__default["default"](cwd, sinceRef); + return assembleReleasePlan__default["default"](changesets, packages, config$1, preState); +} + +exports["default"] = getReleasePlan; + /***/ }), -/***/ 2796: +/***/ 69674: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); -var _v = _interopRequireDefault(__nccwpck_require__(42504)); +var spawn = __nccwpck_require__(54081); +var fs = __nccwpck_require__(57147); +var path = __nccwpck_require__(71017); +var getPackages = __nccwpck_require__(54393); +var errors = __nccwpck_require__(76249); +var isSubdir = __nccwpck_require__(63093); +var micromatch = __nccwpck_require__(39015); -var _sha = _interopRequireDefault(__nccwpck_require__(88224)); +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +var spawn__default = /*#__PURE__*/_interopDefault(spawn); +var fs__default = /*#__PURE__*/_interopDefault(fs); +var path__default = /*#__PURE__*/_interopDefault(path); +var isSubdir__default = /*#__PURE__*/_interopDefault(isSubdir); +var micromatch__default = /*#__PURE__*/_interopDefault(micromatch); -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = v5; -exports["default"] = _default; +async function add(pathToFile, cwd) { + const gitCmd = await spawn__default["default"]("git", ["add", pathToFile], { + cwd + }); -/***/ }), + if (gitCmd.code !== 0) { + console.log(pathToFile, gitCmd.stderr.toString()); + } -/***/ 3705: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return gitCmd.code === 0; +} +async function commit(message, cwd) { + const gitCmd = await spawn__default["default"]("git", ["commit", "-m", message, "--allow-empty"], { + cwd + }); + return gitCmd.code === 0; +} +async function getAllTags(cwd) { + const gitCmd = await spawn__default["default"]("git", ["tag"], { + cwd + }); -"use strict"; + if (gitCmd.code !== 0) { + throw new Error(gitCmd.stderr.toString()); + } + const tags = gitCmd.stdout.toString().trim().split("\n"); + return new Set(tags); +} // used to create a single tag at a time for the current head only -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +async function tag(tagStr, cwd) { + // NOTE: it's important we use the -m flag to create annotated tag otherwise 'git push --follow-tags' won't actually push + // the tags + const gitCmd = await spawn__default["default"]("git", ["tag", tagStr, "-m", tagStr], { + cwd + }); + return gitCmd.code === 0; +} // Find the commit where we diverged from `ref` at using `git merge-base` -var _regex = _interopRequireDefault(__nccwpck_require__(31315)); +async function getDivergedCommit(cwd, ref) { + const cmd = await spawn__default["default"]("git", ["merge-base", ref, "HEAD"], { + cwd + }); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + if (cmd.code !== 0) { + throw new Error(`Failed to find where HEAD diverged from ${ref}. Does ${ref} exist?`); + } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); + return cmd.stdout.toString().trim(); } +/** + * Get the SHAs for the commits that added files, including automatically + * extending a shallow clone if necessary to determine any commits. + * @param gitPaths - Paths to fetch + * @param options - `cwd` and `short` + */ + +async function getCommitsThatAddFiles(gitPaths, { + cwd, + short = false +}) { + // Maps gitPath to commit SHA + const map = new Map(); // Paths we haven't completed processing on yet + + let remaining = gitPaths; + + do { + // Fetch commit information for all paths we don't have yet + const commitInfos = await Promise.all(remaining.map(async gitPath => { + const [commitSha, parentSha] = (await spawn__default["default"]("git", ["log", "--diff-filter=A", "--max-count=1", short ? "--pretty=format:%h:%p" : "--pretty=format:%H:%p", gitPath], { + cwd + })).stdout.toString().split(":"); + return { + path: gitPath, + commitSha, + parentSha + }; + })); // To collect commits without parents (usually because they're absent from + // a shallow clone). + + let commitsWithMissingParents = []; + + for (const info of commitInfos) { + if (info.commitSha) { + if (info.parentSha) { + // We have found the parent of the commit that added the file. + // Therefore we know that the commit is legitimate and isn't simply the boundary of a shallow clone. + map.set(info.path, info.commitSha); + } else { + commitsWithMissingParents.push(info); + } + } + } + + if (commitsWithMissingParents.length === 0) { + break; + } // The commits we've found may be the real commits or they may be the boundary of + // a shallow clone. + // Can we deepen the clone? + + + if (await isRepoShallow({ + cwd + })) { + // Yes. + await deepenCloneBy({ + by: 50, + cwd + }); + remaining = commitsWithMissingParents.map(p => p.path); + } else { + // It's not a shallow clone, so all the commit SHAs we have are legitimate. + for (const unresolved of commitsWithMissingParents) { + map.set(unresolved.path, unresolved.commitSha); + } + + break; + } + } while (true); + + return gitPaths.map(p => map.get(p)); +} +async function isRepoShallow({ + cwd +}) { + const isShallowRepoOutput = (await spawn__default["default"]("git", ["rev-parse", "--is-shallow-repository"], { + cwd + })).stdout.toString().trim(); + + if (isShallowRepoOutput === "--is-shallow-repository") { + // We have an old version of Git (<2.15) which doesn't support `rev-parse --is-shallow-repository` + // In that case, we'll test for the existence of .git/shallow. + // Firstly, find the .git folder for the repo; note that this will be relative to the repo dir + const gitDir = (await spawn__default["default"]("git", ["rev-parse", "--git-dir"], { + cwd + })).stdout.toString().trim(); + const fullGitDir = path__default["default"].resolve(cwd, gitDir); // Check for the existence of /shallow + + return fs__default["default"].existsSync(path__default["default"].join(fullGitDir, "shallow")); + } else { + // We have a newer Git which supports `rev-parse --is-shallow-repository`. We'll use + // the output of that instead of messing with .git/shallow in case that changes in the future. + return isShallowRepoOutput === "true"; + } +} +async function deepenCloneBy({ + by, + cwd +}) { + await spawn__default["default"]("git", ["fetch", `--deepen=${by}`], { + cwd + }); +} + +async function getRepoRoot({ + cwd +}) { + const { + stdout, + code, + stderr + } = await spawn__default["default"]("git", ["rev-parse", "--show-toplevel"], { + cwd + }); + + if (code !== 0) { + throw new Error(stderr.toString()); + } + + return stdout.toString().trim().replace(/\n|\r/g, ""); +} + +async function getChangedFilesSince({ + cwd, + ref, + fullPath = false +}) { + const divergedAt = await getDivergedCommit(cwd, ref); // Now we can find which files we added + + const cmd = await spawn__default["default"]("git", ["diff", "--name-only", divergedAt], { + cwd + }); + + if (cmd.code !== 0) { + throw new Error(`Failed to diff against ${divergedAt}. Is ${divergedAt} a valid ref?`); + } + + const files = cmd.stdout.toString().trim().split("\n").filter(a => a); + if (!fullPath) return files; + const repoRoot = await getRepoRoot({ + cwd + }); + return files.map(file => path__default["default"].resolve(repoRoot, file)); +} // below are less generic functions that we use in combination with other things we are doing + +async function getChangedChangesetFilesSinceRef({ + cwd, + ref +}) { + try { + const divergedAt = await getDivergedCommit(cwd, ref); // Now we can find which files we added + + const cmd = await spawn__default["default"]("git", ["diff", "--name-only", "--diff-filter=d", divergedAt], { + cwd + }); + let tester = /.changeset\/[^/]+\.md$/; + const files = cmd.stdout.toString().trim().split("\n").filter(file => tester.test(file)); + return files; + } catch (err) { + if (err instanceof errors.GitError) return []; + throw err; + } +} +async function getChangedPackagesSinceRef({ + cwd, + ref, + changedFilePatterns = ["**"] +}) { + const changedFiles = await getChangedFilesSince({ + ref, + cwd, + fullPath: true + }); + return [...(await getPackages.getPackages(cwd)).packages] // sort packages by length of dir, so that we can check for subdirs first + .sort((pkgA, pkgB) => pkgB.dir.length - pkgA.dir.length).filter(pkg => { + const changedPackageFiles = []; + + for (let i = changedFiles.length - 1; i >= 0; i--) { + const file = changedFiles[i]; + + if (isSubdir__default["default"](pkg.dir, file)) { + changedFiles.splice(i, 1); + const relativeFile = file.slice(pkg.dir.length + 1); + changedPackageFiles.push(relativeFile); + } + } + + return changedPackageFiles.length > 0 && micromatch__default["default"](changedPackageFiles, changedFilePatterns).length > 0; + }); +} +async function tagExists(tagStr, cwd) { + const gitCmd = await spawn__default["default"]("git", ["tag", "-l", tagStr], { + cwd + }); + const output = gitCmd.stdout.toString().trim(); + const tagExists = !!output; + return tagExists; +} +async function getCurrentCommitId({ + cwd, + short = false +}) { + return (await spawn__default["default"]("git", ["rev-parse", short && "--short", "HEAD"].filter(Boolean), { + cwd + })).stdout.toString().trim(); +} +async function remoteTagExists(tagStr) { + const gitCmd = await spawn__default["default"]("git", ["ls-remote", "--tags", "origin", "-l", tagStr]); + const output = gitCmd.stdout.toString().trim(); + const tagExists = !!output; + return tagExists; +} + +exports.add = add; +exports.commit = commit; +exports.deepenCloneBy = deepenCloneBy; +exports.getAllTags = getAllTags; +exports.getChangedChangesetFilesSinceRef = getChangedChangesetFilesSinceRef; +exports.getChangedFilesSince = getChangedFilesSince; +exports.getChangedPackagesSinceRef = getChangedPackagesSinceRef; +exports.getCommitsThatAddFiles = getCommitsThatAddFiles; +exports.getCurrentCommitId = getCurrentCommitId; +exports.getDivergedCommit = getDivergedCommit; +exports.isRepoShallow = isRepoShallow; +exports.remoteTagExists = remoteTagExists; +exports.tag = tag; +exports.tagExists = tagExists; -var _default = validate; -exports["default"] = _default; /***/ }), -/***/ 44056: +/***/ 11376: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; +Object.defineProperty(exports, "__esModule", ({ value: true })); -var _validate = _interopRequireDefault(__nccwpck_require__(3705)); +var pc = __nccwpck_require__(88276); +var util = __nccwpck_require__(73837); -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } +var pc__default = /*#__PURE__*/_interopDefault(pc); +var util__default = /*#__PURE__*/_interopDefault(util); - return parseInt(uuid.substr(14, 1), 16); +let prefix = "🦋 "; + +function format(args, customPrefix) { + let fullPrefix = prefix + (customPrefix === undefined ? "" : " " + customPrefix); + return fullPrefix + util__default["default"].format("", ...args).split("\n").join("\n" + fullPrefix + " "); } -var _default = version; -exports["default"] = _default; +function error(...args) { + console.error(format(args, pc__default["default"].red("error"))); +} +function info(...args) { + console.info(format(args, pc__default["default"].cyan("info"))); +} +function log(...args) { + console.log(format(args)); +} +function success(...args) { + console.log(format(args, pc__default["default"].green("success"))); +} +function warn(...args) { + console.warn(format(args, pc__default["default"].yellow("warn"))); +} + +exports.error = error; +exports.info = info; +exports.log = log; +exports.prefix = prefix; +exports.success = success; +exports.warn = warn; + /***/ }), -/***/ 99873: -/***/ (function(__unused_webpack_module, exports) { +/***/ 80428: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; + Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); + +var fs = __nccwpck_require__(41621); +var path = __nccwpck_require__(71017); +var getPackages = __nccwpck_require__(54393); +var errors = __nccwpck_require__(76249); + +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } }); - } + } + }); + } + n["default"] = e; + return Object.freeze(n); } -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } + +var fs__namespace = /*#__PURE__*/_interopNamespace(fs); +var path__default = /*#__PURE__*/_interopDefault(path); + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; } -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; + } + + return target; +} + +async function readPreState(cwd) { + let preStatePath = path__default["default"].resolve(cwd, ".changeset", "pre.json"); // TODO: verify that the pre state isn't broken + + let preState; + + try { + let contents = await fs__namespace.readFile(preStatePath, "utf8"); + + try { + preState = JSON.parse(contents); + } catch (err) { + if (err instanceof SyntaxError) { + console.error("error parsing json:", contents); + } + + throw err; } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); + } catch (err) { + if (err.code !== "ENOENT") { + throw err; } + } + + return preState; } -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map +async function exitPre(cwd) { + let preStatePath = path__default["default"].resolve(cwd, ".changeset", "pre.json"); // TODO: verify that the pre state isn't broken + + let preState = await readPreState(cwd); + + if (preState === undefined) { + throw new errors.PreExitButNotInPreModeError(); + } + + await fs__namespace.outputFile(preStatePath, JSON.stringify(_objectSpread2(_objectSpread2({}, preState), {}, { + mode: "exit" + }), null, 2) + "\n"); +} +async function enterPre(cwd, tag) { + var _preState$changesets; + + let packages = await getPackages.getPackages(cwd); + let preStatePath = path__default["default"].resolve(packages.root.dir, ".changeset", "pre.json"); + let preState = await readPreState(packages.root.dir); // can't reenter if pre mode still exists, but we should allow exited pre mode to be reentered + + if ((preState === null || preState === void 0 ? void 0 : preState.mode) === "pre") { + throw new errors.PreEnterButInPreModeError(); + } + + let newPreState = { + mode: "pre", + tag, + initialVersions: {}, + changesets: (_preState$changesets = preState === null || preState === void 0 ? void 0 : preState.changesets) !== null && _preState$changesets !== void 0 ? _preState$changesets : [] + }; + + for (let pkg of packages.packages) { + newPreState.initialVersions[pkg.packageJson.name] = pkg.packageJson.version; + } + + await fs__namespace.outputFile(preStatePath, JSON.stringify(newPreState, null, 2) + "\n"); +} + +exports.enterPre = enterPre; +exports.exitPre = exitPre; +exports.readPreState = readPreState; + /***/ }), -/***/ 87301: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +/***/ 8492: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -/* eslint-disable @typescript-eslint/no-explicit-any */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; + Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(13685)); -const https = __importStar(__nccwpck_require__(95687)); -const pm = __importStar(__nccwpck_require__(11390)); -const tunnel = __importStar(__nccwpck_require__(89382)); -const undici_1 = __nccwpck_require__(7482); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers || (exports.Headers = Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; + +var fs = __nccwpck_require__(41621); +var path = __nccwpck_require__(71017); +var parse = __nccwpck_require__(2107); +var git = __nccwpck_require__(69674); +var pc = __nccwpck_require__(88276); +var pFilter = __nccwpck_require__(25073); +var logger = __nccwpck_require__(11376); + +function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } + +function _interopNamespace(e) { + if (e && e.__esModule) return e; + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== 'default') { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + } + n["default"] = e; + return Object.freeze(n); } -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } + +var fs__namespace = /*#__PURE__*/_interopNamespace(fs); +var path__default = /*#__PURE__*/_interopDefault(path); +var parse__default = /*#__PURE__*/_interopDefault(parse); +var git__namespace = /*#__PURE__*/_interopNamespace(git); +var pc__default = /*#__PURE__*/_interopDefault(pc); +var pFilter__default = /*#__PURE__*/_interopDefault(pFilter); + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; } -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - readBodyBuffer() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - const chunks = []; - this.message.on('data', (chunk) => { - chunks.push(chunk); - }); - this.message.on('end', () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); + } + + return target; +} + +let importantSeparator = pc__default["default"].red("===============================IMPORTANT!==============================="); +let importantEnd = pc__default["default"].red("----------------------------------------------------------------------"); + +async function getOldChangesets(changesetBase, dirs) { + // this needs to support just not dealing with dirs that aren't set up properly + let changesets = await pFilter__default["default"](dirs, async (dir) => (await fs__namespace.lstat(path__default["default"].join(changesetBase, dir))).isDirectory()); + const changesetContents = changesets.map(async changesetDir => { + const jsonPath = path__default["default"].join(changesetBase, changesetDir, "changes.json"); + const [summary, json] = await Promise.all([fs__namespace.readFile(path__default["default"].join(changesetBase, changesetDir, "changes.md"), "utf-8"), fs__namespace.readJson(jsonPath)]); + return { + releases: json.releases, + summary, + id: changesetDir + }; + }); + return Promise.all(changesetContents); +} // this function only exists while we wait for v1 changesets to be obsoleted +// and should be deleted before v3 + + +async function getOldChangesetsAndWarn(changesetBase, dirs) { + let oldChangesets = await getOldChangesets(changesetBase, dirs); + + if (oldChangesets.length === 0) { + return []; + } + + logger.warn(importantSeparator); + logger.warn("There were old changesets from version 1 found"); + logger.warn("These are being applied now but the dependents graph may have changed"); + logger.warn("Make sure you validate all your dependencies"); + logger.warn("In a future major version, we will no longer apply these old changesets, and will instead throw here"); + logger.warn(importantEnd); + return oldChangesets; +} + +async function filterChangesetsSinceRef(changesets, changesetBase, sinceRef) { + const newChangesets = await git__namespace.getChangedChangesetFilesSinceRef({ + cwd: changesetBase, + ref: sinceRef + }); + const newHashes = newChangesets.map(c => c.split("/")[1]); + return changesets.filter(dir => newHashes.includes(dir)); +} + +async function getChangesets(cwd, sinceRef) { + let changesetBase = path__default["default"].join(cwd, ".changeset"); + let contents; + + try { + contents = await fs__namespace["default"].readdir(changesetBase); + } catch (err) { + if (err.code === "ENOENT") { + throw new Error("There is no .changeset directory in this project"); } + + throw err; + } + + if (sinceRef !== undefined) { + contents = await filterChangesetsSinceRef(contents, changesetBase, sinceRef); + } + + let oldChangesetsPromise = getOldChangesetsAndWarn(changesetBase, contents); + let changesets = contents.filter(file => !file.startsWith(".") && file.endsWith(".md") && file !== "README.md"); + const changesetContents = changesets.map(async file => { + const changeset = await fs__namespace["default"].readFile(path__default["default"].join(changesetBase, file), "utf-8"); + return _objectSpread2(_objectSpread2({}, parse__default["default"](changeset)), {}, { + id: file.replace(".md", "") + }); + }); + return [...(await oldChangesetsPromise), ...(await Promise.all(changesetContents))]; } -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; + +exports["default"] = getChangesets; + + +/***/ }), + +/***/ 57193: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function shouldSkipPackage({ + packageJson +}, { + ignore, + allowPrivatePackages +}) { + if (ignore.includes(packageJson.name)) { + return true; + } + + if (packageJson.private && !allowPrivatePackages) { + return true; + } + + return !packageJson.version; } -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } + +exports.shouldSkipPackage = shouldSkipPackage; + + +/***/ }), + +/***/ 88276: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +let argv = process.argv || [], + env = process.env +let isColorSupported = + !("NO_COLOR" in env || argv.includes("--no-color")) && + ("FORCE_COLOR" in env || + argv.includes("--color") || + process.platform === "win32" || + (require != null && (__nccwpck_require__(76224).isatty)(1) && env.TERM !== "dumb") || + "CI" in env) + +let formatter = + (open, close, replace = open) => + input => { + let string = "" + input + let index = string.indexOf(close, open.length) + return ~index + ? open + replaceClose(string, close, replace, index) + close + : open + string + close + } + +let replaceClose = (string, close, replace, index) => { + let result = "" + let cursor = 0 + do { + result += string.substring(cursor, index) + replace + cursor = index + close.length + index = string.indexOf(close, cursor) + } while (~index) + return result + string.substring(cursor) +} + +let createColors = (enabled = isColorSupported) => { + let init = enabled ? formatter : () => String + return { + isColorSupported: enabled, + reset: init("\x1b[0m", "\x1b[0m"), + bold: init("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), + dim: init("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), + italic: init("\x1b[3m", "\x1b[23m"), + underline: init("\x1b[4m", "\x1b[24m"), + inverse: init("\x1b[7m", "\x1b[27m"), + hidden: init("\x1b[8m", "\x1b[28m"), + strikethrough: init("\x1b[9m", "\x1b[29m"), + + black: init("\x1b[30m", "\x1b[39m"), + red: init("\x1b[31m", "\x1b[39m"), + green: init("\x1b[32m", "\x1b[39m"), + yellow: init("\x1b[33m", "\x1b[39m"), + blue: init("\x1b[34m", "\x1b[39m"), + magenta: init("\x1b[35m", "\x1b[39m"), + cyan: init("\x1b[36m", "\x1b[39m"), + white: init("\x1b[37m", "\x1b[39m"), + gray: init("\x1b[90m", "\x1b[39m"), + + bgBlack: init("\x1b[40m", "\x1b[49m"), + bgRed: init("\x1b[41m", "\x1b[49m"), + bgGreen: init("\x1b[42m", "\x1b[49m"), + bgYellow: init("\x1b[43m", "\x1b[49m"), + bgBlue: init("\x1b[44m", "\x1b[49m"), + bgMagenta: init("\x1b[45m", "\x1b[49m"), + bgCyan: init("\x1b[46m", "\x1b[49m"), + bgWhite: init("\x1b[47m", "\x1b[49m"), + + blackBright: init("\x1b[90m", "\x1b[39m"), + redBright: init("\x1b[91m", "\x1b[39m"), + greenBright: init("\x1b[92m", "\x1b[39m"), + yellowBright: init("\x1b[93m", "\x1b[39m"), + blueBright: init("\x1b[94m", "\x1b[39m"), + magentaBright: init("\x1b[95m", "\x1b[39m"), + cyanBright: init("\x1b[96m", "\x1b[39m"), + whiteBright: init("\x1b[97m", "\x1b[39m"), + + bgBlackBright: init("\x1b[100m","\x1b[49m"), + bgRedBright: init("\x1b[101m","\x1b[49m"), + bgGreenBright: init("\x1b[102m","\x1b[49m"), + bgYellowBright: init("\x1b[103m","\x1b[49m"), + bgBlueBright: init("\x1b[104m","\x1b[49m"), + bgMagentaBright: init("\x1b[105m","\x1b[49m"), + bgCyanBright: init("\x1b[106m","\x1b[49m"), + bgWhiteBright: init("\x1b[107m","\x1b[49m"), + } +} + +module.exports = createColors() +module.exports.createColors = createColors + + +/***/ }), + +/***/ 29548: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(22037)); +const utils_1 = __nccwpck_require__(87472); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; } + this.command = command; + this.properties = properties; + this.message = message; } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } + else { + cmdStr += ','; } + cmdStr += `${key}=${escapeProperty(val)}`; } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); + } } - this._disposed = true; + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; } +} +function escapeData(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return utils_1.toCommandValue(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 37117: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(29548); +const file_command_1 = __nccwpck_require__(92469); +const utils_1 = __nccwpck_require__(87472); +const os = __importStar(__nccwpck_require__(22037)); +const path = __importStar(__nccwpck_require__(71017)); +const oidc_utils_1 = __nccwpck_require__(65172); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { /** - * Raw request. - * @param info - * @param data + * A code indicating that the action was successful */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); - } + ExitCode[ExitCode["Success"] = 0] = "Success"; /** - * Raw request with callback. - * @param info - * @param data - * @param onResult + * A code indicating that the action was a failure */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = utils_1.toCommandValue(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('ENV', file_command_1.prepareKeyValueMessage(name, val)); + } + command_1.issueCommand('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + file_command_1.issueFileCommand('PATH', inputPath); + } + else { + command_1.issueCommand('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + if (options && options.trimWhitespace === false) { + return val; + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); +} +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('OUTPUT', file_command_1.prepareKeyValueMessage(name, value)); + } + process.stdout.write(os.EOL); + command_1.issueCommand('set-output', { name }, utils_1.toCommandValue(value)); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + command_1.issue('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + command_1.issueCommand('error', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + command_1.issueCommand('warning', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + command_1.issueCommand('notice', utils_1.toCommandProperties(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); } - else { - req.end(); + finally { + endGroup(); } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return file_command_1.issueFileCommand('STATE', file_command_1.prepareKeyValueMessage(name, value)); } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); + command_1.issueCommand('save-state', { name }, utils_1.toCommandValue(value)); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(38452); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(38452); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(66890); +Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); +Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); +Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 92469: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +// For internal use, subject to change. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const fs = __importStar(__nccwpck_require__(57147)); +const os = __importStar(__nccwpck_require__(22037)); +const uuid_1 = __nccwpck_require__(77041); +const utils_1 = __nccwpck_require__(87472); +function issueFileCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; - } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } - } - return info; + fs.appendFileSync(filePath, `${utils_1.toCommandValue(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${uuid_1.v4()}`; + const convertedValue = utils_1.toCommandValue(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; +//# sourceMappingURL=file-command.js.map + +/***/ }), + +/***/ 65172: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(87301); +const auth_1 = __nccwpck_require__(99873); +const core_1 = __nccwpck_require__(37117); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (!useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if tunneling agent isn't assigned create a new agent - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); } - return agent; + return token; } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - // if agent is already assigned use that agent. - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { - token: `${proxyUrl.username}:${proxyUrl.password}` - }))); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); } - return proxyAgent; + return runtimeUrl; } - _performExponentialBackoff(retryNumber) { + static getCall(id_token_url) { + var _a; return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; }); } - _processResponse(res, options) { + static getIDToken(audience) { return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; } - })); + core_1.debug(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + core_1.setSecret(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } }); } } -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map + +/***/ }), + +/***/ 66890: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(71017)); +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); +} +exports.toPosixPath = toPosixPath; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); +} +exports.toWin32Path = toWin32Path; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); +} +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map /***/ }), -/***/ 11390: -/***/ ((__unused_webpack_module, exports) => { +/***/ 38452: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { "use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; +exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(22037); +const fs_1 = __nccwpck_require__(57147); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - try { - return new URL(proxyVar); - } - catch (_a) { - if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new URL(`http://${proxyVar}`); + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; } + return `<${tag}${htmlAttrs}>${content}`; } - else { - return undefined; + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); } -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress(reqHost)) { - return true; + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperNoProxyItem === '*' || - upperReqHosts.some(x => x === upperNoProxyItem || - x.endsWith(`.${upperNoProxyItem}`) || - (upperNoProxyItem.startsWith('.') && - x.endsWith(`${upperNoProxyItem}`)))) { - return true; - } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); } - return false; -} -exports.checkBypass = checkBypass; -function isLoopbackAddress(host) { - const hostLower = host.toLowerCase(); - return (hostLower === 'localhost' || - hostLower.startsWith('127.') || - hostLower.startsWith('[::1]') || - hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } -//# sourceMappingURL=proxy.js.map +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map /***/ }), -/***/ 76249: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 87472: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ Object.defineProperty(exports, "__esModule", ({ value: true })); - -var ExtendableError = __nccwpck_require__(53868); - -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } - -var ExtendableError__default = /*#__PURE__*/_interopDefault(ExtendableError); - -class GitError extends ExtendableError__default["default"] { - constructor(code, message) { - super(`${message}, exit code: ${code}`); - this.code = code; - } - -} -class ValidationError extends ExtendableError__default["default"] {} -class ExitError extends ExtendableError__default["default"] { - constructor(code) { - super(`The process exited with code: ${code}`); - this.code = code; - } - -} -class PreExitButNotInPreModeError extends ExtendableError__default["default"] { - constructor() { - super("pre mode cannot be exited when not in pre mode"); - } - -} -class PreEnterButInPreModeError extends ExtendableError__default["default"] { - constructor() { - super("pre mode cannot be entered when in pre mode"); - } - +exports.toCommandProperties = exports.toCommandValue = void 0; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); } -class InternalError extends ExtendableError__default["default"] { - constructor(message) { - super(message); - } - +exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; } - -exports.ExitError = ExitError; -exports.GitError = GitError; -exports.InternalError = InternalError; -exports.PreEnterButInPreModeError = PreEnterButInPreModeError; -exports.PreExitButNotInPreModeError = PreExitButNotInPreModeError; -exports.ValidationError = ValidationError; - +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 69256: +/***/ 77041: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var assembleReleasePlan = __nccwpck_require__(47109); -var readChangesets = __nccwpck_require__(21980); -var config = __nccwpck_require__(72059); -var getPackages = __nccwpck_require__(54393); -var pre = __nccwpck_require__(8920); - -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } - -var assembleReleasePlan__default = /*#__PURE__*/_interopDefault(assembleReleasePlan); -var readChangesets__default = /*#__PURE__*/_interopDefault(readChangesets); - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +Object.defineProperty(exports, "v1", ({ + enumerable: true, + get: function () { + return _v.default; + } +})); +Object.defineProperty(exports, "v3", ({ + enumerable: true, + get: function () { + return _v2.default; + } +})); +Object.defineProperty(exports, "v4", ({ + enumerable: true, + get: function () { + return _v3.default; + } +})); +Object.defineProperty(exports, "v5", ({ + enumerable: true, + get: function () { + return _v4.default; + } +})); +Object.defineProperty(exports, "NIL", ({ + enumerable: true, + get: function () { + return _nil.default; + } +})); +Object.defineProperty(exports, "version", ({ + enumerable: true, + get: function () { + return _version.default; + } +})); +Object.defineProperty(exports, "validate", ({ + enumerable: true, + get: function () { + return _validate.default; + } +})); +Object.defineProperty(exports, "stringify", ({ + enumerable: true, + get: function () { + return _stringify.default; + } +})); +Object.defineProperty(exports, "parse", ({ + enumerable: true, + get: function () { + return _parse.default; } +})); - return obj; -} +var _v = _interopRequireDefault(__nccwpck_require__(96415)); -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); +var _v2 = _interopRequireDefault(__nccwpck_require__(45410)); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } +var _v3 = _interopRequireDefault(__nccwpck_require__(24100)); - return keys; -} +var _v4 = _interopRequireDefault(__nccwpck_require__(2796)); -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; +var _nil = _interopRequireDefault(__nccwpck_require__(79259)); - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } +var _version = _interopRequireDefault(__nccwpck_require__(44056)); - return target; -} +var _validate = _interopRequireDefault(__nccwpck_require__(3705)); -async function getReleasePlan(cwd, sinceRef, passedConfig) { - const packages = await getPackages.getPackages(cwd); - const preState = await pre.readPreState(cwd); - const readConfig = await config.read(cwd, packages); - const config$1 = passedConfig ? _objectSpread2(_objectSpread2({}, readConfig), passedConfig) : readConfig; - const changesets = await readChangesets__default["default"](cwd, sinceRef); - return assembleReleasePlan__default["default"](changesets, packages, config$1, preState); -} +var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); -exports["default"] = getReleasePlan; +var _parse = _interopRequireDefault(__nccwpck_require__(75670)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /***/ }), -/***/ 47109: +/***/ 57627: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var errors = __nccwpck_require__(76249); -var getDependentsGraph = __nccwpck_require__(98296); -var shouldSkipPackage = __nccwpck_require__(97589); -var semverParse = __nccwpck_require__(58257); -var semverGt = __nccwpck_require__(93473); -var semverSatisfies = __nccwpck_require__(81495); -var semverInc = __nccwpck_require__(25009); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); -var semverParse__default = /*#__PURE__*/_interopDefault(semverParse); -var semverGt__default = /*#__PURE__*/_interopDefault(semverGt); -var semverSatisfies__default = /*#__PURE__*/_interopDefault(semverSatisfies); -var semverInc__default = /*#__PURE__*/_interopDefault(semverInc); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); } - return obj; + return _crypto.default.createHash('md5').update(bytes).digest(); } -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); +var _default = md5; +exports["default"] = _default; - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } +/***/ }), - return keys; -} +/***/ 79259: +/***/ ((__unused_webpack_module, exports) => { -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; +"use strict"; - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - return target; -} +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = '00000000-0000-0000-0000-000000000000'; +exports["default"] = _default; -function getHighestReleaseType(releases) { - if (releases.length === 0) { - throw new Error(`Large internal Changesets error when calculating highest release type in the set of releases. Please contact the maintainers`); - } +/***/ }), - let highestReleaseType = "none"; +/***/ 75670: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - for (let release of releases) { - switch (release.type) { - case "major": - return "major"; +"use strict"; - case "minor": - highestReleaseType = "minor"; - break; - case "patch": - if (highestReleaseType === "none") { - highestReleaseType = "patch"; - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - break; - } +var _validate = _interopRequireDefault(__nccwpck_require__(3705)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); } - return highestReleaseType; -} -function getCurrentHighestVersion(packageGroup, packagesByName) { - let highestVersion; + let v; + const arr = new Uint8Array(16); // Parse ########-....-....-....-............ - for (let pkgName of packageGroup) { - let pkg = packagesByName.get(pkgName); + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; // Parse ........-####-....-....-............ - if (!pkg) { - console.error(`FATAL ERROR IN CHANGESETS! We were unable to version for package group: ${pkgName} in package group: ${packageGroup.toString()}`); - throw new Error(`fatal: could not resolve linked packages`); - } + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; // Parse ........-....-####-....-............ - if (highestVersion === undefined || semverGt__default["default"](pkg.packageJson.version, highestVersion)) { - highestVersion = pkg.packageJson.version; - } - } + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; // Parse ........-....-....-####-............ - return highestVersion; + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; } -/* - WARNING: - Important note for understanding how this package works: +var _default = parse; +exports["default"] = _default; - We are doing some kind of wacky things with manipulating the objects within the - releases array, despite the fact that this was passed to us as an argument. We are - aware that this is generally bad practice, but have decided to to this here as - we control the entire flow of releases. +/***/ }), - We could solve this by inlining this function, or by returning a deep-cloned then - modified array, but we decided both of those are worse than this solution. -*/ +/***/ 31315: +/***/ ((__unused_webpack_module, exports) => { -function applyLinks(releases, packagesByName, linked) { - let updated = false; // We do this for each set of linked packages +"use strict"; - for (let linkedPackages of linked) { - // First we filter down to all the relevant releases for one set of linked packages - let releasingLinkedPackages = [...releases.values()].filter(release => linkedPackages.includes(release.name) && release.type !== "none"); // If we proceed any further we do extra work with calculating highestVersion for things that might - // not need one, as they only have workspace based packages - if (releasingLinkedPackages.length === 0) continue; - let highestReleaseType = getHighestReleaseType(releasingLinkedPackages); - let highestVersion = getCurrentHighestVersion(linkedPackages, packagesByName); // Finally, we update the packages so all of them are on the highest version +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i; +exports["default"] = _default; - for (let linkedPackage of releasingLinkedPackages) { - if (linkedPackage.type !== highestReleaseType) { - updated = true; - linkedPackage.type = highestReleaseType; - } +/***/ }), - if (linkedPackage.oldVersion !== highestVersion) { - updated = true; - linkedPackage.oldVersion = highestVersion; - } - } - } +/***/ 20397: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return updated; -} +"use strict"; -function incrementVersion(release, preInfo) { - if (release.type === "none") { - return release.oldVersion; - } - let version = semverInc__default["default"](release.oldVersion, release.type); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = rng; - if (preInfo !== undefined && preInfo.state.mode !== "exit") { - let preVersion = preInfo.preVersions.get(release.name); +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - if (preVersion === undefined) { - throw new errors.InternalError(`preVersion for ${release.name} does not exist when preState is defined`); - } // why are we adding this ourselves rather than passing 'pre' + versionType to semver.inc? - // because semver.inc with prereleases is confusing and this seems easier +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate - version += `-${preInfo.state.tag}.${preVersion}`; +let poolPtr = rnds8Pool.length; + +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _crypto.default.randomFillSync(rnds8Pool); + + poolPtr = 0; } - return version; + return rnds8Pool.slice(poolPtr, poolPtr += 16); } -/* - WARNING: - Important note for understanding how this package works: +/***/ }), - We are doing some kind of wacky things with manipulating the objects within the - releases array, despite the fact that this was passed to us as an argument. We are - aware that this is generally bad practice, but have decided to to this here as - we control the entire flow of releases. +/***/ 88224: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - We could solve this by inlining this function, or by returning a deep-cloned then - modified array, but we decided both of those are worse than this solution. -*/ -function determineDependents({ - releases, - packagesByName, - dependencyGraph, - preInfo, - config -}) { - let updated = false; // NOTE this is intended to be called recursively +"use strict"; - let pkgsToSearch = [...releases.values()]; - while (pkgsToSearch.length > 0) { - // nextRelease is our dependency, think of it as "avatar" - const nextRelease = pkgsToSearch.shift(); - if (!nextRelease) continue; // pkgDependents will be a list of packages that depend on nextRelease ie. ['avatar-group', 'comment'] +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - const pkgDependents = dependencyGraph.get(nextRelease.name); +var _crypto = _interopRequireDefault(__nccwpck_require__(6113)); - if (!pkgDependents) { - throw new Error(`Error in determining dependents - could not find package in repository: ${nextRelease.name}`); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - pkgDependents.map(dependent => { - let type; - const dependentPackage = packagesByName.get(dependent); - if (!dependentPackage) throw new Error("Dependency map is incorrect"); +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } - if (shouldSkipPackage.shouldSkipPackage(dependentPackage, { - ignore: config.ignore, - allowPrivatePackages: config.privatePackages.version - })) { - type = "none"; - } else { - const dependencyVersionRanges = getDependencyVersionRanges(dependentPackage.packageJson, nextRelease); + return _crypto.default.createHash('sha1').update(bytes).digest(); +} - for (const { - depType, - versionRange - } of dependencyVersionRanges) { - if (nextRelease.type === "none") { - continue; - } else if (shouldBumpMajor({ - dependent, - depType, - versionRange, - releases, - nextRelease, - preInfo, - onlyUpdatePeerDependentsWhenOutOfRange: config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.onlyUpdatePeerDependentsWhenOutOfRange - })) { - type = "major"; - } else if ((!releases.has(dependent) || releases.get(dependent).type === "none") && (config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.updateInternalDependents === "always" || !semverSatisfies__default["default"](incrementVersion(nextRelease, preInfo), versionRange))) { - switch (depType) { - case "dependencies": - case "optionalDependencies": - case "peerDependencies": - if (type !== "major" && type !== "minor") { - type = "patch"; - } +var _default = sha1; +exports["default"] = _default; - break; +/***/ }), - case "devDependencies": - { - // We don't need a version bump if the package is only in the devDependencies of the dependent package - if (type !== "major" && type !== "minor" && type !== "patch") { - type = "none"; - } - } - } - } - } - } +/***/ 13538: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (releases.has(dependent) && releases.get(dependent).type === type) { - type = undefined; - } +"use strict"; - return { - name: dependent, - type, - pkgJSON: dependentPackage.packageJson - }; - }).filter(dependentItem => !!dependentItem.type).forEach(({ - name, - type, - pkgJSON - }) => { - // At this point, we know if we are making a change - updated = true; - const existing = releases.get(name); // For things that are being given a major bump, we check if we have already - // added them here. If we have, we update the existing item instead of pushing it on to search. - // It is safe to not add it to pkgsToSearch because it should have already been searched at the - // largest possible bump type. - if (existing && type === "major" && existing.type !== "major") { - existing.type = "major"; - pkgsToSearch.push(existing); - } else { - let newDependent = { - name, - type, - oldVersion: pkgJSON.version, - changesets: [] - }; - pkgsToSearch.push(newDependent); - releases.set(name, newDependent); - } - }); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - return updated; -} -/* - Returns an array of objects in the shape { depType: DependencyType, versionRange: string } - The array can contain more than one elements in case a dependency appears in multiple - dependency lists. For example, a package that is both a peerDepenency and a devDependency. -*/ +var _validate = _interopRequireDefault(__nccwpck_require__(3705)); -function getDependencyVersionRanges(dependentPkgJSON, dependencyRelease) { - const DEPENDENCY_TYPES = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; - const dependencyVersionRanges = []; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - for (const type of DEPENDENCY_TYPES) { - var _dependentPkgJSON$typ; +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; - const versionRange = (_dependentPkgJSON$typ = dependentPkgJSON[type]) === null || _dependentPkgJSON$typ === void 0 ? void 0 : _dependentPkgJSON$typ[dependencyRelease.name]; - if (!versionRange) continue; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).substr(1)); +} - if (versionRange.startsWith("workspace:")) { - dependencyVersionRanges.push({ - depType: type, - versionRange: // intentionally keep other workspace ranges untouched - // this has to be fixed but this should only be done when adding appropriate tests - versionRange === "workspace:*" ? // workspace:* actually means the current exact version, and not a wildcard similar to a reguler * range - dependencyRelease.oldVersion : versionRange.replace(/^workspace:/, "") - }); - } else { - dependencyVersionRanges.push({ - depType: type, - versionRange - }); - } - } +function stringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + const uuid = (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields - return dependencyVersionRanges; -} + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } -function shouldBumpMajor({ - dependent, - depType, - versionRange, - releases, - nextRelease, - preInfo, - onlyUpdatePeerDependentsWhenOutOfRange -}) { - // we check if it is a peerDependency because if it is, our dependent bump type might need to be major. - return depType === "peerDependencies" && nextRelease.type !== "none" && nextRelease.type !== "patch" && ( // 1. If onlyUpdatePeerDependentsWhenOutOfRange set to true, bump major if the version is leaving the range. - // 2. If onlyUpdatePeerDependentsWhenOutOfRange set to false, bump major regardless whether or not the version is leaving the range. - !onlyUpdatePeerDependentsWhenOutOfRange || !semverSatisfies__default["default"](incrementVersion(nextRelease, preInfo), versionRange)) && ( // bump major only if the dependent doesn't already has a major release. - !releases.has(dependent) || releases.has(dependent) && releases.get(dependent).type !== "major"); + return uuid; } -// This function takes in changesets and returns one release per -function flattenReleases(changesets, packagesByName, config) { - let releases = new Map(); - changesets.forEach(changeset => { - changeset.releases // Filter out skipped packages because they should not trigger a release - // If their dependencies need updates, they will be added to releases by `determineDependents()` with release type `none` - .filter(({ - name - }) => !shouldSkipPackage.shouldSkipPackage(packagesByName.get(name), { - ignore: config.ignore, - allowPrivatePackages: config.privatePackages.version - })).forEach(({ - name, - type - }) => { - let release = releases.get(name); - let pkg = packagesByName.get(name); +var _default = stringify; +exports["default"] = _default; - if (!pkg) { - throw new Error(`"${changeset.id}" changeset mentions a release for a package "${name}" but such a package could not be found.`); - } +/***/ }), - if (!release) { - release = { - name, - type, - oldVersion: pkg.packageJson.version, - changesets: [changeset.id] - }; - } else { - if (type === "major" || (release.type === "patch" || release.type === "none") && (type === "minor" || type === "patch")) { - release.type = type; - } // Check whether the bumpType will change - // If the bumpType has changed recalc newVersion - // push new changeset to releases +/***/ 96415: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +"use strict"; - release.changesets.push(changeset.id); - } - releases.set(name, release); - }); - }); - return releases; -} +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -function matchFixedConstraint(releases, packagesByName, config) { - let updated = false; +var _rng = _interopRequireDefault(__nccwpck_require__(20397)); - for (let fixedPackages of config.fixed) { - let releasingFixedPackages = [...releases.values()].filter(release => fixedPackages.includes(release.name) && release.type !== "none"); - if (releasingFixedPackages.length === 0) continue; - let highestReleaseType = getHighestReleaseType(releasingFixedPackages); - let highestVersion = getCurrentHighestVersion(fixedPackages, packagesByName); // Finally, we update the packages so all of them are on the highest version +var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); - for (let pkgName of fixedPackages) { - if (shouldSkipPackage.shouldSkipPackage(packagesByName.get(pkgName), { - ignore: config.ignore, - allowPrivatePackages: config.privatePackages.version - })) { - continue; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - let release = releases.get(pkgName); +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html +let _nodeId; - if (!release) { - updated = true; - releases.set(pkgName, { - name: pkgName, - type: highestReleaseType, - oldVersion: highestVersion, - changesets: [] - }); - continue; - } +let _clockseq; // Previous uuid creation time - if (release.type !== highestReleaseType) { - updated = true; - release.type = highestReleaseType; - } - if (release.oldVersion !== highestVersion) { - updated = true; - release.oldVersion = highestVersion; - } +let _lastMSecs = 0; +let _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details + +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node || _nodeId; + let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not + // specified. We do this lazily to minimize issues related to insufficient + // system entropy. See #189 + + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + if (node == null) { + // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) + node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; } - } - return updated; -} + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + } + } // UUID timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so + // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. -function getPreVersion(version) { - let parsed = semverParse__default["default"](version); - let preVersion = parsed.prerelease[1] === undefined ? -1 : parsed.prerelease[1]; - if (typeof preVersion !== "number") { - throw new errors.InternalError("preVersion is not a number"); - } + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock - preVersion++; - return preVersion; -} + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs) -function getSnapshotSuffix(template, snapshotParameters) { - let snapshotRefDate = new Date(); - const placeholderValues = { - commit: snapshotParameters.commit, - tag: snapshotParameters.tag, - timestamp: snapshotRefDate.getTime().toString(), - datetime: snapshotRefDate.toISOString().replace(/\.\d{3}Z$/, "").replace(/[^\d]/g, "") - }; // We need a special handling because we need to handle a case where `--snapshot` is used without any template, - // and the resulting version needs to be composed without a tag. + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression - if (!template) { - return [placeholderValues.tag, placeholderValues.datetime].filter(Boolean).join("-"); - } + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval - const placeholders = Object.keys(placeholderValues); - if (!template.includes(`{tag}`) && placeholderValues.tag !== undefined) { - throw new Error(`Failed to compose snapshot version: "{tag}" placeholder is missing, but the snapshot parameter is defined (value: '${placeholderValues.tag}')`); + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } // Per 4.2.1.2 Throw error if too many uuids are requested + + + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); } - return placeholders.reduce((prev, key) => { - return prev.replace(new RegExp(`\\{${key}\\}`, "g"), () => { - const value = placeholderValues[key]; + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - if (value === undefined) { - throw new Error(`Failed to compose snapshot version: "{${key}}" placeholder is used without having a value defined!`); - } + msecs += 12219292800000; // `time_low` - return value; - }); - }, template); -} + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; // `time_mid` -function getSnapshotVersion(release, preInfo, useCalculatedVersion, snapshotSuffix) { - if (release.type === "none") { - return release.oldVersion; - } - /** - * Using version as 0.0.0 so that it does not hinder with other version release - * For example; - * if user has a regular pre-release at 1.0.0-beta.0 and then you had a snapshot pre-release at 1.0.0-canary-git-hash - * and a consumer is using the range ^1.0.0-beta, most people would expect that range to resolve to 1.0.0-beta.0 - * but it'll actually resolve to 1.0.0-canary-hash. Using 0.0.0 solves this problem because it won't conflict with other versions. - * - * You can set `snapshot.useCalculatedVersion` flag to true to use calculated versions if you don't care about the above problem. - */ + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - const baseVersion = useCalculatedVersion ? incrementVersion(release, preInfo) : `0.0.0`; - return `${baseVersion}-${snapshotSuffix}`; -} + b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) -function getNewVersion(release, preInfo) { - if (release.type === "none") { - return release.oldVersion; + b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low` + + b[i++] = clockseq & 0xff; // `node` + + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; } - return incrementVersion(release, preInfo); + return buf || (0, _stringify.default)(b); } -function assembleReleasePlan(changesets, packages, config, // intentionally not using an optional parameter here so the result of `readPreState` has to be passed in here -preState, // snapshot: undefined -> not using snaphot -// snapshot: { tag: undefined } -> --snapshot (empty tag) -// snapshot: { tag: "canary" } -> --snapshot canary -snapshot) { - // TODO: remove `refined*` in the next major version of this package - // just use `config` and `snapshot` parameters directly, typed as: `config: Config, snapshot?: SnapshotReleaseParameters` - const refinedConfig = config.snapshot ? config : _objectSpread2(_objectSpread2({}, config), {}, { - snapshot: { - prereleaseTemplate: null, - useCalculatedVersion: config.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.useCalculatedVersionForSnapshots - } - }); - const refinedSnapshot = typeof snapshot === "string" ? { - tag: snapshot - } : typeof snapshot === "boolean" ? { - tag: undefined - } : snapshot; - let packagesByName = new Map(packages.packages.map(x => [x.packageJson.name, x])); - const relevantChangesets = getRelevantChangesets(changesets, packagesByName, refinedConfig, preState); - const preInfo = getPreInfo(changesets, packagesByName, refinedConfig, preState); // releases is, at this point a list of all packages we are going to releases, - // flattened down to one release per package, having a reference back to their - // changesets, and with a calculated new versions +var _default = v1; +exports["default"] = _default; - let releases = flattenReleases(relevantChangesets, packagesByName, refinedConfig); - let dependencyGraph = getDependentsGraph.getDependentsGraph(packages, { - bumpVersionsWithWorkspaceProtocolOnly: refinedConfig.bumpVersionsWithWorkspaceProtocolOnly - }); - let releasesValidated = false; +/***/ }), - while (releasesValidated === false) { - // The map passed in to determineDependents will be mutated - let dependentAdded = determineDependents({ - releases, - packagesByName, - dependencyGraph, - preInfo, - config: refinedConfig - }); // `releases` might get mutated here +/***/ 45410: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let fixedConstraintUpdated = matchFixedConstraint(releases, packagesByName, refinedConfig); - let linksUpdated = applyLinks(releases, packagesByName, refinedConfig.linked); - releasesValidated = !linksUpdated && !dependentAdded && !fixedConstraintUpdated; - } +"use strict"; - if ((preInfo === null || preInfo === void 0 ? void 0 : preInfo.state.mode) === "exit") { - for (let pkg of packages.packages) { - // If a package had a prerelease, but didn't trigger a version bump in the regular release, - // we want to give it a patch release. - // Detailed explanation at https://github.com/changesets/changesets/pull/382#discussion_r434434182 - if (preInfo.preVersions.get(pkg.packageJson.name) !== 0) { - const existingRelease = releases.get(pkg.packageJson.name); - if (!existingRelease) { - releases.set(pkg.packageJson.name, { - name: pkg.packageJson.name, - type: "patch", - oldVersion: pkg.packageJson.version, - changesets: [] - }); - } else if (existingRelease.type === "none" && !shouldSkipPackage.shouldSkipPackage(pkg, { - ignore: refinedConfig.ignore, - allowPrivatePackages: refinedConfig.privatePackages.version - })) { - existingRelease.type = "patch"; - } - } - } - } // Caching the snapshot version here and use this if it is snapshot release +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _v = _interopRequireDefault(__nccwpck_require__(42504)); - const snapshotSuffix = refinedSnapshot && getSnapshotSuffix(refinedConfig.snapshot.prereleaseTemplate, refinedSnapshot); - return { - changesets: relevantChangesets, - releases: [...releases.values()].map(incompleteRelease => { - return _objectSpread2(_objectSpread2({}, incompleteRelease), {}, { - newVersion: snapshotSuffix ? getSnapshotVersion(incompleteRelease, preInfo, refinedConfig.snapshot.useCalculatedVersion, snapshotSuffix) : getNewVersion(incompleteRelease, preInfo) - }); - }), - preState: preInfo === null || preInfo === void 0 ? void 0 : preInfo.state - }; -} +var _md = _interopRequireDefault(__nccwpck_require__(57627)); -function getRelevantChangesets(changesets, packagesByName, config, preState) { - for (const changeset of changesets) { - // Using the following 2 arrays to decide whether a changeset - // contains both skipped and not skipped packages - const skippedPackages = []; - const notSkippedPackages = []; +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - for (const release of changeset.releases) { - if (shouldSkipPackage.shouldSkipPackage(packagesByName.get(release.name), { - ignore: config.ignore, - allowPrivatePackages: config.privatePackages.version - })) { - skippedPackages.push(release.name); - } else { - notSkippedPackages.push(release.name); - } - } +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = v3; +exports["default"] = _default; - if (skippedPackages.length > 0 && notSkippedPackages.length > 0) { - throw new Error(`Found mixed changeset ${changeset.id}\n` + `Found ignored packages: ${skippedPackages.join(" ")}\n` + `Found not ignored packages: ${notSkippedPackages.join(" ")}\n` + "Mixed changesets that contain both ignored and not ignored packages are not allowed"); - } - } +/***/ }), - if (preState && preState.mode !== "exit") { - let usedChangesetIds = new Set(preState.changesets); - return changesets.filter(changeset => !usedChangesetIds.has(changeset.id)); - } +/***/ 42504: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return changesets; -} +"use strict"; -function getHighestPreVersion(packageGroup, packagesByName) { - let highestPreVersion = 0; - for (let pkg of packageGroup) { - highestPreVersion = Math.max(getPreVersion(packagesByName.get(pkg).packageJson.version), highestPreVersion); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = _default; +exports.URL = exports.DNS = void 0; + +var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); + +var _parse = _interopRequireDefault(__nccwpck_require__(75670)); + +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); } - return highestPreVersion; + return bytes; } -function getPreInfo(changesets, packagesByName, config, preState) { - if (preState === undefined) { - return; - } +const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +exports.DNS = DNS; +const URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +exports.URL = URL; - let updatedPreState = _objectSpread2(_objectSpread2({}, preState), {}, { - changesets: changesets.map(changeset => changeset.id), - initialVersions: _objectSpread2({}, preState.initialVersions) - }); +function _default(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + if (typeof value === 'string') { + value = stringToBytes(value); + } - for (const [, pkg] of packagesByName) { - if (updatedPreState.initialVersions[pkg.packageJson.name] === undefined) { - updatedPreState.initialVersions[pkg.packageJson.name] = pkg.packageJson.version; + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); } - } // Populate preVersion - // preVersion is the map between package name and its next pre version number. + if (namespace.length !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` - let preVersions = new Map(); - for (const [, pkg] of packagesByName) { - preVersions.set(pkg.packageJson.name, getPreVersion(pkg.packageJson.version)); - } + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; - for (let fixedGroup of config.fixed) { - let highestPreVersion = getHighestPreVersion(fixedGroup, packagesByName); + if (buf) { + offset = offset || 0; - for (let fixedPackage of fixedGroup) { - preVersions.set(fixedPackage, highestPreVersion); + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + + return buf; } - } - for (let linkedGroup of config.linked) { - let highestPreVersion = getHighestPreVersion(linkedGroup, packagesByName); + return (0, _stringify.default)(bytes); + } // Function#name is not settable on some platforms (#270) - for (let linkedPackage of linkedGroup) { - preVersions.set(linkedPackage, highestPreVersion); - } - } - return { - state: updatedPreState, - preVersions - }; -} + try { + generateUUID.name = name; // eslint-disable-next-line no-empty + } catch (err) {} // For CommonJS default export support -exports["default"] = assembleReleasePlan; + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} /***/ }), -/***/ 72059: +/***/ 24100: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -var fs = __nccwpck_require__(41621); -var path = __nccwpck_require__(71017); -var micromatch = __nccwpck_require__(39015); -var errors = __nccwpck_require__(76249); -var logger = __nccwpck_require__(95889); -var getDependentsGraph = __nccwpck_require__(98296); +var _rng = _interopRequireDefault(__nccwpck_require__(20397)); -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } +var _stringify = _interopRequireDefault(__nccwpck_require__(13538)); -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } + +function v4(options, buf, offset) { + options = options || {}; + + const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + + + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided + + if (buf) { + offset = offset || 0; + + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + + return buf; } - n["default"] = e; - return Object.freeze(n); + + return (0, _stringify.default)(rnds); } -var fs__namespace = /*#__PURE__*/_interopNamespace(fs); -var path__default = /*#__PURE__*/_interopDefault(path); -var micromatch__default = /*#__PURE__*/_interopDefault(micromatch); +var _default = v4; +exports["default"] = _default; -var packageJson = { - name: "@changesets/config", - version: "3.0.3", - description: "Utilities for reading and parsing Changeset's config", - main: "dist/changesets-config.cjs.js", - module: "dist/changesets-config.esm.js", - exports: { - ".": { - types: { - "import": "./dist/changesets-config.cjs.mjs", - "default": "./dist/changesets-config.cjs.js" - }, - module: "./dist/changesets-config.esm.js", - "import": "./dist/changesets-config.cjs.mjs", - "default": "./dist/changesets-config.cjs.js" - }, - "./package.json": "./package.json" - }, - license: "MIT", - repository: "https://github.com/changesets/changesets/tree/main/packages/config", - files: [ - "dist", - "schema.json" - ], - dependencies: { - "@changesets/errors": "^0.2.0", - "@changesets/get-dependents-graph": "^2.1.2", - "@changesets/logger": "^0.1.1", - "@changesets/types": "^6.0.0", - "@manypkg/get-packages": "^1.1.3", - "fs-extra": "^7.0.1", - micromatch: "^4.0.2" - }, - devDependencies: { - "@changesets/test-utils": "*", - "@types/micromatch": "^4.0.1", - "jest-in-case": "^1.0.2", - outdent: "^0.5.0" - } -}; +/***/ }), -let defaultWrittenConfig = { - $schema: `https://unpkg.com/@changesets/config@${packageJson.version}/schema.json`, - changelog: "@changesets/cli/changelog", - commit: false, - fixed: [], - linked: [], - access: "restricted", - baseBranch: "master", - updateInternalDependencies: "patch", - ignore: [] -}; +/***/ 2796: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function flatten(arr) { - return [].concat(...arr); -} +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; + +var _v = _interopRequireDefault(__nccwpck_require__(42504)); -function getNormalizedChangelogOption(thing) { - if (thing === false) { - return false; - } +var _sha = _interopRequireDefault(__nccwpck_require__(88224)); - if (typeof thing === "string") { - return [thing, null]; - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - return thing; -} +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = v5; +exports["default"] = _default; -function getNormalizedCommitOption(thing) { - if (thing === false) { - return false; - } +/***/ }), - if (thing === true) { - return ["@changesets/cli/commit", { - skipCI: "version" - }]; - } +/***/ 3705: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (typeof thing === "string") { - return [thing, null]; - } +"use strict"; - return thing; -} -function getUnmatchedPatterns(listOfPackageNamesOrGlob, pkgNames) { - return listOfPackageNamesOrGlob.filter(pkgNameOrGlob => !pkgNames.some(pkgName => micromatch__default["default"].isMatch(pkgName, pkgNameOrGlob))); -} +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; -const havePackageGroupsCorrectShape = pkgGroups => { - return isArray(pkgGroups) && pkgGroups.every(arr => isArray(arr) && arr.every(pkgName => typeof pkgName === "string")); -}; // TODO: it might be possible to remove this if improvements to `Array.isArray` ever land -// related thread: github.com/microsoft/TypeScript/issues/36554 +var _regex = _interopRequireDefault(__nccwpck_require__(31315)); +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } -function isArray(arg) { - return Array.isArray(arg); +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); } -let read = async (cwd, packages) => { - let json = await fs__namespace.readJSON(path__default["default"].join(cwd, ".changeset", "config.json")); - return parse(json, packages); -}; -let parse = (json, packages) => { - var _json$changedFilePatt, _json$snapshot$prerel, _json$snapshot, _json$snapshot2, _json$___experimental, _json$___experimental2, _json$___experimental3, _json$___experimental4, _json$privatePackages, _json$privatePackages2; +var _default = validate; +exports["default"] = _default; - let messages = []; - let pkgNames = packages.packages.map(({ - packageJson - }) => packageJson.name); +/***/ }), - if (json.changelog !== undefined && json.changelog !== false && typeof json.changelog !== "string" && !(isArray(json.changelog) && json.changelog.length === 2 && typeof json.changelog[0] === "string")) { - messages.push(`The \`changelog\` option is set as ${JSON.stringify(json.changelog, null, 2)} when the only valid values are undefined, false, a module path(e.g. "@changesets/cli/changelog" or "./some-module") or a tuple with a module path and config for the changelog generator(e.g. ["@changesets/cli/changelog", { someOption: true }])`); - } +/***/ 44056: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - let normalizedAccess = json.access; +"use strict"; - if (json.access === "private") { - normalizedAccess = "restricted"; - logger.warn('The `access` option is set as "private", but this is actually not a valid value - the correct form is "restricted".'); - } - if (normalizedAccess !== undefined && normalizedAccess !== "restricted" && normalizedAccess !== "public") { - messages.push(`The \`access\` option is set as ${JSON.stringify(normalizedAccess, null, 2)} when the only valid values are undefined, "public" or "restricted"`); - } +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; - if (json.commit !== undefined && typeof json.commit !== "boolean" && typeof json.commit !== "string" && !(isArray(json.commit) && json.commit.length === 2 && typeof json.commit[0] === "string")) { - messages.push(`The \`commit\` option is set as ${JSON.stringify(json.commit, null, 2)} when the only valid values are undefined or a boolean or a module path (e.g. "@changesets/cli/commit" or "./some-module") or a tuple with a module path and config for the commit message generator (e.g. ["@changesets/cli/commit", { "skipCI": "version" }])`); - } +var _validate = _interopRequireDefault(__nccwpck_require__(3705)); - if (json.baseBranch !== undefined && typeof json.baseBranch !== "string") { - messages.push(`The \`baseBranch\` option is set as ${JSON.stringify(json.baseBranch, null, 2)} but the \`baseBranch\` option can only be set as a string`); - } +function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - if (json.changedFilePatterns !== undefined && (!isArray(json.changedFilePatterns) || !json.changedFilePatterns.every(pattern => typeof pattern === "string"))) { - messages.push(`The \`changedFilePatterns\` option is set as ${JSON.stringify(json.changedFilePatterns, null, 2)} but the \`changedFilePatterns\` option can only be set as an array of strings`); +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); } - let fixed = []; + return parseInt(uuid.substr(14, 1), 16); +} - if (json.fixed !== undefined) { - if (!havePackageGroupsCorrectShape(json.fixed)) { - messages.push(`The \`fixed\` option is set as ${JSON.stringify(json.fixed, null, 2)} when the only valid values are undefined or an array of arrays of package names`); - } else { - let foundPkgNames = new Set(); - let duplicatedPkgNames = new Set(); +var _default = version; +exports["default"] = _default; - for (let fixedGroup of json.fixed) { - messages.push(...getUnmatchedPatterns(fixedGroup, pkgNames).map(pkgOrGlob => `The package or glob expression "${pkgOrGlob}" specified in the \`fixed\` option does not match any package in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.`)); - let expandedFixedGroup = micromatch__default["default"](pkgNames, fixedGroup); - fixed.push(expandedFixedGroup); +/***/ }), - for (let fixedPkgName of expandedFixedGroup) { - if (foundPkgNames.has(fixedPkgName)) { - duplicatedPkgNames.add(fixedPkgName); - } +/***/ 99873: +/***/ (function(__unused_webpack_module, exports) { - foundPkgNames.add(fixedPkgName); +"use strict"; + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); } - } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map - if (duplicatedPkgNames.size) { - duplicatedPkgNames.forEach(pkgName => { - messages.push(`The package "${pkgName}" is defined in multiple sets of fixed packages. Packages can only be defined in a single set of fixed packages. If you are using glob expressions, make sure that they are valid according to https://www.npmjs.com/package/micromatch.`); +/***/ }), + +/***/ 87301: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + 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 step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(13685)); +const https = __importStar(__nccwpck_require__(95687)); +const pm = __importStar(__nccwpck_require__(11390)); +const tunnel = __importStar(__nccwpck_require__(89382)); +const undici_1 = __nccwpck_require__(7482); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (exports.Headers = Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; +} +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } +} +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; }); - } } - } - - let linked = []; - - if (json.linked !== undefined) { - if (!havePackageGroupsCorrectShape(json.linked)) { - messages.push(`The \`linked\` option is set as ${JSON.stringify(json.linked, null, 2)} when the only valid values are undefined or an array of arrays of package names`); - } else { - let foundPkgNames = new Set(); - let duplicatedPkgNames = new Set(); - - for (let linkedGroup of json.linked) { - messages.push(...getUnmatchedPatterns(linkedGroup, pkgNames).map(pkgOrGlob => `The package or glob expression "${pkgOrGlob}" specified in the \`linked\` option does not match any package in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.`)); - let expandedLinkedGroup = micromatch__default["default"](pkgNames, linkedGroup); - linked.push(expandedLinkedGroup); - - for (let linkedPkgName of expandedLinkedGroup) { - if (foundPkgNames.has(linkedPkgName)) { - duplicatedPkgNames.add(linkedPkgName); - } - - foundPkgNames.add(linkedPkgName); + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); } - } - - if (duplicatedPkgNames.size) { - duplicatedPkgNames.forEach(pkgName => { - messages.push(`The package "${pkgName}" is defined in multiple sets of linked packages. Packages can only be defined in a single set of linked packages. If you are using glob expressions, make sure that they are valid according to https://www.npmjs.com/package/micromatch.`); - }); - } + this._disposed = true; } - } - - const allFixedPackages = new Set(flatten(fixed)); - const allLinkedPackages = new Set(flatten(linked)); - allFixedPackages.forEach(pkgName => { - if (allLinkedPackages.has(pkgName)) { - messages.push(`The package "${pkgName}" can be found in both fixed and linked groups. A package can only be either fixed or linked.`); + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); } - }); - - if (json.updateInternalDependencies !== undefined && !["patch", "minor"].includes(json.updateInternalDependencies)) { - messages.push(`The \`updateInternalDependencies\` option is set as ${JSON.stringify(json.updateInternalDependencies, null, 2)} but can only be 'patch' or 'minor'`); - } - - if (json.ignore) { - if (!(isArray(json.ignore) && json.ignore.every(pkgName => typeof pkgName === "string"))) { - messages.push(`The \`ignore\` option is set as ${JSON.stringify(json.ignore, null, 2)} when the only valid values are undefined or an array of package names`); - } else { - messages.push(...getUnmatchedPatterns(json.ignore, pkgNames).map(pkgOrGlob => `The package or glob expression "${pkgOrGlob}" is specified in the \`ignore\` option but it is not found in the project. You may have misspelled the package name or provided an invalid glob expression. Note that glob expressions must be defined according to https://www.npmjs.com/package/micromatch.`)); // Validate that all dependents of ignored packages are listed in the ignore list - - const dependentsGraph = getDependentsGraph.getDependentsGraph(packages); - - for (const ignoredPackage of json.ignore) { - const dependents = dependentsGraph.get(ignoredPackage) || []; - - for (const dependent of dependents) { - if (!json.ignore.includes(dependent)) { - messages.push(`The package "${dependent}" depends on the ignored package "${ignoredPackage}", but "${dependent}" is not being ignored. Please add "${dependent}" to the \`ignore\` option.`); - } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); } - } - } - } - - const { - snapshot - } = json; - - if (snapshot !== undefined) { - if (snapshot.useCalculatedVersion !== undefined && typeof snapshot.useCalculatedVersion !== "boolean") { - messages.push(`The \`snapshot.useCalculatedVersion\` option is set as ${JSON.stringify(snapshot.useCalculatedVersion, null, 2)} when the only valid values are undefined or a boolean`); } - - if (snapshot.prereleaseTemplate !== undefined && typeof snapshot.prereleaseTemplate !== "string") { - messages.push(`The \`snapshot.prereleaseTemplate\` option is set as ${JSON.stringify(snapshot.prereleaseTemplate, null, 2)} when the only valid values are undefined, or a template string.`); + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); } - } - - if (json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH !== undefined) { - const { - onlyUpdatePeerDependentsWhenOutOfRange, - updateInternalDependents, - useCalculatedVersionForSnapshots - } = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH; - - if (onlyUpdatePeerDependentsWhenOutOfRange !== undefined && typeof onlyUpdatePeerDependentsWhenOutOfRange !== "boolean") { - messages.push(`The \`onlyUpdatePeerDependentsWhenOutOfRange\` option is set as ${JSON.stringify(onlyUpdatePeerDependentsWhenOutOfRange, null, 2)} when the only valid values are undefined or a boolean`); + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); } - - if (updateInternalDependents !== undefined && !["always", "out-of-range"].includes(updateInternalDependents)) { - messages.push(`The \`updateInternalDependents\` option is set as ${JSON.stringify(updateInternalDependents, null, 2)} but can only be 'always' or 'out-of-range'`); + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } + } + return info; } - - if (useCalculatedVersionForSnapshots && useCalculatedVersionForSnapshots !== undefined) { - console.warn(`Experimental flag "useCalculatedVersionForSnapshots" is deprecated since snapshot feature became stable. Please use "snapshot.useCalculatedVersion" instead.`); - - if (typeof useCalculatedVersionForSnapshots !== "boolean") { - messages.push(`The \`useCalculatedVersionForSnapshots\` option is set as ${JSON.stringify(useCalculatedVersionForSnapshots, null, 2)} when the only valid values are undefined or a boolean`); - } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); } - } - - if (messages.length) { - throw new errors.ValidationError(`Some errors occurred when validating the changesets config:\n` + messages.join("\n")); - } - - let config = { - changelog: getNormalizedChangelogOption(json.changelog === undefined ? defaultWrittenConfig.changelog : json.changelog), - access: normalizedAccess === undefined ? defaultWrittenConfig.access : normalizedAccess, - commit: getNormalizedCommitOption(json.commit === undefined ? defaultWrittenConfig.commit : json.commit), - fixed, - linked, - baseBranch: json.baseBranch === undefined ? defaultWrittenConfig.baseBranch : json.baseBranch, - changedFilePatterns: (_json$changedFilePatt = json.changedFilePatterns) !== null && _json$changedFilePatt !== void 0 ? _json$changedFilePatt : ["**"], - updateInternalDependencies: json.updateInternalDependencies === undefined ? defaultWrittenConfig.updateInternalDependencies : json.updateInternalDependencies, - ignore: json.ignore === undefined ? defaultWrittenConfig.ignore : micromatch__default["default"](pkgNames, json.ignore), - bumpVersionsWithWorkspaceProtocolOnly: json.bumpVersionsWithWorkspaceProtocolOnly === true, - snapshot: { - prereleaseTemplate: (_json$snapshot$prerel = (_json$snapshot = json.snapshot) === null || _json$snapshot === void 0 ? void 0 : _json$snapshot.prereleaseTemplate) !== null && _json$snapshot$prerel !== void 0 ? _json$snapshot$prerel : null, - useCalculatedVersion: ((_json$snapshot2 = json.snapshot) === null || _json$snapshot2 === void 0 ? void 0 : _json$snapshot2.useCalculatedVersion) !== undefined ? json.snapshot.useCalculatedVersion : ((_json$___experimental = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH) === null || _json$___experimental === void 0 ? void 0 : _json$___experimental.useCalculatedVersionForSnapshots) !== undefined ? (_json$___experimental2 = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH) === null || _json$___experimental2 === void 0 ? void 0 : _json$___experimental2.useCalculatedVersionForSnapshots : false - }, - ___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH: { - onlyUpdatePeerDependentsWhenOutOfRange: json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH === undefined || json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.onlyUpdatePeerDependentsWhenOutOfRange === undefined ? false : json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH.onlyUpdatePeerDependentsWhenOutOfRange, - updateInternalDependents: (_json$___experimental3 = (_json$___experimental4 = json.___experimentalUnsafeOptions_WILL_CHANGE_IN_PATCH) === null || _json$___experimental4 === void 0 ? void 0 : _json$___experimental4.updateInternalDependents) !== null && _json$___experimental3 !== void 0 ? _json$___experimental3 : "out-of-range" - }, - // TODO consider enabling this by default in the next major version - privatePackages: json.privatePackages === false ? { - tag: false, - version: false - } : json.privatePackages ? { - version: (_json$privatePackages = json.privatePackages.version) !== null && _json$privatePackages !== void 0 ? _json$privatePackages : true, - tag: (_json$privatePackages2 = json.privatePackages.tag) !== null && _json$privatePackages2 !== void 0 ? _json$privatePackages2 : false - } : { - version: true, - tag: false + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; } - }; - - if (config.privatePackages.version === false && config.privatePackages.tag === true) { - throw new errors.ValidationError(`The \`privatePackages.tag\` option is set to \`true\` but \`privatePackages.version\` is set to \`false\`. This is not allowed.`); - } - - return config; -}; -let fakePackage = { - dir: "", - packageJson: { - name: "", - version: "" - } -}; -let defaultConfig = parse(defaultWrittenConfig, { - root: fakePackage, - tool: "root", - packages: [fakePackage] -}); - -exports.defaultConfig = defaultConfig; -exports.defaultWrittenConfig = defaultWrittenConfig; -exports.parse = parse; -exports.read = read; - - -/***/ }), - -/***/ 98296: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var Range = __nccwpck_require__(25287); -var pc = __nccwpck_require__(69397); - -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } - -var Range__default = /*#__PURE__*/_interopDefault(Range); -var pc__default = /*#__PURE__*/_interopDefault(pc); - -// This is a modified version of the graph-getting in bolt -const DEPENDENCY_TYPES = ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]; - -const getAllDependencies = (config, ignoreDevDependencies) => { - const allDependencies = new Map(); - - for (const type of DEPENDENCY_TYPES) { - const deps = config[type]; - if (!deps) continue; - - for (const name of Object.keys(deps)) { - const depRange = deps[name]; - - if (type === "devDependencies" && (ignoreDevDependencies || depRange.startsWith("link:") || depRange.startsWith("file:"))) { - continue; - } - - allDependencies.set(name, depRange); + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if tunneling agent isn't assigned create a new agent + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; } - } - - return allDependencies; -}; - -const isProtocolRange = range => range.indexOf(":") !== -1; - -const getValidRange = potentialRange => { - if (isProtocolRange(potentialRange)) { - return null; - } - - try { - return new Range__default["default"](potentialRange); - } catch (_unused) { - return null; - } -}; - -function getDependencyGraph(packages, { - ignoreDevDependencies = false, - bumpVersionsWithWorkspaceProtocolOnly = false -} = {}) { - const graph = new Map(); - let valid = true; - const packagesByName = { - [packages.root.packageJson.name]: packages.root - }; - const queue = [packages.root]; - - for (const pkg of packages.packages) { - queue.push(pkg); - packagesByName[pkg.packageJson.name] = pkg; - } - - for (const pkg of queue) { - const { - name - } = pkg.packageJson; - const dependencies = []; - const allDependencies = getAllDependencies(pkg.packageJson, ignoreDevDependencies); - - for (let [depName, depRange] of allDependencies) { - const match = packagesByName[depName]; - if (!match) continue; - const expected = match.packageJson.version; - const usesWorkspaceRange = depRange.startsWith("workspace:"); - - if (usesWorkspaceRange) { - depRange = depRange.replace(/^workspace:/, ""); - - if (depRange === "*" || depRange === "^" || depRange === "~") { - dependencies.push(depName); - continue; + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; } - } else if (bumpVersionsWithWorkspaceProtocolOnly) { - continue; - } - - const range = getValidRange(depRange); - - if (range && !range.test(expected) || isProtocolRange(depRange)) { - valid = false; - console.error(`Package ${pc__default["default"].cyan(`"${name}"`)} must depend on the current version of ${pc__default["default"].cyan(`"${depName}"`)}: ${pc__default["default"].green(`"${expected}"`)} vs ${pc__default["default"].red(`"${depRange}"`)}`); - continue; - } // `depRange` could have been a tag and if a tag has been used there might have been a reason for that - // we should not count this as a local monorepro dependant - - - if (!range) { - continue; - } - - dependencies.push(depName); + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `${proxyUrl.username}:${proxyUrl.password}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; } - - graph.set(name, { - pkg, - dependencies - }); - } - - return { - graph, - valid - }; -} - -function getDependentsGraph(packages, opts) { - const graph = new Map(); - const { - graph: dependencyGraph - } = getDependencyGraph(packages, opts); - const dependentsLookup = { - [packages.root.packageJson.name]: { - pkg: packages.root, - dependents: [] + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); } - }; - packages.packages.forEach(pkg => { - dependentsLookup[pkg.packageJson.name] = { - pkg, - dependents: [] - }; - }); - packages.packages.forEach(pkg => { - const dependent = pkg.packageJson.name; - const valFromDependencyGraph = dependencyGraph.get(dependent); - - if (valFromDependencyGraph) { - const dependencies = valFromDependencyGraph.dependencies; - dependencies.forEach(dependency => { - dependentsLookup[dependency].dependents.push(dependent); - }); + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); } - }); - Object.keys(dependentsLookup).forEach(key => { - graph.set(key, dependentsLookup[key]); - }); - const simplifiedDependentsGraph = new Map(); - graph.forEach((pkgInfo, pkgName) => { - simplifiedDependentsGraph.set(pkgName, pkgInfo.dependents); - }); - return simplifiedDependentsGraph; -} - -exports.getDependentsGraph = getDependentsGraph; - - -/***/ }), - -/***/ 95889: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var pc = __nccwpck_require__(69397); -var util = __nccwpck_require__(73837); - -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } - -var pc__default = /*#__PURE__*/_interopDefault(pc); -var util__default = /*#__PURE__*/_interopDefault(util); - -let prefix = "🦋 "; - -function format(args, customPrefix) { - let fullPrefix = prefix + (customPrefix === undefined ? "" : " " + customPrefix); - return fullPrefix + util__default["default"].format("", ...args).split("\n").join("\n" + fullPrefix + " "); -} - -function error(...args) { - console.error(format(args, pc__default["default"].red("error"))); -} -function info(...args) { - console.info(format(args, pc__default["default"].cyan("info"))); -} -function log(...args) { - console.log(format(args)); -} -function success(...args) { - console.log(format(args, pc__default["default"].green("success"))); -} -function warn(...args) { - console.warn(format(args, pc__default["default"].yellow("warn"))); } - -exports.error = error; -exports.info = info; -exports.log = log; -exports.prefix = prefix; -exports.success = success; -exports.warn = warn; - +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map /***/ }), -/***/ 8920: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 11390: +/***/ ((__unused_webpack_module, exports) => { "use strict"; - Object.defineProperty(exports, "__esModule", ({ value: true })); - -var fs = __nccwpck_require__(41621); -var path = __nccwpck_require__(71017); -var getPackages = __nccwpck_require__(54393); -var errors = __nccwpck_require__(76249); - -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } - -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - } - n["default"] = e; - return Object.freeze(n); -} - -var fs__namespace = /*#__PURE__*/_interopNamespace(fs); -var path__default = /*#__PURE__*/_interopDefault(path); - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; } - } - - return target; -} - -async function readPreState(cwd) { - let preStatePath = path__default["default"].resolve(cwd, ".changeset", "pre.json"); // TODO: verify that the pre state isn't broken - - let preState; - - try { - let contents = await fs__namespace.readFile(preStatePath, "utf8"); - - try { - preState = JSON.parse(contents); - } catch (err) { - if (err instanceof SyntaxError) { - console.error("error parsing json:", contents); - } - - throw err; + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + try { + return new URL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new URL(`http://${proxyVar}`); + } } - } catch (err) { - if (err.code !== "ENOENT") { - throw err; + else { + return undefined; } - } - - return preState; -} -async function exitPre(cwd) { - let preStatePath = path__default["default"].resolve(cwd, ".changeset", "pre.json"); // TODO: verify that the pre state isn't broken - - let preState = await readPreState(cwd); - - if (preState === undefined) { - throw new errors.PreExitButNotInPreModeError(); - } - - await fs__namespace.outputFile(preStatePath, JSON.stringify(_objectSpread2(_objectSpread2({}, preState), {}, { - mode: "exit" - }), null, 2) + "\n"); -} -async function enterPre(cwd, tag) { - var _preState$changesets; - - let packages = await getPackages.getPackages(cwd); - let preStatePath = path__default["default"].resolve(packages.root.dir, ".changeset", "pre.json"); - let preState = await readPreState(packages.root.dir); // can't reenter if pre mode still exists, but we should allow exited pre mode to be reentered - - if ((preState === null || preState === void 0 ? void 0 : preState.mode) === "pre") { - throw new errors.PreEnterButInPreModeError(); - } - - let newPreState = { - mode: "pre", - tag, - initialVersions: {}, - changesets: (_preState$changesets = preState === null || preState === void 0 ? void 0 : preState.changesets) !== null && _preState$changesets !== void 0 ? _preState$changesets : [] - }; - - for (let pkg of packages.packages) { - newPreState.initialVersions[pkg.packageJson.name] = pkg.packageJson.version; - } - - await fs__namespace.outputFile(preStatePath, JSON.stringify(newPreState, null, 2) + "\n"); -} - -exports.enterPre = enterPre; -exports.exitPre = exitPre; -exports.readPreState = readPreState; - - -/***/ }), - -/***/ 21980: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var fs = __nccwpck_require__(41621); -var path = __nccwpck_require__(71017); -var parse = __nccwpck_require__(2107); -var git = __nccwpck_require__(23321); -var pc = __nccwpck_require__(69397); -var pFilter = __nccwpck_require__(25073); -var logger = __nccwpck_require__(95889); - -function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } - -function _interopNamespace(e) { - if (e && e.__esModule) return e; - var n = Object.create(null); - if (e) { - Object.keys(e).forEach(function (k) { - if (k !== 'default') { - var d = Object.getOwnPropertyDescriptor(e, k); - Object.defineProperty(n, k, d.get ? d : { - enumerable: true, - get: function () { return e[k]; } - }); - } - }); - } - n["default"] = e; - return Object.freeze(n); -} - -var fs__namespace = /*#__PURE__*/_interopNamespace(fs); -var path__default = /*#__PURE__*/_interopDefault(path); -var parse__default = /*#__PURE__*/_interopDefault(parse); -var git__namespace = /*#__PURE__*/_interopNamespace(git); -var pc__default = /*#__PURE__*/_interopDefault(pc); -var pFilter__default = /*#__PURE__*/_interopDefault(pFilter); - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; } - -function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; -} - -function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; } - } - - return target; -} - -let importantSeparator = pc__default["default"].red("===============================IMPORTANT!==============================="); -let importantEnd = pc__default["default"].red("----------------------------------------------------------------------"); - -async function getOldChangesets(changesetBase, dirs) { - // this needs to support just not dealing with dirs that aren't set up properly - let changesets = await pFilter__default["default"](dirs, async (dir) => (await fs__namespace.lstat(path__default["default"].join(changesetBase, dir))).isDirectory()); - const changesetContents = changesets.map(async changesetDir => { - const jsonPath = path__default["default"].join(changesetBase, changesetDir, "changes.json"); - const [summary, json] = await Promise.all([fs__namespace.readFile(path__default["default"].join(changesetBase, changesetDir, "changes.md"), "utf-8"), fs__namespace.readJson(jsonPath)]); - return { - releases: json.releases, - summary, - id: changesetDir - }; - }); - return Promise.all(changesetContents); -} // this function only exists while we wait for v1 changesets to be obsoleted -// and should be deleted before v3 - - -async function getOldChangesetsAndWarn(changesetBase, dirs) { - let oldChangesets = await getOldChangesets(changesetBase, dirs); - - if (oldChangesets.length === 0) { - return []; - } - - logger.warn(importantSeparator); - logger.warn("There were old changesets from version 1 found"); - logger.warn("These are being applied now but the dependents graph may have changed"); - logger.warn("Make sure you validate all your dependencies"); - logger.warn("In a future major version, we will no longer apply these old changesets, and will instead throw here"); - logger.warn(importantEnd); - return oldChangesets; -} - -async function filterChangesetsSinceRef(changesets, changesetBase, sinceRef) { - const newChangesets = await git__namespace.getChangedChangesetFilesSinceRef({ - cwd: changesetBase, - ref: sinceRef - }); - const newHashes = newChangesets.map(c => c.split("/")[1]); - return changesets.filter(dir => newHashes.includes(dir)); -} - -async function getChangesets(cwd, sinceRef) { - let changesetBase = path__default["default"].join(cwd, ".changeset"); - let contents; - - try { - contents = await fs__namespace["default"].readdir(changesetBase); - } catch (err) { - if (err.code === "ENOENT") { - throw new Error("There is no .changeset directory in this project"); + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); } - - throw err; - } - - if (sinceRef !== undefined) { - contents = await filterChangesetsSinceRef(contents, changesetBase, sinceRef); - } - - let oldChangesetsPromise = getOldChangesetsAndWarn(changesetBase, contents); - let changesets = contents.filter(file => !file.startsWith(".") && file.endsWith(".md") && file !== "README.md"); - const changesetContents = changesets.map(async file => { - const changeset = await fs__namespace["default"].readFile(path__default["default"].join(changesetBase, file), "utf-8"); - return _objectSpread2(_objectSpread2({}, parse__default["default"](changeset)), {}, { - id: file.replace(".md", "") - }); - }); - return [...(await oldChangesetsPromise), ...(await Promise.all(changesetContents))]; + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { + return true; + } + } + return false; } - -exports["default"] = getChangesets; - - -/***/ }), - -/***/ 97589: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function shouldSkipPackage({ - packageJson -}, { - ignore, - allowPrivatePackages -}) { - if (ignore.includes(packageJson.name)) { - return true; - } - - if (packageJson.private && !allowPrivatePackages) { - return true; - } - - return !packageJson.version; +exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); } - -exports.shouldSkipPackage = shouldSkipPackage; - +//# sourceMappingURL=proxy.js.map /***/ }), -/***/ 23321: +/***/ 76249: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -4391,299 +4656,52 @@ exports.shouldSkipPackage = shouldSkipPackage; Object.defineProperty(exports, "__esModule", ({ value: true })); -var spawn = __nccwpck_require__(54081); -var fs = __nccwpck_require__(57147); -var path = __nccwpck_require__(71017); -var getPackages = __nccwpck_require__(54393); -var errors = __nccwpck_require__(76249); -var isSubdir = __nccwpck_require__(63093); -var micromatch = __nccwpck_require__(39015); +var ExtendableError = __nccwpck_require__(53868); function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; } -var spawn__default = /*#__PURE__*/_interopDefault(spawn); -var fs__default = /*#__PURE__*/_interopDefault(fs); -var path__default = /*#__PURE__*/_interopDefault(path); -var isSubdir__default = /*#__PURE__*/_interopDefault(isSubdir); -var micromatch__default = /*#__PURE__*/_interopDefault(micromatch); - -async function add(pathToFile, cwd) { - const gitCmd = await spawn__default["default"]("git", ["add", pathToFile], { - cwd - }); +var ExtendableError__default = /*#__PURE__*/_interopDefault(ExtendableError); - if (gitCmd.code !== 0) { - console.log(pathToFile, gitCmd.stderr.toString()); +class GitError extends ExtendableError__default["default"] { + constructor(code, message) { + super(`${message}, exit code: ${code}`); + this.code = code; } - return gitCmd.code === 0; -} -async function commit(message, cwd) { - const gitCmd = await spawn__default["default"]("git", ["commit", "-m", message, "--allow-empty"], { - cwd - }); - return gitCmd.code === 0; } -async function getAllTags(cwd) { - const gitCmd = await spawn__default["default"]("git", ["tag"], { - cwd - }); - - if (gitCmd.code !== 0) { - throw new Error(gitCmd.stderr.toString()); - } - - const tags = gitCmd.stdout.toString().trim().split("\n"); - return new Set(tags); -} // used to create a single tag at a time for the current head only - -async function tag(tagStr, cwd) { - // NOTE: it's important we use the -m flag to create annotated tag otherwise 'git push --follow-tags' won't actually push - // the tags - const gitCmd = await spawn__default["default"]("git", ["tag", tagStr, "-m", tagStr], { - cwd - }); - return gitCmd.code === 0; -} // Find the commit where we diverged from `ref` at using `git merge-base` - -async function getDivergedCommit(cwd, ref) { - const cmd = await spawn__default["default"]("git", ["merge-base", ref, "HEAD"], { - cwd - }); - - if (cmd.code !== 0) { - throw new Error(`Failed to find where HEAD diverged from ${ref}. Does ${ref} exist?`); +class ValidationError extends ExtendableError__default["default"] {} +class ExitError extends ExtendableError__default["default"] { + constructor(code) { + super(`The process exited with code: ${code}`); + this.code = code; } - return cmd.stdout.toString().trim(); -} -/** - * Get the SHAs for the commits that added files, including automatically - * extending a shallow clone if necessary to determine any commits. - * @param gitPaths - Paths to fetch - * @param options - `cwd` and `short` - */ - -async function getCommitsThatAddFiles(gitPaths, { - cwd, - short = false -}) { - // Maps gitPath to commit SHA - const map = new Map(); // Paths we haven't completed processing on yet - - let remaining = gitPaths; - - do { - // Fetch commit information for all paths we don't have yet - const commitInfos = await Promise.all(remaining.map(async gitPath => { - const [commitSha, parentSha] = (await spawn__default["default"]("git", ["log", "--diff-filter=A", "--max-count=1", short ? "--pretty=format:%h:%p" : "--pretty=format:%H:%p", gitPath], { - cwd - })).stdout.toString().split(":"); - return { - path: gitPath, - commitSha, - parentSha - }; - })); // To collect commits without parents (usually because they're absent from - // a shallow clone). - - let commitsWithMissingParents = []; - - for (const info of commitInfos) { - if (info.commitSha) { - if (info.parentSha) { - // We have found the parent of the commit that added the file. - // Therefore we know that the commit is legitimate and isn't simply the boundary of a shallow clone. - map.set(info.path, info.commitSha); - } else { - commitsWithMissingParents.push(info); - } - } - } - - if (commitsWithMissingParents.length === 0) { - break; - } // The commits we've found may be the real commits or they may be the boundary of - // a shallow clone. - // Can we deepen the clone? - - - if (await isRepoShallow({ - cwd - })) { - // Yes. - await deepenCloneBy({ - by: 50, - cwd - }); - remaining = commitsWithMissingParents.map(p => p.path); - } else { - // It's not a shallow clone, so all the commit SHAs we have are legitimate. - for (const unresolved of commitsWithMissingParents) { - map.set(unresolved.path, unresolved.commitSha); - } - - break; - } - } while (true); - - return gitPaths.map(p => map.get(p)); -} -async function isRepoShallow({ - cwd -}) { - const isShallowRepoOutput = (await spawn__default["default"]("git", ["rev-parse", "--is-shallow-repository"], { - cwd - })).stdout.toString().trim(); - - if (isShallowRepoOutput === "--is-shallow-repository") { - // We have an old version of Git (<2.15) which doesn't support `rev-parse --is-shallow-repository` - // In that case, we'll test for the existence of .git/shallow. - // Firstly, find the .git folder for the repo; note that this will be relative to the repo dir - const gitDir = (await spawn__default["default"]("git", ["rev-parse", "--git-dir"], { - cwd - })).stdout.toString().trim(); - const fullGitDir = path__default["default"].resolve(cwd, gitDir); // Check for the existence of /shallow - - return fs__default["default"].existsSync(path__default["default"].join(fullGitDir, "shallow")); - } else { - // We have a newer Git which supports `rev-parse --is-shallow-repository`. We'll use - // the output of that instead of messing with .git/shallow in case that changes in the future. - return isShallowRepoOutput === "true"; - } -} -async function deepenCloneBy({ - by, - cwd -}) { - await spawn__default["default"]("git", ["fetch", `--deepen=${by}`], { - cwd - }); } - -async function getRepoRoot({ - cwd -}) { - const { - stdout, - code, - stderr - } = await spawn__default["default"]("git", ["rev-parse", "--show-toplevel"], { - cwd - }); - - if (code !== 0) { - throw new Error(stderr.toString()); +class PreExitButNotInPreModeError extends ExtendableError__default["default"] { + constructor() { + super("pre mode cannot be exited when not in pre mode"); } - return stdout.toString().trim().replace(/\n|\r/g, ""); } - -async function getChangedFilesSince({ - cwd, - ref, - fullPath = false -}) { - const divergedAt = await getDivergedCommit(cwd, ref); // Now we can find which files we added - - const cmd = await spawn__default["default"]("git", ["diff", "--name-only", divergedAt], { - cwd - }); - - if (cmd.code !== 0) { - throw new Error(`Failed to diff against ${divergedAt}. Is ${divergedAt} a valid ref?`); +class PreEnterButInPreModeError extends ExtendableError__default["default"] { + constructor() { + super("pre mode cannot be entered when in pre mode"); } - const files = cmd.stdout.toString().trim().split("\n").filter(a => a); - if (!fullPath) return files; - const repoRoot = await getRepoRoot({ - cwd - }); - return files.map(file => path__default["default"].resolve(repoRoot, file)); -} // below are less generic functions that we use in combination with other things we are doing - -async function getChangedChangesetFilesSinceRef({ - cwd, - ref -}) { - try { - const divergedAt = await getDivergedCommit(cwd, ref); // Now we can find which files we added - - const cmd = await spawn__default["default"]("git", ["diff", "--name-only", "--diff-filter=d", divergedAt], { - cwd - }); - let tester = /.changeset\/[^/]+\.md$/; - const files = cmd.stdout.toString().trim().split("\n").filter(file => tester.test(file)); - return files; - } catch (err) { - if (err instanceof errors.GitError) return []; - throw err; - } } -async function getChangedPackagesSinceRef({ - cwd, - ref, - changedFilePatterns = ["**"] -}) { - const changedFiles = await getChangedFilesSince({ - ref, - cwd, - fullPath: true - }); - return [...(await getPackages.getPackages(cwd)).packages] // sort packages by length of dir, so that we can check for subdirs first - .sort((pkgA, pkgB) => pkgB.dir.length - pkgA.dir.length).filter(pkg => { - const changedPackageFiles = []; - - for (let i = changedFiles.length - 1; i >= 0; i--) { - const file = changedFiles[i]; - - if (isSubdir__default["default"](pkg.dir, file)) { - changedFiles.splice(i, 1); - const relativeFile = file.slice(pkg.dir.length + 1); - changedPackageFiles.push(relativeFile); - } - } +class InternalError extends ExtendableError__default["default"] { + constructor(message) { + super(message); + } - return changedPackageFiles.length > 0 && micromatch__default["default"](changedPackageFiles, changedFilePatterns).length > 0; - }); -} -async function tagExists(tagStr, cwd) { - const gitCmd = await spawn__default["default"]("git", ["tag", "-l", tagStr], { - cwd - }); - const output = gitCmd.stdout.toString().trim(); - const tagExists = !!output; - return tagExists; -} -async function getCurrentCommitId({ - cwd, - short = false -}) { - return (await spawn__default["default"]("git", ["rev-parse", short && "--short", "HEAD"].filter(Boolean), { - cwd - })).stdout.toString().trim(); -} -async function remoteTagExists(tagStr) { - const gitCmd = await spawn__default["default"]("git", ["ls-remote", "--tags", "origin", "-l", tagStr]); - const output = gitCmd.stdout.toString().trim(); - const tagExists = !!output; - return tagExists; } -exports.add = add; -exports.commit = commit; -exports.deepenCloneBy = deepenCloneBy; -exports.getAllTags = getAllTags; -exports.getChangedChangesetFilesSinceRef = getChangedChangesetFilesSinceRef; -exports.getChangedFilesSince = getChangedFilesSince; -exports.getChangedPackagesSinceRef = getChangedPackagesSinceRef; -exports.getCommitsThatAddFiles = getCommitsThatAddFiles; -exports.getCurrentCommitId = getCurrentCommitId; -exports.getDivergedCommit = getDivergedCommit; -exports.isRepoShallow = isRepoShallow; -exports.remoteTagExists = remoteTagExists; -exports.tag = tag; -exports.tagExists = tagExists; +exports.ExitError = ExitError; +exports.GitError = GitError; +exports.InternalError = InternalError; +exports.PreEnterButInPreModeError = PreEnterButInPreModeError; +exports.PreExitButNotInPreModeError = PreExitButNotInPreModeError; +exports.ValidationError = ValidationError; /***/ }), @@ -37752,98 +37770,6 @@ exports.isDirectorySync = isTypeSync.bind(null, 'statSync', 'isDirectory'); exports.isSymlinkSync = isTypeSync.bind(null, 'lstatSync', 'isSymbolicLink'); -/***/ }), - -/***/ 69397: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -let argv = process.argv || [], - env = process.env -let isColorSupported = - !("NO_COLOR" in env || argv.includes("--no-color")) && - ("FORCE_COLOR" in env || - argv.includes("--color") || - process.platform === "win32" || - (require != null && (__nccwpck_require__(76224).isatty)(1) && env.TERM !== "dumb") || - "CI" in env) - -let formatter = - (open, close, replace = open) => - input => { - let string = "" + input - let index = string.indexOf(close, open.length) - return ~index - ? open + replaceClose(string, close, replace, index) + close - : open + string + close - } - -let replaceClose = (string, close, replace, index) => { - let result = "" - let cursor = 0 - do { - result += string.substring(cursor, index) + replace - cursor = index + close.length - index = string.indexOf(close, cursor) - } while (~index) - return result + string.substring(cursor) -} - -let createColors = (enabled = isColorSupported) => { - let init = enabled ? formatter : () => String - return { - isColorSupported: enabled, - reset: init("\x1b[0m", "\x1b[0m"), - bold: init("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), - dim: init("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), - italic: init("\x1b[3m", "\x1b[23m"), - underline: init("\x1b[4m", "\x1b[24m"), - inverse: init("\x1b[7m", "\x1b[27m"), - hidden: init("\x1b[8m", "\x1b[28m"), - strikethrough: init("\x1b[9m", "\x1b[29m"), - - black: init("\x1b[30m", "\x1b[39m"), - red: init("\x1b[31m", "\x1b[39m"), - green: init("\x1b[32m", "\x1b[39m"), - yellow: init("\x1b[33m", "\x1b[39m"), - blue: init("\x1b[34m", "\x1b[39m"), - magenta: init("\x1b[35m", "\x1b[39m"), - cyan: init("\x1b[36m", "\x1b[39m"), - white: init("\x1b[37m", "\x1b[39m"), - gray: init("\x1b[90m", "\x1b[39m"), - - bgBlack: init("\x1b[40m", "\x1b[49m"), - bgRed: init("\x1b[41m", "\x1b[49m"), - bgGreen: init("\x1b[42m", "\x1b[49m"), - bgYellow: init("\x1b[43m", "\x1b[49m"), - bgBlue: init("\x1b[44m", "\x1b[49m"), - bgMagenta: init("\x1b[45m", "\x1b[49m"), - bgCyan: init("\x1b[46m", "\x1b[49m"), - bgWhite: init("\x1b[47m", "\x1b[49m"), - - blackBright: init("\x1b[90m", "\x1b[39m"), - redBright: init("\x1b[91m", "\x1b[39m"), - greenBright: init("\x1b[92m", "\x1b[39m"), - yellowBright: init("\x1b[93m", "\x1b[39m"), - blueBright: init("\x1b[94m", "\x1b[39m"), - magentaBright: init("\x1b[95m", "\x1b[39m"), - cyanBright: init("\x1b[96m", "\x1b[39m"), - whiteBright: init("\x1b[97m", "\x1b[39m"), - - bgBlackBright: init("\x1b[100m","\x1b[49m"), - bgRedBright: init("\x1b[101m","\x1b[49m"), - bgGreenBright: init("\x1b[102m","\x1b[49m"), - bgYellowBright: init("\x1b[103m","\x1b[49m"), - bgBlueBright: init("\x1b[104m","\x1b[49m"), - bgMagentaBright: init("\x1b[105m","\x1b[49m"), - bgCyanBright: init("\x1b[106m","\x1b[49m"), - bgWhiteBright: init("\x1b[107m","\x1b[49m"), - } -} - -module.exports = createColors() -module.exports.createColors = createColors - - /***/ }), /***/ 9138: @@ -89123,12 +89049,57 @@ module.exports = {"version":"3.14.2"}; /******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = __dirname + "/"; /******/ /************************************************************************/ -/******/ -/******/ // startup -/******/ // Load entry module and return exports -/******/ // This entry module is referenced by other modules so it can't be inlined -/******/ var __webpack_exports__ = __nccwpck_require__(8865); -/******/ module.exports = __webpack_exports__; -/******/ +var __webpack_exports__ = {}; +// This entry need to be wrapped in an IIFE because it need to be in strict mode. +(() => { +"use strict"; +var exports = __webpack_exports__; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* eslint-disable jsdoc/require-jsdoc */ +const path_1 = __nccwpck_require__(71017); +const util_1 = __nccwpck_require__(76786); +const core_1 = __nccwpck_require__(37117); +const execa_1 = __nccwpck_require__(30580); +const git_1 = __nccwpck_require__(69674); +const util_2 = __nccwpck_require__(50914); +async function bump() { + // before bump + const version = await (0, util_2.getNextVersion)(); + process.env.NEXT_PACKAGE_VERSION = version; + const beforeBumpScript = (0, core_1.getInput)('before-bump'); + if (beforeBumpScript) { + (0, execa_1.command)(beforeBumpScript); + } + await updateRootPackageJson(version); + // TODO: what if I use pnpm? either pass the command or package manager? + (0, execa_1.command)('yarn changeset version'); + // after bump + const afterBumpScript = (0, core_1.getInput)('after-bump'); + if (afterBumpScript) { + (0, execa_1.command)(afterBumpScript); + } + await commitAndTag(version).catch(err => { + (0, core_1.error)(err); + process.exit(1); + }); +} +async function updateRootPackageJson(version) { + await (0, util_2.transformFile)((0, path_1.resolve)('package.json'), packageJson => (0, util_1.formatJson)({ + ...JSON.parse(packageJson), + version: `${version}` + })); +} +async function commitAndTag(version) { + const cwd = process.cwd(); + await (0, git_1.add)('-A', cwd); + await (0, git_1.commit)(`v${version}`, cwd); + await (0, git_1.tag)(`v${version}`, cwd); +} +bump(); + +})(); + +module.exports = __webpack_exports__; /******/ })() ; \ No newline at end of file diff --git a/build-packages/changesets-fixed-version-bump/index.ts b/build-packages/changesets-fixed-version-bump/index.ts index 8254a32095..70ebf0db91 100644 --- a/build-packages/changesets-fixed-version-bump/index.ts +++ b/build-packages/changesets-fixed-version-bump/index.ts @@ -2,7 +2,7 @@ import { resolve } from 'path'; import { formatJson } from '@sap-cloud-sdk/util'; import { getInput, error } from '@actions/core'; -import execa, { command } from 'execa'; +import { command } from 'execa'; import { add, commit, tag } from '@changesets/git'; import { transformFile, getNextVersion } from './util'; @@ -17,7 +17,7 @@ async function bump() { await updateRootPackageJson(version); // TODO: what if I use pnpm? either pass the command or package manager? - execa('yarn changeset version'); + command('yarn changeset version'); // after bump const afterBumpScript = getInput('after-bump');