first commit

This commit is contained in:
2025-10-26 23:10:15 +08:00
commit 8f0345b7be
14961 changed files with 2356381 additions and 0 deletions

21
node_modules/release-it/LICENSE generated vendored Normal file
View File

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

461
node_modules/release-it/README.md generated vendored Normal file
View File

@@ -0,0 +1,461 @@
# Release It! 🚀
🚀 Generic CLI tool to automate versioning and package publishing-related tasks:
<img align="right" src="./docs/assets/release-it.svg?raw=true" height="280" />
- Bump version (in e.g. `package.json`)
- [Git commit, tag, push][1]
- Execute any (test or build) commands using [hooks][2]
- [Create release at GitHub][3] or [GitLab][4]
- [Generate changelog][5]
- [Publish to npm][6]
- [Manage pre-releases][7]
- Extend with [plugins][8]
- Release from any [CI/CD environment][9]
Use release-it for version management and publish to anywhere with its versatile configuration, a powerful plugin
system, and hooks to execute any command you need to test, build, and/or publish your project.
[![Action Status][11]][10] [![npm version][13]][12]
Are you using release-it at work? Please consider [sponsoring me][14]!
## Installation
Although release-it is a **generic** release tool, most projects use it for projects with npm packages. The recommended
way to install release-it uses npm and adds some minimal configuration to get started:
```bash
npm init release-it
```
Alternatively, install it manually, and add the `release` script to `package.json`:
```bash
npm install -D release-it
```
```json
{
"name": "my-package",
"version": "1.0.0",
"scripts": {
"release": "release-it"
},
"devDependencies": {
"release-it": "^19.0.0"
}
}
```
## Usage
Run release-it from the root of the project using either `npm run` or `npx`:
```bash
npm run release
npx release-it
```
You will be prompted to select the new version, and more prompts will follow based on your configuration.
## Yarn & pnpm
- Using Yarn? Please see the [npm section on Yarn][15].
- Using pnpm? Please see [release-it-pnpm][16].
## Monorepos
Using a monorepo? Please see this [monorepo recipe][17].
## Global Installation
Per-project installation as shown above is recommended, but global installs are supported as well:
- From npm: `npm install -g release-it`
- From Homebrew: `brew install release-it`
## Containerized
Use [Release It! - Containerized][18] to run it in any environment as a standardized container without the need for a
Node environment. Thanks [Juan Carlos][19]!
## Videos, articles & examples
Here's a list of interesting external resources:
- Video: [How to use GitHub Actions & Release-It to Easily Release Your Code][20]
- Article: [Monorepo Semantic Releases][21] ([repo][22])
Want to add yours to the list? Just open a pull request!
## Configuration
Out of the box, release-it has sane defaults, and [plenty of options][23] to configure it. Most projects use a
`.release-it.json` file in the project root, or a `release-it` property in `package.json`.
Here's a quick example `.release-it.json`:
```json
{
"$schema": "https://unpkg.com/release-it@19/schema/release-it.json",
"git": {
"commitMessage": "chore: release v${version}"
},
"github": {
"release": true
}
}
```
→ See [Configuration][24] for more details.
## Interactive vs. CI mode
By default, release-it is **interactive** and allows you to confirm each task before execution:
<img src="./docs/assets/release-it-interactive.gif?raw=true" height="290" />
By using the `--ci` option, the process is fully automated without prompts. The configured tasks will be executed as
demonstrated in the first animation above. In a Continuous Integration (CI) environment, this non-interactive mode is
activated automatically.
Use `--only-version` to use a prompt only to determine the version, and automate the rest.
## Latest version
How does release-it determine the latest version?
1. For projects with a `package.json`, its `version` will be used (see [npm][25] to skip this).
2. Otherwise, release-it uses the latest Git tag to determine which version should be released.
3. As a last resort, `0.0.0` will be used as the latest version.
Alternatively, a plugin can be used to override this (e.g. to manage a `VERSION` or `composer.json` file):
- [@release-it/bumper][26] to read from or bump the version in any file
- [@release-it/conventional-changelog][27] to get a recommended bump based on commit messages
- [release-it-calver-plugin][28] to use CalVer (Calendar Versioning)
Add the `--release-version` flag to print the **next** version without releasing anything.
## Git
Git projects are supported well by release-it, automating the tasks to stage, commit, tag and push releases to any Git
remote.
→ See [Git][29] for more details.
## npmjs.com Releases
As of July 2025, GitHub and GitLab CI workflows can now use npm's [Trusted Publishing][30] OpenID Connect (OIDC)
integration for secure, token-free publishing from CI/CD. This eliminates long-lived tokens and automatically generates
provenance attestations. See [docs/npm.md][31] for details.
## GitHub Releases
GitHub projects can have releases attached to Git tags, containing release notes and assets. There are two ways to add
[GitHub releases][32] in your release-it flow:
1. Automated (requires a `GITHUB_TOKEN`)
2. Manual (using the GitHub web interface with pre-populated fields)
→ See [GitHub Releases][33] for more details.
## GitLab Releases
GitLab projects can have releases attached to Git tags, containing release notes and assets. To automate [GitLab
releases][34]:
- Configure `gitlab.release: true`
- Obtain a [personal access token][35] (release-it needs the `api` and `self_rotate` scopes).
- Make sure the token is [available as an environment variable][36].
→ See [GitLab Releases][37] for more details.
## Changelog
By default, release-it generates a changelog, to show and help select a version for the new release. Additionally, this
changelog serves as the release notes for the GitHub or GitLab release.
The [default command][23] is based on `git log ...`. This setting (`git.changelog`) can be overridden. To further
customize the release notes for the GitHub or GitLab release, there's `github.releaseNotes` or `gitlab.releaseNotes`.
Make sure any of these commands output the changelog to `stdout`. Note that release-it by default is agnostic to commit
message conventions. Plugins are available for:
- GitHub and GitLab Releases
- auto-changelog
- Conventional Changelog
- Keep A Changelog
- git-cliff
To print the changelog without releasing anything, add the `--changelog` flag.
→ See [Changelog][38] for more details.
## Publish to npm
With a `package.json` in the current directory, release-it will let `npm` bump the version in `package.json` (and
`package-lock.json` if present), and publish to the npm registry.
→ See [Publish to npm][25] for more details.
## Manage pre-releases
With release-it, it's easy to create pre-releases: a version of your software that you want to make available, while
it's not in the stable semver range yet. Often "alpha", "beta", and "rc" (release candidate) are used as identifiers for
pre-releases. An example pre-release version is `2.0.0-beta.0`.
→ See [Manage pre-releases][39] for more details.
## Update or re-run existing releases
Use `--no-increment` to not increment the last version, but update the last existing tag/version.
This may be helpful in cases where the version was already incremented. Here are a few example scenarios:
- To update or publish a (draft) GitHub Release for an existing Git tag.
- Publishing to npm succeeded, but pushing the Git tag to the remote failed. Then use
`release-it --no-increment --no-npm` to skip the `npm publish` and try pushing the same Git tag again.
## Hooks
Use script hooks to run shell commands at any moment during the release process (such as `before:init` or
`after:release`).
The format is `[prefix]:[hook]` or `[prefix]:[plugin]:[hook]`:
| part | value |
| ------ | ------------------------------------------- |
| prefix | `before` or `after` |
| plugin | `version`, `git`, `npm`, `github`, `gitlab` |
| hook | `init`, `bump`, `release` |
Use the optional `:plugin` part in the middle to hook into a life cycle method exactly before or after any plugin.
The core plugins include `version`, `git`, `npm`, `github`, `gitlab`.
Note that hooks like `after:git:release` will not run when either the `git push` failed, or when it is configured not to
be executed (e.g. `git.push: false`). See [execution order][40] for more details on execution order of plugin lifecycle
methods.
All commands can use configuration variables (like template strings). An array of commands can also be provided, they
will run one after another. Some example release-it configuration:
```json
{
"hooks": {
"before:init": ["npm run lint", "npm test"],
"after:my-plugin:bump": "./bin/my-script.sh",
"after:bump": "npm run build",
"after:git:release": "echo After git push, before github release",
"after:release": "echo Successfully released ${name} v${version} to ${repo.repository}."
}
}
```
The variables can be found in the [default configuration][23]. Additionally, the following variables are exposed:
```text
version
latestVersion
changelog
name
repo.remote, repo.protocol, repo.host, repo.owner, repo.repository, repo.project
branchName
releaseUrl
```
All variables are available in all hooks. The only exception is that the additional variables listed above are not yet
available in the `init` hook.
Use `--verbose` to log the output of the commands.
For the sake of verbosity, the full list of hooks is actually: `init`, `beforeBump`, `bump`, `beforeRelease`, `release`
or `afterRelease`. However, hooks like `before:beforeRelease` look weird and are usually not useful in practice.
Note that arguments need to be quoted properly when used from the command line:
```bash
release-it --'hooks.after:release="echo Successfully released ${name} v${version} to ${repo.repository}."'
```
Using Inquirer.js inside custom hook scripts might cause issues (since release-it also uses this itself).
## Dry Runs
Use `--dry-run` to show the interactivity and the commands it _would_ execute.
→ See [Dry Runs][41] for more details.
## Troubleshooting & debugging
- With `release-it --verbose` (or `-V`), release-it prints the output of every user-defined [hook][2].
- With `release-it -VV`, release-it also prints the output of every internal command.
- Use `NODE_DEBUG=release-it:* release-it [...]` to print configuration and more error details.
Use `verbose: 2` in a configuration file to have the equivalent of `-VV` on the command line.
## Plugins
Since v11, release-it can be extended in many, many ways. Here are some plugins:
| Plugin | Description |
| ----------------------------------------- | ------------------------------------------------------------------------------------------- |
| [@release-it/bumper][26] | Read & write the version from/to any file |
| [@release-it/conventional-changelog][27] | Provides recommended bump, conventional-changelog, and updates `CHANGELOG.md` |
| [@release-it/keep-a-changelog][42] | Maintain CHANGELOG.md using the Keep a Changelog standards |
| [@release-it-plugins/lerna-changelog][43] | Integrates lerna-changelog into the release-it pipeline |
| [@jcamp-code/release-it-changelogen][44] | Use [@unjs/changelogen][45] for versioning and changelog |
| [@release-it-plugins/workspaces][46] | Releases each of your projects configured workspaces |
| [release-it-calver-plugin][28] | Enables Calendar Versioning (calver) with release-it |
| [@grupoboticario/news-fragments][47] | An easy way to generate your changelog file |
| [@j-ulrich/release-it-regex-bumper][48] | Regular expression based version read/write plugin for release-it |
| [@jcamp-code/release-it-dotnet][49] | Use .csproj or .props file for versioning, automate NuGet publishing |
| [release-it-pnpm][16] | Add basic support for pnpm workspaces, integrates with [bumpp][50] and [changelogithub][51] |
| [changesets-release-it-plugin][52] | Combine [Changesets][53] changelog management with release-it |
| [release-it-gitea][54] | Gitea plugin to create Gitea releases and upload attachments |
Internally, release-it uses its own plugin architecture (for Git, GitHub, GitLab, npm).
→ See all [release-it plugins on npm][55].
→ See [plugins][56] for documentation to write plugins.
## Use release-it programmatically
While mostly used as a CLI tool, release-it can be used as a dependency to integrate in your own scripts. See [use
release-it programmatically][57] for example code.
## Projects using release-it
- [AdonisJs][58]
- [Axios][59]
- [Chakra UI][60]
- [Halo][61]
- [hosts][62]
- [js-cookie][63]
- [jQuery][64]
- [Madge][65]
- [Metalsmith][66]
- [n8n][67]
- [Node-Redis][68]
- [React Native Paper][69]
- [Readability.js][70]
- [Redux][71]
- [Saleor][72]
- [Semantic UI React][73]
- [tabler-icons][74]
- Swagger ([swagger-ui][75] + [swagger-editor][76])
- [Repositories that depend on release-it][77]
- GitHub search for [path:\*\*/.release-it.json][78]
## Node.js version support
The latest major version is v19, supporting Node.js 20 and up:
| release-it | Node.js |
| :--------: | :-----: |
| v19 | v20 |
| v18 | v20 |
| v17 | v18 |
| v16 | v16 |
| v15 | v14 |
Also see [CHANGELOG.md][79] for dates and details.
## Links
- See [CHANGELOG.md][79] for major/breaking updates, and [releases][80] for a detailed version history.
- To **contribute**, please read [CONTRIBUTING.md][81] first.
- Please [open an issue][82] if anything is missing or unclear in this documentation.
## License
[MIT][83]
Are you using release-it at work? Please consider [sponsoring me][14]!
[1]: #git
[2]: #hooks
[3]: #github-releases
[4]: #gitlab-releases
[5]: #changelog
[6]: #publish-to-npm
[7]: #manage-pre-releases
[8]: #plugins
[9]: ./docs/ci.md
[10]: https://github.com/release-it/release-it/actions
[11]: https://github.com/release-it/release-it/workflows/Cross-OS%20Tests/badge.svg
[12]: https://www.npmjs.com/package/release-it
[13]: https://badge.fury.io/js/release-it.svg
[14]: https://github.com/sponsors/webpro
[15]: ./docs/npm.md#yarn
[16]: https://github.com/hyoban/release-it-pnpm
[17]: ./docs/recipes/monorepo.md
[18]: https://github.com/juancarlosjr97/release-it-containerized
[19]: https://github.com/juancarlosjr97
[20]: https://www.youtube.com/watch?v=7pBcuT7j_A0
[21]: https://medium.com/valtech-ch/monorepo-semantic-releases-db114811efa5
[22]: https://github.com/b12k/monorepo-semantic-releases
[23]: ./config/release-it.json
[24]: ./docs/configuration.md
[25]: ./docs/npm.md
[26]: https://github.com/release-it/bumper
[27]: https://github.com/release-it/conventional-changelog
[28]: https://github.com/casmith/release-it-calver-plugin
[29]: ./docs/git.md
[30]: https://docs.npmjs.com/trusted-publishers
[31]: ./docs/npm.md#trusted-publishing-oidc
[32]: https://docs.github.com/en/repositories/releasing-projects-on-github/about-releases
[33]: ./docs/github-releases.md
[34]: https://docs.gitlab.com/api/releases/
[35]: https://gitlab.com/profile/personal_access_tokens
[36]: ./docs/environment-variables.md
[37]: ./docs/gitlab-releases.md
[38]: ./docs/changelog.md
[39]: ./docs/pre-releases.md
[40]: ./docs/plugins.md#execution-order
[41]: ./docs/dry-runs.md
[42]: https://github.com/release-it/keep-a-changelog
[43]: https://github.com/release-it-plugins/lerna-changelog
[44]: https://github.com/jcamp-code/release-it-changelogen
[45]: https://github.com/unjs/changelogen
[46]: https://github.com/release-it-plugins/workspaces
[47]: https://github.com/grupoboticario/news-fragments
[48]: https://github.com/j-ulrich/release-it-regex-bumper
[49]: https://github.com/jcamp-code/release-it-dotnet
[50]: https://github.com/antfu/bumpp
[51]: https://github.com/antfu/changelogithub
[52]: https://www.npmjs.com/package/changesets-release-it-plugin
[53]: https://github.com/changesets/changesets
[54]: https://github.com/lib-pack/release-it-gitea
[55]: https://www.npmjs.com/search?q=keywords:release-it-plugin
[56]: ./docs/plugins.md
[57]: ./docs/recipes/programmatic.md
[58]: https://github.com/adonisjs/core
[59]: https://github.com/axios/axios
[60]: https://github.com/chakra-ui/chakra-ui
[61]: https://github.com/halo-dev/halo
[62]: https://github.com/StevenBlack/hosts
[63]: https://github.com/js-cookie/js-cookie
[64]: https://github.com/jquery/jquery
[65]: https://github.com/pahen/madge
[66]: https://github.com/metalsmith/metalsmith
[67]: https://github.com/n8n-io/n8n
[68]: https://github.com/redis/node-redis
[69]: https://github.com/callstack/react-native-paper
[70]: https://github.com/mozilla/readability
[71]: https://github.com/reduxjs/redux
[72]: https://github.com/saleor/saleor
[73]: https://github.com/Semantic-Org/Semantic-UI-React
[74]: https://github.com/tabler/tabler-icons
[75]: https://github.com/swagger-api/swagger-ui
[76]: https://github.com/swagger-api/swagger-editor
[77]: https://github.com/release-it/release-it/network/dependents
[78]: https://github.com/search?q=path%3A**%2F.release-it.json&type=code
[79]: ./CHANGELOG.md
[80]: https://github.com/release-it/release-it/releases
[81]: ./.github/CONTRIBUTING.md
[82]: https://github.com/release-it/release-it/issues/new
[83]: ./LICENSE

11
node_modules/release-it/bin/release-it.js generated vendored Executable file
View File

@@ -0,0 +1,11 @@
#!/usr/bin/env node
import release from '../lib/cli.js';
import { parseCliArguments } from '../lib/args.js';
const options = parseCliArguments([].slice.call(process.argv, 2));
release(options).then(
() => process.exit(0),
({ code }) => process.exit(Number.isInteger(code) ? code : 1)
);

74
node_modules/release-it/config/release-it.json generated vendored Normal file
View File

@@ -0,0 +1,74 @@
{
"hooks": {},
"git": {
"changelog": "git log --pretty=format:\"* %s (%h)\" ${from}...${to}",
"requireCleanWorkingDir": true,
"requireBranch": false,
"requireUpstream": true,
"requireCommits": false,
"requireCommitsFail": true,
"commitsPath": "",
"addUntrackedFiles": false,
"commit": true,
"commitMessage": "Release ${version}",
"commitArgs": [],
"tag": true,
"tagExclude": null,
"tagName": null,
"tagMatch": null,
"getLatestTagFromAllRefs": false,
"tagAnnotation": "Release ${version}",
"tagArgs": [],
"push": true,
"pushArgs": ["--follow-tags"],
"pushRepo": ""
},
"npm": {
"publish": true,
"publishPath": ".",
"publishArgs": [],
"tag": null,
"otp": null,
"ignoreVersion": false,
"allowSameVersion": false,
"versionArgs": [],
"skipChecks": false,
"timeout": 10
},
"github": {
"release": false,
"releaseName": "Release ${version}",
"releaseNotes": null,
"autoGenerate": false,
"preRelease": false,
"draft": false,
"tokenRef": "GITHUB_TOKEN",
"assets": null,
"host": null,
"timeout": 0,
"proxy": null,
"skipChecks": false,
"web": false,
"comments": {
"submit": false,
"issue": ":rocket: _This issue has been resolved in v${version}. See [${releaseName}](${releaseUrl}) for release notes._",
"pr": ":rocket: _This pull request is included in v${version}. See [${releaseName}](${releaseUrl}) for release notes._"
}
},
"gitlab": {
"release": false,
"releaseName": "Release ${version}",
"releaseNotes": null,
"milestones": [],
"tokenRef": "GITLAB_TOKEN",
"tokenHeader": "Private-Token",
"certificateAuthorityFile": null,
"secure": false,
"assets": null,
"useIdsForUrls": false,
"useGenericPackageRepositoryForAssets": false,
"genericPackageRepositoryName": "release-it",
"origin": null,
"skipChecks": false
}
}

64
node_modules/release-it/lib/args.js generated vendored Normal file
View File

@@ -0,0 +1,64 @@
import parseArgs from 'yargs-parser';
const aliases = {
c: 'config',
d: 'dry-run',
h: 'help',
i: 'increment',
v: 'version',
V: 'verbose'
};
const booleanOptions = [
'dry-run',
'ci',
'git',
'npm',
'github',
'gitlab',
'git.addUntrackedFiles',
'git.requireCleanWorkingDir',
'git.requireUpstream',
'git.requireCommits',
'git.requireCommitsFail',
'git.commit',
'git.tag',
'git.push',
'git.getLatestTagFromAllRefs',
'git.skipChecks',
'github.release',
'github.autoGenerate',
'github.preRelease',
'github.draft',
'github.skipChecks',
'github.web',
'github.comments.submit',
'gitlab.release',
'gitlab.autoGenerate',
'gitlab.preRelease',
'gitlab.draft',
'gitlab.useIdsForUrls',
'gitlab.useGenericPackageRepositoryForAssets',
'gitlab.skipChecks',
'npm.publish',
'npm.ignoreVersion',
'npm.allowSameVersion',
'npm.skipChecks'
];
export const parseCliArguments = args => {
const options = parseArgs(args, {
boolean: booleanOptions,
alias: aliases,
configuration: {
'parse-numbers': false,
'camel-case-expansion': false
}
});
if (options.V) {
options.verbose = typeof options.V === 'boolean' ? options.V : options.V.length;
delete options.V;
}
options.increment = options._[0] || options.i;
return options;
};

41
node_modules/release-it/lib/cli.js generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import { readJSON } from './util.js';
import runTasks from './index.js';
const pkg = readJSON(new URL('../package.json', import.meta.url));
const helpText = `Release It! v${pkg.version}
Usage: release-it <increment> [options]
Use e.g. "release-it minor" directly as shorthand for "release-it --increment=minor".
-c --config Path to local configuration options [default: ".release-it.json"]
-d --dry-run Do not touch or write anything, but show the commands
-h --help Print this help
-i --increment Increment "major", "minor", "patch", or "pre*" version; or specify version [default: "patch"]
--ci No prompts, no user interaction; activated automatically in CI environments
--only-version Prompt only for version, no further interaction
-v --version Print release-it version number
--release-version Print version number to be released
--changelog Print changelog for the version to be released
-V --verbose Verbose output (user hooks output)
-VV Extra verbose output (also internal commands output)
For more details, please see https://github.com/release-it/release-it`;
/** @internal */
export const version = () => console.log(`v${pkg.version}`);
/** @internal */
export const help = () => console.log(helpText);
export default async options => {
if (options.version) {
version();
} else if (options.help) {
help();
} else {
return runTasks(options);
}
return Promise.resolve();
};

181
node_modules/release-it/lib/config.js generated vendored Normal file
View File

@@ -0,0 +1,181 @@
import util from 'node:util';
import assert from 'node:assert';
import { isCI } from 'ci-info';
import defaultsDeep from '@nodeutils/defaults-deep';
import { isObjectStrict } from '@phun-ky/typeof';
import merge from 'lodash.merge';
import { loadConfig as loadC12 } from 'c12';
import { get, getSystemInfo, readJSON } from './util.js';
const debug = util.debug('release-it:config');
const defaultConfig = readJSON(new URL('../config/release-it.json', import.meta.url));
class Config {
constructor(config = {}) {
this.constructorConfig = config;
this.contextOptions = {};
debug({ system: getSystemInfo() });
}
async init() {
await loadOptions(this.constructorConfig).then(({ options, localConfig }) => {
this._options = options;
this._localConfig = localConfig;
debug(this._options);
});
}
getContext(path) {
const context = merge({}, this.options, this.contextOptions);
return path ? get(context, path) : context;
}
setContext(options) {
debug(options);
merge(this.contextOptions, options);
}
setCI(value = true) {
this.options.ci = value;
}
get defaultConfig() {
return defaultConfig;
}
get isDryRun() {
return Boolean(this.options['dry-run']);
}
get isIncrement() {
return this.options.increment !== false;
}
get isVerbose() {
return Boolean(this.options.verbose);
}
get verbosityLevel() {
return this.options.verbose;
}
get isDebug() {
return debug.enabled;
}
get isCI() {
return Boolean(this.options.ci) || this.isReleaseVersion || this.isChangelog;
}
get isPromptOnlyVersion() {
return this.options['only-version'];
}
get isReleaseVersion() {
return Boolean(this.options['release-version']);
}
get isChangelog() {
return Boolean(this.options['changelog']);
}
get options() {
assert(this._options, `The "options" not resolve yet`);
return this._options;
}
get localConfig() {
assert(this._localConfig, `The "localConfig" not resolve yet`);
return this._localConfig;
}
}
async function loadOptions(constructorConfig) {
const localConfig = await loadLocalConfig(constructorConfig);
const merged = defaultsDeep(
{},
constructorConfig,
{
ci: isCI
},
localConfig,
defaultConfig
);
const expanded = expandPreReleaseShorthand(merged);
return {
options: expanded,
localConfig
};
}
function expandPreReleaseShorthand(options) {
const { increment, preRelease, preReleaseId, snapshot, preReleaseBase } = options;
const isPreRelease = Boolean(preRelease) || Boolean(snapshot);
const inc = snapshot ? 'prerelease' : increment;
const preId = typeof preRelease === 'string' ? preRelease : typeof snapshot === 'string' ? snapshot : preReleaseId;
options.version = {
increment: inc,
isPreRelease,
preReleaseId: preId,
preReleaseBase
};
if (typeof snapshot === 'string' && options.git) {
// Pre set and hard code some options
options.git.tagMatch = `0.0.0-${snapshot}.[0-9]*`;
options.git.getLatestTagFromAllRefs = true;
options.git.requireBranch = '!main';
options.git.requireUpstream = false;
options.npm.ignoreVersion = true;
}
return options;
}
async function loadLocalConfig(constructorConfig) {
const file = resolveFile();
const dir = resolveDir();
const extend = resolveExtend();
const defaultConfig = resolveDefaultConfig();
if (file === false) return {};
const resolvedConfig = await loadC12({
name: 'release-it',
configFile: file,
packageJson: true,
rcFile: false,
envName: false,
cwd: dir,
extend,
defaultConfig
}).catch(() => {
throw new Error(`Invalid configuration file at ${file}`);
});
debug('Loaded local config', resolvedConfig.config);
return isObjectStrict(resolvedConfig.config) ? resolvedConfig.config : {};
function resolveFile() {
if (constructorConfig.config === false) return false;
if (constructorConfig.config === true) return '.release-it';
return constructorConfig.config ?? '.release-it';
}
function resolveDir() {
return constructorConfig.configDir ?? process.cwd();
}
function resolveExtend() {
return constructorConfig.extends === false ? false : undefined;
}
function resolveDefaultConfig() {
return {
extends: constructorConfig.extends === false ? undefined : constructorConfig.extends
};
}
}
export default Config;

163
node_modules/release-it/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,163 @@
import { getPlugins } from './plugin/factory.js';
import Logger from './log.js';
import Config from './config.js';
import Shell from './shell.js';
import Prompt from './prompt.js';
import Spinner from './spinner.js';
import { reduceUntil, parseVersion, castArray } from './util.js';
const runTasks = async (opts, di) => {
let container = {};
try {
Object.assign(container, di);
container.config = container.config || new Config(opts);
await container.config.init();
const { config } = container;
const { isCI, isVerbose, verbosityLevel, isDryRun, isChangelog, isReleaseVersion } = config;
container.log = container.log || new Logger({ isCI, isVerbose, verbosityLevel, isDryRun });
container.spinner = container.spinner || new Spinner({ container, config });
container.prompt = container.prompt || new Prompt({ container: { config } });
container.shell = container.shell || new Shell({ container });
const { log, shell, spinner } = container;
const options = config.getContext();
const { hooks } = options;
const runHook = async (...name) => {
const scripts = hooks[name.join(':')];
if (!scripts || !scripts.length) return;
const context = config.getContext();
const external = true;
for (const script of castArray(scripts)) {
const task = () => shell.exec(script, { external }, context);
await spinner.show({ task, label: script, context, external });
}
};
const runLifeCycleHook = async (plugin, name, ...args) => {
if (plugin === plugins.at(0)) await runHook('before', name);
await runHook('before', plugin.namespace, name);
const willHookRun = (await plugin[name](...args)) !== false;
if (willHookRun) {
await runHook('after', plugin.namespace, name);
}
if (plugin === plugins.at(-1)) await runHook('after', name);
};
const [internal, external] = await getPlugins(config, container);
let plugins = [...external, ...internal];
for (const plugin of plugins) {
await runLifeCycleHook(plugin, 'init');
}
const { increment, isPreRelease, preReleaseId, preReleaseBase } = options.version;
const name = await reduceUntil(plugins, plugin => plugin.getName());
const latestVersion = (await reduceUntil(plugins, plugin => plugin.getLatestVersion())) || '0.0.0';
const changelog = await reduceUntil(plugins, plugin => plugin.getChangelog(latestVersion));
if (isChangelog) {
if (changelog) {
console.log(changelog);
process.exit(0);
} else {
log.warn('No changelog found');
process.exit(1);
}
}
const incrementBase = { latestVersion, increment, isPreRelease, preReleaseId, preReleaseBase };
const { snapshot } = config.options;
if (snapshot && (!incrementBase.latestVersion.startsWith('0.0.0') || incrementBase.latestVersion === '0.0.0')) {
// Reading the latest version first allows to increment the final counter, fake it if it's not a snapshot:
incrementBase.latestVersion = `0.0.0-0`;
}
let version;
if (config.isIncrement) {
incrementBase.increment = await reduceUntil(plugins, plugin => plugin.getIncrement(incrementBase));
version = await reduceUntil(plugins, plugin => plugin.getIncrementedVersionCI(incrementBase));
} else {
version = latestVersion;
}
config.setContext({ name, latestVersion, version, changelog });
if (!isReleaseVersion) {
const action = config.isIncrement ? 'release' : 'update';
const suffix = version && config.isIncrement ? `${latestVersion}...${version}` : `currently at ${latestVersion}`;
log.obtrusive(`🚀 Let's ${action} ${name} (${suffix})`);
log.preview({ title: 'changelog', text: changelog });
}
if (config.isIncrement) {
version = version || (await reduceUntil(plugins, plugin => plugin.getIncrementedVersion(incrementBase)));
}
if (isReleaseVersion) {
if (version) {
console.log(version);
process.exit(0);
} else {
log.warn(`No new version to release`);
process.exit(1);
}
}
if (version) {
config.setContext(parseVersion(version));
if (config.isPromptOnlyVersion) {
config.setCI(true);
}
for (const hook of ['beforeBump', 'bump', 'beforeRelease']) {
for (const plugin of plugins) {
const args = hook === 'bump' ? [version] : [];
await runLifeCycleHook(plugin, hook, ...args);
}
}
plugins = [...internal, ...external];
for (const hook of ['release', 'afterRelease']) {
for (const plugin of plugins) {
await runLifeCycleHook(plugin, hook);
}
}
} else {
log.obtrusive(`No new version to release`);
}
log.log(`🏁 Done (in ${Math.floor(process.uptime())}s.)`);
return {
name,
changelog,
latestVersion,
version
};
} catch (err) {
const { log } = container;
const errorMessage = err.message || err;
const logger = log || console;
err.cause === 'INFO' ? logger.info(errorMessage) : logger.error(errorMessage);
throw err;
}
};
export default runTasks;
export { default as Config } from './config.js';
export { default as Plugin } from './plugin/Plugin.js';

