Add node modules and compiled JavaScript from main (#54)

Co-authored-by: Oliver King <oking3@uncc.edu>
This commit is contained in:
github-actions[bot]
2022-06-29 15:41:55 -04:00
committed by GitHub
parent 4a983766a0
commit 52d71d28bd
6814 changed files with 2048539 additions and 2 deletions

1
node_modules/ts-jest/.ts-jest-digest generated vendored Normal file
View File

@ -0,0 +1 @@
60d8111ee0c613e292a844a081abf56c285c9036

1588
node_modules/ts-jest/CHANGELOG.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

120
node_modules/ts-jest/CONTRIBUTING.md generated vendored Normal file
View File

@ -0,0 +1,120 @@
# Contributing
When contributing to this repository, please first discuss the change you wish to make via
[discussion](https://github.com/kulshekhar/ts-jest/discussions) or [issue](https://github.com/kulshekhar/ts-jest/issues)
with the owners of this repository before making a change.
Please note we have a code of conduct, please follow it in all your interactions with the project.
## Workflow and Pull Requests
The team will monitor pull requests. We'll do our best to provide updates and feedback throughout the process.
_Before_ submitting a pull request, please make sure the following is done…
1. Fork the repo and create your branch from `main`. A guide on how to fork a repository: https://help.github.com/articles/fork-a-repo/
Open terminal (e.g. Terminal, iTerm, Git Bash or Git Shell) and type:
```sh-session
$ git clone https://github.com/<your_username>/ts-jest
$ cd ts-jest
$ git checkout -b my_branch
```
Note: Replace `<your_username>` with your GitHub username
2. `ts-jest` uses `npm` for running development scripts. If you haven't already done so, please [install npm](https://docs.npmjs.com/downloading-and-installing-node-js-and-npm).
3. Make sure you have a compatible version of `node` installed (As of April 14th 2021, `v14.x` is recommended).
```sh
node -v
```
4. Run `npm ci`. `ts-jest` will automatically build source files into `dist/` after installing dependencies.
5. Ensure the test suite passes via `npm run test`.
### Testing
Code that is written needs to be tested to ensure that it achieves the desired behaviour. Tests either fall into a unit
test or an integration test.
##### Unit tests
The unit test files are associated with source files which are in `src/`. If the scope of your work only requires a unit test,
this is where you will write it in. Tests here usually don't require much if any setup.
##### Integration tests
There will be situations however where the work you have done cannot be tested alone using unit tests. In situations like this,
you should write an integration test for your code. The integration tests reside within the `e2e` directory.
Within this directory, there is a `__tests__` directory. This is where you will write the integration test itself.
The tests within this directory execute jest itself using `run-jest.ts` and assertions are usually made on one if not all
the output of the following `status`, `stdout` and `stderr`. The other subdirectories within the `e2e` directory are
where you will write the files that jest will run for your integration tests. Feel free to take a look at any of the tests
in the `__tests__` directory within `e2e` to have a better sense of how it is currently being done.
It is possible to run the integration test itself manually to inspect that the new behaviour is indeed correct.
Here is a small code snippet of how to do just that. This is useful when debugging a failing test.
```bash
$ cd e2e/test-utils
$ node ../../node_modules/jest/bin/jest.js # It is possible to use node --inspect or ndb
PASS __tests__/test-utils.spec.ts
✓ stub (3ms)
Test Suites: 1 passed, 1 total
Tests: 1 passed, 1 total
Snapshots: 0 total
Time: 0.232 s, estimated 1 s
Ran all test suites.
```
### Additional Workflow for any changes made to website or docs
If you are making changes to the website or documentation, test the `website` folder and run the server to check if your
changes are being displayed accurately.
1. Locate to the `website` directory and install any website specific dependencies by typing in `npm ci`.
2. Following steps are to be followed for this purpose from the root directory.
```sh-session
$ cd website # Only needed if you are not already in the website directory
$ npm ci
$ npm run start
```
3. You can run a development server to check if the changes you made are being displayed accurately by running `npm run start` in the website directory.
The `ts-jest` website also offers documentation for older versions of `ts-jest`, which you can edit in `website/versioned_docs`.
After making changes to the current documentation in `docs`, please check if any older versions of the documentation
have a copy of the file where the change is also relevant and apply the changes to the `versioned_docs` as well.
## Bugs
### Where to Find Known Issues
We will be using GitHub Issues for our public bugs. We will keep a close eye on this and try to make it clear when we
have an internal fix in progress. Before filing a new issue, try to make sure your problem doesn't already exist.
### Reporting New Issues
The best way to get your bug fixed is to provide a reduced test case. Please provide a public repository with a runnable example.
## How to Get in Touch
[`#testing` on Reactiflux](https://discord.gg/j6FKKQQrW9) or [our GitHub discussion](https://github.com/kulshekhar/ts-jest/discussions)
## Code Conventions
- 2 spaces for indentation (no tabs).
- 120 character line length strongly preferred.
- Prefer `'` over `"`.
- ES6 syntax when possible.
- Use [TypeScript](https://www.typescriptlang.org/).
- No semicolon (`;`) required
- Trailing commas,
## License
By contributing to `ts-jest`, you agree that your contributions will be licensed under its MIT license.

21
node_modules/ts-jest/LICENSE.md generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016-2018
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.

73
node_modules/ts-jest/README.md generated vendored Normal file
View File

@ -0,0 +1,73 @@
<h1 align="center">ts-jest</h1>
<p align="center">A Jest transformer with source map support that lets you use Jest to test projects written in TypeScript.</p>
<p align="center">
<a href="https://www.npmjs.com/package/ts-jest"><img src="https://img.shields.io/npm/v/ts-jest/latest.svg?style=flat-square" alt="NPM version" /> </a>
<a href="https://www.npmjs.com/package/ts-jest"><img src="https://img.shields.io/npm/dm/ts-jest.svg?style=flat-square" alt="NPM downloads"/> </a>
<a href="https://snyk.io/test/github/kulshekhar/ts-jest"><img src="https://snyk.io/test/github/kulshekhar/ts-jest/badge.svg?style=flat-square" alt="Known vulnerabilities"/> </a>
<a href="https://coveralls.io/github/kulshekhar/ts-jest?branch=main"><img src="https://coveralls.io/repos/github/kulshekhar/ts-jest/badge.svg?branch=main" alt="Coverage status"/> </a>
<a href="https://actions-badge.atrox.dev/kulshekhar/ts-jest/goto?ref=main"><img alt="GitHub actions" src="https://img.shields.io/endpoint.svg?url=https%3A%2F%2Factions-badge.atrox.dev%2Fkulshekhar%2Fts-jest%2Fbadge%3Fref%3Dmain&style=flat-square" /> </a>
<a href="https://github.com/kulshekhar/ts-jest/blob/main/LICENSE.md"><img src="https://img.shields.io/npm/l/ts-jest.svg?style=flat-square" alt="GitHub license"/> </a>
</p>
<img src="./icon.png" align="right" title="ts-jest Logo" width="128" height="128">
It supports all features of TypeScript including type-checking. [Read more about Babel7 + `preset-typescript` **vs** TypeScript (and `ts-jest`)](https://kulshekhar.github.io/ts-jest/docs/babel7-or-ts).
---
| We are not doing semantic versioning and `23.10` is a re-write, run `npm i -D ts-jest@"<23.10.0"` to go back to the previous version |
| ------------------------------------------------------------------------------------------------------------------------------------ |
[<img src="./website/static/img/documentation.png" align="left" height="24"> View the online documentation (usage & technical)](https://kulshekhar.github.io/ts-jest)
[<img src="./website/static/img/discord.svg" align="left" height="24"> Ask for some help in the `Jest` Discord community](https://discord.gg/j6FKKQQrW9) or [`ts-jest` GitHub Discussion](https://github.com/kulshekhar/ts-jest/discussions)
[<img src="./website/static/img/troubleshooting.png" align="left" height="24"> Before reporting any issues, be sure to check the troubleshooting page](TROUBLESHOOTING.md)
[<img src="./website/static/img/pull-request.png" align="left" height="24"> We're looking for collaborators! Want to help improve `ts-jest`?](https://github.com/kulshekhar/ts-jest/issues/223)
---
## Getting Started
These instructions will get you setup to use `ts-jest` in your project. For more detailed documentation, please check [online documentation](https://kulshekhar.github.io/ts-jest).
| | using npm | using yarn |
| ------------------: | ------------------------------ | ------------------------------------ |
| **Prerequisites** | `npm i -D jest typescript` | `yarn add --dev jest typescript` |
| **Installing** | `npm i -D ts-jest @types/jest` | `yarn add --dev ts-jest @types/jest` |
| **Creating config** | `npx ts-jest config:init` | `yarn ts-jest config:init` |
| **Running tests** | `npm test` or `npx jest` | `yarn test` or `yarn jest` |
## Built With
- [TypeScript](https://www.typescriptlang.org/) - JavaScript that scales
- [Jest](https://jestjs.io/) - Delightful JavaScript Testing
- [`ts-jest`](https://kulshekhar.github.io/ts-jest) - Jest [transformer](https://jestjs.io/docs/next/code-transformation#writing-custom-transformers) for TypeScript _(yes, `ts-jest` uses itself for its tests)_
## Contributing
Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on our code of conduct, and the process for submitting pull requests to us.
## Versioning
We **DO NOT** use [SemVer](https://semver.org/) for versioning. Though you can think about SemVer when reading our version, except our major number follows the one of Jest. For the versions available, see the [tags on this repository](https://github.com/kulshekhar/ts-jest/tags).
## Authors/maintainers
- **Kulshekhar Kabra** - [kulshekhar](https://github.com/kulshekhar)
- **Gustav Wengel** - [GeeWee](https://github.com/GeeWee)
- **Ahn** - [ahnpnl](https://github.com/ahnpnl)
- **Huafu Gandon** - [huafu](https://github.com/huafu)
See also the list of [contributors](https://github.com/kulshekhar/ts-jest/contributors) who participated in this project.
## Supporters
- [JetBrains](https://www.jetbrains.com/?from=ts-jest) has been kind enough to support ts-jest with an [open source license](https://www.jetbrains.com/community/opensource/?from=ts-jest).
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details

75
node_modules/ts-jest/TROUBLESHOOTING.md generated vendored Normal file
View File

@ -0,0 +1,75 @@
# Troubleshooting
## Running ts-jest on CI tools
### PROBLEM
Cannot find module "" from ""
### SOLUTION
- Check if `rootDir` is referenced correctly. If not add this on your existing jest configuration.
```javascript
module.exports = {
...
roots: ["<rootDir>"]
}
```
- Check if module directories are included on your jest configuration. If not add this on your existing jest configuration.
```javascript
module.exports = {
...
moduleDirectories: ["node_modules","<module-directory>"],
modulePaths: ["<path-of-module>"],
}
```
- Check if module name is properly mapped and can be referenced by jest. If not, you can define moduleNameMapper for your jest configuration.
```javascript
module.exports = {
...
moduleNameMapper: {
"<import-path>": "<rootDir>/<real-physical-path>",
},
}
```
- Check github folder names if its identical to you local folder names. Sometimes github never updates your folder names even if you rename it locally. If this happens rename your folders via github or use this command `git mv <source> <destination>` and commit changes.
## Transform (node)-module explicitly
### PROBLEM
SyntaxError: Cannot use import statement outside a module
### SOLUTION
One of the node modules hasn't the correct syntax for Jests execution step. It needs to
be transformed first.
There is a good chance that the error message shows which module is affected:
```shell
SyntaxError: Cannot use import statement outside a module
> 22 | import Component from "../../node_modules/some-module/lib";
| ^
```
In this case **some-module** is the problem and needs to be transformed.
By adding the following line to the configuration file it will tell Jest which modules
shouldnt be ignored during the transformation step:
```javascript
module.exports = {
...
transformIgnorePatterns: ["node_modules/(?!(some-module|another-module))"]
};
```
**some-module** and **another-module** will be transformed.
For more information see [here](https://stackoverflow.com/questions/63389757/jest-unit-test-syntaxerror-cannot-use-import-statement-outside-a-module) and [here](https://stackoverflow.com/questions/52035066/how-to-write-jest-transformignorepatterns).

3
node_modules/ts-jest/cli.js generated vendored Executable file
View File

@ -0,0 +1,3 @@
#!/usr/bin/env node
require('./dist/cli').processArgv()

1
node_modules/ts-jest/dist/cli/config/init.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

157
node_modules/ts-jest/dist/cli/config/init.js generated vendored Normal file
View File

@ -0,0 +1,157 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.help = exports.run = void 0;
var fs_1 = require("fs");
var path_1 = require("path");
var json5_1 = require("json5");
var presets_1 = require("../helpers/presets");
var run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
var file, filePath, name, isPackage, exists, pkgFile, hasPackage, _a, jestPreset, askedTsconfig, force, jsdom, tsconfig, pkgJson, jsFilesProcessor, shouldPostProcessWithBabel, preset, body, base, tsJestConf, content;
var _b, _c;
return __generator(this, function (_d) {
file = (_c = (_b = args._[0]) === null || _b === void 0 ? void 0 : _b.toString()) !== null && _c !== void 0 ? _c : 'jest.config.js';
filePath = (0, path_1.join)(process.cwd(), file);
name = (0, path_1.basename)(file);
isPackage = name === 'package.json';
exists = (0, fs_1.existsSync)(filePath);
pkgFile = isPackage ? filePath : (0, path_1.join)(process.cwd(), 'package.json');
hasPackage = isPackage || (0, fs_1.existsSync)(pkgFile);
_a = args.jestPreset, jestPreset = _a === void 0 ? true : _a, askedTsconfig = args.tsconfig, force = args.force, jsdom = args.jsdom;
tsconfig = askedTsconfig === 'tsconfig.json' ? undefined : askedTsconfig;
pkgJson = hasPackage ? JSON.parse((0, fs_1.readFileSync)(pkgFile, 'utf8')) : {};
jsFilesProcessor = args.js, shouldPostProcessWithBabel = args.babel;
if (jsFilesProcessor == null) {
jsFilesProcessor = shouldPostProcessWithBabel ? 'babel' : undefined;
}
else if (shouldPostProcessWithBabel == null) {
shouldPostProcessWithBabel = jsFilesProcessor === 'babel';
}
if (jsFilesProcessor === 'babel') {
preset = presets_1.jsWIthBabel;
}
else if (jsFilesProcessor === 'ts') {
preset = presets_1.jsWithTs;
}
else {
preset = presets_1.defaults;
}
if (isPackage && !exists) {
throw new Error("File ".concat(file, " does not exists."));
}
else if (!isPackage && exists && !force) {
throw new Error("Configuration file ".concat(file, " already exists."));
}
if (!isPackage && !name.endsWith('.js')) {
throw new TypeError("Configuration file ".concat(file, " must be a .js file or the package.json."));
}
if (hasPackage && pkgJson.jest) {
if (force && !isPackage) {
delete pkgJson.jest;
(0, fs_1.writeFileSync)(pkgFile, JSON.stringify(pkgJson, undefined, ' '));
}
else if (!force) {
throw new Error("A Jest configuration is already set in ".concat(pkgFile, "."));
}
}
if (isPackage) {
base = jestPreset ? { preset: preset.name } : __assign({}, preset.value);
if (!jsdom)
base.testEnvironment = 'node';
if (tsconfig || shouldPostProcessWithBabel) {
tsJestConf = {};
base.globals = { 'ts-jest': tsJestConf };
if (tsconfig)
tsJestConf.tsconfig = tsconfig;
if (shouldPostProcessWithBabel)
tsJestConf.babelConfig = true;
}
body = JSON.stringify(__assign(__assign({}, pkgJson), { jest: base }), undefined, ' ');
}
else {
content = [];
if (!jestPreset) {
content.push("".concat(preset.jsImport('tsjPreset'), ";"), '');
}
content.push("/** @type {import('ts-jest/dist/types').InitialOptionsTsJest} */");
content.push('module.exports = {');
if (jestPreset) {
content.push(" preset: '".concat(preset.name, "',"));
}
else {
content.push(' ...tsjPreset,');
}
if (!jsdom)
content.push(" testEnvironment: 'node',");
if (tsconfig || shouldPostProcessWithBabel) {
content.push(' globals: {');
content.push(" 'ts-jest': {");
if (tsconfig)
content.push(" tsconfig: ".concat((0, json5_1.stringify)(tsconfig), ","));
if (shouldPostProcessWithBabel)
content.push(' babelConfig: true,');
content.push(' },');
content.push(' },');
}
content.push('};');
body = content.join('\n');
}
(0, fs_1.writeFileSync)(filePath, body);
process.stderr.write("\nJest configuration written to \"".concat(filePath, "\".\n"));
return [2];
});
}); };
exports.run = run;
var help = function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
process.stdout.write("\nUsage:\n ts-jest config:init [options] [<config-file>]\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n Default: jest.config.js\n\nOptions:\n --force Discard any existing Jest config\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n --tsconfig <file> Path to the tsconfig.json file\n --babel Pipe babel-jest after ts-jest\n --jsdom Use jsdom as test environment instead of node\n");
return [2];
});
}); };
exports.help = help;

1
node_modules/ts-jest/dist/cli/config/migrate.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

229
node_modules/ts-jest/dist/cli/config/migrate.js generated vendored Normal file
View File

@ -0,0 +1,229 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.help = exports.run = void 0;
var fs_1 = require("fs");
var path_1 = require("path");
var bs_logger_1 = require("bs-logger");
var fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
var json5_1 = require("json5");
var backports_1 = require("../../utils/backports");
var presets_1 = require("../helpers/presets");
var run = function (args) { return __awaiter(void 0, void 0, void 0, function () {
var nullLogger, file, filePath, footNotes, name, isPackage, actualConfig, migratedConfig, presetName, preset, jsTransformers, jsWithTs, jsWithBabel, presetValue, migratedValue, presetValue, migratedValue, before, after, stringify, prefix;
var _a, _b, _c, _d, _e, _f, _g, _h;
return __generator(this, function (_j) {
nullLogger = (0, bs_logger_1.createLogger)({ targets: [] });
file = (_a = args._[0]) === null || _a === void 0 ? void 0 : _a.toString();
filePath = (0, path_1.resolve)(process.cwd(), file);
footNotes = [];
if (!(0, fs_1.existsSync)(filePath)) {
throw new Error("Configuration file ".concat(file, " does not exists."));
}
name = (0, path_1.basename)(file);
isPackage = name === 'package.json';
if (!/\.(js|json)$/.test(name)) {
throw new TypeError("Configuration file ".concat(file, " must be a JavaScript or JSON file."));
}
actualConfig = require(filePath);
if (isPackage) {
actualConfig = actualConfig.jest;
}
if (!actualConfig)
actualConfig = {};
migratedConfig = (0, backports_1.backportJestConfig)(nullLogger, actualConfig);
if (!migratedConfig.preset && args.jestPreset) {
if (args.js) {
presetName = args.js === 'babel' ? "ts-jest/presets/js-with-babel" : "ts-jest/presets/js-with-ts";
}
else {
jsTransformers = Object.keys(migratedConfig.transform || {}).reduce(function (list, pattern) {
if (RegExp(pattern.replace(/^<rootDir>\/?/, '/dummy-project/')).test('/dummy-project/src/foo.js')) {
var transformer = migratedConfig.transform[pattern];
if (/\bbabel-jest\b/.test(transformer))
transformer = 'babel-jest';
else if (/\ts-jest\b/.test(transformer))
transformer = 'ts-jest';
return __spreadArray(__spreadArray([], __read(list), false), [transformer], false);
}
return list;
}, []);
jsWithTs = jsTransformers.includes('ts-jest');
jsWithBabel = jsTransformers.includes('babel-jest');
if (jsWithBabel && !jsWithTs) {
presetName = "ts-jest/presets/js-with-babel";
}
else if (jsWithTs && !jsWithBabel) {
presetName = "ts-jest/presets/js-with-ts";
}
else {
presetName = "ts-jest/presets/default";
}
}
presetName = presetName !== null && presetName !== void 0 ? presetName : "ts-jest/presets/default";
preset = presets_1.allPresets[presetName];
footNotes.push("Detected preset '".concat(preset.label, "' as the best matching preset for your configuration.\nVisit https://kulshekhar.github.io/ts-jest/user/config/#jest-preset for more information about presets.\n"));
}
else if ((_b = migratedConfig.preset) === null || _b === void 0 ? void 0 : _b.startsWith('ts-jest')) {
if (args.jestPreset === false) {
delete migratedConfig.preset;
}
else {
preset = (_c = presets_1.allPresets[migratedConfig.preset]) !== null && _c !== void 0 ? _c : presets_1.defaults;
}
}
if (preset)
migratedConfig.preset = preset.name;
if (((_d = migratedConfig.moduleFileExtensions) === null || _d === void 0 ? void 0 : _d.length) && preset) {
presetValue = dedupSort((_e = preset.value.moduleFileExtensions) !== null && _e !== void 0 ? _e : []).join('::');
migratedValue = dedupSort(migratedConfig.moduleFileExtensions).join('::');
if (presetValue === migratedValue) {
delete migratedConfig.moduleFileExtensions;
}
}
if ((typeof migratedConfig.testRegex === 'string' || ((_f = migratedConfig.testRegex) === null || _f === void 0 ? void 0 : _f.length)) && preset) {
delete migratedConfig.testMatch;
}
else if (((_g = migratedConfig.testMatch) === null || _g === void 0 ? void 0 : _g.length) && preset) {
presetValue = dedupSort((_h = preset.value.testMatch) !== null && _h !== void 0 ? _h : []).join('::');
migratedValue = dedupSort(migratedConfig.testMatch).join('::');
if (presetValue === migratedValue) {
delete migratedConfig.testMatch;
}
}
if (migratedConfig.transform) {
Object.keys(migratedConfig.transform).forEach(function (key) {
var val = migratedConfig.transform[key];
if (typeof val === 'string' && /\/?ts-jest(?:\/preprocessor\.js)?$/.test(val)) {
;
migratedConfig.transform[key] = 'ts-jest';
}
});
}
if (preset &&
migratedConfig.transform &&
(0, fast_json_stable_stringify_1.default)(migratedConfig.transform) === (0, fast_json_stable_stringify_1.default)(preset.value.transform)) {
delete migratedConfig.transform;
}
cleanupConfig(actualConfig);
cleanupConfig(migratedConfig);
before = (0, fast_json_stable_stringify_1.default)(actualConfig);
after = (0, fast_json_stable_stringify_1.default)(migratedConfig);
if (after === before) {
process.stderr.write("\nNo migration needed for given Jest configuration\n ");
return [2];
}
stringify = file.endsWith('.json') ? JSON.stringify : json5_1.stringify;
prefix = file.endsWith('.json') ? '"jest": ' : 'module.exports = ';
if (preset && migratedConfig.transform) {
footNotes.push("\nI couldn't check if your \"transform\" value is the same as mine which is: ".concat(stringify(preset.value.transform, undefined, ' '), "\nIf it is the case, you can safely remove the \"transform\" from what I've migrated.\n"));
}
process.stderr.write("\nMigrated Jest configuration:\n");
process.stdout.write("".concat(prefix).concat(stringify(migratedConfig, undefined, ' '), "\n"));
if (footNotes.length) {
process.stderr.write("\n".concat(footNotes.join('\n'), "\n"));
}
return [2];
});
}); };
exports.run = run;
function cleanupConfig(config) {
if (config.globals) {
if (config.globals['ts-jest'] && Object.keys(config.globals['ts-jest']).length === 0) {
delete config.globals['ts-jest'];
}
if (!Object.keys(config.globals).length) {
delete config.globals;
}
}
if (config.transform && !Object.keys(config.transform).length) {
delete config.transform;
}
if (config.moduleFileExtensions) {
config.moduleFileExtensions = dedupSort(config.moduleFileExtensions);
if (!config.moduleFileExtensions.length)
delete config.moduleFileExtensions;
}
if (config.testMatch) {
config.testMatch = dedupSort(config.testMatch);
if (!config.testMatch.length)
delete config.testMatch;
}
if (config.preset === "ts-jest/presets/default")
config.preset = presets_1.defaults.name;
}
function dedupSort(arr) {
return arr
.filter(function (s, i, a) { return a.findIndex(function (e) { return s.toString() === e.toString(); }) === i; })
.sort(function (a, b) { return (a.toString() > b.toString() ? 1 : a.toString() < b.toString() ? -1 : 0); });
}
var help = function () { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
process.stdout.write("\nUsage:\n ts-jest config:migrate [options] <config-file>\n\nArguments:\n <config-file> Can be a js or json Jest config file. If it is a\n package.json file, the configuration will be read from\n the \"jest\" property.\n\nOptions:\n --js ts|babel Process .js files with ts-jest if 'ts' or with\n babel-jest if 'babel'\n --no-jest-preset Disable the use of Jest presets\n");
return [2];
});
}); };
exports.help = help;

1
node_modules/ts-jest/dist/cli/help.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

47
node_modules/ts-jest/dist/cli/help.js generated vendored Normal file
View File

@ -0,0 +1,47 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.help = exports.run = void 0;
var run = function (_) { return __awaiter(void 0, void 0, void 0, function () {
return __generator(this, function (_a) {
process.stdout.write("\nUsage:\n ts-jest command [options] [...args]\n\nCommands:\n config:init Creates initial Jest configuration\n config:migrate Migrates a given Jest configuration\n help [command] Show this help, or help about a command\n\nExample:\n ts-jest help config:migrate\n");
return [2];
});
}); };
exports.run = run;
exports.help = exports.run;

1
node_modules/ts-jest/dist/cli/helpers/presets.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

35
node_modules/ts-jest/dist/cli/helpers/presets.js generated vendored Normal file
View File

@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.jsWIthBabel = exports.jsWithTs = exports.defaults = exports.allPresets = void 0;
var definePreset = function (fullName) { return ({
fullName: fullName,
get name() {
return this.isDefault ? 'ts-jest' : fullName;
},
get label() {
return fullName.split('/').pop();
},
get jsVarName() {
return this.isDefault
? 'defaults'
:
fullName
.split('/')
.pop()
.replace(/\-([a-z])/g, function (_, l) { return l.toUpperCase(); });
},
get value() {
return require("../../../".concat(fullName.replace(/^ts-jest\//, ''), "/jest-preset"));
},
jsImport: function (varName) {
if (varName === void 0) { varName = 'tsjPreset'; }
return "const { ".concat(this.jsVarName, ": ").concat(varName, " } = require('ts-jest/presets')");
},
get isDefault() {
return fullName === "ts-jest/presets/default";
},
}); };
exports.allPresets = {};
exports.defaults = (exports.allPresets["ts-jest/presets/default"] = definePreset("ts-jest/presets/default"));
exports.jsWithTs = (exports.allPresets["ts-jest/presets/js-with-ts"] = definePreset("ts-jest/presets/js-with-ts"));
exports.jsWIthBabel = (exports.allPresets["ts-jest/presets/js-with-babel"] = definePreset("ts-jest/presets/js-with-babel"));

1
node_modules/ts-jest/dist/cli/index.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

114
node_modules/ts-jest/dist/cli/index.js generated vendored Normal file
View File

@ -0,0 +1,114 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.processArgv = void 0;
var bs_logger_1 = require("bs-logger");
var yargs_parser_1 = __importDefault(require("yargs-parser"));
var utils_1 = require("../utils");
var VALID_COMMANDS = ['help', 'config:migrate', 'config:init'];
var logger = utils_1.rootLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'cli', _a[bs_logger_1.LogContexts.application] = 'ts-jest', _a));
function cli(args) {
return __awaiter(this, void 0, void 0, function () {
var parsedArgv, command, isHelp, _a, run, help, cmd;
return __generator(this, function (_b) {
parsedArgv = (0, yargs_parser_1.default)(args, {
boolean: ['dry-run', 'jest-preset', 'allow-js', 'diff', 'babel', 'force', 'jsdom'],
string: ['tsconfig', 'js'],
count: ['verbose'],
alias: { verbose: ['v'] },
default: { jestPreset: true, verbose: 0 },
coerce: {
js: function (val) {
var res = val.trim().toLowerCase();
if (!['babel', 'ts'].includes(res))
throw new Error("The 'js' option must be 'babel' or 'ts', given: '".concat(val, "'."));
return res;
},
},
});
if (parsedArgv.allowJs != null) {
if (parsedArgv.js)
throw new Error("The 'allowJs' and 'js' options cannot be set together.");
parsedArgv.js = parsedArgv.allowJs ? 'ts' : undefined;
}
command = parsedArgv._.shift();
isHelp = command === 'help';
if (isHelp)
command = parsedArgv._.shift();
if (!VALID_COMMANDS.includes(command))
command = 'help';
_a = require("./".concat(command.replace(/:/g, '/'))), run = _a.run, help = _a.help;
cmd = isHelp && command !== 'help' ? help : run;
return [2, cmd(parsedArgv, logger)];
});
});
}
var errorHasMessage = function (err) {
if (typeof err !== 'object' || err === null)
return false;
return 'message' in err;
};
function processArgv() {
return __awaiter(this, void 0, void 0, function () {
var err_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
return [4, cli(process.argv.slice(2))];
case 1:
_a.sent();
process.exit(0);
return [3, 3];
case 2:
err_1 = _a.sent();
if (errorHasMessage(err_1)) {
logger.fatal(err_1.message);
process.exit(1);
}
return [3, 3];
case 3: return [2];
}
});
});
}
exports.processArgv = processArgv;

1
node_modules/ts-jest/dist/config/index.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export * from './paths-to-module-name-mapper';

17
node_modules/ts-jest/dist/config/index.js generated vendored Normal file
View File

@ -0,0 +1,17 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./paths-to-module-name-mapper"), exports);

View File

@ -0,0 +1,6 @@
import type { Config } from '@jest/types';
declare type JestPathMapping = Config.InitialOptions['moduleNameMapper'];
export declare const pathsToModuleNameMapper: (mapping: import("typescript").MapLike<string[]>, { prefix }?: {
prefix: string;
}) => JestPathMapping;
export {};

View File

@ -0,0 +1,66 @@
"use strict";
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.pathsToModuleNameMapper = void 0;
var bs_logger_1 = require("bs-logger");
var utils_1 = require("../utils");
var messages_1 = require("../utils/messages");
var escapeRegex = function (str) { return str.replace(/[-\\^$*+?.()|[\]{}]/g, '\\$&'); };
var logger = utils_1.rootLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'path-mapper', _a));
var pathsToModuleNameMapper = function (mapping, _a) {
var e_1, _b;
var _c = _a === void 0 ? Object.create(null) : _a, _d = _c.prefix, prefix = _d === void 0 ? '' : _d;
var jestMap = {};
try {
for (var _e = __values(Object.keys(mapping)), _f = _e.next(); !_f.done; _f = _e.next()) {
var fromPath = _f.value;
var pattern = void 0;
var toPaths = mapping[fromPath];
if (toPaths.length === 0) {
logger.warn((0, messages_1.interpolate)("Not mapping \"{{path}}\" because it has no target.", { path: fromPath }));
continue;
}
var segments = fromPath.split(/\*/g);
if (segments.length === 1) {
var paths = toPaths.map(function (target) {
var enrichedPrefix = prefix !== '' && !prefix.endsWith('/') ? "".concat(prefix, "/") : prefix;
return "".concat(enrichedPrefix).concat(target);
});
pattern = "^".concat(escapeRegex(fromPath), "$");
jestMap[pattern] = paths.length === 1 ? paths[0] : paths;
}
else if (segments.length === 2) {
var paths = toPaths.map(function (target) {
var enrichedTarget = target.startsWith('./') && prefix !== '' ? target.substring(target.indexOf('/') + 1) : target;
var enrichedPrefix = prefix !== '' && !prefix.endsWith('/') ? "".concat(prefix, "/") : prefix;
return "".concat(enrichedPrefix).concat(enrichedTarget.replace(/\*/g, '$1'));
});
pattern = "^".concat(escapeRegex(segments[0]), "(.*)").concat(escapeRegex(segments[1]), "$");
jestMap[pattern] = paths.length === 1 ? paths[0] : paths;
}
else {
logger.warn((0, messages_1.interpolate)("Not mapping \"{{path}}\" because it has more than one star (`*`).", { path: fromPath }));
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_f && !_f.done && (_b = _e.return)) _b.call(_e);
}
finally { if (e_1) throw e_1.error; }
}
return jestMap;
};
exports.pathsToModuleNameMapper = pathsToModuleNameMapper;

7
node_modules/ts-jest/dist/constants.d.ts generated vendored Normal file
View File

@ -0,0 +1,7 @@
export declare const LINE_FEED = "\n";
export declare const DECLARATION_TYPE_EXT = ".d.ts";
export declare const JS_JSX_EXTENSIONS: string[];
export declare const TS_TSX_REGEX: RegExp;
export declare const JS_JSX_REGEX: RegExp;
export declare const TS_EXT_TO_TREAT_AS_ESM: string[];
export declare const JS_EXT_TO_TREAT_AS_ESM: string[];

11
node_modules/ts-jest/dist/constants.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.DEFAULT_JEST_TEST_MATCH = exports.JS_EXT_TO_TREAT_AS_ESM = exports.TS_EXT_TO_TREAT_AS_ESM = exports.JS_JSX_REGEX = exports.TS_TSX_REGEX = exports.JS_JSX_EXTENSIONS = exports.DECLARATION_TYPE_EXT = exports.LINE_FEED = void 0;
exports.LINE_FEED = '\n';
exports.DECLARATION_TYPE_EXT = '.d.ts';
exports.JS_JSX_EXTENSIONS = ['.js', '.jsx'];
exports.TS_TSX_REGEX = /\.tsx?$/;
exports.JS_JSX_REGEX = /\.jsx?$/;
exports.TS_EXT_TO_TREAT_AS_ESM = ['.ts', '.tsx'];
exports.JS_EXT_TO_TREAT_AS_ESM = ['.jsx'];
exports.DEFAULT_JEST_TEST_MATCH = ['**/__tests__/**/*.[jt]s?(x)', '**/?(*.)+(spec|test).[jt]s?(x)'];

14
node_modules/ts-jest/dist/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,14 @@
import { TsJestTransformer } from './legacy/ts-jest-transformer';
export * from './config';
export * from './constants';
export * from './legacy/compiler';
export * from './legacy/ts-jest-transformer';
export * from './legacy/config/config-set';
export * from './presets/create-jest-preset';
export * from './raw-compiler-options';
export * from './utils';
export * from './types';
declare const _default: {
createTransformer(): TsJestTransformer;
};
export default _default;

31
node_modules/ts-jest/dist/index.js generated vendored Normal file
View File

@ -0,0 +1,31 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
var ts_jest_transformer_1 = require("./legacy/ts-jest-transformer");
__exportStar(require("./config"), exports);
__exportStar(require("./constants"), exports);
__exportStar(require("./legacy/compiler"), exports);
__exportStar(require("./legacy/ts-jest-transformer"), exports);
__exportStar(require("./legacy/config/config-set"), exports);
__exportStar(require("./presets/create-jest-preset"), exports);
__exportStar(require("./raw-compiler-options"), exports);
__exportStar(require("./utils"), exports);
__exportStar(require("./types"), exports);
exports.default = {
createTransformer: function () {
return new ts_jest_transformer_1.TsJestTransformer();
},
};

View File

@ -0,0 +1,2 @@
export declare const SOURCE_MAPPING_PREFIX = "sourceMappingURL=";
export declare function updateOutput(outputText: string, normalizedFileName: string, sourceMap?: string): string;

View File

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.updateOutput = exports.SOURCE_MAPPING_PREFIX = void 0;
var utils_1 = require("../../utils");
exports.SOURCE_MAPPING_PREFIX = 'sourceMappingURL=';
function updateOutput(outputText, normalizedFileName, sourceMap) {
if (sourceMap) {
var base64Map = Buffer.from(updateSourceMap(sourceMap, normalizedFileName), 'utf8').toString('base64');
var sourceMapContent = "data:application/json;charset=utf-8;base64,".concat(base64Map);
return (outputText.slice(0, outputText.lastIndexOf(exports.SOURCE_MAPPING_PREFIX) + exports.SOURCE_MAPPING_PREFIX.length) +
sourceMapContent);
}
return outputText;
}
exports.updateOutput = updateOutput;
var updateSourceMap = function (sourceMapText, normalizedFileName) {
var sourceMap = JSON.parse(sourceMapText);
sourceMap.file = normalizedFileName;
sourceMap.sources = [normalizedFileName];
delete sourceMap.sourceRoot;
return (0, utils_1.stringify)(sourceMap);
};

2
node_modules/ts-jest/dist/legacy/compiler/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,2 @@
export * from './ts-compiler';
export * from './ts-jest-compiler';

18
node_modules/ts-jest/dist/legacy/compiler/index.js generated vendored Normal file
View File

@ -0,0 +1,18 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./ts-compiler"), exports);
__exportStar(require("./ts-jest-compiler"), exports);

View File

@ -0,0 +1,21 @@
import { Logger } from 'bs-logger';
import type { CompilerOptions, CustomTransformers, Program, TranspileOutput } from 'typescript';
import type { StringMap, TsCompilerInstance, TsJestAstTransformer, TsJestCompileOptions, TTypeScript } from '../../types';
import { CompiledOutput } from '../../types';
import type { ConfigSet } from '../config/config-set';
export declare class TsCompiler implements TsCompilerInstance {
readonly configSet: ConfigSet;
readonly runtimeCacheFS: StringMap;
protected readonly _logger: Logger;
protected readonly _ts: TTypeScript;
protected readonly _initialCompilerOptions: CompilerOptions;
protected _compilerOptions: CompilerOptions;
private _runtimeCacheFS;
private _fileContentCache;
program: Program | undefined;
constructor(configSet: ConfigSet, runtimeCacheFS: StringMap);
getResolvedModules(fileContent: string, fileName: string, runtimeCacheFS: StringMap): string[];
getCompiledOutput(fileContent: string, fileName: string, options: TsJestCompileOptions): CompiledOutput;
protected _transpileOutput(fileContent: string, fileName: string): TranspileOutput;
protected _makeTransformers(customTransformers: TsJestAstTransformer): CustomTransformers;
}

View File

@ -0,0 +1,334 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TsCompiler = void 0;
var path_1 = require("path");
var bs_logger_1 = require("bs-logger");
var lodash_memoize_1 = __importDefault(require("lodash.memoize"));
var constants_1 = require("../../constants");
var utils_1 = require("../../utils");
var messages_1 = require("../../utils/messages");
var compiler_utils_1 = require("./compiler-utils");
var TsCompiler = (function () {
function TsCompiler(configSet, runtimeCacheFS) {
var _a;
var _this = this;
this.configSet = configSet;
this.runtimeCacheFS = runtimeCacheFS;
this._projectVersion = 1;
this._ts = configSet.compilerModule;
this._logger = utils_1.rootLogger.child({ namespace: 'ts-compiler' });
this._parsedTsConfig = this.configSet.parsedTsConfig;
this._initialCompilerOptions = __assign({}, this._parsedTsConfig.options);
this._compilerOptions = __assign({}, this._initialCompilerOptions);
this._runtimeCacheFS = runtimeCacheFS;
if (!this.configSet.isolatedModules) {
this._fileContentCache = new Map();
this._fileVersionCache = new Map();
this._cachedReadFile = this._logger.wrap((_a = {
namespace: 'ts:serviceHost',
call: null
},
_a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.trace,
_a), 'readFile', (0, lodash_memoize_1.default)(this._ts.sys.readFile));
this._moduleResolutionHost = {
fileExists: (0, lodash_memoize_1.default)(this._ts.sys.fileExists),
readFile: this._cachedReadFile,
directoryExists: (0, lodash_memoize_1.default)(this._ts.sys.directoryExists),
getCurrentDirectory: function () { return _this.configSet.cwd; },
realpath: this._ts.sys.realpath && (0, lodash_memoize_1.default)(this._ts.sys.realpath),
getDirectories: (0, lodash_memoize_1.default)(this._ts.sys.getDirectories),
};
this._moduleResolutionCache = this._ts.createModuleResolutionCache(this.configSet.cwd, function (x) { return x; }, this._compilerOptions);
this._createLanguageService();
}
}
TsCompiler.prototype.getResolvedModules = function (fileContent, fileName, runtimeCacheFS) {
var _this = this;
if (!this.runtimeCacheFS.size) {
this._runtimeCacheFS = runtimeCacheFS;
}
this._logger.debug({ fileName: fileName }, 'getResolvedModules(): resolve direct imported module paths');
var importedModulePaths = Array.from(new Set(this._getImportedModulePaths(fileContent, fileName)));
this._logger.debug({ fileName: fileName }, 'getResolvedModules(): resolve nested imported module paths from directed imported module paths');
importedModulePaths.forEach(function (importedModulePath) {
var resolvedFileContent = _this._getFileContentFromCache(importedModulePath);
importedModulePaths.push.apply(importedModulePaths, __spreadArray([], __read(_this._getImportedModulePaths(resolvedFileContent, importedModulePath).filter(function (modulePath) { return !importedModulePaths.includes(modulePath); })), false));
});
return importedModulePaths;
};
TsCompiler.prototype.getCompiledOutput = function (fileContent, fileName, options) {
var e_1, _a;
var moduleKind = this._initialCompilerOptions.module;
var esModuleInterop = this._initialCompilerOptions.esModuleInterop;
var allowSyntheticDefaultImports = this._initialCompilerOptions.allowSyntheticDefaultImports;
var currentModuleKind = this._compilerOptions.module;
var isEsmMode = this.configSet.useESM && options.supportsStaticESM;
if ((this.configSet.babelJestTransformer || (!this.configSet.babelJestTransformer && options.supportsStaticESM)) &&
this.configSet.useESM) {
moduleKind =
!moduleKind ||
(moduleKind &&
![this._ts.ModuleKind.ES2015, this._ts.ModuleKind.ES2020, this._ts.ModuleKind.ESNext].includes(moduleKind))
? this._ts.ModuleKind.ESNext
: moduleKind;
esModuleInterop = true;
allowSyntheticDefaultImports = true;
}
else {
moduleKind = this._ts.ModuleKind.CommonJS;
}
this._compilerOptions = __assign(__assign({}, this._compilerOptions), { allowSyntheticDefaultImports: allowSyntheticDefaultImports, esModuleInterop: esModuleInterop, module: moduleKind });
if (this._languageService) {
this._logger.debug({ fileName: fileName }, 'getCompiledOutput(): compiling using language service');
this._updateMemoryCache(fileContent, fileName, currentModuleKind === moduleKind);
var output = this._languageService.getEmitOutput(fileName);
var diagnostics = this.getDiagnostics(fileName);
if (!isEsmMode && diagnostics.length) {
this.configSet.raiseDiagnostics(diagnostics, fileName, this._logger);
if (options.watchMode) {
this._logger.debug({ fileName: fileName }, '_doTypeChecking(): starting watch mode computing diagnostics');
try {
for (var _b = __values(options.depGraphs.entries()), _c = _b.next(); !_c.done; _c = _b.next()) {
var entry = _c.value;
var normalizedModuleNames = entry[1].resolvedModuleNames.map(function (moduleName) { return (0, path_1.normalize)(moduleName); });
var fileToReTypeCheck = entry[0];
if (normalizedModuleNames.includes(fileName) && this.configSet.shouldReportDiagnostics(fileToReTypeCheck)) {
this._logger.debug({ fileToReTypeCheck: fileToReTypeCheck }, '_doTypeChecking(): computing diagnostics using language service');
this._updateMemoryCache(this._getFileContentFromCache(fileToReTypeCheck), fileToReTypeCheck);
var importedModulesDiagnostics = __spreadArray(__spreadArray([], __read(this._languageService.getSemanticDiagnostics(fileToReTypeCheck)), false), __read(this._languageService.getSyntacticDiagnostics(fileToReTypeCheck)), false);
this.configSet.raiseDiagnostics(importedModulesDiagnostics, fileName, this._logger);
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
}
finally { if (e_1) throw e_1.error; }
}
}
}
if (output.emitSkipped) {
if (constants_1.TS_TSX_REGEX.test(fileName)) {
throw new Error((0, messages_1.interpolate)("Unable to process '{{file}}', please make sure that `outDir` in your tsconfig is neither `''` or `'.'`. You can also configure Jest config option `transformIgnorePatterns` to inform `ts-jest` to transform {{file}}", { file: fileName }));
}
else {
this._logger.warn((0, messages_1.interpolate)("Unable to process '{{file}}', falling back to original file content. You can also configure Jest config option `transformIgnorePatterns` to ignore {{file}} from transformation or make sure that `outDir` in your tsconfig is neither `''` or `'.'`", { file: fileName }));
return {
code: fileContent,
};
}
}
if (!output.outputFiles.length) {
throw new TypeError((0, messages_1.interpolate)("Unable to require `.d.ts` file for file: {{file}}.\nThis is usually the result of a faulty configuration or import. Make sure there is a `.js`, `.json` or another executable extension available alongside `{{file}}`.", {
file: (0, path_1.basename)(fileName),
}));
}
var outputFiles = output.outputFiles;
return this._compilerOptions.sourceMap
? {
code: (0, compiler_utils_1.updateOutput)(outputFiles[1].text, fileName, outputFiles[0].text),
diagnostics: diagnostics,
}
: {
code: (0, compiler_utils_1.updateOutput)(outputFiles[0].text, fileName),
diagnostics: diagnostics,
};
}
else {
this._logger.debug({ fileName: fileName }, 'getCompiledOutput(): compiling as isolated module');
var result = this._transpileOutput(fileContent, fileName);
if (result.diagnostics && this.configSet.shouldReportDiagnostics(fileName)) {
this.configSet.raiseDiagnostics(result.diagnostics, fileName, this._logger);
}
return {
code: (0, compiler_utils_1.updateOutput)(result.outputText, fileName, result.sourceMapText),
};
}
};
TsCompiler.prototype._transpileOutput = function (fileContent, fileName) {
return this._ts.transpileModule(fileContent, {
fileName: fileName,
transformers: this._makeTransformers(this.configSet.resolvedTransformers),
compilerOptions: this._compilerOptions,
reportDiagnostics: this.configSet.shouldReportDiagnostics(fileName),
});
};
TsCompiler.prototype._makeTransformers = function (customTransformers) {
var _this = this;
return {
before: customTransformers.before.map(function (beforeTransformer) {
return beforeTransformer.factory(_this, beforeTransformer.options);
}),
after: customTransformers.after.map(function (afterTransformer) {
return afterTransformer.factory(_this, afterTransformer.options);
}),
afterDeclarations: customTransformers.afterDeclarations.map(function (afterDeclarations) {
return afterDeclarations.factory(_this, afterDeclarations.options);
}),
};
};
TsCompiler.prototype._createLanguageService = function () {
var _this = this;
var _a;
this._parsedTsConfig.fileNames
.filter(function (fileName) { return constants_1.TS_TSX_REGEX.test(fileName) && !_this.configSet.isTestFile(fileName); })
.forEach(function (fileName) { return _this._fileVersionCache.set(fileName, 0); });
var serviceHost = {
getProjectVersion: function () { return String(_this._projectVersion); },
getScriptFileNames: function () { return __spreadArray([], __read(_this._fileVersionCache.keys()), false); },
getScriptVersion: function (fileName) {
var normalizedFileName = (0, path_1.normalize)(fileName);
var version = _this._fileVersionCache.get(normalizedFileName);
return version === undefined ? undefined : String(version);
},
getScriptSnapshot: function (fileName) {
var _a, _b, _c, _d;
var normalizedFileName = (0, path_1.normalize)(fileName);
var hit = _this._isFileInCache(normalizedFileName);
_this._logger.trace({ normalizedFileName: normalizedFileName, cacheHit: hit }, 'getScriptSnapshot():', 'cache', hit ? 'hit' : 'miss');
if (!hit) {
var fileContent = (_d = (_b = (_a = _this._fileContentCache.get(normalizedFileName)) !== null && _a !== void 0 ? _a : _this._runtimeCacheFS.get(normalizedFileName)) !== null && _b !== void 0 ? _b : (_c = _this._cachedReadFile) === null || _c === void 0 ? void 0 : _c.call(_this, normalizedFileName)) !== null && _d !== void 0 ? _d : undefined;
if (fileContent !== undefined) {
_this._fileContentCache.set(normalizedFileName, fileContent);
_this._fileVersionCache.set(normalizedFileName, 1);
}
}
var contents = _this._fileContentCache.get(normalizedFileName);
if (contents === undefined)
return;
return _this._ts.ScriptSnapshot.fromString(contents);
},
fileExists: (0, lodash_memoize_1.default)(this._ts.sys.fileExists),
readFile: (_a = this._cachedReadFile) !== null && _a !== void 0 ? _a : this._ts.sys.readFile,
readDirectory: (0, lodash_memoize_1.default)(this._ts.sys.readDirectory),
getDirectories: (0, lodash_memoize_1.default)(this._ts.sys.getDirectories),
directoryExists: (0, lodash_memoize_1.default)(this._ts.sys.directoryExists),
realpath: this._ts.sys.realpath && (0, lodash_memoize_1.default)(this._ts.sys.realpath),
getNewLine: function () { return constants_1.LINE_FEED; },
getCurrentDirectory: function () { return _this.configSet.cwd; },
getCompilationSettings: function () { return _this._compilerOptions; },
getDefaultLibFileName: function () { return _this._ts.getDefaultLibFilePath(_this._compilerOptions); },
getCustomTransformers: function () { return _this._makeTransformers(_this.configSet.resolvedTransformers); },
resolveModuleNames: function (moduleNames, containingFile) {
return moduleNames.map(function (moduleName) { return _this._resolveModuleName(moduleName, containingFile).resolvedModule; });
},
};
this._logger.debug('created language service');
this._languageService = this._ts.createLanguageService(serviceHost, this._ts.createDocumentRegistry());
this.program = this._languageService.getProgram();
};
TsCompiler.prototype._getFileContentFromCache = function (filePath) {
var normalizedFilePath = (0, path_1.normalize)(filePath);
var resolvedFileContent = this._runtimeCacheFS.get(normalizedFilePath);
if (!resolvedFileContent) {
resolvedFileContent = this._moduleResolutionHost.readFile(normalizedFilePath);
this._runtimeCacheFS.set(normalizedFilePath, resolvedFileContent);
}
return resolvedFileContent;
};
TsCompiler.prototype._getImportedModulePaths = function (resolvedFileContent, containingFile) {
var _this = this;
return this._ts
.preProcessFile(resolvedFileContent, true, true)
.importedFiles.map(function (importedFile) {
var resolvedModule = _this._resolveModuleName(importedFile.fileName, containingFile).resolvedModule;
var resolvedFileName = resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.resolvedFileName;
return resolvedFileName && !(resolvedModule === null || resolvedModule === void 0 ? void 0 : resolvedModule.isExternalLibraryImport) ? resolvedFileName : '';
})
.filter(function (resolveFileName) { return !!resolveFileName; });
};
TsCompiler.prototype._resolveModuleName = function (moduleNameToResolve, containingFile) {
return this._ts.resolveModuleName(moduleNameToResolve, containingFile, this._compilerOptions, this._moduleResolutionHost, this._moduleResolutionCache);
};
TsCompiler.prototype._isFileInCache = function (fileName) {
return (this._fileContentCache.has(fileName) &&
this._fileVersionCache.has(fileName) &&
this._fileVersionCache.get(fileName) !== 0);
};
TsCompiler.prototype._updateMemoryCache = function (contents, fileName, isModuleKindTheSame) {
if (isModuleKindTheSame === void 0) { isModuleKindTheSame = true; }
this._logger.debug({ fileName: fileName }, 'updateMemoryCache: update memory cache for language service');
var shouldIncrementProjectVersion = false;
var hit = this._isFileInCache(fileName);
if (!hit) {
this._fileVersionCache.set(fileName, 1);
shouldIncrementProjectVersion = true;
}
else {
var prevVersion = this._fileVersionCache.get(fileName);
var previousContents = this._fileContentCache.get(fileName);
if (previousContents !== contents) {
this._fileVersionCache.set(fileName, prevVersion + 1);
this._fileContentCache.set(fileName, contents);
shouldIncrementProjectVersion = true;
}
if (!this._parsedTsConfig.fileNames.includes(fileName) || !isModuleKindTheSame) {
shouldIncrementProjectVersion = true;
}
}
if (shouldIncrementProjectVersion)
this._projectVersion++;
};
TsCompiler.prototype.getDiagnostics = function (fileName) {
var diagnostics = [];
if (this.configSet.shouldReportDiagnostics(fileName)) {
this._logger.debug({ fileName: fileName }, '_doTypeChecking(): computing diagnostics using language service');
diagnostics.push.apply(diagnostics, __spreadArray(__spreadArray([], __read(this._languageService.getSemanticDiagnostics(fileName)), false), __read(this._languageService.getSyntacticDiagnostics(fileName)), false));
}
return diagnostics;
};
return TsCompiler;
}());
exports.TsCompiler = TsCompiler;

View File

@ -0,0 +1,8 @@
import type { CompilerInstance, CompiledOutput, StringMap, TsJestCompileOptions } from '../../types';
import type { ConfigSet } from '../config/config-set';
export declare class TsJestCompiler implements CompilerInstance {
private readonly _compilerInstance;
constructor(configSet: ConfigSet, runtimeCacheFS: StringMap);
getResolvedModules(fileContent: string, fileName: string, runtimeCacheFS: StringMap): string[];
getCompiledOutput(fileContent: string, fileName: string, options: TsJestCompileOptions): CompiledOutput;
}

View File

@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TsJestCompiler = void 0;
var ts_compiler_1 = require("./ts-compiler");
var TsJestCompiler = (function () {
function TsJestCompiler(configSet, runtimeCacheFS) {
this._compilerInstance = new ts_compiler_1.TsCompiler(configSet, runtimeCacheFS);
}
TsJestCompiler.prototype.getResolvedModules = function (fileContent, fileName, runtimeCacheFS) {
return this._compilerInstance.getResolvedModules(fileContent, fileName, runtimeCacheFS);
};
TsJestCompiler.prototype.getCompiledOutput = function (fileContent, fileName, options) {
return this._compilerInstance.getCompiledOutput(fileContent, fileName, options);
};
return TsJestCompiler;
}());
exports.TsJestCompiler = TsJestCompiler;

View File

@ -0,0 +1,28 @@
import { Logger } from 'bs-logger';
import type * as ts from 'typescript';
import type { RawCompilerOptions } from '../../raw-compiler-options';
import type { ProjectConfigTsJest, TsJestAstTransformer, TTypeScript } from '../../types';
export declare class ConfigSet {
readonly parentLogger?: Logger | undefined;
readonly tsJestDigest: string;
readonly logger: Logger;
readonly compilerModule: TTypeScript;
readonly isolatedModules: boolean;
readonly cwd: string;
readonly rootDir: string;
cacheSuffix: string;
tsCacheDir: string | undefined;
parsedTsConfig: ts.ParsedCommandLine | Record<string, any>;
resolvedTransformers: TsJestAstTransformer;
useESM: boolean;
constructor(jestConfig: ProjectConfigTsJest | undefined, parentLogger?: Logger | undefined);
protected _resolveTsConfig(compilerOptions?: RawCompilerOptions, resolvedConfigFile?: string): Record<string, any>;
isTestFile(fileName: string): boolean;
shouldStringifyContent(filePath: string): boolean;
raiseDiagnostics(diagnostics: ts.Diagnostic[], filePath?: string, logger?: Logger): void;
shouldReportDiagnostics(filePath: string): boolean;
resolvePath(inputPath: string, { throwIfMissing, nodeResolve }?: {
throwIfMissing?: boolean;
nodeResolve?: boolean;
}): string;
}

521
node_modules/ts-jest/dist/legacy/config/config-set.js generated vendored Normal file
View File

@ -0,0 +1,521 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __values = (this && this.__values) || function(o) {
var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
if (m) return m.call(o);
if (o && typeof o.length === "number") return {
next: function () {
if (o && i >= o.length) o = void 0;
return { value: o && o[i++], done: !o };
}
};
throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ConfigSet = exports.TS_JEST_OUT_DIR = exports.IGNORE_DIAGNOSTIC_CODES = exports.MY_DIGEST = void 0;
var fs_1 = require("fs");
var module_1 = __importDefault(require("module"));
var path_1 = require("path");
var bs_logger_1 = require("bs-logger");
var jest_util_1 = require("jest-util");
var json5_1 = __importDefault(require("json5"));
var constants_1 = require("../../constants");
var hoistJestTransformer = __importStar(require("../../transformers/hoist-jest"));
var utils_1 = require("../../utils");
var backports_1 = require("../../utils/backports");
var importer_1 = require("../../utils/importer");
var messages_1 = require("../../utils/messages");
var normalize_slashes_1 = require("../../utils/normalize-slashes");
var sha1_1 = require("../../utils/sha1");
var ts_error_1 = require("../../utils/ts-error");
exports.MY_DIGEST = (0, fs_1.readFileSync)((0, path_1.resolve)(__dirname, '../../../.ts-jest-digest'), 'utf8');
exports.IGNORE_DIAGNOSTIC_CODES = [
6059,
18002,
18003,
];
exports.TS_JEST_OUT_DIR = '$$ts-jest$$';
var normalizeRegex = function (pattern) {
return pattern ? (typeof pattern === 'string' ? pattern : pattern.source) : undefined;
};
var toDiagnosticCode = function (code) { var _a; return code ? (_a = parseInt("".concat(code).trim().replace(/^TS/, ''), 10)) !== null && _a !== void 0 ? _a : undefined : undefined; };
var toDiagnosticCodeList = function (items, into) {
var e_1, _a;
if (into === void 0) { into = []; }
try {
for (var items_1 = __values(items), items_1_1 = items_1.next(); !items_1_1.done; items_1_1 = items_1.next()) {
var item = items_1_1.value;
if (typeof item === 'string') {
var children = item.trim().split(/\s*,\s*/g);
if (children.length > 1) {
toDiagnosticCodeList(children, into);
continue;
}
item = children[0];
}
if (!item)
continue;
var code = toDiagnosticCode(item);
if (code && !into.includes(code))
into.push(code);
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (items_1_1 && !items_1_1.done && (_a = items_1.return)) _a.call(items_1);
}
finally { if (e_1) throw e_1.error; }
}
return into;
};
var requireFromString = function (code, fileName) {
var paths = module_1.default._nodeModulePaths((0, path_1.dirname)(fileName));
var parent = module.parent;
var m = new module_1.default(fileName, parent);
m.filename = fileName;
m.paths = [].concat(paths);
m._compile(code, fileName);
var exports = m.exports;
parent && parent.children && parent.children.splice(parent.children.indexOf(m), 1);
return exports;
};
var ConfigSet = (function () {
function ConfigSet(jestConfig, parentLogger) {
var _a, _b;
var _c, _d, _e, _f;
this.parentLogger = parentLogger;
this.tsJestDigest = exports.MY_DIGEST;
this.resolvedTransformers = {
before: [],
after: [],
afterDeclarations: [],
};
this.useESM = false;
this._overriddenCompilerOptions = {
inlineSourceMap: false,
declaration: false,
noEmit: false,
removeComments: false,
out: undefined,
outFile: undefined,
composite: undefined,
declarationDir: undefined,
declarationMap: undefined,
emitDeclarationOnly: undefined,
sourceRoot: undefined,
tsBuildInfoFile: undefined,
};
this.logger = this.parentLogger
? this.parentLogger.child((_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'config', _a))
: utils_1.rootLogger.child({ namespace: 'config' });
this._backportJestCfg(jestConfig !== null && jestConfig !== void 0 ? jestConfig : Object.create(null));
this.cwd = (0, path_1.normalize)((_c = this._jestCfg.cwd) !== null && _c !== void 0 ? _c : process.cwd());
this.rootDir = (0, path_1.normalize)((_d = this._jestCfg.rootDir) !== null && _d !== void 0 ? _d : this.cwd);
var tsJestCfg = this._jestCfg.globals && this._jestCfg.globals['ts-jest'];
var options = tsJestCfg !== null && tsJestCfg !== void 0 ? tsJestCfg : Object.create(null);
this.compilerModule = importer_1.importer.typescript("Using \"ts-jest\" requires this package to be installed.", (_e = options.compiler) !== null && _e !== void 0 ? _e : 'typescript');
this.isolatedModules = (_f = options.isolatedModules) !== null && _f !== void 0 ? _f : false;
this.logger.debug({ compilerModule: this.compilerModule }, 'normalized compiler module config via ts-jest option');
this._setupConfigSet(options);
this._resolveTsCacheDir();
this._matchablePatterns = __spreadArray(__spreadArray([], __read(this._jestCfg.testMatch), false), __read(this._jestCfg.testRegex), false).filter(function (pattern) {
return pattern instanceof RegExp || typeof pattern === 'string';
});
if (!this._matchablePatterns.length) {
(_b = this._matchablePatterns).push.apply(_b, __spreadArray([], __read(constants_1.DEFAULT_JEST_TEST_MATCH), false));
}
this._matchTestFilePath = (0, jest_util_1.globsToMatcher)(this._matchablePatterns.filter(function (pattern) { return typeof pattern === 'string'; }));
}
ConfigSet.prototype._backportJestCfg = function (jestCfg) {
var _a, _b;
var config = (0, backports_1.backportJestConfig)(this.logger, jestCfg);
this.logger.debug({ jestConfig: config }, 'normalized jest config');
this._jestCfg = __assign(__assign({}, config), { testMatch: (_a = config.testMatch) !== null && _a !== void 0 ? _a : constants_1.DEFAULT_JEST_TEST_MATCH, testRegex: (_b = config.testRegex) !== null && _b !== void 0 ? _b : [] });
};
ConfigSet.prototype._setupConfigSet = function (options) {
var _this = this;
var _a, _b, _c, _d, _e;
this.useESM = (_a = options.useESM) !== null && _a !== void 0 ? _a : false;
if (!options.babelConfig) {
this.logger.debug('babel is disabled');
}
else {
var baseBabelCfg = { cwd: this.cwd };
if (typeof options.babelConfig === 'string') {
var babelCfgPath = this.resolvePath(options.babelConfig);
var babelFileExtName = (0, path_1.extname)(options.babelConfig);
if (babelFileExtName === '.js' || babelFileExtName === '.cjs') {
this.babelConfig = __assign(__assign({}, baseBabelCfg), require(babelCfgPath));
}
else {
this.babelConfig = __assign(__assign({}, baseBabelCfg), json5_1.default.parse((0, fs_1.readFileSync)(babelCfgPath, 'utf-8')));
}
}
else if (typeof options.babelConfig === 'object') {
this.babelConfig = __assign(__assign({}, baseBabelCfg), options.babelConfig);
}
else {
this.babelConfig = baseBabelCfg;
}
this.logger.debug({ babelConfig: this.babelConfig }, 'normalized babel config via ts-jest option');
this.babelJestTransformer = importer_1.importer
.babelJest("Using \"babel-jest\" requires this package to be installed.")
.createTransformer(this.babelConfig);
this.logger.debug('created babel-jest transformer');
}
var diagnosticsOpt = (_b = options.diagnostics) !== null && _b !== void 0 ? _b : true;
var ignoreList = __spreadArray([], __read(exports.IGNORE_DIAGNOSTIC_CODES), false);
if (typeof diagnosticsOpt === 'object') {
var ignoreCodes = diagnosticsOpt.ignoreCodes;
if (ignoreCodes) {
Array.isArray(ignoreCodes) ? ignoreList.push.apply(ignoreList, __spreadArray([], __read(ignoreCodes), false)) : ignoreList.push(ignoreCodes);
}
this._diagnostics = {
pretty: (_c = diagnosticsOpt.pretty) !== null && _c !== void 0 ? _c : true,
exclude: (_d = diagnosticsOpt.exclude) !== null && _d !== void 0 ? _d : [],
ignoreCodes: toDiagnosticCodeList(ignoreList),
throws: !diagnosticsOpt.warnOnly,
};
}
else {
this._diagnostics = {
ignoreCodes: diagnosticsOpt ? toDiagnosticCodeList(ignoreList) : [],
exclude: [],
pretty: true,
throws: diagnosticsOpt,
};
}
this._shouldIgnoreDiagnosticsForFile = this._diagnostics.exclude.length
? (0, jest_util_1.globsToMatcher)(this._diagnostics.exclude)
: function () { return false; };
this.logger.debug({ diagnostics: this._diagnostics }, 'normalized diagnostics config via ts-jest option');
var tsconfigOpt = options.tsconfig;
var configFilePath = typeof tsconfigOpt === 'string' ? this.resolvePath(tsconfigOpt) : undefined;
this.parsedTsConfig = this._getAndResolveTsConfig(typeof tsconfigOpt === 'object' ? tsconfigOpt : undefined, configFilePath);
this.raiseDiagnostics(this.parsedTsConfig.errors, configFilePath);
this.logger.debug({ tsconfig: this.parsedTsConfig }, 'normalized typescript config via ts-jest option');
this.resolvedTransformers.before = [
{
factory: hoistJestTransformer.factory,
name: hoistJestTransformer.name,
version: hoistJestTransformer.version,
},
];
var astTransformers = options.astTransformers;
if (astTransformers) {
var resolveTransformerFunc_1 = function (transformerPath) {
var transformerFunc;
if ((0, path_1.extname)(transformerPath) === '.ts') {
var compiledTransformer = importer_1.importer
.esBuild("Using \"esbuild\" requires this package to be installed.")
.transformSync((0, fs_1.readFileSync)(transformerPath, 'utf-8'), {
loader: 'ts',
format: 'cjs',
target: 'es2015',
}).code;
transformerFunc = requireFromString(compiledTransformer, transformerPath.replace('.ts', '.js'));
}
else {
transformerFunc = require(transformerPath);
}
if (!transformerFunc.version) {
_this.logger.warn("The AST transformer {{file}} must have an `export const version = <your_transformer_version>`", { file: transformerPath });
}
if (!transformerFunc.name) {
_this.logger.warn("The AST transformer {{file}} must have an `export const name = <your_transformer_name>`", { file: transformerPath });
}
return transformerFunc;
};
var resolveTransformers = function (transformers) {
return transformers.map(function (transformer) {
if (typeof transformer === 'string') {
return resolveTransformerFunc_1(_this.resolvePath(transformer, { nodeResolve: true }));
}
else {
return __assign(__assign({}, resolveTransformerFunc_1(_this.resolvePath(transformer.path, { nodeResolve: true }))), { options: transformer.options });
}
});
};
if (astTransformers.before) {
(_e = this.resolvedTransformers.before) === null || _e === void 0 ? void 0 : _e.push.apply(_e, __spreadArray([], __read(resolveTransformers(astTransformers.before)), false));
}
if (astTransformers.after) {
this.resolvedTransformers = __assign(__assign({}, this.resolvedTransformers), { after: resolveTransformers(astTransformers.after) });
}
if (astTransformers.afterDeclarations) {
this.resolvedTransformers = __assign(__assign({}, this.resolvedTransformers), { afterDeclarations: resolveTransformers(astTransformers.afterDeclarations) });
}
}
this.logger.debug({ customTransformers: this.resolvedTransformers }, 'normalized custom AST transformers via ts-jest option');
if (options.stringifyContentPathRegex) {
this._stringifyContentRegExp =
typeof options.stringifyContentPathRegex === 'string'
? new RegExp(normalizeRegex(options.stringifyContentPathRegex))
: options.stringifyContentPathRegex;
this.logger.debug({ stringifyContentPathRegex: this._stringifyContentRegExp }, 'normalized stringifyContentPathRegex config via ts-jest option');
}
};
ConfigSet.prototype._resolveTsCacheDir = function () {
this.cacheSuffix = (0, sha1_1.sha1)((0, utils_1.stringify)({
version: this.compilerModule.version,
digest: this.tsJestDigest,
babelConfig: this.babelConfig,
tsconfig: {
options: this.parsedTsConfig.options,
raw: this.parsedTsConfig.raw,
},
isolatedModules: this.isolatedModules,
diagnostics: this._diagnostics,
transformers: Object.values(this.resolvedTransformers)
.reduce(function (prevVal, currentVal) { return __spreadArray(__spreadArray([], __read(prevVal), false), [currentVal], false); })
.map(function (transformer) { return "".concat(transformer.name, "-").concat(transformer.version); }),
}));
if (!this._jestCfg.cache) {
this.logger.debug('file caching disabled');
}
else {
var res = (0, path_1.join)(this._jestCfg.cacheDirectory, 'ts-jest', this.cacheSuffix.substr(0, 2), this.cacheSuffix.substr(2));
this.logger.debug({ cacheDirectory: res }, 'will use file caching');
this.tsCacheDir = res;
}
};
ConfigSet.prototype._getAndResolveTsConfig = function (compilerOptions, resolvedConfigFile) {
var e_2, _a, _b;
var _c, _d, _e;
var result = this._resolveTsConfig(compilerOptions, resolvedConfigFile);
var forcedOptions = this._overriddenCompilerOptions;
var finalOptions = result.options;
if (finalOptions.target === undefined) {
finalOptions.target = this.compilerModule.ScriptTarget.ES2015;
}
var target = finalOptions.target;
var defaultModule = [this.compilerModule.ScriptTarget.ES3, this.compilerModule.ScriptTarget.ES5].includes(target)
? this.compilerModule.ModuleKind.CommonJS
: this.compilerModule.ModuleKind.ESNext;
var moduleValue = (_c = finalOptions.module) !== null && _c !== void 0 ? _c : defaultModule;
if (!this.babelConfig &&
moduleValue !== this.compilerModule.ModuleKind.CommonJS &&
!(finalOptions.esModuleInterop || finalOptions.allowSyntheticDefaultImports)) {
result.errors.push({
code: 151001,
messageText: "If you have issues related to imports, you should consider setting `esModuleInterop` to `true` in your TypeScript configuration file (usually `tsconfig.json`). See https://blogs.msdn.microsoft.com/typescript/2018/01/31/announcing-typescript-2-7/#easier-ecmascript-module-interoperability for more information.",
category: this.compilerModule.DiagnosticCategory.Message,
file: undefined,
start: undefined,
length: undefined,
});
if (!('allowSyntheticDefaultImports' in finalOptions)) {
finalOptions.allowSyntheticDefaultImports = true;
}
}
if (finalOptions.allowJs && !finalOptions.outDir) {
finalOptions.outDir = exports.TS_JEST_OUT_DIR;
}
try {
for (var _f = __values(Object.keys(forcedOptions)), _g = _f.next(); !_g.done; _g = _f.next()) {
var key = _g.value;
var val = forcedOptions[key];
if (val === undefined) {
delete finalOptions[key];
}
else {
finalOptions[key] = val;
}
}
}
catch (e_2_1) { e_2 = { error: e_2_1 }; }
finally {
try {
if (_g && !_g.done && (_a = _f.return)) _a.call(_f);
}
finally { if (e_2) throw e_2.error; }
}
var nodeJsVer = process.version;
var compilationTarget = result.options.target;
var TARGET_TO_VERSION_MAPPING = (_b = {},
_b[this.compilerModule.ScriptTarget.ES2018] = 'es2018',
_b[this.compilerModule.ScriptTarget.ES2019] = 'es2019',
_b[this.compilerModule.ScriptTarget.ES2020] = 'es2020',
_b[this.compilerModule.ScriptTarget.ESNext] = 'ESNext',
_b);
if (compilationTarget &&
!this.babelConfig &&
nodeJsVer.startsWith('v12') &&
compilationTarget > this.compilerModule.ScriptTarget.ES2019) {
var message = (0, messages_1.interpolate)("There is a mismatch between your NodeJs version {{nodeJsVer}} and your TypeScript target {{compilationTarget}}. This might lead to some unexpected errors when running tests with `ts-jest`. To fix this, you can check https://github.com/microsoft/TypeScript/wiki/Node-Target-Mapping", {
nodeJsVer: process.version,
compilationTarget: TARGET_TO_VERSION_MAPPING[compilationTarget],
});
this.logger.warn(message);
}
var resultOptions = result.options;
var sourceMap = (_d = resultOptions.sourceMap) !== null && _d !== void 0 ? _d : true;
return __assign(__assign({}, result), { options: __assign(__assign({}, resultOptions), { sourceMap: sourceMap, inlineSources: sourceMap, module: (_e = resultOptions.module) !== null && _e !== void 0 ? _e : this.compilerModule.ModuleKind.CommonJS }) });
};
ConfigSet.prototype._resolveTsConfig = function (compilerOptions, resolvedConfigFile) {
var config = { compilerOptions: Object.create(null) };
var basePath = (0, normalize_slashes_1.normalizeSlashes)(this.rootDir);
var ts = this.compilerModule;
var configFileName = resolvedConfigFile
? (0, normalize_slashes_1.normalizeSlashes)(resolvedConfigFile)
: ts.findConfigFile((0, normalize_slashes_1.normalizeSlashes)(this.rootDir), ts.sys.fileExists);
if (configFileName) {
this.logger.debug({ tsConfigFileName: configFileName }, 'readTsConfig(): reading', configFileName);
var result = ts.readConfigFile(configFileName, ts.sys.readFile);
if (result.error) {
return { errors: [result.error], fileNames: [], options: {} };
}
config = result.config;
basePath = (0, normalize_slashes_1.normalizeSlashes)((0, path_1.dirname)(configFileName));
}
config.compilerOptions = __assign(__assign({}, config.compilerOptions), compilerOptions);
return ts.parseJsonConfigFileContent(config, ts.sys, basePath, undefined, configFileName);
};
ConfigSet.prototype.isTestFile = function (fileName) {
var _this = this;
return this._matchablePatterns.some(function (pattern) {
return typeof pattern === 'string' ? _this._matchTestFilePath(fileName) : pattern.test(fileName);
});
};
ConfigSet.prototype.shouldStringifyContent = function (filePath) {
return this._stringifyContentRegExp ? this._stringifyContentRegExp.test(filePath) : false;
};
ConfigSet.prototype.raiseDiagnostics = function (diagnostics, filePath, logger) {
var _this = this;
var ignoreCodes = this._diagnostics.ignoreCodes;
var DiagnosticCategory = this.compilerModule.DiagnosticCategory;
var filteredDiagnostics = filePath && !this.shouldReportDiagnostics(filePath)
? []
: diagnostics.filter(function (diagnostic) {
var _a;
if (((_a = diagnostic.file) === null || _a === void 0 ? void 0 : _a.fileName) && !_this.shouldReportDiagnostics(diagnostic.file.fileName)) {
return false;
}
return !ignoreCodes.includes(diagnostic.code);
});
if (!filteredDiagnostics.length)
return;
var error = this.createTsError(filteredDiagnostics);
var importantCategories = [DiagnosticCategory.Warning, DiagnosticCategory.Error];
if (this._diagnostics.throws && filteredDiagnostics.some(function (d) { return importantCategories.includes(d.category); })) {
throw error;
}
logger ? logger.warn({ error: error }, error.message) : this.logger.warn({ error: error }, error.message);
};
ConfigSet.prototype.shouldReportDiagnostics = function (filePath) {
var fileExtension = (0, path_1.extname)(filePath);
return constants_1.JS_JSX_EXTENSIONS.includes(fileExtension)
? this.parsedTsConfig.options.checkJs && !this._shouldIgnoreDiagnosticsForFile(filePath)
: !this._shouldIgnoreDiagnosticsForFile(filePath);
};
ConfigSet.prototype.createTsError = function (diagnostics) {
var _this = this;
var formatDiagnostics = this._diagnostics.pretty
? this.compilerModule.formatDiagnosticsWithColorAndContext
: this.compilerModule.formatDiagnostics;
var diagnosticHost = {
getNewLine: function () { return '\n'; },
getCurrentDirectory: function () { return _this.cwd; },
getCanonicalFileName: function (path) { return path; },
};
var diagnosticText = formatDiagnostics(diagnostics, diagnosticHost);
var diagnosticCodes = diagnostics.map(function (x) { return x.code; });
return new ts_error_1.TSError(diagnosticText, diagnosticCodes);
};
ConfigSet.prototype.resolvePath = function (inputPath, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.throwIfMissing, throwIfMissing = _c === void 0 ? true : _c, _d = _b.nodeResolve, nodeResolve = _d === void 0 ? false : _d;
var path = inputPath;
var nodeResolved = false;
if (path.startsWith('<rootDir>')) {
path = (0, path_1.resolve)((0, path_1.join)(this.rootDir, path.substr(9)));
}
else if (!(0, path_1.isAbsolute)(path)) {
if (!path.startsWith('.') && nodeResolve) {
try {
path = require.resolve(path);
nodeResolved = true;
}
catch (_) { }
}
if (!nodeResolved) {
path = (0, path_1.resolve)(this.cwd, path);
}
}
if (!nodeResolved && nodeResolve) {
try {
path = require.resolve(path);
nodeResolved = true;
}
catch (_) { }
}
if (throwIfMissing && !(0, fs_1.existsSync)(path)) {
throw new Error((0, messages_1.interpolate)("File not found: {{inputPath}} (resolved as: {{resolvedPath}})", { inputPath: inputPath, resolvedPath: path }));
}
this.logger.debug({ fromPath: inputPath, toPath: path }, 'resolved path from', inputPath, 'to', path);
return path;
};
return ConfigSet;
}());
exports.ConfigSet = ConfigSet;

5
node_modules/ts-jest/dist/legacy/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,5 @@
import { TsJestTransformer } from './ts-jest-transformer';
declare const _default: {
createTransformer: () => TsJestTransformer;
};
export default _default;

6
node_modules/ts-jest/dist/legacy/index.js generated vendored Normal file
View File

@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var ts_jest_transformer_1 = require("./ts-jest-transformer");
exports.default = {
createTransformer: function () { return new ts_jest_transformer_1.TsJestTransformer(); },
};

View File

@ -0,0 +1,22 @@
import type { SyncTransformer, TransformedSource } from '@jest/transform';
import type { CompilerInstance, ProjectConfigTsJest, TransformOptionsTsJest } from '../types';
import { ConfigSet } from './config/config-set';
export declare class TsJestTransformer implements SyncTransformer {
private readonly _logger;
protected _compiler: CompilerInstance;
private _tsResolvedModulesCachePath;
private _transformCfgStr;
private _depGraphs;
private _watchMode;
constructor();
private _configsFor;
protected _createConfigSet(config: ProjectConfigTsJest | undefined): ConfigSet;
protected _createCompiler(configSet: ConfigSet, cacheFS: Map<string, string>): void;
process(sourceText: string, sourcePath: string, transformOptions: TransformOptionsTsJest): TransformedSource;
processAsync(sourceText: string, sourcePath: string, transformOptions: TransformOptionsTsJest): Promise<TransformedSource>;
private processWithTs;
private runTsJestHook;
getCacheKey(fileContent: string, filePath: string, transformOptions: TransformOptionsTsJest): string;
getCacheKeyAsync(sourceText: string, sourcePath: string, transformOptions: TransformOptionsTsJest): Promise<string>;
private _getFsCachedResolvedModules;
}

324
node_modules/ts-jest/dist/legacy/ts-jest-transformer.js generated vendored Normal file
View File

@ -0,0 +1,324 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TsJestTransformer = exports.CACHE_KEY_EL_SEPARATOR = void 0;
var fs_1 = require("fs");
var path_1 = __importDefault(require("path"));
var constants_1 = require("../constants");
var utils_1 = require("../utils");
var importer_1 = require("../utils/importer");
var messages_1 = require("../utils/messages");
var sha1_1 = require("../utils/sha1");
var version_checkers_1 = require("../utils/version-checkers");
var compiler_1 = require("./compiler");
var config_set_1 = require("./config/config-set");
exports.CACHE_KEY_EL_SEPARATOR = '\x00';
var TsJestTransformer = (function () {
function TsJestTransformer() {
this._depGraphs = new Map();
this._watchMode = false;
this._logger = utils_1.rootLogger.child({ namespace: 'ts-jest-transformer' });
version_checkers_1.VersionCheckers.jest.warn();
this.getCacheKey = this.getCacheKey.bind(this);
this.getCacheKeyAsync = this.getCacheKeyAsync.bind(this);
this.process = this.process.bind(this);
this.processAsync = this.processAsync.bind(this);
this._logger.debug('created new transformer');
process.env.TS_JEST = '1';
}
TsJestTransformer.prototype._configsFor = function (transformOptions) {
var config = transformOptions.config, cacheFS = transformOptions.cacheFS;
var ccs = TsJestTransformer._cachedConfigSets.find(function (cs) { return cs.jestConfig.value === config; });
var configSet;
if (ccs) {
this._transformCfgStr = ccs.transformerCfgStr;
this._compiler = ccs.compiler;
this._depGraphs = ccs.depGraphs;
this._tsResolvedModulesCachePath = ccs.tsResolvedModulesCachePath;
this._watchMode = ccs.watchMode;
configSet = ccs.configSet;
}
else {
var serializedJestCfg_1 = (0, utils_1.stringify)(config);
var serializedCcs = TsJestTransformer._cachedConfigSets.find(function (cs) { return cs.jestConfig.serialized === serializedJestCfg_1; });
if (serializedCcs) {
serializedCcs.jestConfig.value = config;
this._transformCfgStr = serializedCcs.transformerCfgStr;
this._compiler = serializedCcs.compiler;
this._depGraphs = serializedCcs.depGraphs;
this._tsResolvedModulesCachePath = serializedCcs.tsResolvedModulesCachePath;
this._watchMode = serializedCcs.watchMode;
configSet = serializedCcs.configSet;
}
else {
this._logger.info('no matching config-set found, creating a new one');
configSet = this._createConfigSet(config);
var jest_1 = __assign({}, config);
jest_1.cacheDirectory = undefined;
this._transformCfgStr = "".concat(new utils_1.JsonableValue(jest_1).serialized).concat(configSet.cacheSuffix);
this._createCompiler(configSet, cacheFS);
this._getFsCachedResolvedModules(configSet);
this._watchMode = process.argv.includes('--watch');
TsJestTransformer._cachedConfigSets.push({
jestConfig: new utils_1.JsonableValue(config),
configSet: configSet,
transformerCfgStr: this._transformCfgStr,
compiler: this._compiler,
depGraphs: this._depGraphs,
tsResolvedModulesCachePath: this._tsResolvedModulesCachePath,
watchMode: this._watchMode,
});
}
}
return configSet;
};
TsJestTransformer.prototype._createConfigSet = function (config) {
return new config_set_1.ConfigSet(config);
};
TsJestTransformer.prototype._createCompiler = function (configSet, cacheFS) {
this._compiler = new compiler_1.TsJestCompiler(configSet, cacheFS);
};
TsJestTransformer.prototype.process = function (sourceText, sourcePath, transformOptions) {
this._logger.debug({ fileName: sourcePath, transformOptions: transformOptions }, 'processing', sourcePath);
var configs = this._configsFor(transformOptions);
var shouldStringifyContent = configs.shouldStringifyContent(sourcePath);
var babelJest = shouldStringifyContent ? undefined : configs.babelJestTransformer;
var result = {
code: this.processWithTs(sourceText, sourcePath, transformOptions).code,
};
if (babelJest) {
this._logger.debug({ fileName: sourcePath }, 'calling babel-jest processor');
result = babelJest.process(result.code, sourcePath, __assign(__assign({}, transformOptions), { instrument: false }));
}
result = this.runTsJestHook(sourcePath, sourceText, transformOptions, result);
return result;
};
TsJestTransformer.prototype.processAsync = function (sourceText, sourcePath, transformOptions) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
this._logger.debug({ fileName: sourcePath, transformOptions: transformOptions }, 'processing', sourcePath);
return [2, new Promise(function (resolve, reject) { return __awaiter(_this, void 0, void 0, function () {
var configs, shouldStringifyContent, babelJest, result, processWithTsResult;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
configs = this._configsFor(transformOptions);
shouldStringifyContent = configs.shouldStringifyContent(sourcePath);
babelJest = shouldStringifyContent ? undefined : configs.babelJestTransformer;
processWithTsResult = this.processWithTs(sourceText, sourcePath, transformOptions);
result = {
code: processWithTsResult.code,
};
if ((_a = processWithTsResult.diagnostics) === null || _a === void 0 ? void 0 : _a.length) {
reject(configs.createTsError(processWithTsResult.diagnostics));
}
if (!babelJest) return [3, 2];
this._logger.debug({ fileName: sourcePath }, 'calling babel-jest processor');
return [4, babelJest.processAsync(result.code, sourcePath, __assign(__assign({}, transformOptions), { instrument: false }))];
case 1:
result = _b.sent();
_b.label = 2;
case 2:
result = this.runTsJestHook(sourcePath, sourceText, transformOptions, result);
resolve(result);
return [2];
}
});
}); })];
});
});
};
TsJestTransformer.prototype.processWithTs = function (sourceText, sourcePath, transformOptions) {
var result;
var configs = this._configsFor(transformOptions);
var shouldStringifyContent = configs.shouldStringifyContent(sourcePath);
var babelJest = shouldStringifyContent ? undefined : configs.babelJestTransformer;
var isDefinitionFile = sourcePath.endsWith(constants_1.DECLARATION_TYPE_EXT);
var isJsFile = constants_1.JS_JSX_REGEX.test(sourcePath);
var isTsFile = !isDefinitionFile && constants_1.TS_TSX_REGEX.test(sourcePath);
if (shouldStringifyContent) {
result = {
code: "module.exports=".concat((0, utils_1.stringify)(sourceText)),
};
}
else if (isDefinitionFile) {
result = {
code: '',
};
}
else if (!configs.parsedTsConfig.options.allowJs && isJsFile) {
this._logger.warn({ fileName: sourcePath }, (0, messages_1.interpolate)("Got a `.js` file to compile while `allowJs` option is not set to `true` (file: {{path}}). To fix this:\n - if you want TypeScript to process JS files, set `allowJs` to `true` in your TypeScript config (usually tsconfig.json)\n - if you do not want TypeScript to process your `.js` files, in your Jest config change the `transform` key which value is `ts-jest` so that it does not match `.js` files anymore", { path: sourcePath }));
result = {
code: sourceText,
};
}
else if (isJsFile || isTsFile) {
result = this._compiler.getCompiledOutput(sourceText, sourcePath, {
depGraphs: this._depGraphs,
supportsStaticESM: transformOptions.supportsStaticESM,
watchMode: this._watchMode,
});
}
else {
var message = babelJest ? "Got a unknown file type to compile (file: {{path}}). To fix this, in your Jest config change the `transform` key which value is `ts-jest` so that it does not match this kind of files anymore. If you still want Babel to process it, add another entry to the `transform` option with value `babel-jest` which key matches this type of files." : "Got a unknown file type to compile (file: {{path}}). To fix this, in your Jest config change the `transform` key which value is `ts-jest` so that it does not match this kind of files anymore.";
this._logger.warn({ fileName: sourcePath }, (0, messages_1.interpolate)(message, { path: sourcePath }));
result = {
code: sourceText,
};
}
return result;
};
TsJestTransformer.prototype.runTsJestHook = function (sourcePath, sourceText, transformOptions, compiledOutput) {
var hooksFile = process.env.TS_JEST_HOOKS;
var hooks;
if (hooksFile) {
hooksFile = path_1.default.resolve(this._configsFor(transformOptions).cwd, hooksFile);
hooks = importer_1.importer.tryTheseOr(hooksFile, {});
}
if (hooks === null || hooks === void 0 ? void 0 : hooks.afterProcess) {
this._logger.debug({ fileName: sourcePath, hookName: 'afterProcess' }, 'calling afterProcess hook');
var newResult = hooks.afterProcess([sourceText, sourcePath, transformOptions.config, transformOptions], compiledOutput);
if (newResult) {
return newResult;
}
}
return compiledOutput;
};
TsJestTransformer.prototype.getCacheKey = function (fileContent, filePath, transformOptions) {
var _a;
var configs = this._configsFor(transformOptions);
this._logger.debug({ fileName: filePath, transformOptions: transformOptions }, 'computing cache key for', filePath);
var _b = transformOptions.instrument, instrument = _b === void 0 ? false : _b;
var constructingCacheKeyElements = [
this._transformCfgStr,
exports.CACHE_KEY_EL_SEPARATOR,
configs.rootDir,
exports.CACHE_KEY_EL_SEPARATOR,
"instrument:".concat(instrument ? 'on' : 'off'),
exports.CACHE_KEY_EL_SEPARATOR,
fileContent,
exports.CACHE_KEY_EL_SEPARATOR,
filePath,
];
if (!configs.isolatedModules && this._tsResolvedModulesCachePath) {
var resolvedModuleNames = void 0;
if (((_a = this._depGraphs.get(filePath)) === null || _a === void 0 ? void 0 : _a.fileContent) === fileContent) {
this._logger.debug({ fileName: filePath, transformOptions: transformOptions }, 'getting resolved modules from disk caching or memory caching for', filePath);
resolvedModuleNames = this._depGraphs
.get(filePath)
.resolvedModuleNames.filter(function (moduleName) { return (0, fs_1.existsSync)(moduleName); });
}
else {
this._logger.debug({ fileName: filePath, transformOptions: transformOptions }, 'getting resolved modules from TypeScript API for', filePath);
resolvedModuleNames = this._compiler.getResolvedModules(fileContent, filePath, transformOptions.cacheFS);
this._depGraphs.set(filePath, {
fileContent: fileContent,
resolvedModuleNames: resolvedModuleNames,
});
(0, fs_1.writeFileSync)(this._tsResolvedModulesCachePath, (0, utils_1.stringify)(__spreadArray([], __read(this._depGraphs), false)));
}
resolvedModuleNames.forEach(function (moduleName) {
constructingCacheKeyElements.push(exports.CACHE_KEY_EL_SEPARATOR, moduleName, exports.CACHE_KEY_EL_SEPARATOR, (0, fs_1.statSync)(moduleName).mtimeMs.toString());
});
}
return sha1_1.sha1.apply(void 0, __spreadArray([], __read(constructingCacheKeyElements), false));
};
TsJestTransformer.prototype.getCacheKeyAsync = function (sourceText, sourcePath, transformOptions) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
return [2, Promise.resolve(this.getCacheKey(sourceText, sourcePath, transformOptions))];
});
});
};
TsJestTransformer.prototype._getFsCachedResolvedModules = function (configSet) {
var cacheDir = configSet.tsCacheDir;
if (!configSet.isolatedModules && cacheDir) {
(0, fs_1.mkdirSync)(cacheDir, { recursive: true });
this._tsResolvedModulesCachePath = path_1.default.join(cacheDir, (0, sha1_1.sha1)('ts-jest-resolved-modules', exports.CACHE_KEY_EL_SEPARATOR));
try {
var cachedTSResolvedModules = (0, fs_1.readFileSync)(this._tsResolvedModulesCachePath, 'utf-8');
this._depGraphs = new Map((0, utils_1.parse)(cachedTSResolvedModules));
}
catch (e) { }
}
};
TsJestTransformer._cachedConfigSets = [];
return TsJestTransformer;
}());
exports.TsJestTransformer = TsJestTransformer;

