🎉 initiate project *astro_rewrite*

This commit is contained in:
sindrekjelsrud 2023-07-19 21:31:30 +02:00
parent ffd4d5e86c
commit 2ba37bfbe3
8658 changed files with 2268794 additions and 2538 deletions

97
node_modules/tsconfig-resolver/CHANGELOG.md generated vendored Normal file
View file

@ -0,0 +1,97 @@
### [3.0.1](https://github.com/ifiokjr/tsconfig-resolver/compare/v3.0.0...v3.0.1) (2020-05-06)
### Bug Fixes
* upgrade dependencies ([6f24a86](https://github.com/ifiokjr/tsconfig-resolver/commit/6f24a8677130a952db67254e81865c00568417ba))
## [3.0.0](https://github.com/ifiokjr/tsconfig-resolver/compare/v2.2.0...v3.0.0) (2020-03-17)
### ⚠ BREAKING CHANGES
* `tsconfigResolver` is now an async function. To
maintain previous behaviour you can use `tsconfigResolverSync`.
* **cache:** `cacheStrategy` option has been renamed to `cache`.
- It now accepts `boolean`'s and `string`s.
### Features
* export both a sync and async resolver ([83c6631](https://github.com/ifiokjr/tsconfig-resolver/commit/83c66319d25c95480dd6d5ce55574dacc871e3de))
* **cache:** accept `boolean` values for `cache` ([24bf910](https://github.com/ifiokjr/tsconfig-resolver/commit/24bf91049e4311faf3882ec29055a8359162a8e5))
## [2.2.0](https://github.com/ifiokjr/tsconfig-resolver/compare/v2.1.1...v2.2.0) (2020-03-15)
### Features
- new option `ignoreExtends` ([9fbd1b4](https://github.com/ifiokjr/tsconfig-resolver/commit/9fbd1b438c8bfe0677af5f79dda7c4d95706f1df))
- new return property `extendedPaths` ([ee0fd1a](https://github.com/ifiokjr/tsconfig-resolver/commit/ee0fd1acf05500c8af8c653c350baec61e3d7c8d))
- new returned property `isCircular` ([85b220a](https://github.com/ifiokjr/tsconfig-resolver/commit/85b220a95eae5b526a804f738ffd71644a55fad6))
### Bug Fixes
- circular `extends` property causing crash ([ae908c2](https://github.com/ifiokjr/tsconfig-resolver/commit/ae908c2aabdce575f0faff913585c61806296aec))
### [2.1.1](https://github.com/ifiokjr/tsconfig-resolver/compare/v2.1.0...v2.1.1) (2020-03-14)
### Bug Fixes
- move `prettier-pulugin-packagejson` to `devDependencies` ([0426a2c](https://github.com/ifiokjr/tsconfig-resolver/commit/0426a2cb71d2358c89796fffee795b905cdc05c4))
## [2.1.0](https://github.com/ifiokjr/tsconfig-resolver/compare/v2.0.1...v2.1.0) (2020-03-14)
### Features
- default to `always` cache when `filePath` used ([3fc605c](https://github.com/ifiokjr/tsconfig-resolver/commit/3fc605c8b40c7973787417e5708966abe0108121))
### [2.0.1](https://github.com/ifiokjr/tsconfig-resolver/compare/v2.0.0...v2.0.1) (2020-03-14)
### Bug Fixes
- update package description ([f09eb23](https://github.com/ifiokjr/tsconfig-resolver/commit/f09eb2338efd02733ac7bde12787423279e93182))
## [2.0.0](https://github.com/ifiokjr/tsconfig-resolver/compare/v1.2.1...v2.0.0) (2020-03-14)
### ⚠ BREAKING CHANGES
- This changes the previously named `fileName` option to
`searchName`.
* Adds a new configuration option `filePath` which is a direct path to
the tsconfig file that should be loaded.
* Export the `DEFAULT_SEARCH_NAME` constant.
### Features
- `filePath` option for direct path to tsconfig ([bcde047](https://github.com/ifiokjr/tsconfig-resolver/commit/bcde0474451917bd73eb111ee3710bac87740fc2))
### [1.2.1](https://github.com/ifiokjr/tsconfig-resolver/compare/v1.2.0...v1.2.1) (2020-03-14)
### Bug Fixes
- Revert "feat(api): `filePath` option sets direct path to tsconfig" ([10332a4](https://github.com/ifiokjr/tsconfig-resolver/commit/10332a47239660a3457fb221a5a072270d42287c))
## [1.2.0](https://github.com/ifiokjr/tsconfig-resolver/compare/v1.1.0...v1.2.0) (2020-03-14)
### Features
- **api:** `filePath` option sets direct path to tsconfig ([bc7b2fe](https://github.com/ifiokjr/tsconfig-resolver/commit/bc7b2fe3bbd12b71d69e8ab9df5f8da5a0864923))
## [1.1.0](https://github.com/ifiokjr/tsconfig-resolver/compare/v1.0.1...v1.1.0) (2020-03-12)
### Features
- re-export `TsConfigJson` ([4dce11a](https://github.com/ifiokjr/tsconfig-resolver/commit/4dce11ac15137ca4e8dfe200217fbe99696ccc7e))
### [1.0.1](https://github.com/ifiokjr/tsconfig-resolver/compare/v1.0.0...v1.0.1) (2020-03-12)
### Bug Fixes
- **package.json:** update the fields for the package.json ([1c5abb1](https://github.com/ifiokjr/tsconfig-resolver/commit/1c5abb196e16a7717393414795d9d446a7b2c96f))
## 1.0.0 (2020-03-12)
### Features
- setup the initial codebase ([f63e13e](https://github.com/ifiokjr/tsconfig-resolver/commit/f63e13e8531de22af5d95e28faa8add18c3b94c8))

21
node_modules/tsconfig-resolver/LICENSE generated vendored Normal file
View file

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

225
node_modules/tsconfig-resolver/README.md generated vendored Normal file
View file

@ -0,0 +1,225 @@
# tsconfig-resolver
<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-1-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->
[![GitHub Actions Build Status](https://github.com/ifiokjr/tsconfig-resolver/workflows/Node%20CI/badge.svg)](https://github.com/ifiokjr/tsconfig-resolver/actions?query=workflow%3A%22Node+CI%22)
[![Version][version]][npm]
[![Weekly Downloads][downloads-badge]][npm]
[![Typed Codebase][typescript]](./src/index.ts)
![MIT License][license]
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
<br />
> A tool for loading the nearest tsconfig file in the same way the TypeScript compiler does. It walks up the directory tree until it finds the first matching `tsconfig.json` file.
<br />
## Table of Contents
- [tsconfig-resolver](#tsconfig-resolver)
- [Table of Contents](#table-of-contents)
- [Usage](#usage)
- [Setup](#setup)
- [Code Example](#code-example)
- [API](#api)
- [`tsconfigResolverSync`](#tsconfigresolversync)
- [Returns](#returns)
- [Options](#options)
- [`tsconfigResolver`](#tsconfigresolver)
- [`clearCache`](#clearcache)
- [`CacheStrategy`](#cachestrategy)
- [`TsConfigErrorReason`](#tsconfigerrorreason)
- [`TsConfigJson`](#tsconfigjson)
- [Contributing](#contributing)
- [Versioning](#versioning)
- [License](#license)
- [Contributors](#contributors)
<br />
## Usage
`tsconfig-resolver` is designed to be used inside your node project. It automatically populates the extends field so that the configuration received is the same as would be used by any consuming TypeScript project.
<br />
### Setup
First, install the plugin and it's peer dependencies:
```bash
npm install --save tsconfig-resolver
```
or
```bash
yarn add tsconfig-resolver
```
<br />
### Code Example
The following will load the first `tsconfig.json` file working upwards from the `process.cwd()` of the running node process.
```ts
import { tsconfigResolver } from 'tsconfig-resolver';
const result = await tsconfigResolver();
// without type narrowing
console.log(result?.config);
// with type narrowing
if (result.exists) {
console.log(result.config);
}
```
Configuration options can also be passed into the export function.
```ts
import { join } from 'path';
import { CacheStrategy, tsconfigResolver } from 'tsconfig-resolver';
const result = tsconfig({
cwd: join(__dirname, 'src'),
fileName: 'tsconfig.prod.json',
cache: CacheStrategy.Directory,
});
```
<br />
## API
### `tsconfigResolverSync`
```ts
import { tsconfigResolverSync } from 'tsconfig-resolver';
```
#### Returns
The function returns an object consisting of the following.
| Property | Type | Description |
| ----------------- | ------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **config** | `TsConfigJson` or `undefined` | The configuration object. <ul><li>`undefined` when the tsconfig resolver failed and no configuration was found.</li><li>`TsConfigJson` (exported by the `type-fest` library) when the resolved tsconfig has been found and loaded.</li></ul> |
| **exists** | `boolean` | Whether or not the configuration could be loaded. <ul><li>`false` when no tsconfig could be found.</li><li>`true` when a valid tsconfig file has been found and successfully loaded.</li></ul> |
| **reason** | `TsConfigErrorReason` or `undefined` | The reason for failure. <ul><li>`TsConfigErrorReason.NotFound` when the config failure is because the filename has not been found.</li><li>`TsConfigErrorReason.InvalidConfig` when the config failure is because of an invalid config.</li><li>`undefined` when no failure has occurred.</li></ul> |
| **path** | `string` or `undefined` | The absolute path to the tsconfig.json or given filename.<ul><li>`undefined` when not found.</li><li>`string` when config json is invalid.</li><li>`string` when a valid tsconfig has been loaded.</li></ul> |
| **extendedPaths** | `string[]` or `undefined` | The extendedPaths array.<ul><li>`undefined` when the tsconfig resolver failed to load a valid configuration.</li><li>`string[]` of absolute paths to resolved tsconfig files when extended paths are encountered.</li><li>`[]` an empty array when no extended paths are encountered.</li><li>`[]` an empty array when ignoreExtends options is set to true.</li></ul> |
| **isCircular** | `boolean` or `undefined` | The `isCircular` config flag.<ul><li>`undefined` when the tsconfig resolver failed to load a valid configuration.</li><li>`true` when a circular `extends` property was encountered (an extends path chain that references itself).</li><li>`false` when no circular `extends` property was encountered.</li></ul> |
#### Options
| Property | Type | Default | Description |
| ----------------- | --------------------- | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **cwd** | `string` | `process.cwd()` | The directory to start searching from. |
| **searchName** | `string` | `'tsconfig.json'` | The tsconfig file name to search for. This is where the `TsConfigJson` configuration object will be loaded from. |
| **filePath** | `string` | `undefined` | A direct path to the tsconfig file you would like to load. The path will be resolved relative to the current `process.cwd()`. If it leads to a directory then the `searchName` will be appended. \* This also supports the `npm:` prefix which will find the given npm package directory, if it is installed. When provided the `cache` is set to `'always'` by default. |
| **cache** | `string` or `boolean` | `'never'` | Set the caching strategy that will be used when searching for a file that's already been found. When a `filePath` is provided the default value becomes `'always'`. |
| **ignoreExtends** | `boolean` | `false` | When true will not automatically populate the `extends` argument. This is useful if all you want is the json object and not the fully resolved configuration. |
### `tsconfigResolver`
```ts
import { tsconfigResolver } from 'tsconfig-resolver';
```
The same API as `tsconfigResolverSync` except the return value is wrapped in a promise.
### `clearCache`
Clears the cache.
```ts
import { clearCache, tsconfigResolver } from 'tsconfig-resolver';
const result = await tsconfigResolver();
// Now clear the cache.
clearCache();
```
### `CacheStrategy`
```ts
import { CacheStrategy } from 'tsconfig-resolver';
```
Provides the available caching strategies that can be used.
Sometimes you'll want to run this module several times during runtime but it can be slow and expensive walk up the file tree for the tsconfig value every time.
To help prevent unnecessary lookups there are custom caching strategies available.
- `CacheStrategy.Never` - Caching never happens and the returned value is always recalculated
- `CacheStrategy.Always` - The first time the `tsconfigResolver` method is run it will save a cached value (by `searchName`) which will be returned every time after that. This value will always be the same. This is turned on by default when a `filePath` is provided.
- `CacheStrategy.Directory` - The cache will be used when the same directory (and `searchName`) is being searched.
### `TsConfigErrorReason`
```ts
import { TsConfigErrorReason } from 'tsconfig-resolver';
```
This provides the reason for the error in resolving the `tsconfig`.
- `TsConfigErrorReason.NotFound` - The `tsconfig` file could not be found.
- `TsConfigErrorReason.InvalidConfig` - The file was found but the configuration was invalid.
### `TsConfigJson`
Re-exported from [`type-fest`](https://github.com/sindresorhus/type-fest).
<br />
## Contributing
Dive into the codebase with Gitpod.
[![Open in Gitpod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/ifiokjr/tsconfig-resolver)
<br />
## Versioning
This project uses [SemVer](http://semver.org/) for versioning. For the versions available, see the
[tags on this repository](https://github.com/ifiokjr/tsconfig-resolver/tags).
<br />
## License
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details
## Contributors
<!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
<!-- prettier-ignore-start -->
<!-- markdownlint-disable -->
<table>
<tr>
<td align="center"><a href="https://ifiokjr.com"><img src="https://avatars2.githubusercontent.com/u/1160934?v=4" width="100px;" alt=""/><br /><sub><b>Ifiok Jr.</b></sub></a><br /><a href="https://github.com/ifiokjr/tsconfig-resolver/commits?author=ifiokjr" title="Code">💻</a></td>
</tr>
</table>
<!-- markdownlint-enable -->
<!-- prettier-ignore-end -->
<!-- ALL-CONTRIBUTORS-LIST:END -->
[version]: https://flat.badgen.net/npm/v/tsconfig-resolver
[npm]: https://npmjs.com/package/tsconfig-resolver
[license]: https://flat.badgen.net/badge/license/MIT/purple
[size]: https://bundlephobia.com/result?p=#tsconfig-resolver
[size-badge]: https://flat.badgen.net/bundlephobia/minzip/tsconfig-resolver
[typescript]: https://flat.badgen.net/badge/icon/TypeScript/?icon=typescript&label&labelColor=blue&color=555555
[downloads-badge]: https://badgen.net/npm/dw/tsconfig-resolver/red?icon=npm

218
node_modules/tsconfig-resolver/dist/index.d.ts generated vendored Normal file
View file

@ -0,0 +1,218 @@
import { TsConfigJson } from 'type-fest';
/** The default search name used. */
export declare const DEFAULT_SEARCH_NAME = "tsconfig.json";
/**
* The reason that the tsconfig exist flag is false.
*/
export declare const TsConfigErrorReason: {
/**
* The `tsconfig` file could not be found.
*/
readonly NotFound: "not-found";
/**
* The file was found but the configuration was invalid.
*/
readonly InvalidConfig: "invalid-config";
};
interface TsConfigFailure {
/**
* Whether or not the configuration could be loaded.
*
* - `false` when no tsconfig could be found.
*/
exists: false;
/**
* The configuration object.
*
* - `undefined` when the tsconfig resolver failed and no configuration was
* found.
*/
config?: undefined;
/**
* The extendedPaths array.
*
* - `undefined` when the tsconfig resolver failed to load a valid
* configuration.
*/
extendedPaths?: undefined;
/**
* The `isCircular` config flag.
*
* - `undefined` when the tsconfig resolver failed to load a valid
* configuration.
*/
isCircular?: undefined;
}
export interface TsConfigFailureNotFound extends TsConfigFailure {
/**
* The reason for failure.
*
* - `TsConfigErrorReason.NotFound` when the config failure is because the
* filename has not been found.
*/
reason: typeof TsConfigErrorReason.NotFound;
/**
* The absolute path to the `tsconfig.json` or given filename.
*
* - `undefined` when not found.
*/
path?: undefined;
}
export interface TsConfigFailureInvalidConfig extends TsConfigFailure {
/**
* - `TsConfigErrorReason.InvalidConfig` when the config failure is because of
* an invalid config.
*/
reason: typeof TsConfigErrorReason.InvalidConfig;
/**
* - `string` when config json is invalid.
*/
path: string;
}
export interface TsConfigResultSuccess {
/**
* - `true` when a valid tsconfig file has been found and successfully loaded.
*/
exists: true;
/**
* - `string` when a valid tsconfig has been loaded.
*/
path: string;
/**
* - `string[]` of absolute paths to resolved tsconfig files when extended
* paths are encountered.
* - `[]` an empty array when no extended paths were encountered.
* - `[]` an empty array when `ignoreExtends` options is set to true.
*/
extendedPaths: string[];
/**
* - `true` when a circular `extends` property was encountered (an extends
* path chain that references itself).
* - `false` when no circular `extends` property was encountered.
*/
isCircular: boolean;
/**
* - `TsConfigJson` when the resolved tsconfig has been found and loaded.
*/
config: TsConfigJson;
/**
* - `undefined` when no failure has occurred.
*/
reason?: undefined;
}
/**
* The result of loading the tsconfig. If the exists property is `true` then
* there will be a path and config property available.
*/
export declare type TsConfigResult = TsConfigFailureNotFound | TsConfigFailureInvalidConfig | TsConfigResultSuccess;
export interface TsConfigLoaderParams {
getEnv: (key: string) => string | undefined;
cwd: string;
loadSync?(cwd: string, searchName?: string): TsConfigResult;
}
export interface TsConfigResolverOptions {
/**
* The absolute directory to start resolving from.
*
* @default `process.cwd()`
*/
cwd?: string;
/**
* The tsconfig file name to search for. This is where the `TsConfigJson`
* configuration object will be loaded from.
*
* @default 'tsconfig.json'
*/
searchName?: string;
/**
* A direct path to the tsconfig file you would like to load. The path will be
* relative to `cwd`. If it leads to a directory then the `searchName` will be
* appended.
*
* This also supports the `npm:` prefix which will find the given npm package
* directory, if it is installed.
*
* @default undefined
*/
filePath?: string | undefined;
/**
* The caching strategy to use. `'never'` or `'always'` or `'directory'` or
* `true` or `false`.
*
* `true` is the same as `'always'`
* `false` is the same as `'never'`
*
* @default 'never'
*
* @remarks
*
* Sometimes you'll want to run this module several times during runtime but
* it can be slow and expensive walk up the file tree for the tsconfig value
* every time.
*
* To help prevent unnecessary lookups there are custom caching strategies
* available. See {@link CacheStrategy}.
*/
cache?: CacheStrategyType | boolean;
/**
* When true will not automatically populate the `extends` argument. This is
* useful if all you want is the json object and not the fully resolved
* configuration.
*
* @default false
*/
ignoreExtends?: boolean;
}
export declare const CacheStrategy: {
/**
* Caching never happens and the returned value is always recalculated.
*/
readonly Never: "never";
/**
* The first time the `tsconfigResolver` method is run it will save a cached
* value (by `searchName`) which will be returned every time after that. This
* value will always be the same.
*/
readonly Always: "always";
/**
* The cache will be used when the same directory (and searchName) is being
* searched.
*/
readonly Directory: "directory";
};
/**
* The available cache strategies as a union of strings.
*/
export declare type CacheStrategyType = typeof CacheStrategy[keyof typeof CacheStrategy];
/**
* Clears the cache.
*/
export declare const clearCache: () => void;
export { TsConfigJson };
/**
* Resolve the `tsconfig` file synchronously. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @returns an object containing whether a configuration was found and is valid.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
export declare function tsconfigResolverSync({ filePath, cwd, cache: shouldCache, searchName, ignoreExtends, }?: TsConfigResolverOptions): TsConfigResult;
/**
* Resolve the `tsconfig` file. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
export declare function tsconfigResolver({ filePath, cwd, cache: shouldCache, searchName, ignoreExtends, }?: TsConfigResolverOptions): Promise<TsConfigResult>;
//# sourceMappingURL=index.d.ts.map

1
node_modules/tsconfig-resolver/dist/index.d.ts.map generated vendored Normal file
View file

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAaA,OAAO,EAAuB,YAAY,EAAE,MAAM,WAAW,CAAC;AAI9D,oCAAoC;AACpC,eAAO,MAAM,mBAAmB,kBAAkB,CAAC;AA0CnD;;GAEG;AACH,eAAO,MAAM,mBAAmB;IAC9B;;OAEG;;IAGH;;OAEG;;CAEK,CAAC;AAEX,UAAU,eAAe;IACvB;;;;OAIG;IACH,MAAM,EAAE,KAAK,CAAC;IAEd;;;;;OAKG;IACH,MAAM,CAAC,EAAE,SAAS,CAAC;IAEnB;;;;;OAKG;IACH,aAAa,CAAC,EAAE,SAAS,CAAC;IAE1B;;;;;OAKG;IACH,UAAU,CAAC,EAAE,SAAS,CAAC;CACxB;AAED,MAAM,WAAW,uBAAwB,SAAQ,eAAe;IAC9D;;;;;OAKG;IACH,MAAM,EAAE,OAAO,mBAAmB,CAAC,QAAQ,CAAC;IAE5C;;;;OAIG;IACH,IAAI,CAAC,EAAE,SAAS,CAAC;CAClB;AAED,MAAM,WAAW,4BAA6B,SAAQ,eAAe;IACnE;;;OAGG;IACH,MAAM,EAAE,OAAO,mBAAmB,CAAC,aAAa,CAAC;IAEjD;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;CACd;AAED,MAAM,WAAW,qBAAqB;IACpC;;OAEG;IACH,MAAM,EAAE,IAAI,CAAC;IAEb;;OAEG;IACH,IAAI,EAAE,MAAM,CAAC;IAEb;;;;;OAKG;IACH,aAAa,EAAE,MAAM,EAAE,CAAC;IAExB;;;;OAIG;IACH,UAAU,EAAE,OAAO,CAAC;IAEpB;;OAEG;IACH,MAAM,EAAE,YAAY,CAAC;IAErB;;OAEG;IACH,MAAM,CAAC,EAAE,SAAS,CAAC;CACpB;AAED;;;GAGG;AACH,oBAAY,cAAc,GACtB,uBAAuB,GACvB,4BAA4B,GAC5B,qBAAqB,CAAC;AAE1B,MAAM,WAAW,oBAAoB;IACnC,MAAM,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,MAAM,GAAG,SAAS,CAAC;IAC5C,GAAG,EAAE,MAAM,CAAC;IACZ,QAAQ,CAAC,CAAC,GAAG,EAAE,MAAM,EAAE,UAAU,CAAC,EAAE,MAAM,GAAG,cAAc,CAAC;CAC7D;AAqaD,MAAM,WAAW,uBAAuB;IACtC;;;;OAIG;IACH,GAAG,CAAC,EAAE,MAAM,CAAC;IAEb;;;;;OAKG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;IAEpB;;;;;;;;;OASG;IACH,QAAQ,CAAC,EAAE,MAAM,GAAG,SAAS,CAAC;IAE9B;;;;;;;;;;;;;;;;;OAiBG;IACH,KAAK,CAAC,EAAE,iBAAiB,GAAG,OAAO,CAAC;IAEpC;;;;;;OAMG;IACH,aAAa,CAAC,EAAE,OAAO,CAAC;CACzB;AAOD,eAAO,MAAM,aAAa;IACxB;;OAEG;;IAGH;;;;OAIG;;IAGH;;;OAGG;;CAEK,CAAC;AAEX;;GAEG;AACH,oBAAY,iBAAiB,GAAG,OAAO,aAAa,CAAC,MAAM,OAAO,aAAa,CAAC,CAAC;AA8DjF;;GAEG;AACH,eAAO,MAAM,UAAU,YAItB,CAAC;AAkFF,OAAO,EAAE,YAAY,EAAE,CAAC;AAExB;;;;;;;;;;;;GAYG;AACH,wBAAgB,oBAAoB,CAAC,EACnC,QAAQ,EACR,GAAmB,EACnB,KAAK,EAAE,WAAmE,EAC1E,UAAgC,EAChC,aAAqB,GACtB,GAAE,uBAA4B,GAAG,cAAc,CA2B/C;AAED;;;;;;;;;;GAUG;AACH,wBAAsB,gBAAgB,CAAC,EACrC,QAAQ,EACR,GAAmB,EACnB,KAAK,EAAE,WAAmE,EAC1E,UAAgC,EAChC,aAAqB,GACtB,GAAE,uBAA4B,GAAG,OAAO,CAAC,cAAc,CAAC,CA2BxD"}

8
node_modules/tsconfig-resolver/dist/index.js generated vendored Normal file
View file

@ -0,0 +1,8 @@
'use strict'
if (process.env.NODE_ENV === 'production') {
module.exports = require('./tsconfig-resolver.cjs.production.min.js')
} else {
module.exports = require('./tsconfig-resolver.cjs.development.js')
}

View file

@ -0,0 +1,880 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var fs = require('fs');
var path = require('path');
var JSON5 = _interopDefault(require('json5'));
var resolvePackageNpm = _interopDefault(require('resolve'));
var StripBom = _interopDefault(require('strip-bom'));
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// A type of promise-like that resolves synchronously and supports only one observer
const _iteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator"))) : "@@iterator";
const _asyncIteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.asyncIterator || (Symbol.asyncIterator = Symbol("Symbol.asyncIterator"))) : "@@asyncIterator";
// Asynchronously call a function and send errors to recovery continuation
function _catch(body, recover) {
try {
var result = body();
} catch(e) {
return recover(e);
}
if (result && result.then) {
return result.then(void 0, recover);
}
return result;
}
var _cacheObject;
/**
* Resolve the `tsconfig` file. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
var tsconfigResolver = function tsconfigResolver(_temp17) {
var _ref6 = _temp17 === void 0 ? {} : _temp17,
filePath = _ref6.filePath,
_ref6$cwd = _ref6.cwd,
cwd = _ref6$cwd === void 0 ? process.cwd() : _ref6$cwd,
_ref6$cache = _ref6.cache,
shouldCache = _ref6$cache === void 0 ? filePath ? CacheStrategy.Always : CacheStrategy.Never : _ref6$cache,
_ref6$searchName = _ref6.searchName,
searchName = _ref6$searchName === void 0 ? DEFAULT_SEARCH_NAME : _ref6$searchName,
_ref6$ignoreExtends = _ref6.ignoreExtends,
ignoreExtends = _ref6$ignoreExtends === void 0 ? false : _ref6$ignoreExtends;
try {
var cacheStrategy = convertCacheToStrategy(shouldCache);
var cache = getCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
});
if (cache) {
return Promise.resolve(cache);
}
return Promise.resolve(getTsConfigResult({
cwd: cwd,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
})).then(function (result) {
updateCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
}, result);
return result;
});
} catch (e) {
return Promise.reject(e);
}
};
var readFile = fs.promises.readFile,
stat = fs.promises.stat;
/** The default search name used. */
var DEFAULT_SEARCH_NAME = 'tsconfig.json';
/**
* Extends the default node file parser and determines whether the path provided
* should be resolved from the node modules or directly from the provided path.
*/
var parseFilePath = function parseFilePath(file, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
windows = _ref.windows;
var isWindows = windows !== null && windows !== void 0 ? windows : process.platform === 'win32';
var parser = isWindows ? path.win32.parse : path.parse;
var parsedPath = parser(file);
return _extends({}, parsedPath, {
isAbsolute: Boolean(parsedPath.root),
isPackage: !file.startsWith('.') && !parsedPath.root
});
};
/**
* The reason that the tsconfig exist flag is false.
*/
var TsConfigErrorReason = {
/**
* The `tsconfig` file could not be found.
*/
NotFound: 'not-found',
/**
* The file was found but the configuration was invalid.
*/
InvalidConfig: 'invalid-config'
};
/**
* Synchronously walk up the path until a `tsconfig` is located.
*/
var walkForTsConfigSync = function walkForTsConfigSync(directory) {
var configPath = path.join(directory, './tsconfig.json');
if (isFileOrDirectorySync(configPath)) {
return configPath;
}
var parentDirectory = path.join(directory, '../'); // If we reached the top
if (directory === parentDirectory) {
return undefined;
}
return walkForTsConfigSync(parentDirectory);
};
/**
* Walk up the path until a `tsconfig` is located.
*/
var walkForTsConfig = function walkForTsConfig(directory) {
try {
var _exit2 = false;
var configPath = path.join(directory, './tsconfig.json');
return Promise.resolve(isFileOrDirectory(configPath)).then(function (_isFileOrDirectory) {
if (_isFileOrDirectory) {
_exit2 = true;
return configPath;
}
// Step up one level in the directory path.
var parentDirectory = path.join(directory, '../'); // If we reached the top
return directory === parentDirectory ? undefined : walkForTsConfig(parentDirectory);
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Synchronously check that the passed string is a directory.
*/
var isDirectorySync = function isDirectorySync(directory) {
try {
return fs.statSync(directory).isDirectory();
} catch (_unused) {
return false;
}
};
/**
* Check that the passed string is a directory.
*/
var isDirectory = function isDirectory(directory) {
return Promise.resolve(_catch(function () {
return Promise.resolve(stat(directory)).then(function (stats) {
return stats.isDirectory();
});
}, function () {
return false;
}));
};
/**
* Synchronously check that the passed filePath is a valid file.
*/
var isFileSync = function isFileSync(filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (_unused2) {
return false;
}
};
/**
* Check that the passed filePath is a valid file.
*/
var isFile = function isFile(filePath) {
return Promise.resolve(_catch(function () {
return Promise.resolve(stat(filePath)).then(function (stats) {
return stats.isFile();
});
}, function () {
return false;
}));
};
/**
* Synchronously check that the provided `filePath` is a file or directory.
*/
var isFileOrDirectorySync = function isFileOrDirectorySync(filePath) {
return isFileSync(filePath) || isDirectorySync(filePath);
};
/**
* Check that the provided `filePath` is a file or directory.
*/
var isFileOrDirectory = function isFileOrDirectory(filePath) {
try {
var _exit5 = false;
return Promise.resolve(isFile(filePath)).then(function (_isFile) {
var _exit4 = false;
if (_isFile) {
_exit5 = true;
return true;
}
return Promise.resolve(isDirectory(filePath)).then(function (_isDirectory) {
if (_isDirectory) {
_exit4 = true;
return true;
}
return false;
});
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Synchronously resolves an npm package by the given name.
*/
var resolvePackageSync = function resolvePackageSync(name, basedir) {
try {
return resolvePackageNpm.sync(name, {
basedir: basedir,
extensions: ['.json', '.js']
});
} catch (_unused3) {
return;
}
};
/**
* Resolves an npm package by the given name.
*/
var resolvePackage = function resolvePackage(name, basedir) {
return new Promise(function (resolve, reject) {
resolvePackageNpm(name, {
basedir: basedir,
extensions: ['.json', '.js']
}, function (error, resolved) {
if (error) {
reject(error);
} else {
resolve(resolved);
}
});
});
};
/**
* Synchronously checks a filePath exists and if it can be resolved.
*/
var resolveFilePathSync = function resolveFilePathSync(searchName, filePath) {
var cwd = process.cwd();
if (!filePath) {
return;
}
var resolvedPath;
if (filePath.startsWith('npm:')) {
resolvedPath = resolvePackageSync(filePath.replace('npm:', ''), cwd);
} else {
resolvedPath = path.resolve(cwd, filePath);
}
if (!resolvedPath || !isDirectorySync(resolvedPath)) {
return resolvedPath;
}
return path.resolve(resolvedPath, searchName);
};
/**
* When a filePath exists check if it can be resolved.
*/
var resolveFilePath = function resolveFilePath(searchName, filePath) {
try {
var _temp6 = function _temp6() {
var _exit6 = false;
function _temp3(_isDirectory2) {
if (_temp2 || !_isDirectory2) {
_exit6 = true;
return resolvedPath;
}
return path.resolve(resolvedPath, searchName);
}
var _temp2 = !resolvedPath;
return _temp2 ? _temp3(_temp2) : Promise.resolve(isDirectory(resolvedPath)).then(_temp3);
};
var cwd = process.cwd();
if (!filePath) {
return Promise.resolve();
}
var resolvedPath;
var _temp7 = function () {
if (filePath.startsWith('npm:')) {
return Promise.resolve(resolvePackage(filePath.replace('npm:', ''), cwd)).then(function (_resolvePackage) {
resolvedPath = _resolvePackage;
});
} else {
resolvedPath = path.resolve(cwd, filePath);
}
}();
return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(_temp6) : _temp6(_temp7));
} catch (e) {
return Promise.reject(e);
}
};
/**
* Get the desired path to the configuration.
*/
var resolveConfigPathSync = function resolveConfigPathSync(cwd, searchName, filePath) {
var resolvedFilePath = resolveFilePathSync(searchName, filePath);
if (resolvedFilePath) {
return resolvedFilePath;
}
if (searchName !== DEFAULT_SEARCH_NAME) {
var resolvedSearchName = path.resolve(cwd, searchName);
var absolutePath = isDirectorySync(resolvedSearchName) ? path.resolve(resolvedSearchName, 'tsconfig.json') : resolvedSearchName;
return isFileSync(absolutePath) ? absolutePath : undefined;
}
if (isFileSync(cwd)) {
return path.resolve(cwd);
}
var configAbsolutePath = walkForTsConfigSync(cwd);
return configAbsolutePath ? path.resolve(configAbsolutePath) : undefined;
};
/**
* Get the desired path to the configuration.
*/
var resolveConfigPath = function resolveConfigPath(cwd, searchName, filePath) {
try {
return Promise.resolve(resolveFilePath(searchName, filePath)).then(function (resolvedFilePath) {
var _exit7 = false;
function _temp9(_result) {
var _exit8 = false;
if (_exit7) return _result;
return Promise.resolve(isFile(cwd)).then(function (_isFile3) {
if (_isFile3) {
_exit8 = true;
return path.resolve(cwd);
}
return Promise.resolve(walkForTsConfig(cwd)).then(function (configAbsolutePath) {
return configAbsolutePath ? path.resolve(configAbsolutePath) : undefined;
});
});
}
if (resolvedFilePath) {
return resolvedFilePath;
}
var _temp8 = function () {
if (searchName !== DEFAULT_SEARCH_NAME) {
var resolvedSearchName = path.resolve(cwd, searchName);
return Promise.resolve(isDirectory(resolvedSearchName)).then(function (_isDirectory3) {
var absolutePath = _isDirectory3 ? path.resolve(resolvedSearchName, 'tsconfig.json') : resolvedSearchName;
_exit7 = true;
return Promise.resolve(isFile(absolutePath)).then(function (_isFile2) {
return _isFile2 ? absolutePath : undefined;
});
});
}
}();
return _temp8 && _temp8.then ? _temp8.then(_temp9) : _temp9(_temp8);
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Loads the `jsonString` and returns it as a TsConfigJson object.
*/
var parseTsConfigJson = function parseTsConfigJson(jsonString) {
try {
var json = JSON5.parse(jsonString);
return json && typeof json === 'object' ? json : undefined;
} catch (_unused4) {
return undefined;
}
};
/**
* Synchronously loads a tsconfig file while also resolving the `extends` path.
*/
var loadTsConfigSync = function loadTsConfigSync(configFilePath, extendedPaths, ignoreExtends) {
var _base, _base$compilerOptions;
if (ignoreExtends === void 0) {
ignoreExtends = false;
}
if (!isFileOrDirectorySync(configFilePath)) return undefined;
var configString = fs.readFileSync(configFilePath, 'utf8');
var jsonString = StripBom(configString);
var config = parseTsConfigJson(jsonString);
var extendedConfig = config === null || config === void 0 ? void 0 : config["extends"];
if (!config || !extendedConfig || ignoreExtends) return config;
var base;
if (parseFilePath(extendedConfig).isPackage) {
var _loadTsConfigSync;
var newConfigPath = resolvePackageSync(extendedConfig);
if (!newConfigPath) {
return config;
} else if (isDirectorySync(newConfigPath)) {
extendedConfig = path.join(newConfigPath, DEFAULT_SEARCH_NAME);
} else if (isFileSync(newConfigPath)) {
extendedConfig = newConfigPath;
} else if (isFileSync(newConfigPath + ".json")) {
extendedConfig = newConfigPath + ".json";
}
if (extendedPaths.includes(extendedConfig)) {
return config;
}
extendedPaths.push(extendedConfig);
base = (_loadTsConfigSync = loadTsConfigSync(extendedConfig, extendedPaths)) !== null && _loadTsConfigSync !== void 0 ? _loadTsConfigSync : {};
} else {
var _loadTsConfigSync2;
if (!extendedConfig.endsWith('.json')) {
extendedConfig += '.json';
}
var currentDir = path.dirname(configFilePath);
var extendedConfigPath = path.join(currentDir, extendedConfig);
if (extendedPaths.includes(extendedConfigPath)) {
return config;
}
extendedPaths.push(extendedConfigPath);
base = (_loadTsConfigSync2 = loadTsConfigSync(extendedConfigPath, extendedPaths)) !== null && _loadTsConfigSync2 !== void 0 ? _loadTsConfigSync2 : {};
} // baseUrl should be interpreted as relative to the base tsconfig, but we need
// to update it so it is relative to the original tsconfig being loaded
if ((_base = base) === null || _base === void 0 ? void 0 : (_base$compilerOptions = _base.compilerOptions) === null || _base$compilerOptions === void 0 ? void 0 : _base$compilerOptions.baseUrl) {
var extendsDir = path.dirname(extendedConfig);
base.compilerOptions.baseUrl = path.join(extendsDir, base.compilerOptions.baseUrl);
}
return _extends({}, base, {}, config, {
compilerOptions: _extends({}, base.compilerOptions, {}, config.compilerOptions)
});
};
/**
* Loads a tsconfig file while also resolving the `extends` path.
*/
var loadTsConfig = function loadTsConfig(configFilePath, extendedPaths, ignoreExtends) {
if (ignoreExtends === void 0) {
ignoreExtends = false;
}
try {
var _exit12 = false;
return Promise.resolve(isFileOrDirectory(configFilePath)).then(function (_isFileOrDirectory2) {
if (!_isFileOrDirectory2) {
_exit12 = true;
return undefined;
}
return Promise.resolve(readFile(configFilePath, 'utf8')).then(function (configString) {
var _exit10 = false;
function _temp15(_result2) {
var _base2, _base2$compilerOption;
if (_exit10) return _result2;
// baseUrl should be interpreted as relative to the base tsconfig, but we need
// to update it so it is relative to the original tsconfig being loaded
if ((_base2 = base) === null || _base2 === void 0 ? void 0 : (_base2$compilerOption = _base2.compilerOptions) === null || _base2$compilerOption === void 0 ? void 0 : _base2$compilerOption.baseUrl) {
var extendsDir = path.dirname(extendedConfig);
base.compilerOptions.baseUrl = path.join(extendsDir, base.compilerOptions.baseUrl);
}
return _extends({}, base, {}, config, {
compilerOptions: _extends({}, base.compilerOptions, {}, config.compilerOptions)
});
}
var jsonString = StripBom(configString);
var config = parseTsConfigJson(jsonString);
var extendedConfig = config === null || config === void 0 ? void 0 : config["extends"];
if (!config || !extendedConfig || ignoreExtends) return config;
var base;
var _temp14 = function () {
if (parseFilePath(extendedConfig).isPackage) {
return Promise.resolve(resolvePackage(extendedConfig)).then(function (newConfigPath) {
var _exit11 = false;
function _temp13(_result3) {
if (_exit11) return _result3;
if (extendedPaths.includes(extendedConfig)) {
_exit10 = true;
return config;
}
extendedPaths.push(extendedConfig);
return Promise.resolve(loadTsConfig(extendedConfig, extendedPaths)).then(function (_loadTsConfig) {
base = _loadTsConfig !== null && _loadTsConfig !== void 0 ? _loadTsConfig : {};
});
}
var _temp12 = function () {
if (!newConfigPath) {
_exit10 = true;
return config;
} else return Promise.resolve(isDirectory(newConfigPath)).then(function (_isDirectory4) {
var _temp11 = function () {
if (_isDirectory4) {
extendedConfig = path.join(newConfigPath, DEFAULT_SEARCH_NAME);
} else return Promise.resolve(isFile(newConfigPath)).then(function (_isFile4) {
var _temp10 = function () {
if (_isFile4) {
extendedConfig = newConfigPath;
} else return Promise.resolve(isFile(newConfigPath + ".json")).then(function (_isFile5) {
if (_isFile5) {
extendedConfig = newConfigPath + ".json";
}
});
}();
if (_temp10 && _temp10.then) return _temp10.then(function () {});
});
}();
if (_temp11 && _temp11.then) return _temp11.then(function () {});
});
}();
return _temp12 && _temp12.then ? _temp12.then(_temp13) : _temp13(_temp12);
});
} else {
if (!extendedConfig.endsWith('.json')) {
extendedConfig += '.json';
}
var currentDir = path.dirname(configFilePath);
var extendedConfigPath = path.join(currentDir, extendedConfig);
if (extendedPaths.includes(extendedConfigPath)) {
_exit10 = true;
return config;
}
extendedPaths.push(extendedConfigPath);
return Promise.resolve(loadTsConfig(extendedConfigPath, extendedPaths)).then(function (_loadTsConfig2) {
base = _loadTsConfig2 !== null && _loadTsConfig2 !== void 0 ? _loadTsConfig2 : {};
});
}
}();
return _temp14 && _temp14.then ? _temp14.then(_temp15) : _temp15(_temp14);
});
});
} catch (e) {
return Promise.reject(e);
}
};
var CacheStrategy = {
/**
* Caching never happens and the returned value is always recalculated.
*/
Never: 'never',
/**
* The first time the `tsconfigResolver` method is run it will save a cached
* value (by `searchName`) which will be returned every time after that. This
* value will always be the same.
*/
Always: 'always',
/**
* The cache will be used when the same directory (and searchName) is being
* searched.
*/
Directory: 'directory'
};
var cacheObject = (_cacheObject = {}, _cacheObject[CacheStrategy.Always] = /*#__PURE__*/new Map(), _cacheObject[CacheStrategy.Directory] = /*#__PURE__*/new Map(), _cacheObject);
/**
* Converts a boolean or string type into a cache strategy.
*/
var convertCacheToStrategy = function convertCacheToStrategy(value) {
return value === false ? CacheStrategy.Never : value === true ? CacheStrategy.Always : value;
};
/**
* Get the key to store in the cache.
*/
var cacheKey = function cacheKey(_ref2) {
var cache = _ref2.cache,
cwd = _ref2.cwd,
searchName = _ref2.searchName,
ignoreExtends = _ref2.ignoreExtends;
return cache === CacheStrategy.Always ? searchName + " - " + ignoreExtends : path.join(cwd, searchName) + " - " + ignoreExtends;
};
/**
* Based on the options passed in, retrieve the value from the cache or return
* undefined if the value still needs to be calculated.
*/
var getCache = function getCache(options) {
if (options.cache === CacheStrategy.Always) {
return cacheObject[CacheStrategy.Always].get(cacheKey(options));
}
if (options.cache === CacheStrategy.Directory) {
return cacheObject[CacheStrategy.Always].get(cacheKey(options));
}
return undefined;
};
/**
* Updates the cache with the provided result.
*/
var updateCache = function updateCache(options, result) {
if (options.cache === CacheStrategy.Always) {
cacheObject[CacheStrategy.Always].set(cacheKey(options), result);
} else if (options.cache === CacheStrategy.Directory) {
cacheObject[CacheStrategy.Always].set(cacheKey(options), result);
}
};
/**
* Clears the cache.
*/
var clearCache = function clearCache() {
for (var _i = 0, _Object$values = Object.values(cacheObject); _i < _Object$values.length; _i++) {
var map = _Object$values[_i];
map.clear();
}
};
/**
* Synchronously get the nearest tsconfig by walking up the directory.
*/
var getTsConfigResultSync = function getTsConfigResultSync(_ref3) {
var cwd = _ref3.cwd,
searchName = _ref3.searchName,
filePath = _ref3.filePath,
ignoreExtends = _ref3.ignoreExtends;
var configPath = resolveConfigPathSync(cwd, searchName, filePath);
if (!configPath) {
return {
exists: false,
reason: TsConfigErrorReason.NotFound
};
} // This path will be mutated to include all paths that have been found.
var extendedPaths = [];
var config = loadTsConfigSync(configPath, extendedPaths, ignoreExtends);
if (!config) {
return {
exists: false,
reason: TsConfigErrorReason.InvalidConfig,
path: configPath
};
}
return {
exists: true,
path: configPath,
extendedPaths: extendedPaths,
config: config,
isCircular: extendedPaths.includes(configPath)
};
};
/**
* Get the nearest tsconfig by walking up the directory.
*/
var getTsConfigResult = function getTsConfigResult(_ref4) {
var cwd = _ref4.cwd,
searchName = _ref4.searchName,
filePath = _ref4.filePath,
ignoreExtends = _ref4.ignoreExtends;
try {
return Promise.resolve(resolveConfigPath(cwd, searchName, filePath)).then(function (configPath) {
if (!configPath) {
return {
exists: false,
reason: TsConfigErrorReason.NotFound
};
} // This path will be mutated to include all paths that have been found.
var extendedPaths = [];
return Promise.resolve(loadTsConfig(configPath, extendedPaths, ignoreExtends)).then(function (config) {
return config ? {
exists: true,
path: configPath,
extendedPaths: extendedPaths,
config: config,
isCircular: extendedPaths.includes(configPath)
} : {
exists: false,
reason: TsConfigErrorReason.InvalidConfig,
path: configPath
};
});
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Resolve the `tsconfig` file synchronously. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @returns an object containing whether a configuration was found and is valid.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
function tsconfigResolverSync(_temp16) {
var _ref5 = _temp16 === void 0 ? {} : _temp16,
filePath = _ref5.filePath,
_ref5$cwd = _ref5.cwd,
cwd = _ref5$cwd === void 0 ? process.cwd() : _ref5$cwd,
_ref5$cache = _ref5.cache,
shouldCache = _ref5$cache === void 0 ? filePath ? CacheStrategy.Always : CacheStrategy.Never : _ref5$cache,
_ref5$searchName = _ref5.searchName,
searchName = _ref5$searchName === void 0 ? DEFAULT_SEARCH_NAME : _ref5$searchName,
_ref5$ignoreExtends = _ref5.ignoreExtends,
ignoreExtends = _ref5$ignoreExtends === void 0 ? false : _ref5$ignoreExtends;
var cacheStrategy = convertCacheToStrategy(shouldCache);
var cache = getCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
});
if (cache) {
return cache;
}
var result = getTsConfigResultSync({
cwd: cwd,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
});
updateCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
}, result);
return result;
}
exports.CacheStrategy = CacheStrategy;
exports.DEFAULT_SEARCH_NAME = DEFAULT_SEARCH_NAME;
exports.TsConfigErrorReason = TsConfigErrorReason;
exports.clearCache = clearCache;
exports.tsconfigResolver = tsconfigResolver;
exports.tsconfigResolverSync = tsconfigResolverSync;
//# sourceMappingURL=tsconfig-resolver.cjs.development.js.map

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,869 @@
import { promises, readFileSync, statSync } from 'fs';
import { join, resolve, dirname, win32, parse } from 'path';
import JSON5 from 'json5';
import resolvePackageNpm from 'resolve';
import StripBom from 'strip-bom';
function _extends() {
_extends = Object.assign || function (target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i];
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
}
return target;
};
return _extends.apply(this, arguments);
}
// A type of promise-like that resolves synchronously and supports only one observer
const _iteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.iterator || (Symbol.iterator = Symbol("Symbol.iterator"))) : "@@iterator";
const _asyncIteratorSymbol = /*#__PURE__*/ typeof Symbol !== "undefined" ? (Symbol.asyncIterator || (Symbol.asyncIterator = Symbol("Symbol.asyncIterator"))) : "@@asyncIterator";
// Asynchronously call a function and send errors to recovery continuation
function _catch(body, recover) {
try {
var result = body();
} catch(e) {
return recover(e);
}
if (result && result.then) {
return result.then(void 0, recover);
}
return result;
}
var _cacheObject;
/**
* Resolve the `tsconfig` file. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
var tsconfigResolver = function tsconfigResolver(_temp17) {
var _ref6 = _temp17 === void 0 ? {} : _temp17,
filePath = _ref6.filePath,
_ref6$cwd = _ref6.cwd,
cwd = _ref6$cwd === void 0 ? process.cwd() : _ref6$cwd,
_ref6$cache = _ref6.cache,
shouldCache = _ref6$cache === void 0 ? filePath ? CacheStrategy.Always : CacheStrategy.Never : _ref6$cache,
_ref6$searchName = _ref6.searchName,
searchName = _ref6$searchName === void 0 ? DEFAULT_SEARCH_NAME : _ref6$searchName,
_ref6$ignoreExtends = _ref6.ignoreExtends,
ignoreExtends = _ref6$ignoreExtends === void 0 ? false : _ref6$ignoreExtends;
try {
var cacheStrategy = convertCacheToStrategy(shouldCache);
var cache = getCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
});
if (cache) {
return Promise.resolve(cache);
}
return Promise.resolve(getTsConfigResult({
cwd: cwd,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
})).then(function (result) {
updateCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
}, result);
return result;
});
} catch (e) {
return Promise.reject(e);
}
};
var readFile = promises.readFile,
stat = promises.stat;
/** The default search name used. */
var DEFAULT_SEARCH_NAME = 'tsconfig.json';
/**
* Extends the default node file parser and determines whether the path provided
* should be resolved from the node modules or directly from the provided path.
*/
var parseFilePath = function parseFilePath(file, _temp) {
var _ref = _temp === void 0 ? {} : _temp,
windows = _ref.windows;
var isWindows = windows !== null && windows !== void 0 ? windows : process.platform === 'win32';
var parser = isWindows ? win32.parse : parse;
var parsedPath = parser(file);
return _extends({}, parsedPath, {
isAbsolute: Boolean(parsedPath.root),
isPackage: !file.startsWith('.') && !parsedPath.root
});
};
/**
* The reason that the tsconfig exist flag is false.
*/
var TsConfigErrorReason = {
/**
* The `tsconfig` file could not be found.
*/
NotFound: 'not-found',
/**
* The file was found but the configuration was invalid.
*/
InvalidConfig: 'invalid-config'
};
/**
* Synchronously walk up the path until a `tsconfig` is located.
*/
var walkForTsConfigSync = function walkForTsConfigSync(directory) {
var configPath = join(directory, './tsconfig.json');
if (isFileOrDirectorySync(configPath)) {
return configPath;
}
var parentDirectory = join(directory, '../'); // If we reached the top
if (directory === parentDirectory) {
return undefined;
}
return walkForTsConfigSync(parentDirectory);
};
/**
* Walk up the path until a `tsconfig` is located.
*/
var walkForTsConfig = function walkForTsConfig(directory) {
try {
var _exit2 = false;
var configPath = join(directory, './tsconfig.json');
return Promise.resolve(isFileOrDirectory(configPath)).then(function (_isFileOrDirectory) {
if (_isFileOrDirectory) {
_exit2 = true;
return configPath;
}
// Step up one level in the directory path.
var parentDirectory = join(directory, '../'); // If we reached the top
return directory === parentDirectory ? undefined : walkForTsConfig(parentDirectory);
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Synchronously check that the passed string is a directory.
*/
var isDirectorySync = function isDirectorySync(directory) {
try {
return statSync(directory).isDirectory();
} catch (_unused) {
return false;
}
};
/**
* Check that the passed string is a directory.
*/
var isDirectory = function isDirectory(directory) {
return Promise.resolve(_catch(function () {
return Promise.resolve(stat(directory)).then(function (stats) {
return stats.isDirectory();
});
}, function () {
return false;
}));
};
/**
* Synchronously check that the passed filePath is a valid file.
*/
var isFileSync = function isFileSync(filePath) {
try {
return statSync(filePath).isFile();
} catch (_unused2) {
return false;
}
};
/**
* Check that the passed filePath is a valid file.
*/
var isFile = function isFile(filePath) {
return Promise.resolve(_catch(function () {
return Promise.resolve(stat(filePath)).then(function (stats) {
return stats.isFile();
});
}, function () {
return false;
}));
};
/**
* Synchronously check that the provided `filePath` is a file or directory.
*/
var isFileOrDirectorySync = function isFileOrDirectorySync(filePath) {
return isFileSync(filePath) || isDirectorySync(filePath);
};
/**
* Check that the provided `filePath` is a file or directory.
*/
var isFileOrDirectory = function isFileOrDirectory(filePath) {
try {
var _exit5 = false;
return Promise.resolve(isFile(filePath)).then(function (_isFile) {
var _exit4 = false;
if (_isFile) {
_exit5 = true;
return true;
}
return Promise.resolve(isDirectory(filePath)).then(function (_isDirectory) {
if (_isDirectory) {
_exit4 = true;
return true;
}
return false;
});
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Synchronously resolves an npm package by the given name.
*/
var resolvePackageSync = function resolvePackageSync(name, basedir) {
try {
return resolvePackageNpm.sync(name, {
basedir: basedir,
extensions: ['.json', '.js']
});
} catch (_unused3) {
return;
}
};
/**
* Resolves an npm package by the given name.
*/
var resolvePackage = function resolvePackage(name, basedir) {
return new Promise(function (resolve, reject) {
resolvePackageNpm(name, {
basedir: basedir,
extensions: ['.json', '.js']
}, function (error, resolved) {
if (error) {
reject(error);
} else {
resolve(resolved);
}
});
});
};
/**
* Synchronously checks a filePath exists and if it can be resolved.
*/
var resolveFilePathSync = function resolveFilePathSync(searchName, filePath) {
var cwd = process.cwd();
if (!filePath) {
return;
}
var resolvedPath;
if (filePath.startsWith('npm:')) {
resolvedPath = resolvePackageSync(filePath.replace('npm:', ''), cwd);
} else {
resolvedPath = resolve(cwd, filePath);
}
if (!resolvedPath || !isDirectorySync(resolvedPath)) {
return resolvedPath;
}
return resolve(resolvedPath, searchName);
};
/**
* When a filePath exists check if it can be resolved.
*/
var resolveFilePath = function resolveFilePath(searchName, filePath) {
try {
var _temp6 = function _temp6() {
var _exit6 = false;
function _temp3(_isDirectory2) {
if (_temp2 || !_isDirectory2) {
_exit6 = true;
return resolvedPath;
}
return resolve(resolvedPath, searchName);
}
var _temp2 = !resolvedPath;
return _temp2 ? _temp3(_temp2) : Promise.resolve(isDirectory(resolvedPath)).then(_temp3);
};
var cwd = process.cwd();
if (!filePath) {
return Promise.resolve();
}
var resolvedPath;
var _temp7 = function () {
if (filePath.startsWith('npm:')) {
return Promise.resolve(resolvePackage(filePath.replace('npm:', ''), cwd)).then(function (_resolvePackage) {
resolvedPath = _resolvePackage;
});
} else {
resolvedPath = resolve(cwd, filePath);
}
}();
return Promise.resolve(_temp7 && _temp7.then ? _temp7.then(_temp6) : _temp6(_temp7));
} catch (e) {
return Promise.reject(e);
}
};
/**
* Get the desired path to the configuration.
*/
var resolveConfigPathSync = function resolveConfigPathSync(cwd, searchName, filePath) {
var resolvedFilePath = resolveFilePathSync(searchName, filePath);
if (resolvedFilePath) {
return resolvedFilePath;
}
if (searchName !== DEFAULT_SEARCH_NAME) {
var resolvedSearchName = resolve(cwd, searchName);
var absolutePath = isDirectorySync(resolvedSearchName) ? resolve(resolvedSearchName, 'tsconfig.json') : resolvedSearchName;
return isFileSync(absolutePath) ? absolutePath : undefined;
}
if (isFileSync(cwd)) {
return resolve(cwd);
}
var configAbsolutePath = walkForTsConfigSync(cwd);
return configAbsolutePath ? resolve(configAbsolutePath) : undefined;
};
/**
* Get the desired path to the configuration.
*/
var resolveConfigPath = function resolveConfigPath(cwd, searchName, filePath) {
try {
return Promise.resolve(resolveFilePath(searchName, filePath)).then(function (resolvedFilePath) {
var _exit7 = false;
function _temp9(_result) {
var _exit8 = false;
if (_exit7) return _result;
return Promise.resolve(isFile(cwd)).then(function (_isFile3) {
if (_isFile3) {
_exit8 = true;
return resolve(cwd);
}
return Promise.resolve(walkForTsConfig(cwd)).then(function (configAbsolutePath) {
return configAbsolutePath ? resolve(configAbsolutePath) : undefined;
});
});
}
if (resolvedFilePath) {
return resolvedFilePath;
}
var _temp8 = function () {
if (searchName !== DEFAULT_SEARCH_NAME) {
var resolvedSearchName = resolve(cwd, searchName);
return Promise.resolve(isDirectory(resolvedSearchName)).then(function (_isDirectory3) {
var absolutePath = _isDirectory3 ? resolve(resolvedSearchName, 'tsconfig.json') : resolvedSearchName;
_exit7 = true;
return Promise.resolve(isFile(absolutePath)).then(function (_isFile2) {
return _isFile2 ? absolutePath : undefined;
});
});
}
}();
return _temp8 && _temp8.then ? _temp8.then(_temp9) : _temp9(_temp8);
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Loads the `jsonString` and returns it as a TsConfigJson object.
*/
var parseTsConfigJson = function parseTsConfigJson(jsonString) {
try {
var json = JSON5.parse(jsonString);
return json && typeof json === 'object' ? json : undefined;
} catch (_unused4) {
return undefined;
}
};
/**
* Synchronously loads a tsconfig file while also resolving the `extends` path.
*/
var loadTsConfigSync = function loadTsConfigSync(configFilePath, extendedPaths, ignoreExtends) {
var _base, _base$compilerOptions;
if (ignoreExtends === void 0) {
ignoreExtends = false;
}
if (!isFileOrDirectorySync(configFilePath)) return undefined;
var configString = readFileSync(configFilePath, 'utf8');
var jsonString = StripBom(configString);
var config = parseTsConfigJson(jsonString);
var extendedConfig = config === null || config === void 0 ? void 0 : config["extends"];
if (!config || !extendedConfig || ignoreExtends) return config;
var base;
if (parseFilePath(extendedConfig).isPackage) {
var _loadTsConfigSync;
var newConfigPath = resolvePackageSync(extendedConfig);
if (!newConfigPath) {
return config;
} else if (isDirectorySync(newConfigPath)) {
extendedConfig = join(newConfigPath, DEFAULT_SEARCH_NAME);
} else if (isFileSync(newConfigPath)) {
extendedConfig = newConfigPath;
} else if (isFileSync(newConfigPath + ".json")) {
extendedConfig = newConfigPath + ".json";
}
if (extendedPaths.includes(extendedConfig)) {
return config;
}
extendedPaths.push(extendedConfig);
base = (_loadTsConfigSync = loadTsConfigSync(extendedConfig, extendedPaths)) !== null && _loadTsConfigSync !== void 0 ? _loadTsConfigSync : {};
} else {
var _loadTsConfigSync2;
if (!extendedConfig.endsWith('.json')) {
extendedConfig += '.json';
}
var currentDir = dirname(configFilePath);
var extendedConfigPath = join(currentDir, extendedConfig);
if (extendedPaths.includes(extendedConfigPath)) {
return config;
}
extendedPaths.push(extendedConfigPath);
base = (_loadTsConfigSync2 = loadTsConfigSync(extendedConfigPath, extendedPaths)) !== null && _loadTsConfigSync2 !== void 0 ? _loadTsConfigSync2 : {};
} // baseUrl should be interpreted as relative to the base tsconfig, but we need
// to update it so it is relative to the original tsconfig being loaded
if ((_base = base) === null || _base === void 0 ? void 0 : (_base$compilerOptions = _base.compilerOptions) === null || _base$compilerOptions === void 0 ? void 0 : _base$compilerOptions.baseUrl) {
var extendsDir = dirname(extendedConfig);
base.compilerOptions.baseUrl = join(extendsDir, base.compilerOptions.baseUrl);
}
return _extends({}, base, {}, config, {
compilerOptions: _extends({}, base.compilerOptions, {}, config.compilerOptions)
});
};
/**
* Loads a tsconfig file while also resolving the `extends` path.
*/
var loadTsConfig = function loadTsConfig(configFilePath, extendedPaths, ignoreExtends) {
if (ignoreExtends === void 0) {
ignoreExtends = false;
}
try {
var _exit12 = false;
return Promise.resolve(isFileOrDirectory(configFilePath)).then(function (_isFileOrDirectory2) {
if (!_isFileOrDirectory2) {
_exit12 = true;
return undefined;
}
return Promise.resolve(readFile(configFilePath, 'utf8')).then(function (configString) {
var _exit10 = false;
function _temp15(_result2) {
var _base2, _base2$compilerOption;
if (_exit10) return _result2;
// baseUrl should be interpreted as relative to the base tsconfig, but we need
// to update it so it is relative to the original tsconfig being loaded
if ((_base2 = base) === null || _base2 === void 0 ? void 0 : (_base2$compilerOption = _base2.compilerOptions) === null || _base2$compilerOption === void 0 ? void 0 : _base2$compilerOption.baseUrl) {
var extendsDir = dirname(extendedConfig);
base.compilerOptions.baseUrl = join(extendsDir, base.compilerOptions.baseUrl);
}
return _extends({}, base, {}, config, {
compilerOptions: _extends({}, base.compilerOptions, {}, config.compilerOptions)
});
}
var jsonString = StripBom(configString);
var config = parseTsConfigJson(jsonString);
var extendedConfig = config === null || config === void 0 ? void 0 : config["extends"];
if (!config || !extendedConfig || ignoreExtends) return config;
var base;
var _temp14 = function () {
if (parseFilePath(extendedConfig).isPackage) {
return Promise.resolve(resolvePackage(extendedConfig)).then(function (newConfigPath) {
var _exit11 = false;
function _temp13(_result3) {
if (_exit11) return _result3;
if (extendedPaths.includes(extendedConfig)) {
_exit10 = true;
return config;
}
extendedPaths.push(extendedConfig);
return Promise.resolve(loadTsConfig(extendedConfig, extendedPaths)).then(function (_loadTsConfig) {
base = _loadTsConfig !== null && _loadTsConfig !== void 0 ? _loadTsConfig : {};
});
}
var _temp12 = function () {
if (!newConfigPath) {
_exit10 = true;
return config;
} else return Promise.resolve(isDirectory(newConfigPath)).then(function (_isDirectory4) {
var _temp11 = function () {
if (_isDirectory4) {
extendedConfig = join(newConfigPath, DEFAULT_SEARCH_NAME);
} else return Promise.resolve(isFile(newConfigPath)).then(function (_isFile4) {
var _temp10 = function () {
if (_isFile4) {
extendedConfig = newConfigPath;
} else return Promise.resolve(isFile(newConfigPath + ".json")).then(function (_isFile5) {
if (_isFile5) {
extendedConfig = newConfigPath + ".json";
}
});
}();
if (_temp10 && _temp10.then) return _temp10.then(function () {});
});
}();
if (_temp11 && _temp11.then) return _temp11.then(function () {});
});
}();
return _temp12 && _temp12.then ? _temp12.then(_temp13) : _temp13(_temp12);
});
} else {
if (!extendedConfig.endsWith('.json')) {
extendedConfig += '.json';
}
var currentDir = dirname(configFilePath);
var extendedConfigPath = join(currentDir, extendedConfig);
if (extendedPaths.includes(extendedConfigPath)) {
_exit10 = true;
return config;
}
extendedPaths.push(extendedConfigPath);
return Promise.resolve(loadTsConfig(extendedConfigPath, extendedPaths)).then(function (_loadTsConfig2) {
base = _loadTsConfig2 !== null && _loadTsConfig2 !== void 0 ? _loadTsConfig2 : {};
});
}
}();
return _temp14 && _temp14.then ? _temp14.then(_temp15) : _temp15(_temp14);
});
});
} catch (e) {
return Promise.reject(e);
}
};
var CacheStrategy = {
/**
* Caching never happens and the returned value is always recalculated.
*/
Never: 'never',
/**
* The first time the `tsconfigResolver` method is run it will save a cached
* value (by `searchName`) which will be returned every time after that. This
* value will always be the same.
*/
Always: 'always',
/**
* The cache will be used when the same directory (and searchName) is being
* searched.
*/
Directory: 'directory'
};
var cacheObject = (_cacheObject = {}, _cacheObject[CacheStrategy.Always] = /*#__PURE__*/new Map(), _cacheObject[CacheStrategy.Directory] = /*#__PURE__*/new Map(), _cacheObject);
/**
* Converts a boolean or string type into a cache strategy.
*/
var convertCacheToStrategy = function convertCacheToStrategy(value) {
return value === false ? CacheStrategy.Never : value === true ? CacheStrategy.Always : value;
};
/**
* Get the key to store in the cache.
*/
var cacheKey = function cacheKey(_ref2) {
var cache = _ref2.cache,
cwd = _ref2.cwd,
searchName = _ref2.searchName,
ignoreExtends = _ref2.ignoreExtends;
return cache === CacheStrategy.Always ? searchName + " - " + ignoreExtends : join(cwd, searchName) + " - " + ignoreExtends;
};
/**
* Based on the options passed in, retrieve the value from the cache or return
* undefined if the value still needs to be calculated.
*/
var getCache = function getCache(options) {
if (options.cache === CacheStrategy.Always) {
return cacheObject[CacheStrategy.Always].get(cacheKey(options));
}
if (options.cache === CacheStrategy.Directory) {
return cacheObject[CacheStrategy.Always].get(cacheKey(options));
}
return undefined;
};
/**
* Updates the cache with the provided result.
*/
var updateCache = function updateCache(options, result) {
if (options.cache === CacheStrategy.Always) {
cacheObject[CacheStrategy.Always].set(cacheKey(options), result);
} else if (options.cache === CacheStrategy.Directory) {
cacheObject[CacheStrategy.Always].set(cacheKey(options), result);
}
};
/**
* Clears the cache.
*/
var clearCache = function clearCache() {
for (var _i = 0, _Object$values = Object.values(cacheObject); _i < _Object$values.length; _i++) {
var map = _Object$values[_i];
map.clear();
}
};
/**
* Synchronously get the nearest tsconfig by walking up the directory.
*/
var getTsConfigResultSync = function getTsConfigResultSync(_ref3) {
var cwd = _ref3.cwd,
searchName = _ref3.searchName,
filePath = _ref3.filePath,
ignoreExtends = _ref3.ignoreExtends;
var configPath = resolveConfigPathSync(cwd, searchName, filePath);
if (!configPath) {
return {
exists: false,
reason: TsConfigErrorReason.NotFound
};
} // This path will be mutated to include all paths that have been found.
var extendedPaths = [];
var config = loadTsConfigSync(configPath, extendedPaths, ignoreExtends);
if (!config) {
return {
exists: false,
reason: TsConfigErrorReason.InvalidConfig,
path: configPath
};
}
return {
exists: true,
path: configPath,
extendedPaths: extendedPaths,
config: config,
isCircular: extendedPaths.includes(configPath)
};
};
/**
* Get the nearest tsconfig by walking up the directory.
*/
var getTsConfigResult = function getTsConfigResult(_ref4) {
var cwd = _ref4.cwd,
searchName = _ref4.searchName,
filePath = _ref4.filePath,
ignoreExtends = _ref4.ignoreExtends;
try {
return Promise.resolve(resolveConfigPath(cwd, searchName, filePath)).then(function (configPath) {
if (!configPath) {
return {
exists: false,
reason: TsConfigErrorReason.NotFound
};
} // This path will be mutated to include all paths that have been found.
var extendedPaths = [];
return Promise.resolve(loadTsConfig(configPath, extendedPaths, ignoreExtends)).then(function (config) {
return config ? {
exists: true,
path: configPath,
extendedPaths: extendedPaths,
config: config,
isCircular: extendedPaths.includes(configPath)
} : {
exists: false,
reason: TsConfigErrorReason.InvalidConfig,
path: configPath
};
});
});
} catch (e) {
return Promise.reject(e);
}
};
/**
* Resolve the `tsconfig` file synchronously. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @returns an object containing whether a configuration was found and is valid.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
function tsconfigResolverSync(_temp16) {
var _ref5 = _temp16 === void 0 ? {} : _temp16,
filePath = _ref5.filePath,
_ref5$cwd = _ref5.cwd,
cwd = _ref5$cwd === void 0 ? process.cwd() : _ref5$cwd,
_ref5$cache = _ref5.cache,
shouldCache = _ref5$cache === void 0 ? filePath ? CacheStrategy.Always : CacheStrategy.Never : _ref5$cache,
_ref5$searchName = _ref5.searchName,
searchName = _ref5$searchName === void 0 ? DEFAULT_SEARCH_NAME : _ref5$searchName,
_ref5$ignoreExtends = _ref5.ignoreExtends,
ignoreExtends = _ref5$ignoreExtends === void 0 ? false : _ref5$ignoreExtends;
var cacheStrategy = convertCacheToStrategy(shouldCache);
var cache = getCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
});
if (cache) {
return cache;
}
var result = getTsConfigResultSync({
cwd: cwd,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
});
updateCache({
cwd: cwd,
cache: cacheStrategy,
searchName: searchName,
filePath: filePath,
ignoreExtends: ignoreExtends
}, result);
return result;
}
export { CacheStrategy, DEFAULT_SEARCH_NAME, TsConfigErrorReason, clearCache, tsconfigResolver, tsconfigResolverSync };
//# sourceMappingURL=tsconfig-resolver.esm.js.map

File diff suppressed because one or more lines are too long

1
node_modules/tsconfig-resolver/node_modules/.bin/json5 generated vendored Symbolic link
View file

@ -0,0 +1 @@
../../../json5/lib/cli.js

View file

@ -0,0 +1 @@
../../../resolve/bin/resolve

126
node_modules/tsconfig-resolver/package.json generated vendored Normal file
View file

@ -0,0 +1,126 @@
{
"name": "tsconfig-resolver",
"version": "3.0.1",
"description": "Walk up the tree to resolve `tsconfig.json` configuration objects.",
"keywords": [
"tsconfig",
"typescript",
"json",
"read",
"parse",
"file",
"fs",
"graceful",
"load",
"find",
"up",
"find-up",
"findup",
"look-up",
"look",
"search",
"match",
"resolve",
"parent",
"parents",
"folder",
"directory",
"walk",
"walking",
"path"
],
"funding": "https://github.com/sponsors/ifiokjr",
"license": "MIT",
"author": {
"name": "Ifiok Jr.",
"email": "ifiokotung@gmail.com",
"url": "https://ifiokjr.com"
},
"files": [
"src",
"dist"
],
"main": "dist/index.js",
"module": "dist/tsconfig-resolver.esm.js",
"typings": "dist/index.d.ts",
"scripts": {
"build": "tsdx build",
"lint": "tsdx lint",
"prepare": "tsdx build",
"start": "tsdx watch",
"test": "tsdx test"
},
"husky": {
"hooks": {
"pre-commit": "tsdx lint",
"pre-push": "yarn tsc --noEmit && yarn lint && yarn test"
}
},
"prettier": {
"plugins": [
"prettier-plugin-packagejson",
"prettier-plugin-sorted"
],
"printWidth": 80,
"semi": true,
"singleQuote": true,
"trailingComma": "all"
},
"resolutions": {
"mem": ">=4",
"minimist": ">=1.2.2"
},
"dependencies": {
"@types/json5": "^0.0.30",
"@types/resolve": "^1.17.0",
"json5": "^2.1.3",
"resolve": "^1.17.0",
"strip-bom": "^4.0.0",
"type-fest": "^0.13.1"
},
"devDependencies": {
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/git": "^9.0.0",
"@sindresorhus/tsconfig": "0.7.0",
"@types/jest": "^25.2.1",
"conventional-changelog-conventionalcommits": "^4.2.3",
"husky": "^4.2.5",
"lint-staged": "^10.2.2",
"prettier-plugin-packagejson": "^2.2.3",
"prettier-plugin-sorted": "^2.0.0",
"semantic-release": "^17.0.7",
"tsdx": "^0.13.2",
"tslib": "^1.11.2",
"typescript": "^3.8.3"
},
"peerDependencies": {},
"release": {
"plugins": [
[
"@semantic-release/commit-analyzer",
{
"preset": "conventionalcommits"
}
],
[
"@semantic-release/release-notes-generator",
{
"preset": "conventionalcommits"
}
],
"@semantic-release/changelog",
"@semantic-release/npm",
"@semantic-release/github",
[
"@semantic-release/git",
{
"assets": [
"package.json",
"CHANGELOG.md"
],
"message": "chore(release): ${nextRelease.version} [skip ci]\n\n${nextRelease.notes}"
}
]
]
}
}

View file

@ -0,0 +1,5 @@
{
"compilerOptions": {
"alwaysStrict": true
}
}

View file

@ -0,0 +1,3 @@
{
"custom": "yes"
}

View file

@ -0,0 +1,5 @@
{
"compilerOptions": {
"baseUrl": "specific"
}
}

View file

@ -0,0 +1 @@
{}

View file

@ -0,0 +1,5 @@
{
"compilerOptions": {
"jsx": "react"
}
}

View file

@ -0,0 +1 @@
not valid json

View file

@ -0,0 +1,5 @@
{
"compilerOptions": {
"jsx": "preserve"
}
}

View file

@ -0,0 +1,9 @@
{
"compilerOptions": {
"allowJs": false,
"baseUrl": "./",
"paths": {
"simple": ["./simple"]
}
}
}

View file

@ -0,0 +1,6 @@
{
"extends": "./circular2.tsconfig.json",
"compilerOptions": {
"baseUrl": "oops"
}
}

View file

@ -0,0 +1,6 @@
{
"extends": "./circular.tsconfig.json",
"compilerOptions": {
"allowJs": true
}
}

View file

@ -0,0 +1,10 @@
{
"extends": "../tsconfig.paths.json",
"compilerOptions": {
"baseUrl": "simple",
"paths": {
"g": ["./g"],
"b": ["./b"]
}
}
}

View file

@ -0,0 +1,3 @@
{
"extends": "./base.tsconfig.json"
}

View file

@ -0,0 +1,3 @@
{
"extends": "@sindresorhus/tsconfig"
}

View file

@ -0,0 +1,6 @@
{
"extends": "./base.tsconfig.json",
"compilerOptions": {
"paths": {}
}
}

View file

@ -0,0 +1,384 @@
import { join } from 'path';
import { CacheStrategy, clearCache, tsconfigResolver } from '..';
const processCwd = jest.spyOn(process, 'cwd');
const fixtures = (...paths: string[]) =>
join(__dirname, '__fixtures__', ...paths);
afterEach(clearCache);
describe('resolver', () => {
beforeEach(() => {
processCwd.mockReturnValue(fixtures('basic'));
});
it('resolves the tsconfig by default', async () => {
const { exists, config, path } = await tsconfigResolver();
expect(path?.endsWith('__fixtures__/basic/tsconfig.json')).toBe(true);
expect(exists).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"jsx": "preserve",
},
}
`);
});
it('resolves from a sub directory', async () => {
processCwd.mockReturnValue(fixtures('basic', 'subdir'));
const { exists, config, path } = await tsconfigResolver();
expect(path?.endsWith('__fixtures__/basic/tsconfig.json')).toBe(true);
expect(exists).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"jsx": "preserve",
},
}
`);
});
it('resolves with a custom `searchName`', async () => {
const { exists, config, path } = await tsconfigResolver({
searchName: 'tsconfig.alt.json',
});
expect(path?.endsWith('__fixtures__/basic/tsconfig.alt.json')).toBe(true);
expect(exists).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"jsx": "react",
},
}
`);
});
it('appends `tsconfig.json` when `searchName` is a directory', async () => {
const result = await tsconfigResolver({ searchName: 'cachedir' });
expect(
result.path?.endsWith('__fixtures__/basic/cachedir/tsconfig.json'),
).toBe(true);
expect(result.config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"alwaysStrict": true,
},
}
`);
});
it('properly resolves invalid json', async () => {
const { exists, reason } = await tsconfigResolver({
searchName: 'tsconfig.invalid.json',
});
expect(exists).toBe(false);
expect(reason).toBe('invalid-config');
});
it('properly resolves missing config', async () => {
const { exists, reason } = await tsconfigResolver({
searchName: 'tsconfig.missing.json',
});
expect(exists).toBe(false);
expect(reason).toBe('not-found');
});
it('returns the config found by a custom `filePath`', async () => {
const result = await tsconfigResolver({
filePath: 'specific/custom.json',
});
expect(
result.path?.endsWith('__fixtures__/basic/specific/custom.json'),
).toBe(true);
expect(result.config).toMatchInlineSnapshot(`
Object {
"custom": "yes",
}
`);
});
it('defaults to `tsconfig.json` when `filePath` is a directory', async () => {
const result = await tsconfigResolver({
filePath: './specific',
});
expect(
result.path?.endsWith('__fixtures__/basic/specific/tsconfig.json'),
).toBe(true);
expect(result.config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"baseUrl": "specific",
},
}
`);
});
it('allows `filePath` to be prefixed with `npm:` for npm packages', async () => {
const result = await tsconfigResolver({
filePath: 'npm:@sindresorhus/tsconfig',
});
expect(result.config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"declaration": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"newLine": "lf",
"noEmitOnError": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"stripInternal": true,
"target": "es2017",
},
}
`);
});
});
describe('extends', () => {
beforeEach(() => {
processCwd.mockReturnValue(fixtures('extends'));
});
it('extends a base config', async () => {
const { config } = await tsconfigResolver();
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": false,
"baseUrl": "./",
"paths": Object {
"simple": Array [
"./simple",
],
},
},
"extends": "./base.tsconfig.json",
}
`);
});
it('extends and resolves paths', async () => {
const { config, extendedPaths } = await tsconfigResolver({
searchName: 'tsconfig.paths.json',
});
expect(extendedPaths).toEqual([
fixtures('extends', './base.tsconfig.json'),
]);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": false,
"baseUrl": "./",
"paths": Object {},
},
"extends": "./base.tsconfig.json",
}
`);
});
it('extends from npm', async () => {
const { config, extendedPaths } = await tsconfigResolver({
searchName: 'tsconfig.npm.json',
});
expect(extendedPaths).toEqual([require.resolve('@sindresorhus/tsconfig')]);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"declaration": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"newLine": "lf",
"noEmitOnError": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"stripInternal": true,
"target": "es2017",
},
"extends": "@sindresorhus/tsconfig",
}
`);
});
it('can ignore extends', async () => {
const { config, extendedPaths } = await tsconfigResolver({
searchName: 'tsconfig.npm.json',
ignoreExtends: true,
});
expect(extendedPaths).toEqual([]);
expect(config).toMatchInlineSnapshot(`
Object {
"extends": "@sindresorhus/tsconfig",
}
`);
});
it('supports nested extends', async () => {
const { config, extendedPaths } = await tsconfigResolver({
cwd: fixtures('extends', 'nested'),
});
expect(extendedPaths).toEqual([
fixtures('extends', 'tsconfig.paths.json'),
fixtures('extends', 'base.tsconfig.json'),
]);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": false,
"baseUrl": "simple",
"paths": Object {
"b": Array [
"./b",
],
"g": Array [
"./g",
],
},
},
"extends": "../tsconfig.paths.json",
}
`);
});
it('handles `circular` extends', async () => {
const { config, extendedPaths, isCircular } = await tsconfigResolver({
searchName: 'circular.tsconfig.json',
});
expect(extendedPaths).toEqual([
fixtures('extends', 'circular2.tsconfig.json'),
fixtures('extends', 'circular.tsconfig.json'),
]);
expect(isCircular).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": true,
"baseUrl": "oops",
},
"extends": "./circular2.tsconfig.json",
}
`);
});
});
describe('caching', () => {
beforeEach(() => {
processCwd.mockReturnValue(fixtures('basic'));
});
it('supports searchName caching', async () => {
const result1 = await tsconfigResolver({
cache: CacheStrategy.Always,
});
const result2 = await tsconfigResolver({
cwd: fixtures('basic', 'cachedir'),
cache: CacheStrategy.Always,
});
const result3 = await tsconfigResolver({
cache: CacheStrategy.Always,
searchName: 'fake',
});
expect(result1).toBe(result2);
expect(result3).not.toBe(result2);
});
it('support directory caching', async () => {
const result1 = await tsconfigResolver({
cache: CacheStrategy.Directory,
});
const result2 = await tsconfigResolver({
cwd: fixtures('basic', 'subdir'),
cache: CacheStrategy.Directory,
});
const result3 = await tsconfigResolver({
cache: CacheStrategy.Directory,
});
const result4 = await tsconfigResolver({
cache: CacheStrategy.Directory,
searchName: 'fake',
});
expect(result1).not.toBe(result2);
expect(result3).toBe(result1);
expect(result4).not.toBe(result1);
});
it('caches by default when using a filePath', async () => {
const result1 = await tsconfigResolver({
filePath: 'cachedir/tsconfig.json',
});
const result2 = await tsconfigResolver({
cwd: fixtures('basic', 'subdir'),
filePath: 'cachedir/tsconfig.json',
});
expect(result1).toBe(result2);
});
it('separates cache by `ignoreExtends` property', async () => {
const result1 = await tsconfigResolver({
cache: CacheStrategy.Always,
});
const result2 = await tsconfigResolver({
ignoreExtends: true,
cache: CacheStrategy.Always,
});
expect(result1).not.toBe(result2);
});
it('supports clearing the cache', async () => {
const result1 = await tsconfigResolver({
cache: CacheStrategy.Always,
});
clearCache();
const result2 = await tsconfigResolver({
cache: CacheStrategy.Always,
});
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
});

View file

@ -0,0 +1,384 @@
import { join } from 'path';
import { CacheStrategy, clearCache, tsconfigResolverSync } from '..';
const processCwd = jest.spyOn(process, 'cwd');
const fixtures = (...paths: string[]) =>
join(__dirname, '__fixtures__', ...paths);
afterEach(clearCache);
describe('resolver', () => {
beforeEach(() => {
processCwd.mockReturnValue(fixtures('basic'));
});
it('resolves the tsconfig by default', () => {
const { exists, config, path } = tsconfigResolverSync();
expect(path?.endsWith('__fixtures__/basic/tsconfig.json')).toBe(true);
expect(exists).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"jsx": "preserve",
},
}
`);
});
it('resolves from a sub directory', () => {
processCwd.mockReturnValue(fixtures('basic', 'subdir'));
const { exists, config, path } = tsconfigResolverSync();
expect(path?.endsWith('__fixtures__/basic/tsconfig.json')).toBe(true);
expect(exists).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"jsx": "preserve",
},
}
`);
});
it('resolves with a custom `searchName`', () => {
const { exists, config, path } = tsconfigResolverSync({
searchName: 'tsconfig.alt.json',
});
expect(path?.endsWith('__fixtures__/basic/tsconfig.alt.json')).toBe(true);
expect(exists).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"jsx": "react",
},
}
`);
});
it('appends `tsconfig.json` when `searchName` is a directory', () => {
const result = tsconfigResolverSync({ searchName: 'cachedir' });
expect(
result.path?.endsWith('__fixtures__/basic/cachedir/tsconfig.json'),
).toBe(true);
expect(result.config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"alwaysStrict": true,
},
}
`);
});
it('properly resolves invalid json', () => {
const { exists, reason } = tsconfigResolverSync({
searchName: 'tsconfig.invalid.json',
});
expect(exists).toBe(false);
expect(reason).toBe('invalid-config');
});
it('properly resolves missing config', () => {
const { exists, reason } = tsconfigResolverSync({
searchName: 'tsconfig.missing.json',
});
expect(exists).toBe(false);
expect(reason).toBe('not-found');
});
it('returns the config found by a custom `filePath`', () => {
const result = tsconfigResolverSync({
filePath: 'specific/custom.json',
});
expect(
result.path?.endsWith('__fixtures__/basic/specific/custom.json'),
).toBe(true);
expect(result.config).toMatchInlineSnapshot(`
Object {
"custom": "yes",
}
`);
});
it('defaults to `tsconfig.json` when `filePath` is a directory', () => {
const result = tsconfigResolverSync({
filePath: './specific',
});
expect(
result.path?.endsWith('__fixtures__/basic/specific/tsconfig.json'),
).toBe(true);
expect(result.config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"baseUrl": "specific",
},
}
`);
});
it('allows `filePath` to be prefixed with `npm:` for npm packages', () => {
const result = tsconfigResolverSync({
filePath: 'npm:@sindresorhus/tsconfig',
});
expect(result.config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"declaration": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"newLine": "lf",
"noEmitOnError": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"stripInternal": true,
"target": "es2017",
},
}
`);
});
});
describe('extends', () => {
beforeEach(() => {
processCwd.mockReturnValue(fixtures('extends'));
});
it('extends a base config', () => {
const { config } = tsconfigResolverSync();
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": false,
"baseUrl": "./",
"paths": Object {
"simple": Array [
"./simple",
],
},
},
"extends": "./base.tsconfig.json",
}
`);
});
it('extends and resolves paths', () => {
const { config, extendedPaths } = tsconfigResolverSync({
searchName: 'tsconfig.paths.json',
});
expect(extendedPaths).toEqual([
fixtures('extends', './base.tsconfig.json'),
]);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": false,
"baseUrl": "./",
"paths": Object {},
},
"extends": "./base.tsconfig.json",
}
`);
});
it('extends from npm', () => {
const { config, extendedPaths } = tsconfigResolverSync({
searchName: 'tsconfig.npm.json',
});
expect(extendedPaths).toEqual([require.resolve('@sindresorhus/tsconfig')]);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"declaration": true,
"forceConsistentCasingInFileNames": true,
"jsx": "react",
"module": "commonjs",
"moduleResolution": "node",
"newLine": "lf",
"noEmitOnError": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"pretty": true,
"resolveJsonModule": true,
"skipLibCheck": true,
"strict": true,
"stripInternal": true,
"target": "es2017",
},
"extends": "@sindresorhus/tsconfig",
}
`);
});
it('can ignore extends', () => {
const { config, extendedPaths } = tsconfigResolverSync({
searchName: 'tsconfig.npm.json',
ignoreExtends: true,
});
expect(extendedPaths).toEqual([]);
expect(config).toMatchInlineSnapshot(`
Object {
"extends": "@sindresorhus/tsconfig",
}
`);
});
it('supports nested extends', () => {
const { config, extendedPaths } = tsconfigResolverSync({
cwd: fixtures('extends', 'nested'),
});
expect(extendedPaths).toEqual([
fixtures('extends', 'tsconfig.paths.json'),
fixtures('extends', 'base.tsconfig.json'),
]);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": false,
"baseUrl": "simple",
"paths": Object {
"b": Array [
"./b",
],
"g": Array [
"./g",
],
},
},
"extends": "../tsconfig.paths.json",
}
`);
});
it('handles `circular` extends', () => {
const { config, extendedPaths, isCircular } = tsconfigResolverSync({
searchName: 'circular.tsconfig.json',
});
expect(extendedPaths).toEqual([
fixtures('extends', 'circular2.tsconfig.json'),
fixtures('extends', 'circular.tsconfig.json'),
]);
expect(isCircular).toBe(true);
expect(config).toMatchInlineSnapshot(`
Object {
"compilerOptions": Object {
"allowJs": true,
"baseUrl": "oops",
},
"extends": "./circular2.tsconfig.json",
}
`);
});
});
describe('caching', () => {
beforeEach(() => {
processCwd.mockReturnValue(fixtures('basic'));
});
it('supports searchName caching', () => {
const result1 = tsconfigResolverSync({
cache: CacheStrategy.Always,
});
const result2 = tsconfigResolverSync({
cwd: fixtures('basic', 'cachedir'),
cache: CacheStrategy.Always,
});
const result3 = tsconfigResolverSync({
cache: CacheStrategy.Always,
searchName: 'fake',
});
expect(result1).toBe(result2);
expect(result3).not.toBe(result2);
});
it('support directory caching', () => {
const result1 = tsconfigResolverSync({
cache: CacheStrategy.Directory,
});
const result2 = tsconfigResolverSync({
cwd: fixtures('basic', 'subdir'),
cache: CacheStrategy.Directory,
});
const result3 = tsconfigResolverSync({
cache: CacheStrategy.Directory,
});
const result4 = tsconfigResolverSync({
cache: CacheStrategy.Directory,
searchName: 'fake',
});
expect(result1).not.toBe(result2);
expect(result3).toBe(result1);
expect(result4).not.toBe(result1);
});
it('caches by default when using a filePath', () => {
const result1 = tsconfigResolverSync({
filePath: 'cachedir/tsconfig.json',
});
const result2 = tsconfigResolverSync({
cwd: fixtures('basic', 'subdir'),
filePath: 'cachedir/tsconfig.json',
});
expect(result1).toBe(result2);
});
it('separates cache by `ignoreExtends` property', () => {
const result1 = tsconfigResolverSync({
cache: CacheStrategy.Always,
});
const result2 = tsconfigResolverSync({
ignoreExtends: true,
cache: CacheStrategy.Always,
});
expect(result1).not.toBe(result2);
});
it('supports clearing the cache', () => {
const result1 = tsconfigResolverSync({
cache: CacheStrategy.Always,
});
clearCache();
const result2 = tsconfigResolverSync({
cache: CacheStrategy.Always,
});
expect(result1).not.toBe(result2);
expect(result1).toEqual(result2);
});
});

941
node_modules/tsconfig-resolver/src/index.ts generated vendored Normal file
View file

@ -0,0 +1,941 @@
import { promises, readFileSync, statSync } from 'fs';
import {
ParsedPath,
dirname,
join,
parse as pathParse,
win32 as pathWin32,
resolve,
} from 'path';
import JSON5 from 'json5';
import resolvePackageNpm from 'resolve';
import StripBom from 'strip-bom';
import { Except, SetOptional, TsConfigJson } from 'type-fest';
const { readFile, stat } = promises;
/** The default search name used. */
export const DEFAULT_SEARCH_NAME = 'tsconfig.json';
interface IsNodeModuleRequireOptions {
/**
* Whether to simulate windows.
*
* @default undefined
*/
windows?: boolean;
}
interface ParseFilePath {
/**
* True when the file path provided is an absolute path.
*/
isAbsolute: boolean;
/**
* True when the file path potentially refers to a node module package.
*/
isPackage: boolean;
}
/**
* Extends the default node file parser and determines whether the path provided
* should be resolved from the node modules or directly from the provided path.
*/
const parseFilePath = (
file: string,
{ windows }: IsNodeModuleRequireOptions = {},
): ParsedPath & ParseFilePath => {
const isWindows = windows ?? process.platform === 'win32';
const parser = isWindows ? pathWin32.parse : pathParse;
const parsedPath = parser(file);
return {
...parsedPath,
isAbsolute: Boolean(parsedPath.root),
isPackage: !file.startsWith('.') && !parsedPath.root,
};
};
/**
* The reason that the tsconfig exist flag is false.
*/
export const TsConfigErrorReason = {
/**
* The `tsconfig` file could not be found.
*/
NotFound: 'not-found',
/**
* The file was found but the configuration was invalid.
*/
InvalidConfig: 'invalid-config',
} as const;
interface TsConfigFailure {
/**
* Whether or not the configuration could be loaded.
*
* - `false` when no tsconfig could be found.
*/
exists: false;
/**
* The configuration object.
*
* - `undefined` when the tsconfig resolver failed and no configuration was
* found.
*/
config?: undefined;
/**
* The extendedPaths array.
*
* - `undefined` when the tsconfig resolver failed to load a valid
* configuration.
*/
extendedPaths?: undefined;
/**
* The `isCircular` config flag.
*
* - `undefined` when the tsconfig resolver failed to load a valid
* configuration.
*/
isCircular?: undefined;
}
export interface TsConfigFailureNotFound extends TsConfigFailure {
/**
* The reason for failure.
*
* - `TsConfigErrorReason.NotFound` when the config failure is because the
* filename has not been found.
*/
reason: typeof TsConfigErrorReason.NotFound;
/**
* The absolute path to the `tsconfig.json` or given filename.
*
* - `undefined` when not found.
*/
path?: undefined;
}
export interface TsConfigFailureInvalidConfig extends TsConfigFailure {
/**
* - `TsConfigErrorReason.InvalidConfig` when the config failure is because of
* an invalid config.
*/
reason: typeof TsConfigErrorReason.InvalidConfig;
/**
* - `string` when config json is invalid.
*/
path: string;
}
export interface TsConfigResultSuccess {
/**
* - `true` when a valid tsconfig file has been found and successfully loaded.
*/
exists: true;
/**
* - `string` when a valid tsconfig has been loaded.
*/
path: string;
/**
* - `string[]` of absolute paths to resolved tsconfig files when extended
* paths are encountered.
* - `[]` an empty array when no extended paths were encountered.
* - `[]` an empty array when `ignoreExtends` options is set to true.
*/
extendedPaths: string[];
/**
* - `true` when a circular `extends` property was encountered (an extends
* path chain that references itself).
* - `false` when no circular `extends` property was encountered.
*/
isCircular: boolean;
/**
* - `TsConfigJson` when the resolved tsconfig has been found and loaded.
*/
config: TsConfigJson;
/**
* - `undefined` when no failure has occurred.
*/
reason?: undefined;
}
/**
* The result of loading the tsconfig. If the exists property is `true` then
* there will be a path and config property available.
*/
export type TsConfigResult =
| TsConfigFailureNotFound
| TsConfigFailureInvalidConfig
| TsConfigResultSuccess;
export interface TsConfigLoaderParams {
getEnv: (key: string) => string | undefined;
cwd: string;
loadSync?(cwd: string, searchName?: string): TsConfigResult;
}
/**
* Synchronously walk up the path until a `tsconfig` is located.
*/
const walkForTsConfigSync = (directory: string): string | undefined => {
const configPath = join(directory, './tsconfig.json');
if (isFileOrDirectorySync(configPath)) {
return configPath;
}
const parentDirectory = join(directory, '../');
// If we reached the top
if (directory === parentDirectory) {
return undefined;
}
return walkForTsConfigSync(parentDirectory);
};
/**
* Walk up the path until a `tsconfig` is located.
*/
const walkForTsConfig = async (
directory: string,
): Promise<string | undefined> => {
const configPath = join(directory, './tsconfig.json');
if (await isFileOrDirectory(configPath)) {
return configPath;
}
// Step up one level in the directory path.
const parentDirectory = join(directory, '../');
// If we reached the top
if (directory === parentDirectory) {
return undefined;
}
return walkForTsConfig(parentDirectory);
};
/**
* Synchronously check that the passed string is a directory.
*/
const isDirectorySync = (directory: string) => {
try {
return statSync(directory).isDirectory();
} catch {
return false;
}
};
/**
* Check that the passed string is a directory.
*/
const isDirectory = async (directory: string) => {
try {
const stats = await stat(directory);
return stats.isDirectory();
} catch {
return false;
}
};
/**
* Synchronously check that the passed filePath is a valid file.
*/
const isFileSync = (filePath: string) => {
try {
return statSync(filePath).isFile();
} catch {
return false;
}
};
/**
* Check that the passed filePath is a valid file.
*/
const isFile = async (filePath: string) => {
try {
const stats = await stat(filePath);
return stats.isFile();
} catch {
return false;
}
};
/**
* Synchronously check that the provided `filePath` is a file or directory.
*/
const isFileOrDirectorySync = (filePath: string) =>
isFileSync(filePath) || isDirectorySync(filePath);
/**
* Check that the provided `filePath` is a file or directory.
*/
const isFileOrDirectory = async (filePath: string) => {
if (await isFile(filePath)) {
return true;
}
if (await isDirectory(filePath)) {
return true;
}
return false;
};
/**
* Synchronously resolves an npm package by the given name.
*/
const resolvePackageSync = (name: string, basedir?: string) => {
try {
return resolvePackageNpm.sync(name, {
basedir,
extensions: ['.json', '.js'],
});
} catch {
return;
}
};
/**
* Resolves an npm package by the given name.
*/
const resolvePackage = (name: string, basedir?: string) => {
return new Promise<string | undefined>((resolve, reject) => {
resolvePackageNpm(
name,
{
basedir,
extensions: ['.json', '.js'],
},
(error, resolved) => {
if (error) {
reject(error);
} else {
resolve(resolved);
}
},
);
});
};
/**
* Synchronously checks a filePath exists and if it can be resolved.
*/
const resolveFilePathSync = (
searchName: string,
filePath?: string,
): string | undefined => {
const cwd = process.cwd();
if (!filePath) {
return;
}
let resolvedPath: string | undefined;
if (filePath.startsWith('npm:')) {
resolvedPath = resolvePackageSync(filePath.replace('npm:', ''), cwd);
} else {
resolvedPath = resolve(cwd, filePath);
}
if (!resolvedPath || !isDirectorySync(resolvedPath)) {
return resolvedPath;
}
return resolve(resolvedPath, searchName);
};
/**
* When a filePath exists check if it can be resolved.
*/
const resolveFilePath = async (
searchName: string,
filePath?: string,
): Promise<string | undefined> => {
const cwd = process.cwd();
if (!filePath) {
return;
}
let resolvedPath: string | undefined;
if (filePath.startsWith('npm:')) {
resolvedPath = await resolvePackage(filePath.replace('npm:', ''), cwd);
} else {
resolvedPath = resolve(cwd, filePath);
}
if (!resolvedPath || !(await isDirectory(resolvedPath))) {
return resolvedPath;
}
return resolve(resolvedPath, searchName);
};
/**
* Get the desired path to the configuration.
*/
const resolveConfigPathSync = (
cwd: string,
searchName: string,
filePath?: string,
): string | undefined => {
const resolvedFilePath = resolveFilePathSync(searchName, filePath);
if (resolvedFilePath) {
return resolvedFilePath;
}
if (searchName !== DEFAULT_SEARCH_NAME) {
const resolvedSearchName = resolve(cwd, searchName);
const absolutePath = isDirectorySync(resolvedSearchName)
? resolve(resolvedSearchName, 'tsconfig.json')
: resolvedSearchName;
return isFileSync(absolutePath) ? absolutePath : undefined;
}
if (isFileSync(cwd)) {
return resolve(cwd);
}
const configAbsolutePath = walkForTsConfigSync(cwd);
return configAbsolutePath ? resolve(configAbsolutePath) : undefined;
};
/**
* Get the desired path to the configuration.
*/
const resolveConfigPath = async (
cwd: string,
searchName: string,
filePath?: string,
): Promise<string | undefined> => {
const resolvedFilePath = await resolveFilePath(searchName, filePath);
if (resolvedFilePath) {
return resolvedFilePath;
}
if (searchName !== DEFAULT_SEARCH_NAME) {
const resolvedSearchName = resolve(cwd, searchName);
const absolutePath = (await isDirectory(resolvedSearchName))
? resolve(resolvedSearchName, 'tsconfig.json')
: resolvedSearchName;
return (await isFile(absolutePath)) ? absolutePath : undefined;
}
if (await isFile(cwd)) {
return resolve(cwd);
}
const configAbsolutePath = await walkForTsConfig(cwd);
return configAbsolutePath ? resolve(configAbsolutePath) : undefined;
};
/**
* Loads the `jsonString` and returns it as a TsConfigJson object.
*/
const parseTsConfigJson = (jsonString: string): TsConfigJson | undefined => {
try {
const json = JSON5.parse(jsonString);
return json && typeof json === 'object' ? json : undefined;
} catch {
return undefined;
}
};
/**
* Synchronously loads a tsconfig file while also resolving the `extends` path.
*/
const loadTsConfigSync = (
configFilePath: string,
extendedPaths: string[],
ignoreExtends = false,
): TsConfigJson | undefined => {
if (!isFileOrDirectorySync(configFilePath)) return undefined;
const configString = readFileSync(configFilePath, 'utf8');
const jsonString = StripBom(configString);
const config = parseTsConfigJson(jsonString);
let extendedConfig = config?.extends;
if (!config || !extendedConfig || ignoreExtends) return config;
let base: TsConfigJson;
if (parseFilePath(extendedConfig).isPackage) {
const newConfigPath = resolvePackageSync(extendedConfig);
if (!newConfigPath) {
return config;
} else if (isDirectorySync(newConfigPath)) {
extendedConfig = join(newConfigPath, DEFAULT_SEARCH_NAME);
} else if (isFileSync(newConfigPath)) {
extendedConfig = newConfigPath;
} else if (isFileSync(`${newConfigPath}.json`)) {
extendedConfig = `${newConfigPath}.json`;
}
if (extendedPaths.includes(extendedConfig)) {
return config;
}
extendedPaths.push(extendedConfig);
base = loadTsConfigSync(extendedConfig, extendedPaths) ?? {};
} else {
if (!extendedConfig.endsWith('.json')) {
extendedConfig += '.json';
}
const currentDir = dirname(configFilePath);
const extendedConfigPath = join(currentDir, extendedConfig);
if (extendedPaths.includes(extendedConfigPath)) {
return config;
}
extendedPaths.push(extendedConfigPath);
base = loadTsConfigSync(extendedConfigPath, extendedPaths) ?? {};
}
// baseUrl should be interpreted as relative to the base tsconfig, but we need
// to update it so it is relative to the original tsconfig being loaded
if (base?.compilerOptions?.baseUrl) {
const extendsDir = dirname(extendedConfig);
base.compilerOptions.baseUrl = join(
extendsDir,
base.compilerOptions.baseUrl,
);
}
return {
...base,
...config,
compilerOptions: {
...base.compilerOptions,
...config.compilerOptions,
},
};
};
/**
* Loads a tsconfig file while also resolving the `extends` path.
*/
const loadTsConfig = async (
configFilePath: string,
extendedPaths: string[],
ignoreExtends = false,
): Promise<TsConfigJson | undefined> => {
if (!(await isFileOrDirectory(configFilePath))) return undefined;
const configString = await readFile(configFilePath, 'utf8');
const jsonString = StripBom(configString);
const config = parseTsConfigJson(jsonString);
let extendedConfig = config?.extends;
if (!config || !extendedConfig || ignoreExtends) return config;
let base: TsConfigJson;
if (parseFilePath(extendedConfig).isPackage) {
const newConfigPath = await resolvePackage(extendedConfig);
if (!newConfigPath) {
return config;
} else if (await isDirectory(newConfigPath)) {
extendedConfig = join(newConfigPath, DEFAULT_SEARCH_NAME);
} else if (await isFile(newConfigPath)) {
extendedConfig = newConfigPath;
} else if (await isFile(`${newConfigPath}.json`)) {
extendedConfig = `${newConfigPath}.json`;
}
if (extendedPaths.includes(extendedConfig)) {
return config;
}
extendedPaths.push(extendedConfig);
base = (await loadTsConfig(extendedConfig, extendedPaths)) ?? {};
} else {
if (!extendedConfig.endsWith('.json')) {
extendedConfig += '.json';
}
const currentDir = dirname(configFilePath);
const extendedConfigPath = join(currentDir, extendedConfig);
if (extendedPaths.includes(extendedConfigPath)) {
return config;
}
extendedPaths.push(extendedConfigPath);
base = (await loadTsConfig(extendedConfigPath, extendedPaths)) ?? {};
}
// baseUrl should be interpreted as relative to the base tsconfig, but we need
// to update it so it is relative to the original tsconfig being loaded
if (base?.compilerOptions?.baseUrl) {
const extendsDir = dirname(extendedConfig);
base.compilerOptions.baseUrl = join(
extendsDir,
base.compilerOptions.baseUrl,
);
}
return {
...base,
...config,
compilerOptions: {
...base.compilerOptions,
...config.compilerOptions,
},
};
};
export interface TsConfigResolverOptions {
/**
* The absolute directory to start resolving from.
*
* @default `process.cwd()`
*/
cwd?: string;
/**
* The tsconfig file name to search for. This is where the `TsConfigJson`
* configuration object will be loaded from.
*
* @default 'tsconfig.json'
*/
searchName?: string;
/**
* A direct path to the tsconfig file you would like to load. The path will be
* relative to `cwd`. If it leads to a directory then the `searchName` will be
* appended.
*
* This also supports the `npm:` prefix which will find the given npm package
* directory, if it is installed.
*
* @default undefined
*/
filePath?: string | undefined;
/**
* The caching strategy to use. `'never'` or `'always'` or `'directory'` or
* `true` or `false`.
*
* `true` is the same as `'always'`
* `false` is the same as `'never'`
*
* @default 'never'
*
* @remarks
*
* Sometimes you'll want to run this module several times during runtime but
* it can be slow and expensive walk up the file tree for the tsconfig value
* every time.
*
* To help prevent unnecessary lookups there are custom caching strategies
* available. See {@link CacheStrategy}.
*/
cache?: CacheStrategyType | boolean;
/**
* When true will not automatically populate the `extends` argument. This is
* useful if all you want is the json object and not the fully resolved
* configuration.
*
* @default false
*/
ignoreExtends?: boolean;
}
type TsConfigResolverParams = SetOptional<
Required<Except<TsConfigResolverOptions, 'cache'>>,
'filePath'
> & { cache: CacheStrategyType };
export const CacheStrategy = {
/**
* Caching never happens and the returned value is always recalculated.
*/
Never: 'never',
/**
* The first time the `tsconfigResolver` method is run it will save a cached
* value (by `searchName`) which will be returned every time after that. This
* value will always be the same.
*/
Always: 'always',
/**
* The cache will be used when the same directory (and searchName) is being
* searched.
*/
Directory: 'directory',
} as const;
/**
* The available cache strategies as a union of strings.
*/
export type CacheStrategyType = typeof CacheStrategy[keyof typeof CacheStrategy];
const cacheObject = {
[CacheStrategy.Always]: new Map<string, TsConfigResult>(),
[CacheStrategy.Directory]: new Map<string, TsConfigResult>(),
};
/**
* Converts a boolean or string type into a cache strategy.
*/
const convertCacheToStrategy = (value: boolean | CacheStrategyType) =>
value === false
? CacheStrategy.Never
: value === true
? CacheStrategy.Always
: value;
/**
* Get the key to store in the cache.
*/
const cacheKey = ({
cache,
cwd,
searchName,
ignoreExtends,
}: Exclude<TsConfigResolverParams, 'filePath'>) =>
cache === CacheStrategy.Always
? `${searchName} - ${ignoreExtends}`
: `${join(cwd, searchName)} - ${ignoreExtends}`;
/**
* Based on the options passed in, retrieve the value from the cache or return
* undefined if the value still needs to be calculated.
*/
const getCache = (
options: TsConfigResolverParams,
): TsConfigResult | undefined => {
if (options.cache === CacheStrategy.Always) {
return cacheObject[CacheStrategy.Always].get(cacheKey(options));
}
if (options.cache === CacheStrategy.Directory) {
return cacheObject[CacheStrategy.Always].get(cacheKey(options));
}
return undefined;
};
/**
* Updates the cache with the provided result.
*/
const updateCache = (
options: TsConfigResolverParams,
result: TsConfigResult,
): void => {
if (options.cache === CacheStrategy.Always) {
cacheObject[CacheStrategy.Always].set(cacheKey(options), result);
} else if (options.cache === CacheStrategy.Directory) {
cacheObject[CacheStrategy.Always].set(cacheKey(options), result);
}
};
/**
* Clears the cache.
*/
export const clearCache = () => {
for (const map of Object.values(cacheObject)) {
map.clear();
}
};
/**
* Synchronously get the nearest tsconfig by walking up the directory.
*/
const getTsConfigResultSync = ({
cwd,
searchName,
filePath,
ignoreExtends,
}: Except<TsConfigResolverParams, 'cache'>): TsConfigResult => {
const configPath = resolveConfigPathSync(cwd, searchName, filePath);
if (!configPath) {
return {
exists: false,
reason: TsConfigErrorReason.NotFound,
};
}
// This path will be mutated to include all paths that have been found.
const extendedPaths: string[] = [];
const config = loadTsConfigSync(configPath, extendedPaths, ignoreExtends);
if (!config) {
return {
exists: false,
reason: TsConfigErrorReason.InvalidConfig,
path: configPath,
};
}
return {
exists: true,
path: configPath,
extendedPaths,
config,
isCircular: extendedPaths.includes(configPath),
};
};
/**
* Get the nearest tsconfig by walking up the directory.
*/
const getTsConfigResult = async ({
cwd,
searchName,
filePath,
ignoreExtends,
}: Except<TsConfigResolverParams, 'cache'>): Promise<TsConfigResult> => {
const configPath = await resolveConfigPath(cwd, searchName, filePath);
if (!configPath) {
return {
exists: false,
reason: TsConfigErrorReason.NotFound,
};
}
// This path will be mutated to include all paths that have been found.
const extendedPaths: string[] = [];
const config = await loadTsConfig(configPath, extendedPaths, ignoreExtends);
if (!config) {
return {
exists: false,
reason: TsConfigErrorReason.InvalidConfig,
path: configPath,
};
}
return {
exists: true,
path: configPath,
extendedPaths,
config,
isCircular: extendedPaths.includes(configPath),
};
};
export { TsConfigJson };
/**
* Resolve the `tsconfig` file synchronously. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @returns an object containing whether a configuration was found and is valid.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
export function tsconfigResolverSync({
filePath,
cwd = process.cwd(),
cache: shouldCache = filePath ? CacheStrategy.Always : CacheStrategy.Never,
searchName = DEFAULT_SEARCH_NAME,
ignoreExtends = false,
}: TsConfigResolverOptions = {}): TsConfigResult {
const cacheStrategy = convertCacheToStrategy(shouldCache);
const cache = getCache({
cwd,
cache: cacheStrategy,
searchName,
filePath,
ignoreExtends,
});
if (cache) {
return cache;
}
const result = getTsConfigResultSync({
cwd,
searchName,
filePath,
ignoreExtends,
});
updateCache(
{ cwd, cache: cacheStrategy, searchName, filePath, ignoreExtends },
result,
);
return result;
}
/**
* Resolve the `tsconfig` file. Walks up the file tree until it
* finds a file that matches the searchName.
*
* @param options - `TsConfigResolverOptions`.
*
* @remarks
*
* If a non-default caching strategy is provided the returned result might be
* from the cache instead.
*/
export async function tsconfigResolver({
filePath,
cwd = process.cwd(),
cache: shouldCache = filePath ? CacheStrategy.Always : CacheStrategy.Never,
searchName = DEFAULT_SEARCH_NAME,
ignoreExtends = false,
}: TsConfigResolverOptions = {}): Promise<TsConfigResult> {
const cacheStrategy = convertCacheToStrategy(shouldCache);
const cache = getCache({
cwd,
cache: cacheStrategy,
searchName,
filePath,
ignoreExtends,
});
if (cache) {
return cache;
}
const result = await getTsConfigResult({
cwd,
searchName,
filePath,
ignoreExtends,
});
updateCache(
{ cwd, cache: cacheStrategy, searchName, filePath, ignoreExtends },
result,
);
return result;
}