70
node_modules/release-it/lib/log.js generated vendored Normal file
View File

@@ -0,0 +1,70 @@
import { EOL } from 'node:os';
import { styleText } from 'node:util';
import { isObjectLoose } from '@phun-ky/typeof';
import { upperFirst } from './util.js';
class Logger {
constructor({ isCI = true, isVerbose = false, verbosityLevel = 0, isDryRun = false } = {}) {
this.isCI = isCI;
this.isVerbose = isVerbose;
this.verbosityLevel = verbosityLevel;
this.isDryRun = isDryRun;
}
shouldLog(isExternal) {
return this.verbosityLevel === 2 || (this.isVerbose && isExternal);
}
log(...args) {
console.log(...args);
}
error(...args) {
console.error([styleText('red', 'ERROR'), ...args].join(' '));
}
info(...args) {
console.error(styleText('grey', args.join(' ')));
}
warn(...args) {
console.error([styleText('yellow', 'WARNING'), ...args].join(' '));
}
verbose(...args) {
const { isExternal } = isObjectLoose(args.at(-1)) ? args.at(-1) : {};
if (this.shouldLog(isExternal)) {
console.error(...args.filter(str => typeof str === 'string'));
}
}
exec(...args) {
const { isDryRun: isExecutedInDryRun, isExternal, isCached } = isObjectLoose(args.at(-1)) ? args.at(-1) : {};
if (this.shouldLog(isExternal) || this.isDryRun) {
const prefix = isExecutedInDryRun == null ? '$' : '!';
const command = args
.map(cmd => (typeof cmd === 'string' ? cmd : Array.isArray(cmd) ? cmd.join(' ') : ''))
.join(' ');
const message = [prefix, command, isCached ? '[cached]' : ''].join(' ').trim();
console.error(message);
}
}
obtrusive(...args) {
if (!this.isCI) this.log();
this.log(...args);
if (!this.isCI) this.log();
}
preview({ title, text }) {
if (text) {
const header = styleText('bold', upperFirst(title));
const body = text.replace(new RegExp(EOL + EOL, 'g'), EOL);
this.obtrusive(`${header}:${EOL}${body}`);
} else {
this.obtrusive(`Empty ${title.toLowerCase()}`);
}
}
}
export default Logger;

126
node_modules/release-it/lib/plugin/GitBase.js generated vendored Normal file
View File

@@ -0,0 +1,126 @@
import { EOL } from 'node:os';
import { format, parseGitUrl } from '../util.js';
import Plugin from './Plugin.js';
const options = { write: false };
const changelogFallback = 'git log --pretty=format:"* %s (%h)"';
class GitBase extends Plugin {
async init() {
const remoteUrl = await this.getRemoteUrl();
await this.fetch(remoteUrl);
const branchName = await this.getBranchName();
const repo = parseGitUrl(remoteUrl);
this.setContext({ remoteUrl, branchName, repo });
this.config.setContext({ remoteUrl, branchName, repo });
const latestTag = await this.getLatestTagName();
const secondLatestTag = !this.config.isIncrement ? await this.getSecondLatestTagName(latestTag) : null;
const tagTemplate = this.options.tagName || ((latestTag || '').match(/^v/) ? 'v${version}' : '${version}');
this.config.setContext({ latestTag, secondLatestTag, tagTemplate });
}
getName() {
const repo = this.getContext('repo');
return repo.project;
}
getLatestVersion() {
const { tagTemplate, latestTag } = this.config.getContext();
const prefix = format(tagTemplate.replace(/\$\{version\}/, ''), this.config.getContext());
return latestTag ? latestTag.replace(prefix, '').replace(/^v/, '') : null;
}
async getChangelog() {
const { snapshot } = this.config.getContext();
const { latestTag, secondLatestTag } = this.config.getContext();
const context = { latestTag, from: latestTag, to: 'HEAD' };
const { changelog } = this.options;
if (!changelog) return null;
if (latestTag && !this.config.isIncrement) {
context.from = secondLatestTag;
context.to = `${latestTag}^1`;
}
// For now, snapshots do not get a changelog, as it often goes haywire (easy to add to release manually)
if (snapshot) return '';
if (!context.from && changelog.includes('${from}')) {
return this.exec(changelogFallback);
}
return this.exec(changelog, { context, options });
}
bump(version) {
const { tagTemplate } = this.config.getContext();
const context = Object.assign(this.config.getContext(), { version });
const tagName = format(tagTemplate, context) || version;
this.setContext({ version });
this.config.setContext({ tagName });
}
isRemoteName(remoteUrlOrName) {
return remoteUrlOrName && !remoteUrlOrName.includes('/');
}
async getRemoteUrl() {
const remoteNameOrUrl = this.options.pushRepo || (await this.getRemote()) || 'origin';
return this.isRemoteName(remoteNameOrUrl)
? this.exec(`git remote get-url ${remoteNameOrUrl}`, { options }).catch(() =>
this.exec(`git config --get remote.${remoteNameOrUrl}.url`, { options }).catch(() => null)
)
: remoteNameOrUrl;
}
async getRemote() {
const branchName = await this.getBranchName();
return branchName ? await this.getRemoteForBranch(branchName) : null;
}
getBranchName() {
return this.exec('git rev-parse --abbrev-ref HEAD', { options }).catch(() => null);
}
getRemoteForBranch(branch) {
return this.exec(`git config --get branch.${branch}.remote`, { options }).catch(() => null);
}
fetch(remoteUrl) {
return this.exec('git fetch').catch(err => {
this.debug(err);
throw new Error(`Unable to fetch from ${remoteUrl}${EOL}${err.message}`);
});
}
getLatestTagName() {
const context = Object.assign({}, this.config.getContext(), { version: '*' });
const match = format(this.options.tagMatch || this.options.tagName || '${version}', context);
const exclude = this.options.tagExclude ? ` --exclude=${format(this.options.tagExclude, context)}` : '';
if (this.options.getLatestTagFromAllRefs) {
return this.exec(
`git -c "versionsort.suffix=-" for-each-ref --count=1 --sort=-v:refname --format="%(refname:short)" refs/tags/${match}`,
{ options }
).then(
stdout => stdout || null,
() => null
);
} else {
return this.exec(`git describe --tags --match=${match} --abbrev=0${exclude}`, { options }).then(
stdout => stdout || null,
() => null
);
}
}
async getSecondLatestTagName(latestTag) {
const sha = await this.exec(`git rev-list ${latestTag || '--skip=1'} --tags --max-count=1`, {
options
});
return this.exec(`git describe --tags --abbrev=0 "${sha}^"`, { options }).catch(() => null);
}
}
export default GitBase;

65
node_modules/release-it/lib/plugin/GitRelease.js generated vendored Normal file
View File

@@ -0,0 +1,65 @@
import { pick, readJSON } from '../util.js';
import GitBase from './GitBase.js';
const defaultConfig = readJSON(new URL('../../config/release-it.json', import.meta.url));
class GitRelease extends GitBase {
static isEnabled(options) {
return options.release;
}
getInitialOptions(options) {
const baseOptions = super.getInitialOptions(...arguments);
const git = options.git || defaultConfig.git;
const gitOptions = pick(git, [
'tagExclude',
'tagName',
'tagMatch',
'getLatestTagFromAllRefs',
'pushRepo',
'changelog',
'commit'
]);
return Object.assign({}, gitOptions, baseOptions);
}
get token() {
const { tokenRef } = this.options;
return process.env[tokenRef] || null;
}
async beforeRelease() {
const { releaseNotes: script } = this.options;
const { changelog } = this.config.getContext();
const releaseNotes =
typeof script === 'function' || typeof script === 'string' ? await this.processReleaseNotes(script) : changelog;
this.setContext({ releaseNotes });
if (releaseNotes !== changelog) {
this.log.preview({ title: 'release notes', text: releaseNotes });
}
}
async processReleaseNotes(script) {
if (typeof script === 'function') {
const ctx = Object.assign({}, this.config.getContext(), { [this.namespace]: this.getContext() });
return script(ctx);
}
if (typeof script === 'string') {
return this.exec(script);
}
}
afterRelease() {
const { isReleased, releaseUrl, discussionUrl } = this.getContext();
if (isReleased) {
this.log.log(`🔗 ${releaseUrl}`);
}
if (discussionUrl) {
this.log.log(`🔗 ${discussionUrl}`);
}
}
}
export default GitRelease;

75
node_modules/release-it/lib/plugin/Plugin.js generated vendored Normal file
View File

@@ -0,0 +1,75 @@
import { debug } from 'node:util';
import merge from 'lodash.merge';
import { get } from '../util.js';
class Plugin {
static isEnabled() {
return true;
}
static disablePlugin() {
return null;
}
constructor({ namespace, options = {}, container = {} } = {}) {
this.namespace = namespace;
this.options = Object.freeze(this.getInitialOptions(options, namespace));
this.context = {};
this.config = container.config;
this.log = container.log;
this.shell = container.shell;
this.spinner = container.spinner;
this.prompt = container.prompt;
this.debug = debug(`release-it:${namespace}`);
}
getInitialOptions(options, namespace) {
return options[namespace] || {};
}
init() {}
getName() {}
getLatestVersion() {}
getChangelog() {}
getIncrement() {}
getIncrementedVersionCI() {}
getIncrementedVersion() {}
beforeBump() {}
bump() {}
beforeRelease() {}
release() {}
afterRelease() {}
getContext(path) {
const context = merge({}, this.options, this.context);
return path ? get(context, path) : context;
}
setContext(context) {
merge(this.context, context);
}
exec(command, { options, context = {} } = {}) {
const ctx = Object.assign(context, this.config.getContext(), { [this.namespace]: this.getContext() });
return this.shell.exec(command, options, ctx);
}
registerPrompts(prompts) {
this.prompt.register(prompts, this.namespace);
}
async showPrompt(options) {
options.namespace = this.namespace;
return this.prompt.show(options);
}
step(options) {
const context = Object.assign({}, this.config.getContext(), { [this.namespace]: this.getContext() });
const opts = Object.assign({}, options, { context });
const isException = this.config.isPromptOnlyVersion && ['incrementList', 'publish', 'otp'].includes(opts.prompt);
return this.config.isCI && !isException ? this.spinner.show(opts) : this.showPrompt(opts);
}
}
export default Plugin;

89
node_modules/release-it/lib/plugin/factory.js generated vendored Normal file
View File

@@ -0,0 +1,89 @@
import url from 'node:url';
import path from 'node:path';
import util from 'node:util';
import { createRequire } from 'node:module';
import { castArray } from '../util.js';
import Version from './version/Version.js';
import Git from './git/Git.js';
import GitLab from './gitlab/GitLab.js';
import GitHub from './github/GitHub.js';
import npm from './npm/npm.js';
const debug = util.debug('release-it:plugins');
const pluginNames = ['npm', 'git', 'github', 'gitlab', 'version'];
const plugins = {
version: Version,
git: Git,
gitlab: GitLab,
github: GitHub,
npm: npm
};
const load = async pluginName => {
let plugin = null;
try {
const module = await import(pluginName);
plugin = module.default;
} catch (err) {
debug(err);
try {
const module = await import(path.join(process.cwd(), pluginName));
plugin = module.default;
} catch (err) {
debug(err);
// In some cases or tests we might need to support legacy `require.resolve`
const require = createRequire(process.cwd());
const module = await import(url.pathToFileURL(require.resolve(pluginName, { paths: [process.cwd()] })));
plugin = module.default;
}
}
return [getPluginName(pluginName), plugin];
};
/** @internal */
export const getPluginName = pluginName => {
if (pluginName.startsWith('.')) {
return path.parse(pluginName).name;
}
return pluginName;
};
export let getPlugins = async (config, container) => {
const context = config.getContext();
const disabledPlugins = [];
const enabledExternalPlugins = [];
if (context.plugins) {
for (const [pluginName, pluginConfig] of Object.entries(context.plugins)) {
const [name, Plugin] = await load(pluginName);
const [namespace, options] = pluginConfig.length === 2 ? pluginConfig : [name, pluginConfig];
config.setContext({ [namespace]: options });
if (await Plugin.isEnabled(options)) {
const instance = new Plugin({ namespace, options: config.getContext(), container });
debug({ namespace, options: instance.options });
enabledExternalPlugins.push(instance);
disabledPlugins.push(...pluginNames.filter(p => castArray(Plugin.disablePlugin(options)).includes(p)));
}
}
}
const enabledPlugins = await pluginNames.reduce(async (result, plugin) => {
if (plugin in plugins && !disabledPlugins.includes(plugin)) {
const Plugin = plugins[plugin];
const pluginOptions = context[plugin];
if (await Plugin.isEnabled(pluginOptions)) {
const instance = new Plugin({ namespace: plugin, options: context, container });
debug({ namespace: plugin, options: instance.options });
(await result).push(instance);
}
}
return result;
}, []);
return [enabledPlugins, enabledExternalPlugins];
};

242
node_modules/release-it/lib/plugin/git/Git.js generated vendored Normal file
View File

@@ -0,0 +1,242 @@
import { EOL } from 'node:os';
import { spawn } from 'node:child_process';
import matcher from 'wildcard-match';
import { format, e, fixArgs, once, castArray } from '../../util.js';
import GitBase from '../GitBase.js';
import prompts from './prompts.js';
const noop = Promise.resolve();
const invalidPushRepoRe = /^\S+@/;
const options = { write: false };
const docs = 'https://git.io/release-it-git';
async function isGitRepo() {
return await new Promise(resolve => {
const process = spawn('git', ['rev-parse', '--git-dir']);
process.on('close', code => resolve(code === 0));
process.on('error', () => resolve(false));
});
}
class Git extends GitBase {
constructor(...args) {
super(...args);
this.registerPrompts(prompts);
}
static async isEnabled(options) {
return options !== false && (await isGitRepo());
}
async init() {
if (this.options.requireBranch && !(await this.isRequiredBranch(this.options.requireBranch))) {
throw e(`Must be on branch ${this.options.requireBranch}`, docs);
}
if (this.options.requireCleanWorkingDir && !(await this.isWorkingDirClean())) {
throw e(`Working dir must be clean.${EOL}Please stage and commit your changes.`, docs);
}
await super.init();
const remoteUrl = this.getContext('remoteUrl');
if (this.options.push && !remoteUrl) {
throw e(`Could not get remote Git url.${EOL}Please add a remote repository.`, docs);
}
if (this.options.requireUpstream && !(await this.hasUpstreamBranch())) {
throw e(`No upstream configured for current branch.${EOL}Please set an upstream branch.`, docs);
}
if (this.options.requireCommits && (await this.getCommitsSinceLatestTag(this.options.commitsPath)) === 0) {
throw e(`There are no commits since the latest tag.`, docs, this.options.requireCommitsFail);
}
}
rollback() {
this.log.info('Rolling back changes...');
const { tagName } = this.config.getContext();
const { isCommitted, isTagged } = this.getContext();
if (isTagged) {
this.log.info(`Deleting local tag ${tagName}`);
this.exec(`git tag --delete ${tagName}`);
}
this.log.info(`Resetting local changes made`);
this.exec(`git reset --hard HEAD${isCommitted ? '~1' : ''}`);
}
enableRollback() {
this.rollbackOnce = once(this.rollback.bind(this));
process.on('SIGINT', this.rollbackOnce);
process.on('exit', this.rollbackOnce);
}
disableRollback() {
if (this.rollbackOnce) {
process.removeListener('SIGINT', this.rollbackOnce);
process.removeListener('exit', this.rollbackOnce);
}
}
async beforeRelease() {
if (this.options.commit) {
if (this.options.requireCleanWorkingDir) {
this.enableRollback();
}
const changeSet = await this.status();
this.log.preview({ title: 'changeset', text: changeSet });
await this.stageDir();
}
}
async release() {
const { commit, tag, push } = this.options;
await this.step({ enabled: commit, task: () => this.commit(), label: 'Git commit', prompt: 'commit' });
await this.step({ enabled: tag, task: () => this.tag(), label: 'Git tag', prompt: 'tag' });
return !!(await this.step({ enabled: push, task: () => this.push(), label: 'Git push', prompt: 'push' }));
}
async isRequiredBranch() {
const branch = await this.getBranchName();
const requiredBranches = castArray(this.options.requireBranch);
const [branches, negated] = requiredBranches.reduce(
([p, n], b) => (b.startsWith('!') ? [p, [...n, b.slice(1)]] : [[...p, b], n]),
[[], []]
);
return (
(branches.length > 0 ? matcher(branches)(branch) : true) &&
(negated.length > 0 ? !matcher(negated)(branch) : true)
);
}
async hasUpstreamBranch() {
const ref = await this.exec('git symbolic-ref HEAD', { options });
const branch = await this.exec(`git for-each-ref --format="%(upstream:short)" ${ref}`, { options }).catch(
() => null
);
return Boolean(branch);
}
tagExists(tag) {
return this.exec(`git show-ref --tags --quiet --verify -- refs/tags/${tag}`, { options }).then(
() => true,
() => false
);
}
isWorkingDirClean() {
return this.exec('git diff --quiet HEAD', { options }).then(
() => true,
() => false
);
}
async getCommitsSinceLatestTag(commitsPath = '') {
const latestTagName = await this.getLatestTagName();
const ref = latestTagName ? `${latestTagName}..HEAD` : 'HEAD';
return this.exec(`git rev-list ${ref} --count ${commitsPath ? `-- ${commitsPath}` : ''}`, { options }).then(Number);
}
async getUpstreamArgs(pushRepo) {
if (pushRepo && !this.isRemoteName(pushRepo)) {
// Use (only) `pushRepo` if it's configured and looks like a url
return [pushRepo];
} else if (!(await this.hasUpstreamBranch())) {
// Start tracking upstream branch (`pushRepo` is a name if set)
return ['--set-upstream', pushRepo || 'origin', await this.getBranchName()];
} else if (pushRepo && !invalidPushRepoRe.test(pushRepo)) {
return [pushRepo];
} else {
return [];
}
}
stage(file) {
if (!file || !file.length) return noop;
const files = castArray(file);
return this.exec(['git', 'add', ...files]).catch(err => {
this.log.warn(`Could not stage ${files}`);
this.debug(err);
});
}
stageDir({ baseDir = '.' } = {}) {
const { addUntrackedFiles } = this.options;
return this.exec(['git', 'add', baseDir, addUntrackedFiles ? '--all' : '--update']);
}
reset(file) {
const files = castArray(file);
return this.exec(['git', 'checkout', 'HEAD', '--', ...files]).catch(err => {
this.log.warn(`Could not reset ${files}`);
this.debug(err);
});
}
status() {
return this.exec('git status --short --untracked-files=no', { options }).catch(() => null);
}
commit({ message = this.options.commitMessage, args = this.options.commitArgs } = {}) {
const msg = format(message, this.config.getContext());
const commitMessageArgs = msg ? ['--message', msg] : [];
return this.exec(['git', 'commit', ...commitMessageArgs, ...fixArgs(args)]).then(
() => this.setContext({ isCommitted: true }),
err => {
this.debug(err);
if (/nothing (added )?to commit/.test(err) || /nichts zu committen/.test(err)) {
this.log.warn('No changes to commit. The latest commit will be tagged.');
} else {
throw new Error(err);
}
}
);
}
tag({ name, annotation = this.options.tagAnnotation, args = this.options.tagArgs } = {}) {
const message = format(annotation, this.config.getContext());
const tagName = name || this.config.getContext('tagName');
return this.exec(['git', 'tag', '--annotate', '--message', message, ...fixArgs(args), tagName])
.then(() => this.setContext({ isTagged: true }))
.catch(err => {
const { latestTag, tagName } = this.config.getContext();
if (/tag '.+' already exists/.test(err) && latestTag === tagName) {
this.log.warn(`Tag "${tagName}" already exists`);
} else {
throw err;
}
});
}
async push({ args = this.options.pushArgs } = {}) {
const { pushRepo } = this.options;
const upstreamArgs = await this.getUpstreamArgs(pushRepo);
try {
const push = await this.exec(['git', 'push', ...fixArgs(args), ...upstreamArgs]);
this.disableRollback();
return push;
} catch (error) {
try {
await this.rollbackTagPush();
} catch (tagError) {
this.log.warn(`An error was encountered when trying to rollback the tag on the remote: ${tagError.message}`);
}
throw error;
}
}
async rollbackTagPush() {
const { isTagged } = this.getContext();
if (isTagged) {
const { tagName } = this.config.getContext();
this.log.info(`Rolling back remote tag push ${tagName}`);
await this.exec(`git push origin --delete ${tagName}`);
}
}
afterRelease() {
this.disableRollback();
}
}
export default Git;

19
node_modules/release-it/lib/plugin/git/prompts.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
import { format, truncateLines } from '../../util.js';
export default {
commit: {
type: 'confirm',
message: context => `Commit (${truncateLines(format(context.git.commitMessage, context), 1, ' [...]')})?`,
default: true
},
tag: {
type: 'confirm',
message: context => `Tag (${format(context.tagName, context)})?`,
default: true
},
push: {
type: 'confirm',
message: () => 'Push?',
default: true
}
};

471
node_modules/release-it/lib/plugin/github/GitHub.js generated vendored Normal file
View File

@@ -0,0 +1,471 @@
import { createReadStream, statSync } from 'node:fs';
import path from 'node:path';
import open from 'open';
import { Octokit } from '@octokit/rest';
import { glob } from 'tinyglobby';
import mime from 'mime-types';
import retry from 'async-retry';
import newGithubReleaseUrl from 'new-github-release-url';
import { ProxyAgent } from 'proxy-agent';
import { format, parseVersion, readJSON, e, castArray } from '../../util.js';
import Release from '../GitRelease.js';
import prompts from './prompts.js';
import { getCommitsFromChangelog, getResolvedIssuesFromChangelog, searchQueries } from './util.js';
/**
* @typedef {import('@octokit/rest').RestEndpointMethodTypes['repos']['createRelease']['parameters']} CreateReleaseOptions
*/
const pkg = readJSON(new URL('../../../package.json', import.meta.url));
const docs = 'https://git.io/release-it-github';
const RETRY_CODES = [408, 413, 429, 500, 502, 503, 504, 521, 522, 524];
const DEFAULT_RETRY_MIN_TIMEOUT = 1000;
const parseErrormsg = err => {
let msg = err;
if (err instanceof Error) {
const { status, message } = err;
const headers = err.response ? err.response.headers : {};
msg = `${headers?.status || status} (${message})`;
}
return msg;
};
const truncateBody = body => {
// https://github.com/release-it/release-it/issues/965
if (body && body.length >= 124000) return body.substring(0, 124000) + '...';
return body;
};
class GitHub extends Release {
constructor(...args) {
super(...args);
this.registerPrompts(prompts);
}
async init() {
await super.init();
const { skipChecks, tokenRef, web, update, assets } = this.options;
if (!this.token || web) {
if (!web) {
this.log.warn(`Environment variable "${tokenRef}" is required for automated GitHub Releases.`);
this.log.warn('Falling back to web-based GitHub Release.');
}
this.setContext({ isWeb: true });
return;
}
if (web && assets) {
this.log.warn('Assets are not included in web-based releases.');
}
if (!skipChecks) {
// If we're running on GitHub Actions, we can skip the authentication and
// collaborator checks. Ref: https://bit.ly/2vsyRzu
if (process.env.GITHUB_ACTIONS) {
this.setContext({ username: process.env.GITHUB_ACTOR });
} else {
if (!(await this.isAuthenticated())) {
throw e(`Could not authenticate with GitHub using environment variable "${tokenRef}".`, docs);
}
if (!(await this.isCollaborator())) {
const { repository } = this.getContext('repo');
const { username } = this.getContext();
throw e(`User ${username} is not a collaborator for ${repository}.`, docs);
}
}
}
if (update) {
const { latestTag } = this.config.getContext();
try {
const { id, upload_url, tag_name } = await this.getLatestRelease();
if (latestTag === tag_name) {
this.setContext({ isUpdate: true, isReleased: true, releaseId: id, upload_url });
} else {
this.setContext({ isUpdate: false });
}
} catch (error) {
this.setContext({ isUpdate: false });
}
if (!this.getContext('isUpdate')) {
this.log.warn(`GitHub release for tag ${latestTag} was not found. Creating new release.`);
}
}
}
async isAuthenticated() {
if (this.config.isDryRun) return true;
try {
this.log.verbose('octokit users#getAuthenticated');
const { data } = await this.client.users.getAuthenticated();
this.setContext({ username: data.login });
return true;
} catch (err) {
this.debug(err);
return false;
}
}
async isCollaborator() {
if (this.config.isDryRun) return true;
const { owner, project: repo } = this.getContext('repo');
const { username } = this.getContext();
try {
const options = { owner, repo, username };
this.log.verbose(`octokit repos#checkCollaborator (${username})`);
await this.client.repos.checkCollaborator(options);
return true;
} catch (err) {
this.debug(err);
return false;
}
}
async release() {
const { assets } = this.options;
const { isWeb, isUpdate } = this.getContext();
const { isCI } = this.config;
const type = isUpdate ? 'update' : 'create';
const publishMethod = `${type}Release`;
if (isWeb) {
const task = () => this.createWebRelease();
return this.step({ task, label: 'Generating link to GitHub Release web interface', prompt: 'release' });
} else if (isCI) {
await this.step({ task: () => this[publishMethod](), label: `GitHub ${type} release` });
await this.step({ enabled: assets, task: () => this.uploadAssets(), label: 'GitHub upload assets' });
return this.step({
task: () => (isUpdate ? Promise.resolve() : this.commentOnResolvedItems()),
label: 'GitHub comment on resolved items'
});
} else {
const release = async () => {
await this[publishMethod]();
await this.uploadAssets();
return isUpdate ? Promise.resolve(true) : this.commentOnResolvedItems();
};
return this.step({ task: release, label: `GitHub ${type} release`, prompt: 'release' });
}
}
handleError(err, bail) {
const message = parseErrormsg(err);
const githubError = new Error(message);
this.log.verbose(err.errors);
this.debug(err);
if (!RETRY_CODES.includes(err.status)) {
return bail(githubError);
}
throw githubError;
}
get client() {
if (this._client) return this._client;
const { proxy, timeout } = this.options;
const repo = this.getContext('repo');
const host = this.options.host || repo.host;
const isGitHub = host === 'github.com';
const baseUrl = `https://${isGitHub ? 'api.github.com' : host}${isGitHub ? '' : '/api/v3'}`;
const options = {
baseUrl,
auth: `token ${this.token}`,
userAgent: `release-it/${pkg.version}`,
log: this.config.isDebug ? console : {},
request: {
timeout
}
};
if (proxy) {
options.request.agent = new ProxyAgent(proxy);
}
const client = new Octokit(options);
this._client = client;
return client;
}
async getLatestRelease() {
const { owner, project: repo } = this.getContext('repo');
try {
const options = { owner, repo };
this.debug(options);
const response = await this.client.repos.listReleases({ owner, repo, per_page: 1, page: 1 });
this.debug(response.data[0]);
return response.data[0];
} catch (err) {
return this.handleError(err, () => {});
}
}
async getOctokitReleaseOptions(options = {}) {
const { owner, project: repo } = this.getContext('repo');
const {
releaseName,
draft = false,
preRelease = false,
autoGenerate = false,
makeLatest = true,
discussionCategoryName = undefined
} = this.options;
const { tagName } = this.config.getContext();
const { version, releaseNotes, isUpdate } = this.getContext();
const { isPreRelease } = parseVersion(version);
const name = format(releaseName, this.config.getContext());
const releaseNotesObject = this.options.releaseNotes;
const body = autoGenerate
? isUpdate
? null
: ''
: truncateBody(releaseNotesObject?.commit ? await this.renderReleaseNotes(releaseNotesObject) : releaseNotes);
/**
* @type {CreateReleaseOptions}
*/
const contextOptions = {
owner,
make_latest: makeLatest.toString(),
repo,
tag_name: tagName,
name,
body,
draft,
prerelease: isPreRelease || preRelease,
generate_release_notes: autoGenerate,
discussion_category_name: discussionCategoryName
};
return Object.assign(options, contextOptions);
}
retry(fn) {
const { retryMinTimeout } = this.options;
return retry(fn, {
retries: 2,
minTimeout: typeof retryMinTimeout === 'number' ? retryMinTimeout : DEFAULT_RETRY_MIN_TIMEOUT
});
}
async createRelease() {
const options = await this.getOctokitReleaseOptions();
const { isDryRun } = this.config;
this.log.exec(`octokit repos.createRelease "${options.name}" (${options.tag_name})`, { isDryRun });
if (isDryRun) {
this.setContext({ isReleased: true, releaseUrl: this.getReleaseUrlFallback(options.tag_name) });
return true;
}
return this.retry(async bail => {
try {
this.debug(options);
const response = await this.client.repos.createRelease(options);
this.debug(response.data);
const { html_url, upload_url, id, discussion_url } = response.data;
this.setContext({
isReleased: true,
releaseId: id,
releaseUrl: html_url,
upload_url,
discussionUrl: discussion_url
});
this.config.setContext({
isReleased: true,
releaseId: id,
releaseUrl: html_url,
upload_url,
discussionUrl: discussion_url
});
this.log.verbose(`octokit repos.createRelease: done (${response.headers.location})`);
return response.data;
} catch (err) {
return this.handleError(err, bail);
}
});
}
uploadAsset(filePath) {
const url = this.getContext('upload_url');
const name = path.basename(filePath);
const contentType = mime.contentType(name) || 'application/octet-stream';
const contentLength = statSync(filePath).size;
return this.retry(async bail => {
try {
const options = {
url,
data: createReadStream(filePath),
name,
headers: {
'content-type': contentType,
'content-length': contentLength
}
};
this.debug(options);
const response = await this.client.repos.uploadReleaseAsset(options);
this.debug(response.data);
this.log.verbose(`octokit repos.uploadReleaseAsset: done (${response.data.browser_download_url})`);
return response.data;
} catch (err) {
return this.handleError(err, bail);
}
});
}
uploadAssets() {
const { assets } = this.options;
const { isReleased } = this.getContext();
const context = this.config.getContext();
const { isDryRun } = this.config;
const patterns = castArray(assets).map(pattern => format(pattern, context));
this.log.exec('octokit repos.uploadReleaseAssets', patterns, { isDryRun });
if (!assets || !isReleased) {
return true;
}
return glob(patterns).then(files => {
if (!files.length) {
this.log.warn(`octokit repos.uploadReleaseAssets: did not find "${assets}" relative to ${process.cwd()}`);
}
if (isDryRun) return Promise.resolve();
return Promise.all(files.map(filePath => this.uploadAsset(filePath)));
});
}
getReleaseUrlFallback(tagName) {
const { host, repository } = this.getContext('repo');
return `https://${host}/${repository}/releases/tag/${tagName}`;
}
async generateWebUrl() {
const repo = this.getContext('repo');
const host = this.options.host || repo.host;
const isGitHub = host === 'github.com';
const options = await this.getOctokitReleaseOptions();
const url = newGithubReleaseUrl({
user: options.owner,
repo: options.repo,
tag: options.tag_name,
isPrerelease: options.prerelease,
title: options.name,
body: options.body
});
return isGitHub ? url : url.replace('github.com', host);
}
async createWebRelease() {
const { isCI } = this.config;
const { tagName } = this.config.getContext();
const url = await this.generateWebUrl();
if (isCI) {
this.setContext({ isReleased: true, releaseUrl: url });
} else {
const isWindows = process.platform === 'win32';
if (isWindows) this.log.info(`Opening ${url}`);
await open(url, { wait: isWindows });
this.setContext({ isReleased: true, releaseUrl: this.getReleaseUrlFallback(tagName) });
}
}
async updateRelease() {
const { isDryRun } = this.config;
const release_id = this.getContext('releaseId');
const options = await this.getOctokitReleaseOptions({ release_id });
this.log.exec(`octokit repos.updateRelease (${options.tag_name})`, { isDryRun });
if (isDryRun) return true;
return this.retry(async bail => {
try {
this.debug(options);
const response = await this.client.repos.updateRelease(options);
this.setContext({ releaseUrl: response.data.html_url });
this.debug(response.data);
this.log.verbose(`octokit repos.updateRelease: done (${response.headers.location})`);
return true;
} catch (err) {
return this.handleError(err, bail);
}
});
}
async commentOnResolvedItems() {
const { isDryRun } = this.config;
const { host, owner, project: repo } = this.getContext('repo');
const changelog = await this.getChangelog();
const { comments } = this.options;
const { submit, issue, pr } = comments ?? {};
const context = this.getContext();
if (!submit || !changelog) return true;
const shas = getCommitsFromChangelog(changelog);
const searchResults = await Promise.all(searchQueries(this.client, owner, repo, shas));
const mergedPullRequests = searchResults.flatMap(items => items.map(item => ({ type: 'pr', number: item.number })));
const hostURL = 'https://' + (this.options.host || host);
const resolvedIssues = getResolvedIssuesFromChangelog(hostURL, owner, repo, changelog);
for (const item of [...resolvedIssues, ...mergedPullRequests]) {
const { type, number } = item;
const comment = format(format(type === 'pr' ? pr : issue, context), context);
const url = `${hostURL}/${owner}/${repo}/${type === 'pr' ? 'pull' : 'issues'}/${number}`;
if (isDryRun) {
this.log.exec(`octokit issues.createComment (${url})`, { isDryRun });
return Promise.resolve();
}
try {
await this.client.issues.createComment({ owner, repo, issue_number: number, body: comment });
this.log.log(`● Commented on ${url}`);
} catch (error) {
this.log.log(`✕ Failed to comment on ${url}`);
}
}
}
async getCommits() {
const { owner, project: repo } = this.getContext('repo');
const { latestTag } = this.config.getContext();
this.debug({ owner, repo, base: latestTag, head: 'HEAD' });
const { data } = await this.client.repos.compareCommits({ owner, repo, base: latestTag, head: 'HEAD' });
return data.commits;
}
async renderReleaseNotes(releaseNotes) {
const { commit: template, excludeMatches = [] } = releaseNotes;
const commits = await this.getCommits();
if (this.options.commit) commits.pop();
return commits
.map(commit => {
commit.commit.subject = commit.commit.message.split('\n')[0];
const partial = template.replace(/(?<!\$)\{((?:[^{}]|\${[^}]+})+)\}/g, (_, block) => {
const rendered = format(block, commit);
return excludeMatches.some(match => rendered.includes(match)) ? '' : rendered;
});
return format(partial, commit);
})
.join('\n');
}
}
export default GitHub;