View File

@ -0,0 +1,3 @@
import type { Config } from '@jest/types';
import type { TsJestPresets } from '../types';
export declare function createJestPreset(legacy?: boolean, allowJs?: boolean, extraOptions?: Config.InitialOptions): TsJestPresets;

View File

@ -0,0 +1,29 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createJestPreset = void 0;
var utils_1 = require("../utils");
var logger = utils_1.rootLogger.child({ namespace: 'jest-preset' });
function createJestPreset(legacy, allowJs, extraOptions) {
var _a;
if (legacy === void 0) { legacy = false; }
if (allowJs === void 0) { allowJs = false; }
if (extraOptions === void 0) { extraOptions = {}; }
logger.debug({ allowJs: allowJs }, 'creating jest presets', allowJs ? 'handling' : 'not handling', 'JavaScript files');
var extensionsToTreatAsEsm = extraOptions.extensionsToTreatAsEsm, moduleFileExtensions = extraOptions.moduleFileExtensions, testMatch = extraOptions.testMatch;
var supportESM = extensionsToTreatAsEsm === null || extensionsToTreatAsEsm === void 0 ? void 0 : extensionsToTreatAsEsm.length;
return __assign(__assign(__assign(__assign({}, (extensionsToTreatAsEsm ? { extensionsToTreatAsEsm: extensionsToTreatAsEsm } : undefined)), (moduleFileExtensions ? { moduleFileExtensions: moduleFileExtensions } : undefined)), (testMatch ? { testMatch: testMatch } : undefined)), { transform: __assign(__assign({}, extraOptions.transform), (_a = {}, _a[allowJs ? (supportESM ? '^.+\\.m?[tj]sx?$' : '^.+\\.[tj]sx?$') : '^.+\\.tsx?$'] = legacy
? 'ts-jest/legacy'
: 'ts-jest', _a)) });
}
exports.createJestPreset = createJestPreset;

