From 4a2274def58d1d41352b33f4e9c197d258fb5a36 Mon Sep 17 00:00:00 2001 From: "Nicholas C. Zakas" Date: Wed, 24 Apr 2024 11:23:25 -0700 Subject: [PATCH] feat: Add config-array package --- .github/workflows/release-please.yml | 37 +- .release-please-manifest.json | 3 +- packages/config-array/CHANGELOG.md | 283 +++ packages/config-array/LICENSE | 201 ++ packages/config-array/README.md | 342 +++ packages/config-array/jsr.json | 10 + packages/config-array/package.json | 50 + packages/config-array/rollup.config.js | 23 + packages/config-array/src/base-schema.js | 40 + packages/config-array/src/config-array.js | 1002 ++++++++ .../src/files-and-ignores-schema.js | 85 + packages/config-array/src/index.js | 6 + .../config-array/tests/config-array.test.js | 2149 +++++++++++++++++ packages/config-array/tsconfig.cjs.json | 9 + packages/config-array/tsconfig.esm.json | 4 + packages/config-array/tsconfig.json | 13 + 16 files changed, 4254 insertions(+), 3 deletions(-) create mode 100644 packages/config-array/CHANGELOG.md create mode 100644 packages/config-array/LICENSE create mode 100644 packages/config-array/README.md create mode 100644 packages/config-array/jsr.json create mode 100644 packages/config-array/package.json create mode 100644 packages/config-array/rollup.config.js create mode 100644 packages/config-array/src/base-schema.js create mode 100644 packages/config-array/src/config-array.js create mode 100644 packages/config-array/src/files-and-ignores-schema.js create mode 100644 packages/config-array/src/index.js create mode 100644 packages/config-array/tests/config-array.test.js create mode 100644 packages/config-array/tsconfig.cjs.json create mode 100644 packages/config-array/tsconfig.esm.json create mode 100644 packages/config-array/tsconfig.json diff --git a/.github/workflows/release-please.yml b/.github/workflows/release-please.yml index e433090e..ece717bf 100644 --- a/.github/workflows/release-please.yml +++ b/.github/workflows/release-please.yml @@ -38,7 +38,7 @@ jobs: if: ${{ steps.release.outputs.releases_created }} #----------------------------------------------------------------------------- - # @eslint/objects-schema + # @eslint/object-schema #----------------------------------------------------------------------------- - name: Publish @eslint/object-schema package to npm @@ -55,7 +55,7 @@ jobs: if: ${{ steps.release.outputs['packages/object-schema--release_created'] }} - name: Tweet Release Announcement - run: npx @humanwhocodes/tweet "@eslint/object-schema v${{ steps.release.outputs['packages/object-schema--major'] }}.${{ steps.release.outputs['packages/core--minor'] }}.${{ steps.release.outputs['packages/core--patch'] }} has been released!\n\n${{ github.event.repository.html_url }}/releases/tag/v${{ steps.release.outputs['packages/core--tag_name'] }}" + run: npx @humanwhocodes/tweet "@eslint/object-schema v${{ steps.release.outputs['packages/object-schema--major'] }}.${{ steps.release.outputs['packages/object-schema--minor'] }}.${{ steps.release.outputs['packages/object-schema--patch'] }} has been released!\n\n${{ github.event.repository.html_url }}/releases/tag/v${{ steps.release.outputs['packages/object-schema--tag_name'] }}" if: ${{ steps.release.outputs['packages/object-schema--release_created'] }} env: TWITTER_CONSUMER_KEY: ${{ secrets.TWITTER_CONSUMER_KEY }} @@ -69,3 +69,36 @@ jobs: env: MASTODON_ACCESS_TOKEN: ${{ secrets.MASTODON_ACCESS_TOKEN }} MASTODON_HOST: ${{ secrets.MASTODON_HOST }} + + #----------------------------------------------------------------------------- + # @eslint/config-array + #----------------------------------------------------------------------------- + + - name: Publish @eslint/config-array package to npm + run: npm publish -w packages/config-array + if: ${{ steps.release.outputs['packages/config-array--release_created'] }} + env: + NODE_AUTH_TOKEN: ${{secrets.NPM_TOKEN}} + + - name: Publish @eslint/config-array package to JSR + run: | + npm run build --if-present + npx jsr publish + working-directory: packages/config-array + if: ${{ steps.release.outputs['packages/config-array--release_created'] }} + + - name: Tweet Release Announcement + run: npx @humanwhocodes/tweet "@eslint/config-array v${{ steps.release.outputs['packages/config-array--major'] }}.${{ steps.release.outputs['packages/config-array--minor'] }}.${{ steps.release.outputs['packages/config-array--patch'] }} has been released!\n\n${{ github.event.repository.html_url }}/releases/tag/v${{ steps.release.outputs['packages/config-array--tag_name'] }}" + if: ${{ steps.release.outputs['packages/config-array--release_created'] }} + env: + TWITTER_CONSUMER_KEY: ${{ secrets.TWITTER_CONSUMER_KEY }} + TWITTER_CONSUMER_SECRET: ${{ secrets.TWITTER_CONSUMER_SECRET }} + TWITTER_ACCESS_TOKEN_KEY: ${{ secrets.TWITTER_ACCESS_TOKEN_KEY }} + TWITTER_ACCESS_TOKEN_SECRET: ${{ secrets.TWITTER_ACCESS_TOKEN_SECRET }} + + - name: Toot Release Announcement + run: npx @humanwhocodes/toot "@eslint/config-array v${{ steps.release.outputs['packages/config-array--major'] }}.${{ steps.release.outputs['packages/config-array--minor'] }}.${{ steps.release.outputs['packages/config-array--patch'] }} has been released!\n\n${{ github.event.repository.html_url }}/releases/tag/v${{ steps.release.outputs['packages/config-array--tag_name'] }}"' + if: ${{ steps.release.outputs['packages/config-array--release_created'] }} + env: + MASTODON_ACCESS_TOKEN: ${{ secrets.MASTODON_ACCESS_TOKEN }} + MASTODON_HOST: ${{ secrets.MASTODON_HOST }} diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 796c24c2..42ee473d 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,4 @@ { - "packages/object-schema": "2.0.3" + "packages/object-schema": "2.0.3", + "packages/config-array": "0.30.0" } diff --git a/packages/config-array/CHANGELOG.md b/packages/config-array/CHANGELOG.md new file mode 100644 index 00000000..4767e99b --- /dev/null +++ b/packages/config-array/CHANGELOG.md @@ -0,0 +1,283 @@ +# Changelog + +## [0.13.0](https://github.com/humanwhocodes/config-array/compare/v0.12.3...v0.13.0) (2024-04-17) + + +### Bug Fixes + +* Throw friendly message for non-object configs ([#136](https://github.com/humanwhocodes/config-array/issues/136)) ([be918b6](https://github.com/humanwhocodes/config-array/commit/be918b6fa636a671a025354af7bbc69fa02842f7)) +* Update release version for breaking change ([0b803d4](https://github.com/humanwhocodes/config-array/commit/0b803d41db6c93051f48b65325cb1b438c4b550b)) + + +### Miscellaneous Chores + +* Update release version ([5cacca6](https://github.com/humanwhocodes/config-array/commit/5cacca6e005bd27ea08e2f03692232f915d1a7bb)) + +## [0.12.3](https://github.com/humanwhocodes/config-array/compare/v0.12.2...v0.12.3) (2024-04-03) + + +### Bug Fixes + +* don't match config with `ignores` and `name` only ([#133](https://github.com/humanwhocodes/config-array/issues/133)) ([3dabb4d](https://github.com/humanwhocodes/config-array/commit/3dabb4db2072a86d9b567205626ba0ed537bea2f)) + +## [0.12.2](https://github.com/humanwhocodes/config-array/compare/v0.12.1...v0.12.2) (2024-04-02) + + +### Bug Fixes + +* ignore `name` field for global `ignores` ([#131](https://github.com/humanwhocodes/config-array/issues/131)) ([286f489](https://github.com/humanwhocodes/config-array/commit/286f48970f2b2c35c3fae14c5081d29ac23d11cc)) + +## [0.12.1](https://github.com/humanwhocodes/config-array/compare/v0.12.0...v0.12.1) (2024-04-01) + + +### Bug Fixes + +* **deps:** Ensure unnecessary files are not packaged ([6c26fef](https://github.com/humanwhocodes/config-array/commit/6c26fef4f5367eeba48ff782e44f914b47e278bf)) + +## [0.12.0](https://github.com/humanwhocodes/config-array/compare/v0.11.14...v0.12.0) (2024-04-01) + + +### Features + +* Report config name in error messages ([#128](https://github.com/humanwhocodes/config-array/issues/128)) ([58f8c9f](https://github.com/humanwhocodes/config-array/commit/58f8c9f8c06cbc6c67dfefe71b719bc6a940b7b3)) + +## [0.11.14](https://github.com/humanwhocodes/config-array/compare/v0.11.13...v0.11.14) (2024-01-10) + + +### Bug Fixes + +* behavior of global `ignores` ([#126](https://github.com/humanwhocodes/config-array/issues/126)) ([9b3c72c](https://github.com/humanwhocodes/config-array/commit/9b3c72c67ff41f77ee7df549d95c4ca45b36d1ed)) +* **deps:** Update object-schema ([8f0950a](https://github.com/humanwhocodes/config-array/commit/8f0950a253fd117e787e71f0c3bffe33942ce3a1)) + +## [0.11.13](https://github.com/humanwhocodes/config-array/compare/v0.11.12...v0.11.13) (2023-10-20) + + +### Bug Fixes + +* **deps:** Upgrade object-schema to restore custom properties on errors ([d6d0b6a](https://github.com/humanwhocodes/config-array/commit/d6d0b6a415ef191ef9acd9169aec0827b86dcad3)) + +## [0.11.12](https://github.com/humanwhocodes/config-array/compare/v0.11.11...v0.11.12) (2023-10-19) + + +### Bug Fixes + +* caching of ignored files ([#111](https://github.com/humanwhocodes/config-array/issues/111)) ([839d838](https://github.com/humanwhocodes/config-array/commit/839d838e607cf5fb69d1acd314d6bb7aa20bc042)) + +## [0.11.11](https://github.com/humanwhocodes/config-array/compare/v0.11.10...v0.11.11) (2023-08-29) + + +### Bug Fixes + +* validate `files` and `ignores` elements ([#103](https://github.com/humanwhocodes/config-array/issues/103)) ([c40894f](https://github.com/humanwhocodes/config-array/commit/c40894ff86d1635c45649ac1f3c03a274e2529d9)) + +## [0.11.10](https://github.com/humanwhocodes/config-array/compare/v0.11.9...v0.11.10) (2023-06-01) + + +### Bug Fixes + +* Allow directory-based ignores for files matches ([0163f31](https://github.com/humanwhocodes/config-array/commit/0163f313dbfe50d283042141dbad5958f9d5d2ad)) +* Revert allow directory-based ignores for files matches ([322ad01](https://github.com/humanwhocodes/config-array/commit/322ad011b7d4761205ae7f85c8fdb58574dbf388)) + +## [0.11.9](https://github.com/humanwhocodes/config-array/compare/v0.11.8...v0.11.9) (2023-05-12) + + +### Bug Fixes + +* Config with just ignores should not always be applied ([#89](https://github.com/humanwhocodes/config-array/issues/89)) ([5ed9c2c](https://github.com/humanwhocodes/config-array/commit/5ed9c2c1a13afb42cd7e9d3b1b247761cb7aa040)) + +## [0.11.8](https://github.com/humanwhocodes/config-array/compare/v0.11.7...v0.11.8) (2022-12-14) + + +### Bug Fixes + +* Ensure gitignore-style directory ignores ([#74](https://github.com/humanwhocodes/config-array/issues/74)) ([8e17f4a](https://github.com/humanwhocodes/config-array/commit/8e17f4a7378cb0b417e1103d60ef397b26d2f917)) + +## [0.11.7](https://github.com/humanwhocodes/config-array/compare/v0.11.6...v0.11.7) (2022-10-28) + + +### Bug Fixes + +* **deps:** Update minimatch to secure version ([3219294](https://github.com/humanwhocodes/config-array/commit/3219294bf9170c500ee9e212b59e17ef205b7c3c)) + +## [0.11.6](https://github.com/humanwhocodes/config-array/compare/v0.11.5...v0.11.6) (2022-10-21) + + +### Bug Fixes + +* Only apply universal patterns if others match. ([e69c8fd](https://github.com/humanwhocodes/config-array/commit/e69c8fdbb7696b406821bc723b86b4c5304c4260)) + +## [0.11.5](https://github.com/humanwhocodes/config-array/compare/v0.11.4...v0.11.5) (2022-10-17) + + +### Bug Fixes + +* Unignoring of directories should work ([e1c9dcd](https://github.com/humanwhocodes/config-array/commit/e1c9dcd05534619effe258596191ea9dc5bb37af)) + +## [0.11.4](https://github.com/humanwhocodes/config-array/compare/v0.11.3...v0.11.4) (2022-10-14) + + +### Bug Fixes + +* Ensure subdirectories of ignored directories are ignored ([0df450e](https://github.com/humanwhocodes/config-array/commit/0df450eabeb595ae22fe680ce3320dc47edb1e66)) + +## [0.11.3](https://github.com/humanwhocodes/config-array/compare/v0.11.2...v0.11.3) (2022-10-13) + + +### Bug Fixes + +* Ensure directories can be unignored. ([206404c](https://github.com/humanwhocodes/config-array/commit/206404c490d354a4f39ef9b4a6d0ceaec119abc5)) + +## [0.11.2](https://github.com/humanwhocodes/config-array/compare/v0.11.1...v0.11.2) (2022-10-03) + + +### Bug Fixes + +* Error conditions for isDirectoryIgnored ([0bd81f5](https://github.com/humanwhocodes/config-array/commit/0bd81f53b7c217d561f70709057c7d77f17e8c6d)) +* isDirectoryIgnored should match on relative path. ([3d1eaf6](https://github.com/humanwhocodes/config-array/commit/3d1eaf6389056215e27793cde9c2954c01c78df8)) +* isFileIgnored should call isDirectoryIgnored ([270d359](https://github.com/humanwhocodes/config-array/commit/270d359295f376edb0c73905f62a848284d34053)) + + +### Performance Improvements + +* Cache isDirectoryIgnored calls ([c5e6720](https://github.com/humanwhocodes/config-array/commit/c5e67208618e253c08bd320efeae4b1f63641e63)) + +## [0.11.1](https://github.com/humanwhocodes/config-array/compare/v0.11.0...v0.11.1) (2022-09-30) + + +### Bug Fixes + +* isDirectoryIgnored should not test negated patterns ([f6cdb68](https://github.com/humanwhocodes/config-array/commit/f6cdb688784901970fda72eb688eb1a00c44b09a)) + +## [0.11.0](https://github.com/humanwhocodes/config-array/compare/v0.10.7...v0.11.0) (2022-09-30) + + +### Features + +* Add isDirectoryIgnored; deprecated isIgnored ([e6942f2](https://github.com/humanwhocodes/config-array/commit/e6942f2ce075007d39f23530593b7adb19178a52)) + +## [0.10.7](https://github.com/humanwhocodes/config-array/compare/v0.10.6...v0.10.7) (2022-09-29) + + +### Bug Fixes + +* Cache negated patterns separately ([fef617b](https://github.com/humanwhocodes/config-array/commit/fef617b6999f9a4b5871d4525c82c4181bc96fb7)) + +## [0.10.6](https://github.com/humanwhocodes/config-array/compare/v0.10.5...v0.10.6) (2022-09-28) + + +### Performance Improvements + +* Cache Minimatch instances ([5cf9af7](https://github.com/humanwhocodes/config-array/commit/5cf9af7ecaf227d2106be0cebd92d7f5148867e6)) + +## [0.10.5](https://github.com/humanwhocodes/config-array/compare/v0.10.4...v0.10.5) (2022-09-21) + + +### Bug Fixes + +* Improve caching to improve performance ([#50](https://github.com/humanwhocodes/config-array/issues/50)) ([8a7e8ab](https://github.com/humanwhocodes/config-array/commit/8a7e8ab499bcbb10d7cbdd676197fc686966a64e)) + +### [0.10.4](https://www.github.com/humanwhocodes/config-array/compare/v0.10.3...v0.10.4) (2022-07-29) + + +### Bug Fixes + +* Global ignores only when no other keys ([1f6b6ae](https://www.github.com/humanwhocodes/config-array/commit/1f6b6ae89152c1ebe118f55e7ea05c37e7c960dc)) +* Re-introduce ignores fixes ([b3ec560](https://www.github.com/humanwhocodes/config-array/commit/b3ec560c485bec2f7420fd63a939448b49a073e3)) + +### [0.10.3](https://www.github.com/humanwhocodes/config-array/compare/v0.10.2...v0.10.3) (2022-07-20) + + +### Bug Fixes + +* Ensure preprocess method has correct 'this' value. ([f86933a](https://www.github.com/humanwhocodes/config-array/commit/f86933a072e5a4069bab2c1ce284dedf0efa715d)) + +### [0.10.2](https://www.github.com/humanwhocodes/config-array/compare/v0.10.1...v0.10.2) (2022-03-18) + + +### Bug Fixes + +* Files outside of basePath should be ignored ([fc4d7b2](https://www.github.com/humanwhocodes/config-array/commit/fc4d7b2e851959ab9ab84305f6c78c52e9cc2c3c)) + +### [0.10.1](https://www.github.com/humanwhocodes/config-array/compare/v0.10.0...v0.10.1) (2022-03-03) + + +### Bug Fixes + +* Explicit matching is required against files field ([ab4e428](https://www.github.com/humanwhocodes/config-array/commit/ab4e4282ecea994ef88d273dc47aa24bf3c6972e)) + +## [0.10.0](https://www.github.com/humanwhocodes/config-array/compare/v0.9.5...v0.10.0) (2022-03-01) + + +### Features + +* Add isExplicitMatch() method ([9ecd90e](https://www.github.com/humanwhocodes/config-array/commit/9ecd90e2a3e984633f535daa4da3cbfb96964fdd)) + +### [0.9.5](https://www.github.com/humanwhocodes/config-array/compare/v0.9.4...v0.9.5) (2022-02-23) + + +### Bug Fixes + +* Ensure dot directories are matched correctly ([6e8d180](https://www.github.com/humanwhocodes/config-array/commit/6e8d180f43cedf3c2072d8a1229470e9fafabf5b)) +* preprocessConfig should have correct 'this' value ([9641540](https://www.github.com/humanwhocodes/config-array/commit/96415402cf0012ccf8e4af6c7b934dfc1a058986)) + +### [0.9.4](https://www.github.com/humanwhocodes/config-array/compare/v0.9.3...v0.9.4) (2022-01-27) + + +### Bug Fixes + +* Negated patterns to work when files match ([398c811](https://www.github.com/humanwhocodes/config-array/commit/398c8119d359493dc7b82b40df4d92ea6528375f)) + +### [0.9.3](https://www.github.com/humanwhocodes/config-array/compare/v0.9.2...v0.9.3) (2022-01-26) + + +### Bug Fixes + +* Make negated ignore patterns work like gitignore ([4ee8e99](https://www.github.com/humanwhocodes/config-array/commit/4ee8e998436e2c4538b06476e0bead8a44fe5a1b)) + +### [0.9.2](https://www.github.com/humanwhocodes/config-array/compare/v0.9.1...v0.9.2) (2021-11-02) + + +### Bug Fixes + +* Object merging error by upgrading object-schema ([377d06d](https://www.github.com/humanwhocodes/config-array/commit/377d06d2a44d781b0bec70b3389c48b3d5a63f94)) + +### [0.9.1](https://www.github.com/humanwhocodes/config-array/compare/v0.9.0...v0.9.1) (2021-10-05) + + +### Bug Fixes + +* Properly build package for release ([168155f](https://www.github.com/humanwhocodes/config-array/commit/168155f3fed91ab35566c452efd28debf8ec2b85)) + +## [0.9.0](https://www.github.com/humanwhocodes/config-array/compare/v0.8.0...v0.9.0) (2021-10-04) + + +### Features + +* getConfig() now returns undefined when no configs match. ([a563b82](https://www.github.com/humanwhocodes/config-array/commit/a563b8255d4eb2bb7745314e3f00ef53792b343f)) + +## [0.8.0](https://www.github.com/humanwhocodes/config-array/compare/v0.7.0...v0.8.0) (2021-10-01) + + +### Features + +* Add isIgnored() method ([343e5a0](https://www.github.com/humanwhocodes/config-array/commit/343e5a0a9e32028bfc6c0bf1ec0c6badf74f47f9)) + + +### Bug Fixes + +* Ensure global ignores are honored ([343e5a0](https://www.github.com/humanwhocodes/config-array/commit/343e5a0a9e32028bfc6c0bf1ec0c6badf74f47f9)) + +## [0.7.0](https://www.github.com/humanwhocodes/config-array/compare/v0.6.0...v0.7.0) (2021-09-24) + + +### Features + +* Only object configs by default ([5645f24](https://www.github.com/humanwhocodes/config-array/commit/5645f241b2412a3263a02ef9e3a9bd19cc86035d)) + +## [0.6.0](https://www.github.com/humanwhocodes/config-array/compare/v0.5.0...v0.6.0) (2021-04-20) + + +### Features + +* Add the normalizeSync() method ([3e347f9](https://www.github.com/humanwhocodes/config-array/commit/3e347f9d77c5ca2b15995e75ff7bc4fb96b7d66e)) +* Allow async config functions ([a9def0f](https://www.github.com/humanwhocodes/config-array/commit/a9def0faf579c223349dfe08d2486756840538c3)) diff --git a/packages/config-array/LICENSE b/packages/config-array/LICENSE new file mode 100644 index 00000000..261eeb9e --- /dev/null +++ b/packages/config-array/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/packages/config-array/README.md b/packages/config-array/README.md new file mode 100644 index 00000000..d64784c1 --- /dev/null +++ b/packages/config-array/README.md @@ -0,0 +1,342 @@ +# Config Array + +by [Nicholas C. Zakas](https://humanwhocodes.com) + +If you find this useful, please consider supporting my work with a [donation](https://humanwhocodes.com/donate). + +## Description + +A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename. + +## Background + +In 2019, I submitted an [ESLint RFC](https://github.com/eslint/rfcs/pull/9) proposing a new way of configuring ESLint. The goal was to streamline what had become an increasingly complicated configuration process. Over several iterations, this proposal was eventually born. + +The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example: + +```js +export default [ + + // match all JSON files + { + name: "JSON Handler", + files: ["**/*.json"], + handler: jsonHandler + }, + + // match only package.json + { + name: "package.json Handler", + files: ["package.json"], + handler: packageJsonHandler + } +]; +``` + +In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins). + +## Installation + +You can install the package using npm or Yarn: + +```bash +npm install @humanwhocodes/config-array --save + +# or + +yarn add @humanwhocodes/config-array +``` + +## Usage + +First, import the `ConfigArray` constructor: + +```js +import { ConfigArray } from "@humanwhocodes/config-array"; + +// or using CommonJS + +const { ConfigArray } = require("@humanwhocodes/config-array"); +``` + +When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example: + +```js +const configFilename = path.resolve(process.cwd(), "my.config.js"); +const { default: rawConfigs } = await import(configFilename); +const configs = new ConfigArray(rawConfigs, { + + // the path to match filenames from + basePath: process.cwd(), + + // additional items in each config + schema: mySchema +}); +``` + +This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, and `name`. + +### Specifying a Schema + +The `schema` option is required for you to use additional properties in config objects. The schema is an object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@humanwhocodes/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example: + +```js +const configFilename = path.resolve(process.cwd(), "my.config.js"); +const { default: rawConfigs } = await import(configFilename); + +const mySchema = { + + // define the handler key in configs + handler: { + required: true, + merge(a, b) { + if (!b) return a; + if (!a) return b; + }, + validate(value) { + if (typeof value !== "function") { + throw new TypeError("Function expected."); + } + } + } +}; + +const configs = new ConfigArray(rawConfigs, { + + // the path to match filenames from + basePath: process.cwd(), + + // additional item schemas in each config + schema: mySchema, + + // additional config types supported (default: []) + extraConfigTypes: ["array", "function"]; +}); +``` + +### Config Arrays + +Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as: + +```js +export default [ + + // JS config + { + files: ["**/*.js"], + handler: jsHandler + }, + + // JSON configs + [ + + // match all JSON files + { + name: "JSON Handler", + files: ["**/*.json"], + handler: jsonHandler + }, + + // match only package.json + { + name: "package.json Handler", + files: ["package.json"], + handler: packageJsonHandler + } + ], + + // filename must match function + { + files: [ filePath => filePath.endsWith(".md") ], + handler: markdownHandler + }, + + // filename must match all patterns in subarray + { + files: [ ["*.test.*", "*.js"] ], + handler: jsTestHandler + }, + + // filename must not match patterns beginning with ! + { + name: "Non-JS files", + files: ["!*.js"], + settings: { + js: false + } + } +]; +``` + +In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same. + +If the `files` array contains a function, then that function is called with the absolute path of the file and is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.) + +If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used. + +If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically get a `settings.js` property set to `false`. + +You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example: + +```js +export default [ + + // Always ignored + { + ignores: ["**/.git/**", "**/node_modules/**"] + }, + + // .eslintrc.js file is ignored only when .js file matches + { + files: ["**/*.js"], + ignores: [".eslintrc.js"] + handler: jsHandler + } +]; +``` + +You can use negated patterns in `ignores` to exclude a file that was already ignored, such as: + +```js +export default [ + + // Ignore all JSON files except tsconfig.json + { + files: ["**/*"], + ignores: ["**/*.json", "!tsconfig.json"] + }, + +]; +``` + +### Config Functions + +Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example: + +```js +export default [ + + // JS config + { + files: ["**/*.js"], + handler: jsHandler + }, + + // JSON configs + function (context) { + return [ + + // match all JSON files + { + name: context.name + " JSON Handler", + files: ["**/*.json"], + handler: jsonHandler + }, + + // match only package.json + { + name: context.name + " package.json Handler", + files: ["package.json"], + handler: packageJsonHandler + } + ]; + } +]; +``` + +When a config array is normalized, each function is executed and replaced in the config array with the return value. + +**Note:** Config functions can also be async. + +### Normalizing Config Arrays + +Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values. + +To normalize a config array, call the `normalize()` method and pass in a context object: + +```js +await configs.normalize({ + name: "MyApp" +}); +``` + +The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable. + +If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise: + +```js +await configs.normalizeSync({ + name: "MyApp" +}); +``` + +**Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy. + +### Getting Config for a File + +To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for: + +```js +// pass in absolute filename +const fileConfig = configs.getConfig(path.resolve(process.cwd(), "package.json")); +``` + +The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed. + +A few things to keep in mind: + +* You must pass in the absolute filename to get a config for. +* The returned config object never has `files`, `ignores`, or `name` properties; the only properties on the object will be the other configuration options specified. +* The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation. +* A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry ending with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches. + +## Determining Ignored Paths + +You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the absolute path of any file, as in this example: + +```js +const ignored = configs.isFileIgnored('/foo/bar/baz.txt'); +``` + +A file is considered ignored if any of the following is true: + +* **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored. +* **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored. +* **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +* **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +* **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored. + +For directories, use the `isDirectoryIgnored()` method and pass in the absolute path of any directory, as in this example: + +```js +const ignored = configs.isDirectoryIgnored('/foo/bar/'); +``` + +A directory is considered ignored if any of the following is true: + +* **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored. +* **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored. +* **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +* **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored. +* **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored. + +**Important:** A pattern such as `foo/**` means that `foo` and `foo/` are *not* ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`. + +## Caching Mechanisms + +Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways: + +1. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in. +2. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`. + +## Acknowledgements + +The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from: + +* Teddy Katz (@not-an-aardvark) +* Toru Nagashima (@mysticatea) +* Kai Cataldo (@kaicataldo) + +## License + +Apache 2.0 diff --git a/packages/config-array/jsr.json b/packages/config-array/jsr.json new file mode 100644 index 00000000..8e20ed22 --- /dev/null +++ b/packages/config-array/jsr.json @@ -0,0 +1,10 @@ +{ + "name": "@eslint/config-array", + "version": "0.12.3", + "exports": "./dist/esm/index.js", + "publish": { + "exclude": [ + "!dist" + ] + } +} diff --git a/packages/config-array/package.json b/packages/config-array/package.json new file mode 100644 index 00000000..cfd57892 --- /dev/null +++ b/packages/config-array/package.json @@ -0,0 +1,50 @@ +{ + "name": "@eslint/config-array", + "version": "0.12.3", + "description": "Glob-based configuration matching.", + "author": "Nicholas C. Zakas", + "type": "module", + "exports": { + "require": { + "types": "./dist/cjs/index.d.cts", + "default": "./dist/cjs/index.cjs" + }, + "import": { + "types": "./dist/esm/index.d.ts", + "default": "./dist/esm/index.js" + } + }, + "repository": { + "type": "git", + "url": "git+https://github.com/eslint/rewrite.git" + }, + "bugs": { + "url": "https://github.com/eslint/rewrite/issues" + }, + "homepage": "https://github.com/eslint/rewrite#readme", + "scripts": { + "build": "rollup -c", + "prepare": "npm run build", + "test": "mocha tests/" + }, + "keywords": [ + "configuration", + "configarray", + "config file" + ], + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.0.3", + "debug": "^4.3.1", + "minimatch": "^3.0.5" + }, + "devDependencies": { + "mocha": "^10.4.0", + "rollup": "^4.16.2", + "typescript": "^5.4.5", + "rollup-plugin-copy": "^3.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } +} diff --git a/packages/config-array/rollup.config.js b/packages/config-array/rollup.config.js new file mode 100644 index 00000000..804b7954 --- /dev/null +++ b/packages/config-array/rollup.config.js @@ -0,0 +1,23 @@ +import copy from "rollup-plugin-copy"; + +export default { + input: 'src/index.js', + output: [ + { + file: 'dist/cjs/index.cjs', + format: 'cjs' + }, + { + file: 'dist/esm/index.js', + format: 'esm' + } + ], + plugins: [ + copy({ + targets: [ + { src: 'src/types.ts', dest: 'dist/cjs' }, + { src: 'src/types.ts', dest: 'dist/esm' } + ] + }) + ] +}; diff --git a/packages/config-array/src/base-schema.js b/packages/config-array/src/base-schema.js new file mode 100644 index 00000000..dd7ece00 --- /dev/null +++ b/packages/config-array/src/base-schema.js @@ -0,0 +1,40 @@ +/** + * @fileoverview ConfigSchema + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const NOOP_STRATEGY = { + required: false, + merge() { + return undefined; + }, + validate() { } +}; + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The base schema that every ConfigArray uses. + * @type Object + */ +export const baseSchema = Object.freeze({ + name: { + required: false, + merge() { + return undefined; + }, + validate(value) { + if (typeof value !== 'string') { + throw new TypeError('Property must be a string.'); + } + } + }, + files: NOOP_STRATEGY, + ignores: NOOP_STRATEGY +}); diff --git a/packages/config-array/src/config-array.js b/packages/config-array/src/config-array.js new file mode 100644 index 00000000..60f02939 --- /dev/null +++ b/packages/config-array/src/config-array.js @@ -0,0 +1,1002 @@ +/** + * @fileoverview ConfigArray + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Imports +//------------------------------------------------------------------------------ + +import path from 'path'; +import minimatch from 'minimatch'; +import createDebug from 'debug'; + +import { ObjectSchema } from '@humanwhocodes/object-schema'; +import { baseSchema } from './base-schema.js'; +import { filesAndIgnoresSchema } from './files-and-ignores-schema.js'; + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +const Minimatch = minimatch.Minimatch; +const minimatchCache = new Map(); +const negatedMinimatchCache = new Map(); +const debug = createDebug('@hwc/config-array'); + +const MINIMATCH_OPTIONS = { + // matchBase: true, + dot: true +}; + +const CONFIG_TYPES = new Set(['array', 'function']); + +/** + * Fields that are considered metadata and not part of the config object. + */ +const META_FIELDS = new Set(['name']); + +const FILES_AND_IGNORES_SCHEMA = new ObjectSchema(filesAndIgnoresSchema); + +/** + * Wrapper error for config validation errors that adds a name to the front of the + * error message. + */ +class ConfigError extends Error { + + /** + * Creates a new instance. + * @param {string} name The config object name causing the error. + * @param {number} index The index of the config object in the array. + * @param {Error} source The source error. + */ + constructor(name, index, { cause, message }) { + + + const finalMessage = message || cause.message; + + super(`Config ${name}: ${finalMessage}`, { cause }); + + // copy over custom properties that aren't represented + if (cause) { + for (const key of Object.keys(cause)) { + if (!(key in this)) { + this[key] = cause[key]; + } + } + } + + /** + * The name of the error. + * @type {string} + * @readonly + */ + this.name = 'ConfigError'; + + /** + * The index of the config object in the array. + * @type {number} + * @readonly + */ + this.index = index; + } +} + +/** + * Gets the name of a config object. + * @param {object} config The config object to get the name of. + * @returns {string} The name of the config object. + */ +function getConfigName(config) { + if (config && typeof config.name === 'string' && config.name) { + return `"${config.name}"`; + } + + return '(unnamed)'; +} + +/** + * Rethrows a config error with additional information about the config object. + * @param {object} config The config object to get the name of. + * @param {number} index The index of the config object in the array. + * @param {Error} error The error to rethrow. + * @throws {ConfigError} When the error is rethrown for a config. + */ +function rethrowConfigError(config, index, error) { + const configName = getConfigName(config); + throw new ConfigError(configName, index, error); +} + +/** + * Shorthand for checking if a value is a string. + * @param {any} value The value to check. + * @returns {boolean} True if a string, false if not. + */ +function isString(value) { + return typeof value === 'string'; +} + +/** + * Creates a function that asserts that the config is valid + * during normalization. This checks that the config is not nullish + * and that files and ignores keys of a config object are valid as per base schema. + * @param {Object} config The config object to check. + * @param {number} index The index of the config object in the array. + * @returns {void} + * @throws {ConfigError} If the files and ignores keys of a config object are not valid. + */ +function assertValidBaseConfig(config, index) { + + if (config === null) { + throw new ConfigError(getConfigName(config), index, { message: 'Unexpected null config.' }); + } + + if (config === undefined) { + throw new ConfigError(getConfigName(config), index, { message: 'Unexpected undefined config.' }); + } + + if (typeof config !== 'object') { + throw new ConfigError(getConfigName(config), index, { message: 'Unexpected non-object config.' }); + } + + const validateConfig = { }; + + if ('files' in config) { + validateConfig.files = config.files; + } + + if ('ignores' in config) { + validateConfig.ignores = config.ignores; + } + + try { + FILES_AND_IGNORES_SCHEMA.validate(validateConfig); + } catch (validationError) { + rethrowConfigError(config, index, { cause: validationError }); + } +} + +/** + * Wrapper around minimatch that caches minimatch patterns for + * faster matching speed over multiple file path evaluations. + * @param {string} filepath The file path to match. + * @param {string} pattern The glob pattern to match against. + * @param {object} options The minimatch options to use. + * @returns + */ +function doMatch(filepath, pattern, options = {}) { + + let cache = minimatchCache; + + if (options.flipNegate) { + cache = negatedMinimatchCache; + } + + let matcher = cache.get(pattern); + + if (!matcher) { + matcher = new Minimatch(pattern, Object.assign({}, MINIMATCH_OPTIONS, options)); + cache.set(pattern, matcher); + } + + return matcher.match(filepath); +} + +/** + * Normalizes a `ConfigArray` by flattening it and executing any functions + * that are found inside. + * @param {Array} items The items in a `ConfigArray`. + * @param {Object} context The context object to pass into any function + * found. + * @param {Array} extraConfigTypes The config types to check. + * @returns {Promise} A flattened array containing only config objects. + * @throws {TypeError} When a config function returns a function. + */ +async function normalize(items, context, extraConfigTypes) { + + const allowFunctions = extraConfigTypes.includes('function'); + const allowArrays = extraConfigTypes.includes('array'); + + async function* flatTraverse(array) { + for (let item of array) { + if (typeof item === 'function') { + if (!allowFunctions) { + throw new TypeError('Unexpected function.'); + } + + item = item(context); + if (item.then) { + item = await item; + } + } + + if (Array.isArray(item)) { + if (!allowArrays) { + throw new TypeError('Unexpected array.'); + } + yield* flatTraverse(item); + } else if (typeof item === 'function') { + throw new TypeError('A config function can only return an object or array.'); + } else { + yield item; + } + } + } + + /* + * Async iterables cannot be used with the spread operator, so we need to manually + * create the array to return. + */ + const asyncIterable = await flatTraverse(items); + const configs = []; + + for await (const config of asyncIterable) { + configs.push(config); + } + + return configs; +} + +/** + * Normalizes a `ConfigArray` by flattening it and executing any functions + * that are found inside. + * @param {Array} items The items in a `ConfigArray`. + * @param {Object} context The context object to pass into any function + * found. + * @param {Array} extraConfigTypes The config types to check. + * @returns {Array} A flattened array containing only config objects. + * @throws {TypeError} When a config function returns a function. + */ +function normalizeSync(items, context, extraConfigTypes) { + + const allowFunctions = extraConfigTypes.includes('function'); + const allowArrays = extraConfigTypes.includes('array'); + + function* flatTraverse(array) { + for (let item of array) { + if (typeof item === 'function') { + + if (!allowFunctions) { + throw new TypeError('Unexpected function.'); + } + + item = item(context); + if (item.then) { + throw new TypeError('Async config functions are not supported.'); + } + } + + if (Array.isArray(item)) { + + if (!allowArrays) { + throw new TypeError('Unexpected array.'); + } + + yield* flatTraverse(item); + } else if (typeof item === 'function') { + throw new TypeError('A config function can only return an object or array.'); + } else { + yield item; + } + } + } + + return [...flatTraverse(items)]; +} + +/** + * Determines if a given file path should be ignored based on the given + * matcher. + * @param {Array boolean>} ignores The ignore patterns to check. + * @param {string} filePath The absolute path of the file to check. + * @param {string} relativeFilePath The relative path of the file to check. + * @returns {boolean} True if the path should be ignored and false if not. + */ +function shouldIgnorePath(ignores, filePath, relativeFilePath) { + + // all files outside of the basePath are ignored + if (relativeFilePath.startsWith('..')) { + return true; + } + + return ignores.reduce((ignored, matcher) => { + + if (!ignored) { + + if (typeof matcher === 'function') { + return matcher(filePath); + } + + // don't check negated patterns because we're not ignored yet + if (!matcher.startsWith('!')) { + return doMatch(relativeFilePath, matcher); + } + + // otherwise we're still not ignored + return false; + + } + + // only need to check negated patterns because we're ignored + if (typeof matcher === 'string' && matcher.startsWith('!')) { + return !doMatch(relativeFilePath, matcher, { + flipNegate: true + }); + } + + return ignored; + + }, false); + +} + +/** + * Determines if a given file path is matched by a config based on + * `ignores` only. + * @param {string} filePath The absolute file path to check. + * @param {string} basePath The base path for the config. + * @param {Object} config The config object to check. + * @returns {boolean} True if the file path is matched by the config, + * false if not. + */ +function pathMatchesIgnores(filePath, basePath, config) { + + /* + * For both files and ignores, functions are passed the absolute + * file path while strings are compared against the relative + * file path. + */ + const relativeFilePath = path.relative(basePath, filePath); + + return Object.keys(config).filter(key => !META_FIELDS.has(key)).length > 1 && + !shouldIgnorePath(config.ignores, filePath, relativeFilePath); +} + + +/** + * Determines if a given file path is matched by a config. If the config + * has no `files` field, then it matches; otherwise, if a `files` field + * is present then we match the globs in `files` and exclude any globs in + * `ignores`. + * @param {string} filePath The absolute file path to check. + * @param {string} basePath The base path for the config. + * @param {Object} config The config object to check. + * @returns {boolean} True if the file path is matched by the config, + * false if not. + */ +function pathMatches(filePath, basePath, config) { + + /* + * For both files and ignores, functions are passed the absolute + * file path while strings are compared against the relative + * file path. + */ + const relativeFilePath = path.relative(basePath, filePath); + + // match both strings and functions + const match = pattern => { + + if (isString(pattern)) { + return doMatch(relativeFilePath, pattern); + } + + if (typeof pattern === 'function') { + return pattern(filePath); + } + + throw new TypeError(`Unexpected matcher type ${pattern}.`); + }; + + // check for all matches to config.files + let filePathMatchesPattern = config.files.some(pattern => { + if (Array.isArray(pattern)) { + return pattern.every(match); + } + + return match(pattern); + }); + + /* + * If the file path matches the config.files patterns, then check to see + * if there are any files to ignore. + */ + if (filePathMatchesPattern && config.ignores) { + filePathMatchesPattern = !shouldIgnorePath(config.ignores, filePath, relativeFilePath); + } + + return filePathMatchesPattern; +} + +/** + * Ensures that a ConfigArray has been normalized. + * @param {ConfigArray} configArray The ConfigArray to check. + * @returns {void} + * @throws {Error} When the `ConfigArray` is not normalized. + */ +function assertNormalized(configArray) { + // TODO: Throw more verbose error + if (!configArray.isNormalized()) { + throw new Error('ConfigArray must be normalized to perform this operation.'); + } +} + +/** + * Ensures that config types are valid. + * @param {Array} extraConfigTypes The config types to check. + * @returns {void} + * @throws {Error} When the config types array is invalid. + */ +function assertExtraConfigTypes(extraConfigTypes) { + if (extraConfigTypes.length > 2) { + throw new TypeError('configTypes must be an array with at most two items.'); + } + + for (const configType of extraConfigTypes) { + if (!CONFIG_TYPES.has(configType)) { + throw new TypeError(`Unexpected config type "${configType}" found. Expected one of: "object", "array", "function".`); + } + } +} + +//------------------------------------------------------------------------------ +// Public Interface +//------------------------------------------------------------------------------ + +export const ConfigArraySymbol = { + isNormalized: Symbol('isNormalized'), + configCache: Symbol('configCache'), + schema: Symbol('schema'), + finalizeConfig: Symbol('finalizeConfig'), + preprocessConfig: Symbol('preprocessConfig') +}; + +// used to store calculate data for faster lookup +const dataCache = new WeakMap(); + +/** + * Represents an array of config objects and provides method for working with + * those config objects. + */ +export class ConfigArray extends Array { + + /** + * Creates a new instance of ConfigArray. + * @param {Iterable|Function|Object} configs An iterable yielding config + * objects, or a config function, or a config object. + * @param {string} [options.basePath=""] The path of the config file + * @param {boolean} [options.normalized=false] Flag indicating if the + * configs have already been normalized. + * @param {Object} [options.schema] The additional schema + * definitions to use for the ConfigArray schema. + * @param {Array} [options.configTypes] List of config types supported. + */ + constructor(configs, { + basePath = '', + normalized = false, + schema: customSchema, + extraConfigTypes = [] + } = {} + ) { + super(); + + /** + * Tracks if the array has been normalized. + * @property isNormalized + * @type {boolean} + * @private + */ + this[ConfigArraySymbol.isNormalized] = normalized; + + /** + * The schema used for validating and merging configs. + * @property schema + * @type ObjectSchema + * @private + */ + this[ConfigArraySymbol.schema] = new ObjectSchema( + Object.assign({}, customSchema, baseSchema) + ); + + /** + * The path of the config file that this array was loaded from. + * This is used to calculate filename matches. + * @property basePath + * @type {string} + */ + this.basePath = basePath; + + assertExtraConfigTypes(extraConfigTypes); + + /** + * The supported config types. + * @property configTypes + * @type {Array} + */ + this.extraConfigTypes = Object.freeze([...extraConfigTypes]); + + /** + * A cache to store calculated configs for faster repeat lookup. + * @property configCache + * @type {Map} + * @private + */ + this[ConfigArraySymbol.configCache] = new Map(); + + // init cache + dataCache.set(this, { + explicitMatches: new Map(), + directoryMatches: new Map(), + files: undefined, + ignores: undefined + }); + + // load the configs into this array + if (Array.isArray(configs)) { + this.push(...configs); + } else { + this.push(configs); + } + + } + + /** + * Prevent normal array methods from creating a new `ConfigArray` instance. + * This is to ensure that methods such as `slice()` won't try to create a + * new instance of `ConfigArray` behind the scenes as doing so may throw + * an error due to the different constructor signature. + * @returns {Function} The `Array` constructor. + */ + static get [Symbol.species]() { + return Array; + } + + /** + * Returns the `files` globs from every config object in the array. + * This can be used to determine which files will be matched by a + * config array or to use as a glob pattern when no patterns are provided + * for a command line interface. + * @returns {Array} An array of matchers. + */ + get files() { + + assertNormalized(this); + + // if this data has been cached, retrieve it + const cache = dataCache.get(this); + + if (cache.files) { + return cache.files; + } + + // otherwise calculate it + + const result = []; + + for (const config of this) { + if (config.files) { + config.files.forEach(filePattern => { + result.push(filePattern); + }); + } + } + + // store result + cache.files = result; + dataCache.set(this, cache); + + return result; + } + + /** + * Returns ignore matchers that should always be ignored regardless of + * the matching `files` fields in any configs. This is necessary to mimic + * the behavior of things like .gitignore and .eslintignore, allowing a + * globbing operation to be faster. + * @returns {string[]} An array of string patterns and functions to be ignored. + */ + get ignores() { + + assertNormalized(this); + + // if this data has been cached, retrieve it + const cache = dataCache.get(this); + + if (cache.ignores) { + return cache.ignores; + } + + // otherwise calculate it + + const result = []; + + for (const config of this) { + + /* + * We only count ignores if there are no other keys in the object. + * In this case, it acts list a globally ignored pattern. If there + * are additional keys, then ignores act like exclusions. + */ + if (config.ignores && Object.keys(config).filter(key => !META_FIELDS.has(key)).length === 1) { + result.push(...config.ignores); + } + } + + // store result + cache.ignores = result; + dataCache.set(this, cache); + + return result; + } + + /** + * Indicates if the config array has been normalized. + * @returns {boolean} True if the config array is normalized, false if not. + */ + isNormalized() { + return this[ConfigArraySymbol.isNormalized]; + } + + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {ConfigContext} context The context object for config functions. + * @returns {Promise} The current ConfigArray instance. + */ + async normalize(context = {}) { + + if (!this.isNormalized()) { + const normalizedConfigs = await normalize(this, context, this.extraConfigTypes); + this.length = 0; + this.push(...normalizedConfigs.map(this[ConfigArraySymbol.preprocessConfig].bind(this))); + this.forEach(assertValidBaseConfig); + this[ConfigArraySymbol.isNormalized] = true; + + // prevent further changes + Object.freeze(this); + } + + return this; + } + + /** + * Normalizes a config array by flattening embedded arrays and executing + * config functions. + * @param {ConfigContext} context The context object for config functions. + * @returns {ConfigArray} The current ConfigArray instance. + */ + normalizeSync(context = {}) { + + if (!this.isNormalized()) { + const normalizedConfigs = normalizeSync(this, context, this.extraConfigTypes); + this.length = 0; + this.push(...normalizedConfigs.map(this[ConfigArraySymbol.preprocessConfig].bind(this))); + this.forEach(assertValidBaseConfig); + this[ConfigArraySymbol.isNormalized] = true; + + // prevent further changes + Object.freeze(this); + } + + return this; + } + + /** + * Finalizes the state of a config before being cached and returned by + * `getConfig()`. Does nothing by default but is provided to be + * overridden by subclasses as necessary. + * @param {Object} config The config to finalize. + * @returns {Object} The finalized config. + */ + [ConfigArraySymbol.finalizeConfig](config) { + return config; + } + + /** + * Preprocesses a config during the normalization process. This is the + * method to override if you want to convert an array item before it is + * validated for the first time. For example, if you want to replace a + * string with an object, this is the method to override. + * @param {Object} config The config to preprocess. + * @returns {Object} The config to use in place of the argument. + */ + [ConfigArraySymbol.preprocessConfig](config) { + return config; + } + + /** + * Determines if a given file path explicitly matches a `files` entry + * and also doesn't match an `ignores` entry. Configs that don't have + * a `files` property are not considered an explicit match. + * @param {string} filePath The complete path of a file to check. + * @returns {boolean} True if the file path matches a `files` entry + * or false if not. + */ + isExplicitMatch(filePath) { + + assertNormalized(this); + + const cache = dataCache.get(this); + + // first check the cache to avoid duplicate work + let result = cache.explicitMatches.get(filePath); + + if (typeof result == 'boolean') { + return result; + } + + // TODO: Maybe move elsewhere? Maybe combine with getConfig() logic? + const relativeFilePath = path.relative(this.basePath, filePath); + + if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) { + debug(`Ignoring ${filePath}`); + + // cache and return result + cache.explicitMatches.set(filePath, false); + return false; + } + + // filePath isn't automatically ignored, so try to find a match + + for (const config of this) { + + if (!config.files) { + continue; + } + + if (pathMatches(filePath, this.basePath, config)) { + debug(`Matching config found for ${filePath}`); + cache.explicitMatches.set(filePath, true); + return true; + } + } + + return false; + } + + /** + * Returns the config object for a given file path. + * @param {string} filePath The complete path of a file to get a config for. + * @returns {Object} The config object for this file. + */ + getConfig(filePath) { + + assertNormalized(this); + + const cache = this[ConfigArraySymbol.configCache]; + + // first check the cache for a filename match to avoid duplicate work + if (cache.has(filePath)) { + return cache.get(filePath); + } + + let finalConfig; + + // next check to see if the file should be ignored + + // check if this should be ignored due to its directory + if (this.isDirectoryIgnored(path.dirname(filePath))) { + debug(`Ignoring ${filePath} based on directory pattern`); + + // cache and return result - finalConfig is undefined at this point + cache.set(filePath, finalConfig); + return finalConfig; + } + + // TODO: Maybe move elsewhere? + const relativeFilePath = path.relative(this.basePath, filePath); + + if (shouldIgnorePath(this.ignores, filePath, relativeFilePath)) { + debug(`Ignoring ${filePath} based on file pattern`); + + // cache and return result - finalConfig is undefined at this point + cache.set(filePath, finalConfig); + return finalConfig; + } + + // filePath isn't automatically ignored, so try to construct config + + const matchingConfigIndices = []; + let matchFound = false; + const universalPattern = /\/\*{1,2}$/; + + this.forEach((config, index) => { + + if (!config.files) { + + if (!config.ignores) { + debug(`Anonymous universal config found for ${filePath}`); + matchingConfigIndices.push(index); + return; + } + + if (pathMatchesIgnores(filePath, this.basePath, config)) { + debug(`Matching config found for ${filePath} (based on ignores: ${config.ignores})`); + matchingConfigIndices.push(index); + return; + } + + debug(`Skipped config found for ${filePath} (based on ignores: ${config.ignores})`); + return; + } + + /* + * If a config has a files pattern ending in /** or /*, and the + * filePath only matches those patterns, then the config is only + * applied if there is another config where the filePath matches + * a file with a specific extensions such as *.js. + */ + + const universalFiles = config.files.filter( + pattern => universalPattern.test(pattern) + ); + + // universal patterns were found so we need to check the config twice + if (universalFiles.length) { + + debug('Universal files patterns found. Checking carefully.'); + + const nonUniversalFiles = config.files.filter( + pattern => !universalPattern.test(pattern) + ); + + // check that the config matches without the non-universal files first + if ( + nonUniversalFiles.length && + pathMatches( + filePath, this.basePath, + { files: nonUniversalFiles, ignores: config.ignores } + ) + ) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + matchFound = true; + return; + } + + // if there wasn't a match then check if it matches with universal files + if ( + universalFiles.length && + pathMatches( + filePath, this.basePath, + { files: universalFiles, ignores: config.ignores } + ) + ) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + return; + } + + // if we make here, then there was no match + return; + } + + // the normal case + if (pathMatches(filePath, this.basePath, config)) { + debug(`Matching config found for ${filePath}`); + matchingConfigIndices.push(index); + matchFound = true; + return; + } + + }); + + // if matching both files and ignores, there will be no config to create + if (!matchFound) { + debug(`No matching configs found for ${filePath}`); + + // cache and return result - finalConfig is undefined at this point + cache.set(filePath, finalConfig); + return finalConfig; + } + + // check to see if there is a config cached by indices + finalConfig = cache.get(matchingConfigIndices.toString()); + + if (finalConfig) { + + // also store for filename for faster lookup next time + cache.set(filePath, finalConfig); + + return finalConfig; + } + + // otherwise construct the config + + finalConfig = matchingConfigIndices.reduce((result, index) => { + try { + return this[ConfigArraySymbol.schema].merge(result, this[index]); + } catch (validationError) { + rethrowConfigError(this[index], index, { cause: validationError}); + } + }, {}, this); + + finalConfig = this[ConfigArraySymbol.finalizeConfig](finalConfig); + + cache.set(filePath, finalConfig); + cache.set(matchingConfigIndices.toString(), finalConfig); + + return finalConfig; + } + + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The complete path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + * @deprecated Use `isFileIgnored` instead. + */ + isIgnored(filePath) { + return this.isFileIgnored(filePath); + } + + /** + * Determines if the given filepath is ignored based on the configs. + * @param {string} filePath The complete path of a file to check. + * @returns {boolean} True if the path is ignored, false if not. + */ + isFileIgnored(filePath) { + return this.getConfig(filePath) === undefined; + } + + /** + * Determines if the given directory is ignored based on the configs. + * This checks only default `ignores` that don't have `files` in the + * same config. A pattern such as `/foo` be considered to ignore the directory + * while a pattern such as `/foo/**` is not considered to ignore the + * directory because it is matching files. + * @param {string} directoryPath The complete path of a directory to check. + * @returns {boolean} True if the directory is ignored, false if not. Will + * return true for any directory that is not inside of `basePath`. + * @throws {Error} When the `ConfigArray` is not normalized. + */ + isDirectoryIgnored(directoryPath) { + + assertNormalized(this); + + const relativeDirectoryPath = path.relative(this.basePath, directoryPath) + .replace(/\\/g, '/'); + + if (relativeDirectoryPath.startsWith('..')) { + return true; + } + + // first check the cache + const cache = dataCache.get(this).directoryMatches; + + if (cache.has(relativeDirectoryPath)) { + return cache.get(relativeDirectoryPath); + } + + const directoryParts = relativeDirectoryPath.split('/'); + let relativeDirectoryToCheck = ''; + let result = false; + + /* + * In order to get the correct gitignore-style ignores, where an + * ignored parent directory cannot have any descendants unignored, + * we need to check every directory starting at the parent all + * the way down to the actual requested directory. + * + * We aggressively cache all of this info to make sure we don't + * have to recalculate everything for every call. + */ + do { + + relativeDirectoryToCheck += directoryParts.shift() + '/'; + + result = shouldIgnorePath( + this.ignores, + path.join(this.basePath, relativeDirectoryToCheck), + relativeDirectoryToCheck + ); + + cache.set(relativeDirectoryToCheck, result); + + } while (!result && directoryParts.length); + + // also cache the result for the requested path + cache.set(relativeDirectoryPath, result); + + return result; + } + +} diff --git a/packages/config-array/src/files-and-ignores-schema.js b/packages/config-array/src/files-and-ignores-schema.js new file mode 100644 index 00000000..87629345 --- /dev/null +++ b/packages/config-array/src/files-and-ignores-schema.js @@ -0,0 +1,85 @@ +/** + * @fileoverview ConfigSchema + * @author Nicholas C. Zakas + */ + +//------------------------------------------------------------------------------ +// Helpers +//------------------------------------------------------------------------------ + +/** + * Asserts that a given value is an array. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array. + */ +function assertIsArray(value) { + if (!Array.isArray(value)) { + throw new TypeError('Expected value to be an array.'); + } +} + +/** + * Asserts that a given value is an array containing only strings and functions. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array of strings and functions. + */ +function assertIsArrayOfStringsAndFunctions(value, name) { + assertIsArray(value, name); + + if (value.some(item => typeof item !== 'string' && typeof item !== 'function')) { + throw new TypeError('Expected array to only contain strings and functions.'); + } +} + +/** + * Asserts that a given value is a non-empty array. + * @param {*} value The value to check. + * @returns {void} + * @throws {TypeError} When the value is not an array or an empty array. + */ +function assertIsNonEmptyArray(value) { + if (!Array.isArray(value) || value.length === 0) { + throw new TypeError('Expected value to be a non-empty array.'); + } +} + +//------------------------------------------------------------------------------ +// Exports +//------------------------------------------------------------------------------ + +/** + * The schema for `files` and `ignores` that every ConfigArray uses. + * @type Object + */ +export const filesAndIgnoresSchema = Object.freeze({ + files: { + required: false, + merge() { + return undefined; + }, + validate(value) { + + // first check if it's an array + assertIsNonEmptyArray(value); + + // then check each member + value.forEach(item => { + if (Array.isArray(item)) { + assertIsArrayOfStringsAndFunctions(item); + } else if (typeof item !== 'string' && typeof item !== 'function') { + throw new TypeError('Items must be a string, a function, or an array of strings and functions.'); + } + }); + + } + }, + ignores: { + required: false, + merge() { + return undefined; + }, + validate: assertIsArrayOfStringsAndFunctions + } +}); diff --git a/packages/config-array/src/index.js b/packages/config-array/src/index.js new file mode 100644 index 00000000..a083c475 --- /dev/null +++ b/packages/config-array/src/index.js @@ -0,0 +1,6 @@ +/** + * @fileoverview Package API + * @author Nicholas C. Zakas + */ + +export { ConfigArray, ConfigArraySymbol } from './config-array.js'; diff --git a/packages/config-array/tests/config-array.test.js b/packages/config-array/tests/config-array.test.js new file mode 100644 index 00000000..c6cf5ed0 --- /dev/null +++ b/packages/config-array/tests/config-array.test.js @@ -0,0 +1,2149 @@ +/** + * @fileoverview Tests for ConfigArray object. + * @author Nicholas C. Zakas + */ +/* globals URL */ + +//----------------------------------------------------------------------------- +// Imports +//----------------------------------------------------------------------------- + +import { ConfigArray, ConfigArraySymbol } from '../src/config-array.js'; +import path from 'path'; +import assert from "node:assert"; + +//----------------------------------------------------------------------------- +// Helpers +//----------------------------------------------------------------------------- + +// calculate base path using import.meta +const basePath = path.dirname(new URL(import.meta.url).pathname); + +const schema = { + language: { + required: false, + validate(value) { + if (typeof value !== 'function') { + throw new TypeError('Expected a function.'); + } + }, + merge(a, b) { + if (!b) { + return a; + } + + if (!a) { + return b; + } + } + }, + defs: { + required: false, + validate(value) { + if (!value || typeof value !== 'object') { + throw new TypeError('Object expected.'); + } + }, + merge(a, b) { + return { + ...a, + ...b + }; + } + } +}; + +const JSLanguage = class {}; +const CSSLanguage = class {}; +const MarkdownLanguage = class {}; +const JSONLanguage = class {}; + +function createConfigArray(options) { + return new ConfigArray([ + { + files: ['**/*.js'], + language: JSLanguage + }, + { + files: ['**/*.json'], + language: JSONLanguage + }, + { + files: ['**/*.css'], + language: CSSLanguage + }, + { + files: ['**/*.md', '**/.markdown'], + language: MarkdownLanguage + }, + {}, + { + files: ['!*.css'], + defs: { + css: false + } + }, + { + files: ['**/*.xsl'], + ignores: ['fixtures/test.xsl'], + defs: { + xsl: true + } + }, + { + files: ['tests/**/*.xyz'], + defs: { + xyz: true + } + }, + { + ignores: ['tests/fixtures/**'], + defs: { + name: 'config-array' + } + }, + { + ignores: ['node_modules/**'] + }, + { + files: ['foo.test.js'], + defs: { + name: 'config-array.test' + } + }, + function(context) { + return { + files: ['bar.test.js'], + defs: { + name: context.name + } + }; + }, + function(context) { + return [ + { + files: ['baz.test.js'], + defs: { + name: 'baz-' + context.name + } + }, + { + files: ['boom.test.js'], + defs: { + name: 'boom-' + context.name + } + } + ]; + }, + { + files: [['*.and.*', '*.js']], + defs: { + name: 'AND operator' + } + }, + { + files: [filePath => filePath.endsWith('.html')], + defs: { + name: 'HTML' + } + }, + { + ignores: [filePath => filePath.endsWith('.gitignore')] + }, + { + files: ['**/*'], + defs: { + universal: true + } + } + ], { + basePath, + schema, + extraConfigTypes: ['array', 'function'], + ...options + }); +} + +//----------------------------------------------------------------------------- +// Tests +//----------------------------------------------------------------------------- + +describe('ConfigArray', () => { + + let configs, + unnormalizedConfigs; + + beforeEach(() => { + unnormalizedConfigs = new ConfigArray([], { basePath, extraConfigTypes: ['array', 'function'] }); + configs = createConfigArray(); + return configs.normalize({ + name: 'from-context' + }); + }); + + describe('Config Types Validation', () => { + it('should not throw an error when objects are allowed', async () => { + configs = new ConfigArray([ + { + files: ['*.js'] + } + ], { + basePath + }); + await configs.normalize(); + + }); + + it('should not throw an error when arrays are allowed', async () => { + configs = new ConfigArray([ + [ + { + files: ['*.js'] + } + ] + ], { + basePath, + extraConfigTypes: ['array'] + }); + await configs.normalize(); + + }); + + it('should not throw an error when functions are allowed', async () => { + configs = new ConfigArray([ + () => ({}) + ], { + basePath, + extraConfigTypes: ['function'] + }); + await configs.normalize(); + + }); + + it('should throw an error in normalize() when arrays are not allowed', done => { + + configs = new ConfigArray([ + [ + { + files: '*.js' + } + ] + ], { + basePath + }); + + configs + .normalize() + .then(() => { + throw new Error('Missing error.'); + }) + .catch(ex => { + assert.match(ex.message, /Unexpected array/); + done(); + }); + + }); + + it('should throw an error in normalizeSync() when arrays are not allowed', () => { + + configs = new ConfigArray([ + [ + { + files: '*.js' + } + ] + ], { + basePath + }); + assert.throws(() => { + configs.normalizeSync(); + }, /Unexpected array/); + + }); + + it('should throw an error in normalize() when functions are not allowed', done => { + + configs = new ConfigArray([ + () => ({}) + ], { + basePath + }); + + configs + .normalize() + .then(() => { + throw new Error('Missing error.'); + }) + .catch(ex => { + assert.match(ex.message, /Unexpected function/); + done(); + }); + + }); + + it('should throw an error in normalizeSync() when functions are not allowed', () => { + + configs = new ConfigArray([ + () => {} + ], { + basePath + }); + + assert.throws(() => { + configs.normalizeSync(); + }, /Unexpected function/); + + }); + + }); + + describe('Validation', () => { + + function testValidationError({ only = false, title, configs, expectedError }) { + + const localIt = only ? it.only : it; + + localIt(`${title} when calling normalize()`, async () => { + const configArray = new ConfigArray(configs, { basePath }); + + let actualError; + try { + await configArray.normalize(); + } catch (error) { + actualError = error; + } + assert.throws(() => { + if (actualError) { + throw actualError; + } + }, expectedError.message); + + }); + + localIt(`${title} when calling normalizeSync()`, () => { + const configArray = new ConfigArray(configs, { basePath }); + + assert.throws(() => configArray.normalizeSync(), expectedError.message); + + }); + } + + testValidationError({ + title: 'should throw an error when files is not an array', + configs: [ + { + files: '*.js' + } + ], + expectedError: /non-empty array/ + }); + + testValidationError({ + title: 'should throw an error when files is an empty array', + configs: [ + { + files: [] + } + ], + expectedError: /non-empty array/ + }); + + testValidationError({ + title: 'should throw an error when files is undefined', + configs: [ + { + files: undefined + } + ], + expectedError: /non-empty array/ + }); + + testValidationError({ + title: 'should throw an error when files contains an invalid element', + configs: [ + { + name: '', + files: ['*.js', undefined] + } + ], + expectedError: 'Config Error: Config (unnamed): Key "files": Items must be a string, a function, or an array of strings and functions.' + }); + + testValidationError({ + title: 'should throw an error when ignores is undefined', + configs: [ + { + ignores: undefined + } + ], + expectedError: 'Config Error: Config (unnamed): Key "ignores": Expected value to be an array.' + }); + + testValidationError({ + title: 'should throw an error when a global ignores contains an invalid element', + configs: [ + { + name: 'foo', + ignores: ['ignored/**', -1] + } + ], + expectedError: 'Config "foo": Key "ignores": Expected array to only contain strings and functions.' + }); + + testValidationError({ + title: 'should throw an error when a non-global ignores contains an invalid element', + configs: [ + { + name: 'foo', + files: ['*.js'], + ignores: [-1] + } + ], + expectedError: 'Config "foo": Key "ignores": Expected array to only contain strings and functions.' + }); + + it('should throw an error when a config is not an object', async () => { + configs = new ConfigArray([ + { + files: ['*.js'] + }, + 'eslint:reccommended' // typo + ], { basePath }); + + assert.throws(() => { + configs.normalizeSync(); + }, 'Config Error: Config (unnamed): Unexpected non-object config.'); + + }); + + it('should throw an error when base config name is not a string', async () => { + configs = new ConfigArray([ + { + files: ['**'], + name: true + } + ], { basePath }); + + await configs.normalize(); + + assert.throws(() => { + configs.getConfig(path.resolve(basePath, 'foo.js')); + }, 'Config Error: Config (unnamed): Key "name": Property must be a string.'); + + }); + + it('should throw an error when additional config name is not a string', async () => { + configs = new ConfigArray([{}], { basePath }); + configs.push( + { + files: ['**'], + name: true + } + ); + + await configs.normalize(); + + assert.throws(() => { + configs.getConfig(path.resolve(basePath, 'foo.js')); + }, 'Config Error: Config (unnamed): Key "name": Property must be a string.'); + + }); + + it('should throw an error when base config is undefined', async () => { + configs = new ConfigArray([undefined], { basePath }); + + assert.throws(() => { + configs.normalizeSync(); + }, 'ConfigError: Config (unnamed): Unexpected undefined config.'); + + }); + + it('should throw an error when base config is null', async () => { + configs = new ConfigArray([null], { basePath }); + + assert.throws(() => { + configs.normalizeSync(); + }, 'Config Error: Config (unnamed): Unexpected null config.'); + + }); + + it('should throw an error when additional config is undefined', async () => { + configs = new ConfigArray([{}], { basePath }); + configs.push(undefined); + + assert.throws(() => { + configs.normalizeSync(); + }, 'Config Error: Config (unnamed): Unexpected undefined config.'); + + }); + + it('should throw an error when additional config is null', async () => { + configs = new ConfigArray([{}], { basePath }); + configs.push(null); + + assert.throws(() => { + configs.normalizeSync(); + }, 'Config Error: Config (unnamed): Unexpected null config.'); + + }); + }); + + describe('ConfigArray members', () => { + + beforeEach(() => { + configs = createConfigArray(); + return configs.normalize({ + name: 'from-context' + }); + }); + + describe('ConfigArraySymbol.finalizeConfig', () => { + it('should allow finalizeConfig to alter config before returning when calling normalize()', async () => { + + configs = createConfigArray(); + configs[ConfigArraySymbol.finalizeConfig] = () => { + return { + name: 'from-finalize' + }; + }; + + await configs.normalize({ + name: 'from-context' + }); + + const filename = path.resolve(basePath, 'foo.js'); + const config = configs.getConfig(filename); + assert.strictEqual(config.name, 'from-finalize'); + }); + + it('should allow finalizeConfig to alter config before returning when calling normalizeSync()', async () => { + + configs = createConfigArray(); + configs[ConfigArraySymbol.finalizeConfig] = () => { + return { + name: 'from-finalize' + }; + }; + + configs.normalizeSync({ + name: 'from-context' + }); + + const filename = path.resolve(basePath, 'foo.js'); + const config = configs.getConfig(filename); + assert.strictEqual(config.name, 'from-finalize'); + }); + + }); + + describe('ConfigArraySymbol.preprocessConfig', () => { + it('should allow preprocessConfig to alter config before returning', async () => { + + configs = createConfigArray(); + configs.push('foo:bar'); + + configs[ConfigArraySymbol.preprocessConfig] = config => { + + if (config === 'foo:bar') { + return { + defs: { + name: 'foo:bar' + } + }; + } + + return config; + }; + + await configs.normalize({ + name: 'from-context' + }); + + const filename = path.resolve(basePath, 'foo.js'); + const config = configs.getConfig(filename); + assert.strictEqual(config.defs.name, 'foo:bar'); + }); + + it('should have "this" inside of function be equal to config array when calling normalize()', async () => { + + configs = createConfigArray(); + configs.push('foo:bar'); + let internalThis; + + configs[ConfigArraySymbol.preprocessConfig] = function(config) { + internalThis = this; + + if (config === 'foo:bar') { + return { + defs: { + name: 'foo:bar' + } + }; + } + + return config; + }; + + await configs.normalize({ + name: 'from-context' + }); + + assert.strictEqual(internalThis, configs); + }); + + it('should have "this" inside of function be equal to config array when calling normalizeSync()', async () => { + + configs = createConfigArray(); + configs.push('foo:bar'); + let internalThis; + + configs[ConfigArraySymbol.preprocessConfig] = function(config) { + internalThis = this; + + if (config === 'foo:bar') { + return { + defs: { + name: 'foo:bar' + } + }; + } + + return config; + }; + + configs.normalizeSync({ + name: 'from-context' + }); + + assert.strictEqual(internalThis, configs); + }); + + }); + + describe('basePath', () => { + it('should store basePath property when basePath is provided', () => { + assert.strictEqual(unnormalizedConfigs.basePath, basePath); + assert.strictEqual(configs.basePath, basePath); + }); + }); + + describe('isNormalized()', () => { + it('should return true when the config array is normalized', () => { + assert.strictEqual(configs.isNormalized(), true); + }); + + it('should return false when the config array is not normalized', () => { + assert.strictEqual(unnormalizedConfigs.isNormalized(), false); + }); + }); + + describe('getConfig()', () => { + + it('should throw an error when not normalized', () => { + const filename = path.resolve(basePath, 'foo.js'); + + assert.throws(() => { + unnormalizedConfigs.getConfig(filename); + }, /normalized/); + }); + + it('should calculate correct config when passed JS filename', () => { + const filename = path.resolve(basePath, 'foo.js'); + const config = configs.getConfig(filename); + + assert.strictEqual(config.language, JSLanguage); + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'config-array'); + assert.strictEqual(config.defs.universal, true); + assert.strictEqual(config.defs.css, false); + }); + + it('should calculate correct config when passed XYZ filename', () => { + const filename = path.resolve(basePath, 'tests/.bar/foo.xyz'); + + const config = configs.getConfig(filename); + + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'config-array'); + assert.strictEqual(config.defs.universal, true); + assert.strictEqual(config.defs.xyz, true); + }); + + it('should calculate correct config when passed HTML filename', () => { + const filename = path.resolve(basePath, 'foo.html'); + + const config = configs.getConfig(filename); + + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'HTML'); + assert.strictEqual(config.defs.universal, true); + }); + + it('should return undefined when passed ignored .gitignore filename', () => { + const filename = path.resolve(basePath, '.gitignore'); + + const config = configs.getConfig(filename); + + assert.strictEqual(config, undefined); + }); + + it('should calculate correct config when passed JS filename that matches two configs', () => { + const filename = path.resolve(basePath, 'foo.test.js'); + + const config = configs.getConfig(filename); + + assert.strictEqual(config.language, JSLanguage); + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'config-array.test'); + assert.strictEqual(config.defs.css, false); + assert.strictEqual(config.defs.universal, true); + }); + + it('should calculate correct config when passed JS filename that matches a function config', () => { + const filename = path.resolve(basePath, 'bar.test.js'); + + const config = configs.getConfig(filename); + + assert.strictEqual(config.language, JSLanguage); + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'from-context'); + assert.strictEqual(config.defs.css, false); + assert.strictEqual(config.defs.universal, true); + }); + + it('should not match a filename that doesn\'t explicitly match a files pattern', () => { + const matchingFilename = path.resolve(basePath, 'foo.js'); + const notMatchingFilename = path.resolve(basePath, 'foo.md'); + configs = new ConfigArray([ + {}, + { + files: ['**/*.js'] + } + ], { basePath, schema }); + + configs.normalizeSync(); + + const config1 = configs.getConfig(matchingFilename); + assert.strictEqual(typeof config1, 'object'); + + const config2 = configs.getConfig(notMatchingFilename); + assert.strictEqual(config2, undefined); + }); + + it('should calculate correct config when passed JS filename that matches a async function config', () => { + const configs = createConfigArray(); + configs.push(context => { + return Promise.resolve([ + { + files: ['async.test.js'], + defs: { + name: 'async-' + context.name + } + } + ]); + }); + + assert.throws(() => { + configs.normalizeSync(); + }, /Async config functions are not supported/); + }); + + it('should throw an error when passed JS filename that matches a async function config and normalizeSync() is called', async () => { + const filename = path.resolve(basePath, 'async.test.js'); + const configs = createConfigArray(); + configs.push(context => { + return Promise.resolve([ + { + files: ['async.test.js'], + defs: { + name: 'async-' + context.name + } + } + ]); + }); + + await configs.normalize({ + name: 'from-context' + }); + + const config = configs.getConfig(filename); + + assert.strictEqual(config.language, JSLanguage); + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'async-from-context'); + assert.strictEqual(config.defs.css, false); + assert.strictEqual(config.defs.universal, true); + }); + + it('should throw an error when defs doesn\'t pass validation', async () => { + const configs = new ConfigArray([ + { + files: ['**/*.js'], + defs: 'foo', + name: 'bar' + } + ], { basePath, schema }); + + await configs.normalize(); + + const filename = path.resolve(basePath, 'foo.js'); + assert.throws(() => { + configs.getConfig(filename); + }, /Config "bar": Key "defs": Object expected./); + }); + + it('should calculate correct config when passed JS filename that matches a function config returning an array', () => { + const filename1 = path.resolve(basePath, 'baz.test.js'); + const config1 = configs.getConfig(filename1); + + assert.strictEqual(typeof config1.defs, 'object'); + assert.strictEqual(config1.language, JSLanguage); + assert.strictEqual(config1.defs.name, 'baz-from-context'); + + const filename2 = path.resolve(basePath, 'baz.test.js'); + const config2 = configs.getConfig(filename2); + + assert.strictEqual(config2.language, JSLanguage); + assert.strictEqual(typeof config2.defs, 'object'); + assert.strictEqual(config2.defs.name, 'baz-from-context'); + assert.strictEqual(config2.defs.css, false); + }); + + it('should calculate correct config when passed CSS filename', () => { + const filename = path.resolve(basePath, 'foo.css'); + + const config = configs.getConfig(filename); + assert.strictEqual(config.language, CSSLanguage); + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'config-array'); + assert.strictEqual(config.defs.universal, true); ; + }); + + it('should calculate correct config when passed JS filename that matches AND pattern', () => { + const filename = path.resolve(basePath, 'foo.and.js'); + + const config = configs.getConfig(filename); + assert.strictEqual(config.language, JSLanguage); + assert.strictEqual(typeof config.defs, 'object'); + assert.strictEqual(config.defs.name, 'AND operator'); + assert.strictEqual(config.defs.css, false); ; + assert.strictEqual(config.defs.universal, true); ; + }); + + it('should return the same config when called with the same filename twice (caching)', () => { + const filename = path.resolve(basePath, 'foo.js'); + + const config1 = configs.getConfig(filename); + const config2 = configs.getConfig(filename); + + assert.strictEqual(config1, config2); + }); + + it('should return the same config when called with two filenames that match the same configs (caching)', () => { + const filename1 = path.resolve(basePath, 'foo1.js'); + const filename2 = path.resolve(basePath, 'foo2.js'); + + const config1 = configs.getConfig(filename1); + const config2 = configs.getConfig(filename2); + + assert.strictEqual(config1, config2); + }); + + it('should return empty config when called with ignored node_modules filename', () => { + const filename = path.resolve(basePath, 'node_modules/foo.js'); + const config = configs.getConfig(filename); + + assert.strictEqual(config, undefined); + }); + + // https://github.com/eslint/eslint/issues/17103 + describe('ignores patterns should be properly applied', () => { + + it('should return undefined when a filename matches an ignores pattern but not a files pattern', () => { + const matchingFilename = path.resolve(basePath, 'foo.js'); + const notMatchingFilename = path.resolve(basePath, 'foo.md'); + configs = new ConfigArray([ + { + defs: { + severity: 'error' + } + }, + { + ignores: ['**/*.md'], + defs: { + severity: 'warn' + } + } + ], { basePath, schema }); + + configs.normalizeSync(); + + const config1 = configs.getConfig(matchingFilename); + assert.strictEqual(config1, undefined); + + const config2 = configs.getConfig(notMatchingFilename); + assert.strictEqual(config2, undefined); + }); + + it('should apply config with only ignores when a filename matches a files pattern', () => { + const matchingFilename = path.resolve(basePath, 'foo.js'); + const notMatchingFilename = path.resolve(basePath, 'foo.md'); + configs = new ConfigArray([ + { + files: ['**/*.js'], + defs: { + severity: 'error' + } + }, + { + ignores: ['**/*.md'], + defs: { + severity: 'warn' + } + } + ], { basePath, schema }); + + configs.normalizeSync(); + + const config1 = configs.getConfig(matchingFilename); + assert.strictEqual(typeof config1, 'object'); + assert.strictEqual(config1.defs.severity, 'warn'); + + const config2 = configs.getConfig(notMatchingFilename); + assert.strictEqual(config2, undefined); + }); + + it('should not apply config with only ignores when a filename should be ignored', () => { + const matchingFilename = path.resolve(basePath, 'foo.js'); + const ignoredFilename = path.resolve(basePath, 'bar.js'); + configs = new ConfigArray([ + { + files: ['**/*.js'], + defs: { + severity: 'error' + } + }, + { + ignores: ['**/bar.js'], + defs: { + severity: 'warn' + } + } + ], { basePath, schema }); + + configs.normalizeSync(); + + const config1 = configs.getConfig(matchingFilename); + assert.strictEqual(typeof config1, 'object'); + assert.strictEqual(config1.defs.severity, 'warn'); + + const config2 = configs.getConfig(ignoredFilename); + assert.strictEqual(typeof config2, 'object'); + assert.strictEqual(config2.defs.severity, 'error'); + }); + + }); + + }); + + describe('isIgnored()', () => { + + it('should throw an error when not normalized', () => { + const filename = path.resolve(basePath, 'foo.js'); + assert.throws(() => { + unnormalizedConfigs.isIgnored(filename); + }, /normalized/); + }); + it('should return false when passed JS filename', () => { + const filename = path.resolve(basePath, 'foo.js'); + assert.strictEqual(configs.isIgnored(filename), false); + }); + + it('should return true when passed JS filename in parent directory', () => { + const filename = path.resolve(basePath, '../foo.js'); + assert.strictEqual(configs.isIgnored(filename), true); + }); + + it('should return false when passed HTML filename', () => { + const filename = path.resolve(basePath, 'foo.html'); + assert.strictEqual(configs.isIgnored(filename), false); + }); + + it('should return true when passed ignored .gitignore filename', () => { + const filename = path.resolve(basePath, '.gitignore'); + assert.strictEqual(configs.isIgnored(filename), true); + }); + + it('should return false when passed CSS filename', () => { + const filename = path.resolve(basePath, 'foo.css'); + + assert.strictEqual(configs.isIgnored(filename), false); + }); + + it('should return true when passed docx filename', () => { + const filename = path.resolve(basePath, 'sss.docx'); + + assert.strictEqual(configs.isIgnored(filename), false); + }); + + it('should return true when passed ignored node_modules filename', () => { + const filename = path.resolve(basePath, 'node_modules/foo.js'); + + assert.strictEqual(configs.isIgnored(filename), true); + }); + it('should return true when passed matching both files and ignores in a config', () => { + configs = new ConfigArray([ + { + files: ['**/*.xsl'], + ignores: ['fixtures/test.xsl'], + defs: { + xsl: true + } + } + ], { basePath }); + + configs.normalizeSync(); + const filename = path.resolve(basePath, 'fixtures/test.xsl'); + + assert.strictEqual(configs.isIgnored(filename), true); + }); + + it('should return false when negated pattern comes after matching pattern', () => { + configs = new ConfigArray([ + { + files: ['**/foo.*'], + ignores: ['**/*.txt', '!foo.txt'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isIgnored(path.join(basePath, 'bar.txt')), true); + assert.strictEqual(configs.isIgnored(path.join(basePath, 'foo.txt')), false); + }); + + it('should return true when negated pattern comes before matching pattern', () => { + configs = new ConfigArray([ + { + ignores: ['!foo.txt', '**/*.txt'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isIgnored(path.join(basePath, 'bar.txt')), true); ; + assert.strictEqual(configs.isIgnored(path.join(basePath, 'foo.txt')), true); ; + }); + + it('should return false when matching files and ignores has a negated pattern comes after matching pattern', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'], + ignores: ['**/*.test.js', '!foo.test.js'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isIgnored(path.join(basePath, 'bar.test.js')), true); ; + assert.strictEqual(configs.isIgnored(path.join(basePath, 'foo.test.js')), false); ; + }); + + }); + + describe('isFileIgnored()', () => { + + it('should throw an error when not normalized', () => { + const filename = path.resolve(basePath, 'foo.js'); + assert.throws(() => { + unnormalizedConfigs.isFileIgnored(filename); + }, /normalized/); + }); + + it('should return false when passed JS filename', () => { + const filename = path.resolve(basePath, 'foo.js'); + + assert.strictEqual(configs.isFileIgnored(filename), false); ; + }); + + it('should return true when passed JS filename in parent directory', () => { + const filename = path.resolve(basePath, '../foo.js'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + + it('should return false when passed HTML filename', () => { + const filename = path.resolve(basePath, 'foo.html'); + + assert.strictEqual(configs.isFileIgnored(filename), false); ; + }); + + it('should return true when passed ignored .gitignore filename', () => { + const filename = path.resolve(basePath, '.gitignore'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + + it('should return false when passed CSS filename', () => { + const filename = path.resolve(basePath, 'foo.css'); + + assert.strictEqual(configs.isFileIgnored(filename), false); ; + }); + + it('should return true when passed docx filename', () => { + const filename = path.resolve(basePath, 'sss.docx'); + + assert.strictEqual(configs.isFileIgnored(filename), false); ; + }); + + it('should return true when passed ignored node_modules filename', () => { + const filename = path.resolve(basePath, 'node_modules/foo.js'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + + it('should return true when passed matching both files and ignores in a config', () => { + configs = new ConfigArray([ + { + files: ['**/*.xsl'], + ignores: ['fixtures/test.xsl'], + defs: { + xsl: true + } + } + ], { basePath }); + + configs.normalizeSync(); + const filename = path.resolve(basePath, 'fixtures/test.xsl'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + + it('should return false when negated pattern comes after matching pattern', () => { + configs = new ConfigArray([ + { + files: ['**/foo.*'], + ignores: ['**/*.txt', '!foo.txt'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'bar.txt')), true); ; + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo.txt')), false); ; + }); + + it('should return true when negated pattern comes before matching pattern', () => { + configs = new ConfigArray([ + { + ignores: ['!foo.txt', '**/*.txt'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'bar.txt')), true); ; + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo.txt')), true); ; + }); + + it('should return false when matching files and ignores has a negated pattern comes after matching pattern', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'], + ignores: ['**/*.test.js', '!foo.test.js'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'bar.test.js')), true); ; + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo.test.js')), false); ; + }); + + it('should return false when file is inside of ignored directory', () => { + configs = new ConfigArray([ + { + ignores: ['ignoreme'] + }, + { + files: ['**/*.js'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'ignoreme/foo.js')), true); ; + }); + + it('should return false when file is inside of ignored directory', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo/*', + '!foo/bar' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/bar/a.js')), false); ; + }); + + it('should return true when file is ignored, unignored, and then reignored', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'a.js', + '!a*.js', + 'a.js' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'a.js')), true); ; + }); + + it('should return true when the parent directory of a file is ignored', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/bar/a.js')), true); ; + }); + + it('should return true when an ignored directory is later negated with **', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + '**/node_modules/**' + ] + }, + { + ignores: [ + '!node_modules/package/**' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'node_modules/package/a.js')), true); ; + }); + + it('should return true when an ignored directory is later negated with *', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + '**/node_modules/**' + ] + }, + { + ignores: [ + '!node_modules/package/*' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'node_modules/package/a.js')), true); ; + }); + + it('should return true when there are only patterns ending with /*', () => { + configs = new ConfigArray([ + { + files: ['foo/*'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), true); ; + }); + + it('should return true when there are only patterns ending with /**', () => { + configs = new ConfigArray([ + { + files: ['foo/**'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), true); ; + }); + + it('should return false when files pattern matches and there is a pattern ending with /**', () => { + configs = new ConfigArray([ + { + files: ['foo/*.js', 'foo/**'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), false); ; + }); + + it('should return false when file has the same name as a directory that is ignored by a pattern that ends with `/`', () => { + configs = new ConfigArray([ + { + files: ['**/foo'] + }, + { + ignores: [ + 'foo/' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo')), false); ; + }); + + it('should return false when file is in the parent directory of directories that are ignored by a pattern that ends with `/`', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo/*/' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), false); ; + }); + + it('should return true when file is in a directory that is ignored by a pattern that ends with `/`', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo/' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), true); ; + }); + + it('should return true when file is in a directory that is ignored by a pattern that does not end with `/`', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), true); ; + }); + + it('should return false when file is in a directory that is ignored and then unignored by pattern that end with `/`', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo/', + '!foo/' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), false); ; + }); + + it('should return true when file is in a directory that is ignored along with its files by a pattern that ends with `/**` and then unignored by pattern that ends with `/`', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo/**', + + // only the directory is unignored, files are not + '!foo/' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), true); ; + }); + + it('should return true when file is in a directory that is ignored along with its files by a pattern that ends with `/**` and then unignored by pattern that does not end with `/`', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo/**', + + // only the directory is unignored, files are not + '!foo' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), true); ; + }); + + it('should return false when file is in a directory that is ignored along its files by pattern that ends with `/**` and then unignored along its files by pattern that ends with `/**`', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo/**', + + // both the directory and the files are unignored + '!foo/**' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), false); ; + }); + + it('should return true when file is ignored by a pattern and there are unignore patterns that target files of a directory with the same name', () => { + configs = new ConfigArray([ + { + files: ['**/foo'] + }, + { + ignores: [ + 'foo', + '!foo/*', + '!foo/**' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo')), true); ; + }); + + it('should return true when file is in a directory that is ignored even if an unignore pattern that ends with `/*` matches the file', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo', + '!foo/*' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'foo/a.js')), true); ; + }); + + // https://github.com/eslint/eslint/issues/17964#issuecomment-1879840650 + it('should return true for all files ignored in a directory tree except for explicitly unignored ones', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + + // ignore all files and directories + 'tests/format/**/*', + + // unignore all directories + '!tests/format/**/*/', + + // unignore specific files + '!tests/format/**/jsfmt.spec.js' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'tests/format/foo.js')), true); ; + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'tests/format/jsfmt.spec.js')), false); ; + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'tests/format/subdir/foo.js')), true); ; + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'tests/format/subdir/jsfmt.spec.js')), false); ; + }); + + // https://github.com/eslint/eslint/pull/16579/files + describe('gitignore-style unignores', () => { + + it('should return true when a subdirectory is ignored and then we try to unignore a directory', () => { + configs = new ConfigArray([ + { + ignores: [ + '/**/node_modules/*', + '!/node_modules/foo' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + + it('should return true when a subdirectory is ignored and then we try to unignore a file', () => { + configs = new ConfigArray([ + { + ignores: [ + '/**/node_modules/*', + '!/node_modules/foo/**' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + + it('should return true when all descendant directories are ignored and then we try to unignore a file', () => { + configs = new ConfigArray([ + { + ignores: [ + '/**/node_modules/**', + '!/node_modules/foo/**' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + + it('should return true when all descendant directories are ignored without leading slash and then we try to unignore a file', () => { + configs = new ConfigArray([ + { + ignores: [ + '**/node_modules/**', + '!/node_modules/foo/**' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const filename = path.resolve(basePath, 'node_modules/foo/bar.js'); + + assert.strictEqual(configs.isFileIgnored(filename), true); ; + }); + }); + + }); + + describe('isDirectoryIgnored()', () => { + + it('should return true when a function return false in ignores', () => { + configs = new ConfigArray([ + { + ignores: [directoryPath => directoryPath.includes('node_modules')] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules'), 'No trailing slash'), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/', 'Trailing slash'), true); ; + + }); + + it('should return true when a directory is in ignores', () => { + configs = new ConfigArray([ + { + ignores: ['**/node_modules'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules'), 'No trailing slash'), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/', 'Trailing slash'), true); ; + + }); + + it('should return true when a directory with a trailing slash is in ignores', () => { + configs = new ConfigArray([ + { + ignores: ['**/node_modules/'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/', 'Trailing slash'), true); ; + }); + + it('should return true when a directory followed by ** is in ignores', () => { + configs = new ConfigArray([ + { + ignores: ['**/node_modules/**'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/'), true); ; + + }); + + it('should return false when there is a files entry', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'], + ignores: ['**/node_modules'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules')), false); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules') + '/', 'Trailing slash'), false); ; + }); + + it('should return true when directory matches and there is a negated pattern', () => { + configs = new ConfigArray([ + { + ignores: ['**/foo/', '!**/node_modules'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo') + '/', 'Trailing slash'), true); ; + }); + + it('should return false when directory doesn\'t match and there is a negated pattern', () => { + configs = new ConfigArray([ + { + ignores: ['**/foo/', '!**/node_modules'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'bar')), false); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'bar') + '/', 'Trailing slash'), false); ; + }); + + it('should return false when ignored directory is unignored', () => { + configs = new ConfigArray([ + { + ignores: [ + 'foo/*', + '!foo/bar' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar')), false); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar/')), false); ; + }); + + + it('should return true when there is a directory relative to basePath in ignores', () => { + configs = new ConfigArray([ + { + ignores: ['foo/bar'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar') + '/', 'Trailing slash'), true); ; + }); + + it('should throw an error when the config array isn\'t normalized', () => { + configs = new ConfigArray([ + { + ignores: ['foo/bar'] + } + ], { + basePath + }); + assert.throws(() => { + configs.isDirectoryIgnored('foo/bar'); + }, /normalized/); + }); + + it('should return true when the directory is outside of the basePath', () => { + configs = new ConfigArray([ + { + ignores: ['foo/bar'] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.resolve(basePath, '../foo/bar')), true); ; + }); + + it('should return true when the parent directory of a directory is ignored', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + 'foo' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'foo/bar/')), true); ; + }); + + + it('should return true when a directory in an ignored directory is later negated with **', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + '**/node_modules/**' + ] + }, + { + ignores: [ + + // this unignores `node_modules/package/`, but its parent `node_modules/` is still ignored + '!node_modules/package/**' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package/')), true); ; + }); + + it('should return false when a directory is later negated with **', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + '**/node_modules/**' + ] + }, + { + ignores: [ + '!node_modules/**' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules')), false); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/')), false); ; + }); + + it('should return true when a directory\'s content is later negated with *', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + '**/node_modules/**' + ] + }, + { + ignores: [ + '!node_modules/*' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/')), true); ; + }); + + it('should return true when an ignored directory is later unignored with *', () => { + configs = new ConfigArray([ + { + files: ['**/*.js'] + }, + { + ignores: [ + '**/node_modules/**' + ] + }, + { + ignores: [ + '!node_modules/package/*' + ] + } + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package')), true); ; + assert.strictEqual(configs.isDirectoryIgnored(path.join(basePath, 'node_modules/package/')), true); ; + }); + + // https://github.com/eslint/eslint/pull/16579/files + describe('gitignore-style unignores', () => { + + it('should return false when first-level subdirectories are ignored and then one is negated', () => { + configs = new ConfigArray([ + { + ignores: [ + '**/node_modules/*', + '!**/node_modules/foo/' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const directoryPath = path.resolve(basePath, 'node_modules/foo'); + + assert.strictEqual(configs.isDirectoryIgnored(directoryPath), false); ; + }); + + it('should return false when first-level subdirectories are ignored with leading slash and then one is negated', () => { + configs = new ConfigArray([ + { + ignores: [ + '/**/node_modules/*', + '!**/node_modules/foo/' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const directoryPath = path.resolve(basePath, 'node_modules/foo'); + + assert.strictEqual(configs.isDirectoryIgnored(directoryPath), false); ; + }); + + it('should return true when all descendant subdirectories are ignored and then one is negated', () => { + configs = new ConfigArray([ + { + ignores: [ + '**/node_modules/**', + '!**/node_modules/foo/' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const directoryPath = path.resolve(basePath, 'node_modules/foo'); + + assert.strictEqual(configs.isDirectoryIgnored(directoryPath), true); ; + }); + + it('should return true when all descendant subdirectories are ignored and then other descendants are negated', () => { + configs = new ConfigArray([ + { + ignores: [ + '**/node_modules/**', + '!**/node_modules/foo/**' + ], + } + ], { basePath }); + + configs.normalizeSync(); + const directoryPath = path.resolve(basePath, 'node_modules/foo'); + + assert.strictEqual(configs.isDirectoryIgnored(directoryPath), true); ; + }); + }); + + }); + + describe('isExplicitMatch()', () => { + + it('should throw an error when not normalized', () => { + const filename = path.resolve(basePath, 'foo.js'); + assert.throws(() => { + unnormalizedConfigs.isExplicitMatch(filename); + }, /normalized/); + }); + + it('should return true when passed JS filename', () => { + const filename = path.resolve(basePath, 'foo.js'); + + assert.strictEqual(configs.isExplicitMatch(filename), true); ; + }); + + it('should return true when passed HTML filename', () => { + const filename = path.resolve(basePath, 'foo.html'); + + assert.strictEqual(configs.isExplicitMatch(filename), true); ; + }); + + it('should return true when passed CSS filename', () => { + const filename = path.resolve(basePath, 'foo.css'); + + assert.strictEqual(configs.isExplicitMatch(filename), true); ; + }); + + it('should return true when passed EXE filename because it matches !.css', () => { + const filename = path.resolve(basePath, 'foo.exe'); + + assert.strictEqual(configs.isExplicitMatch(filename), true); ; + }); + + it('should return false when passed EXE filename because no explicit matches', () => { + const filename = path.resolve(basePath, 'foo.exe'); + configs = new ConfigArray([ + { + files: ['*.js'] + } + ], { + basePath + }); + configs.normalizeSync(); + + assert.strictEqual(configs.isExplicitMatch(filename), false); ; + }); + + it('should return false when passed matching both files and ignores in a config', () => { + configs = new ConfigArray([ + { + files: ['**/*.xsl'], + ignores: ['fixtures/test.xsl'], + defs: { + xsl: true + } + } + ], { basePath }); + + configs.normalizeSync(); + const filename = path.resolve(basePath, 'fixtures/test.xsl'); + + assert.strictEqual(configs.isExplicitMatch(filename), false); ; + }); + + }); + + describe('files', () => { + + it('should throw an error when not normalized', () => { + assert.throws(() => { + unnormalizedConfigs.files; + }, /normalized/); + }); + + it('should return all string pattern file from all configs when called', () => { + const expectedFiles = configs.reduce((list, config) => { + if (config.files) { + list.push(...config.files); + } + + return list; + }, []); + const files = configs.files; + assert.deepStrictEqual(files, expectedFiles); + + }); + }); + + describe('ignores', () => { + + it('should throw an error when not normalized', () => { + assert.throws(() => { + unnormalizedConfigs.ignores; + }, /normalized/); + }); + + it('should return all ignores from all configs without files when called', () => { + const expectedIgnores = configs.reduce((list, config) => { + if (config.ignores && Object.keys(config).length === 1) { + list.push(...config.ignores); + } + + return list; + }, []); + const ignores = configs.ignores; + assert.deepStrictEqual(ignores, expectedIgnores); + + }); + + it('should ignore name field for when considering global ignores', () => { + configs = new ConfigArray([ + { + name: 'foo', + ignores: ['ignoreme'] + }, + ], { + basePath + }); + + configs.normalizeSync(); + + assert.strictEqual(configs.isFileIgnored(path.join(basePath, 'ignoreme/foo.js')), true); ; + assert.deepStrictEqual(configs.ignores, ['ignoreme']); + }); + }); + + describe('push()', () => { + + it('should throw an error when normalized', () => { + assert.throws(() => { + configs.push({}); + }, /extensible/); + }); + + }); + + }); + +}); diff --git a/packages/config-array/tsconfig.cjs.json b/packages/config-array/tsconfig.cjs.json new file mode 100644 index 00000000..75819270 --- /dev/null +++ b/packages/config-array/tsconfig.cjs.json @@ -0,0 +1,9 @@ +{ + "extends": "./tsconfig.json", + "files": ["dist/cjs/index.cjs"], + "compilerOptions": { + "outDir": "dist/cjs", + "moduleResolution": "Node", + "module": "CommonJS" + }, +} diff --git a/packages/config-array/tsconfig.esm.json b/packages/config-array/tsconfig.esm.json new file mode 100644 index 00000000..07605862 --- /dev/null +++ b/packages/config-array/tsconfig.esm.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "files": ["dist/esm/index.js"], +} diff --git a/packages/config-array/tsconfig.json b/packages/config-array/tsconfig.json new file mode 100644 index 00000000..3fa504c2 --- /dev/null +++ b/packages/config-array/tsconfig.json @@ -0,0 +1,13 @@ +{ + "files": ["src/index.js"], + "compilerOptions": { + "declaration": true, + "emitDeclarationOnly": true, + "allowJs": true, + "checkJs": true, + "outDir": "dist/esm", + "target": "ES2022", + "moduleResolution": "NodeNext", + "module": "NodeNext" + } +}