16
node_modules/release-it/lib/plugin/github/prompts.js generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import { format } from '../../util.js';
const message = context => {
const { isPreRelease, github } = context;
const { releaseName, update } = github;
const name = format(releaseName, context);
return `${update ? 'Update' : 'Create a'} ${isPreRelease ? 'pre-' : ''}release on GitHub (${name})?`;
};
export default {
release: {
type: 'confirm',
message,
default: true
}
};

42
node_modules/release-it/lib/plugin/github/util.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
// Totally much borrowed from https://github.com/semantic-release/github/blob/master/lib/success.js
import issueParser from 'issue-parser';
/** @internal */
export const getSearchQueries = (base, commits, separator = '+') => {
const encodedSeparator = encodeURIComponent(separator);
return commits.reduce((searches, commit) => {
const lastSearch = searches[searches.length - 1];
if (lastSearch && encodeURIComponent(lastSearch).length + commit.length <= 256 - encodedSeparator.length) {
searches[searches.length - 1] = `${lastSearch}${separator}${commit}`;
} else {
searches.push(`${base}${separator}${commit}`);
}
return searches;
}, []);
};
export const searchQueries = (client, owner, repo, shas) =>
getSearchQueries(`repo:${owner}/${repo}+type:pr+is:merged`, shas).map(
async q => (await client.search.issuesAndPullRequests({ q, advanced_search: true })).data.items
);
export const getCommitsFromChangelog = changelog => {
const regex = /\(([a-f0-9]{7,})\)/i;
return changelog.split('\n').flatMap(message => {
const match = message.match(regex);
if (match) return match[1];
return [];
});
};
export const getResolvedIssuesFromChangelog = (host, owner, repo, changelog) => {
const parser = issueParser('github', { hosts: [host] });
return changelog
.split('\n')
.map(parser)
.flatMap(parsed => parsed.actions.close)
.filter(action => !action.slug || action.slug === `${owner}/${repo}`)
.map(action => ({ type: 'issue', number: parseInt(action.issue, 10) }));
};

338
node_modules/release-it/lib/plugin/gitlab/GitLab.js generated vendored Normal file
View File

@@ -0,0 +1,338 @@
import path from 'node:path';
import fs from 'node:fs'; // import fs here so it can be stubbed in tests
import { readFile } from 'node:fs/promises';
import { glob } from 'tinyglobby';
import { Agent } from 'undici';
import Release from '../GitRelease.js';
import { format, e, castArray } from '../../util.js';
import prompts from './prompts.js';
const docs = 'https://git.io/release-it-gitlab';
const noop = Promise.resolve();
class GitLab extends Release {
constructor(...args) {
super(...args);
this.registerPrompts(prompts);
this.assets = [];
const { secure } = this.options;
const certificateAuthorityFileRef = this.options.certificateAuthorityFileRef || 'CI_SERVER_TLS_CA_FILE';
const certificateAuthorityFile =
this.options.certificateAuthorityFile || process.env[certificateAuthorityFileRef] || null;
this.certificateAuthorityOption = {};
const needsCustomAgent = Boolean(secure === false || certificateAuthorityFile);
if (needsCustomAgent) {
this.certificateAuthorityOption.dispatcher = new Agent({
connect: {
rejectUnauthorized: secure,
ca: certificateAuthorityFile ? fs.readFileSync(certificateAuthorityFile) : undefined
}
});
}
}
async init() {
await super.init();
const { skipChecks, tokenRef, tokenHeader } = this.options;
const { repo } = this.getContext();
const hasJobToken = (tokenHeader || '').toLowerCase() === 'job-token';
const origin = this.options.origin || `https://${repo.host}`;
this.setContext({
id: encodeURIComponent(repo.repository),
origin,
baseUrl: `${origin}/api/v4`
});
if (skipChecks) return;
if (!this.token) {
throw e(`Environment variable "${tokenRef}" is required for GitLab releases.`, docs);
}
if (!hasJobToken) {
if (!(await this.isAuthenticated())) {
throw e(`Could not authenticate with GitLab using environment variable "${tokenRef}".`, docs);
}
if (!(await this.isCollaborator())) {
const { user, repo } = this.getContext();
throw e(`User ${user.username} is not a collaborator for ${repo.repository}.`, docs);
}
}
}
async isAuthenticated() {
if (this.config.isDryRun) return true;
const endpoint = `user`;
try {
const { id, username } = await this.request(endpoint, { method: 'GET' });
this.setContext({ user: { id, username } });
return true;
} catch (err) {
this.debug(err);
return false;
}
}
async isCollaborator() {
if (this.config.isDryRun) return true;
const { id, user } = this.getContext();
const endpoint = `projects/${id}/members/all/${user.id}`;
try {
const { access_level } = await this.request(endpoint, { method: 'GET' });
return access_level && access_level >= 30;
} catch (err) {
this.debug(err);
return false;
}
}
async beforeRelease() {
await super.beforeRelease();
await this.checkReleaseMilestones();
}
async checkReleaseMilestones() {
if (this.options.skipChecks) return;
const releaseMilestones = this.getReleaseMilestones();
if (releaseMilestones.length < 1) {
return;
}
this.log.exec(`gitlab releases#checkReleaseMilestones`);
const { id } = this.getContext();
const endpoint = `projects/${id}/milestones`;
const requests = releaseMilestones.map(milestone => {
const options = {
method: 'GET',
searchParams: {
title: milestone,
include_parent_milestones: true
}
};
return this.request(endpoint, options).then(response => {
if (!Array.isArray(response)) {
const { baseUrl } = this.getContext();
throw new Error(
`Unexpected response from ${baseUrl}/${endpoint}. Expected an array but got: ${JSON.stringify(response)}`
);
}
if (response.length === 0) {
const error = new Error(`Milestone '${milestone}' does not exist.`);
this.log.warn(error.message);
throw error;
}
this.log.verbose(`gitlab releases#checkReleaseMilestones: milestone '${milestone}' exists`);
});
});
try {
await Promise.allSettled(requests).then(results => {
for (const result of results) {
if (result.status === 'rejected') {
throw e('Missing one or more milestones in GitLab. Creating a GitLab release will fail.', docs);
}
}
});
} catch (err) {
this.debug(err);
throw err;
}
this.log.verbose('gitlab releases#checkReleaseMilestones: done');
}
getReleaseMilestones() {
const { milestones } = this.options;
return (milestones || []).map(milestone => format(milestone, this.config.getContext()));
}
async release() {
const glRelease = () => this.createRelease();
const glUploadAssets = () => this.uploadAssets();
if (this.config.isCI) {
await this.step({ enabled: this.options.assets, task: glUploadAssets, label: 'GitLab upload assets' });
return await this.step({ task: glRelease, label: 'GitLab release' });
} else {
const release = () => glUploadAssets().then(() => glRelease());
return await this.step({ task: release, label: 'GitLab release', prompt: 'release' });
}
}
async request(endpoint, options) {
const { baseUrl } = this.getContext();
this.debug(Object.assign({ url: `${baseUrl}/${endpoint}` }, options));
const method = (options.method || 'POST').toLowerCase();
const { tokenHeader } = this.options;
const url = `${baseUrl}/${endpoint}${options.searchParams ? `?${new URLSearchParams(options.searchParams)}` : ''}`;
const headers = {
'user-agent': 'webpro/release-it',
[tokenHeader]: this.token
};
// When using fetch() with FormData bodies, we should not set the Content-Type header.
// See: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest_API/Using_FormData_Objects#sending_files_using_a_formdata_object
if (!(options.body instanceof FormData)) {
headers['Content-Type'] = typeof options.json !== 'undefined' ? 'application/json' : 'text/plain';
}
const requestOptions = {
method,
headers,
...this.certificateAuthorityOption
};
try {
const response = await fetch(
url,
options.json || options.body
? {
...requestOptions,
body: options.json ? JSON.stringify(options.json) : options.body
}
: requestOptions
);
if (!response.ok) {
const body = await response.json();
throw new Error(body.error);
}
const body = await response.json();
this.debug(body);
return body;
} catch (err) {
this.debug(err);
throw err;
}
}
async createRelease() {
const { releaseName } = this.options;
const { tagName, branchName, git: { tagAnnotation } = {} } = this.config.getContext();
const { id, releaseNotes, repo, origin } = this.getContext();
const { isDryRun } = this.config;
const name = format(releaseName, this.config.getContext());
const tagMessage = format(tagAnnotation, this.config.getContext());
const description = releaseNotes || '-';
const releaseUrl = `${origin}/${repo.repository}/-/releases/${tagName}`;
const releaseMilestones = this.getReleaseMilestones();
this.log.exec(`gitlab releases#createRelease "${name}" (${tagName})`, { isDryRun });
if (isDryRun) {
this.setContext({ isReleased: true, releaseUrl });
return true;
}
const endpoint = `projects/${id}/releases`;
const options = {
json: {
name,
ref: branchName,
tag_name: tagName,
tag_message: tagMessage,
description
}
};
if (this.assets.length) {
options.json.assets = {
links: this.assets
};
}
if (releaseMilestones.length) {
options.json.milestones = releaseMilestones;
}
try {
const body = await this.request(endpoint, options);
const releaseUrlSelf = body._links?.self ?? releaseUrl;
this.log.verbose('gitlab releases#createRelease: done');
this.setContext({ isReleased: true, releaseUrl: releaseUrlSelf });
this.config.setContext({ isReleased: true, releaseUrl: releaseUrlSelf });
return true;
} catch (err) {
this.debug(err);
throw err;
}
}
async uploadAsset(filePath) {
const name = path.basename(filePath);
const { useIdsForUrls, useGenericPackageRepositoryForAssets, genericPackageRepositoryName } = this.options;
const { id, origin, repo, version, baseUrl } = this.getContext();
const endpoint = useGenericPackageRepositoryForAssets
? `projects/${id}/packages/generic/${genericPackageRepositoryName}/${version}/${name}`
: `projects/${id}/uploads`;
if (useGenericPackageRepositoryForAssets) {
const options = {
method: 'PUT',
body: await readFile(filePath)
};
try {
const body = await this.request(endpoint, options);
if (!(body.message && body.message == '201 Created')) {
throw new Error(`GitLab asset upload failed`);
}
this.log.verbose(`gitlab releases#uploadAsset: done (${endpoint})`);
this.assets.push({
name,
url: `${baseUrl}/${endpoint}`
});
} catch (err) {
this.debug(err);
throw err;
}
} else {
const body = new FormData();
const rawData = await readFile(filePath);
body.set('file', new Blob([rawData]), name);
const options = { body };
try {
const body = await this.request(endpoint, options);
this.log.verbose(`gitlab releases#uploadAsset: done (${body.url})`);
this.assets.push({
name,
url: useIdsForUrls ? `${origin}${body.full_path}` : `${origin}/${repo.repository}${body.url}`
});
} catch (err) {
this.debug(err);
throw err;
}
}
}
uploadAssets() {
const { assets } = this.options;
const { isDryRun } = this.config;
const context = this.config.getContext();
const patterns = castArray(assets).map(pattern => format(pattern, context));
this.log.exec('gitlab releases#uploadAssets', patterns, { isDryRun });
if (!assets) {
return noop;
}
return glob(patterns).then(files => {
if (!files.length) {
this.log.warn(`gitlab releases#uploadAssets: could not find "${assets}" relative to ${process.cwd()}`);
}
if (isDryRun) return Promise.resolve();
return Promise.all(files.map(filePath => this.uploadAsset(filePath)));
});
}
}
export default GitLab;

9
node_modules/release-it/lib/plugin/gitlab/prompts.js generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { format } from '../../util.js';
export default {
release: {
type: 'confirm',
message: context => `Create a release on GitLab (${format(context.gitlab.releaseName, context)})?`,
default: true
}
};

284
node_modules/release-it/lib/plugin/npm/npm.js generated vendored Normal file
View File

@@ -0,0 +1,284 @@
import path from 'node:path';
import semver from 'semver';
import urlJoin from 'url-join';
import Plugin from '../Plugin.js';
import { hasAccess, rejectAfter, parseVersion, readJSON, e, fixArgs } from '../../util.js';
import prompts from './prompts.js';
const docs = 'https://git.io/release-it-npm';
const options = { write: false };
const MANIFEST_PATH = './package.json';
const DEFAULT_TAG = 'latest';
const DEFAULT_TAG_PRERELEASE = 'next';
const NPM_BASE_URL = 'https://www.npmjs.com';
const NPM_PUBLIC_PATH = '/package';
const DEFAULT_TIMEOUT = 10;
class npm extends Plugin {
static isEnabled(options) {
return hasAccess(MANIFEST_PATH) && options !== false;
}
constructor(...args) {
super(...args);
this.registerPrompts(prompts);
}
async init() {
const { name, version: latestVersion, private: isPrivate, publishConfig } = readJSON(path.resolve(MANIFEST_PATH));
this.setContext({ name, latestVersion, private: isPrivate, publishConfig });
this.config.setContext({ npm: { name } });
const { publish, skipChecks } = this.options;
const timeout = Number(this.options.timeout ?? DEFAULT_TIMEOUT) * 1000;
if (publish === false || isPrivate) return;
if (skipChecks) return;
const validations = Promise.all([this.isRegistryUp(), this.isAuthenticated(), this.getLatestRegistryVersion()]);
await Promise.race([validations, rejectAfter(timeout, e(`Timed out after ${timeout}ms.`, docs))]);
const [isRegistryUp, isAuthenticated, latestVersionInRegistry] = await validations;
if (!isRegistryUp) {
throw e(`Unable to reach npm registry (timed out after ${timeout}ms).`, docs);
}
if (!isAuthenticated) {
throw e('Not authenticated with npm. Please `npm login` and try again.', docs);
}
if (!(await this.isCollaborator())) {
const { username } = this.getContext();
throw e(`User ${username} is not a collaborator for ${name}.`, docs);
}
if (!latestVersionInRegistry) {
this.log.warn('No version found in npm registry. Assuming new package.');
} else {
if (!semver.eq(latestVersion, latestVersionInRegistry)) {
this.log.warn(
`Latest version in registry (${latestVersionInRegistry}) does not match package.json (${latestVersion}).`
);
}
}
}
getName() {
return this.getContext('name');
}
getLatestVersion() {
return this.options.ignoreVersion ? null : this.getContext('latestVersion');
}
async bump(version) {
const tag = this.options.tag || (await this.resolveTag(version));
this.setContext({ version, tag });
if (!this.config.isIncrement) return false;
const { versionArgs, allowSameVersion } = this.options;
const args = [version, '--no-git-tag-version', allowSameVersion && '--allow-same-version', ...fixArgs(versionArgs)];
const task = () => this.exec(`npm version ${args.filter(Boolean).join(' ')}`);
return this.spinner.show({ task, label: 'npm version' });
}
release() {
if (this.options.publish === false) return false;
if (this.getContext('private')) return false;
const publish = () => this.publish({ otpCallback });
const otpCallback =
this.config.isCI && !this.config.isPromptOnlyVersion ? null : task => this.step({ prompt: 'otp', task });
return this.step({ task: publish, label: 'npm publish', prompt: 'publish' });
}
isRegistryUp() {
const registry = this.getRegistry();
const registryArg = registry ? ` --registry ${registry}` : '';
return this.exec(`npm ping${registryArg}`, { options }).then(
() => true,
err => {
if (/code E40[04]|404.*(ping not found|No content for path)/.test(err)) {
this.log.warn('Ignoring response from unsupported `npm ping` command.');
return true;
}
return false;
}
);
}
isAuthenticated() {
const registry = this.getRegistry();
const registryArg = registry ? ` --registry ${registry}` : '';
return this.exec(`npm whoami${registryArg}`, { options }).then(
output => {
const username = output ? output.trim() : null;
this.setContext({ username });
return true;
},
err => {
this.debug(err);
if (/code E40[04]/.test(err)) {
this.log.warn('Ignoring response from unsupported `npm whoami` command.');
return true;
}
return false;
}
);
}
async isCollaborator() {
const registry = this.getRegistry();
const registryArg = registry ? ` --registry ${registry}` : '';
const name = this.getName();
const { username } = this.getContext();
if (username === undefined) return true;
if (username === null) return false;
try {
let npmVersion = await this.exec('npm --version', { options });
let accessCommand;
if (semver.gt(npmVersion, '9.0.0')) {
accessCommand = 'npm access list collaborators --json';
} else {
accessCommand = 'npm access ls-collaborators';
}
const output = await this.exec(`${accessCommand} ${name}${registryArg}`, { options });
try {
const collaborators = JSON.parse(output);
const permissions = collaborators[username];
return permissions && permissions.includes('write');
} catch (err) {
this.debug(err);
return false;
}
} catch (err) {
this.debug(err);
if (/code E400/.test(err)) {
this.log.warn('Ignoring response from unsupported `npm access` command.');
} else {
this.log.warn(`Unable to verify if user ${username} is a collaborator for ${name}.`);
}
return true;
}
}
async getLatestRegistryVersion() {
const registry = this.getRegistry();
const registryArg = registry ? ` --registry ${registry}` : '';
const name = this.getName();
const latestVersion = this.getLatestVersion();
const tag = await this.resolveTag(latestVersion);
return this.exec(`npm show ${name}@${tag} version${registryArg}`, { options }).catch(() => null);
}
getRegistryPreReleaseTags() {
return this.exec(`npm view ${this.getName()} dist-tags --json`, { options }).then(
output => {
try {
const tags = JSON.parse(output);
return Object.keys(tags).filter(tag => tag !== DEFAULT_TAG);
} catch (err) {
this.debug(err);
return [];
}
},
() => []
);
}
getPackageUrl() {
const baseUrl = this.getRegistry() || NPM_BASE_URL;
const publicPath = this.getPublicPath() || NPM_PUBLIC_PATH;
return urlJoin(baseUrl, publicPath, this.getName());
}
getRegistry() {
const { publishConfig } = this.getContext();
const registries = publishConfig
? publishConfig.registry
? [publishConfig.registry]
: Object.keys(publishConfig)
.filter(key => key.endsWith('registry'))
.map(key => publishConfig[key])
: [];
return registries[0];
}
getPublicPath() {
const { publishConfig } = this.getContext();
return (publishConfig && publishConfig.publicPath) ?? '';
}
async guessPreReleaseTag() {
const [tag] = await this.getRegistryPreReleaseTags();
if (tag) {
return tag;
} else {
this.log.warn(`Unable to get pre-release tag(s) from npm registry. Using "${DEFAULT_TAG_PRERELEASE}".`);
return DEFAULT_TAG_PRERELEASE;
}
}
async resolveTag(version) {
const { tag } = this.options;
const { isPreRelease, preReleaseId } = parseVersion(version);
if (!isPreRelease) {
return DEFAULT_TAG;
} else {
return tag || preReleaseId || (await this.guessPreReleaseTag());
}
}
async publish({ otp = this.options.otp, otpCallback } = {}) {
const { publishPath = '.', publishArgs } = this.options;
const { private: isPrivate, tag = DEFAULT_TAG } = this.getContext();
const otpArg = otp ? `--otp ${otp}` : '';
const dryRunArg = this.config.isDryRun ? '--dry-run' : '';
const registry = this.getRegistry();
const registryArg = registry ? `--registry ${registry}` : '';
if (isPrivate) {
this.log.warn('Skip publish: package is private.');
return false;
}
const args = [publishPath, `--tag ${tag}`, otpArg, dryRunArg, registryArg, ...fixArgs(publishArgs)].filter(Boolean);
return this.exec(`npm publish ${args.join(' ')}`, { options })
.then(() => {
this.setContext({ isReleased: true });
})
.catch(err => {
this.debug(err);
if (this.config.isDryRun && /publish over the previously published version/.test(err)) {
return Promise.resolve();
}
if (/one-time pass/.test(err)) {
if (otp != null) {
this.log.warn('The provided OTP is incorrect or has expired.');
}
if (otpCallback) {
return otpCallback(otp => this.publish({ otp, otpCallback }));
}
}
throw err;
});
}
afterRelease() {
const { isReleased } = this.getContext();
if (isReleased) {
this.log.log(`🔗 ${this.getPackageUrl()}`);
}
}
}
export default npm;

12
node_modules/release-it/lib/plugin/npm/prompts.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
export default {
publish: {
type: 'confirm',
message: context =>
`Publish ${context.npm.name}${context.npm.tag === 'latest' ? '' : `@${context.npm.tag}`} to npm?`,
default: true
},
otp: {
type: 'input',
message: () => `Please enter OTP for npm:`
}
};

131
node_modules/release-it/lib/plugin/version/Version.js generated vendored Normal file
View File

@@ -0,0 +1,131 @@
import { styleText } from 'node:util';
import semver from 'semver';
import Plugin from '../Plugin.js';
const RELEASE_TYPES = ['patch', 'minor', 'major'];
const PRERELEASE_TYPES = ['prepatch', 'preminor', 'premajor'];
const CONTINUATION_TYPES = ['prerelease', 'pre'];
const ALL_RELEASE_TYPES = [...RELEASE_TYPES, ...PRERELEASE_TYPES, ...CONTINUATION_TYPES];
const CHOICES = {
latestIsPreRelease: [CONTINUATION_TYPES[0], ...RELEASE_TYPES],
preRelease: PRERELEASE_TYPES,
default: [...RELEASE_TYPES, ...PRERELEASE_TYPES]
};
const getIncrementChoices = context => {
const { latestIsPreRelease, isPreRelease, preReleaseId, preReleaseBase } = context.version;
const types = latestIsPreRelease ? CHOICES.latestIsPreRelease : isPreRelease ? CHOICES.preRelease : CHOICES.default;
const choices = types.map(increment => ({
name: `${increment} (${semver.inc(context.latestVersion, increment, preReleaseId, preReleaseBase)})`,
value: increment
}));
const otherChoice = {
name: 'Other, please specify...',
value: null
};
return [...choices, otherChoice];
};
const versionTransformer = context => input =>
semver.valid(input)
? semver.gt(input, context.latestVersion)
? styleText('green', input)
: styleText('red', input)
: styleText(['red', 'bold'], input);
const prompts = {
incrementList: {
type: 'list',
message: () => 'Select increment (next version):',
choices: context => getIncrementChoices(context),
pageSize: 9
},
version: {
type: 'input',
message: () => `Please enter a valid version:`,
transformer: context => versionTransformer(context),
validate: input => !!semver.valid(input) || 'The version must follow the semver standard.'
}
};
class Version extends Plugin {
constructor(...args) {
super(...args);
this.registerPrompts(prompts);
}
getIncrement(options) {
return options.increment;
}
getIncrementedVersionCI(options) {
return this.incrementVersion(options);
}
async getIncrementedVersion(options) {
const { isCI } = this.config;
const version = this.incrementVersion(options);
return version || (isCI ? null : await this.promptIncrementVersion(options));
}
promptIncrementVersion(options) {
return new Promise(resolve => {
this.step({
prompt: 'incrementList',
task: increment =>
increment
? resolve(this.incrementVersion(Object.assign({}, options, { increment })))
: this.step({ prompt: 'version', task: resolve })
});
});
}
isPreRelease(version) {
return Boolean(semver.prerelease(version));
}
isValid(version) {
return Boolean(semver.valid(version));
}
incrementVersion({ latestVersion, increment, isPreRelease, preReleaseId, preReleaseBase }) {
if (increment === false) return latestVersion;
const latestIsPreRelease = this.isPreRelease(latestVersion);
const isValidVersion = this.isValid(increment);
if (latestVersion) {
this.setContext({ latestIsPreRelease });
}
if (isValidVersion && semver.gte(increment, latestVersion)) {
return increment;
}
if (isPreRelease && !increment && latestIsPreRelease) {
return semver.inc(latestVersion, 'prerelease', preReleaseId, preReleaseBase);
}
if (this.config.isCI && !increment) {
if (isPreRelease) {
return semver.inc(latestVersion, 'prepatch', preReleaseId, preReleaseBase);
} else {
return semver.inc(latestVersion, 'patch');
}
}
const normalizedType = RELEASE_TYPES.includes(increment) && isPreRelease ? `pre${increment}` : increment;
if (ALL_RELEASE_TYPES.includes(normalizedType)) {
return semver.inc(latestVersion, normalizedType, preReleaseId, preReleaseBase);
}
const coercedVersion = !isValidVersion && semver.coerce(increment);
if (coercedVersion) {
this.log.warn(`Coerced invalid semver version "${increment}" into "${coercedVersion}".`);
return coercedVersion.toString();
}
}
}
export default Version;