106
node_modules/ts-jest/dist/raw-compiler-options.d.ts generated vendored Normal file
View File

@ -0,0 +1,106 @@
export interface RawCompilerOptions {
charset?: string;
composite?: boolean;
declaration?: boolean;
declarationDir?: string | null;
diagnostics?: boolean;
disableReferencedProjectLoad?: boolean;
noPropertyAccessFromIndexSignature?: boolean;
emitBOM?: boolean;
emitDeclarationOnly?: boolean;
incremental?: boolean;
tsBuildInfoFile?: string;
inlineSourceMap?: boolean;
inlineSources?: boolean;
jsx?: 'preserve' | 'react' | 'react-jsx' | 'react-jsxdev' | 'react-native';
reactNamespace?: string;
jsxFactory?: string;
jsxFragmentFactory?: string;
jsxImportSource?: string;
listFiles?: boolean;
mapRoot?: string;
module?: ('CommonJS' | 'AMD' | 'System' | 'UMD' | 'ES6' | 'ES2015' | 'ES2020' | 'ESNext' | 'None') | string;
moduleResolution?: ('Classic' | 'Node') | string;
newLine?: ('crlf' | 'lf') | string;
noEmit?: boolean;
noEmitHelpers?: boolean;
noEmitOnError?: boolean;
noImplicitAny?: boolean;
noImplicitThis?: boolean;
noUnusedLocals?: boolean;
noUnusedParameters?: boolean;
noLib?: boolean;
noResolve?: boolean;
noStrictGenericChecks?: boolean;
skipDefaultLibCheck?: boolean;
skipLibCheck?: boolean;
outFile?: string;
outDir?: string;
preserveConstEnums?: boolean;
preserveSymlinks?: boolean;
preserveWatchOutput?: boolean;
pretty?: boolean;
removeComments?: boolean;
rootDir?: string;
isolatedModules?: boolean;
sourceMap?: boolean;
sourceRoot?: string;
suppressExcessPropertyErrors?: boolean;
suppressImplicitAnyIndexErrors?: boolean;
target?: ('ES3' | 'ES5' | 'ES6' | 'ES2015' | 'ES2016' | 'ES2017' | 'ES2018' | 'ES2019' | 'ES2020' | 'ESNext') | string;
watch?: boolean;
fallbackPolling?: 'fixedPollingInterval' | 'priorityPollingInterval' | 'dynamicPriorityPolling';
watchDirectory?: 'useFsEvents' | 'fixedPollingInterval' | 'dynamicPriorityPolling';
watchFile?: 'fixedPollingInterval' | 'priorityPollingInterval' | 'dynamicPriorityPolling' | 'useFsEvents' | 'useFsEventsOnParentDirectory';
experimentalDecorators?: boolean;
emitDecoratorMetadata?: boolean;
allowUnusedLabels?: boolean;
noImplicitReturns?: boolean;
noUncheckedIndexedAccess?: boolean;
noFallthroughCasesInSwitch?: boolean;
allowUnreachableCode?: boolean;
forceConsistentCasingInFileNames?: boolean;
generateCpuProfile?: string;
baseUrl?: string;
paths?: {
[k: string]: string[];
};
plugins?: Array<{
name?: string;
[k: string]: unknown;
}>;
rootDirs?: string[];
typeRoots?: string[];
types?: string[];
traceResolution?: boolean;
allowJs?: boolean;
noErrorTruncation?: boolean;
allowSyntheticDefaultImports?: boolean;
noImplicitUseStrict?: boolean;
listEmittedFiles?: boolean;
disableSizeLimit?: boolean;
lib?: Array<('ES5' | 'ES6' | 'ES2015' | 'ES2015.Collection' | 'ES2015.Core' | 'ES2015.Generator' | 'ES2015.Iterable' | 'ES2015.Promise' | 'ES2015.Proxy' | 'ES2015.Reflect' | 'ES2015.Symbol.WellKnown' | 'ES2015.Symbol' | 'ES2016' | 'ES2016.Array.Include' | 'ES2017' | 'ES2017.Intl' | 'ES2017.Object' | 'ES2017.SharedMemory' | 'ES2017.String' | 'ES2017.TypedArrays' | 'ES2018' | 'ES2018.AsyncGenerator' | 'ES2018.AsyncIterable' | 'ES2018.Intl' | 'ES2018.Promise' | 'ES2018.Regexp' | 'ES2019' | 'ES2019.Array' | 'ES2019.Object' | 'ES2019.String' | 'ES2019.Symbol' | 'ES2020' | 'ES2020.BigInt' | 'ES2020.Promise' | 'ES2020.String' | 'ES2020.Symbol.WellKnown' | 'ESNext' | 'ESNext.Array' | 'ESNext.AsyncIterable' | 'ESNext.BigInt' | 'ESNext.Intl' | 'ESNext.Promise' | 'ESNext.String' | 'ESNext.Symbol' | 'DOM' | 'DOM.Iterable' | 'ScriptHost' | 'WebWorker' | 'WebWorker.ImportScripts') | string>;
strictNullChecks?: boolean;
maxNodeModuleJsDepth?: number;
importHelpers?: boolean;
importsNotUsedAsValues?: 'remove' | 'preserve' | 'error';
alwaysStrict?: boolean;
strict?: boolean;
strictBindCallApply?: boolean;
downlevelIteration?: boolean;
checkJs?: boolean;
strictFunctionTypes?: boolean;
strictPropertyInitialization?: boolean;
esModuleInterop?: boolean;
allowUmdGlobalAccess?: boolean;
keyofStringsOnly?: boolean;
useDefineForClassFields?: boolean;
declarationMap?: boolean;
resolveJsonModule?: boolean;
assumeChangesOnlyAffectDirectDependencies?: boolean;
extendedDiagnostics?: boolean;
listFilesOnly?: boolean;
disableSourceOfProjectReferenceRedirect?: boolean;
disableSolutionSearching?: boolean;
[k: string]: unknown;
}

2
node_modules/ts-jest/dist/raw-compiler-options.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

View File

@ -0,0 +1,5 @@
import type _ts from 'typescript';
import type { TsCompilerInstance } from '../types';
export declare const version = 4;
export declare const name = "hoist-jest";
export declare function factory({ configSet }: TsCompilerInstance): (ctx: _ts.TransformationContext) => _ts.Transformer<_ts.SourceFile>;

100
node_modules/ts-jest/dist/transformers/hoist-jest.js generated vendored Normal file
View File

@ -0,0 +1,100 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.factory = exports.name = exports.version = void 0;
var bs_logger_1 = require("bs-logger");
exports.version = 4;
exports.name = 'hoist-jest';
var HOIST_METHODS = ['mock', 'unmock', 'enableAutomock', 'disableAutomock', 'deepUnmock'];
var JEST_GLOBALS_MODULE_NAME = '@jest/globals';
var JEST_GLOBAL_NAME = 'jest';
function factory(_a) {
var configSet = _a.configSet;
var logger = configSet.logger.child({ namespace: exports.name });
var ts = configSet.compilerModule;
var importNamesOfJestObj = [];
var isJestGlobalImport = function (node) {
return (ts.isImportDeclaration(node) &&
ts.isStringLiteral(node.moduleSpecifier) &&
node.moduleSpecifier.text === JEST_GLOBALS_MODULE_NAME);
};
var shouldHoistExpression = function (node) {
if (ts.isCallExpression(node) &&
ts.isPropertyAccessExpression(node.expression) &&
HOIST_METHODS.includes(node.expression.name.text)) {
if (importNamesOfJestObj.length) {
return ((ts.isIdentifier(node.expression.expression) &&
importNamesOfJestObj.includes(node.expression.expression.text)) ||
(ts.isPropertyAccessExpression(node.expression.expression) &&
ts.isIdentifier(node.expression.expression.expression) &&
importNamesOfJestObj.includes(node.expression.expression.expression.text)) ||
shouldHoistExpression(node.expression.expression));
}
else {
return ((ts.isIdentifier(node.expression.expression) && node.expression.expression.text === JEST_GLOBAL_NAME) ||
shouldHoistExpression(node.expression.expression));
}
}
return false;
};
var isHoistableStatement = function (node) {
return ts.isExpressionStatement(node) && shouldHoistExpression(node.expression);
};
var canHoistInBlockScope = function (node) {
return !!node.statements.find(function (stmt) {
return ts.isVariableStatement(stmt) &&
stmt.declarationList.declarations.find(function (decl) { return ts.isIdentifier(decl.name) && decl.name.text !== JEST_GLOBAL_NAME; }) &&
node.statements.find(function (stmt) { return isHoistableStatement(stmt); });
});
};
var sortStatements = function (statements) {
if (statements.length <= 1) {
return statements;
}
return statements.sort(function (stmtA, stmtB) {
return isJestGlobalImport(stmtA) ||
(isHoistableStatement(stmtA) && !isHoistableStatement(stmtB) && !isJestGlobalImport(stmtB))
? -1
: 1;
});
};
var createVisitor = function (ctx, _) {
var visitor = function (node) {
var resultNode = ts.visitEachChild(node, visitor, ctx);
if (ts.isBlock(resultNode) && canHoistInBlockScope(resultNode)) {
var newNodeArrayStatements = ts.factory.createNodeArray(sortStatements(resultNode.statements));
return ts.factory.updateBlock(resultNode, newNodeArrayStatements);
}
else {
if (ts.isSourceFile(resultNode)) {
resultNode.statements.forEach(function (stmt) {
var _a, _b;
if (isJestGlobalImport(stmt) &&
((_a = stmt.importClause) === null || _a === void 0 ? void 0 : _a.namedBindings) &&
(ts.isNamespaceImport(stmt.importClause.namedBindings) ||
ts.isNamedImports(stmt.importClause.namedBindings))) {
var namedBindings = stmt.importClause.namedBindings;
var jestImportName = ts.isNamespaceImport(namedBindings)
? namedBindings.name.text
: (_b = namedBindings.elements.find(function (element) { var _a; return element.name.text === JEST_GLOBAL_NAME || ((_a = element.propertyName) === null || _a === void 0 ? void 0 : _a.text) === JEST_GLOBAL_NAME; })) === null || _b === void 0 ? void 0 : _b.name.text;
if (jestImportName) {
importNamesOfJestObj.push(jestImportName);
}
}
});
var newNodeArrayStatements = ts.factory.createNodeArray(sortStatements(resultNode.statements));
importNamesOfJestObj.length = 0;
return ts.factory.updateSourceFile(resultNode, newNodeArrayStatements, resultNode.isDeclarationFile, resultNode.referencedFiles, resultNode.typeReferenceDirectives, resultNode.hasNoDefaultLib, resultNode.libReferenceDirectives);
}
return resultNode;
}
};
return visitor;
};
return function (ctx) {
var _a;
return logger.wrap((_a = {}, _a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.debug, _a.call = null, _a), 'visitSourceFileNode(): hoist jest', function (sf) {
return ts.visitNode(sf, createVisitor(ctx, sf));
});
};
}
exports.factory = factory;