33
node_modules/release-it/lib/prompt.js generated vendored Normal file
View File

@@ -0,0 +1,33 @@
import inquirer from 'inquirer';
class Prompt {
constructor({ container }) {
this.createPrompt = (container.inquirer || inquirer).prompt;
this.prompts = {};
}
register(pluginPrompts, namespace = 'default') {
this.prompts[namespace] = this.prompts[namespace] || {};
Object.assign(this.prompts[namespace], pluginPrompts);
}
async show({ enabled = true, prompt: promptName, namespace = 'default', task, context }) {
if (!enabled) return false;
const prompt = this.prompts[namespace][promptName];
const options = Object.assign({}, prompt, {
name: promptName,
message: prompt.message(context),
choices: 'choices' in prompt && prompt.choices(context),
transformer: 'transformer' in prompt ? prompt.transformer(context) : undefined
});
const answers = await this.createPrompt([options]);
const doExecute = prompt.type === 'confirm' ? answers[promptName] : true;
return doExecute && task ? await task(answers[promptName]) : false;
}
}
export default Prompt;

120
node_modules/release-it/lib/shell.js generated vendored Normal file
View File

@@ -0,0 +1,120 @@
import util from 'node:util';
import { spawn, exec } from 'node:child_process';
import { format } from './util.js';
const debug = util.debug('release-it:shell');
const noop = Promise.resolve();
class Shell {
constructor({ container }) {
this.log = container.log;
this.config = container.config;
this.cache = new Map();
}
exec(command, options = {}, context = {}) {
if (!command || !command.length) return;
return typeof command === 'string'
? this.execFormattedCommand(format(command, context), options)
: this.execFormattedCommand(command, options);
}
async execFormattedCommand(command, options = {}) {
const { isDryRun } = this.config;
const isWrite = options.write !== false;
const isExternal = options.external === true;
const cacheKey = typeof command === 'string' ? command : command.join(' ');
const isCached = !isExternal && this.cache.has(cacheKey);
if (isDryRun && isWrite) {
this.log.exec(command, { isDryRun });
return noop;
}
this.log.exec(command, { isExternal, isCached });
if (isCached) {
return this.cache.get(cacheKey);
}
const result =
typeof command === 'string'
? this.execStringCommand(command, options, { isExternal })
: this.execWithArguments(command, options, { isExternal });
if (!isExternal && !this.cache.has(cacheKey)) {
this.cache.set(cacheKey, result);
}
return result;
}
execStringCommand(command, options, { isExternal }) {
return new Promise((resolve, reject) => {
const proc = exec(command, (err, stdout, stderr) => {
stdout = stdout.toString().trimEnd();
const code = !err ? 0 : err === 'undefined' ? 1 : err.code;
debug({ command, options, code, stdout, stderr });
if (code === 0) {
resolve(stdout);
} else {
reject(new Error(stderr || stdout));
}
});
proc.stdout.on('data', stdout => this.log.verbose(stdout.toString().trimEnd(), { isExternal }));
proc.stderr.on('data', stderr => this.log.verbose(stderr.toString().trimEnd(), { isExternal }));
});
}
async execWithArguments(command, options = {}, { isExternal } = {}) {
const [program, ...programArgs] = command;
try {
return await new Promise((resolve, reject) => {
const proc = spawn(program, programArgs, {
// we want to capture all output from the process so the extra 2 pipe
stdio: ['inherit', 'pipe', 'pipe'],
...options
});
let stdout = '';
let stderr = '';
proc.stdout.on('data', data => {
stdout += data.toString();
});
proc.stderr.on('data', data => {
stderr += data.toString();
});
proc.on('close', code => {
stdout = stdout === '""' ? '' : stdout;
this.log.verbose(stdout, { isExternal });
debug({ command, options, stdout, stderr });
if (code === 0) {
resolve((stdout || stderr).trim());
} else {
if (stdout) {
this.log.log(`\n${stdout}`);
}
debug({ code, command, options, stdout, stderr });
reject(new Error(stderr || stdout || `Process exited with code ${code}`));
}
});
proc.on('error', err => {
debug(err);
reject(new Error(err.message));
});
});
} catch (err) {
debug(err);
return Promise.reject(err);
}
}
}
export default Shell;

29
node_modules/release-it/lib/spinner.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
import { oraPromise } from 'ora';
import { format } from './util.js';
const noop = Promise.resolve();
class Spinner {
constructor({ container = {} } = {}) {
this.config = container.config;
this.ora = container.ora || oraPromise;
}
show({ enabled = true, task, label, external = false, context }) {
if (!enabled) return noop;
const { config } = this;
this.isSpinnerDisabled = !config.isCI || config.isVerbose || config.isDryRun || config.isDebug;
this.canForce = !config.isCI && !config.isVerbose && !config.isDryRun && !config.isDebug;
const awaitTask = task();
if (!this.isSpinnerDisabled || (external && this.canForce)) {
const text = format(label, context);
this.ora(awaitTask, text);
}
return awaitTask;
}
}
export default Spinner;

206
node_modules/release-it/lib/util.js generated vendored Normal file
View File