103
node_modules/ts-jest/dist/types.d.ts generated vendored Normal file
View File

@ -0,0 +1,103 @@
import type { TransformedSource, TransformOptions } from '@jest/transform';
import type { Config } from '@jest/types';
import type * as babelJest from 'babel-jest';
import type * as _babel from 'babel__core';
import type * as _ts from 'typescript';
import type { ConfigSet } from './legacy/config/config-set';
import type { RawCompilerOptions } from './raw-compiler-options';
declare module '@jest/types' {
namespace Config {
interface ConfigGlobals {
'ts-jest': TsJestGlobalOptions;
}
}
}
export declare type TBabelJest = typeof babelJest;
export declare type TTypeScript = typeof _ts;
export interface TEsBuild {
transformSync(input: string, options?: {
loader: 'ts' | 'js';
format: 'cjs' | 'esm';
target: string;
}): {
code: string;
map: string;
};
}
export declare type BabelConfig = _babel.TransformOptions;
export declare type TsJestPresets = Pick<Config.InitialOptions, 'extensionsToTreatAsEsm' | 'moduleFileExtensions' | 'transform' | 'testMatch'>;
export interface AstTransformer<T = Record<string, unknown>> {
path: string;
options?: T;
}
export interface ConfigCustomTransformer {
before?: Array<string | AstTransformer>;
after?: Array<string | AstTransformer>;
afterDeclarations?: Array<string | AstTransformer>;
}
export interface TsJestGlobalOptions {
tsconfig?: boolean | string | RawCompilerOptions;
isolatedModules?: boolean;
compiler?: 'typescript' | 'ttypescript' | string;
astTransformers?: ConfigCustomTransformer;
diagnostics?: boolean | {
pretty?: boolean;
ignoreCodes?: number | string | Array<number | string>;
exclude?: string[];
warnOnly?: boolean;
};
babelConfig?: boolean | string | BabelConfig;
stringifyContentPathRegex?: string | RegExp;
useESM?: boolean;
}
export interface TsJestDiagnosticsCfg {
pretty: boolean;
ignoreCodes: number[];
exclude: string[];
throws: boolean;
warnOnly?: boolean;
}
export interface ProjectConfigTsJest extends Config.ProjectConfig {
globals: GlobalConfigTsJest;
}
export interface TransformOptionsTsJest extends TransformOptions {
config: ProjectConfigTsJest;
}
export interface GlobalConfigTsJest extends Config.ConfigGlobals {
'ts-jest': TsJestGlobalOptions;
}
export interface InitialOptionsTsJest extends Config.InitialOptions {
globals?: GlobalConfigTsJest;
}
export declare type StringMap = Map<string, string>;
export interface DepGraphInfo {
fileContent: string;
resolvedModuleNames: string[];
}
export interface TsJestCompileOptions {
depGraphs: Map<string, DepGraphInfo>;
watchMode: boolean;
supportsStaticESM: boolean;
}
export interface CompiledOutput extends TransformedSource {
diagnostics?: _ts.Diagnostic[];
}
export interface CompilerInstance {
getResolvedModules(fileContent: string, fileName: string, runtimeCacheFS: StringMap): string[];
getCompiledOutput(fileContent: string, fileName: string, options: TsJestCompileOptions): CompiledOutput;
}
export interface TsCompilerInstance extends CompilerInstance {
configSet: ConfigSet;
program: _ts.Program | undefined;
}
export interface AstTransformerDesc<T = Record<string, unknown>> {
name: string;
version: number;
factory(tsCompiler: TsCompilerInstance, opts?: T): _ts.TransformerFactory<_ts.SourceFile> | _ts.TransformerFactory<_ts.Bundle | _ts.SourceFile>;
options?: T;
}
export interface TsJestAstTransformer {
before: AstTransformerDesc[];
after: AstTransformerDesc[];
afterDeclarations: AstTransformerDesc[];
}