@@ -0,0 +1,206 @@
import fs, { close, openSync, statSync, utimesSync, accessSync } from 'node:fs'; // need import fs here due to test stubbing
import util from 'node:util';
import { EOL } from 'node:os';
import gitUrlParse from 'git-url-parse';
import semver from 'semver';
import osName from 'os-name';
import { Eta } from 'eta';
import Log from './log.js';
const debug = util.debug('release-it:shell');
const eta = new Eta({
autoEscape: false,
useWith: true,
tags: ['${', '}'],
parse: { interpolate: '' },
rmWhitespace: false,
autoTrim: false
});
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));
const before = (n, func) => {
var result;
if (typeof func != 'function') {
throw new TypeError('Missing argument for `func`');
}
n = parseInt(n);
return function () {
if (--n > 0) {
result = func.apply(this, arguments);
}
if (n <= 1) {
func = undefined;
}
return result;
};
};
const tryStatFile = filePath => {
try {
return statSync(filePath);
} catch (e) {
debug(e);
return null;
}
};
/** @internal */
export const execOpts = {
stdio: process.env.NODE_DEBUG && process.env.NODE_DEBUG.indexOf('release-it') === 0 ? 'pipe' : []
};
export const readJSON = file => JSON.parse(fs.readFileSync(file, 'utf8'));
const pkg = readJSON(new URL('../package.json', import.meta.url));
export const getSystemInfo = () => {
return {
'release-it': pkg.version,
node: process.version,
os: osName()
};
};
export const format = (template = '', context = {}) => {
if (!context || context === null || !template || template === null || template.indexOf('${') === -1) return template;
const log = new Log();
try {
return eta.renderString(template, context);
} catch (error) {
log.error(`Unable to render template with context:\n${template}\n${JSON.stringify(context)}`);
log.error(error);
throw error;
}
};
export const truncateLines = (input, maxLines = 10, surplusText = null) => {
const lines = input.split(EOL);
const surplus = lines.length - maxLines;
const output = lines.slice(0, maxLines).join(EOL);
return surplus > 0 ? (surplusText ? `${output}${surplusText}` : `${output}${EOL}...and ${surplus} more`) : output;
};
export const rejectAfter = (ms, error) =>
wait(ms).then(() => {
throw error;
});
export const parseGitUrl = remoteUrl => {
if (!remoteUrl) return { host: null, owner: null, project: null, protocol: null, remote: null, repository: null };
const normalizedUrl = (remoteUrl || '')
.replace(/^[A-Z]:\\\\/, 'file://') // Assume file protocol for Windows drive letters
.replace(/^\//, 'file://') // Assume file protocol if only /path is given
.replace(/\\+/g, '/'); // Replace forward with backslashes
const parsedUrl = gitUrlParse(normalizedUrl);
const { resource: host, name: project, protocol, href: remote } = parsedUrl;
const owner = protocol === 'file' ? parsedUrl.owner.split('/').at(-1) : parsedUrl.owner; // Fix owner for file protocol
const repository = `${owner}/${project}`;
return { host, owner, project, protocol, remote, repository };
};
export const reduceUntil = async (collection, fn) => {
let result;
for (const item of collection) {
if (result) break;
result = await fn(item);
}
return result;
};
export const hasAccess = path => {
try {
accessSync(path);
return true;
} catch (err) {
return false;
}
};
export const parseVersion = raw => {
if (raw == null) return { version: raw, isPreRelease: false, preReleaseId: null };
const version = semver.valid(raw) ? raw : semver.coerce(raw);
if (!version) return { version: raw, isPreRelease: false, preReleaseId: null };
const parsed = semver.parse(version);
const isPreRelease = parsed.prerelease.length > 0;
const preReleaseId = isPreRelease && isNaN(parsed.prerelease[0]) ? parsed.prerelease[0] : null;
return {
version: version.toString(),
isPreRelease,
preReleaseId
};
};
export const e = (message, docs, fail = true) => {
const error = new Error(docs ? `${message}${EOL}Documentation: ${docs}${EOL}` : message);
error.code = fail ? 1 : 0;
error.cause = fail ? 'ERROR' : 'INFO';
return error;
};
/** @internal */
export const touch = (path, callback) => {
const stat = tryStatFile(path);
if (stat && stat.isDirectory()) {
// don't error just exit
return;
}
const fd = openSync(path, 'a');
close(fd);
const now = new Date();
const mtime = now;
const atime = now;
utimesSync(path, atime, mtime);
if (callback) {
callback();
}
};
export const fixArgs = args => (args ? (typeof args === 'string' ? args.split(' ') : args) : []);
export const upperFirst = string => {
return string ? string.charAt(0).toUpperCase() + string.slice(1) : '';
};
export const castArray = arr => {
return Array.isArray(arr) ? arr : [arr];
};
export const once = fn => {
return before(2, fn);
};
export const pick = (object, keys) => {
return keys.reduce((obj, key) => {
if (object && Object.prototype.hasOwnProperty.call(object, key)) {
obj[key] = object[key];
}
return obj;
}, {});
};
const parsePath = path => {
const result = [];
const regex = /[^.[\]]+|\[(?:(\d+)|["'](.+?)["'])\]/g;
let match;
while ((match = regex.exec(path)) !== null) {
result.push(match[1] ?? match[2] ?? match[0]);
}
return result;
};
export const get = (obj, path, defaultValue = undefined) => {
if (!path || typeof path !== 'string') {
return defaultValue;
}
try {
const keys = parsePath(path);
return keys.reduce((acc, key) => acc?.[key], obj) ?? defaultValue;
} catch {
return defaultValue;
}
};

1
node_modules/release-it/node_modules/.bin/semver generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../semver/bin/semver.js

541
node_modules/release-it/node_modules/mime-db/HISTORY.md generated vendored Normal file
View File

@@ -0,0 +1,541 @@
1.54.0 / 2025-03-17
===================
* Update mime type for DCM format (#362)
* mark application/octet-stream as compressible (#163)
* Fix typo in application/x-zip-compressed mimetype (#359)
* Add mime-type for Jupyter notebooks (#282)
* Add Google Drive MIME types (#311)
* Add .blend file type (#338)
* Add support for the FBX file extension (#342)
* Add Adobe DNG file (#340)
* Add Procreate Brush and Brush Set file Types (#339)
* Add support for Procreate Dreams (#341)
* replace got with undici (#352)
* Added extensions list for model/step (#293)
* Add m4b as a type of audio/mp4 (#357)
* windows 11 application/x-zip-compressed (#346)
* add dotLottie mime type (#351)
* Add some MS-related extensions and types (#336)
1.53.0 / 2024-07-12
===================
* Add extension `.sql` to `application/sql`
* Add extensions `.aac` and `.adts` to `audio/aac`
* Add extensions `.js` and `.mjs` to `text/javascript`
* Add extensions for `application/mp4` from IANA
* Add extensions from IANA for more MIME types
* Add Microsoft app installer types and extensions
* Add new upstream MIME types
* Fix extensions for `text/markdown` to match IANA
* Remove extension `.mjs` from `application/javascript`
* Remove obsolete MIME types from IANA data
1.52.0 / 2022-02-21
===================
* Add extensions from IANA for more `image/*` types
* Add extension `.asc` to `application/pgp-keys`
* Add extensions to various XML types
* Add new upstream MIME types
1.51.0 / 2021-11-08
===================
* Add new upstream MIME types
* Mark `image/vnd.microsoft.icon` as compressible
* Mark `image/vnd.ms-dds` as compressible
1.50.0 / 2021-09-15
===================
* Add deprecated iWorks mime types and extensions
* Add new upstream MIME types
1.49.0 / 2021-07-26
===================
* Add extension `.trig` to `application/trig`
* Add new upstream MIME types
1.48.0 / 2021-05-30
===================
* Add extension `.mvt` to `application/vnd.mapbox-vector-tile`
* Add new upstream MIME types
* Mark `text/yaml` as compressible
1.47.0 / 2021-04-01
===================
* Add new upstream MIME types
* Remove ambiguous extensions from IANA for `application/*+xml` types
* Update primary extension to `.es` for `application/ecmascript`
1.46.0 / 2021-02-13
===================
* Add extension `.amr` to `audio/amr`
* Add extension `.m4s` to `video/iso.segment`
* Add extension `.opus` to `audio/ogg`
* Add new upstream MIME types
1.45.0 / 2020-09-22
===================
* Add `application/ubjson` with extension `.ubj`
* Add `image/avif` with extension `.avif`
* Add `image/ktx2` with extension `.ktx2`
* Add extension `.dbf` to `application/vnd.dbf`
* Add extension `.rar` to `application/vnd.rar`
* Add extension `.td` to `application/urc-targetdesc+xml`
* Add new upstream MIME types
* Fix extension of `application/vnd.apple.keynote` to be `.key`
1.44.0 / 2020-04-22
===================
* Add charsets from IANA
* Add extension `.cjs` to `application/node`
* Add new upstream MIME types
1.43.0 / 2020-01-05
===================
* Add `application/x-keepass2` with extension `.kdbx`
* Add extension `.mxmf` to `audio/mobile-xmf`
* Add extensions from IANA for `application/*+xml` types
* Add new upstream MIME types
1.42.0 / 2019-09-25
===================
* Add `image/vnd.ms-dds` with extension `.dds`
* Add new upstream MIME types
* Remove compressible from `multipart/mixed`
1.41.0 / 2019-08-30
===================
* Add new upstream MIME types
* Add `application/toml` with extension `.toml`
* Mark `font/ttf` as compressible
1.40.0 / 2019-04-20
===================
* Add extensions from IANA for `model/*` types
* Add `text/mdx` with extension `.mdx`
1.39.0 / 2019-04-04
===================
* Add extensions `.siv` and `.sieve` to `application/sieve`
* Add new upstream MIME types
1.38.0 / 2019-02-04
===================
* Add extension `.nq` to `application/n-quads`
* Add extension `.nt` to `application/n-triples`
* Add new upstream MIME types
* Mark `text/less` as compressible
1.37.0 / 2018-10-19
===================
* Add extensions to HEIC image types
* Add new upstream MIME types
1.36.0 / 2018-08-20
===================
* Add Apple file extensions from IANA
* Add extensions from IANA for `image/*` types
* Add new upstream MIME types
1.35.0 / 2018-07-15
===================
* Add extension `.owl` to `application/rdf+xml`
* Add new upstream MIME types
- Removes extension `.woff` from `application/font-woff`
1.34.0 / 2018-06-03
===================
* Add extension `.csl` to `application/vnd.citationstyles.style+xml`
* Add extension `.es` to `application/ecmascript`
* Add new upstream MIME types
* Add `UTF-8` as default charset for `text/turtle`
* Mark all XML-derived types as compressible
1.33.0 / 2018-02-15
===================
* Add extensions from IANA for `message/*` types
* Add new upstream MIME types
* Fix some incorrect OOXML types
* Remove `application/font-woff2`
1.32.0 / 2017-11-29
===================
* Add new upstream MIME types
* Update `text/hjson` to registered `application/hjson`
* Add `text/shex` with extension `.shex`
1.31.0 / 2017-10-25
===================
* Add `application/raml+yaml` with extension `.raml`
* Add `application/wasm` with extension `.wasm`
* Add new `font` type from IANA
* Add new upstream font extensions
* Add new upstream MIME types
* Add extensions for JPEG-2000 images
1.30.0 / 2017-08-27
===================
* Add `application/vnd.ms-outlook`
* Add `application/x-arj`
* Add extension `.mjs` to `application/javascript`
* Add glTF types and extensions
* Add new upstream MIME types
* Add `text/x-org`
* Add VirtualBox MIME types
* Fix `source` records for `video/*` types that are IANA
* Update `font/opentype` to registered `font/otf`
1.29.0 / 2017-07-10
===================
* Add `application/fido.trusted-apps+json`
* Add extension `.wadl` to `application/vnd.sun.wadl+xml`
* Add new upstream MIME types
* Add `UTF-8` as default charset for `text/css`
1.28.0 / 2017-05-14
===================
* Add new upstream MIME types
* Add extension `.gz` to `application/gzip`
* Update extensions `.md` and `.markdown` to be `text/markdown`
1.27.0 / 2017-03-16
===================
* Add new upstream MIME types
* Add `image/apng` with extension `.apng`
1.26.0 / 2017-01-14
===================
* Add new upstream MIME types
* Add extension `.geojson` to `application/geo+json`
1.25.0 / 2016-11-11
===================
* Add new upstream MIME types
1.24.0 / 2016-09-18
===================
* Add `audio/mp3`
* Add new upstream MIME types
1.23.0 / 2016-05-01
===================
* Add new upstream MIME types
* Add extension `.3gpp` to `audio/3gpp`
1.22.0 / 2016-02-15
===================
* Add `text/slim`
* Add extension `.rng` to `application/xml`
* Add new upstream MIME types
* Fix extension of `application/dash+xml` to be `.mpd`
* Update primary extension to `.m4a` for `audio/mp4`
1.21.0 / 2016-01-06
===================
* Add Google document types
* Add new upstream MIME types
1.20.0 / 2015-11-10
===================
* Add `text/x-suse-ymp`
* Add new upstream MIME types
1.19.0 / 2015-09-17
===================
* Add `application/vnd.apple.pkpass`
* Add new upstream MIME types
1.18.0 / 2015-09-03
===================
* Add new upstream MIME types
1.17.0 / 2015-08-13
===================
* Add `application/x-msdos-program`
* Add `audio/g711-0`
* Add `image/vnd.mozilla.apng`
* Add extension `.exe` to `application/x-msdos-program`
1.16.0 / 2015-07-29
===================
* Add `application/vnd.uri-map`
1.15.0 / 2015-07-13
===================
* Add `application/x-httpd-php`
1.14.0 / 2015-06-25
===================
* Add `application/scim+json`
* Add `application/vnd.3gpp.ussd+xml`
* Add `application/vnd.biopax.rdf+xml`
* Add `text/x-processing`
1.13.0 / 2015-06-07
===================
* Add nginx as a source
* Add `application/x-cocoa`
* Add `application/x-java-archive-diff`
* Add `application/x-makeself`
* Add `application/x-perl`
* Add `application/x-pilot`
* Add `application/x-redhat-package-manager`
* Add `application/x-sea`
* Add `audio/x-m4a`
* Add `audio/x-realaudio`
* Add `image/x-jng`
* Add `text/mathml`
1.12.0 / 2015-06-05
===================
* Add `application/bdoc`
* Add `application/vnd.hyperdrive+json`
* Add `application/x-bdoc`
* Add extension `.rtf` to `text/rtf`
1.11.0 / 2015-05-31
===================
* Add `audio/wav`
* Add `audio/wave`
* Add extension `.litcoffee` to `text/coffeescript`
* Add extension `.sfd-hdstx` to `application/vnd.hydrostatix.sof-data`
* Add extension `.n-gage` to `application/vnd.nokia.n-gage.symbian.install`
1.10.0 / 2015-05-19
===================
* Add `application/vnd.balsamiq.bmpr`
* Add `application/vnd.microsoft.portable-executable`
* Add `application/x-ns-proxy-autoconfig`
1.9.1 / 2015-04-19
==================
* Remove `.json` extension from `application/manifest+json`
- This is causing bugs downstream
1.9.0 / 2015-04-19
==================
* Add `application/manifest+json`
* Add `application/vnd.micro+json`
* Add `image/vnd.zbrush.pcx`
* Add `image/x-ms-bmp`
1.8.0 / 2015-03-13
==================
* Add `application/vnd.citationstyles.style+xml`
* Add `application/vnd.fastcopy-disk-image`
* Add `application/vnd.gov.sk.xmldatacontainer+xml`
* Add extension `.jsonld` to `application/ld+json`
1.7.0 / 2015-02-08
==================
* Add `application/vnd.gerber`
* Add `application/vnd.msa-disk-image`
1.6.1 / 2015-02-05
==================
* Community extensions ownership transferred from `node-mime`
1.6.0 / 2015-01-29
==================
* Add `application/jose`
* Add `application/jose+json`
* Add `application/json-seq`
* Add `application/jwk+json`
* Add `application/jwk-set+json`
* Add `application/jwt`
* Add `application/rdap+json`
* Add `application/vnd.gov.sk.e-form+xml`
* Add `application/vnd.ims.imsccv1p3`
1.5.0 / 2014-12-30
==================
* Add `application/vnd.oracle.resource+json`
* Fix various invalid MIME type entries
- `application/mbox+xml`
- `application/oscp-response`
- `application/vwg-multiplexed`
- `audio/g721`
1.4.0 / 2014-12-21
==================
* Add `application/vnd.ims.imsccv1p2`
* Fix various invalid MIME type entries
- `application/vnd-acucobol`
- `application/vnd-curl`
- `application/vnd-dart`
- `application/vnd-dxr`
- `application/vnd-fdf`
- `application/vnd-mif`
- `application/vnd-sema`
- `application/vnd-wap-wmlc`
- `application/vnd.adobe.flash-movie`
- `application/vnd.dece-zip`
- `application/vnd.dvb_service`
- `application/vnd.micrografx-igx`
- `application/vnd.sealed-doc`
- `application/vnd.sealed-eml`
- `application/vnd.sealed-mht`
- `application/vnd.sealed-ppt`
- `application/vnd.sealed-tiff`
- `application/vnd.sealed-xls`
- `application/vnd.sealedmedia.softseal-html`
- `application/vnd.sealedmedia.softseal-pdf`
- `application/vnd.wap-slc`
- `application/vnd.wap-wbxml`
- `audio/vnd.sealedmedia.softseal-mpeg`
- `image/vnd-djvu`
- `image/vnd-svf`
- `image/vnd-wap-wbmp`
- `image/vnd.sealed-png`
- `image/vnd.sealedmedia.softseal-gif`
- `image/vnd.sealedmedia.softseal-jpg`
- `model/vnd-dwf`
- `model/vnd.parasolid.transmit-binary`
- `model/vnd.parasolid.transmit-text`
- `text/vnd-a`
- `text/vnd-curl`
- `text/vnd.wap-wml`
* Remove example template MIME types
- `application/example`
- `audio/example`
- `image/example`
- `message/example`
- `model/example`
- `multipart/example`
- `text/example`
- `video/example`
1.3.1 / 2014-12-16
==================
* Fix missing extensions
- `application/json5`
- `text/hjson`
1.3.0 / 2014-12-07
==================
* Add `application/a2l`
* Add `application/aml`
* Add `application/atfx`
* Add `application/atxml`
* Add `application/cdfx+xml`
* Add `application/dii`
* Add `application/json5`
* Add `application/lxf`
* Add `application/mf4`
* Add `application/vnd.apache.thrift.compact`
* Add `application/vnd.apache.thrift.json`
* Add `application/vnd.coffeescript`
* Add `application/vnd.enphase.envoy`
* Add `application/vnd.ims.imsccv1p1`
* Add `text/csv-schema`
* Add `text/hjson`
* Add `text/markdown`
* Add `text/yaml`
1.2.0 / 2014-11-09
==================
* Add `application/cea`
* Add `application/dit`
* Add `application/vnd.gov.sk.e-form+zip`
* Add `application/vnd.tmd.mediaflex.api+xml`
* Type `application/epub+zip` is now IANA-registered
1.1.2 / 2014-10-23
==================
* Rebuild database for `application/x-www-form-urlencoded` change
1.1.1 / 2014-10-20
==================
* Mark `application/x-www-form-urlencoded` as compressible.
1.1.0 / 2014-09-28
==================
* Add `application/font-woff2`
1.0.3 / 2014-09-25
==================
* Fix engine requirement in package
1.0.2 / 2014-09-25
==================
* Add `application/coap-group+json`
* Add `application/dcd`
* Add `application/vnd.apache.thrift.binary`
* Add `image/vnd.tencent.tap`
* Mark all JSON-derived types as compressible
* Update `text/vtt` data
1.0.1 / 2014-08-30
==================
* Fix extension ordering
1.0.0 / 2014-08-30
==================
* Add `application/atf`
* Add `application/merge-patch+json`
* Add `multipart/x-mixed-replace`
* Add `source: 'apache'` metadata
* Add `source: 'iana'` metadata
* Remove badly-assumed charset data

23
node_modules/release-it/node_modules/mime-db/LICENSE generated vendored Normal file
View File

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

109
node_modules/release-it/node_modules/mime-db/README.md generated vendored Normal file
View File

@@ -0,0 +1,109 @@
# mime-db
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-image]][node-url]
[![Build Status][ci-image]][ci-url]
[![Coverage Status][coveralls-image]][coveralls-url]
This is a large database of mime types and information about them.
It consists of a single, public JSON file and does not include any logic,
allowing it to remain as un-opinionated as possible with an API.
It aggregates data from the following sources:
- https://www.iana.org/assignments/media-types/media-types.xhtml
- https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
- https://hg.nginx.org/nginx/raw-file/default/conf/mime.types
## Installation
```bash
npm install mime-db
```
### Database Download
If you intend to use this in a web browser, you can conveniently access the JSON file via [jsDelivr](https://www.jsdelivr.com/), a popular CDN (Content Delivery Network). To ensure stability and compatibility, it is advisable to specify [a release tag](https://github.com/jshttp/mime-db/tags) instead of using the 'master' branch. This is because the JSON file's format might change in future updates, and relying on a specific release tag will prevent potential issues arising from these changes.
```
https://cdn.jsdelivr.net/gh/jshttp/mime-db@master/db.json
```
## Usage
```js
var db = require('mime-db')
// grab data on .js files
var data = db['application/javascript']
```
## Data Structure
The JSON file is a map lookup for lowercased mime types.
Each mime type has the following properties:
- `.source` - where the mime type is defined.
If not set, it's probably a custom media type.
- `apache` - [Apache common media types](https://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types)
- `iana` - [IANA-defined media types](https://www.iana.org/assignments/media-types/media-types.xhtml)
- `nginx` - [nginx media types](https://hg.nginx.org/nginx/raw-file/default/conf/mime.types)
- `.extensions[]` - known extensions associated with this mime type.
- `.compressible` - whether a file of this type can be gzipped.
- `.charset` - the default charset associated with this type, if any.
If unknown, every property could be `undefined`.
## Note on MIME Type Data and Semver
This package considers the programmatic api as the semver compatibility. This means the MIME type resolution is *not* considered
in the semver bumps. This means that if you want to pin your `mime-db` data you will need to do it in your application. While
this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is a breaking change.
## Contributing
The primary way to contribute to this database is by updating the data in
one of the upstream sources. The database is updated from the upstreams
periodically and will pull in any changes.
### Registering Media Types
The best way to get new media types included in this library is to register
them with the IANA. The community registration procedure is outlined in
[RFC 6838 section 5](https://tools.ietf.org/html/rfc6838#section-5). Types
registered with the IANA are automatically pulled into this library.
### Direct Inclusion
If that is not possible / feasible, they can be added directly here as a
"custom" type. To do this, it is required to have a primary source that
definitively lists the media type. If an extension is going to be listed as
associated with this media type, the source must definitively link the
media type and extension as well.
To edit the database, only make PRs against `src/custom-types.json` or
`src/custom-suffix.json`.
The `src/custom-types.json` file is a JSON object with the MIME type as the
keys and the values being an object with the following keys:
- `compressible` - leave out if you don't know, otherwise `true`/`false` to
indicate whether the data represented by the type is typically compressible.
- `extensions` - include an array of file extensions that are associated with
the type.
- `notes` - human-readable notes about the type, typically what the type is.
- `sources` - include an array of URLs of where the MIME type and the associated
extensions are sourced from. This needs to be a [primary source](https://en.wikipedia.org/wiki/Primary_source);
links to type aggregating sites and Wikipedia are _not acceptable_.
To update the build, run `npm run build`.
[ci-image]: https://badgen.net/github/checks/jshttp/mime-db/master?label=ci
[ci-url]: https://github.com/jshttp/mime-db/actions/workflows/ci.yml
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-db/master
[coveralls-url]: https://coveralls.io/r/jshttp/mime-db?branch=master
[node-image]: https://badgen.net/npm/node/mime-db
[node-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/mime-db
[npm-url]: https://npmjs.org/package/mime-db
[npm-version-image]: https://badgen.net/npm/v/mime-db

9342
node_modules/release-it/node_modules/mime-db/db.json generated vendored Normal file

File diff suppressed because it is too large Load Diff

12
node_modules/release-it/node_modules/mime-db/index.js generated vendored Normal file
View File

@@ -0,0 +1,12 @@
/*!
* mime-db
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015-2022 Douglas Christopher Wilson
* MIT Licensed
*/
/**
* Module exports.
*/
module.exports = require('./db.json')

View File

@@ -0,0 +1,56 @@
{
"name": "mime-db",
"description": "Media Type Database",
"version": "1.54.0",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)",
"Robert Kieffer <robert@broofa.com> (http://github.com/broofa)"
],
"license": "MIT",
"keywords": [
"mime",
"db",
"type",
"types",
"database",
"charset",
"charsets"
],
"repository": "jshttp/mime-db",
"devDependencies": {
"csv-parse": "4.16.3",
"eslint": "8.32.0",
"eslint-config-standard": "15.0.1",
"eslint-plugin-import": "2.27.5",
"eslint-plugin-markdown": "3.0.0",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "6.1.1",
"eslint-plugin-standard": "4.1.0",
"media-typer": "1.1.0",
"mocha": "10.2.0",
"nyc": "15.1.0",
"stream-to-array": "2.3.0",
"undici": "7.1.0"
},
"files": [
"HISTORY.md",
"LICENSE",
"README.md",
"db.json",
"index.js"
],
"engines": {
"node": ">= 0.6"
},
"scripts": {
"build": "node scripts/build",
"fetch": "node scripts/fetch-apache && node scripts/fetch-iana && node scripts/fetch-nginx",
"lint": "eslint .",
"test": "mocha --reporter spec --check-leaks test/",
"test-ci": "nyc --reporter=lcovonly --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test",
"update": "npm run fetch && npm run build",
"version": "node scripts/version-history.js && git add HISTORY.md"
}
}

View File

@@ -0,0 +1,421 @@
3.0.1 / 2025-03-26
===================
* deps: mime-db@1.54.0
3.0.0 / 2024-08-31
===================
* Drop support for node <18
* deps: mime-db@1.53.0
* resolve extension conflicts with mime-score (#119)
* asc -> application/pgp-signature is now application/pgp-keys
* mpp -> application/vnd.ms-project is now application/dash-patch+xml
* ac -> application/vnd.nokia.n-gage.ac+xml is now application/pkix-attr-cert
* bdoc -> application/x-bdoc is now application/bdoc
* wmz -> application/x-msmetafile is now application/x-ms-wmz
* xsl -> application/xslt+xml is now application/xml
* wav -> audio/wave is now audio/wav
* rtf -> text/rtf is now application/rtf
* xml -> text/xml is now application/xml
* mp4 -> video/mp4 is now application/mp4
* mpg4 -> video/mp4 is now application/mp4
2.1.35 / 2022-03-12
===================
* deps: mime-db@1.52.0
- Add extensions from IANA for more `image/*` types
- Add extension `.asc` to `application/pgp-keys`
- Add extensions to various XML types
- Add new upstream MIME types
2.1.34 / 2021-11-08
===================
* deps: mime-db@1.51.0
- Add new upstream MIME types
2.1.33 / 2021-10-01
===================
* deps: mime-db@1.50.0
- Add deprecated iWorks mime types and extensions
- Add new upstream MIME types
2.1.32 / 2021-07-27
===================
* deps: mime-db@1.49.0
- Add extension `.trig` to `application/trig`
- Add new upstream MIME types
2.1.31 / 2021-06-01
===================
* deps: mime-db@1.48.0
- Add extension `.mvt` to `application/vnd.mapbox-vector-tile`
- Add new upstream MIME types
2.1.30 / 2021-04-02
===================
* deps: mime-db@1.47.0
- Add extension `.amr` to `audio/amr`
- Remove ambigious extensions from IANA for `application/*+xml` types
- Update primary extension to `.es` for `application/ecmascript`
2.1.29 / 2021-02-17
===================
* deps: mime-db@1.46.0
- Add extension `.amr` to `audio/amr`
- Add extension `.m4s` to `video/iso.segment`
- Add extension `.opus` to `audio/ogg`
- Add new upstream MIME types
2.1.28 / 2021-01-01
===================
* deps: mime-db@1.45.0
- Add `application/ubjson` with extension `.ubj`
- Add `image/avif` with extension `.avif`
- Add `image/ktx2` with extension `.ktx2`
- Add extension `.dbf` to `application/vnd.dbf`
- Add extension `.rar` to `application/vnd.rar`
- Add extension `.td` to `application/urc-targetdesc+xml`
- Add new upstream MIME types
- Fix extension of `application/vnd.apple.keynote` to be `.key`
2.1.27 / 2020-04-23
===================
* deps: mime-db@1.44.0
- Add charsets from IANA
- Add extension `.cjs` to `application/node`
- Add new upstream MIME types
2.1.26 / 2020-01-05
===================
* deps: mime-db@1.43.0
- Add `application/x-keepass2` with extension `.kdbx`
- Add extension `.mxmf` to `audio/mobile-xmf`
- Add extensions from IANA for `application/*+xml` types
- Add new upstream MIME types
2.1.25 / 2019-11-12
===================
* deps: mime-db@1.42.0
- Add new upstream MIME types
- Add `application/toml` with extension `.toml`
- Add `image/vnd.ms-dds` with extension `.dds`
2.1.24 / 2019-04-20
===================
* deps: mime-db@1.40.0
- Add extensions from IANA for `model/*` types
- Add `text/mdx` with extension `.mdx`
2.1.23 / 2019-04-17
===================
* deps: mime-db@~1.39.0
- Add extensions `.siv` and `.sieve` to `application/sieve`
- Add new upstream MIME types
2.1.22 / 2019-02-14
===================
* deps: mime-db@~1.38.0
- Add extension `.nq` to `application/n-quads`
- Add extension `.nt` to `application/n-triples`
- Add new upstream MIME types
2.1.21 / 2018-10-19
===================
* deps: mime-db@~1.37.0
- Add extensions to HEIC image types
- Add new upstream MIME types
2.1.20 / 2018-08-26
===================
* deps: mime-db@~1.36.0
- Add Apple file extensions from IANA
- Add extensions from IANA for `image/*` types
- Add new upstream MIME types
2.1.19 / 2018-07-17
===================
* deps: mime-db@~1.35.0
- Add extension `.csl` to `application/vnd.citationstyles.style+xml`
- Add extension `.es` to `application/ecmascript`
- Add extension `.owl` to `application/rdf+xml`
- Add new upstream MIME types
- Add UTF-8 as default charset for `text/turtle`
2.1.18 / 2018-02-16
===================
* deps: mime-db@~1.33.0
- Add `application/raml+yaml` with extension `.raml`
- Add `application/wasm` with extension `.wasm`
- Add `text/shex` with extension `.shex`
- Add extensions for JPEG-2000 images
- Add extensions from IANA for `message/*` types
- Add new upstream MIME types
- Update font MIME types
- Update `text/hjson` to registered `application/hjson`
2.1.17 / 2017-09-01
===================
* deps: mime-db@~1.30.0
- Add `application/vnd.ms-outlook`
- Add `application/x-arj`
- Add extension `.mjs` to `application/javascript`
- Add glTF types and extensions
- Add new upstream MIME types
- Add `text/x-org`
- Add VirtualBox MIME types
- Fix `source` records for `video/*` types that are IANA
- Update `font/opentype` to registered `font/otf`
2.1.16 / 2017-07-24
===================
* deps: mime-db@~1.29.0
- Add `application/fido.trusted-apps+json`
- Add extension `.wadl` to `application/vnd.sun.wadl+xml`
- Add extension `.gz` to `application/gzip`
- Add new upstream MIME types
- Update extensions `.md` and `.markdown` to be `text/markdown`
2.1.15 / 2017-03-23
===================
* deps: mime-db@~1.27.0
- Add new mime types
- Add `image/apng`
2.1.14 / 2017-01-14
===================
* deps: mime-db@~1.26.0
- Add new mime types
2.1.13 / 2016-11-18
===================
* deps: mime-db@~1.25.0
- Add new mime types
2.1.12 / 2016-09-18
===================
* deps: mime-db@~1.24.0
- Add new mime types
- Add `audio/mp3`
2.1.11 / 2016-05-01
===================
* deps: mime-db@~1.23.0
- Add new mime types
2.1.10 / 2016-02-15
===================
* deps: mime-db@~1.22.0
- Add new mime types
- Fix extension of `application/dash+xml`
- Update primary extension for `audio/mp4`
2.1.9 / 2016-01-06
==================
* deps: mime-db@~1.21.0
- Add new mime types
2.1.8 / 2015-11-30
==================
* deps: mime-db@~1.20.0
- Add new mime types
2.1.7 / 2015-09-20
==================
* deps: mime-db@~1.19.0
- Add new mime types
2.1.6 / 2015-09-03
==================
* deps: mime-db@~1.18.0
- Add new mime types
2.1.5 / 2015-08-20
==================
* deps: mime-db@~1.17.0
- Add new mime types
2.1.4 / 2015-07-30
==================
* deps: mime-db@~1.16.0
- Add new mime types
2.1.3 / 2015-07-13
==================
* deps: mime-db@~1.15.0
- Add new mime types
2.1.2 / 2015-06-25
==================
* deps: mime-db@~1.14.0
- Add new mime types
2.1.1 / 2015-06-08
==================
* perf: fix deopt during mapping
2.1.0 / 2015-06-07
==================
* Fix incorrectly treating extension-less file name as extension
- i.e. `'path/to/json'` will no longer return `application/json`
* Fix `.charset(type)` to accept parameters
* Fix `.charset(type)` to match case-insensitive
* Improve generation of extension to MIME mapping
* Refactor internals for readability and no argument reassignment
* Prefer `application/*` MIME types from the same source
* Prefer any type over `application/octet-stream`
* deps: mime-db@~1.13.0
- Add nginx as a source
- Add new mime types
2.0.14 / 2015-06-06
===================
* deps: mime-db@~1.12.0
- Add new mime types
2.0.13 / 2015-05-31
===================
* deps: mime-db@~1.11.0
- Add new mime types
2.0.12 / 2015-05-19
===================
* deps: mime-db@~1.10.0
- Add new mime types
2.0.11 / 2015-05-05
===================
* deps: mime-db@~1.9.1
- Add new mime types
2.0.10 / 2015-03-13
===================
* deps: mime-db@~1.8.0
- Add new mime types
2.0.9 / 2015-02-09
==================
* deps: mime-db@~1.7.0
- Add new mime types
- Community extensions ownership transferred from `node-mime`
2.0.8 / 2015-01-29
==================
* deps: mime-db@~1.6.0
- Add new mime types
2.0.7 / 2014-12-30
==================
* deps: mime-db@~1.5.0
- Add new mime types
- Fix various invalid MIME type entries
2.0.6 / 2014-12-30
==================
* deps: mime-db@~1.4.0
- Add new mime types
- Fix various invalid MIME type entries
- Remove example template MIME types
2.0.5 / 2014-12-29
==================
* deps: mime-db@~1.3.1
- Fix missing extensions
2.0.4 / 2014-12-10
==================
* deps: mime-db@~1.3.0
- Add new mime types
2.0.3 / 2014-11-09
==================
* deps: mime-db@~1.2.0
- Add new mime types
2.0.2 / 2014-09-28
==================
* deps: mime-db@~1.1.0
- Add new mime types
- Update charsets
2.0.1 / 2014-09-07
==================
* Support Node.js 0.6
2.0.0 / 2014-09-02
==================
* Use `mime-db`
* Remove `.define()`
1.0.2 / 2014-08-04
==================
* Set charset=utf-8 for `text/javascript`
1.0.1 / 2014-06-24
==================
* Add `text/jsx` type
1.0.0 / 2014-05-12
==================
* Return `false` for unknown types
* Set charset=utf-8 for `application/json`
0.1.0 / 2014-05-02
==================
* Initial release

View File

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

View File

@@ -0,0 +1,126 @@
# mime-types
[![NPM Version][npm-version-image]][npm-url]
[![NPM Downloads][npm-downloads-image]][npm-url]
[![Node.js Version][node-version-image]][node-version-url]
[![Build Status][ci-image]][ci-url]
[![Test Coverage][coveralls-image]][coveralls-url]
The ultimate javascript content-type utility.
Similar to [the `mime@1.x` module](https://www.npmjs.com/package/mime), except:
- __No fallbacks.__ Instead of naively returning the first available type,
`mime-types` simply returns `false`, so do
`var type = mime.lookup('unrecognized') || 'application/octet-stream'`.
- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`.
- No `.define()` functionality
- Bug fixes for `.lookup(path)`
Otherwise, the API is compatible with `mime` 1.x.
## Install
This is a [Node.js](https://nodejs.org/en/) module available through the
[npm registry](https://www.npmjs.com/). Installation is done using the
[`npm install` command](https://docs.npmjs.com/getting-started/installing-npm-packages-locally):
```sh
$ npm install mime-types
```
## Note on MIME Type Data and Semver
This package considers the programmatic api as the semver compatibility. Additionally, the package which provides the MIME data
for this package (`mime-db`) *also* considers it's programmatic api as the semver contract. This means the MIME type resolution is *not* considered
in the semver bumps.
In the past the version of `mime-db` was pinned to give two decision points when adopting MIME data changes. This is no longer true. We still update the
`mime-db` package here as a `minor` release when necessary, but will use a `^` range going forward. This means that if you want to pin your `mime-db` data
you will need to do it in your application. While this expectation was not set in docs until now, it is how the pacakge operated, so we do not feel this is
a breaking change.
If you wish to pin your `mime-db` version you can do that with overrides via your package manager of choice. See their documentation for how to correctly configure that.
## Adding Types
All mime types are based on [mime-db](https://www.npmjs.com/package/mime-db),
so open a PR there if you'd like to add mime types.
## API
```js
var mime = require('mime-types')
```
All functions return `false` if input is invalid or not found.
### mime.lookup(path)
Lookup the content-type associated with a file.
```js
mime.lookup('json') // 'application/json'
mime.lookup('.md') // 'text/markdown'
mime.lookup('file.html') // 'text/html'
mime.lookup('folder/file.js') // 'application/javascript'
mime.lookup('folder/.htaccess') // false
mime.lookup('cats') // false
```
### mime.contentType(type)
Create a full content-type header given a content-type or extension.
When given an extension, `mime.lookup` is used to get the matching
content-type, otherwise the given content-type is used. Then if the
content-type does not already have a `charset` parameter, `mime.charset`
is used to get the default charset and add to the returned content-type.
```js
mime.contentType('markdown') // 'text/x-markdown; charset=utf-8'
mime.contentType('file.json') // 'application/json; charset=utf-8'
mime.contentType('text/html') // 'text/html; charset=utf-8'
mime.contentType('text/html; charset=iso-8859-1') // 'text/html; charset=iso-8859-1'
// from a full path
mime.contentType(path.extname('/path/to/file.json')) // 'application/json; charset=utf-8'
```
### mime.extension(type)
Get the default extension for a content-type.
```js
mime.extension('application/octet-stream') // 'bin'
```
### mime.charset(type)
Lookup the implied default charset of a content-type.
```js
mime.charset('text/markdown') // 'UTF-8'
```
### var type = mime.types[extension]
A map of content-types by extension.
### [extensions...] = mime.extensions[type]
A map of extensions by content-type.
## License
[MIT](LICENSE)
[ci-image]: https://badgen.net/github/checks/jshttp/mime-types/master?label=ci
[ci-url]: https://github.com/jshttp/mime-types/actions/workflows/ci.yml
[coveralls-image]: https://badgen.net/coveralls/c/github/jshttp/mime-types/master
[coveralls-url]: https://coveralls.io/r/jshttp/mime-types?branch=master
[node-version-image]: https://badgen.net/npm/node/mime-types
[node-version-url]: https://nodejs.org/en/download
[npm-downloads-image]: https://badgen.net/npm/dm/mime-types
[npm-url]: https://npmjs.org/package/mime-types
[npm-version-image]: https://badgen.net/npm/v/mime-types

View File

@@ -0,0 +1,211 @@
/*!
* mime-types
* Copyright(c) 2014 Jonathan Ong
* Copyright(c) 2015 Douglas Christopher Wilson
* MIT Licensed
*/
'use strict'
/**
* Module dependencies.
* @private
*/
var db = require('mime-db')
var extname = require('path').extname
var mimeScore = require('./mimeScore')
/**
* Module variables.
* @private
*/
var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/
var TEXT_TYPE_REGEXP = /^text\//i
/**
* Module exports.
* @public
*/
exports.charset = charset
exports.charsets = { lookup: charset }
exports.contentType = contentType
exports.extension = extension
exports.extensions = Object.create(null)
exports.lookup = lookup
exports.types = Object.create(null)
exports._extensionConflicts = []
// Populate the extensions/types maps
populateMaps(exports.extensions, exports.types)
/**
* Get the default charset for a MIME type.
*
* @param {string} type
* @return {boolean|string}
*/
function charset (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
var mime = match && db[match[1].toLowerCase()]
if (mime && mime.charset) {
return mime.charset
}
// default text/* to utf-8
if (match && TEXT_TYPE_REGEXP.test(match[1])) {
return 'UTF-8'
}
return false
}
/**
* Create a full Content-Type header given a MIME type or extension.
*
* @param {string} str
* @return {boolean|string}
*/
function contentType (str) {
// TODO: should this even be in this module?
if (!str || typeof str !== 'string') {
return false
}
var mime = str.indexOf('/') === -1 ? exports.lookup(str) : str
if (!mime) {
return false
}
// TODO: use content-type or other module
if (mime.indexOf('charset') === -1) {
var charset = exports.charset(mime)
if (charset) mime += '; charset=' + charset.toLowerCase()
}
return mime
}
/**
* Get the default extension for a MIME type.
*
* @param {string} type
* @return {boolean|string}
*/
function extension (type) {
if (!type || typeof type !== 'string') {
return false
}
// TODO: use media-typer
var match = EXTRACT_TYPE_REGEXP.exec(type)
// get extensions
var exts = match && exports.extensions[match[1].toLowerCase()]
if (!exts || !exts.length) {
return false
}
return exts[0]
}
/**
* Lookup the MIME type for a file path/extension.
*
* @param {string} path
* @return {boolean|string}
*/
function lookup (path) {
if (!path || typeof path !== 'string') {
return false
}
// get the extension ("ext" or ".ext" or full path)
var extension = extname('x.' + path)
.toLowerCase()
.slice(1)
if (!extension) {
return false
}
return exports.types[extension] || false
}
/**
* Populate the extensions and types maps.
* @private
*/
function populateMaps (extensions, types) {
Object.keys(db).forEach(function forEachMimeType (type) {
var mime = db[type]
var exts = mime.extensions
if (!exts || !exts.length) {
return
}
// mime -> extensions
extensions[type] = exts
// extension -> mime
for (var i = 0; i < exts.length; i++) {
var extension = exts[i]
types[extension] = _preferredType(extension, types[extension], type)
// DELETE (eventually): Capture extension->type maps that change as a
// result of switching to mime-score. This is just to help make reviewing
// PR #119 easier, and can be removed once that PR is approved.
const legacyType = _preferredTypeLegacy(
extension,
types[extension],
type
)
if (legacyType !== types[extension]) {
exports._extensionConflicts.push([extension, legacyType, types[extension]])
}
}
})
}
// Resolve type conflict using mime-score
function _preferredType (ext, type0, type1) {
var score0 = type0 ? mimeScore(type0, db[type0].source) : 0
var score1 = type1 ? mimeScore(type1, db[type1].source) : 0
return score0 > score1 ? type0 : type1
}
// Resolve type conflict using pre-mime-score logic
function _preferredTypeLegacy (ext, type0, type1) {
var SOURCE_RANK = ['nginx', 'apache', undefined, 'iana']
var score0 = type0 ? SOURCE_RANK.indexOf(db[type0].source) : 0
var score1 = type1 ? SOURCE_RANK.indexOf(db[type1].source) : 0
if (
exports.types[extension] !== 'application/octet-stream' &&
(score0 > score1 ||
(score0 === score1 &&
exports.types[extension]?.slice(0, 12) === 'application/'))
) {
return type0
}
return score0 > score1 ? type0 : type1
}

View File

@@ -0,0 +1,52 @@
// 'mime-score' back-ported to CommonJS
// Score RFC facets (see https://tools.ietf.org/html/rfc6838#section-3)
var FACET_SCORES = {
'prs.': 100,
'x-': 200,
'x.': 300,
'vnd.': 400,
default: 900
}
// Score mime source (Logic originally from `jshttp/mime-types` module)
var SOURCE_SCORES = {
nginx: 10,
apache: 20,
iana: 40,
default: 30 // definitions added by `jshttp/mime-db` project?
}
var TYPE_SCORES = {
// prefer application/xml over text/xml
// prefer application/rtf over text/rtf
application: 1,
// prefer font/woff over application/font-woff
font: 2,
default: 0
}
/**
* Get each component of the score for a mime type. The sum of these is the
* total score. The higher the score, the more "official" the type.
*/
module.exports = function mimeScore (mimeType, source = 'default') {
if (mimeType === 'application/octet-stream') {
return 0
}
const [type, subtype] = mimeType.split('/')
const facet = subtype.replace(/(\.|x-).*/, '$1')
const facetScore = FACET_SCORES[facet] || FACET_SCORES.default
const sourceScore = SOURCE_SCORES[source] || SOURCE_SCORES.default
const typeScore = TYPE_SCORES[type] || TYPE_SCORES.default
// All else being equal prefer shorter types
const lengthScore = 1 - mimeType.length / 100
return facetScore + sourceScore + typeScore + lengthScore
}

View File

@@ -0,0 +1,45 @@
{
"name": "mime-types",
"description": "The ultimate javascript content-type utility.",
"version": "3.0.1",
"contributors": [
"Douglas Christopher Wilson <doug@somethingdoug.com>",
"Jeremiah Senkpiel <fishrock123@rocketmail.com> (https://searchbeam.jit.su)",
"Jonathan Ong <me@jongleberry.com> (http://jongleberry.com)"
],
"license": "MIT",
"keywords": [
"mime",
"types"
],
"repository": "jshttp/mime-types",
"dependencies": {
"mime-db": "^1.54.0"
},
"devDependencies": {
"eslint": "8.33.0",
"eslint-config-standard": "14.1.1",
"eslint-plugin-import": "2.27.5",
"eslint-plugin-markdown": "3.0.0",
"eslint-plugin-node": "11.1.0",
"eslint-plugin-promise": "6.1.1",
"eslint-plugin-standard": "4.1.0",
"mocha": "10.2.0",
"nyc": "15.1.0"
},
"files": [
"HISTORY.md",
"LICENSE",
"index.js",
"mimeScore.js"
],
"engines": {
"node": ">= 0.6"
},
"scripts": {
"lint": "eslint .",
"test": "mocha --reporter spec test/test.js",
"test-ci": "nyc --reporter=lcov --reporter=text npm test",
"test-cov": "nyc --reporter=html --reporter=text npm test"
}
}

15
node_modules/release-it/node_modules/semver/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,15 @@
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

664
node_modules/release-it/node_modules/semver/README.md generated vendored Normal file
View File

@@ -0,0 +1,664 @@
semver(1) -- The semantic versioner for npm
===========================================
## Install
```bash
npm install semver
````
## Usage
As a node module:
```js
const semver = require('semver')
semver.valid('1.2.3') // '1.2.3'
semver.valid('a.b.c') // null
semver.clean(' =v1.2.3 ') // '1.2.3'
semver.satisfies('1.2.3', '1.x || >=2.5.0 || 5.0.0 - 7.2.3') // true
semver.gt('1.2.3', '9.8.7') // false
semver.lt('1.2.3', '9.8.7') // true
semver.minVersion('>=1.0.0') // '1.0.0'
semver.valid(semver.coerce('v2')) // '2.0.0'
semver.valid(semver.coerce('42.6.7.9.3-alpha')) // '42.6.7'
```
You can also just load the module for the function that you care about if
you'd like to minimize your footprint.
```js
// load the whole API at once in a single object
const semver = require('semver')
// or just load the bits you need
// all of them listed here, just pick and choose what you want
// classes
const SemVer = require('semver/classes/semver')
const Comparator = require('semver/classes/comparator')
const Range = require('semver/classes/range')
// functions for working with versions
const semverParse = require('semver/functions/parse')
const semverValid = require('semver/functions/valid')
const semverClean = require('semver/functions/clean')
const semverInc = require('semver/functions/inc')
const semverDiff = require('semver/functions/diff')
const semverMajor = require('semver/functions/major')
const semverMinor = require('semver/functions/minor')
const semverPatch = require('semver/functions/patch')
const semverPrerelease = require('semver/functions/prerelease')
const semverCompare = require('semver/functions/compare')
const semverRcompare = require('semver/functions/rcompare')
const semverCompareLoose = require('semver/functions/compare-loose')
const semverCompareBuild = require('semver/functions/compare-build')
const semverSort = require('semver/functions/sort')
const semverRsort = require('semver/functions/rsort')
// low-level comparators between versions
const semverGt = require('semver/functions/gt')
const semverLt = require('semver/functions/lt')
const semverEq = require('semver/functions/eq')
const semverNeq = require('semver/functions/neq')
const semverGte = require('semver/functions/gte')
const semverLte = require('semver/functions/lte')
const semverCmp = require('semver/functions/cmp')
const semverCoerce = require('semver/functions/coerce')
// working with ranges
const semverSatisfies = require('semver/functions/satisfies')
const semverMaxSatisfying = require('semver/ranges/max-satisfying')
const semverMinSatisfying = require('semver/ranges/min-satisfying')
const semverToComparators = require('semver/ranges/to-comparators')
const semverMinVersion = require('semver/ranges/min-version')
const semverValidRange = require('semver/ranges/valid')
const semverOutside = require('semver/ranges/outside')
const semverGtr = require('semver/ranges/gtr')
const semverLtr = require('semver/ranges/ltr')
const semverIntersects = require('semver/ranges/intersects')
const semverSimplifyRange = require('semver/ranges/simplify')
const semverRangeSubset = require('semver/ranges/subset')
```
As a command-line utility:
```
$ semver -h
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, prerelease, or release. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-n <0|1>
This is the base to be used for the prerelease identifier.
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.
```
## Versions
A "version" is described by the `v2.0.0` specification found at
<https://semver.org/>.
A leading `"="` or `"v"` character is stripped off and ignored.
Support for stripping a leading "v" is kept for compatibility with `v1.0.0` of the SemVer
specification but should not be used anymore.
## Ranges
A `version range` is a set of `comparators` that specify versions
that satisfy the range.
A `comparator` is composed of an `operator` and a `version`. The set
of primitive `operators` is:
* `<` Less than
* `<=` Less than or equal to
* `>` Greater than
* `>=` Greater than or equal to
* `=` Equal. If no operator is specified, then equality is assumed,
so this operator is optional but MAY be included.
For example, the comparator `>=1.2.7` would match the versions
`1.2.7`, `1.2.8`, `2.5.3`, and `1.3.9`, but not the versions `1.2.6`
or `1.1.0`. The comparator `>1` is equivalent to `>=2.0.0` and
would match the versions `2.0.0` and `3.1.0`, but not the versions
`1.0.1` or `1.1.0`.
Comparators can be joined by whitespace to form a `comparator set`,
which is satisfied by the **intersection** of all of the comparators
it includes.
A range is composed of one or more comparator sets, joined by `||`. A
version matches a range if and only if every comparator in at least
one of the `||`-separated comparator sets is satisfied by the version.
For example, the range `>=1.2.7 <1.3.0` would match the versions
`1.2.7`, `1.2.8`, and `1.2.99`, but not the versions `1.2.6`, `1.3.0`,
or `1.1.0`.
The range `1.2.7 || >=1.2.9 <2.0.0` would match the versions `1.2.7`,
`1.2.9`, and `1.4.6`, but not the versions `1.2.8` or `2.0.0`.
### Prerelease Tags
If a version has a prerelease tag (for example, `1.2.3-alpha.3`) then
it will only be allowed to satisfy comparator sets if at least one
comparator with the same `[major, minor, patch]` tuple also has a
prerelease tag.
For example, the range `>1.2.3-alpha.3` would be allowed to match the
version `1.2.3-alpha.7`, but it would *not* be satisfied by
`3.4.5-alpha.9`, even though `3.4.5-alpha.9` is technically "greater
than" `1.2.3-alpha.3` according to the SemVer sort rules. The version
range only accepts prerelease tags on the `1.2.3` version.
Version `3.4.5` *would* satisfy the range because it does not have a
prerelease flag, and `3.4.5` is greater than `1.2.3-alpha.7`.
The purpose of this behavior is twofold. First, prerelease versions
frequently are updated very quickly, and contain many breaking changes
that are (by the author's design) not yet fit for public consumption.
Therefore, by default, they are excluded from range-matching
semantics.
Second, a user who has opted into using a prerelease version has
indicated the intent to use *that specific* set of
alpha/beta/rc versions. By including a prerelease tag in the range,
the user is indicating that they are aware of the risk. However, it
is still not appropriate to assume that they have opted into taking a
similar risk on the *next* set of prerelease versions.
Note that this behavior can be suppressed (treating all prerelease
versions as if they were normal versions, for range-matching)
by setting the `includePrerelease` flag on the options
object to any
[functions](https://github.com/npm/node-semver#functions) that do
range matching.
#### Prerelease Identifiers
The method `.inc` takes an additional `identifier` string argument that
will append the value of the string as a prerelease identifier:
```javascript
semver.inc('1.2.3', 'prerelease', 'beta')
// '1.2.4-beta.0'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta
1.2.4-beta.0
```
Which then can be used to increment further:
```bash
$ semver 1.2.4-beta.0 -i prerelease
1.2.4-beta.1
```
To get out of the prerelease phase, use the `release` option:
```bash
$ semver 1.2.4-beta.1 -i release
1.2.4
```
#### Prerelease Identifier Base
The method `.inc` takes an optional parameter 'identifierBase' string
that will let you let your prerelease number as zero-based or one-based.
Set to `false` to omit the prerelease number altogether.
If you do not specify this parameter, it will default to zero-based.
```javascript
semver.inc('1.2.3', 'prerelease', 'beta', '1')
// '1.2.4-beta.1'
```
```javascript
semver.inc('1.2.3', 'prerelease', 'beta', false)
// '1.2.4-beta'
```
command-line example:
```bash
$ semver 1.2.3 -i prerelease --preid beta -n 1
1.2.4-beta.1
```
```bash
$ semver 1.2.3 -i prerelease --preid beta -n false
1.2.4-beta
```
### Advanced Range Syntax
Advanced range syntax desugars to primitive comparators in
deterministic ways.
Advanced ranges may be combined in the same way as primitive
comparators using white space or `||`.
#### Hyphen Ranges `X.Y.Z - A.B.C`
Specifies an inclusive set.
* `1.2.3 - 2.3.4` := `>=1.2.3 <=2.3.4`
If a partial version is provided as the first version in the inclusive
range, then the missing pieces are replaced with zeroes.
* `1.2 - 2.3.4` := `>=1.2.0 <=2.3.4`
If a partial version is provided as the second version in the
inclusive range, then all versions that start with the supplied parts
of the tuple are accepted, but nothing that would be greater than the
provided tuple parts.
* `1.2.3 - 2.3` := `>=1.2.3 <2.4.0-0`
* `1.2.3 - 2` := `>=1.2.3 <3.0.0-0`
#### X-Ranges `1.2.x` `1.X` `1.2.*` `*`
Any of `X`, `x`, or `*` may be used to "stand in" for one of the
numeric values in the `[major, minor, patch]` tuple.
* `*` := `>=0.0.0` (Any non-prerelease version satisfies, unless
`includePrerelease` is specified, in which case any version at all
satisfies)
* `1.x` := `>=1.0.0 <2.0.0-0` (Matching major version)
* `1.2.x` := `>=1.2.0 <1.3.0-0` (Matching major and minor versions)
A partial version range is treated as an X-Range, so the special
character is in fact optional.
* `""` (empty string) := `*` := `>=0.0.0`
* `1` := `1.x.x` := `>=1.0.0 <2.0.0-0`
* `1.2` := `1.2.x` := `>=1.2.0 <1.3.0-0`
#### Tilde Ranges `~1.2.3` `~1.2` `~1`
Allows patch-level changes if a minor version is specified on the
comparator. Allows minor-level changes if not.
* `~1.2.3` := `>=1.2.3 <1.(2+1).0` := `>=1.2.3 <1.3.0-0`
* `~1.2` := `>=1.2.0 <1.(2+1).0` := `>=1.2.0 <1.3.0-0` (Same as `1.2.x`)
* `~1` := `>=1.0.0 <(1+1).0.0` := `>=1.0.0 <2.0.0-0` (Same as `1.x`)
* `~0.2.3` := `>=0.2.3 <0.(2+1).0` := `>=0.2.3 <0.3.0-0`
* `~0.2` := `>=0.2.0 <0.(2+1).0` := `>=0.2.0 <0.3.0-0` (Same as `0.2.x`)
* `~0` := `>=0.0.0 <(0+1).0.0` := `>=0.0.0 <1.0.0-0` (Same as `0.x`)
* `~1.2.3-beta.2` := `>=1.2.3-beta.2 <1.3.0-0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
#### Caret Ranges `^1.2.3` `^0.2.5` `^0.0.4`
Allows changes that do not modify the left-most non-zero element in the
`[major, minor, patch]` tuple. In other words, this allows patch and
minor updates for versions `1.0.0` and above, patch updates for
versions `0.X >=0.1.0`, and *no* updates for versions `0.0.X`.
Many authors treat a `0.x` version as if the `x` were the major
"breaking-change" indicator.
Caret ranges are ideal when an author may make breaking changes
between `0.2.4` and `0.3.0` releases, which is a common practice.
However, it presumes that there will *not* be breaking changes between
`0.2.4` and `0.2.5`. It allows for changes that are presumed to be
additive (but non-breaking), according to commonly observed practices.
* `^1.2.3` := `>=1.2.3 <2.0.0-0`
* `^0.2.3` := `>=0.2.3 <0.3.0-0`
* `^0.0.3` := `>=0.0.3 <0.0.4-0`
* `^1.2.3-beta.2` := `>=1.2.3-beta.2 <2.0.0-0` Note that prereleases in
the `1.2.3` version will be allowed, if they are greater than or
equal to `beta.2`. So, `1.2.3-beta.4` would be allowed, but
`1.2.4-beta.2` would not, because it is a prerelease of a
different `[major, minor, patch]` tuple.
* `^0.0.3-beta` := `>=0.0.3-beta <0.0.4-0` Note that prereleases in the
`0.0.3` version *only* will be allowed, if they are greater than or
equal to `beta`. So, `0.0.3-pr.2` would be allowed.
When parsing caret ranges, a missing `patch` value desugars to the
number `0`, but will allow flexibility within that value, even if the
major and minor versions are both `0`.
* `^1.2.x` := `>=1.2.0 <2.0.0-0`
* `^0.0.x` := `>=0.0.0 <0.1.0-0`
* `^0.0` := `>=0.0.0 <0.1.0-0`
A missing `minor` and `patch` values will desugar to zero, but also
allow flexibility within those values, even if the major version is
zero.
* `^1.x` := `>=1.0.0 <2.0.0-0`
* `^0.x` := `>=0.0.0 <1.0.0-0`
### Range Grammar
Putting all this together, here is a Backus-Naur grammar for ranges,
for the benefit of parser authors:
```bnf
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+
```
## Functions
All methods and classes take a final `options` object argument. All
options in this object are `false` by default. The options supported
are:
- `loose`: Be more forgiving about not-quite-valid semver strings.
(Any resulting output will always be 100% strict compliant, of
course.) For backwards compatibility reasons, if the `options`
argument is a boolean value instead of an object, it is interpreted
to be the `loose` param.
- `includePrerelease`: Set to suppress the [default
behavior](https://github.com/npm/node-semver#prerelease-tags) of
excluding prerelease tagged versions from ranges unless they are
explicitly opted into.
Strict-mode Comparators and Ranges will be strict about the SemVer
strings that they parse.
* `valid(v)`: Return the parsed version, or null if it's not valid.
* `inc(v, releaseType, options, identifier, identifierBase)`:
Return the version incremented by the release
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
`prepatch`, `prerelease`, or `release`), or null if it's not valid
* `premajor` in one call will bump the version up to the next major
version and down to a prerelease of that major version.
`preminor`, and `prepatch` work the same way.
* If called from a non-prerelease version, `prerelease` will work the
same as `prepatch`. It increments the patch version and then makes a
prerelease. If the input version is already a prerelease it simply
increments it.
* `release` will remove any prerelease part of the version.
* `identifier` can be used to prefix `premajor`, `preminor`,
`prepatch`, or `prerelease` version increments. `identifierBase`
is the base to be used for the `prerelease` identifier.
* `prerelease(v)`: Returns an array of prerelease components, or null
if none exist. Example: `prerelease('1.2.3-alpha.1') -> ['alpha', 1]`
* `major(v)`: Return the major version number.
* `minor(v)`: Return the minor version number.
* `patch(v)`: Return the patch version number.
* `intersects(r1, r2, loose)`: Return true if the two supplied ranges
or comparators intersect.
* `parse(v)`: Attempt to parse a string as a semantic version, returning either
a `SemVer` object or `null`.
### Comparison
* `gt(v1, v2)`: `v1 > v2`
* `gte(v1, v2)`: `v1 >= v2`
* `lt(v1, v2)`: `v1 < v2`
* `lte(v1, v2)`: `v1 <= v2`
* `eq(v1, v2)`: `v1 == v2` This is true if they're logically equivalent,
even if they're not the same string. You already know how to
compare strings.
* `neq(v1, v2)`: `v1 != v2` The opposite of `eq`.
* `cmp(v1, comparator, v2)`: Pass in a comparison string, and it'll call
the corresponding function above. `"==="` and `"!=="` do simple
string comparison, but are included for completeness. Throws if an
invalid comparison string is provided.
* `compare(v1, v2)`: Return `0` if `v1 == v2`, or `1` if `v1` is greater, or `-1` if
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `rcompare(v1, v2)`: The reverse of `compare`. Sorts an array of versions
in descending order when passed to `Array.sort()`.
* `compareBuild(v1, v2)`: The same as `compare` but considers `build` when two versions
are equal. Sorts in ascending order if passed to `Array.sort()`.
* `compareLoose(v1, v2)`: Short for `compare(v1, v2, { loose: true })`.
* `diff(v1, v2)`: Returns the difference between two versions by the release type
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
or null if the versions are the same.
### Sorting
* `sort(versions)`: Returns a sorted array of versions based on the `compareBuild`
function.
* `rsort(versions)`: The reverse of `sort`. Returns an array of versions based on
the `compareBuild` function in descending order.
### Comparators
* `intersects(comparator)`: Return true if the comparators intersect
### Ranges
* `validRange(range)`: Return the valid range or null if it's not valid.
* `satisfies(version, range)`: Return true if the version satisfies the
range.
* `maxSatisfying(versions, range)`: Return the highest version in the list
that satisfies the range, or `null` if none of them do.
* `minSatisfying(versions, range)`: Return the lowest version in the list
that satisfies the range, or `null` if none of them do.
* `minVersion(range)`: Return the lowest version that can match
the given range.
* `gtr(version, range)`: Return `true` if the version is greater than all the
versions possible in the range.
* `ltr(version, range)`: Return `true` if the version is less than all the
versions possible in the range.
* `outside(version, range, hilo)`: Return true if the version is outside
the bounds of the range in either the high or low direction. The
`hilo` argument must be either the string `'>'` or `'<'`. (This is
the function called by `gtr` and `ltr`.)
* `intersects(range)`: Return true if any of the range comparators intersect.
* `simplifyRange(versions, range)`: Return a "simplified" range that
matches the same items in the `versions` list as the range specified. Note
that it does *not* guarantee that it would match the same versions in all
cases, only for the set of versions provided. This is useful when
generating ranges by joining together multiple versions with `||`
programmatically, to provide the user with something a bit more
ergonomic. If the provided range is shorter in string-length than the
generated range, then that is returned.
* `subset(subRange, superRange)`: Return `true` if the `subRange` range is
entirely contained by the `superRange` range.
Note that, since ranges may be non-contiguous, a version might not be
greater than a range, less than a range, *or* satisfy a range! For
example, the range `1.2 <1.2.9 || >2.0.0` would have a hole from `1.2.9`
until `2.0.0`, so version `1.2.10` would not be greater than the
range (because `2.0.1` satisfies, which is higher), nor less than the
range (since `1.2.8` satisfies, which is lower), and it also does not
satisfy the range.
If you want to know if a version satisfies or does not satisfy a
range, use the `satisfies(version, range)` function.
### Coercion
* `coerce(version, options)`: Coerces a string to semver if possible
This aims to provide a very forgiving translation of a non-semver string to
semver. It looks for the first digit in a string and consumes all
remaining characters which satisfy at least a partial semver (e.g., `1`,
`1.2`, `1.2.3`) up to the max permitted length (256 characters). Longer
versions are simply truncated (`4.6.3.9.2-alpha2` becomes `4.6.3`). All
surrounding text is simply ignored (`v3.4 replaces v3.3.1` becomes
`3.4.0`). Only text which lacks digits will fail coercion (`version one`
is not valid). The maximum length for any semver component considered for
coercion is 16 characters; longer components will be ignored
(`10000000000000000.4.7.4` becomes `4.7.4`). The maximum value for any
semver component is `Number.MAX_SAFE_INTEGER || (2**53 - 1)`; higher value
components are invalid (`9999999999999999.4.7.4` is likely invalid).
If the `options.rtl` flag is set, then `coerce` will return the right-most
coercible tuple that does not share an ending index with a longer coercible
tuple. For example, `1.2.3.4` will return `2.3.4` in rtl mode, not
`4.0.0`. `1.2.3/4` will return `4.0.0`, because the `4` is not a part of
any other overlapping SemVer tuple.
If the `options.includePrerelease` flag is set, then the `coerce` result will contain
prerelease and build parts of a version. For example, `1.2.3.4-rc.1+rev.2`
will preserve prerelease `rc.1` and build `rev.2` in the result.
### Clean
* `clean(version)`: Clean a string to be a valid semver if possible
This will return a cleaned and trimmed semver version. If the provided
version is not valid a null will be returned. This does not work for
ranges.
ex.
* `s.clean(' = v 2.1.5foo')`: `null`
* `s.clean(' = v 2.1.5foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean(' = v 2.1.5-foo')`: `null`
* `s.clean(' = v 2.1.5-foo', { loose: true })`: `'2.1.5-foo'`
* `s.clean('=v2.1.5')`: `'2.1.5'`
* `s.clean(' =v2.1.5')`: `'2.1.5'`
* `s.clean(' 2.1.5 ')`: `'2.1.5'`
* `s.clean('~1.0.0')`: `null`
## Constants
As a convenience, helper constants are exported to provide information about what `node-semver` supports:
### `RELEASE_TYPES`
- major
- premajor
- minor
- preminor
- patch
- prepatch
- prerelease
```
const semver = require('semver');
if (semver.RELEASE_TYPES.includes(arbitraryUserInput)) {
console.log('This is a valid release type!');
} else {
console.warn('This is NOT a valid release type!');
}
```
### `SEMVER_SPEC_VERSION`
2.0.0
```
const semver = require('semver');
console.log('We are currently using the semver specification version:', semver.SEMVER_SPEC_VERSION);
```
## Exported Modules
<!--
TODO: Make sure that all of these items are documented (classes aren't,
eg), and then pull the module name into the documentation for that specific
thing.
-->
You may pull in just the part of this semver utility that you need if you
are sensitive to packing and tree-shaking concerns. The main
`require('semver')` export uses getter functions to lazily load the parts
of the API that are used.
The following modules are available:
* `require('semver')`
* `require('semver/classes')`
* `require('semver/classes/comparator')`
* `require('semver/classes/range')`
* `require('semver/classes/semver')`
* `require('semver/functions/clean')`
* `require('semver/functions/cmp')`
* `require('semver/functions/coerce')`
* `require('semver/functions/compare')`
* `require('semver/functions/compare-build')`
* `require('semver/functions/compare-loose')`
* `require('semver/functions/diff')`
* `require('semver/functions/eq')`
* `require('semver/functions/gt')`
* `require('semver/functions/gte')`
* `require('semver/functions/inc')`
* `require('semver/functions/lt')`
* `require('semver/functions/lte')`
* `require('semver/functions/major')`
* `require('semver/functions/minor')`
* `require('semver/functions/neq')`
* `require('semver/functions/parse')`
* `require('semver/functions/patch')`
* `require('semver/functions/prerelease')`
* `require('semver/functions/rcompare')`
* `require('semver/functions/rsort')`
* `require('semver/functions/satisfies')`
* `require('semver/functions/sort')`
* `require('semver/functions/valid')`
* `require('semver/ranges/gtr')`
* `require('semver/ranges/intersects')`
* `require('semver/ranges/ltr')`
* `require('semver/ranges/max-satisfying')`
* `require('semver/ranges/min-satisfying')`
* `require('semver/ranges/min-version')`
* `require('semver/ranges/outside')`
* `require('semver/ranges/simplify')`
* `require('semver/ranges/subset')`
* `require('semver/ranges/to-comparators')`
* `require('semver/ranges/valid')`

191
node_modules/release-it/node_modules/semver/bin/semver.js generated vendored Executable file
View File

@@ -0,0 +1,191 @@
#!/usr/bin/env node
// Standalone semver comparison program.
// Exits successfully and prints matching version(s) if
// any supplied version is valid and passes all tests.
'use strict'
const argv = process.argv.slice(2)
let versions = []
const range = []
let inc = null
const version = require('../package.json').version
let loose = false
let includePrerelease = false
let coerce = false
let rtl = false
let identifier
let identifierBase
const semver = require('../')
const parseOptions = require('../internal/parse-options')
let reverse = false
let options = {}
const main = () => {
if (!argv.length) {
return help()
}
while (argv.length) {
let a = argv.shift()
const indexOfEqualSign = a.indexOf('=')
if (indexOfEqualSign !== -1) {
const value = a.slice(indexOfEqualSign + 1)
a = a.slice(0, indexOfEqualSign)
argv.unshift(value)
}
switch (a) {
case '-rv': case '-rev': case '--rev': case '--reverse':
reverse = true
break
case '-l': case '--loose':
loose = true
break
case '-p': case '--include-prerelease':
includePrerelease = true
break
case '-v': case '--version':
versions.push(argv.shift())
break
case '-i': case '--inc': case '--increment':
switch (argv[0]) {
case 'major': case 'minor': case 'patch': case 'prerelease':
case 'premajor': case 'preminor': case 'prepatch':
case 'release':
inc = argv.shift()
break
default:
inc = 'patch'
break
}
break
case '--preid':
identifier = argv.shift()
break
case '-r': case '--range':
range.push(argv.shift())
break
case '-n':
identifierBase = argv.shift()
if (identifierBase === 'false') {
identifierBase = false
}
break
case '-c': case '--coerce':
coerce = true
break
case '--rtl':
rtl = true
break
case '--ltr':
rtl = false
break
case '-h': case '--help': case '-?':
return help()
default:
versions.push(a)
break
}
}
options = parseOptions({ loose, includePrerelease, rtl })
versions = versions.map((v) => {
return coerce ? (semver.coerce(v, options) || { version: v }).version : v
}).filter((v) => {
return semver.valid(v)
})
if (!versions.length) {
return fail()
}
if (inc && (versions.length !== 1 || range.length)) {
return failInc()
}
for (let i = 0, l = range.length; i < l; i++) {
versions = versions.filter((v) => {
return semver.satisfies(v, range[i], options)
})
if (!versions.length) {
return fail()
}
}
versions
.sort((a, b) => semver[reverse ? 'rcompare' : 'compare'](a, b, options))
.map(v => semver.clean(v, options))
.map(v => inc ? semver.inc(v, inc, options, identifier, identifierBase) : v)
.forEach(v => console.log(v))
}
const failInc = () => {
console.error('--inc can only be used on a single version with no range')
fail()
}
const fail = () => process.exit(1)
const help = () => console.log(
`SemVer ${version}
A JavaScript implementation of the https://semver.org/ specification
Copyright Isaac Z. Schlueter
Usage: semver [options] <version> [<version> [...]]
Prints valid versions sorted by SemVer precedence
Options:
-r --range <range>
Print versions that match the specified range.
-i --increment [<level>]
Increment a version by the specified level. Level can
be one of: major, minor, patch, premajor, preminor,
prepatch, prerelease, or release. Default level is 'patch'.
Only one version may be specified.
--preid <identifier>
Identifier to be used to prefix premajor, preminor,
prepatch or prerelease version increments.
-l --loose
Interpret versions and ranges loosely
-p --include-prerelease
Always include prerelease versions in range matching
-c --coerce
Coerce a string into SemVer if possible
(does not imply --loose)
--rtl
Coerce version strings right to left
--ltr
Coerce version strings left to right (default)
-n <base>
Base number to be used for the prerelease identifier.
Can be either 0 or 1, or false to omit the number altogether.
Defaults to 0.
Program exits successfully if any valid version satisfies
all supplied ranges, and prints all satisfying versions.
If no satisfying versions are found, then exits failure.
Versions are printed in ascending order, so supplying
multiple versions to the utility will just sort them.`)
main()

View File

@@ -0,0 +1,143 @@
'use strict'
const ANY = Symbol('SemVer ANY')
// hoisted class for cyclic dependency
class Comparator {
static get ANY () {
return ANY
}
constructor (comp, options) {
options = parseOptions(options)
if (comp instanceof Comparator) {
if (comp.loose === !!options.loose) {
return comp
} else {
comp = comp.value
}
}
comp = comp.trim().split(/\s+/).join(' ')
debug('comparator', comp, options)
this.options = options
this.loose = !!options.loose
this.parse(comp)
if (this.semver === ANY) {
this.value = ''
} else {
this.value = this.operator + this.semver.version
}
debug('comp', this)
}
parse (comp) {
const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]
const m = comp.match(r)
if (!m) {
throw new TypeError(`Invalid comparator: ${comp}`)
}
this.operator = m[1] !== undefined ? m[1] : ''
if (this.operator === '=') {
this.operator = ''
}
// if it literally is just '>' or '' then allow anything.
if (!m[2]) {
this.semver = ANY
} else {
this.semver = new SemVer(m[2], this.options.loose)
}
}
toString () {
return this.value
}
test (version) {
debug('Comparator.test', version, this.options.loose)
if (this.semver === ANY || version === ANY) {
return true
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
return cmp(version, this.operator, this.semver, this.options)
}
intersects (comp, options) {
if (!(comp instanceof Comparator)) {
throw new TypeError('a Comparator is required')
}
if (this.operator === '') {
if (this.value === '') {
return true
}
return new Range(comp.value, options).test(this.value)
} else if (comp.operator === '') {
if (comp.value === '') {
return true
}
return new Range(this.value, options).test(comp.semver)
}
options = parseOptions(options)
// Special cases where nothing can possibly be lower
if (options.includePrerelease &&
(this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) {
return false
}
if (!options.includePrerelease &&
(this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) {
return false
}
// Same direction increasing (> or >=)
if (this.operator.startsWith('>') && comp.operator.startsWith('>')) {
return true
}
// Same direction decreasing (< or <=)
if (this.operator.startsWith('<') && comp.operator.startsWith('<')) {
return true
}
// same SemVer and both sides are inclusive (<= or >=)
if (
(this.semver.version === comp.semver.version) &&
this.operator.includes('=') && comp.operator.includes('=')) {
return true
}
// opposite directions less than
if (cmp(this.semver, '<', comp.semver, options) &&
this.operator.startsWith('>') && comp.operator.startsWith('<')) {
return true
}
// opposite directions greater than
if (cmp(this.semver, '>', comp.semver, options) &&
this.operator.startsWith('<') && comp.operator.startsWith('>')) {
return true
}
return false
}
}
module.exports = Comparator
const parseOptions = require('../internal/parse-options')
const { safeRe: re, t } = require('../internal/re')
const cmp = require('../functions/cmp')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const Range = require('./range')

View File

@@ -0,0 +1,7 @@
'use strict'
module.exports = {
SemVer: require('./semver.js'),
Range: require('./range.js'),
Comparator: require('./comparator.js'),
}

View File

@@ -0,0 +1,556 @@
'use strict'
const SPACE_CHARACTERS = /\s+/g
// hoisted class for cyclic dependency
class Range {
constructor (range, options) {
options = parseOptions(options)
if (range instanceof Range) {
if (
range.loose === !!options.loose &&
range.includePrerelease === !!options.includePrerelease
) {
return range
} else {
return new Range(range.raw, options)
}
}
if (range instanceof Comparator) {
// just put it in the set and return
this.raw = range.value
this.set = [[range]]
this.formatted = undefined
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First reduce all whitespace as much as possible so we do not have to rely
// on potentially slow regexes like \s*. This is then stored and used for
// future error messages as well.
this.raw = range.trim().replace(SPACE_CHARACTERS, ' ')
// First, split on ||
this.set = this.raw
.split('||')
// map the range to a 2d array of comparators
.map(r => this.parseRange(r.trim()))
// throw out any comparator lists that are empty
// this generally means that it was not a valid range, which is allowed
// in loose mode, but will still throw if the WHOLE range is invalid.
.filter(c => c.length)
if (!this.set.length) {
throw new TypeError(`Invalid SemVer Range: ${this.raw}`)
}
// if we have any that are not the null set, throw out null sets.
if (this.set.length > 1) {
// keep the first one, in case they're all null sets
const first = this.set[0]
this.set = this.set.filter(c => !isNullSet(c[0]))
if (this.set.length === 0) {
this.set = [first]
} else if (this.set.length > 1) {
// if we have any that are *, then the range is just *
for (const c of this.set) {
if (c.length === 1 && isAny(c[0])) {
this.set = [c]
break
}
}
}
}
this.formatted = undefined
}
get range () {
if (this.formatted === undefined) {
this.formatted = ''
for (let i = 0; i < this.set.length; i++) {
if (i > 0) {
this.formatted += '||'
}
const comps = this.set[i]
for (let k = 0; k < comps.length; k++) {
if (k > 0) {
this.formatted += ' '
}
this.formatted += comps[k].toString().trim()
}
}
}
return this.formatted
}
format () {
return this.range
}
toString () {
return this.range
}
parseRange (range) {
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts =
(this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) |
(this.options.loose && FLAG_LOOSE)
const memoKey = memoOpts + ':' + range
const cached = cache.get(memoKey)
if (cached) {
return cached
}
const loose = this.options.loose
// `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4`
const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]
range = range.replace(hr, hyphenReplace(this.options.includePrerelease))
debug('hyphen replace', range)
// `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5`
range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace)
debug('comparator trim', range)
// `~ 1.2.3` => `~1.2.3`
range = range.replace(re[t.TILDETRIM], tildeTrimReplace)
debug('tilde trim', range)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
debug('caret trim', range)
// At this point, the range is completely trimmed and
// ready to be split into comparators.
let rangeList = range
.split(' ')
.map(comp => parseComparator(comp, this.options))
.join(' ')
.split(/\s+/)
// >=0.0.0 is equivalent to *
.map(comp => replaceGTE0(comp, this.options))
if (loose) {
// in loose mode, throw out any that are not valid comparators
rangeList = rangeList.filter(comp => {
debug('loose invalid filter', comp, this.options)
return !!comp.match(re[t.COMPARATORLOOSE])
})
}
debug('range list', rangeList)
// if any comparators are the null set, then replace with JUST null set
// if more than one comparator, remove any * comparators
// also, don't include the same comparator more than once
const rangeMap = new Map()
const comparators = rangeList.map(comp => new Comparator(comp, this.options))
for (const comp of comparators) {
if (isNullSet(comp)) {
return [comp]
}
rangeMap.set(comp.value, comp)
}
if (rangeMap.size > 1 && rangeMap.has('')) {
rangeMap.delete('')
}
const result = [...rangeMap.values()]
cache.set(memoKey, result)
return result
}
intersects (range, options) {
if (!(range instanceof Range)) {
throw new TypeError('a Range is required')
}
return this.set.some((thisComparators) => {
return (
isSatisfiable(thisComparators, options) &&
range.set.some((rangeComparators) => {
return (
isSatisfiable(rangeComparators, options) &&
thisComparators.every((thisComparator) => {
return rangeComparators.every((rangeComparator) => {
return thisComparator.intersects(rangeComparator, options)
})
})
)
})
)
})
}
// if ANY of the sets match ALL of its comparators, then pass
test (version) {
if (!version) {
return false
}
if (typeof version === 'string') {
try {
version = new SemVer(version, this.options)
} catch (er) {
return false
}
}
for (let i = 0; i < this.set.length; i++) {
if (testSet(this.set[i], version, this.options)) {
return true
}
}
return false
}
}
module.exports = Range
const LRU = require('../internal/lrucache')
const cache = new LRU()
const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
safeRe: re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace,
} = require('../internal/re')
const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = require('../internal/constants')
const isNullSet = c => c.value === '<0.0.0-0'
const isAny = c => c.value === ''
// take a set of comparators and determine whether there
// exists a version which can satisfy it
const isSatisfiable = (comparators, options) => {
let result = true
const remainingComparators = comparators.slice()
let testComparator = remainingComparators.pop()
while (result && remainingComparators.length) {
result = remainingComparators.every((otherComparator) => {
return testComparator.intersects(otherComparator, options)
})
testComparator = remainingComparators.pop()
}
return result
}
// comprised of xranges, tildes, stars, and gtlt's at this point.
// already replaced the hyphen ranges
// turn into a set of JUST comparators.
const parseComparator = (comp, options) => {
debug('comp', comp, options)
comp = replaceCarets(comp, options)
debug('caret', comp)
comp = replaceTildes(comp, options)
debug('tildes', comp)
comp = replaceXRanges(comp, options)
debug('xrange', comp)
comp = replaceStars(comp, options)
debug('stars', comp)
return comp
}
const isX = id => !id || id.toLowerCase() === 'x' || id === '*'
// ~, ~> --> * (any, kinda silly)
// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0
// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0
// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0
// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0
// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0
// ~0.0.1 --> >=0.0.1 <0.1.0-0
const replaceTildes = (comp, options) => {
return comp
.trim()
.split(/\s+/)
.map((c) => replaceTilde(c, options))
.join(' ')
}
const replaceTilde = (comp, options) => {
const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]
return comp.replace(r, (_, M, m, p, pr) => {
debug('tilde', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0 <${+M + 1}.0.0-0`
} else if (isX(p)) {
// ~1.2 == >=1.2.0 <1.3.0-0
ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`
} else if (pr) {
debug('replaceTilde pr', pr)
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
} else {
// ~1.2.3 == >=1.2.3 <1.3.0-0
ret = `>=${M}.${m}.${p
} <${M}.${+m + 1}.0-0`
}
debug('tilde return', ret)
return ret
})
}
// ^ --> * (any, kinda silly)
// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0
// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0
// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0
// ^1.2.3 --> >=1.2.3 <2.0.0-0
// ^1.2.0 --> >=1.2.0 <2.0.0-0
// ^0.0.1 --> >=0.0.1 <0.0.2-0
// ^0.1.0 --> >=0.1.0 <0.2.0-0
const replaceCarets = (comp, options) => {
return comp
.trim()
.split(/\s+/)
.map((c) => replaceCaret(c, options))
.join(' ')
}
const replaceCaret = (comp, options) => {
debug('caret', comp, options)
const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]
const z = options.includePrerelease ? '-0' : ''
return comp.replace(r, (_, M, m, p, pr) => {
debug('caret', comp, _, M, m, p, pr)
let ret
if (isX(M)) {
ret = ''
} else if (isX(m)) {
ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0`
} else if (isX(p)) {
if (M === '0') {
ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0`
} else {
ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0`
}
} else if (pr) {
debug('replaceCaret pr', pr)
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p}-${pr
} <${+M + 1}.0.0-0`
}
} else {
debug('no pr')
if (M === '0') {
if (m === '0') {
ret = `>=${M}.${m}.${p
}${z} <${M}.${m}.${+p + 1}-0`
} else {
ret = `>=${M}.${m}.${p
}${z} <${M}.${+m + 1}.0-0`
}
} else {
ret = `>=${M}.${m}.${p
} <${+M + 1}.0.0-0`
}
}
debug('caret return', ret)
return ret
})
}
const replaceXRanges = (comp, options) => {
debug('replaceXRanges', comp, options)
return comp
.split(/\s+/)
.map((c) => replaceXRange(c, options))
.join(' ')
}
const replaceXRange = (comp, options) => {
comp = comp.trim()
const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]
return comp.replace(r, (ret, gtlt, M, m, p, pr) => {
debug('xRange', comp, ret, gtlt, M, m, p, pr)
const xM = isX(M)
const xm = xM || isX(m)
const xp = xm || isX(p)
const anyX = xp
if (gtlt === '=' && anyX) {
gtlt = ''
}
// if we're including prereleases in the match, then we need
// to fix this to -0, the lowest possible prerelease value
pr = options.includePrerelease ? '-0' : ''
if (xM) {
if (gtlt === '>' || gtlt === '<') {
// nothing is allowed
ret = '<0.0.0-0'
} else {
// nothing is forbidden
ret = '*'
}
} else if (gtlt && anyX) {
// we know patch is an x, because we have any x at all.
// replace X with 0
if (xm) {
m = 0
}
p = 0
if (gtlt === '>') {
// >1 => >=2.0.0
// >1.2 => >=1.3.0
gtlt = '>='
if (xm) {
M = +M + 1
m = 0
p = 0
} else {
m = +m + 1
p = 0
}
} else if (gtlt === '<=') {
// <=0.7.x is actually <0.8.0, since any 0.7.x should
// pass. Similarly, <=7.x is actually <8.0.0, etc.
gtlt = '<'
if (xm) {
M = +M + 1
} else {
m = +m + 1
}
}
if (gtlt === '<') {
pr = '-0'
}
ret = `${gtlt + M}.${m}.${p}${pr}`
} else if (xm) {
ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0`
} else if (xp) {
ret = `>=${M}.${m}.0${pr
} <${M}.${+m + 1}.0-0`
}
debug('xRange return', ret)
return ret
})
}
// Because * is AND-ed with everything else in the comparator,
// and '' means "any version", just remove the *s entirely.
const replaceStars = (comp, options) => {
debug('replaceStars', comp, options)
// Looseness is ignored here. star is always as loose as it gets!
return comp
.trim()
.replace(re[t.STAR], '')
}
const replaceGTE0 = (comp, options) => {
debug('replaceGTE0', comp, options)
return comp
.trim()
.replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '')
}
// This function is passed to string.replace(re[t.HYPHENRANGE])
// M, m, patch, prerelease, build
// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5
// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do
// 1.2 - 3.4 => >=1.2.0 <3.5.0-0
// TODO build?
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr) => {
if (isX(fM)) {
from = ''
} else if (isX(fm)) {
from = `>=${fM}.0.0${incPr ? '-0' : ''}`
} else if (isX(fp)) {
from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}`
} else if (fpr) {
from = `>=${from}`
} else {
from = `>=${from}${incPr ? '-0' : ''}`
}
if (isX(tM)) {
to = ''
} else if (isX(tm)) {
to = `<${+tM + 1}.0.0-0`
} else if (isX(tp)) {
to = `<${tM}.${+tm + 1}.0-0`
} else if (tpr) {
to = `<=${tM}.${tm}.${tp}-${tpr}`
} else if (incPr) {
to = `<${tM}.${tm}.${+tp + 1}-0`
} else {
to = `<=${to}`
}
return `${from} ${to}`.trim()
}
const testSet = (set, version, options) => {
for (let i = 0; i < set.length; i++) {
if (!set[i].test(version)) {
return false
}
}
if (version.prerelease.length && !options.includePrerelease) {
// Find the set of versions that are allowed to have prereleases
// For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0
// That should allow `1.2.3-pr.2` to pass.
// However, `1.2.4-alpha.notready` should NOT be allowed,
// even though it's within the range set by the comparators.
for (let i = 0; i < set.length; i++) {
debug(set[i].semver)
if (set[i].semver === Comparator.ANY) {
continue
}
if (set[i].semver.prerelease.length > 0) {
const allowed = set[i].semver
if (allowed.major === version.major &&
allowed.minor === version.minor &&
allowed.patch === version.patch) {
return true
}
}
}
// Version has a -pre, but it's not one of the ones we like.
return false
}
return true
}

View File

@@ -0,0 +1,319 @@
'use strict'
const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { safeRe: re, t } = require('../internal/re')
const parseOptions = require('../internal/parse-options')
const { compareIdentifiers } = require('../internal/identifiers')
class SemVer {
constructor (version, options) {
options = parseOptions(options)
if (version instanceof SemVer) {
if (version.loose === !!options.loose &&
version.includePrerelease === !!options.includePrerelease) {
return version
} else {
version = version.version
}
} else if (typeof version !== 'string') {
throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`)
}
if (version.length > MAX_LENGTH) {
throw new TypeError(
`version is longer than ${MAX_LENGTH} characters`
)
}
debug('SemVer', version, options)
this.options = options
this.loose = !!options.loose
// this isn't actually relevant for versions, but keep it so that we
// don't run into trouble passing this.options around.
this.includePrerelease = !!options.includePrerelease
const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL])
if (!m) {
throw new TypeError(`Invalid Version: ${version}`)
}
this.raw = version
// these are actually numbers
this.major = +m[1]
this.minor = +m[2]
this.patch = +m[3]
if (this.major > MAX_SAFE_INTEGER || this.major < 0) {
throw new TypeError('Invalid major version')
}
if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) {
throw new TypeError('Invalid minor version')
}
if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) {
throw new TypeError('Invalid patch version')
}
// numberify any prerelease numeric ids
if (!m[4]) {
this.prerelease = []
} else {
this.prerelease = m[4].split('.').map((id) => {
if (/^[0-9]+$/.test(id)) {
const num = +id
if (num >= 0 && num < MAX_SAFE_INTEGER) {
return num
}
}
return id
})
}
this.build = m[5] ? m[5].split('.') : []
this.format()
}
format () {
this.version = `${this.major}.${this.minor}.${this.patch}`
if (this.prerelease.length) {
this.version += `-${this.prerelease.join('.')}`
}
return this.version
}
toString () {
return this.version
}
compare (other) {
debug('SemVer.compare', this.version, this.options, other)
if (!(other instanceof SemVer)) {
if (typeof other === 'string' && other === this.version) {
return 0
}
other = new SemVer(other, this.options)
}
if (other.version === this.version) {
return 0
}
return this.compareMain(other) || this.comparePre(other)
}
compareMain (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
return (
compareIdentifiers(this.major, other.major) ||
compareIdentifiers(this.minor, other.minor) ||
compareIdentifiers(this.patch, other.patch)
)
}
comparePre (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
// NOT having a prerelease is > having one
if (this.prerelease.length && !other.prerelease.length) {
return -1
} else if (!this.prerelease.length && other.prerelease.length) {
return 1
} else if (!this.prerelease.length && !other.prerelease.length) {
return 0
}
let i = 0
do {
const a = this.prerelease[i]
const b = other.prerelease[i]
debug('prerelease compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
compareBuild (other) {
if (!(other instanceof SemVer)) {
other = new SemVer(other, this.options)
}
let i = 0
do {
const a = this.build[i]
const b = other.build[i]
debug('build compare', i, a, b)
if (a === undefined && b === undefined) {
return 0
} else if (b === undefined) {
return 1
} else if (a === undefined) {
return -1
} else if (a === b) {
continue
} else {
return compareIdentifiers(a, b)
}
} while (++i)
}
// preminor will bump the version up to the next minor release, and immediately
// down to pre-release. premajor and prepatch work the same way.
inc (release, identifier, identifierBase) {
if (release.startsWith('pre')) {
if (!identifier && identifierBase === false) {
throw new Error('invalid increment argument: identifier is empty')
}
// Avoid an invalid semver results
if (identifier) {
const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE])
if (!match || match[1] !== identifier) {
throw new Error(`invalid identifier: ${identifier}`)
}
}
}
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier, identifierBase)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier, identifierBase)
break
case 'prepatch':
// If this is already a prerelease, it will bump to the next version
// drop any prereleases that might already exist, since they are not
// relevant at this point.
this.prerelease.length = 0
this.inc('patch', identifier, identifierBase)
this.inc('pre', identifier, identifierBase)
break
// If the input is a non-prerelease version, this acts the same as
// prepatch.
case 'prerelease':
if (this.prerelease.length === 0) {
this.inc('patch', identifier, identifierBase)
}
this.inc('pre', identifier, identifierBase)
break
case 'release':
if (this.prerelease.length === 0) {
throw new Error(`version ${this.raw} is not a prerelease`)
}
this.prerelease.length = 0
break
case 'major':
// If this is a pre-major version, bump up to the same major version.
// Otherwise increment major.
// 1.0.0-5 bumps to 1.0.0
// 1.1.0 bumps to 2.0.0
if (
this.minor !== 0 ||
this.patch !== 0 ||
this.prerelease.length === 0
) {
this.major++
}
this.minor = 0
this.patch = 0
this.prerelease = []
break
case 'minor':
// If this is a pre-minor version, bump up to the same minor version.
// Otherwise increment minor.
// 1.2.0-5 bumps to 1.2.0
// 1.2.1 bumps to 1.3.0
if (this.patch !== 0 || this.prerelease.length === 0) {
this.minor++
}
this.patch = 0
this.prerelease = []
break
case 'patch':
// If this is not a pre-release version, it will increment the patch.
// If it is a pre-release it will bump up to the same patch version.
// 1.2.0-5 patches to 1.2.0
// 1.2.0 patches to 1.2.1
if (this.prerelease.length === 0) {
this.patch++
}
this.prerelease = []
break
// This probably shouldn't be used publicly.
// 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction.
case 'pre': {
const base = Number(identifierBase) ? 1 : 0
if (this.prerelease.length === 0) {
this.prerelease = [base]
} else {
let i = this.prerelease.length
while (--i >= 0) {
if (typeof this.prerelease[i] === 'number') {
this.prerelease[i]++
i = -2
}
}
if (i === -1) {
// didn't increment anything
if (identifier === this.prerelease.join('.') && identifierBase === false) {
throw new Error('invalid increment argument: identifier already exists')
}
this.prerelease.push(base)
}
}
if (identifier) {
// 1.2.0-beta.1 bumps to 1.2.0-beta.2,
// 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0
let prerelease = [identifier, base]
if (identifierBase === false) {
prerelease = [identifier]
}
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = prerelease
}
} else {
this.prerelease = prerelease
}
}
break
}
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.raw = this.format()
if (this.build.length) {
this.raw += `+${this.build.join('.')}`
}
return this
}
}
module.exports = SemVer

View File

@@ -0,0 +1,8 @@
'use strict'
const parse = require('./parse')
const clean = (version, options) => {
const s = parse(version.trim().replace(/^[=v]+/, ''), options)
return s ? s.version : null
}
module.exports = clean

View File

@@ -0,0 +1,54 @@
'use strict'
const eq = require('./eq')
const neq = require('./neq')
const gt = require('./gt')
const gte = require('./gte')
const lt = require('./lt')
const lte = require('./lte')
const cmp = (a, op, b, loose) => {
switch (op) {
case '===':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a === b
case '!==':
if (typeof a === 'object') {
a = a.version
}
if (typeof b === 'object') {
b = b.version
}
return a !== b
case '':
case '=':
case '==':
return eq(a, b, loose)
case '!=':
return neq(a, b, loose)
case '>':
return gt(a, b, loose)
case '>=':
return gte(a, b, loose)
case '<':
return lt(a, b, loose)
case '<=':
return lte(a, b, loose)
default:
throw new TypeError(`Invalid operator: ${op}`)
}
}
module.exports = cmp

View File

@@ -0,0 +1,62 @@
'use strict'
const SemVer = require('../classes/semver')
const parse = require('./parse')
const { safeRe: re, t } = require('../internal/re')
const coerce = (version, options) => {
if (version instanceof SemVer) {
return version
}
if (typeof version === 'number') {
version = String(version)
}
if (typeof version !== 'string') {
return null
}
options = options || {}
let match = null
if (!options.rtl) {
match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE])
} else {
// Find the right-most coercible string that does not share
// a terminus with a more left-ward coercible string.
// Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4'
// With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4'
//
// Walk through the string checking with a /g regexp
// Manually set the index so as to pick up overlapping matches.
// Stop when we get a match that ends at the string end, since no
// coercible string can be more right-ward without the same terminus.
const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL]
let next
while ((next = coerceRtlRegex.exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
coerceRtlRegex.lastIndex = -1
}
if (match === null) {
return null
}
const major = match[2]
const minor = match[3] || '0'
const patch = match[4] || '0'
const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : ''
const build = options.includePrerelease && match[6] ? `+${match[6]}` : ''
return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options)
}
module.exports = coerce

View File

@@ -0,0 +1,9 @@
'use strict'
const SemVer = require('../classes/semver')
const compareBuild = (a, b, loose) => {
const versionA = new SemVer(a, loose)
const versionB = new SemVer(b, loose)
return versionA.compare(versionB) || versionA.compareBuild(versionB)
}
module.exports = compareBuild

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose

View File

@@ -0,0 +1,7 @@
'use strict'
const SemVer = require('../classes/semver')
const compare = (a, b, loose) =>
new SemVer(a, loose).compare(new SemVer(b, loose))
module.exports = compare

View File

@@ -0,0 +1,60 @@
'use strict'
const parse = require('./parse.js')
const diff = (version1, version2) => {
const v1 = parse(version1, null, true)
const v2 = parse(version2, null, true)
const comparison = v1.compare(v2)
if (comparison === 0) {
return null
}
const v1Higher = comparison > 0
const highVersion = v1Higher ? v1 : v2
const lowVersion = v1Higher ? v2 : v1
const highHasPre = !!highVersion.prerelease.length
const lowHasPre = !!lowVersion.prerelease.length
if (lowHasPre && !highHasPre) {
// Going from prerelease -> no prerelease requires some special casing
// If the low version has only a major, then it will always be a major
// Some examples:
// 1.0.0-1 -> 1.0.0
// 1.0.0-1 -> 1.1.1
// 1.0.0-1 -> 2.0.0
if (!lowVersion.patch && !lowVersion.minor) {
return 'major'
}
// If the main part has no difference
if (lowVersion.compareMain(highVersion) === 0) {
if (lowVersion.minor && !lowVersion.patch) {
return 'minor'
}
return 'patch'
}
}
// add the `pre` prefix if we are going to a prerelease version
const prefix = highHasPre ? 'pre' : ''
if (v1.major !== v2.major) {
return prefix + 'major'
}
if (v1.minor !== v2.minor) {
return prefix + 'minor'
}
if (v1.patch !== v2.patch) {
return prefix + 'patch'
}
// high and low are preleases
return 'prerelease'
}
module.exports = diff

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const eq = (a, b, loose) => compare(a, b, loose) === 0
module.exports = eq

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const gt = (a, b, loose) => compare(a, b, loose) > 0
module.exports = gt

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const gte = (a, b, loose) => compare(a, b, loose) >= 0
module.exports = gte

View File

@@ -0,0 +1,21 @@
'use strict'
const SemVer = require('../classes/semver')
const inc = (version, release, options, identifier, identifierBase) => {
if (typeof (options) === 'string') {
identifierBase = identifier
identifier = options
options = undefined
}
try {
return new SemVer(
version instanceof SemVer ? version.version : version,
options
).inc(release, identifier, identifierBase).version
} catch (er) {
return null
}
}
module.exports = inc

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const lt = (a, b, loose) => compare(a, b, loose) < 0
module.exports = lt

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const lte = (a, b, loose) => compare(a, b, loose) <= 0
module.exports = lte

View File

@@ -0,0 +1,5 @@
'use strict'
const SemVer = require('../classes/semver')
const major = (a, loose) => new SemVer(a, loose).major
module.exports = major

View File

@@ -0,0 +1,5 @@
'use strict'
const SemVer = require('../classes/semver')
const minor = (a, loose) => new SemVer(a, loose).minor
module.exports = minor

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const neq = (a, b, loose) => compare(a, b, loose) !== 0
module.exports = neq

View File

@@ -0,0 +1,18 @@
'use strict'
const SemVer = require('../classes/semver')
const parse = (version, options, throwErrors = false) => {
if (version instanceof SemVer) {
return version
}
try {
return new SemVer(version, options)
} catch (er) {
if (!throwErrors) {
return null
}
throw er
}
}
module.exports = parse

View File

@@ -0,0 +1,5 @@
'use strict'
const SemVer = require('../classes/semver')
const patch = (a, loose) => new SemVer(a, loose).patch
module.exports = patch

View File

@@ -0,0 +1,8 @@
'use strict'
const parse = require('./parse')
const prerelease = (version, options) => {
const parsed = parse(version, options)
return (parsed && parsed.prerelease.length) ? parsed.prerelease : null
}
module.exports = prerelease

View File

@@ -0,0 +1,5 @@
'use strict'
const compare = require('./compare')
const rcompare = (a, b, loose) => compare(b, a, loose)
module.exports = rcompare

View File

@@ -0,0 +1,5 @@
'use strict'
const compareBuild = require('./compare-build')
const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose))
module.exports = rsort

View File

@@ -0,0 +1,12 @@
'use strict'
const Range = require('../classes/range')
const satisfies = (version, range, options) => {
try {
range = new Range(range, options)
} catch (er) {
return false
}
return range.test(version)
}
module.exports = satisfies

View File

@@ -0,0 +1,5 @@
'use strict'
const compareBuild = require('./compare-build')
const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose))
module.exports = sort

View File

@@ -0,0 +1,8 @@
'use strict'
const parse = require('./parse')
const valid = (version, options) => {
const v = parse(version, options)
return v ? v.version : null
}
module.exports = valid

91
node_modules/release-it/node_modules/semver/index.js generated vendored Normal file
View File

@@ -0,0 +1,91 @@
'use strict'
// just pre-load all the stuff that index.js lazily exports
const internalRe = require('./internal/re')
const constants = require('./internal/constants')
const SemVer = require('./classes/semver')
const identifiers = require('./internal/identifiers')
const parse = require('./functions/parse')
const valid = require('./functions/valid')
const clean = require('./functions/clean')
const inc = require('./functions/inc')
const diff = require('./functions/diff')
const major = require('./functions/major')
const minor = require('./functions/minor')
const patch = require('./functions/patch')
const prerelease = require('./functions/prerelease')
const compare = require('./functions/compare')
const rcompare = require('./functions/rcompare')
const compareLoose = require('./functions/compare-loose')
const compareBuild = require('./functions/compare-build')
const sort = require('./functions/sort')
const rsort = require('./functions/rsort')
const gt = require('./functions/gt')
const lt = require('./functions/lt')
const eq = require('./functions/eq')
const neq = require('./functions/neq')
const gte = require('./functions/gte')
const lte = require('./functions/lte')
const cmp = require('./functions/cmp')
const coerce = require('./functions/coerce')
const Comparator = require('./classes/comparator')
const Range = require('./classes/range')
const satisfies = require('./functions/satisfies')
const toComparators = require('./ranges/to-comparators')
const maxSatisfying = require('./ranges/max-satisfying')
const minSatisfying = require('./ranges/min-satisfying')
const minVersion = require('./ranges/min-version')
const validRange = require('./ranges/valid')
const outside = require('./ranges/outside')
const gtr = require('./ranges/gtr')
const ltr = require('./ranges/ltr')
const intersects = require('./ranges/intersects')
const simplifyRange = require('./ranges/simplify')
const subset = require('./ranges/subset')
module.exports = {
parse,
valid,
clean,
inc,
diff,
major,
minor,
patch,
prerelease,
compare,
rcompare,
compareLoose,
compareBuild,
sort,
rsort,
gt,
lt,
eq,
neq,
gte,
lte,
cmp,
coerce,
Comparator,
Range,
satisfies,
toComparators,
maxSatisfying,
minSatisfying,
minVersion,
validRange,
outside,
gtr,
ltr,
intersects,
simplifyRange,
subset,
SemVer,
re: internalRe.re,
src: internalRe.src,
tokens: internalRe.t,
SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION,
RELEASE_TYPES: constants.RELEASE_TYPES,
compareIdentifiers: identifiers.compareIdentifiers,
rcompareIdentifiers: identifiers.rcompareIdentifiers,
}

View File

@@ -0,0 +1,37 @@
'use strict'
// Note: this is the semver.org version of the spec that it implements
// Not necessarily the package version of this code.
const SEMVER_SPEC_VERSION = '2.0.0'
const MAX_LENGTH = 256
const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER ||
/* istanbul ignore next */ 9007199254740991
// Max safe segment length for coercion.
const MAX_SAFE_COMPONENT_LENGTH = 16
// Max safe length for a build identifier. The max length minus 6 characters for
// the shortest version with a build 0.0.0+BUILD.
const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6
const RELEASE_TYPES = [
'major',
'premajor',
'minor',
'preminor',
'patch',
'prepatch',
'prerelease',
]
module.exports = {
MAX_LENGTH,
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_SAFE_INTEGER,
RELEASE_TYPES,
SEMVER_SPEC_VERSION,
FLAG_INCLUDE_PRERELEASE: 0b001,
FLAG_LOOSE: 0b010,
}

View File

@@ -0,0 +1,11 @@
'use strict'
const debug = (
typeof process === 'object' &&
process.env &&
process.env.NODE_DEBUG &&
/\bsemver\b/i.test(process.env.NODE_DEBUG)
) ? (...args) => console.error('SEMVER', ...args)
: () => {}
module.exports = debug

View File

@@ -0,0 +1,25 @@
'use strict'
const numeric = /^[0-9]+$/
const compareIdentifiers = (a, b) => {
const anum = numeric.test(a)
const bnum = numeric.test(b)
if (anum && bnum) {
a = +a
b = +b
}
return a === b ? 0
: (anum && !bnum) ? -1
: (bnum && !anum) ? 1
: a < b ? -1
: 1
}
const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a)
module.exports = {
compareIdentifiers,
rcompareIdentifiers,
}

View File

@@ -0,0 +1,42 @@
'use strict'
class LRUCache {
constructor () {
this.max = 1000
this.map = new Map()
}
get (key) {
const value = this.map.get(key)
if (value === undefined) {
return undefined
} else {
// Remove the key from the map and add it to the end
this.map.delete(key)
this.map.set(key, value)
return value
}
}
delete (key) {
return this.map.delete(key)
}
set (key, value) {
const deleted = this.delete(key)
if (!deleted && value !== undefined) {
// If cache is full, delete the least recently used item
if (this.map.size >= this.max) {
const firstKey = this.map.keys().next().value
this.delete(firstKey)
}
this.map.set(key, value)
}
return this
}
}
module.exports = LRUCache

View File

@@ -0,0 +1,17 @@
'use strict'
// parse out just the options we care about
const looseOption = Object.freeze({ loose: true })
const emptyOpts = Object.freeze({ })
const parseOptions = options => {
if (!options) {
return emptyOpts
}
if (typeof options !== 'object') {
return looseOption
}
return options
}
module.exports = parseOptions

View File

@@ -0,0 +1,223 @@
'use strict'
const {
MAX_SAFE_COMPONENT_LENGTH,
MAX_SAFE_BUILD_LENGTH,
MAX_LENGTH,
} = require('./constants')
const debug = require('./debug')
exports = module.exports = {}
// The actual regexps go on exports.re
const re = exports.re = []
const safeRe = exports.safeRe = []
const src = exports.src = []
const safeSrc = exports.safeSrc = []
const t = exports.t = {}
let R = 0
const LETTERDASHNUMBER = '[a-zA-Z0-9-]'
// Replace some greedy regex tokens to prevent regex dos issues. These regex are
// used internally via the safeRe object since all inputs in this library get
// normalized first to trim and collapse all extra whitespace. The original
// regexes are exported for userland consumption and lower level usage. A
// future breaking change could export the safer regex only with a note that
// all input should have extra whitespace removed.
const safeRegexReplacements = [
['\\s', 1],
['\\d', MAX_LENGTH],
[LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH],
]
const makeSafeRegex = (value) => {
for (const [token, max] of safeRegexReplacements) {
value = value
.split(`${token}*`).join(`${token}{0,${max}}`)
.split(`${token}+`).join(`${token}{1,${max}}`)
}
return value
}
const createToken = (name, value, isGlobal) => {
const safe = makeSafeRegex(value)
const index = R++
debug(name, index, value)
t[name] = index
src[index] = value
safeSrc[index] = safe
re[index] = new RegExp(value, isGlobal ? 'g' : undefined)
safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined)
}
// The following Regular Expressions can be used for tokenizing,
// validating, and parsing SemVer version strings.
// ## Numeric Identifier
// A single `0`, or a non-zero digit followed by zero or more digits.
createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*')
createToken('NUMERICIDENTIFIERLOOSE', '\\d+')
// ## Non-numeric Identifier
// Zero or more digits, followed by a letter or hyphen, and then zero or
// more letters, digits, or hyphens.
createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`)
// ## Main Version
// Three dot-separated numeric identifiers.
createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})\\.` +
`(${src[t.NUMERICIDENTIFIER]})`)
createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` +
`(${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version Identifier
// A numeric identifier, or a non-numeric identifier.
// Non-numberic identifiers include numberic identifiers but can be longer.
// Therefore non-numberic identifiers must go first.
createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIER]})`)
createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER]
}|${src[t.NUMERICIDENTIFIERLOOSE]})`)
// ## Pre-release Version
// Hyphen, followed by one or more dot-separated pre-release version
// identifiers.
createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER]
}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`)
createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE]
}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`)
// ## Build Metadata Identifier
// Any combination of digits, letters, or hyphens.
createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`)
// ## Build Metadata
// Plus sign, followed by one or more period-separated build metadata
// identifiers.
createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER]
}(?:\\.${src[t.BUILDIDENTIFIER]})*))`)
// ## Full Version String
// A main version, followed optionally by a pre-release version and
// build metadata.
// Note that the only major, minor, patch, and pre-release sections of
// the version string are capturing groups. The build metadata is not a
// capturing group, because it should not ever be used in version
// comparison.
createToken('FULLPLAIN', `v?${src[t.MAINVERSION]
}${src[t.PRERELEASE]}?${
src[t.BUILD]}?`)
createToken('FULL', `^${src[t.FULLPLAIN]}$`)
// like full, but allows v1.2.3 and =1.2.3, which people do sometimes.
// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty
// common in the npm registry.
createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE]
}${src[t.PRERELEASELOOSE]}?${
src[t.BUILD]}?`)
createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`)
createToken('GTLT', '((?:<|>)?=?)')
// Something like "2.*" or "1.2.x".
// Note that "x.x" is a valid xRange identifer, meaning "any version"
// Only the first item is strictly required.
createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`)
createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`)
createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIER]})` +
`(?:${src[t.PRERELEASE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` +
`(?:${src[t.PRERELEASELOOSE]})?${
src[t.BUILD]}?` +
`)?)?`)
createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`)
createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`)
// Coercion.
// Extract anything that could conceivably be a part of a valid semver
createToken('COERCEPLAIN', `${'(^|[^\\d])' +
'(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` +
`(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`)
createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`)
createToken('COERCEFULL', src[t.COERCEPLAIN] +
`(?:${src[t.PRERELEASE]})?` +
`(?:${src[t.BUILD]})?` +
`(?:$|[^\\d])`)
createToken('COERCERTL', src[t.COERCE], true)
createToken('COERCERTLFULL', src[t.COERCEFULL], true)
// Tilde ranges.
// Meaning is "reasonably at or greater than"
createToken('LONETILDE', '(?:~>?)')
createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true)
exports.tildeTrimReplace = '$1~'
createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`)
createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`)
// Caret ranges.
// Meaning is "at least and backwards compatible with"
createToken('LONECARET', '(?:\\^)')
createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true)
exports.caretTrimReplace = '$1^'
createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`)
createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`)
// A simple gt/lt/eq thing, or just "" to indicate "any version"
createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`)
createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`)
// An expression to strip any whitespace between the gtlt and the thing
// it modifies, so that `> 1.2.3` ==> `>1.2.3`
createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT]
}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true)
exports.comparatorTrimReplace = '$1$2$3'
// Something like `1.2.3 - 1.2.4`
// Note that these all use the loose form, because they'll be
// checked against either the strict or loose comparator form
// later.
createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAIN]})` +
`\\s*$`)
createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` +
`\\s+-\\s+` +
`(${src[t.XRANGEPLAINLOOSE]})` +
`\\s*$`)
// Star ranges basically just allow anything at all.
createToken('STAR', '(<|>)?=?\\s*\\*')
// >=0.0.0 is like a star
createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$')
createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$')

View File

@@ -0,0 +1,78 @@
{
"name": "semver",
"version": "7.7.2",
"description": "The semantic version parser used by npm.",
"main": "index.js",
"scripts": {
"test": "tap",
"snap": "tap",
"lint": "npm run eslint",
"postlint": "template-oss-check",
"lintfix": "npm run eslint -- --fix",
"posttest": "npm run lint",
"template-oss-apply": "template-oss-apply --force",
"eslint": "eslint \"**/*.{js,cjs,ts,mjs,jsx,tsx}\""
},
"devDependencies": {
"@npmcli/eslint-config": "^5.0.0",
"@npmcli/template-oss": "4.24.3",
"benchmark": "^2.1.4",
"tap": "^16.0.0"
},
"license": "ISC",
"repository": {
"type": "git",
"url": "git+https://github.com/npm/node-semver.git"
},
"bin": {
"semver": "bin/semver.js"
},
"files": [
"bin/",
"lib/",
"classes/",
"functions/",
"internal/",
"ranges/",
"index.js",
"preload.js",
"range.bnf"
],
"tap": {
"timeout": 30,
"coverage-map": "map.js",
"nyc-arg": [
"--exclude",
"tap-snapshots/**"
]
},
"engines": {
"node": ">=10"
},
"author": "GitHub Inc.",
"templateOSS": {
"//@npmcli/template-oss": "This file is partially managed by @npmcli/template-oss. Edits may be overwritten.",
"version": "4.24.3",
"engines": ">=10",
"distPaths": [
"classes/",
"functions/",
"internal/",
"ranges/",
"index.js",
"preload.js",
"range.bnf"
],
"allowPaths": [
"/classes/",
"/functions/",
"/internal/",
"/ranges/",
"/index.js",
"/preload.js",
"/range.bnf",
"/benchmarks"
],
"publish": "true"
}
}

View File

@@ -0,0 +1,4 @@
'use strict'
// XXX remove in v8 or beyond
module.exports = require('./index.js')

16
node_modules/release-it/node_modules/semver/range.bnf generated vendored Normal file
View File

@@ -0,0 +1,16 @@
range-set ::= range ( logical-or range ) *
logical-or ::= ( ' ' ) * '||' ( ' ' ) *
range ::= hyphen | simple ( ' ' simple ) * | ''
hyphen ::= partial ' - ' partial
simple ::= primitive | partial | tilde | caret
primitive ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
partial ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
xr ::= 'x' | 'X' | '*' | nr
nr ::= '0' | [1-9] ( [0-9] ) *
tilde ::= '~' partial
caret ::= '^' partial
qualifier ::= ( '-' pre )? ( '+' build )?
pre ::= parts
build ::= parts
parts ::= part ( '.' part ) *
part ::= nr | [-0-9A-Za-z]+

View File

@@ -0,0 +1,6 @@
'use strict'
// Determine if version is greater than all the versions possible in the range.
const outside = require('./outside')
const gtr = (version, range, options) => outside(version, range, '>', options)
module.exports = gtr

View File

@@ -0,0 +1,9 @@
'use strict'
const Range = require('../classes/range')
const intersects = (r1, r2, options) => {
r1 = new Range(r1, options)
r2 = new Range(r2, options)
return r1.intersects(r2, options)
}
module.exports = intersects

View File

@@ -0,0 +1,6 @@
'use strict'
const outside = require('./outside')
// Determine if version is less than all the versions possible in the range
const ltr = (version, range, options) => outside(version, range, '<', options)
module.exports = ltr

View File

@@ -0,0 +1,27 @@
'use strict'
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const maxSatisfying = (versions, range, options) => {
let max = null
let maxSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!max || maxSV.compare(v) === -1) {
// compare(max, v, true)
max = v
maxSV = new SemVer(max, options)
}
}
})
return max
}
module.exports = maxSatisfying

View File

@@ -0,0 +1,26 @@
'use strict'
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const minSatisfying = (versions, range, options) => {
let min = null
let minSV = null
let rangeObj = null
try {
rangeObj = new Range(range, options)
} catch (er) {
return null
}
versions.forEach((v) => {
if (rangeObj.test(v)) {
// satisfies(v, range, options)
if (!min || minSV.compare(v) === 1) {
// compare(min, v, true)
min = v
minSV = new SemVer(min, options)
}
}
})
return min
}
module.exports = minSatisfying

View File

@@ -0,0 +1,63 @@
'use strict'
const SemVer = require('../classes/semver')
const Range = require('../classes/range')
const gt = require('../functions/gt')
const minVersion = (range, loose) => {
range = new Range(range, loose)
let minver = new SemVer('0.0.0')
if (range.test(minver)) {
return minver
}
minver = new SemVer('0.0.0-0')
if (range.test(minver)) {
return minver
}
minver = null
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let setMin = null
comparators.forEach((comparator) => {
// Clone to avoid manipulating the comparator's semver object.
const compver = new SemVer(comparator.semver.version)
switch (comparator.operator) {
case '>':
if (compver.prerelease.length === 0) {
compver.patch++
} else {
compver.prerelease.push(0)
}
compver.raw = compver.format()
/* fallthrough */
case '':
case '>=':
if (!setMin || gt(compver, setMin)) {
setMin = compver
}
break
case '<':
case '<=':
/* Ignore maximum versions */
break
/* istanbul ignore next */
default:
throw new Error(`Unexpected operation: ${comparator.operator}`)
}
})
if (setMin && (!minver || gt(minver, setMin))) {
minver = setMin
}
}
if (minver && range.test(minver)) {
return minver
}
return null
}
module.exports = minVersion

View File

@@ -0,0 +1,82 @@
'use strict'
const SemVer = require('../classes/semver')
const Comparator = require('../classes/comparator')
const { ANY } = Comparator
const Range = require('../classes/range')
const satisfies = require('../functions/satisfies')
const gt = require('../functions/gt')
const lt = require('../functions/lt')
const lte = require('../functions/lte')
const gte = require('../functions/gte')
const outside = (version, range, hilo, options) => {
version = new SemVer(version, options)
range = new Range(range, options)
let gtfn, ltefn, ltfn, comp, ecomp
switch (hilo) {
case '>':
gtfn = gt
ltefn = lte
ltfn = lt
comp = '>'
ecomp = '>='
break
case '<':
gtfn = lt
ltefn = gte
ltfn = gt
comp = '<'
ecomp = '<='
break
default:
throw new TypeError('Must provide a hilo val of "<" or ">"')
}
// If it satisfies the range it is not outside
if (satisfies(version, range, options)) {
return false
}
// From now on, variable terms are as if we're in "gtr" mode.
// but note that everything is flipped for the "ltr" function.
for (let i = 0; i < range.set.length; ++i) {
const comparators = range.set[i]
let high = null
let low = null
comparators.forEach((comparator) => {
if (comparator.semver === ANY) {
comparator = new Comparator('>=0.0.0')
}
high = high || comparator
low = low || comparator
if (gtfn(comparator.semver, high.semver, options)) {
high = comparator
} else if (ltfn(comparator.semver, low.semver, options)) {
low = comparator
}
})
// If the edge version comparator has a operator then our version
// isn't outside it
if (high.operator === comp || high.operator === ecomp) {
return false
}
// If the lowest version comparator has an operator and our version
// is less than it then it isn't higher than the range
if ((!low.operator || low.operator === comp) &&
ltefn(version, low.semver)) {
return false
} else if (low.operator === ecomp && ltfn(version, low.semver)) {
return false
}
}
return true
}
module.exports = outside

View File

@@ -0,0 +1,49 @@
'use strict'
// given a set of versions and a range, create a "simplified" range
// that includes the same versions that the original range does
// If the original range is shorter than the simplified one, return that.
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
module.exports = (versions, range, options) => {
const set = []
let first = null
let prev = null
const v = versions.sort((a, b) => compare(a, b, options))
for (const version of v) {
const included = satisfies(version, range, options)
if (included) {
prev = version
if (!first) {
first = version
}
} else {
if (prev) {
set.push([first, prev])
}
prev = null
first = null
}
}
if (first) {
set.push([first, null])
}
const ranges = []
for (const [min, max] of set) {
if (min === max) {
ranges.push(min)
} else if (!max && min === v[0]) {
ranges.push('*')
} else if (!max) {
ranges.push(`>=${min}`)
} else if (min === v[0]) {
ranges.push(`<=${max}`)
} else {
ranges.push(`${min} - ${max}`)
}
}
const simplified = ranges.join(' || ')
const original = typeof range.raw === 'string' ? range.raw : String(range)
return simplified.length < original.length ? simplified : range
}

View File

@@ -0,0 +1,249 @@
'use strict'
const Range = require('../classes/range.js')
const Comparator = require('../classes/comparator.js')
const { ANY } = Comparator
const satisfies = require('../functions/satisfies.js')
const compare = require('../functions/compare.js')
// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff:
// - Every simple range `r1, r2, ...` is a null set, OR
// - Every simple range `r1, r2, ...` which is not a null set is a subset of
// some `R1, R2, ...`
//
// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff:
// - If c is only the ANY comparator
// - If C is only the ANY comparator, return true
// - Else if in prerelease mode, return false
// - else replace c with `[>=0.0.0]`
// - If C is only the ANY comparator
// - if in prerelease mode, return true
// - else replace C with `[>=0.0.0]`
// - Let EQ be the set of = comparators in c
// - If EQ is more than one, return true (null set)
// - Let GT be the highest > or >= comparator in c
// - Let LT be the lowest < or <= comparator in c
// - If GT and LT, and GT.semver > LT.semver, return true (null set)
// - If any C is a = range, and GT or LT are set, return false
// - If EQ
// - If GT, and EQ does not satisfy GT, return true (null set)
// - If LT, and EQ does not satisfy LT, return true (null set)
// - If EQ satisfies every C, return true
// - Else return false
// - If GT
// - If GT.semver is lower than any > or >= comp in C, return false
// - If GT is >=, and GT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the GT.semver tuple, return false
// - If LT
// - If LT.semver is greater than any < or <= comp in C, return false
// - If LT is <=, and LT.semver does not satisfy every C, return false
// - If GT.semver has a prerelease, and not in prerelease mode
// - If no C has a prerelease and the LT.semver tuple, return false
// - Else return true
const subset = (sub, dom, options = {}) => {
if (sub === dom) {
return true
}
sub = new Range(sub, options)
dom = new Range(dom, options)
let sawNonNull = false
OUTER: for (const simpleSub of sub.set) {
for (const simpleDom of dom.set) {
const isSub = simpleSubset(simpleSub, simpleDom, options)
sawNonNull = sawNonNull || isSub !== null
if (isSub) {
continue OUTER
}
}
// the null set is a subset of everything, but null simple ranges in
// a complex range should be ignored. so if we saw a non-null range,
// then we know this isn't a subset, but if EVERY simple range was null,
// then it is a subset.
if (sawNonNull) {
return false
}
}
return true
}
const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')]
const minimumVersion = [new Comparator('>=0.0.0')]
const simpleSubset = (sub, dom, options) => {
if (sub === dom) {
return true
}
if (sub.length === 1 && sub[0].semver === ANY) {
if (dom.length === 1 && dom[0].semver === ANY) {
return true
} else if (options.includePrerelease) {
sub = minimumVersionWithPreRelease
} else {
sub = minimumVersion
}
}
if (dom.length === 1 && dom[0].semver === ANY) {
if (options.includePrerelease) {
return true
} else {
dom = minimumVersion
}
}
const eqSet = new Set()
let gt, lt
for (const c of sub) {
if (c.operator === '>' || c.operator === '>=') {
gt = higherGT(gt, c, options)
} else if (c.operator === '<' || c.operator === '<=') {
lt = lowerLT(lt, c, options)
} else {
eqSet.add(c.semver)
}
}
if (eqSet.size > 1) {
return null
}
let gtltComp
if (gt && lt) {
gtltComp = compare(gt.semver, lt.semver, options)
if (gtltComp > 0) {
return null
} else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) {
return null
}
}
// will iterate one or zero times
for (const eq of eqSet) {
if (gt && !satisfies(eq, String(gt), options)) {
return null
}
if (lt && !satisfies(eq, String(lt), options)) {
return null
}
for (const c of dom) {
if (!satisfies(eq, String(c), options)) {
return false
}
}
return true
}
let higher, lower
let hasDomLT, hasDomGT
// if the subset has a prerelease, we need a comparator in the superset
// with the same tuple and a prerelease, or it's not a subset
let needDomLTPre = lt &&
!options.includePrerelease &&
lt.semver.prerelease.length ? lt.semver : false
let needDomGTPre = gt &&
!options.includePrerelease &&
gt.semver.prerelease.length ? gt.semver : false
// exception: <1.2.3-0 is the same as <1.2.3
if (needDomLTPre && needDomLTPre.prerelease.length === 1 &&
lt.operator === '<' && needDomLTPre.prerelease[0] === 0) {
needDomLTPre = false
}
for (const c of dom) {
hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>='
hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<='
if (gt) {
if (needDomGTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomGTPre.major &&
c.semver.minor === needDomGTPre.minor &&
c.semver.patch === needDomGTPre.patch) {
needDomGTPre = false
}
}
if (c.operator === '>' || c.operator === '>=') {
higher = higherGT(gt, c, options)
if (higher === c && higher !== gt) {
return false
}
} else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) {
return false
}
}
if (lt) {
if (needDomLTPre) {
if (c.semver.prerelease && c.semver.prerelease.length &&
c.semver.major === needDomLTPre.major &&
c.semver.minor === needDomLTPre.minor &&
c.semver.patch === needDomLTPre.patch) {
needDomLTPre = false
}
}
if (c.operator === '<' || c.operator === '<=') {
lower = lowerLT(lt, c, options)
if (lower === c && lower !== lt) {
return false
}
} else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) {
return false
}
}
if (!c.operator && (lt || gt) && gtltComp !== 0) {
return false
}
}
// if there was a < or >, and nothing in the dom, then must be false
// UNLESS it was limited by another range in the other direction.
// Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0
if (gt && hasDomLT && !lt && gtltComp !== 0) {
return false
}
if (lt && hasDomGT && !gt && gtltComp !== 0) {
return false
}
// we needed a prerelease range in a specific tuple, but didn't get one
// then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0,
// because it includes prereleases in the 1.2.3 tuple
if (needDomGTPre || needDomLTPre) {
return false
}
return true
}
// >=1.2.3 is lower than >1.2.3
const higherGT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp > 0 ? a
: comp < 0 ? b
: b.operator === '>' && a.operator === '>=' ? b
: a
}
// <=1.2.3 is higher than <1.2.3
const lowerLT = (a, b, options) => {
if (!a) {
return b
}
const comp = compare(a.semver, b.semver, options)
return comp < 0 ? a
: comp > 0 ? b
: b.operator === '<' && a.operator === '<=' ? b
: a
}
module.exports = subset

View File

@@ -0,0 +1,10 @@
'use strict'
const Range = require('../classes/range')
// Mostly just for testing and legacy API reasons
const toComparators = (range, options) =>
new Range(range, options).set
.map(comp => comp.map(c => c.value).join(' ').trim().split(' '))
module.exports = toComparators

View File

@@ -0,0 +1,13 @@
'use strict'
const Range = require('../classes/range')
const validRange = (range, options) => {
try {
// Return '*' instead of '' so that truthiness works.
// This will throw if it's invalid anyway
return new Range(range, options).range || '*'
} catch (er) {
return null
}
}
module.exports = validRange

136
node_modules/release-it/package.json generated vendored Normal file
View File

@@ -0,0 +1,136 @@
{
"name": "release-it",
"version": "19.0.5",
"description": "Generic CLI tool to automate versioning and package publishing-related tasks.",
"keywords": [
"build",
"changelog",
"commit",
"distribution",
"git",
"github",
"gitlab",
"interactive",
"ci",
"npm",
"publish",
"push",
"release",
"release-it",
"repository",
"script",
"shell",
"tag",
"tool",
"version",
"semver",
"plugin"
],
"repository": {
"type": "git",
"url": "https://github.com/release-it/release-it.git"
},
"homepage": "https://github.com/release-it/release-it#readme",
"bugs": "https://github.com/release-it/release-it/issues",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/webpro"
},
{
"type": "opencollective",
"url": "https://opencollective.com/webpro"
}
],
"bin": {
"release-it": "bin/release-it.js"
},
"type": "module",
"exports": {
".": {
"types": "./types/index.d.ts",
"import": "./lib/index.js",
"require": "./lib/index.js"
},
"./package.json": "./package.json",
"./test/util/index.js": "./test/util/index.js"
},
"files": [
"bin",
"config",
"lib",
"test",
"schema",
"types"
],
"types": "./types/index.d.ts",
"scripts": {
"knip": "knip",
"lint": "eslint lib test",
"format": "prettier --write eslint.config.mjs \"{lib,test}/**/*.js\"",
"docs": "remark README.md 'docs/**/*.md' '.github/*.md' -o",
"test": "node --env-file=.env.test --test && installed-check",
"release": "./bin/release-it.js"
},
"author": {
"email": "lars@webpro.nl",
"name": "Lars Kappert"
},
"license": "MIT",
"dependencies": {
"@nodeutils/defaults-deep": "1.1.0",
"@octokit/rest": "22.0.0",
"@phun-ky/typeof": "2.0.3",
"async-retry": "1.3.3",
"c12": "3.3.0",
"ci-info": "^4.3.0",
"eta": "4.0.1",
"git-url-parse": "16.1.0",
"inquirer": "12.9.6",
"issue-parser": "7.0.1",
"lodash.merge": "4.6.2",
"mime-types": "3.0.1",
"new-github-release-url": "2.0.0",
"open": "10.2.0",
"ora": "9.0.0",
"os-name": "6.1.0",
"proxy-agent": "6.5.0",
"semver": "7.7.2",
"tinyglobby": "0.2.15",
"undici": "6.21.3",
"url-join": "5.0.0",
"wildcard-match": "5.1.4",
"yargs-parser": "21.1.1"
},
"devDependencies": {
"@eslint/compat": "1.3.2",
"@eslint/eslintrc": "3.3.1",
"@eslint/js": "9.35.0",
"@octokit/request-error": "7.0.0",
"@types/node": "24.5.2",
"eslint": "9.35.0",
"eslint-plugin-import-x": "4.16.1",
"globals": "16.4.0",
"installed-check": "9.3.0",
"knip": "5.63.1",
"mentoss": "0.11.0",
"mock-stdio": "1.0.3",
"prettier": "3.6.2",
"remark-cli": "12.0.1",
"remark-preset-webpro": "1.1.1",
"tar": "7.4.3",
"typescript": "5.9.2"
},
"overrides": {
"pac-resolver": "7.0.1",
"socks": "2.8.3"
},
"engines": {
"node": "^20.12.0 || >=22.0.0"
},
"remarkConfig": {
"plugins": [
"preset-webpro"
]
}
}

105
node_modules/release-it/schema/git.json generated vendored Normal file
View File

@@ -0,0 +1,105 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "release-it#git",
"title": "JSON schema for release-it Git configuration",
"type": "object",
"additionalItems": false,
"properties": {
"changelog": {
"type": "string",
"default": "git log --pretty=format:\"* %s (%h)\" ${from}...${to}"
},
"requireCleanWorkingDir": {
"type": "boolean",
"default": true
},
"requireBranch": {
"oneOf": [
{ "type": "boolean", "enum": [false] },
{ "type": "string" },
{ "type": "array", "items": { "type": "string" } }
],
"default": false
},
"requireUpstream": {
"type": "boolean",
"default": true
},
"requireCommits": {
"type": "boolean",
"default": false
},
"requireCommitsFail": {
"type": "boolean",
"default": true
},
"commitsPath": {
"type": "string",
"default": ""
},
"addUntrackedFiles": {
"type": "boolean",
"default": false
},
"commit": {
"type": "boolean",
"default": true
},
"commitArgs": {
"type": "array",
"uniqueItems": true,
"items": {
"type": "string"
},
"default": []
},
"commitMessage": {
"type": "string",
"default": null
},
"tag": {
"type": "boolean",
"default": true
},
"tagExclude": {
"type": "string",
"default": null
},
"tagMatch": {
"type": "string",
"default": null
},
"getLatestTagFromAllRefs": {
"type": "boolean",
"default": false
},
"tagAnnotation": {
"type": "string",
"default": "Release ${version}"
},
"tagArgs": {
"type": "array",
"uniqueItems": true,
"items": {
"type": "string"
},
"default": []
},
"push": {
"type": "boolean",
"default": true
},
"pushArgs": {
"type": "array",
"uniqueItems": true,
"items": {
"type": "string"
},
"default": ["--follow-tags"]
},
"pushRepo": {
"type": "string",
"default": ""
}
}
}

103
node_modules/release-it/schema/github.json generated vendored Normal file
View File

@@ -0,0 +1,103 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "release-it#github",
"title": "JSON schema for release-it github configuration",
"type": "object",
"additionalItems": false,
"properties": {
"release": {
"type": "boolean",
"default": false
},
"releaseName": {
"type": "string",
"default": "Release ${version}"
},
"releaseNotes": {
"anyOf": [
{ "type": ["string", "null"] },
{
"type": "object",
"properties": {
"commit": {
"type": "string"
},
"excludeMatches": {
"type": "array",
"items": {
"type": "string"
},
"default": []
}
}
}
],
"default": null
},
"autoGenerate": {
"type": "boolean",
"default": false
},
"makeLatest": {
"anyOf": [{ "type": "boolean" }, { "const": "legacy" }],
"default": true
},
"preRelease": {
"type": "boolean",
"default": false
},
"draft": {
"type": "boolean",
"default": false
},
"discussionCategoryName": {
"$comment": "Create discussion of the specified category and link to the GitHub Release",
"type": "string"
},
"tokenRef": {
"type": "string",
"default": "GITHUB_TOKEN"
},
"assets": {
"default": null
},
"host": {
"type": "string",
"default": null
},
"timeout": {
"type": "integer",
"default": 0
},
"proxy": {
"type": "string",
"default": null
},
"skipChecks": {
"type": "boolean",
"default": false
},
"web": {
"type": "boolean",
"default": false
},
"comments": {
"type": "object",
"additionalProperties": false,
"properties": {
"submit": {
"type": "boolean",
"default": false
},
"issue": {
"type": "string",
"default": ":rocket: _This issue has been resolved in v${version}. See [${releaseName}](${releaseUrl}) for release notes._"
},
"pr": {
"type": "string",
"default": ":rocket: _This pull request is included in v${version}. See [${releaseName}](${releaseUrl}) for release notes._"
}
}
}
}
}

80
node_modules/release-it/schema/gitlab.json generated vendored Normal file
View File

@@ -0,0 +1,80 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "release-it#gitlab",
"title": "JSON schema for release-it gitlab configuration",
"type": "object",
"additionalItems": false,
"properties": {
"release": {
"type": "boolean",
"default": false
},
"releaseName": {
"type": "string",
"default": "Release ${version}"
},
"releaseNotes": {
"default": null
},
"autoGenerate": {
"type": "boolean",
"default": false
},
"preRelease": {
"type": "boolean",
"default": false
},
"draft": {
"type": "boolean",
"default": false
},
"milestones": {
"type": "array",
"items": {
"type": "string"
},
"default": []
},
"tokenRef": {
"type": "string",
"default": "GITLAB_TOKEN"
},
"tokenHeader": {
"type": "string",
"default": "Private-Token"
},
"certificateAuthorityFile": {
"default": null
},
"certificateAuthorityFileRef": {
"type": "string",
"default": "CI_SERVER_TLS_CA_FILE"
},
"secure": {
"default": false
},
"assets": {
"default": null
},
"useIdsForUrls": {
"type": "boolean",
"default": false
},
"useGenericPackageRepositoryForAssets": {
"type": "boolean",
"default": false
},
"genericPackageRepositoryName": {
"type": "string",
"default": "release-it"
},
"origin": {
"type": "string",
"default": null
},
"skipChecks": {
"type": "boolean",
"default": false
}
}
}

57
node_modules/release-it/schema/npm.json generated vendored Normal file
View File

@@ -0,0 +1,57 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "release-it#npm",
"title": "JSON schema for release-it npm configuration",
"type": "object",
"additionalItems": false,
"properties": {
"publish": {
"type": "boolean",
"default": true
},
"publishPath": {
"type": "string",
"default": "."
},
"publishArgs": {
"type": "array",
"uniqueItems": true,
"items": {
"type": "string"
},
"default": []
},
"tag": {
"type": "string",
"default": null
},
"otp": {
"type": "string",
"default": null
},
"ignoreVersion": {
"type": "boolean",
"default": false
},
"allowSameVersion": {
"type": "boolean",
"default": false
},
"versionArgs": {
"type": "array",
"uniqueItems": true,
"items": {
"type": "string"
},
"default": []
},
"skipChecks": {
"type": "boolean",
"default": false
},
"timeout": {
"type": "integer",
"default": 10
}
}
}

93
node_modules/release-it/schema/release-it.json generated vendored Normal file
View File

@@ -0,0 +1,93 @@
{
"$schema": "http://json-schema.org/draft-07/schema",
"$id": "release-it#release-it",
"title": "JSON schema for release-it configuration",
"type": "object",
"additionalProperties": false,
"properties": {
"$schema": {
"type": "string",
"description": "The JSON schema version used to validate this configuration file"
},
"extends": {
"type": "string",
"description": "URL that specifies a configuration to extend"
},
"hooks": {
"type": "object",
"additionalProperties": true,
"patternProperties": {
"^(before|after):((version|git|npm|github|gitlab):)?(init|bump|release)$": {
"if": {
"type": "array"
},
"then": {
"type": "array",
"items": {
"type": "string"
}
},
"else": {
"type": "string"
}
}
}
},
"plugins": {
"type": "object",
"additionalProperties": true
},
"git": {
"$comment": "Boolean or git config object",
"if": {
"type": "object"
},
"then": {
"$ref": "./git.json"
},
"else": {
"type": "boolean",
"default": false
}
},
"npm": {
"$comment": "Boolean or npm config object",
"if": {
"type": "object"
},
"then": {
"$ref": "./npm.json"
},
"else": {
"type": "boolean",
"default": false
}
},
"github": {
"$comment": "Boolean or github config object",
"if": {
"type": "object"
},
"then": {
"$ref": "./github.json"
},
"else": {
"type": "boolean",
"default": false
}
},
"gitlab": {
"$comment": "Boolean or gitlab config object",
"if": {
"type": "object"
},
"then": {
"$ref": "./gitlab.json"
},
"else": {
"type": "boolean",
"default": false
}
}
}
}

27
node_modules/release-it/test/args.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { parseCliArguments } from '../lib/args.js';
test('should parse boolean arguments', () => {
const args = [
'--dry-run=false',
'--ci',
'--github=false',
'--no-npm',
'--git.addUntrackedFiles=true',
'--git.commit=false',
'--no-git.tag',
'--git.commitMessage=test'
];
const result = parseCliArguments(args);
assert.equal(result['dry-run'], false);
assert.equal(result.ci, true);
assert.equal(result.github, false);
assert.equal(result.npm, false);
assert.equal(result.git.addUntrackedFiles, true);
assert.equal(result.git.commit, false);
assert.equal(result.git.tag, false);
assert.equal(result.git.commitMessage, 'test');
});

21
node_modules/release-it/test/cli.js generated vendored Normal file
View File

@@ -0,0 +1,21 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import mockStdIo from 'mock-stdio';
import { version, help } from '../lib/cli.js';
import { readJSON } from '../lib/util.js';
const pkg = readJSON(new URL('../package.json', import.meta.url));
test('should print version', () => {
mockStdIo.start();
version();
const { stdout } = mockStdIo.end();
assert.equal(stdout, `v${pkg.version}\n`);
});
test('should print help', () => {
mockStdIo.start();
help();
const { stdout } = mockStdIo.end();
assert.match(stdout, new RegExp(`Release It!.+${pkg.version}`));
});

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