2
node_modules/ts-jest/dist/types.js generated vendored Normal file
View File

@ -0,0 +1,2 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });

1
node_modules/ts-jest/dist/utils/backports.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

111
node_modules/ts-jest/dist/utils/backports.js generated vendored Normal file
View File

@ -0,0 +1,111 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.backportTsJestDebugEnvVar = exports.backportJestConfig = void 0;
var bs_logger_1 = require("bs-logger");
var messages_1 = require("./messages");
var context = (_a = {}, _a[bs_logger_1.LogContexts.namespace] = 'backports', _a);
var backportJestConfig = function (logger, config) {
logger.debug(__assign(__assign({}, context), { config: config }), 'backporting config');
var _a = (config || {}).globals, globals = _a === void 0 ? {} : _a;
var _b = globals["ts-jest"], tsJest = _b === void 0 ? {} : _b;
var mergeTsJest = {};
var hadWarnings = false;
var warnConfig = function (oldPath, newPath, note) {
hadWarnings = true;
logger.warn(context, (0, messages_1.interpolate)(note ? "\"[jest-config].{{oldPath}}\" is deprecated, use \"[jest-config].{{newPath}}\" instead.\n \u21B3 {{note}}" : "\"[jest-config].{{oldPath}}\" is deprecated, use \"[jest-config].{{newPath}}\" instead.", {
oldPath: oldPath,
newPath: newPath,
note: note,
}));
};
if ('__TS_CONFIG__' in globals) {
warnConfig('globals.__TS_CONFIG__', 'globals.ts-jest.tsconfig');
if (typeof globals.__TS_CONFIG__ === 'object') {
mergeTsJest.tsconfig = globals.__TS_CONFIG__;
}
delete globals.__TS_CONFIG__;
}
if ('__TRANSFORM_HTML__' in globals) {
warnConfig('globals.__TRANSFORM_HTML__', 'globals.ts-jest.stringifyContentPathRegex');
if (globals.__TRANSFORM_HTML__) {
mergeTsJest.stringifyContentPathRegex = '\\.html?$';
}
delete globals.__TRANSFORM_HTML__;
}
if ('typeCheck' in tsJest) {
warnConfig('globals.ts-jest.typeCheck', 'globals.ts-jest.isolatedModules');
mergeTsJest.isolatedModules = !tsJest.typeCheck;
delete tsJest.typeCheck;
}
if ('tsConfigFile' in tsJest) {
warnConfig('globals.ts-jest.tsConfigFile', 'globals.ts-jest.tsconfig');
if (tsJest.tsConfigFile) {
mergeTsJest.tsconfig = tsJest.tsConfigFile;
}
delete tsJest.tsConfigFile;
}
if ('tsConfig' in tsJest) {
warnConfig('globals.ts-jest.tsConfig', 'globals.ts-jest.tsconfig');
if (tsJest.tsConfig) {
mergeTsJest.tsconfig = tsJest.tsConfig;
}
delete tsJest.tsConfig;
}
if ('enableTsDiagnostics' in tsJest) {
warnConfig('globals.ts-jest.enableTsDiagnostics', 'globals.ts-jest.diagnostics');
if (tsJest.enableTsDiagnostics) {
mergeTsJest.diagnostics = { warnOnly: true };
if (typeof tsJest.enableTsDiagnostics === 'string')
mergeTsJest.diagnostics.exclude = [tsJest.enableTsDiagnostics];
}
else {
mergeTsJest.diagnostics = false;
}
delete tsJest.enableTsDiagnostics;
}
if ('useBabelrc' in tsJest) {
warnConfig('globals.ts-jest.useBabelrc', 'globals.ts-jest.babelConfig', "See `babel-jest` related issue: https://github.com/facebook/jest/issues/3845");
if (tsJest.useBabelrc != null) {
mergeTsJest.babelConfig = tsJest.useBabelrc ? true : {};
}
delete tsJest.useBabelrc;
}
if ('skipBabel' in tsJest) {
warnConfig('globals.ts-jest.skipBabel', 'globals.ts-jest.babelConfig');
if (tsJest.skipBabel === false && !mergeTsJest.babelConfig) {
mergeTsJest.babelConfig = true;
}
delete tsJest.skipBabel;
}
if (hadWarnings) {
logger.warn(context, "Your Jest configuration is outdated. Use the CLI to help migrating it: ts-jest config:migrate <config-file>.");
}
return __assign(__assign({}, config), { globals: __assign(__assign({}, globals), { 'ts-jest': __assign(__assign({}, mergeTsJest), tsJest) }) });
};
exports.backportJestConfig = backportJestConfig;
var backportTsJestDebugEnvVar = function (logger) {
if ('TS_JEST_DEBUG' in process.env) {
var shouldLog = !/^\s*(?:0|f(?:alse)?|no?|disabled?|off|)\s*$/i.test(process.env.TS_JEST_DEBUG || '');
delete process.env.TS_JEST_DEBUG;
if (shouldLog) {
process.env.TS_JEST_LOG = 'ts-jest.log,stderr:warn';
}
logger.warn(context, (0, messages_1.interpolate)("Using env. var \"{{old}}\" is deprecated, use \"{{new}}\" instead.", {
old: 'TS_JEST_DEBUG',
new: 'TS_JEST_LOG',
}));
}
};
exports.backportTsJestDebugEnvVar = backportTsJestDebugEnvVar;

View File

@ -0,0 +1 @@
export {};

11
node_modules/ts-jest/dist/utils/get-package-version.js generated vendored Normal file
View File

@ -0,0 +1,11 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getPackageVersion = void 0;
function getPackageVersion(moduleName) {
try {
return require("".concat(moduleName, "/package.json")).version;
}
catch (err) { }
return;
}
exports.getPackageVersion = getPackageVersion;

1
node_modules/ts-jest/dist/utils/importer.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

204
node_modules/ts-jest/dist/utils/importer.js generated vendored Normal file
View File

@ -0,0 +1,204 @@
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __read = (this && this.__read) || function (o, n) {
var m = typeof Symbol === "function" && o[Symbol.iterator];
if (!m) return o;
var i = m.call(o), r, ar = [], e;
try {
while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
}
catch (error) { e = { error: error }; }
finally {
try {
if (r && !r.done && (m = i["return"])) m.call(i);
}
finally { if (e) throw e.error; }
}
return ar;
};
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
if (ar || !(i in from)) {
if (!ar) ar = Array.prototype.slice.call(from, 0, i);
ar[i] = from[i];
}
}
return to.concat(ar || Array.prototype.slice.call(from));
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.__requireModule = exports.importer = exports.Importer = void 0;
var logger_1 = require("./logger");
var memoize_1 = require("./memoize");
var messages_1 = require("./messages");
var version_checkers_1 = require("./version-checkers");
var logger = logger_1.rootLogger.child({ namespace: 'Importer' });
var passThru = function (action) { return function (input) {
action();
return input;
}; };
var Importer = (function () {
function Importer(_patches) {
if (_patches === void 0) { _patches = {}; }
this._patches = _patches;
}
Object.defineProperty(Importer, "instance", {
get: function () {
logger.debug('creating Importer singleton');
return new Importer({
'@babel/core': [passThru(version_checkers_1.VersionCheckers.babelCore.warn)],
'babel-jest': [passThru(version_checkers_1.VersionCheckers.babelJest.warn)],
typescript: [passThru(version_checkers_1.VersionCheckers.typescript.warn)],
jest: [passThru(version_checkers_1.VersionCheckers.jest.warn)],
});
},
enumerable: false,
configurable: true
});
Importer.prototype.babelJest = function (why) {
return this._import(why, 'babel-jest');
};
Importer.prototype.babelCore = function (why) {
return this._import(why, '@babel/core');
};
Importer.prototype.typescript = function (why, which) {
return this._import(why, which);
};
Importer.prototype.esBuild = function (why) {
return this._import(why, 'esbuild');
};
Importer.prototype.tryThese = function (moduleName) {
var fallbacks = [];
for (var _i = 1; _i < arguments.length; _i++) {
fallbacks[_i - 1] = arguments[_i];
}
var name;
var loaded;
var tries = __spreadArray([moduleName], __read(fallbacks), false);
while ((name = tries.shift()) !== undefined) {
var req = requireWrapper(name);
var contextReq = __assign({}, req);
delete contextReq.exports;
if (req.exists) {
loaded = req;
if (loaded.error) {
logger.error({ requireResult: contextReq }, "failed loading module '".concat(name, "'"), loaded.error.message);
}
else {
logger.debug({ requireResult: contextReq }, 'loaded module', name);
loaded.exports = this._patch(name, loaded.exports);
}
break;
}
else {
logger.debug({ requireResult: contextReq }, "module '".concat(name, "' not found"));
}
}
return loaded;
};
Importer.prototype.tryTheseOr = function (moduleNames, missingResult, allowLoadError) {
if (allowLoadError === void 0) { allowLoadError = false; }
var args = Array.isArray(moduleNames) ? moduleNames : [moduleNames];
var result = this.tryThese.apply(this, __spreadArray([], __read(args), false));
if (!result)
return missingResult;
if (!result.error)
return result.exports;
if (allowLoadError)
return missingResult;
throw result.error;
};
Importer.prototype._patch = function (name, unpatched) {
if (name in this._patches) {
logger.debug('patching', name);
return this._patches[name].reduce(function (mod, patcher) { return patcher(mod); }, unpatched);
}
return unpatched;
};
Importer.prototype._import = function (why, moduleName, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.alternatives, alternatives = _c === void 0 ? [] : _c, _d = _b.installTip, installTip = _d === void 0 ? moduleName : _d;
var res = this.tryThese.apply(this, __spreadArray([moduleName], __read(alternatives), false));
if (res && res.exists) {
if (!res.error)
return res.exports;
throw new Error((0, messages_1.interpolate)("Loading module {{module}} failed with error: {{error}}", { module: res.given, error: res.error.message }));
}
var msg = alternatives.length ? "Unable to load any of these modules: {{module}}. {{reason}}. To fix it:\n{{fix}}" : "Unable to load the module {{module}}. {{reason}} To fix it:\n{{fix}}";
var loadModule = __spreadArray([moduleName], __read(alternatives), false).map(function (m) { return "\"".concat(m, "\""); }).join(', ');
if (typeof installTip === 'string') {
installTip = [{ module: installTip, label: "install \"".concat(installTip, "\"") }];
}
var fix = installTip
.map(function (tip) { return " ".concat(installTip.length === 1 ? '↳' : '•', " ").concat((0, messages_1.interpolate)("{{label}}: `npm i -D {{module}}` (or `yarn add --dev {{module}}`)", tip)); })
.join('\n');
throw new Error((0, messages_1.interpolate)(msg, {
module: loadModule,
reason: why,
fix: fix,
}));
};
__decorate([
(0, memoize_1.Memoize)(function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
return args.join(':');
})
], Importer.prototype, "tryThese", null);
__decorate([
(0, memoize_1.Memoize)(function (name) { return name; })
], Importer.prototype, "_patch", null);
__decorate([
(0, memoize_1.Memoize)()
], Importer, "instance", null);
return Importer;
}());
exports.Importer = Importer;
exports.importer = Importer.instance;
function requireWrapper(moduleName) {
var path;
var exists = false;
try {
path = resolveModule(moduleName);
exists = true;
}
catch (error) {
return { error: error, exists: exists, given: moduleName };
}
var result = { exists: exists, path: path, given: moduleName };
try {
result.exports = requireModule(path);
}
catch (error) {
try {
result.exports = requireModule(moduleName);
}
catch (error) {
result.error = error;
}
}
return result;
}
var requireModule = function (mod) { return require(mod); };
var resolveModule = function (mod) { return require.resolve(mod, { paths: [process.cwd(), __dirname] }); };
function __requireModule(localRequire, localResolve) {
requireModule = localRequire;
resolveModule = localResolve;
}
exports.__requireModule = __requireModule;

3
node_modules/ts-jest/dist/utils/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,3 @@
export * from './json';
export * from './jsonable-value';
export * from './logger';

19
node_modules/ts-jest/dist/utils/index.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./json"), exports);
__exportStar(require("./jsonable-value"), exports);
__exportStar(require("./logger"), exports);

2
node_modules/ts-jest/dist/utils/json.d.ts generated vendored Normal file
View File

@ -0,0 +1,2 @@
export declare function stringify(input: unknown): string;
export declare function parse(input: string): any;

35
node_modules/ts-jest/dist/utils/json.js generated vendored Normal file
View File

@ -0,0 +1,35 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalize = exports.parse = exports.stringify = void 0;
var fast_json_stable_stringify_1 = __importDefault(require("fast-json-stable-stringify"));
var UNDEFINED = 'undefined';
function stringify(input) {
return input === undefined ? UNDEFINED : (0, fast_json_stable_stringify_1.default)(input);
}
exports.stringify = stringify;
function parse(input) {
return input === UNDEFINED ? undefined : JSON.parse(input);
}
exports.parse = parse;
function normalize(input, _a) {
var _b = _a === void 0 ? {} : _a, _c = _b.parse, parser = _c === void 0 ? parse : _c;
var result;
if (normalize.cache.has(input)) {
result = normalize.cache.get(input);
}
else {
var data = parser(input);
result = stringify(data);
if (result === input)
result = undefined;
normalize.cache.set(input, result);
}
return result === undefined ? input : result;
}
exports.normalize = normalize;
(function (normalize) {
normalize.cache = new Map();
})(normalize = exports.normalize || (exports.normalize = {}));

10
node_modules/ts-jest/dist/utils/jsonable-value.d.ts generated vendored Normal file
View File

@ -0,0 +1,10 @@
export declare class JsonableValue<V = Record<string, any>> {
private _serialized;
private _value;
constructor(value: V);
set value(value: V);
get value(): V;
get serialized(): string;
valueOf(): V;
toString(): string;
}

35
node_modules/ts-jest/dist/utils/jsonable-value.js generated vendored Normal file
View File

@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.JsonableValue = void 0;
var json_1 = require("./json");
var JsonableValue = (function () {
function JsonableValue(value) {
this.value = value;
}
Object.defineProperty(JsonableValue.prototype, "value", {
get: function () {
return this._value;
},
set: function (value) {
this._value = value;
this._serialized = (0, json_1.stringify)(value);
},
enumerable: false,
configurable: true
});
Object.defineProperty(JsonableValue.prototype, "serialized", {
get: function () {
return this._serialized;
},
enumerable: false,
configurable: true
});
JsonableValue.prototype.valueOf = function () {
return this._value;
};
JsonableValue.prototype.toString = function () {
return this._serialized;
};
return JsonableValue;
}());
exports.JsonableValue = JsonableValue;

1
node_modules/ts-jest/dist/utils/logger.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export declare let rootLogger: import("bs-logger/dist/logger").Logger;

22
node_modules/ts-jest/dist/utils/logger.js generated vendored Normal file
View File

@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rootLogger = void 0;
var bs_logger_1 = require("bs-logger");
var backports_1 = require("./backports");
var original = process.env.TS_JEST_LOG;
var buildOptions = function () {
var _a;
return ({
context: (_a = {},
_a[bs_logger_1.LogContexts.package] = 'ts-jest',
_a[bs_logger_1.LogContexts.logLevel] = bs_logger_1.LogLevels.trace,
_a.version = require('../../package.json').version,
_a),
targets: process.env.TS_JEST_LOG || undefined,
});
};
exports.rootLogger = (0, bs_logger_1.createLogger)(buildOptions());
(0, backports_1.backportTsJestDebugEnvVar)(exports.rootLogger);
if (original !== process.env.TS_JEST_LOG) {
exports.rootLogger = (0, bs_logger_1.createLogger)(buildOptions());
}

1
node_modules/ts-jest/dist/utils/memoize.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

48
node_modules/ts-jest/dist/utils/memoize.js generated vendored Normal file
View File

@ -0,0 +1,48 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.Memoize = void 0;
var cacheProp = Symbol.for('[memoize]');
function Memoize(keyBuilder) {
return function (_, propertyKey, descriptor) {
if (descriptor.value != null) {
descriptor.value = memoize(propertyKey, descriptor.value, keyBuilder || (function (v) { return v; }));
}
else if (descriptor.get != null) {
descriptor.get = memoize(propertyKey, descriptor.get, keyBuilder || (function () { return propertyKey; }));
}
};
}
exports.Memoize = Memoize;
function ensureCache(target, reset) {
if (reset === void 0) { reset = false; }
if (reset || !target[cacheProp]) {
Object.defineProperty(target, cacheProp, {
value: Object.create(null),
configurable: true,
});
}
return target[cacheProp];
}
function ensureChildCache(target, key, reset) {
if (reset === void 0) { reset = false; }
var dict = ensureCache(target);
if (reset || !dict[key]) {
dict[key] = new Map();
}
return dict[key];
}
function memoize(namespace, func, keyBuilder) {
return function () {
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var cache = ensureChildCache(this, namespace);
var key = keyBuilder.apply(this, args);
if (cache.has(key))
return cache.get(key);
var res = func.apply(this, args);
cache.set(key, res);
return res;
};
}

1
node_modules/ts-jest/dist/utils/messages.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

8
node_modules/ts-jest/dist/utils/messages.js generated vendored Normal file
View File

@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.interpolate = void 0;
function interpolate(msg, vars) {
if (vars === void 0) { vars = {}; }
return msg.replace(/\{\{([^\}]+)\}\}/g, function (_, key) { return (key in vars ? vars[key] : _); });
}
exports.interpolate = interpolate;

View File

@ -0,0 +1 @@
export {};

7
node_modules/ts-jest/dist/utils/normalize-slashes.js generated vendored Normal file
View File

@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeSlashes = void 0;
function normalizeSlashes(value) {
return value.replace(/\\/g, '/');
}
exports.normalizeSlashes = normalizeSlashes;

1
node_modules/ts-jest/dist/utils/sha1.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

32
node_modules/ts-jest/dist/utils/sha1.js generated vendored Normal file
View File

@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.sha1 = exports.cache = void 0;
var crypto_1 = require("crypto");
exports.cache = Object.create(null);
function sha1() {
var data = [];
for (var _i = 0; _i < arguments.length; _i++) {
data[_i] = arguments[_i];
}
var canCache = data.length === 1 && typeof data[0] === 'string';
var cacheKey;
if (canCache) {
cacheKey = data[0];
if (cacheKey in exports.cache) {
return exports.cache[cacheKey];
}
}
var hash = (0, crypto_1.createHash)('sha1');
data.forEach(function (item) {
if (typeof item === 'string')
hash.update(item, 'utf8');
else
hash.update(item);
});
var res = hash.digest('hex').toString();
if (canCache) {
exports.cache[cacheKey] = res;
}
return res;
}
exports.sha1 = sha1;

1
node_modules/ts-jest/dist/utils/ts-error.d.ts generated vendored Normal file
View File

@ -0,0 +1 @@
export {};

43
node_modules/ts-jest/dist/utils/ts-error.js generated vendored Normal file
View File

@ -0,0 +1,43 @@
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = function (d, b) {
extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
return extendStatics(d, b);
};
return function (d, b) {
if (typeof b !== "function" && b !== null)
throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
exports.TSError = exports.INSPECT_CUSTOM = void 0;
var util_1 = require("util");
var make_error_1 = require("make-error");
var logger_1 = require("./logger");
var messages_1 = require("./messages");
var logger = logger_1.rootLogger.child({ namespace: 'TSError' });
exports.INSPECT_CUSTOM = util_1.inspect.custom || 'inspect';
var TSError = (function (_super) {
__extends(TSError, _super);
function TSError(diagnosticText, diagnosticCodes) {
var _this = _super.call(this, (0, messages_1.interpolate)("{{diagnostics}}", {
diagnostics: diagnosticText.trim(),
})) || this;
_this.diagnosticText = diagnosticText;
_this.diagnosticCodes = diagnosticCodes;
_this.name = 'TSError';
logger.debug({ diagnosticCodes: diagnosticCodes, diagnosticText: diagnosticText }, 'created new TSError');
Object.defineProperty(_this, 'stack', { value: '' });
return _this;
}
TSError.prototype[exports.INSPECT_CUSTOM] = function () {
return this.diagnosticText;
};
return TSError;
}(make_error_1.BaseError));
exports.TSError = TSError;

View File

@ -0,0 +1 @@
export {};

60
node_modules/ts-jest/dist/utils/version-checkers.js generated vendored Normal file
View File

@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.VersionCheckers = void 0;
var semver_1 = require("semver");
var get_package_version_1 = require("./get-package-version");
var logger_1 = require("./logger");
var messages_1 = require("./messages");
var logger = logger_1.rootLogger.child({ namespace: 'versions' });
exports.VersionCheckers = {
jest: createVersionChecker('jest', ">=28.0.0 <29"),
typescript: createVersionChecker('typescript', ">=4.3 <5"),
babelJest: createVersionChecker('babel-jest', ">=28.0.0 <29"),
babelCore: createVersionChecker('@babel/core', ">=7.0.0-beta.0 <8"),
};
function checkVersion(name, expectedRange, action) {
if (action === void 0) { action = 'warn'; }
var success = true;
if (!('TS_JEST_DISABLE_VER_CHECKER' in process.env)) {
var version = (0, get_package_version_1.getPackageVersion)(name);
success = !!version && (0, semver_1.satisfies)(version, expectedRange);
logger.debug({
actualVersion: version,
expectedVersion: expectedRange,
}, 'checking version of %s: %s', name, success ? 'OK' : 'NOT OK');
if (!action || success)
return success;
var message = (0, messages_1.interpolate)(version ? "Version {{actualVersion}} of {{module}} installed has not been tested with ts-jest. If you're experiencing issues, consider using a supported version ({{expectedVersion}}). Please do not report issues in ts-jest if you are using unsupported versions." : "Module {{module}} is not installed. If you're experiencing issues, consider installing a supported version ({{expectedVersion}}).", {
module: name,
actualVersion: version || '??',
expectedVersion: rangeToHumanString(expectedRange),
});
if (action === 'warn') {
logger.warn(message);
}
else if (action === 'throw') {
logger.fatal(message);
throw new RangeError(message);
}
}
return success;
}
function rangeToHumanString(versionRange) {
return new semver_1.Range(versionRange).toString();
}
function createVersionChecker(moduleName, expectedVersion) {
var memo;
var warn = function () {
if (memo !== undefined)
return memo;
return (memo = checkVersion(moduleName, expectedVersion, 'warn'));
};
var raise = function () { return checkVersion(moduleName, expectedVersion, 'throw'); };
return {
raise: raise,
warn: warn,
forget: function () {
memo = undefined;
},
};
}

18
node_modules/ts-jest/globals.d.ts generated vendored Normal file
View File

@ -0,0 +1,18 @@
declare global {
const beforeAll: typeof import('@jest/globals').beforeAll
const beforeEach: typeof import('@jest/globals').beforeEach
const afterAll: typeof import('@jest/globals').afterAll
const afterEach: typeof import('@jest/globals').afterEach
const describe: typeof import('@jest/globals').describe
const fdescribe: typeof import('@jest/globals').fdescribe
const xdescribe: typeof import('@jest/globals').xdescribe
const it: typeof import('@jest/globals').it
const fit: typeof import('@jest/globals').fit
const xit: typeof import('@jest/globals').xit
const test: typeof import('@jest/globals').test
const xtest: typeof import('@jest/globals').xtest
const expect: typeof import('@jest/globals').expect
const jest: typeof import('@jest/globals').jest
}
export {}

1
node_modules/ts-jest/jest-preset.js generated vendored Normal file
View File

@ -0,0 +1 @@
module.exports = require('./presets').defaults

1
node_modules/ts-jest/legacy.js generated vendored Normal file
View File

@ -0,0 +1 @@
module.exports = require('./dist/legacy')

15
node_modules/ts-jest/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.

568
node_modules/ts-jest/node_modules/semver/README.md generated vendored Normal file
View File

@ -0,0 +1,568 @@
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 simplifyRange = require('semver/ranges/simplify')
const rangeSubset = 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, or prerelease. 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)
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.
## Ranges
A `version range` is a set of `comparators` which 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`.
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. The
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 for 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
clearly 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 the purpose of 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
```
### 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, release)`: Return the version incremented by the release
type (`major`, `premajor`, `minor`, `preminor`, `patch`,
`prepatch`, or `prerelease`), 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, the `prerelease` will work the
same as `prepatch`. It increments the patch version, then makes a
prerelease. If the input version is already a prerelease it simply
increments it.
* `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 exact 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()`.
`v2` is greater. Sorts in ascending order if passed to `Array.sort()`.
* `diff(v1, v2)`: Returns difference between two versions by the release type
(`major`, `premajor`, `minor`, `preminor`, `patch`, `prepatch`, or `prerelease`),
or null if the versions are the same.
### 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 possibly match
the given range.
* `gtr(version, range)`: Return `true` if version is greater than all the
versions possible in the range.
* `ltr(version, range)`: Return `true` if 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 ranges comparators intersect
* `simplifyRange(versions, range)`: Return a "simplified" range that
matches the same items in `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 the 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.
### 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`
## 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/to-comparators')`
* `require('semver/ranges/valid')`

View File

@ -0,0 +1,136 @@
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
}
}
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 (!options || typeof options !== 'object') {
options = {
loose: !!options,
includePrerelease: false,
}
}
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)
}
const sameDirectionIncreasing =
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '>=' || comp.operator === '>')
const sameDirectionDecreasing =
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '<=' || comp.operator === '<')
const sameSemVer = this.semver.version === comp.semver.version
const differentDirectionsInclusive =
(this.operator === '>=' || this.operator === '<=') &&
(comp.operator === '>=' || comp.operator === '<=')
const oppositeDirectionsLessThan =
cmp(this.semver, '<', comp.semver, options) &&
(this.operator === '>=' || this.operator === '>') &&
(comp.operator === '<=' || comp.operator === '<')
const oppositeDirectionsGreaterThan =
cmp(this.semver, '>', comp.semver, options) &&
(this.operator === '<=' || this.operator === '<') &&
(comp.operator === '>=' || comp.operator === '>')
return (
sameDirectionIncreasing ||
sameDirectionDecreasing ||
(sameSemVer && differentDirectionsInclusive) ||
oppositeDirectionsLessThan ||
oppositeDirectionsGreaterThan
)
}
}
module.exports = Comparator
const parseOptions = require('../internal/parse-options')
const { 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,5 @@
module.exports = {
SemVer: require('./semver.js'),
Range: require('./range.js'),
Comparator: require('./comparator.js'),
}

View File

@ -0,0 +1,519 @@
// 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.format()
return this
}
this.options = options
this.loose = !!options.loose
this.includePrerelease = !!options.includePrerelease
// First, split based on boolean or ||
this.raw = range
this.set = range
.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: ${range}`)
}
// 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.format()
}
format () {
this.range = this.set
.map((comps) => {
return comps.join(' ').trim()
})
.join('||')
.trim()
return this.range
}
toString () {
return this.range
}
parseRange (range) {
range = range.trim()
// memoize range parsing for performance.
// this is a very hot path, and fully deterministic.
const memoOpts = Object.keys(this.options).join(',')
const memoKey = `parseRange:${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)
// `^ 1.2.3` => `^1.2.3`
range = range.replace(re[t.CARETTRIM], caretTrimReplace)
// normalize spaces
range = range.split(/\s+/).join(' ')
// 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('lru-cache')
const cache = new LRU({ max: 1000 })
const parseOptions = require('../internal/parse-options')
const Comparator = require('./comparator')
const debug = require('../internal/debug')
const SemVer = require('./semver')
const {
re,
t,
comparatorTrimReplace,
tildeTrimReplace,
caretTrimReplace,
} = require('../internal/re')
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
const replaceTildes = (comp, options) =>
comp.trim().split(/\s+/).map((c) => {
return 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
const replaceCarets = (comp, options) =>
comp.trim().split(/\s+/).map((c) => {
return 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) => {
return 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
const hyphenReplace = incPr => ($0,
from, fM, fm, fp, fpr, fb,
to, tM, tm, tp, tpr, tb) => {
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,287 @@
const debug = require('../internal/debug')
const { MAX_LENGTH, MAX_SAFE_INTEGER } = require('../internal/constants')
const { 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: ${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('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)
}
// 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) {
switch (release) {
case 'premajor':
this.prerelease.length = 0
this.patch = 0
this.minor = 0
this.major++
this.inc('pre', identifier)
break
case 'preminor':
this.prerelease.length = 0
this.patch = 0
this.minor++
this.inc('pre', identifier)
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)
this.inc('pre', identifier)
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)
}
this.inc('pre', identifier)
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':
if (this.prerelease.length === 0) {
this.prerelease = [0]
} 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
this.prerelease.push(0)
}
}
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
if (compareIdentifiers(this.prerelease[0], identifier) === 0) {
if (isNaN(this.prerelease[1])) {
this.prerelease = [identifier, 0]
}
} else {
this.prerelease = [identifier, 0]
}
}
break
default:
throw new Error(`invalid increment argument: ${release}`)
}
this.format()
this.raw = this.version
return this
}
}
module.exports = SemVer

View File

@ -0,0 +1,6 @@
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,52 @@
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,52 @@
const SemVer = require('../classes/semver')
const parse = require('./parse')
const { 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(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'
//
// 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.
let next
while ((next = re[t.COERCERTL].exec(version)) &&
(!match || match.index + match[0].length !== version.length)
) {
if (!match ||
next.index + next[0].length !== match.index + match[0].length) {
match = next
}
re[t.COERCERTL].lastIndex = next.index + next[1].length + next[2].length
}
// leave it in a clean state
re[t.COERCERTL].lastIndex = -1
}
if (match === null) {
return null
}
return parse(`${match[2]}.${match[3] || '0'}.${match[4] || '0'}`, options)
}
module.exports = coerce

View File

@ -0,0 +1,7 @@
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,3 @@
const compare = require('./compare')
const compareLoose = (a, b) => compare(a, b, true)
module.exports = compareLoose

View File

@ -0,0 +1,5 @@
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,23 @@
const parse = require('./parse')
const eq = require('./eq')
const diff = (version1, version2) => {
if (eq(version1, version2)) {
return null
} else {
const v1 = parse(version1)
const v2 = parse(version2)
const hasPre = v1.prerelease.length || v2.prerelease.length
const prefix = hasPre ? 'pre' : ''
const defaultResult = hasPre ? 'prerelease' : ''
for (const key in v1) {
if (key === 'major' || key === 'minor' || key === 'patch') {
if (v1[key] !== v2[key]) {
return prefix + key
}
}
}
return defaultResult // may be undefined
}
}
module.exports = diff

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -0,0 +1,33 @@
const { MAX_LENGTH } = require('../internal/constants')
const { re, t } = require('../internal/re')
const SemVer = require('../classes/semver')
const parseOptions = require('../internal/parse-options')
const parse = (version, options) => {
options = parseOptions(options)
if (version instanceof SemVer) {
return version
}
if (typeof version !== 'string') {
return null
}
if (version.length > MAX_LENGTH) {
return null
}
const r = options.loose ? re[t.LOOSE] : re[t.FULL]
if (!r.test(version)) {
return null
}
try {
return new SemVer(version, options)
} catch (er) {
return null
}
}
module.exports = parse

View File

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

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