chore: update frontend build for v1.1.81 [skip ci]

This commit is contained in:
github-actions[bot]
2025-08-06 02:24:54 +00:00
commit 2fd90c5620
19335 changed files with 2351769 additions and 0 deletions

View File

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

View File

@@ -0,0 +1,454 @@
# unplugin-auto-import
[![NPM version](https://img.shields.io/npm/v/unplugin-auto-import?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-auto-import)
Auto import APIs on-demand for Vite, Webpack, Rspack, Rollup and esbuild. With TypeScript support. Powered by [unplugin](https://github.com/unjs/unplugin).
---
without
```ts
import { computed, ref } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
```
with
```ts
const count = ref(0)
const doubled = computed(() => count.value * 2)
```
---
without
```tsx
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
```
with
```tsx
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
```
## Install
```bash
npm i -D unplugin-auto-import
```
<details>
<summary>Vite</summary><br>
```ts
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({ /* options */ }),
],
})
```
Example: [`playground/`](./playground/)
<br></details>
<details>
<summary>Rollup</summary><br>
```ts
// rollup.config.js
import AutoImport from 'unplugin-auto-import/rollup'
export default {
plugins: [
AutoImport({ /* options */ }),
// other plugins
],
}
```
<br></details>
<details>
<summary>Webpack</summary><br>
```ts
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/webpack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Rspack</summary><br>
```ts
// rspack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/rspack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Nuxt</summary><br>
> You **don't need** this plugin for Nuxt, it's already builtin.
<br></details>
<details>
<summary>Vue CLI</summary><br>
```ts
// vue.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/webpack').default({ /* options */ }),
],
}
```
You can also rename the Vue configuration file to `vue.config.mjs` and use static import syntax (you should use latest `@vue/cli-service ^5.0.8`):
```ts
// vue.config.mjs
import AutoImport from 'unplugin-auto-import/webpack'
export default {
configureWebpack: {
plugins: [
AutoImport({ /* options */ }),
],
},
}
```
<br></details>
<details>
<summary>Quasar</summary><br>
```ts
// vite.config.js [Vite]
import { defineConfig } from 'vite'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({ /* options */ })
]
})
```
```ts
// quasar.conf.js [Webpack]
const AutoImportPlugin = require('unplugin-auto-import/webpack').default
module.exports = {
build: {
chainWebpack(chain) {
chain.plugin('unplugin-auto-import').use(
AutoImportPlugin({ /* options */ }),
)
},
},
}
```
<br></details>
<details>
<summary>esbuild</summary><br>
```ts
// esbuild.config.js
import { build } from 'esbuild'
import AutoImport from 'unplugin-auto-import/esbuild'
build({
/* ... */
plugins: [
AutoImport({
/* options */
}),
],
})
```
<br></details>
<details>
<summary>Astro</summary><br>
```ts
// astro.config.mjs
import AutoImport from 'unplugin-auto-import/astro'
export default defineConfig({
integrations: [
AutoImport({
/* options */
})
],
})
```
<br></details>
## Configuration
```ts
AutoImport({
// targets to transform
include: [
/\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
/\.vue$/,
/\.vue\?vue/, // .vue
/\.md$/, // .md
],
// global imports to register
imports: [
// presets
'vue',
'vue-router',
// custom
{
'@vueuse/core': [
// named imports
'useMouse', // import { useMouse } from '@vueuse/core',
// alias
['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
],
'axios': [
// default imports
['default', 'axios'], // import { default as axios } from 'axios',
],
'[package-name]': [
'[import-names]',
// alias
['[from]', '[alias]'],
],
},
// example type import
{
from: 'vue-router',
imports: ['RouteLocationRaw'],
type: true,
},
],
// Array of strings of regexes that contains imports meant to be filtered out.
ignore: [
'useMouse',
'useFetch'
],
// Enable auto import by filename for default module exports under directories
defaultExportByFilename: false,
// Auto import for module exports under directories
// by default it only scan one level of modules under the directory
dirs: [
// './hooks',
// './composables' // only root modules
// './composables/**', // all nested modules
// ...
],
// Filepath to generate corresponding .d.ts file.
// Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
// Set `false` to disable.
dts: './auto-imports.d.ts',
// Array of strings of regexes that contains imports meant to be ignored during
// the declaration file generation. You may find this useful when you need to provide
// a custom signature for a function.
ignoreDts: [
'ignoredFunction',
/^ignore_/
],
// Auto import inside Vue template
// see https://github.com/unjs/unimport/pull/15 and https://github.com/unjs/unimport/pull/72
vueTemplate: false,
// Custom resolvers, compatible with `unplugin-vue-components`
// see https://github.com/antfu/unplugin-auto-import/pull/23/
resolvers: [
/* ... */
],
// Include auto-imported packages in Vite's `optimizeDeps` options
// Recommend to enable
viteOptimizeDeps: false,
// Inject the imports at the end of other imports
injectAtEnd: true,
// Generate corresponding .eslintrc-auto-import.json file.
// eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
eslintrc: {
enabled: false, // Default `false`
// provide path ending with `.mjs` or `.cjs` to generate the file with the respective format
filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
},
// Generate corresponding .biomelintrc-auto-import.json file.
// biomejs extends Docs - https://biomejs.dev/guides/how-biome-works/#the-extends-option
biomelintrc: {
enabled: false, // Default `false`
filepath: './.biomelintrc-auto-import.json', // Default `./.biomelintrc-auto-import.json`
},
})
```
Refer to the [type definitions](./src/types.ts) for more options.
## Presets
See [src/presets](./src/presets).
## Package Presets
We only provide presets for the most popular packages, to use any package not included here you can install it as dev dependency and add it to the `packagePresets` array option:
```ts
AutoImport({
/* other options */
packagePresets: ['detect-browser-es'/* other local package names */]
})
```
You can check the [Svelte example](./examples/vite-svelte) for a working example registering `detect-browser-es` package preset and auto importing `detect` function in [App.svelte](./examples/vite-svelte/src/App.svelte).
Please refer to the [unimport PackagePresets jsdocs](https://github.com/unjs/unimport/blob/main/src/types.ts) for more information about options like `ignore` or `cache`.
**Note**: ensure local packages used have package exports configured properly, otherwise the corresponding modules exports will not be detected.
## TypeScript
In order to properly hint types for auto-imported APIs
<table>
<tr>
<td width="400px" valign="top">
1. Enable `options.dts` so that `auto-imports.d.ts` file is automatically generated
2. Make sure `auto-imports.d.ts` is not excluded in `tsconfig.json`
</td>
<td width="600px"><br>
```ts
AutoImport({
dts: true // or a custom path
})
```
</td>
</tr>
</table>
## ESLint
> 💡 When using TypeScript, we recommend to **disable** `no-undef` rule directly as TypeScript already check for them and you don't need to worry about this.
If you have encountered ESLint error of `no-undef`:
<table>
<tr>
<td width="400px">
1. Enable `eslintrc.enabled`
</td>
<td width="600px"><br>
```ts
AutoImport({
eslintrc: {
enabled: true, // <-- this
},
})
```
</td></tr></table>
<table><tr><td width="400px">
2. Update your `eslintrc`:
[Extending Configuration Files](https://eslint.org/docs/user-guide/configuring/configuration-files#extending-configuration-files)
</td>
<td width="600px"><br>
```ts
// .eslintrc.js
module.exports = {
extends: [
'./.eslintrc-auto-import.json',
],
}
```
</td>
</tr>
</table>
## FAQ
### Compare to [`unimport`](https://github.com/unjs/unimport)
From v0.8.0, `unplugin-auto-import` **uses** `unimport` underneath. `unimport` is designed to be a lower-level tool (it also powered Nuxt's auto import). You can think `unplugin-auto-import` is a wrapper of it that provides more user-friendly config APIs and capabilities like resolvers. Development of new features will mostly happen in `unimport` from now.
### Compare to [`vue-global-api`](https://github.com/antfu/vue-global-api)
You can think of this plugin as a successor to `vue-global-api`, but offering much more flexibility and bindings with libraries other than Vue (e.g. React).
###### Pros
- Flexible and customizable
- Tree-shakable (on-demand transforming)
- No global population
###### Cons
- Relying on build tools integrations (while `vue-global-api` is pure runtime) - but hey, we have supported quite a few of them already!
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)

View File

@@ -0,0 +1,175 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
export {}
declare global {
const $: typeof import('vue/macros')['$']
const $$: typeof import('vue/macros')['$$']
const $computed: typeof import('vue/macros')['$computed']
const $customRef: typeof import('vue/macros')['$customRef']
const $ref: typeof import('vue/macros')['$ref']
const $shallowRef: typeof import('vue/macros')['$shallowRef']
const $toRef: typeof import('vue/macros')['$toRef']
const EffectScope: typeof import('vue')['EffectScope']
const THREE: typeof import('three.js')
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
const afterAll: typeof import('vitest')['afterAll']
const afterEach: typeof import('vitest')['afterEach']
const afterUpdate: typeof import('svelte')['afterUpdate']
const assert: typeof import('vitest')['assert']
const backIn: typeof import('svelte/easing')['backIn']
const backInOut: typeof import('svelte/easing')['backInOut']
const backOut: typeof import('svelte/easing')['backOut']
const beforeAll: typeof import('vitest')['beforeAll']
const beforeEach: typeof import('vitest')['beforeEach']
const beforeUpdate: typeof import('svelte')['beforeUpdate']
const blur: typeof import('svelte/transition')['blur']
const bounceIn: typeof import('svelte/easing')['bounceIn']
const bounceInOut: typeof import('svelte/easing')['bounceInOut']
const bounceOut: typeof import('svelte/easing')['bounceOut']
const chai: typeof import('vitest')['chai']
const circIn: typeof import('svelte/easing')['circIn']
const circInOut: typeof import('svelte/easing')['circInOut']
const circOut: typeof import('svelte/easing')['circOut']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const createEventDispatcher: typeof import('svelte')['createEventDispatcher']
const createPinia: typeof import('pinia')['createPinia']
const createRef: typeof import('react')['createRef']
const crossfade: typeof import('svelte/transition')['crossfade']
const cubicIn: typeof import('svelte/easing')['cubicIn']
const cubicInOut: typeof import('svelte/easing')['cubicInOut']
const cubicOut: typeof import('svelte/easing')['cubicOut']
const customDefault: typeof import('custom')['default']
const customDefaultAlias: typeof import('custom')['default']
const customNamed: typeof import('custom')['customNamed']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const defineStore: typeof import('pinia')['defineStore']
const derived: typeof import('svelte/store')['derived']
const describe: typeof import('vitest')['describe']
const draw: typeof import('svelte/transition')['draw']
const effectScope: typeof import('vue')['effectScope']
const elasticIn: typeof import('svelte/easing')['elasticIn']
const elasticInOut: typeof import('svelte/easing')['elasticInOut']
const elasticOut: typeof import('svelte/easing')['elasticOut']
const expect: typeof import('vitest')['expect']
const expoIn: typeof import('svelte/easing')['expoIn']
const expoInOut: typeof import('svelte/easing')['expoInOut']
const expoOut: typeof import('svelte/easing')['expoOut']
const fade: typeof import('svelte/transition')['fade']
const flip: typeof import('svelte/animate')['flip']
const fly: typeof import('svelte/transition')['fly']
const forwardRef: typeof import('react')['forwardRef']
const get: typeof import('svelte/store')['get']
const getActivePinia: typeof import('pinia')['getActivePinia']
const getAllContexts: typeof import('svelte')['getAllContexts']
const getContext: typeof import('svelte')['getContext']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const hasContext: typeof import('svelte')['hasContext']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const it: typeof import('vitest')['it']
const lazy: typeof import('react')['lazy']
const linear: typeof import('svelte/easing')['linear']
const mapActions: typeof import('pinia')['mapActions']
const mapGetters: typeof import('pinia')['mapGetters']
const mapState: typeof import('pinia')['mapState']
const mapStores: typeof import('pinia')['mapStores']
const mapWritableState: typeof import('pinia')['mapWritableState']
const markRaw: typeof import('vue')['markRaw']
const memo: typeof import('react')['memo']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onDestroy: typeof import('svelte')['onDestroy']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onMount: typeof import('svelte')['onMount']
const onMounted: typeof import('vue')['onMounted']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const provide: typeof import('vue')['provide']
const quadIn: typeof import('svelte/easing')['quadIn']
const quadInOut: typeof import('svelte/easing')['quadInOut']
const quadOut: typeof import('svelte/easing')['quadOut']
const quartIn: typeof import('svelte/easing')['quartIn']
const quartInOut: typeof import('svelte/easing')['quartInOut']
const quartOut: typeof import('svelte/easing')['quartOut']
const quintIn: typeof import('svelte/easing')['quintIn']
const quintInOut: typeof import('svelte/easing')['quintInOut']
const quintOut: typeof import('svelte/easing')['quintOut']
const reactive: typeof import('vue')['reactive']
const readable: typeof import('svelte/store')['readable']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const scale: typeof import('svelte/transition')['scale']
const setActivePinia: typeof import('pinia')['setActivePinia']
const setContext: typeof import('svelte')['setContext']
const setMapStoreSuffix: typeof import('pinia')['setMapStoreSuffix']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const sineIn: typeof import('svelte/easing')['sineIn']
const sineInOut: typeof import('svelte/easing')['sineInOut']
const sineOut: typeof import('svelte/easing')['sineOut']
const slide: typeof import('svelte/transition')['slide']
const spring: typeof import('svelte/motion')['spring']
const startTransition: typeof import('react')['startTransition']
const storeToRefs: typeof import('pinia')['storeToRefs']
const suite: typeof import('vitest')['suite']
const test: typeof import('vitest')['test']
const tick: typeof import('svelte')['tick']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const tweened: typeof import('svelte/motion')['tweened']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCallback: typeof import('react')['useCallback']
const useContext: typeof import('react')['useContext']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useDebugValue: typeof import('react')['useDebugValue']
const useDeferredValue: typeof import('react')['useDeferredValue']
const useDialogPluginComponent: typeof import('quasar')['useDialogPluginComponent']
const useEffect: typeof import('react')['useEffect']
const useFormChild: typeof import('quasar')['useFormChild']
const useId: typeof import('react')['useId']
const useImperativeHandle: typeof import('react')['useImperativeHandle']
const useInsertionEffect: typeof import('react')['useInsertionEffect']
const useLayoutEffect: typeof import('react')['useLayoutEffect']
const useMemo: typeof import('react')['useMemo']
const useMeta: typeof import('quasar')['useMeta']
const useQuasar: typeof import('quasar')['useQuasar']
const useReducer: typeof import('react')['useReducer']
const useRef: typeof import('react')['useRef']
const useSlots: typeof import('vue')['useSlots']
const useState: typeof import('react')['useState']
const useSyncExternalStore: typeof import('react')['useSyncExternalStore']
const useTransition: typeof import('react')['useTransition']
const vi: typeof import('vitest')['vi']
const vitest: typeof import('vitest')['vitest']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
const writable: typeof import('svelte/store')['writable']
}

View File

@@ -0,0 +1,21 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
// src/astro.ts
function astro_default(options) {
return {
name: "unplugin-auto-import",
hooks: {
"astro:config:setup": async (astro) => {
var _a;
(_a = astro.config.vite).plugins || (_a.plugins = []);
astro.config.vite.plugins.push(_chunkCXITMYZHcjs.unplugin_default.vite(options));
}
}
};
}
exports.default = astro_default;

View File

@@ -0,0 +1,13 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare function export_default(options: Options): {
name: string;
hooks: {
'astro:config:setup': (astro: any) => Promise<void>;
};
};
export { export_default as default };

View File

@@ -0,0 +1,13 @@
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare function export_default(options: Options): {
name: string;
hooks: {
'astro:config:setup': (astro: any) => Promise<void>;
};
};
export { export_default as default };

View File

@@ -0,0 +1,21 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
// src/astro.ts
function astro_default(options) {
return {
name: "unplugin-auto-import",
hooks: {
"astro:config:setup": async (astro) => {
var _a;
(_a = astro.config.vite).plugins || (_a.plugins = []);
astro.config.vite.plugins.push(unplugin_default.vite(options));
}
}
};
}
export {
astro_default as default
};

View File

@@ -0,0 +1,608 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/presets/index.ts
var _unimport = require('unimport');
// src/presets/ahooks.ts
var _fs = require('fs');
var _localpkg = require('local-pkg');
var _cache;
var ahooks_default = () => {
if (!_cache) {
let indexesJson;
try {
const path = _localpkg.resolveModule.call(void 0, "ahooks/metadata.json");
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
}
if (indexesJson) {
_cache = {
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
};
}
}
return _cache || {};
};
// src/presets/mobx.ts
var mobx = [
// https://mobx.js.org/api.html
"makeObservable",
"makeAutoObservable",
"extendObservable",
"observable",
"action",
"runInAction",
"flow",
"flowResult",
"computed",
"autorun",
"reaction",
"when",
"onReactionError",
"intercept",
"observe",
"onBecomeObserved",
"onBecomeUnobserved",
"toJS"
];
var mobx_default = {
mobx: [
// https://mobx.js.org/api.html
...mobx
]
};
// src/presets/mobx-react-lite.ts
var mobx_react_lite_default = {
// https://mobx.js.org/api.html
"mobx-react-lite": [
"observer",
"Observer",
"useLocalObservable"
]
};
// src/presets/preact.ts
var preact_default = {
"preact/hooks": [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer"
]
};
// src/presets/quasar.ts
var quasar_default = {
quasar: [
// https://quasar.dev/vue-composables
"useQuasar",
"useDialogPluginComponent",
"useFormChild",
"useMeta"
]
};
// src/presets/react.ts
var CommonReactAPI = [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer",
"useImperativeHandle",
"useDebugValue",
"useDeferredValue",
"useLayoutEffect",
"useTransition",
"startTransition",
"useSyncExternalStore",
"useInsertionEffect",
"useId",
"lazy",
"memo",
"createRef",
"forwardRef"
];
var react_default = {
react: CommonReactAPI
};
// src/presets/react-router.ts
var ReactRouterHooks = [
"useOutletContext",
"useHref",
"useInRouterContext",
"useLocation",
"useNavigationType",
"useNavigate",
"useOutlet",
"useParams",
"useResolvedPath",
"useRoutes"
];
var react_router_default = {
"react-router": [
...ReactRouterHooks
]
};
// src/presets/react-router-dom.ts
var react_router_dom_default = {
"react-router-dom": [
...ReactRouterHooks,
// react-router-dom only hooks
"useLinkClickHandler",
"useSearchParams",
// react-router-dom Component
// call once in general
// 'BrowserRouter',
// 'HashRouter',
// 'MemoryRouter',
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Routes"
]
};
// src/presets/react-i18next.ts
var react_i18next_default = {
"react-i18next": ["useTranslation"]
};
// src/presets/svelte.ts
var svelteAnimate = {
"svelte/animate": [
"flip"
]
};
var svelteEasing = {
"svelte/easing": [
"back",
"bounce",
"circ",
"cubic",
"elastic",
"expo",
"quad",
"quart",
"quint",
"sine"
].reduce((acc, e) => {
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
return acc;
}, ["linear"])
};
var svelteStore = {
"svelte/store": [
"writable",
"readable",
"derived",
"get"
]
};
var svelteMotion = {
"svelte/motion": [
"tweened",
"spring"
]
};
var svelteTransition = {
"svelte/transition": [
"fade",
"blur",
"fly",
"slide",
"scale",
"draw",
"crossfade"
]
};
var svelte = {
svelte: [
// lifecycle
"onMount",
"beforeUpdate",
"afterUpdate",
"onDestroy",
// tick
"tick",
// context
"setContext",
"getContext",
"hasContext",
"getAllContexts",
// event dispatcher
"createEventDispatcher"
]
};
// src/presets/vee-validate.ts
var vee_validate_default = {
"vee-validate": [
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
"validate",
"defineRule",
"configure",
"useField",
"useForm",
"useFieldArray",
"useResetForm",
"useIsFieldDirty",
"useIsFieldTouched",
"useIsFieldValid",
"useIsSubmitting",
"useValidateField",
"useIsFormDirty",
"useIsFormTouched",
"useIsFormValid",
"useValidateForm",
"useSubmitCount",
"useFieldValue",
"useFormValues",
"useFormErrors",
"useFieldError",
"useSubmitForm",
"FormContextKey",
"FieldContextKey"
]
};
// src/presets/vitepress.ts
var vitepress_default = {
vitepress: [
// helper methods
"useData",
"useRoute",
"useRouter",
"withBase"
]
};
// src/presets/vue-router.ts
var vue_router_default = {
"vue-router": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vue-router-composables.ts
var vue_router_composables_default = {
"vue-router/composables": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vueuse-core.ts
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _cache2;
var vueuse_core_default = () => {
const excluded = ["toRefs", "utils", "toRef", "toValue"];
if (!_cache2) {
let indexesJson;
try {
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
const path = _localpkg.resolveModule.call(void 0, "@vueuse/core/indexes.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
}
if (indexesJson) {
_cache2 = {
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
};
}
}
return _cache2 || {};
};
// src/presets/vueuse-head.ts
var vueuse_head_default = {
"@vueuse/head": [
"useHead",
"useSeoMeta"
]
};
// src/presets/vuex.ts
var vuex_default = {
vuex: [
// https://next.vuex.vuejs.org/api/#createstore
"createStore",
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
"createLogger",
// https://next.vuex.vuejs.org/api/#component-binding-helpers
"mapState",
"mapGetters",
"mapActions",
"mapMutations",
"createNamespacedHelpers",
// https://next.vuex.vuejs.org/api/#composable-functions
"useStore"
]
};
// src/presets/uni-app.ts
var uni_app_default = {
"@dcloudio/uni-app": [
"onAddToFavorites",
"onBackPress",
"onError",
"onHide",
"onLaunch",
"onLoad",
"onNavigationBarButtonTap",
"onNavigationBarSearchInputChanged",
"onNavigationBarSearchInputClicked",
"onNavigationBarSearchInputConfirmed",
"onNavigationBarSearchInputFocusChanged",
"onPageNotFound",
"onPageScroll",
"onPullDownRefresh",
"onReachBottom",
"onReady",
"onResize",
"onShareAppMessage",
"onShareTimeline",
"onShow",
"onTabItemTap",
"onThemeChange",
"onUnhandledRejection",
"onUnload"
]
};
// src/presets/solid.ts
var solidCore = {
"solid-js": [
"createSignal",
"createEffect",
"createMemo",
"createResource",
"onMount",
"onCleanup",
"onError",
"untrack",
"batch",
"on",
"createRoot",
"mergeProps",
"splitProps",
"useTransition",
"observable",
"mapArray",
"indexArray",
"createContext",
"useContext",
"children",
"lazy",
"createDeferred",
"createRenderEffect",
"createSelector",
"For",
"Show",
"Switch",
"Match",
"Index",
"ErrorBoundary",
"Suspense",
"SuspenseList"
]
};
var solidStore = {
"solid-js/store": [
"createStore",
"produce",
"reconcile",
"createMutable"
]
};
var solidWeb = {
"solid-js/web": [
"Dynamic",
"hydrate",
"render",
"renderToString",
"renderToStringAsync",
"renderToStream",
"isServer",
"Portal"
]
};
var solid_default = {
...solidCore,
...solidStore,
...solidWeb
};
// src/presets/solid-router.ts
var solid_router_default = {
"@solidjs/router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/solid-app-router.ts
var solid_app_router_default = {
"solid-app-router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/jotai.ts
var jotai = {
jotai: [
"atom",
"useAtom",
"useAtomValue",
"useSetAtom"
]
};
var jotaiUtils = {
"jotai/utils": [
"atomWithReset",
"useResetAtom",
"useReducerAtom",
"atomWithReducer",
"atomFamily",
"selectAtom",
"useAtomCallback",
"freezeAtom",
"freezeAtomCreator",
"splitAtom",
"atomWithDefault",
"waitForAll",
"atomWithStorage",
"atomWithHash",
"createJSONStorage",
"atomWithObservable",
"useHydrateAtoms",
"loadable"
]
};
// src/presets/vueuse-math.ts
var _cache3;
var vueuse_math_default = () => {
if (!_cache3) {
let indexesJson;
try {
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
const path = _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
}
if (indexesJson) {
_cache3 = {
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
};
}
}
return _cache3 || {};
};
// src/presets/recoil.ts
var recoil_default = {
// https://recoiljs.org/docs/api-reference/core/atom/
recoil: [
"atom",
"selector",
"useRecoilState",
"useRecoilValue",
"useSetRecoilState",
"useResetRecoilState",
"useRecoilStateLoadable",
"useRecoilValueLoadable",
"isRecoilValue",
"useRecoilCallback"
]
};
// src/presets/index.ts
var presets = {
..._unimport.builtinPresets,
"ahooks": ahooks_default,
"@vueuse/core": vueuse_core_default,
"@vueuse/math": vueuse_math_default,
"@vueuse/head": vueuse_head_default,
"mobx": mobx_default,
"mobx-react-lite": mobx_react_lite_default,
"preact": preact_default,
"quasar": quasar_default,
"react": react_default,
"react-router": react_router_default,
"react-router-dom": react_router_dom_default,
"react-i18next": react_i18next_default,
"svelte": svelte,
"svelte/animate": svelteAnimate,
"svelte/easing": svelteEasing,
"svelte/motion": svelteMotion,
"svelte/store": svelteStore,
"svelte/transition": svelteTransition,
"vee-validate": vee_validate_default,
"vitepress": vitepress_default,
"vue-router": vue_router_default,
"vue-router/composables": vue_router_composables_default,
"vuex": vuex_default,
"uni-app": uni_app_default,
"solid-js": solid_default,
"@solidjs/router": solid_router_default,
"solid-app-router": solid_app_router_default,
"jotai": jotai,
"jotai/utils": jotaiUtils,
"recoil": recoil_default
};
exports.presets = presets;

View File

@@ -0,0 +1,431 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _chunk53W4H52Qcjs = require('./chunk-53W4H52Q.cjs');
// src/core/unplugin.ts
var _minimatch = require('minimatch');
var _utils = require('@antfu/utils');
var _unplugin = require('unplugin');
// src/core/ctx.ts
var _path = require('path');
var _fs = require('fs');
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _pluginutils = require('@rollup/pluginutils');
var _localpkg = require('local-pkg');
var _unimport = require('unimport');
var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
var _addons = require('unimport/addons');
var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
// src/core/eslintrc.ts
function generateESLintConfigs(imports, eslintrc, globals = {}) {
const eslintConfigs = { globals };
imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort().forEach((name) => {
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
});
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
return jsonBody;
}
// src/core/biomelintrc.ts
function generateBiomeLintConfigs(imports) {
const names = imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort();
const config = { javascript: { globals: names } };
const jsonBody = JSON.stringify(config, null, 2);
return jsonBody;
}
// src/core/resolvers.ts
function normalizeImport(info, name) {
if (typeof info === "string") {
return {
name: "default",
as: name,
from: info
};
}
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return {
name,
as: name,
...info
};
}
async function firstMatchedResolver(resolvers, fullname) {
let name = fullname;
for (const resolver of resolvers) {
if (typeof resolver === "object" && resolver.type === "directive") {
if (name.startsWith("v"))
name = name.slice(1);
else
continue;
}
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
if (resolved)
return normalizeImport(resolved, fullname);
}
}
function resolversAddon(resolvers) {
return {
async matchImports(names, matched) {
if (!resolvers.length)
return;
const dynamic = [];
const sideEffects = [];
await Promise.all([...names].map(async (name) => {
const matchedImport = matched.find((i) => i.as === name);
if (matchedImport) {
if ("sideEffects" in matchedImport)
sideEffects.push(..._utils.toArray.call(void 0, matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
return;
}
const resolved = await firstMatchedResolver(resolvers, name);
if (resolved)
dynamic.push(resolved);
if (resolved == null ? void 0 : resolved.sideEffects)
sideEffects.push(..._utils.toArray.call(void 0, resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
}));
if (dynamic.length) {
this.dynamicImports.push(...dynamic);
this.invalidate();
}
if (dynamic.length || sideEffects.length)
return [...matched, ...dynamic, ...sideEffects];
}
};
}
// src/core/ctx.ts
function resolveGlobsExclude(root, glob) {
const excludeReg = /^!/;
return `${excludeReg.test(glob) ? "!" : ""}${_path.resolve.call(void 0, root, glob.replace(excludeReg, ""))}`;
}
async function scanDirExports(dirs, root) {
const result = await _fastglob2.default.call(void 0, dirs, {
absolute: true,
cwd: root,
onlyFiles: true,
followSymbolicLinks: true
});
const files = Array.from(new Set(result.flat())).map(_utils.slash);
return (await Promise.all(files.map((i) => _unimport.scanExports.call(void 0, i, false)))).flat();
}
function createContext(options = {}, root = _process2.default.cwd()) {
var _a, _b, _c;
root = _utils.slash.call(void 0, root);
const {
dts: preferDTS = _localpkg.isPackageExists.call(void 0, "typescript")
} = options;
const dirs = (_a = options.dirs) == null ? void 0 : _a.concat(options.dirs.map((dir) => _path.join.call(void 0, dir, "*.{tsx,jsx,ts,js,mjs,cjs,mts,cts}"))).map((dir) => _utils.slash.call(void 0, resolveGlobsExclude(root, dir)));
const eslintrc = options.eslintrc || {};
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
const biomelintrc = options.biomelintrc || {};
biomelintrc.enabled = biomelintrc.enabled !== void 0;
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
const injectAtEnd = options.injectAtEnd !== false;
const unimport = _unimport.createUnimport.call(void 0, {
imports: [],
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
injectAtEnd,
parser: options.parser,
addons: [
...options.vueTemplate ? [_addons.vueTemplateAddon.call(void 0, )] : [],
resolversAddon(resolvers),
{
declaration(dts2) {
return `${`
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
${dts2}`.trim()}
`;
}
}
]
});
const importsPromise = flattenImports(options.imports).then((imports) => {
var _a2, _b2;
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
const compare = (left, right) => {
return right instanceof RegExp ? right.test(left) : right === left;
};
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.disabled = true;
});
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.dtsDisabled = true;
});
return unimport.getInternalContext().replaceImports(imports);
});
const filter = _pluginutils.createFilter.call(void 0,
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
);
const dts = preferDTS === false ? false : preferDTS === true ? _path.resolve.call(void 0, root, "auto-imports.d.ts") : _path.resolve.call(void 0, root, preferDTS);
const multilineCommentsRE = /\/\*.*?\*\//gs;
const singlelineCommentsRE = /\/\/.*$/gm;
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
function parseDTS(dts2) {
var _a2;
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
if (!code)
return;
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
}
async function generateDTS(file) {
await importsPromise;
const dir = _path.dirname.call(void 0, file);
const originalContent = _fs.existsSync.call(void 0, file) ? await _fs.promises.readFile(file, "utf-8") : "";
const originalDTS = parseDTS(originalContent);
let currentContent = await unimport.generateTypeDeclarations({
resolvePath: (i) => {
if (i.from.startsWith(".") || _path.isAbsolute.call(void 0, i.from)) {
const related = _utils.slash.call(void 0, _path.relative.call(void 0, dir, i.from).replace(/\.ts(x)?$/, ""));
return !related.startsWith(".") ? `./${related}` : related;
}
return i.from;
}
});
const currentDTS = parseDTS(currentContent);
if (options.vueTemplate) {
currentContent = currentContent.replace(
componentCustomPropertiesReg,
($1) => `interface GlobalComponents {}
${$1}`
);
}
if (originalDTS) {
Object.keys(currentDTS).forEach((key) => {
originalDTS[key] = currentDTS[key];
});
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
return currentContent.replace(dtsReg, () => `declare global {
${dtsList.join("\n")}
}`);
}
return currentContent;
}
async function parseESLint() {
if (!eslintrc.filepath)
return {};
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
return {};
const configStr = _fs.existsSync.call(void 0, eslintrc.filepath) ? await _fs.promises.readFile(eslintrc.filepath, "utf-8") : "";
const config = JSON.parse(configStr || '{ "globals": {} }');
return config.globals;
}
async function generateESLint() {
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
}
async function generateBiomeLint() {
return generateBiomeLintConfigs(await unimport.getImports());
}
const writeConfigFilesThrottled = _utils.throttle.call(void 0, 500, writeConfigFiles, { noLeading: false });
async function writeFile(filePath, content = "") {
await _fs.promises.mkdir(_path.dirname.call(void 0, filePath), { recursive: true });
return await _fs.promises.writeFile(filePath, content, "utf-8");
}
let lastDTS;
let lastESLint;
let lastBiomeLint;
async function writeConfigFiles() {
const promises = [];
if (dts) {
promises.push(
generateDTS(dts).then((content) => {
if (content !== lastDTS) {
lastDTS = content;
return writeFile(dts, content);
}
})
);
}
if (eslintrc.enabled && eslintrc.filepath) {
const filepath = eslintrc.filepath;
promises.push(
generateESLint().then(async (content) => {
if (filepath.endsWith(".cjs"))
content = `module.exports = ${content}`;
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
content = `export default ${content}`;
content = `${content}
`;
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
lastESLint = content;
return writeFile(eslintrc.filepath, content);
}
})
);
}
if (biomelintrc.enabled) {
promises.push(
generateBiomeLint().then((content) => {
if (content !== lastBiomeLint) {
lastBiomeLint = content;
return writeFile(biomelintrc.filepath, content);
}
})
);
}
return Promise.all(promises);
}
async function scanDirs() {
if (dirs == null ? void 0 : dirs.length) {
await unimport.modifyDynamicImports(async (imports) => {
const exports_ = await scanDirExports(dirs, root);
exports_.forEach((i) => i.__source = "dir");
return modifyDefaultExportsAlias([
...imports.filter((i) => i.__source !== "dir"),
...exports_
], options);
});
}
writeConfigFilesThrottled();
}
async function transform(code, id) {
await importsPromise;
const s = new (0, _magicstring2.default)(code);
await unimport.injectImports(s, id);
if (!s.hasChanged())
return;
writeConfigFilesThrottled();
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true, hires: true })
};
}
return {
root,
dirs,
filter,
scanDirs,
writeConfigFiles,
writeConfigFilesThrottled,
transform,
generateDTS,
generateESLint,
unimport
};
}
async function flattenImports(map) {
const promises = await Promise.all(_utils.toArray.call(void 0, map).map(async (definition) => {
if (typeof definition === "string") {
if (!_chunk53W4H52Qcjs.presets[definition])
throw new Error(`[auto-import] preset ${definition} not found`);
const preset = _chunk53W4H52Qcjs.presets[definition];
definition = typeof preset === "function" ? preset() : preset;
}
if ("from" in definition && "imports" in definition) {
return await _unimport.resolvePreset.call(void 0, definition);
} else {
const resolved = [];
for (const mod of Object.keys(definition)) {
for (const id of definition[mod]) {
const meta = {
from: mod
};
if (Array.isArray(id)) {
meta.name = id[0];
meta.as = id[1];
} else {
meta.name = id;
meta.as = id;
}
resolved.push(meta);
}
}
return resolved;
}
}));
return promises.flat();
}
function modifyDefaultExportsAlias(imports, options) {
if (options.defaultExportByFilename) {
imports.forEach((i) => {
var _a, _b, _c;
if (i.name === "default")
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
});
}
return imports;
}
// src/core/unplugin.ts
var unplugin_default = _unplugin.createUnplugin.call(void 0, (options) => {
let ctx = createContext(options);
return {
name: "unplugin-auto-import",
enforce: "post",
transformInclude(id) {
return ctx.filter(id);
},
async transform(code, id) {
return ctx.transform(code, id);
},
async buildStart() {
await ctx.scanDirs();
},
async buildEnd() {
await ctx.writeConfigFiles();
},
vite: {
async config(config) {
var _a;
if (!options.viteOptimizeDeps)
return;
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i)));
if (!imports.size)
return;
return {
optimizeDeps: {
include: [...imports]
}
};
},
async handleHotUpdate({ file }) {
var _a;
if ((_a = ctx.dirs) == null ? void 0 : _a.some((glob) => _minimatch.minimatch.call(void 0, _utils.slash.call(void 0, file), _utils.slash.call(void 0, glob))))
await ctx.scanDirs();
},
async configResolved(config) {
if (ctx.root !== config.root) {
ctx = createContext(options, config.root);
await ctx.scanDirs();
}
}
}
};
});
exports.unplugin_default = unplugin_default;

View File

@@ -0,0 +1,431 @@
import {
presets
} from "./chunk-S4VTQKPB.js";
// src/core/unplugin.ts
import { minimatch } from "minimatch";
import { slash as slash2 } from "@antfu/utils";
import { createUnplugin } from "unplugin";
// src/core/ctx.ts
import { dirname, isAbsolute, join, relative, resolve } from "path";
import { existsSync, promises as fs } from "fs";
import process from "process";
import { slash, throttle, toArray as toArray2 } from "@antfu/utils";
import { createFilter } from "@rollup/pluginutils";
import { isPackageExists } from "local-pkg";
import { createUnimport, resolvePreset, scanExports } from "unimport";
import fg from "fast-glob";
import { vueTemplateAddon } from "unimport/addons";
import MagicString from "magic-string";
// src/core/eslintrc.ts
function generateESLintConfigs(imports, eslintrc, globals = {}) {
const eslintConfigs = { globals };
imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort().forEach((name) => {
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
});
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
return jsonBody;
}
// src/core/biomelintrc.ts
function generateBiomeLintConfigs(imports) {
const names = imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort();
const config = { javascript: { globals: names } };
const jsonBody = JSON.stringify(config, null, 2);
return jsonBody;
}
// src/core/resolvers.ts
import { toArray } from "@antfu/utils";
function normalizeImport(info, name) {
if (typeof info === "string") {
return {
name: "default",
as: name,
from: info
};
}
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return {
name,
as: name,
...info
};
}
async function firstMatchedResolver(resolvers, fullname) {
let name = fullname;
for (const resolver of resolvers) {
if (typeof resolver === "object" && resolver.type === "directive") {
if (name.startsWith("v"))
name = name.slice(1);
else
continue;
}
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
if (resolved)
return normalizeImport(resolved, fullname);
}
}
function resolversAddon(resolvers) {
return {
async matchImports(names, matched) {
if (!resolvers.length)
return;
const dynamic = [];
const sideEffects = [];
await Promise.all([...names].map(async (name) => {
const matchedImport = matched.find((i) => i.as === name);
if (matchedImport) {
if ("sideEffects" in matchedImport)
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
return;
}
const resolved = await firstMatchedResolver(resolvers, name);
if (resolved)
dynamic.push(resolved);
if (resolved == null ? void 0 : resolved.sideEffects)
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
}));
if (dynamic.length) {
this.dynamicImports.push(...dynamic);
this.invalidate();
}
if (dynamic.length || sideEffects.length)
return [...matched, ...dynamic, ...sideEffects];
}
};
}
// src/core/ctx.ts
function resolveGlobsExclude(root, glob) {
const excludeReg = /^!/;
return `${excludeReg.test(glob) ? "!" : ""}${resolve(root, glob.replace(excludeReg, ""))}`;
}
async function scanDirExports(dirs, root) {
const result = await fg(dirs, {
absolute: true,
cwd: root,
onlyFiles: true,
followSymbolicLinks: true
});
const files = Array.from(new Set(result.flat())).map(slash);
return (await Promise.all(files.map((i) => scanExports(i, false)))).flat();
}
function createContext(options = {}, root = process.cwd()) {
var _a, _b, _c;
root = slash(root);
const {
dts: preferDTS = isPackageExists("typescript")
} = options;
const dirs = (_a = options.dirs) == null ? void 0 : _a.concat(options.dirs.map((dir) => join(dir, "*.{tsx,jsx,ts,js,mjs,cjs,mts,cts}"))).map((dir) => slash(resolveGlobsExclude(root, dir)));
const eslintrc = options.eslintrc || {};
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
const biomelintrc = options.biomelintrc || {};
biomelintrc.enabled = biomelintrc.enabled !== void 0;
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
const injectAtEnd = options.injectAtEnd !== false;
const unimport = createUnimport({
imports: [],
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
injectAtEnd,
parser: options.parser,
addons: [
...options.vueTemplate ? [vueTemplateAddon()] : [],
resolversAddon(resolvers),
{
declaration(dts2) {
return `${`
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
${dts2}`.trim()}
`;
}
}
]
});
const importsPromise = flattenImports(options.imports).then((imports) => {
var _a2, _b2;
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
const compare = (left, right) => {
return right instanceof RegExp ? right.test(left) : right === left;
};
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.disabled = true;
});
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.dtsDisabled = true;
});
return unimport.getInternalContext().replaceImports(imports);
});
const filter = createFilter(
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
);
const dts = preferDTS === false ? false : preferDTS === true ? resolve(root, "auto-imports.d.ts") : resolve(root, preferDTS);
const multilineCommentsRE = /\/\*.*?\*\//gs;
const singlelineCommentsRE = /\/\/.*$/gm;
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
function parseDTS(dts2) {
var _a2;
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
if (!code)
return;
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
}
async function generateDTS(file) {
await importsPromise;
const dir = dirname(file);
const originalContent = existsSync(file) ? await fs.readFile(file, "utf-8") : "";
const originalDTS = parseDTS(originalContent);
let currentContent = await unimport.generateTypeDeclarations({
resolvePath: (i) => {
if (i.from.startsWith(".") || isAbsolute(i.from)) {
const related = slash(relative(dir, i.from).replace(/\.ts(x)?$/, ""));
return !related.startsWith(".") ? `./${related}` : related;
}
return i.from;
}
});
const currentDTS = parseDTS(currentContent);
if (options.vueTemplate) {
currentContent = currentContent.replace(
componentCustomPropertiesReg,
($1) => `interface GlobalComponents {}
${$1}`
);
}
if (originalDTS) {
Object.keys(currentDTS).forEach((key) => {
originalDTS[key] = currentDTS[key];
});
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
return currentContent.replace(dtsReg, () => `declare global {
${dtsList.join("\n")}
}`);
}
return currentContent;
}
async function parseESLint() {
if (!eslintrc.filepath)
return {};
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
return {};
const configStr = existsSync(eslintrc.filepath) ? await fs.readFile(eslintrc.filepath, "utf-8") : "";
const config = JSON.parse(configStr || '{ "globals": {} }');
return config.globals;
}
async function generateESLint() {
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
}
async function generateBiomeLint() {
return generateBiomeLintConfigs(await unimport.getImports());
}
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
async function writeFile(filePath, content = "") {
await fs.mkdir(dirname(filePath), { recursive: true });
return await fs.writeFile(filePath, content, "utf-8");
}
let lastDTS;
let lastESLint;
let lastBiomeLint;
async function writeConfigFiles() {
const promises = [];
if (dts) {
promises.push(
generateDTS(dts).then((content) => {
if (content !== lastDTS) {
lastDTS = content;
return writeFile(dts, content);
}
})
);
}
if (eslintrc.enabled && eslintrc.filepath) {
const filepath = eslintrc.filepath;
promises.push(
generateESLint().then(async (content) => {
if (filepath.endsWith(".cjs"))
content = `module.exports = ${content}`;
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
content = `export default ${content}`;
content = `${content}
`;
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
lastESLint = content;
return writeFile(eslintrc.filepath, content);
}
})
);
}
if (biomelintrc.enabled) {
promises.push(
generateBiomeLint().then((content) => {
if (content !== lastBiomeLint) {
lastBiomeLint = content;
return writeFile(biomelintrc.filepath, content);
}
})
);
}
return Promise.all(promises);
}
async function scanDirs() {
if (dirs == null ? void 0 : dirs.length) {
await unimport.modifyDynamicImports(async (imports) => {
const exports_ = await scanDirExports(dirs, root);
exports_.forEach((i) => i.__source = "dir");
return modifyDefaultExportsAlias([
...imports.filter((i) => i.__source !== "dir"),
...exports_
], options);
});
}
writeConfigFilesThrottled();
}
async function transform(code, id) {
await importsPromise;
const s = new MagicString(code);
await unimport.injectImports(s, id);
if (!s.hasChanged())
return;
writeConfigFilesThrottled();
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true, hires: true })
};
}
return {
root,
dirs,
filter,
scanDirs,
writeConfigFiles,
writeConfigFilesThrottled,
transform,
generateDTS,
generateESLint,
unimport
};
}
async function flattenImports(map) {
const promises = await Promise.all(toArray2(map).map(async (definition) => {
if (typeof definition === "string") {
if (!presets[definition])
throw new Error(`[auto-import] preset ${definition} not found`);
const preset = presets[definition];
definition = typeof preset === "function" ? preset() : preset;
}
if ("from" in definition && "imports" in definition) {
return await resolvePreset(definition);
} else {
const resolved = [];
for (const mod of Object.keys(definition)) {
for (const id of definition[mod]) {
const meta = {
from: mod
};
if (Array.isArray(id)) {
meta.name = id[0];
meta.as = id[1];
} else {
meta.name = id;
meta.as = id;
}
resolved.push(meta);
}
}
return resolved;
}
}));
return promises.flat();
}
function modifyDefaultExportsAlias(imports, options) {
if (options.defaultExportByFilename) {
imports.forEach((i) => {
var _a, _b, _c;
if (i.name === "default")
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
});
}
return imports;
}
// src/core/unplugin.ts
var unplugin_default = createUnplugin((options) => {
let ctx = createContext(options);
return {
name: "unplugin-auto-import",
enforce: "post",
transformInclude(id) {
return ctx.filter(id);
},
async transform(code, id) {
return ctx.transform(code, id);
},
async buildStart() {
await ctx.scanDirs();
},
async buildEnd() {
await ctx.writeConfigFiles();
},
vite: {
async config(config) {
var _a;
if (!options.viteOptimizeDeps)
return;
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i)));
if (!imports.size)
return;
return {
optimizeDeps: {
include: [...imports]
}
};
},
async handleHotUpdate({ file }) {
var _a;
if ((_a = ctx.dirs) == null ? void 0 : _a.some((glob) => minimatch(slash2(file), slash2(glob))))
await ctx.scanDirs();
},
async configResolved(config) {
if (ctx.root !== config.root) {
ctx = createContext(options, config.root);
await ctx.scanDirs();
}
}
}
};
});
export {
unplugin_default
};

View File

@@ -0,0 +1,608 @@
// src/presets/index.ts
import { builtinPresets } from "unimport";
// src/presets/ahooks.ts
import { readFileSync } from "fs";
import { resolveModule } from "local-pkg";
var _cache;
var ahooks_default = () => {
if (!_cache) {
let indexesJson;
try {
const path = resolveModule("ahooks/metadata.json");
indexesJson = JSON.parse(readFileSync(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
}
if (indexesJson) {
_cache = {
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
};
}
}
return _cache || {};
};
// src/presets/mobx.ts
var mobx = [
// https://mobx.js.org/api.html
"makeObservable",
"makeAutoObservable",
"extendObservable",
"observable",
"action",
"runInAction",
"flow",
"flowResult",
"computed",
"autorun",
"reaction",
"when",
"onReactionError",
"intercept",
"observe",
"onBecomeObserved",
"onBecomeUnobserved",
"toJS"
];
var mobx_default = {
mobx: [
// https://mobx.js.org/api.html
...mobx
]
};
// src/presets/mobx-react-lite.ts
var mobx_react_lite_default = {
// https://mobx.js.org/api.html
"mobx-react-lite": [
"observer",
"Observer",
"useLocalObservable"
]
};
// src/presets/preact.ts
var preact_default = {
"preact/hooks": [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer"
]
};
// src/presets/quasar.ts
var quasar_default = {
quasar: [
// https://quasar.dev/vue-composables
"useQuasar",
"useDialogPluginComponent",
"useFormChild",
"useMeta"
]
};
// src/presets/react.ts
var CommonReactAPI = [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer",
"useImperativeHandle",
"useDebugValue",
"useDeferredValue",
"useLayoutEffect",
"useTransition",
"startTransition",
"useSyncExternalStore",
"useInsertionEffect",
"useId",
"lazy",
"memo",
"createRef",
"forwardRef"
];
var react_default = {
react: CommonReactAPI
};
// src/presets/react-router.ts
var ReactRouterHooks = [
"useOutletContext",
"useHref",
"useInRouterContext",
"useLocation",
"useNavigationType",
"useNavigate",
"useOutlet",
"useParams",
"useResolvedPath",
"useRoutes"
];
var react_router_default = {
"react-router": [
...ReactRouterHooks
]
};
// src/presets/react-router-dom.ts
var react_router_dom_default = {
"react-router-dom": [
...ReactRouterHooks,
// react-router-dom only hooks
"useLinkClickHandler",
"useSearchParams",
// react-router-dom Component
// call once in general
// 'BrowserRouter',
// 'HashRouter',
// 'MemoryRouter',
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Routes"
]
};
// src/presets/react-i18next.ts
var react_i18next_default = {
"react-i18next": ["useTranslation"]
};
// src/presets/svelte.ts
var svelteAnimate = {
"svelte/animate": [
"flip"
]
};
var svelteEasing = {
"svelte/easing": [
"back",
"bounce",
"circ",
"cubic",
"elastic",
"expo",
"quad",
"quart",
"quint",
"sine"
].reduce((acc, e) => {
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
return acc;
}, ["linear"])
};
var svelteStore = {
"svelte/store": [
"writable",
"readable",
"derived",
"get"
]
};
var svelteMotion = {
"svelte/motion": [
"tweened",
"spring"
]
};
var svelteTransition = {
"svelte/transition": [
"fade",
"blur",
"fly",
"slide",
"scale",
"draw",
"crossfade"
]
};
var svelte = {
svelte: [
// lifecycle
"onMount",
"beforeUpdate",
"afterUpdate",
"onDestroy",
// tick
"tick",
// context
"setContext",
"getContext",
"hasContext",
"getAllContexts",
// event dispatcher
"createEventDispatcher"
]
};
// src/presets/vee-validate.ts
var vee_validate_default = {
"vee-validate": [
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
"validate",
"defineRule",
"configure",
"useField",
"useForm",
"useFieldArray",
"useResetForm",
"useIsFieldDirty",
"useIsFieldTouched",
"useIsFieldValid",
"useIsSubmitting",
"useValidateField",
"useIsFormDirty",
"useIsFormTouched",
"useIsFormValid",
"useValidateForm",
"useSubmitCount",
"useFieldValue",
"useFormValues",
"useFormErrors",
"useFieldError",
"useSubmitForm",
"FormContextKey",
"FieldContextKey"
]
};
// src/presets/vitepress.ts
var vitepress_default = {
vitepress: [
// helper methods
"useData",
"useRoute",
"useRouter",
"withBase"
]
};
// src/presets/vue-router.ts
var vue_router_default = {
"vue-router": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vue-router-composables.ts
var vue_router_composables_default = {
"vue-router/composables": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vueuse-core.ts
import { readFileSync as readFileSync2 } from "fs";
import process from "process";
import { resolveModule as resolveModule2 } from "local-pkg";
var _cache2;
var vueuse_core_default = () => {
const excluded = ["toRefs", "utils", "toRef", "toValue"];
if (!_cache2) {
let indexesJson;
try {
const corePath = resolveModule2("@vueuse/core") || process.cwd();
const path = resolveModule2("@vueuse/core/indexes.json") || resolveModule2("@vueuse/metadata/index.json") || resolveModule2("@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(readFileSync2(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
}
if (indexesJson) {
_cache2 = {
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
};
}
}
return _cache2 || {};
};
// src/presets/vueuse-head.ts
var vueuse_head_default = {
"@vueuse/head": [
"useHead",
"useSeoMeta"
]
};
// src/presets/vuex.ts
var vuex_default = {
vuex: [
// https://next.vuex.vuejs.org/api/#createstore
"createStore",
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
"createLogger",
// https://next.vuex.vuejs.org/api/#component-binding-helpers
"mapState",
"mapGetters",
"mapActions",
"mapMutations",
"createNamespacedHelpers",
// https://next.vuex.vuejs.org/api/#composable-functions
"useStore"
]
};
// src/presets/uni-app.ts
var uni_app_default = {
"@dcloudio/uni-app": [
"onAddToFavorites",
"onBackPress",
"onError",
"onHide",
"onLaunch",
"onLoad",
"onNavigationBarButtonTap",
"onNavigationBarSearchInputChanged",
"onNavigationBarSearchInputClicked",
"onNavigationBarSearchInputConfirmed",
"onNavigationBarSearchInputFocusChanged",
"onPageNotFound",
"onPageScroll",
"onPullDownRefresh",
"onReachBottom",
"onReady",
"onResize",
"onShareAppMessage",
"onShareTimeline",
"onShow",
"onTabItemTap",
"onThemeChange",
"onUnhandledRejection",
"onUnload"
]
};
// src/presets/solid.ts
var solidCore = {
"solid-js": [
"createSignal",
"createEffect",
"createMemo",
"createResource",
"onMount",
"onCleanup",
"onError",
"untrack",
"batch",
"on",
"createRoot",
"mergeProps",
"splitProps",
"useTransition",
"observable",
"mapArray",
"indexArray",
"createContext",
"useContext",
"children",
"lazy",
"createDeferred",
"createRenderEffect",
"createSelector",
"For",
"Show",
"Switch",
"Match",
"Index",
"ErrorBoundary",
"Suspense",
"SuspenseList"
]
};
var solidStore = {
"solid-js/store": [
"createStore",
"produce",
"reconcile",
"createMutable"
]
};
var solidWeb = {
"solid-js/web": [
"Dynamic",
"hydrate",
"render",
"renderToString",
"renderToStringAsync",
"renderToStream",
"isServer",
"Portal"
]
};
var solid_default = {
...solidCore,
...solidStore,
...solidWeb
};
// src/presets/solid-router.ts
var solid_router_default = {
"@solidjs/router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/solid-app-router.ts
var solid_app_router_default = {
"solid-app-router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/jotai.ts
var jotai = {
jotai: [
"atom",
"useAtom",
"useAtomValue",
"useSetAtom"
]
};
var jotaiUtils = {
"jotai/utils": [
"atomWithReset",
"useResetAtom",
"useReducerAtom",
"atomWithReducer",
"atomFamily",
"selectAtom",
"useAtomCallback",
"freezeAtom",
"freezeAtomCreator",
"splitAtom",
"atomWithDefault",
"waitForAll",
"atomWithStorage",
"atomWithHash",
"createJSONStorage",
"atomWithObservable",
"useHydrateAtoms",
"loadable"
]
};
// src/presets/vueuse-math.ts
import { readFileSync as readFileSync3 } from "fs";
import process2 from "process";
import { resolveModule as resolveModule3 } from "local-pkg";
var _cache3;
var vueuse_math_default = () => {
if (!_cache3) {
let indexesJson;
try {
const corePath = resolveModule3("@vueuse/core") || process2.cwd();
const path = resolveModule3("@vueuse/metadata/index.json") || resolveModule3("@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(readFileSync3(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
}
if (indexesJson) {
_cache3 = {
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
};
}
}
return _cache3 || {};
};
// src/presets/recoil.ts
var recoil_default = {
// https://recoiljs.org/docs/api-reference/core/atom/
recoil: [
"atom",
"selector",
"useRecoilState",
"useRecoilValue",
"useSetRecoilState",
"useResetRecoilState",
"useRecoilStateLoadable",
"useRecoilValueLoadable",
"isRecoilValue",
"useRecoilCallback"
]
};
// src/presets/index.ts
var presets = {
...builtinPresets,
"ahooks": ahooks_default,
"@vueuse/core": vueuse_core_default,
"@vueuse/math": vueuse_math_default,
"@vueuse/head": vueuse_head_default,
"mobx": mobx_default,
"mobx-react-lite": mobx_react_lite_default,
"preact": preact_default,
"quasar": quasar_default,
"react": react_default,
"react-router": react_router_default,
"react-router-dom": react_router_dom_default,
"react-i18next": react_i18next_default,
"svelte": svelte,
"svelte/animate": svelteAnimate,
"svelte/easing": svelteEasing,
"svelte/motion": svelteMotion,
"svelte/store": svelteStore,
"svelte/transition": svelteTransition,
"vee-validate": vee_validate_default,
"vitepress": vitepress_default,
"vue-router": vue_router_default,
"vue-router/composables": vue_router_composables_default,
"vuex": vuex_default,
"uni-app": uni_app_default,
"solid-js": solid_default,
"@solidjs/router": solid_router_default,
"solid-app-router": solid_app_router_default,
"jotai": jotai,
"jotai/utils": jotaiUtils,
"recoil": recoil_default
};
export {
presets
};

View File

@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
// src/esbuild.ts
var esbuild_default = _chunkCXITMYZHcjs.unplugin_default.esbuild;
exports.default = esbuild_default;

View File

@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
// src/esbuild.ts
var esbuild_default = unplugin_default.esbuild;
export {
esbuild_default as default
};

View File

@@ -0,0 +1,7 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
exports.default = _chunkCXITMYZHcjs.unplugin_default;

View File

@@ -0,0 +1,9 @@
import * as unplugin from 'unplugin';
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
export { _default as default };

View File

@@ -0,0 +1,9 @@
import * as unplugin from 'unplugin';
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
export { _default as default };

View File

@@ -0,0 +1,7 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
export {
unplugin_default as default
};

View File

@@ -0,0 +1,17 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
// src/nuxt.ts
var _kit = require('@nuxt/kit');
var nuxt_default = _kit.defineNuxtModule.call(void 0, {
setup(options) {
options.exclude = options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/];
_kit.addWebpackPlugin.call(void 0, _chunkCXITMYZHcjs.unplugin_default.webpack(options));
_kit.addVitePlugin.call(void 0, _chunkCXITMYZHcjs.unplugin_default.vite(options));
}
});
exports.default = nuxt_default;

View File

@@ -0,0 +1,9 @@
import * as _nuxt_schema from '@nuxt/schema';
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: _nuxt_schema.NuxtModule<Options>;
export { _default as default };

View File

@@ -0,0 +1,9 @@
import * as _nuxt_schema from '@nuxt/schema';
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: _nuxt_schema.NuxtModule<Options>;
export { _default as default };

View File

@@ -0,0 +1,17 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
// src/nuxt.ts
import { addVitePlugin, addWebpackPlugin, defineNuxtModule } from "@nuxt/kit";
var nuxt_default = defineNuxtModule({
setup(options) {
options.exclude = options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/];
addWebpackPlugin(unplugin_default.webpack(options));
addVitePlugin(unplugin_default.vite(options));
}
});
export {
nuxt_default as default
};

View File

@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
// src/rollup.ts
var rollup_default = _chunkCXITMYZHcjs.unplugin_default.rollup;
exports.default = rollup_default;

View File

@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
// src/rollup.ts
var rollup_default = unplugin_default.rollup;
export {
rollup_default as default
};

View File

@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
// src/rspack.ts
var rspack_default = _chunkCXITMYZHcjs.unplugin_default.rspack;
exports.default = rspack_default;

View File

@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
// src/rspack.ts
var rspack_default = unplugin_default.rspack;
export {
rspack_default as default
};

View File

@@ -0,0 +1 @@
"use strict";require('./chunk-53W4H52Q.cjs');

View File

@@ -0,0 +1,215 @@
import { Arrayable, Awaitable } from '@antfu/utils';
import { FilterPattern } from '@rollup/pluginutils';
import * as unimport from 'unimport';
import { Import, InlinePreset, PackagePreset, UnimportOptions } from 'unimport';
declare const presets: {
ahooks: () => ImportsMap;
'@vueuse/core': () => ImportsMap;
'@vueuse/math': () => ImportsMap;
'@vueuse/head': ImportsMap;
mobx: ImportsMap;
'mobx-react-lite': ImportsMap;
preact: ImportsMap;
quasar: ImportsMap;
react: ImportsMap;
'react-router': ImportsMap;
'react-router-dom': ImportsMap;
'react-i18next': ImportsMap;
svelte: ImportsMap;
'svelte/animate': ImportsMap;
'svelte/easing': ImportsMap;
'svelte/motion': ImportsMap;
'svelte/store': ImportsMap;
'svelte/transition': ImportsMap;
'vee-validate': ImportsMap;
vitepress: ImportsMap;
'vue-router': ImportsMap;
'vue-router/composables': ImportsMap;
vuex: ImportsMap;
'uni-app': ImportsMap;
'solid-js': ImportsMap;
'@solidjs/router': ImportsMap;
'solid-app-router': ImportsMap;
jotai: ImportsMap;
'jotai/utils': ImportsMap;
recoil: ImportsMap;
'@vue/composition-api': unimport.InlinePreset;
pinia: unimport.InlinePreset;
'vue-demi': unimport.InlinePreset;
'vue-i18n': unimport.InlinePreset;
'vue-router-composables': unimport.InlinePreset;
vue: unimport.InlinePreset;
'vue/macros': unimport.InlinePreset;
vitest: unimport.InlinePreset;
rxjs: unimport.InlinePreset;
'date-fns': unimport.InlinePreset;
};
type PresetName = keyof typeof presets;
interface ImportLegacy {
/**
* @deprecated renamed to `as`
*/
name?: string;
/**
* @deprecated renamed to `name`
*/
importName?: string;
/**
* @deprecated renamed to `from`
*/
path: string;
sideEffects?: SideEffectsInfo;
}
interface ImportExtended extends Import {
sideEffects?: SideEffectsInfo;
__source?: 'dir' | 'resolver';
}
type ImportNameAlias = [string, string];
type SideEffectsInfo = Arrayable<ResolverResult | string> | undefined;
interface ResolverResult {
as?: string;
name?: string;
from: string;
}
type ResolverFunction = (name: string) => Awaitable<string | ResolverResult | ImportExtended | null | undefined | void>;
interface ResolverResultObject {
type: 'component' | 'directive';
resolve: ResolverFunction;
}
/**
* Given a identifier name, returns the import path or an import object
*/
type Resolver = ResolverFunction | ResolverResultObject;
/**
* module, name, alias
*/
type ImportsMap = Record<string, (string | ImportNameAlias)[]>;
type ESLintGlobalsPropValue = boolean | 'readonly' | 'readable' | 'writable' | 'writeable';
interface ESLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
/**
* @default true
*/
globalsPropValue?: ESLintGlobalsPropValue;
}
interface BiomeLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
}
interface Options {
/**
* Preset names or custom imports map
*
* @default []
*/
imports?: Arrayable<ImportsMap | PresetName | InlinePreset>;
/**
* Local package presets.
*
* Register local installed packages as a preset.
*
* @default []
* @see https://github.com/unplugin/unplugin-auto-import#package-presets
*/
packagePresets?: (PackagePreset | string)[];
/**
* Identifiers to be ignored
*/
ignore?: (string | RegExp)[];
/**
* These identifiers won't be put on the DTS file
*/
ignoreDts?: (string | RegExp)[];
/**
* Inject the imports at the end of other imports
*
* @default true
*/
injectAtEnd?: boolean;
/**
* Path for directories to be auto imported
*/
dirs?: string[];
/**
* Pass a custom function to resolve the component importing path from the component name.
*
* The component names are always in PascalCase
*/
resolvers?: Arrayable<Arrayable<Resolver>>;
/**
* Parser to be used for parsing the source code.
*
* @see https://github.com/unjs/unimport#acorn-parser
* @default 'regex'
*/
parser?: UnimportOptions['parser'];
/**
* Filepath to generate corresponding .d.ts file.
* Default enabled when `typescript` is installed locally.
* Set `false` to disable.
*
* @default './auto-imports.d.ts'
*/
dts?: string | boolean;
/**
* Auto import inside Vue templates
*
* @see https://github.com/unjs/unimport/pull/15
* @see https://github.com/unjs/unimport/pull/72
* @default false
*/
vueTemplate?: boolean;
/**
* Set default export alias by file name
*
* @default false
*/
defaultExportByFilename?: boolean;
/**
* Rules to include transforming target.
*
* @default [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/]
*/
include?: FilterPattern;
/**
* Rules to exclude transforming target.
*
* @default [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
*/
exclude?: FilterPattern;
/**
* Generate corresponding .eslintrc-auto-import.json file.
*/
eslintrc?: ESLintrc;
/**
* Generate corresponding .biomelintrc.json file.
*/
biomelintrc?: BiomeLintrc;
/**
* Include auto-imported packages in Vite's `optimizeDeps` option
*
* @default false
*/
viteOptimizeDeps?: boolean;
}
export type { BiomeLintrc, ESLintGlobalsPropValue, ESLintrc, ImportExtended, ImportLegacy, ImportNameAlias, ImportsMap, Options, PresetName, Resolver, ResolverFunction, ResolverResult, ResolverResultObject, SideEffectsInfo };

View File

@@ -0,0 +1,215 @@
import { Arrayable, Awaitable } from '@antfu/utils';
import { FilterPattern } from '@rollup/pluginutils';
import * as unimport from 'unimport';
import { Import, InlinePreset, PackagePreset, UnimportOptions } from 'unimport';
declare const presets: {
ahooks: () => ImportsMap;
'@vueuse/core': () => ImportsMap;
'@vueuse/math': () => ImportsMap;
'@vueuse/head': ImportsMap;
mobx: ImportsMap;
'mobx-react-lite': ImportsMap;
preact: ImportsMap;
quasar: ImportsMap;
react: ImportsMap;
'react-router': ImportsMap;
'react-router-dom': ImportsMap;
'react-i18next': ImportsMap;
svelte: ImportsMap;
'svelte/animate': ImportsMap;
'svelte/easing': ImportsMap;
'svelte/motion': ImportsMap;
'svelte/store': ImportsMap;
'svelte/transition': ImportsMap;
'vee-validate': ImportsMap;
vitepress: ImportsMap;
'vue-router': ImportsMap;
'vue-router/composables': ImportsMap;
vuex: ImportsMap;
'uni-app': ImportsMap;
'solid-js': ImportsMap;
'@solidjs/router': ImportsMap;
'solid-app-router': ImportsMap;
jotai: ImportsMap;
'jotai/utils': ImportsMap;
recoil: ImportsMap;
'@vue/composition-api': unimport.InlinePreset;
pinia: unimport.InlinePreset;
'vue-demi': unimport.InlinePreset;
'vue-i18n': unimport.InlinePreset;
'vue-router-composables': unimport.InlinePreset;
vue: unimport.InlinePreset;
'vue/macros': unimport.InlinePreset;
vitest: unimport.InlinePreset;
rxjs: unimport.InlinePreset;
'date-fns': unimport.InlinePreset;
};
type PresetName = keyof typeof presets;
interface ImportLegacy {
/**
* @deprecated renamed to `as`
*/
name?: string;
/**
* @deprecated renamed to `name`
*/
importName?: string;
/**
* @deprecated renamed to `from`
*/
path: string;
sideEffects?: SideEffectsInfo;
}
interface ImportExtended extends Import {
sideEffects?: SideEffectsInfo;
__source?: 'dir' | 'resolver';
}
type ImportNameAlias = [string, string];
type SideEffectsInfo = Arrayable<ResolverResult | string> | undefined;
interface ResolverResult {
as?: string;
name?: string;
from: string;
}
type ResolverFunction = (name: string) => Awaitable<string | ResolverResult | ImportExtended | null | undefined | void>;
interface ResolverResultObject {
type: 'component' | 'directive';
resolve: ResolverFunction;
}
/**
* Given a identifier name, returns the import path or an import object
*/
type Resolver = ResolverFunction | ResolverResultObject;
/**
* module, name, alias
*/
type ImportsMap = Record<string, (string | ImportNameAlias)[]>;
type ESLintGlobalsPropValue = boolean | 'readonly' | 'readable' | 'writable' | 'writeable';
interface ESLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
/**
* @default true
*/
globalsPropValue?: ESLintGlobalsPropValue;
}
interface BiomeLintrc {
/**
* @default false
*/
enabled?: boolean;
/**
* Filepath to save the generated eslint config
*
* @default './.eslintrc-auto-import.json'
*/
filepath?: string;
}
interface Options {
/**
* Preset names or custom imports map
*
* @default []
*/
imports?: Arrayable<ImportsMap | PresetName | InlinePreset>;
/**
* Local package presets.
*
* Register local installed packages as a preset.
*
* @default []
* @see https://github.com/unplugin/unplugin-auto-import#package-presets
*/
packagePresets?: (PackagePreset | string)[];
/**
* Identifiers to be ignored
*/
ignore?: (string | RegExp)[];
/**
* These identifiers won't be put on the DTS file
*/
ignoreDts?: (string | RegExp)[];
/**
* Inject the imports at the end of other imports
*
* @default true
*/
injectAtEnd?: boolean;
/**
* Path for directories to be auto imported
*/
dirs?: string[];
/**
* Pass a custom function to resolve the component importing path from the component name.
*
* The component names are always in PascalCase
*/
resolvers?: Arrayable<Arrayable<Resolver>>;
/**
* Parser to be used for parsing the source code.
*
* @see https://github.com/unjs/unimport#acorn-parser
* @default 'regex'
*/
parser?: UnimportOptions['parser'];
/**
* Filepath to generate corresponding .d.ts file.
* Default enabled when `typescript` is installed locally.
* Set `false` to disable.
*
* @default './auto-imports.d.ts'
*/
dts?: string | boolean;
/**
* Auto import inside Vue templates
*
* @see https://github.com/unjs/unimport/pull/15
* @see https://github.com/unjs/unimport/pull/72
* @default false
*/
vueTemplate?: boolean;
/**
* Set default export alias by file name
*
* @default false
*/
defaultExportByFilename?: boolean;
/**
* Rules to include transforming target.
*
* @default [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/]
*/
include?: FilterPattern;
/**
* Rules to exclude transforming target.
*
* @default [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
*/
exclude?: FilterPattern;
/**
* Generate corresponding .eslintrc-auto-import.json file.
*/
eslintrc?: ESLintrc;
/**
* Generate corresponding .biomelintrc.json file.
*/
biomelintrc?: BiomeLintrc;
/**
* Include auto-imported packages in Vite's `optimizeDeps` option
*
* @default false
*/
viteOptimizeDeps?: boolean;
}
export type { BiomeLintrc, ESLintGlobalsPropValue, ESLintrc, ImportExtended, ImportLegacy, ImportNameAlias, ImportsMap, Options, PresetName, Resolver, ResolverFunction, ResolverResult, ResolverResultObject, SideEffectsInfo };

View File

@@ -0,0 +1 @@
import "./chunk-S4VTQKPB.js";

View File

@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
// src/vite.ts
var vite_default = _chunkCXITMYZHcjs.unplugin_default.vite;
exports.default = vite_default;

View File

@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
// src/vite.ts
var vite_default = unplugin_default.vite;
export {
vite_default as default
};

View File

@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkCXITMYZHcjs = require('./chunk-CXITMYZH.cjs');
require('./chunk-53W4H52Q.cjs');
// src/webpack.ts
var webpack_default = _chunkCXITMYZHcjs.unplugin_default.webpack;
exports.default = webpack_default;

View File

@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import '@rollup/pluginutils';
import 'unimport';
declare const _default: (options?: Options) => any;
export { _default as default };

View File

@@ -0,0 +1,10 @@
import {
unplugin_default
} from "./chunk-GR6VF5HE.js";
import "./chunk-S4VTQKPB.js";
// src/webpack.ts
var webpack_default = unplugin_default.webpack;
export {
webpack_default as default
};

View File

@@ -0,0 +1,2 @@
tidelift: "npm/brace-expansion"
patreon: juliangruber

View File

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

View File

@@ -0,0 +1,135 @@
# brace-expansion
[Brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html),
as known from sh/bash, in JavaScript.
[![build status](https://secure.travis-ci.org/juliangruber/brace-expansion.svg)](http://travis-ci.org/juliangruber/brace-expansion)
[![downloads](https://img.shields.io/npm/dm/brace-expansion.svg)](https://www.npmjs.org/package/brace-expansion)
[![Greenkeeper badge](https://badges.greenkeeper.io/juliangruber/brace-expansion.svg)](https://greenkeeper.io/)
[![testling badge](https://ci.testling.com/juliangruber/brace-expansion.png)](https://ci.testling.com/juliangruber/brace-expansion)
## Example
```js
var expand = require('brace-expansion');
expand('file-{a,b,c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('-v{,,}')
// => ['-v', '-v', '-v']
expand('file{0..2}.jpg')
// => ['file0.jpg', 'file1.jpg', 'file2.jpg']
expand('file-{a..c}.jpg')
// => ['file-a.jpg', 'file-b.jpg', 'file-c.jpg']
expand('file{2..0}.jpg')
// => ['file2.jpg', 'file1.jpg', 'file0.jpg']
expand('file{0..4..2}.jpg')
// => ['file0.jpg', 'file2.jpg', 'file4.jpg']
expand('file-{a..e..2}.jpg')
// => ['file-a.jpg', 'file-c.jpg', 'file-e.jpg']
expand('file{00..10..5}.jpg')
// => ['file00.jpg', 'file05.jpg', 'file10.jpg']
expand('{{A..C},{a..c}}')
// => ['A', 'B', 'C', 'a', 'b', 'c']
expand('ppp{,config,oe{,conf}}')
// => ['ppp', 'pppconfig', 'pppoe', 'pppoeconf']
```
## API
```js
var expand = require('brace-expansion');
```
### var expanded = expand(str)
Return an array of all possible and valid expansions of `str`. If none are
found, `[str]` is returned.
Valid expansions are:
```js
/^(.*,)+(.+)?$/
// {a,b,...}
```
A comma separated list of options, like `{a,b}` or `{a,{b,c}}` or `{,a,}`.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
A numeric sequence from `x` to `y` inclusive, with optional increment.
If `x` or `y` start with a leading `0`, all the numbers will be padded
to have equal length. Negative numbers and backwards iteration work too.
```js
/^-?\d+\.\.-?\d+(\.\.-?\d+)?$/
// {x..y[..incr]}
```
An alphabetic sequence from `x` to `y` inclusive, with optional increment.
`x` and `y` must be exactly one character, and if given, `incr` must be a
number.
For compatibility reasons, the string `${` is not eligible for brace expansion.
## Installation
With [npm](https://npmjs.org) do:
```bash
npm install brace-expansion
```
## Contributors
- [Julian Gruber](https://github.com/juliangruber)
- [Isaac Z. Schlueter](https://github.com/isaacs)
## Sponsors
This module is proudly supported by my [Sponsors](https://github.com/juliangruber/sponsors)!
Do you want to support modules like this to improve their quality, stability and weigh in on new features? Then please consider donating to my [Patreon](https://www.patreon.com/juliangruber). Not sure how much of my modules you're using? Try [feross/thanks](https://github.com/feross/thanks)!
## Security contact information
To report a security vulnerability, please use the
[Tidelift security contact](https://tidelift.com/security).
Tidelift will coordinate the fix and disclosure.
## License
(MIT)
Copyright (c) 2013 Julian Gruber &lt;julian@juliangruber.com&gt;
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,203 @@
var balanced = require('balanced-match');
module.exports = expandTop;
var escSlash = '\0SLASH'+Math.random()+'\0';
var escOpen = '\0OPEN'+Math.random()+'\0';
var escClose = '\0CLOSE'+Math.random()+'\0';
var escComma = '\0COMMA'+Math.random()+'\0';
var escPeriod = '\0PERIOD'+Math.random()+'\0';
function numeric(str) {
return parseInt(str, 10) == str
? parseInt(str, 10)
: str.charCodeAt(0);
}
function escapeBraces(str) {
return str.split('\\\\').join(escSlash)
.split('\\{').join(escOpen)
.split('\\}').join(escClose)
.split('\\,').join(escComma)
.split('\\.').join(escPeriod);
}
function unescapeBraces(str) {
return str.split(escSlash).join('\\')
.split(escOpen).join('{')
.split(escClose).join('}')
.split(escComma).join(',')
.split(escPeriod).join('.');
}
// Basically just str.split(","), but handling cases
// where we have nested braced sections, which should be
// treated as individual members, like {a,{b,c},d}
function parseCommaParts(str) {
if (!str)
return [''];
var parts = [];
var m = balanced('{', '}', str);
if (!m)
return str.split(',');
var pre = m.pre;
var body = m.body;
var post = m.post;
var p = pre.split(',');
p[p.length-1] += '{' + body + '}';
var postParts = parseCommaParts(post);
if (post.length) {
p[p.length-1] += postParts.shift();
p.push.apply(p, postParts);
}
parts.push.apply(parts, p);
return parts;
}
function expandTop(str) {
if (!str)
return [];
// I don't know why Bash 4.3 does this, but it does.
// Anything starting with {} will have the first two bytes preserved
// but *only* at the top level, so {},a}b will not expand to anything,
// but a{},b}c will be expanded to [a}c,abc].
// One could argue that this is a bug in Bash, but since the goal of
// this module is to match Bash's rules, we escape a leading {}
if (str.substr(0, 2) === '{}') {
str = '\\{\\}' + str.substr(2);
}
return expand(escapeBraces(str), true).map(unescapeBraces);
}
function embrace(str) {
return '{' + str + '}';
}
function isPadded(el) {
return /^-?0\d/.test(el);
}
function lte(i, y) {
return i <= y;
}
function gte(i, y) {
return i >= y;
}
function expand(str, isTop) {
var expansions = [];
var m = balanced('{', '}', str);
if (!m) return [str];
// no need to expand pre, since it is guaranteed to be free of brace-sets
var pre = m.pre;
var post = m.post.length
? expand(m.post, false)
: [''];
if (/\$$/.test(m.pre)) {
for (var k = 0; k < post.length; k++) {
var expansion = pre+ '{' + m.body + '}' + post[k];
expansions.push(expansion);
}
} else {
var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body);
var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body);
var isSequence = isNumericSequence || isAlphaSequence;
var isOptions = m.body.indexOf(',') >= 0;
if (!isSequence && !isOptions) {
// {a},b}
if (m.post.match(/,(?!,).*\}/)) {
str = m.pre + '{' + m.body + escClose + m.post;
return expand(str);
}
return [str];
}
var n;
if (isSequence) {
n = m.body.split(/\.\./);
} else {
n = parseCommaParts(m.body);
if (n.length === 1) {
// x{{a,b}}y ==> x{a}y x{b}y
n = expand(n[0], false).map(embrace);
if (n.length === 1) {
return post.map(function(p) {
return m.pre + n[0] + p;
});
}
}
}
// at this point, n is the parts, and we know it's not a comma set
// with a single entry.
var N;
if (isSequence) {
var x = numeric(n[0]);
var y = numeric(n[1]);
var width = Math.max(n[0].length, n[1].length)
var incr = n.length == 3
? Math.abs(numeric(n[2]))
: 1;
var test = lte;
var reverse = y < x;
if (reverse) {
incr *= -1;
test = gte;
}
var pad = n.some(isPadded);
N = [];
for (var i = x; test(i, y); i += incr) {
var c;
if (isAlphaSequence) {
c = String.fromCharCode(i);
if (c === '\\')
c = '';
} else {
c = String(i);
if (pad) {
var need = width - c.length;
if (need > 0) {
var z = new Array(need + 1).join('0');
if (i < 0)
c = '-' + z + c.slice(1);
else
c = z + c;
}
}
}
N.push(c);
}
} else {
N = [];
for (var j = 0; j < n.length; j++) {
N.push.apply(N, expand(n[j], false));
}
}
for (var j = 0; j < N.length; j++) {
for (var k = 0; k < post.length; k++) {
var expansion = pre + N[j] + post[k];
if (!isTop || isSequence || expansion)
expansions.push(expansion);
}
}
}
return expansions;
}

View File

@@ -0,0 +1,49 @@
{
"name": "brace-expansion",
"description": "Brace expansion as known from sh/bash",
"version": "2.0.2",
"repository": {
"type": "git",
"url": "git://github.com/juliangruber/brace-expansion.git"
},
"homepage": "https://github.com/juliangruber/brace-expansion",
"main": "index.js",
"scripts": {
"test": "tape test/*.js",
"gentest": "bash test/generate.sh",
"bench": "matcha test/perf/bench.js"
},
"dependencies": {
"balanced-match": "^1.0.0"
},
"devDependencies": {
"@c4312/matcha": "^1.3.1",
"tape": "^4.6.0"
},
"keywords": [],
"author": {
"name": "Julian Gruber",
"email": "mail@juliangruber.com",
"url": "http://juliangruber.com"
},
"license": "MIT",
"testling": {
"files": "test/*.js",
"browsers": [
"ie/8..latest",
"firefox/20..latest",
"firefox/nightly",
"chrome/25..latest",
"chrome/canary",
"opera/12..latest",
"opera/next",
"safari/5.1..latest",
"ipad/6.0..latest",
"iphone/6.0..latest",
"android-browser/4.2..latest"
]
},
"publishConfig": {
"tag": "2.x"
}
}

View File

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

View File

@@ -0,0 +1,454 @@
# minimatch
A minimal matching utility.
This is the matching library used internally by npm.
It works by converting glob expressions into JavaScript `RegExp`
objects.
## Usage
```js
// hybrid module, load with require() or import
import { minimatch } from 'minimatch'
// or:
const { minimatch } = require('minimatch')
minimatch('bar.foo', '*.foo') // true!
minimatch('bar.foo', '*.bar') // false!
minimatch('bar.foo', '*.+(bar|foo)', { debug: true }) // true, and noisy!
```
## Features
Supports these glob features:
- Brace Expansion
- Extended glob matching
- "Globstar" `**` matching
- [Posix character
classes](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html),
like `[[:alpha:]]`, supporting the full range of Unicode
characters. For example, `[[:alpha:]]` will match against
`'é'`, though `[a-zA-Z]` will not. Collating symbol and set
matching is not supported, so `[[=e=]]` will _not_ match `'é'`
and `[[.ch.]]` will not match `'ch'` in locales where `ch` is
considered a single character.
See:
- `man sh`
- `man bash` [Pattern
Matching](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html)
- `man 3 fnmatch`
- `man 5 gitignore`
## Windows
**Please only use forward-slashes in glob expressions.**
Though windows uses either `/` or `\` as its path separator, only `/`
characters are used by this glob implementation. You must use
forward-slashes **only** in glob expressions. Back-slashes in patterns
will always be interpreted as escape characters, not path separators.
Note that `\` or `/` _will_ be interpreted as path separators in paths on
Windows, and will match against `/` in glob expressions.
So just always use `/` in patterns.
### UNC Paths
On Windows, UNC paths like `//?/c:/...` or
`//ComputerName/Share/...` are handled specially.
- Patterns starting with a double-slash followed by some
non-slash characters will preserve their double-slash. As a
result, a pattern like `//*` will match `//x`, but not `/x`.
- Patterns staring with `//?/<drive letter>:` will _not_ treat
the `?` as a wildcard character. Instead, it will be treated
as a normal string.
- Patterns starting with `//?/<drive letter>:/...` will match
file paths starting with `<drive letter>:/...`, and vice versa,
as if the `//?/` was not present. This behavior only is
present when the drive letters are a case-insensitive match to
one another. The remaining portions of the path/pattern are
compared case sensitively, unless `nocase:true` is set.
Note that specifying a UNC path using `\` characters as path
separators is always allowed in the file path argument, but only
allowed in the pattern argument when `windowsPathsNoEscape: true`
is set in the options.
## Minimatch Class
Create a minimatch object by instantiating the `minimatch.Minimatch` class.
```javascript
var Minimatch = require('minimatch').Minimatch
var mm = new Minimatch(pattern, options)
```
### Properties
- `pattern` The original pattern the minimatch object represents.
- `options` The options supplied to the constructor.
- `set` A 2-dimensional array of regexp or string expressions.
Each row in the
array corresponds to a brace-expanded pattern. Each item in the row
corresponds to a single path-part. For example, the pattern
`{a,b/c}/d` would expand to a set of patterns like:
[ [ a, d ]
, [ b, c, d ] ]
If a portion of the pattern doesn't have any "magic" in it
(that is, it's something like `"foo"` rather than `fo*o?`), then it
will be left as a string rather than converted to a regular
expression.
- `regexp` Created by the `makeRe` method. A single regular expression
expressing the entire pattern. This is useful in cases where you wish
to use the pattern somewhat like `fnmatch(3)` with `FNM_PATH` enabled.
- `negate` True if the pattern is negated.
- `comment` True if the pattern is a comment.
- `empty` True if the pattern is `""`.
### Methods
- `makeRe()` Generate the `regexp` member if necessary, and return it.
Will return `false` if the pattern is invalid.
- `match(fname)` Return true if the filename matches the pattern, or
false otherwise.
- `matchOne(fileArray, patternArray, partial)` Take a `/`-split
filename, and match it against a single row in the `regExpSet`. This
method is mainly for internal use, but is exposed so that it can be
used by a glob-walker that needs to avoid excessive filesystem calls.
- `hasMagic()` Returns true if the parsed pattern contains any
magic characters. Returns false if all comparator parts are
string literals. If the `magicalBraces` option is set on the
constructor, then it will consider brace expansions which are
not otherwise magical to be magic. If not set, then a pattern
like `a{b,c}d` will return `false`, because neither `abd` nor
`acd` contain any special glob characters.
This does **not** mean that the pattern string can be used as a
literal filename, as it may contain magic glob characters that
are escaped. For example, the pattern `\\*` or `[*]` would not
be considered to have magic, as the matching portion parses to
the literal string `'*'` and would match a path named `'*'`,
not `'\\*'` or `'[*]'`. The `minimatch.unescape()` method may
be used to remove escape characters.
All other methods are internal, and will be called as necessary.
### minimatch(path, pattern, options)
Main export. Tests a path against the pattern using the options.
```javascript
var isJS = minimatch(file, '*.js', { matchBase: true })
```
### minimatch.filter(pattern, options)
Returns a function that tests its
supplied argument, suitable for use with `Array.filter`. Example:
```javascript
var javascripts = fileList.filter(minimatch.filter('*.js', { matchBase: true }))
```
### minimatch.escape(pattern, options = {})
Escape all magic characters in a glob pattern, so that it will
only ever match literal strings
If the `windowsPathsNoEscape` option is used, then characters are
escaped by wrapping in `[]`, because a magic character wrapped in
a character class can only be satisfied by that exact character.
Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.
### minimatch.unescape(pattern, options = {})
Un-escape a glob string that may contain some escaped characters.
If the `windowsPathsNoEscape` option is used, then square-brace
escapes are removed, but not backslash escapes. For example, it
will turn the string `'[*]'` into `*`, but it will not turn
`'\\*'` into `'*'`, because `\` is a path separator in
`windowsPathsNoEscape` mode.
When `windowsPathsNoEscape` is not set, then both brace escapes
and backslash escapes are removed.
Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot
be escaped or unescaped.
### minimatch.match(list, pattern, options)
Match against the list of
files, in the style of fnmatch or glob. If nothing is matched, and
options.nonull is set, then return a list containing the pattern itself.
```javascript
var javascripts = minimatch.match(fileList, '*.js', { matchBase: true })
```
### minimatch.makeRe(pattern, options)
Make a regular expression object from the pattern.
## Options
All options are `false` by default.
### debug
Dump a ton of stuff to stderr.
### nobrace
Do not expand `{a,b}` and `{1..3}` brace sets.
### noglobstar
Disable `**` matching against multiple folder names.
### dot
Allow patterns to match filenames starting with a period, even if
the pattern does not explicitly have a period in that spot.
Note that by default, `a/**/b` will **not** match `a/.d/b`, unless `dot`
is set.
### noext
Disable "extglob" style patterns like `+(a|b)`.
### nocase
Perform a case-insensitive match.
### nocaseMagicOnly
When used with `{nocase: true}`, create regular expressions that
are case-insensitive, but leave string match portions untouched.
Has no effect when used without `{nocase: true}`
Useful when some other form of case-insensitive matching is used,
or if the original string representation is useful in some other
way.
### nonull
When a match is not found by `minimatch.match`, return a list containing
the pattern itself if this option is set. When not set, an empty list
is returned if there are no matches.
### magicalBraces
This only affects the results of the `Minimatch.hasMagic` method.
If the pattern contains brace expansions, such as `a{b,c}d`, but
no other magic characters, then the `Minimatch.hasMagic()` method
will return `false` by default. When this option set, it will
return `true` for brace expansion as well as other magic glob
characters.
### matchBase
If set, then patterns without slashes will be matched
against the basename of the path if it contains slashes. For example,
`a?b` would match the path `/xyz/123/acb`, but not `/xyz/acb/123`.
### nocomment
Suppress the behavior of treating `#` at the start of a pattern as a
comment.
### nonegate
Suppress the behavior of treating a leading `!` character as negation.
### flipNegate
Returns from negate expressions the same as if they were not negated.
(Ie, true on a hit, false on a miss.)
### partial
Compare a partial path to a pattern. As long as the parts of the path that
are present are not contradicted by the pattern, it will be treated as a
match. This is useful in applications where you're walking through a
folder structure, and don't yet have the full path, but want to ensure that
you do not walk down paths that can never be a match.
For example,
```js
minimatch('/a/b', '/a/*/c/d', { partial: true }) // true, might be /a/b/c/d
minimatch('/a/b', '/**/d', { partial: true }) // true, might be /a/b/.../d
minimatch('/x/y/z', '/a/**/z', { partial: true }) // false, because x !== a
```
### windowsPathsNoEscape
Use `\\` as a path separator _only_, and _never_ as an escape
character. If set, all `\\` characters are replaced with `/` in
the pattern. Note that this makes it **impossible** to match
against paths containing literal glob pattern characters, but
allows matching with patterns constructed using `path.join()` and
`path.resolve()` on Windows platforms, mimicking the (buggy!)
behavior of earlier versions on Windows. Please use with
caution, and be mindful of [the caveat about Windows
paths](#windows).
For legacy reasons, this is also set if
`options.allowWindowsEscape` is set to the exact value `false`.
### windowsNoMagicRoot
When a pattern starts with a UNC path or drive letter, and in
`nocase:true` mode, do not convert the root portions of the
pattern into a case-insensitive regular expression, and instead
leave them as strings.
This is the default when the platform is `win32` and
`nocase:true` is set.
### preserveMultipleSlashes
By default, multiple `/` characters (other than the leading `//`
in a UNC path, see "UNC Paths" above) are treated as a single
`/`.
That is, a pattern like `a///b` will match the file path `a/b`.
Set `preserveMultipleSlashes: true` to suppress this behavior.
### optimizationLevel
A number indicating the level of optimization that should be done
to the pattern prior to parsing and using it for matches.
Globstar parts `**` are always converted to `*` when `noglobstar`
is set, and multiple adjacent `**` parts are converted into a
single `**` (ie, `a/**/**/b` will be treated as `a/**/b`, as this
is equivalent in all cases).
- `0` - Make no further changes. In this mode, `.` and `..` are
maintained in the pattern, meaning that they must also appear
in the same position in the test path string. Eg, a pattern
like `a/*/../c` will match the string `a/b/../c` but not the
string `a/c`.
- `1` - (default) Remove cases where a double-dot `..` follows a
pattern portion that is not `**`, `.`, `..`, or empty `''`. For
example, the pattern `./a/b/../*` is converted to `./a/*`, and
so it will match the path string `./a/c`, but not the path
string `./a/b/../c`. Dots and empty path portions in the
pattern are preserved.
- `2` (or higher) - Much more aggressive optimizations, suitable
for use with file-walking cases:
- Remove cases where a double-dot `..` follows a pattern
portion that is not `**`, `.`, or empty `''`. Remove empty
and `.` portions of the pattern, where safe to do so (ie,
anywhere other than the last position, the first position, or
the second position in a pattern starting with `/`, as this
may indicate a UNC path on Windows).
- Convert patterns containing `<pre>/**/../<p>/<rest>` into the
equivalent `<pre>/{..,**}/<p>/<rest>`, where `<p>` is a
a pattern portion other than `.`, `..`, `**`, or empty
`''`.
- Dedupe patterns where a `**` portion is present in one and
omitted in another, and it is not the final path portion, and
they are otherwise equivalent. So `{a/**/b,a/b}` becomes
`a/**/b`, because `**` matches against an empty path portion.
- Dedupe patterns where a `*` portion is present in one, and a
non-dot pattern other than `**`, `.`, `..`, or `''` is in the
same position in the other. So `a/{*,x}/b` becomes `a/*/b`,
because `*` can match against `x`.
While these optimizations improve the performance of
file-walking use cases such as [glob](http://npm.im/glob) (ie,
the reason this module exists), there are cases where it will
fail to match a literal string that would have been matched in
optimization level 1 or 0.
Specifically, while the `Minimatch.match()` method will
optimize the file path string in the same ways, resulting in
the same matches, it will fail when tested with the regular
expression provided by `Minimatch.makeRe()`, unless the path
string is first processed with
`minimatch.levelTwoFileOptimize()` or similar.
### platform
When set to `win32`, this will trigger all windows-specific
behaviors (special handling for UNC paths, and treating `\` as
separators in file paths for comparison.)
Defaults to the value of `process.platform`.
## Comparisons to other fnmatch/glob implementations
While strict compliance with the existing standards is a
worthwhile goal, some discrepancies exist between minimatch and
other implementations. Some are intentional, and some are
unavoidable.
If the pattern starts with a `!` character, then it is negated. Set the
`nonegate` flag to suppress this behavior, and treat leading `!`
characters normally. This is perhaps relevant if you wish to start the
pattern with a negative extglob pattern like `!(a|B)`. Multiple `!`
characters at the start of a pattern will negate the pattern multiple
times.
If a pattern starts with `#`, then it is treated as a comment, and
will not match anything. Use `\#` to match a literal `#` at the
start of a line, or set the `nocomment` flag to suppress this behavior.
The double-star character `**` is supported by default, unless the
`noglobstar` flag is set. This is supported in the manner of bsdglob
and bash 4.1, where `**` only has special significance if it is the only
thing in a path part. That is, `a/**/b` will match `a/x/y/b`, but
`a/**b` will not.
If an escaped pattern has no matches, and the `nonull` flag is set,
then minimatch.match returns the pattern as-provided, rather than
interpreting the character escapes. For example,
`minimatch.match([], "\\*a\\?")` will return `"\\*a\\?"` rather than
`"*a?"`. This is akin to setting the `nullglob` option in bash, except
that it does not resolve escaped pattern characters.
If brace expansion is not disabled, then it is performed before any
other interpretation of the glob pattern. Thus, a pattern like
`+(a|{b),c)}`, which would not be valid in bash or zsh, is expanded
**first** into the set of `+(a|b)` and `+(a|c)`, and those patterns are
checked for validity. Since those two are valid, matching proceeds.
Negated extglob patterns are handled as closely as possible to
Bash semantics, but there are some cases with negative extglobs
which are exceedingly difficult to express in a JavaScript
regular expression. In particular the negated pattern
`<start>!(<pattern>*|)*` will in bash match anything that does
not start with `<start><pattern>`. However,
`<start>!(<pattern>*)*` _will_ match paths starting with
`<start><pattern>`, because the empty string can match against
the negated portion. In this library, `<start>!(<pattern>*|)*`
will _not_ match any pattern starting with `<start>`, due to a
difference in precisely which patterns are considered "greedy" in
Regular Expressions vs bash path expansion. This may be fixable,
but not without incurring some complexity and performance costs,
and the trade-off seems to not be worth pursuing.
Note that `fnmatch(3)` in libc is an extremely naive string comparison
matcher, which does not do anything special for slashes. This library is
designed to be used in glob searching and file walkers, and so it does do
special things with `/`. Thus, `foo*` will not match `foo/bar` in this
library, even though it would in `fnmatch(3)`.

View File

@@ -0,0 +1,2 @@
export declare const assertValidPattern: (pattern: any) => void;
//# sourceMappingURL=assert-valid-pattern.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAUlD,CAAA"}

View File

@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.assertValidPattern = void 0;
const MAX_PATTERN_LENGTH = 1024 * 64;
const assertValidPattern = (pattern) => {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern');
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long');
}
};
exports.assertValidPattern = assertValidPattern;
//# sourceMappingURL=assert-valid-pattern.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":";;;AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AAC7B,MAAM,kBAAkB,GAA2B,CACxD,OAAY,EACe,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;KACvC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE;QACvC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;KAC3C;AACH,CAAC,CAAA;AAVY,QAAA,kBAAkB,sBAU9B","sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n"]}

View File

@@ -0,0 +1,20 @@
import { MinimatchOptions, MMRegExp } from './index.js';
export type ExtglobType = '!' | '?' | '+' | '*' | '@';
export declare class AST {
#private;
type: ExtglobType | null;
constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
get hasMagic(): boolean | undefined;
toString(): string;
push(...parts: (string | AST)[]): void;
toJSON(): any[];
isStart(): boolean;
isEnd(): boolean;
copyIn(part: AST | string): void;
clone(parent: AST): AST;
static fromGlob(pattern: string, options?: MinimatchOptions): AST;
toMMPattern(): MMRegExp | string;
get options(): MinimatchOptions;
toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
}
//# sourceMappingURL=ast.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwCvD,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAkCrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;gBAiBtB,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IA+ClB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAY/B,MAAM;IAgBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsIjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CAiMjE"}

View File

@@ -0,0 +1,592 @@
"use strict";
// parse a single path portion
Object.defineProperty(exports, "__esModule", { value: true });
exports.AST = void 0;
const brace_expressions_js_1 = require("./brace-expressions.js");
const unescape_js_1 = require("./unescape.js");
const types = new Set(['!', '?', '+', '*', '@']);
const isExtglobType = (c) => types.has(c);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
class AST {
type;
#root;
#hasMagic;
#uflag = false;
#parts = [];
#parent;
#parentIndex;
#negs;
#filledNegs = false;
#options;
#toString;
// set to true if it's an extglob with no children
// (which really means one child of '')
#emptyExt = false;
constructor(type, parent, options = {}) {
this.type = type;
// extglobs are inherently magical
if (type)
this.#hasMagic = true;
this.#parent = parent;
this.#root = this.#parent ? this.#parent.#root : this;
this.#options = this.#root === this ? options : this.#root.#options;
this.#negs = this.#root === this ? [] : this.#root.#negs;
if (type === '!' && !this.#root.#filledNegs)
this.#negs.push(this);
this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
}
get hasMagic() {
/* c8 ignore start */
if (this.#hasMagic !== undefined)
return this.#hasMagic;
/* c8 ignore stop */
for (const p of this.#parts) {
if (typeof p === 'string')
continue;
if (p.type || p.hasMagic)
return (this.#hasMagic = true);
}
// note: will be undefined until we generate the regexp src and find out
return this.#hasMagic;
}
// reconstructs the pattern
toString() {
if (this.#toString !== undefined)
return this.#toString;
if (!this.type) {
return (this.#toString = this.#parts.map(p => String(p)).join(''));
}
else {
return (this.#toString =
this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
}
}
#fillNegs() {
/* c8 ignore start */
if (this !== this.#root)
throw new Error('should only call on root');
if (this.#filledNegs)
return this;
/* c8 ignore stop */
// call toString() once to fill this out
this.toString();
this.#filledNegs = true;
let n;
while ((n = this.#negs.pop())) {
if (n.type !== '!')
continue;
// walk up the tree, appending everthing that comes AFTER parentIndex
let p = n;
let pp = p.#parent;
while (pp) {
for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
for (const part of n.#parts) {
/* c8 ignore start */
if (typeof part === 'string') {
throw new Error('string part in extglob AST??');
}
/* c8 ignore stop */
part.copyIn(pp.#parts[i]);
}
}
p = pp;
pp = p.#parent;
}
}
return this;
}
push(...parts) {
for (const p of parts) {
if (p === '')
continue;
/* c8 ignore start */
if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
throw new Error('invalid part: ' + p);
}
/* c8 ignore stop */
this.#parts.push(p);
}
}
toJSON() {
const ret = this.type === null
? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
: [this.type, ...this.#parts.map(p => p.toJSON())];
if (this.isStart() && !this.type)
ret.unshift([]);
if (this.isEnd() &&
(this === this.#root ||
(this.#root.#filledNegs && this.#parent?.type === '!'))) {
ret.push({});
}
return ret;
}
isStart() {
if (this.#root === this)
return true;
// if (this.type) return !!this.#parent?.isStart()
if (!this.#parent?.isStart())
return false;
if (this.#parentIndex === 0)
return true;
// if everything AHEAD of this is a negation, then it's still the "start"
const p = this.#parent;
for (let i = 0; i < this.#parentIndex; i++) {
const pp = p.#parts[i];
if (!(pp instanceof AST && pp.type === '!')) {
return false;
}
}
return true;
}
isEnd() {
if (this.#root === this)
return true;
if (this.#parent?.type === '!')
return true;
if (!this.#parent?.isEnd())
return false;
if (!this.type)
return this.#parent?.isEnd();
// if not root, it'll always have a parent
/* c8 ignore start */
const pl = this.#parent ? this.#parent.#parts.length : 0;
/* c8 ignore stop */
return this.#parentIndex === pl - 1;
}
copyIn(part) {
if (typeof part === 'string')
this.push(part);
else
this.push(part.clone(this));
}
clone(parent) {
const c = new AST(this.type, parent);
for (const p of this.#parts) {
c.copyIn(p);
}
return c;
}
static #parseAST(str, ast, pos, opt) {
let escaping = false;
let inBrace = false;
let braceStart = -1;
let braceNeg = false;
if (ast.type === null) {
// outside of a extglob, append until we find a start
let i = pos;
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
ast.push(acc);
acc = '';
const ext = new AST(c, ast);
i = AST.#parseAST(str, ext, i, opt);
ast.push(ext);
continue;
}
acc += c;
}
ast.push(acc);
return i;
}
// some kind of extglob, pos is at the (
// find the next | or )
let i = pos + 1;
let part = new AST(null, ast);
const parts = [];
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
if (isExtglobType(c) && str.charAt(i) === '(') {
part.push(acc);
acc = '';
const ext = new AST(c, part);
part.push(ext);
i = AST.#parseAST(str, ext, i, opt);
continue;
}
if (c === '|') {
part.push(acc);
acc = '';
parts.push(part);
part = new AST(null, ast);
continue;
}
if (c === ')') {
if (acc === '' && ast.#parts.length === 0) {
ast.#emptyExt = true;
}
part.push(acc);
acc = '';
ast.push(...parts, part);
return i;
}
acc += c;
}
// unfinished extglob
// if we got here, it was a malformed extglob! not an extglob, but
// maybe something else in there.
ast.type = null;
ast.#hasMagic = undefined;
ast.#parts = [str.substring(pos - 1)];
return i;
}
static fromGlob(pattern, options = {}) {
const ast = new AST(null, undefined, options);
AST.#parseAST(pattern, ast, 0, options);
return ast;
}
// returns the regular expression if there's magic, or the unescaped
// string if not.
toMMPattern() {
// should only be called on root
/* c8 ignore start */
if (this !== this.#root)
return this.#root.toMMPattern();
/* c8 ignore stop */
const glob = this.toString();
const [re, body, hasMagic, uflag] = this.toRegExpSource();
// if we're in nocase mode, and not nocaseMagicOnly, then we do
// still need a regular expression if we have to case-insensitively
// match capital/lowercase characters.
const anyMagic = hasMagic ||
this.#hasMagic ||
(this.#options.nocase &&
!this.#options.nocaseMagicOnly &&
glob.toUpperCase() !== glob.toLowerCase());
if (!anyMagic) {
return body;
}
const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
return Object.assign(new RegExp(`^${re}$`, flags), {
_src: re,
_glob: glob,
});
}
get options() {
return this.#options;
}
// returns the string match, the regexp source, whether there's magic
// in the regexp (so a regular expression is required) and whether or
// not the uflag is needed for the regular expression (for posix classes)
// TODO: instead of injecting the start/end at this point, just return
// the BODY of the regexp, along with the start/end portions suitable
// for binding the start/end in either a joined full-path makeRe context
// (where we bind to (^|/), or a standalone matchPart context (where
// we bind to ^, and not /). Otherwise slashes get duped!
//
// In part-matching mode, the start is:
// - if not isStart: nothing
// - if traversal possible, but not allowed: ^(?!\.\.?$)
// - if dots allowed or not possible: ^
// - if dots possible and not allowed: ^(?!\.)
// end is:
// - if not isEnd(): nothing
// - else: $
//
// In full-path matching mode, we put the slash at the START of the
// pattern, so start is:
// - if first pattern: same as part-matching mode
// - if not isStart(): nothing
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
// - if dots allowed or not possible: /
// - if dots possible and not allowed: /(?!\.)
// end is:
// - if last pattern, same as part-matching mode
// - else nothing
//
// Always put the (?:$|/) on negated tails, though, because that has to be
// there to bind the end of the negated pattern portion, and it's easier to
// just stick it in now rather than try to inject it later in the middle of
// the pattern.
//
// We can just always return the same end, and leave it up to the caller
// to know whether it's going to be used joined or in parts.
// And, if the start is adjusted slightly, can do the same there:
// - if not isStart: nothing
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
// - if dots allowed or not possible: (?:/|^)
// - if dots possible and not allowed: (?:/|^)(?!\.)
//
// But it's better to have a simpler binding without a conditional, for
// performance, so probably better to return both start options.
//
// Then the caller just ignores the end if it's not the first pattern,
// and the start always gets applied.
//
// But that's always going to be $ if it's the ending pattern, or nothing,
// so the caller can just attach $ at the end of the pattern when building.
//
// So the todo is:
// - better detect what kind of start is needed
// - return both flavors of starting pattern
// - attach $ at the end of the pattern when creating the actual RegExp
//
// Ah, but wait, no, that all only applies to the root when the first pattern
// is not an extglob. If the first pattern IS an extglob, then we need all
// that dot prevention biz to live in the extglob portions, because eg
// +(*|.x*) can match .xy but not .yx.
//
// So, return the two flavors if it's #root and the first child is not an
// AST, otherwise leave it to the child AST to handle it, and there,
// use the (?:^|/) style of start binding.
//
// Even simplified further:
// - Since the start for a join is eg /(?!\.) and the start for a part
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
// or start or whatever) and prepend ^ or / at the Regexp construction.
toRegExpSource(allowDot) {
const dot = allowDot ?? !!this.#options.dot;
if (this.#root === this)
this.#fillNegs();
if (!this.type) {
const noEmpty = this.isStart() && this.isEnd();
const src = this.#parts
.map(p => {
const [re, _, hasMagic, uflag] = typeof p === 'string'
? AST.#parseGlob(p, this.#hasMagic, noEmpty)
: p.toRegExpSource(allowDot);
this.#hasMagic = this.#hasMagic || hasMagic;
this.#uflag = this.#uflag || uflag;
return re;
})
.join('');
let start = '';
if (this.isStart()) {
if (typeof this.#parts[0] === 'string') {
// this is the string that will match the start of the pattern,
// so we need to protect against dots and such.
// '.' and '..' cannot match unless the pattern is that exactly,
// even if it starts with . or dot:true is set.
const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
if (!dotTravAllowed) {
const aps = addPatternStart;
// check if we have a possibility of matching . or ..,
// and prevent that.
const needNoTrav =
// dots are allowed, and the pattern starts with [ or .
(dot && aps.has(src.charAt(0))) ||
// the pattern starts with \., and then [ or .
(src.startsWith('\\.') && aps.has(src.charAt(2))) ||
// the pattern starts with \.\., and then [ or .
(src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
// no need to prevent dots if it can't match a dot, or if a
// sub-pattern will be preventing it anyway.
const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
}
}
}
// append the "end of path portion" pattern to negation tails
let end = '';
if (this.isEnd() &&
this.#root.#filledNegs &&
this.#parent?.type === '!') {
end = '(?:$|\\/)';
}
const final = start + src + end;
return [
final,
(0, unescape_js_1.unescape)(src),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
// We need to calculate the body *twice* if it's a repeat pattern
// at the start, once in nodot mode, then again in dot mode, so a
// pattern like *(?) can match 'x.y'
const repeated = this.type === '*' || this.type === '+';
// some kind of extglob
const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
let body = this.#partsToRegExp(dot);
if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
// invalid extglob, has to at least be *something* present, if it's
// the entire path portion.
const s = this.toString();
this.#parts = [s];
this.type = null;
this.#hasMagic = undefined;
return [s, (0, unescape_js_1.unescape)(this.toString()), false, false];
}
// XXX abstract out this map method
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
? ''
: this.#partsToRegExp(true);
if (bodyDotAllowed === body) {
bodyDotAllowed = '';
}
if (bodyDotAllowed) {
body = `(?:${body})(?:${bodyDotAllowed})*?`;
}
// an empty !() is exactly equivalent to a starNoEmpty
let final = '';
if (this.type === '!' && this.#emptyExt) {
final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
}
else {
const close = this.type === '!'
? // !() must match something,but !(x) can match ''
'))' +
(this.isStart() && !dot && !allowDot ? startNoDot : '') +
star +
')'
: this.type === '@'
? ')'
: this.type === '?'
? ')?'
: this.type === '+' && bodyDotAllowed
? ')'
: this.type === '*' && bodyDotAllowed
? `)?`
: `)${this.type}`;
final = start + body + close;
}
return [
final,
(0, unescape_js_1.unescape)(body),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
#partsToRegExp(dot) {
return this.#parts
.map(p => {
// extglob ASTs should only contain parent ASTs
/* c8 ignore start */
if (typeof p === 'string') {
throw new Error('string type in extglob ast??');
}
/* c8 ignore stop */
// can ignore hasMagic, because extglobs are already always magic
const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
this.#uflag = this.#uflag || uflag;
return re;
})
.filter(p => !(this.isStart() && this.isEnd()) || !!p)
.join('|');
}
static #parseGlob(glob, hasMagic, noEmpty = false) {
let escaping = false;
let re = '';
let uflag = false;
for (let i = 0; i < glob.length; i++) {
const c = glob.charAt(i);
if (escaping) {
escaping = false;
re += (reSpecials.has(c) ? '\\' : '') + c;
continue;
}
if (c === '\\') {
if (i === glob.length - 1) {
re += '\\\\';
}
else {
escaping = true;
}
continue;
}
if (c === '[') {
const [src, needUflag, consumed, magic] = (0, brace_expressions_js_1.parseClass)(glob, i);
if (consumed) {
re += src;
uflag = uflag || needUflag;
i += consumed - 1;
hasMagic = hasMagic || magic;
continue;
}
}
if (c === '*') {
if (noEmpty && glob === '*')
re += starNoEmpty;
else
re += star;
hasMagic = true;
continue;
}
if (c === '?') {
re += qmark;
hasMagic = true;
continue;
}
re += regExpEscape(c);
}
return [re, (0, unescape_js_1.unescape)(glob), !!hasMagic, uflag];
}
}
exports.AST = AST;
//# sourceMappingURL=ast.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
export type ParseClassResult = [
src: string,
uFlag: boolean,
consumed: number,
hasMagic: boolean
];
export declare const parseClass: (glob: string, position: number) => ParseClassResult;
//# sourceMappingURL=brace-expressions.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AA+BA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,SACf,MAAM,YACF,MAAM,qBA8HjB,CAAA"}

View File

@@ -0,0 +1,152 @@
"use strict";
// translate the various posix character classes into unicode properties
// this works across all unicode locales
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseClass = void 0;
// { <posix class>: [<translation>, /u flag required, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
'[:alpha:]': ['\\p{L}\\p{Nl}', true],
'[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
'[:blank:]': ['\\p{Zs}\\t', true],
'[:cntrl:]': ['\\p{Cc}', true],
'[:digit:]': ['\\p{Nd}', true],
'[:graph:]': ['\\p{Z}\\p{C}', true, true],
'[:lower:]': ['\\p{Ll}', true],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}', true],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
'[:upper:]': ['\\p{Lu}', true],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
'[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
const parseClass = (glob, position) => {
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = glob.charAt(i);
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return ['$.', false, glob.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
}
else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = '';
i++;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + 1)) {
ranges.push(braceEscape(c + '-'));
i += 2;
continue;
}
if (glob.startsWith('-', i + 1)) {
rangeStart = c;
i += 2;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return ['', false, 0, false];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return ['$.', false, glob.length - pos, true];
}
// if we got one positive range, and it's a single character, then that's
// not actually a magic pattern, it's just that one literal character.
// we should not treat that as "magic", we should just return the literal
// character. [_] is a perfectly valid way to escape glob magic chars.
if (negs.length === 0 &&
ranges.length === 1 &&
/^\\?.$/.test(ranges[0]) &&
!negate) {
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r), false, endPos - pos, false];
}
const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
const comb = ranges.length && negs.length
? '(' + sranges + '|' + snegs + ')'
: ranges.length
? sranges
: snegs;
return [comb, uflag, endPos - pos, true];
};
exports.parseClass = parseClass;
//# sourceMappingURL=brace-expressions.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
import { MinimatchOptions } from './index.js';
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*/
export declare const escape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, 'windowsPathsNoEscape'>) => string;
//# sourceMappingURL=escape.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,MACd,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAQlD,CAAA"}

View File

@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.escape = void 0;
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*/
const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
// don't need to escape +@! because we escape the parens
// that make those magic, and escaping ! as [!] isn't valid,
// because [!]] is a valid glob class meaning not ']'.
return windowsPathsNoEscape
? s.replace(/[?*()[\]]/g, '[$&]')
: s.replace(/[?*()[\]\\]/g, '\\$&');
};
exports.escape = escape;
//# sourceMappingURL=escape.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":";;;AACA;;;;;;;;GAQG;AACI,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA;AAZY,QAAA,MAAM,UAYlB","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]}

View File

@@ -0,0 +1,94 @@
import { AST } from './ast.js';
type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
export interface MinimatchOptions {
nobrace?: boolean;
nocomment?: boolean;
nonegate?: boolean;
debug?: boolean;
noglobstar?: boolean;
noext?: boolean;
nonull?: boolean;
windowsPathsNoEscape?: boolean;
allowWindowsEscape?: boolean;
partial?: boolean;
dot?: boolean;
nocase?: boolean;
nocaseMagicOnly?: boolean;
magicalBraces?: boolean;
matchBase?: boolean;
flipNegate?: boolean;
preserveMultipleSlashes?: boolean;
optimizationLevel?: number;
platform?: Platform;
windowsNoMagicRoot?: boolean;
}
export declare const minimatch: {
(p: string, pattern: string, options?: MinimatchOptions): boolean;
sep: Sep;
GLOBSTAR: typeof GLOBSTAR;
filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
defaults: (def: MinimatchOptions) => typeof minimatch;
braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
AST: typeof AST;
Minimatch: typeof Minimatch;
escape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
unescape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
};
type Sep = '\\' | '/';
export declare const sep: Sep;
export declare const GLOBSTAR: unique symbol;
export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
export declare const defaults: (def: MinimatchOptions) => typeof minimatch;
export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
export type MMRegExp = RegExp & {
_src?: string;
_glob?: string;
};
export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
export type ParseReturn = ParseReturnFiltered | false;
export declare class Minimatch {
options: MinimatchOptions;
set: ParseReturnFiltered[][];
pattern: string;
windowsPathsNoEscape: boolean;
nonegate: boolean;
negate: boolean;
comment: boolean;
empty: boolean;
preserveMultipleSlashes: boolean;
partial: boolean;
globSet: string[];
globParts: string[][];
nocase: boolean;
isWindows: boolean;
platform: Platform;
windowsNoMagicRoot: boolean;
regexp: false | null | MMRegExp;
constructor(pattern: string, options?: MinimatchOptions);
hasMagic(): boolean;
debug(..._: any[]): void;
make(): void;
preprocess(globParts: string[][]): string[][];
adjascentGlobstarOptimize(globParts: string[][]): string[][];
levelOneOptimize(globParts: string[][]): string[][];
levelTwoFileOptimize(parts: string | string[]): string[];
firstPhasePreProcess(globParts: string[][]): string[][];
secondPhasePreProcess(globParts: string[][]): string[][];
partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[];
parseNegate(): void;
matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean;
braceExpand(): string[];
parse(pattern: string): ParseReturn;
makeRe(): false | MMRegExp;
slashSplit(p: string): string[];
match(f: string, partial?: boolean): boolean;
static defaults(def: MinimatchOptions): typeof Minimatch;
}
export { AST } from './ast.js';
export { escape } from './escape.js';
export { unescape } from './unescape.js';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAe,MAAM,UAAU,CAAA;AAI3C,KAAK,QAAQ,GACT,KAAK,GACL,SAAS,GACT,QAAQ,GACR,SAAS,GACT,OAAO,GACP,OAAO,GACP,SAAS,GACT,OAAO,GACP,OAAO,GACP,QAAQ,GACR,QAAQ,CAAA;AAEZ,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,uBAAuB,CAAC,EAAE,OAAO,CAAA;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,EAAE,QAAQ,CAAA;IACnB,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAC7B;AAED,eAAO,MAAM,SAAS;QACjB,MAAM,WACA,MAAM,YACN,gBAAgB;;;sBAuGf,MAAM,YAAW,gBAAgB,SACvC,MAAM;oBAOkB,gBAAgB,KAAG,gBAAgB;2BA6EtD,MAAM,YACN,gBAAgB;sBA2BK,MAAM,YAAW,gBAAgB;kBAKzD,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB;;;;;CArN1B,CAAA;AA+DD,KAAK,GAAG,GAAG,IAAI,GAAG,GAAG,CAAA;AAOrB,eAAO,MAAM,GAAG,KAAgE,CAAA;AAGhF,eAAO,MAAM,QAAQ,eAAwB,CAAA;AAmB7C,eAAO,MAAM,MAAM,YACP,MAAM,YAAW,gBAAgB,SACvC,MAAM,YACsB,CAAA;AAMlC,eAAO,MAAM,QAAQ,QAAS,gBAAgB,KAAG,gBA+DhD,CAAA;AAaD,eAAO,MAAM,WAAW,YACb,MAAM,YACN,gBAAgB,aAY1B,CAAA;AAeD,eAAO,MAAM,MAAM,YAAa,MAAM,YAAW,gBAAgB,qBACvB,CAAA;AAG1C,eAAO,MAAM,KAAK,SACV,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB,aAQ1B,CAAA;AAQD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,QAAQ,CAAA;AACrE,MAAM,MAAM,WAAW,GAAG,mBAAmB,GAAG,KAAK,CAAA;AAErD,qBAAa,SAAS;IACpB,OAAO,EAAE,gBAAgB,CAAA;IACzB,GAAG,EAAE,mBAAmB,EAAE,EAAE,CAAA;IAC5B,OAAO,EAAE,MAAM,CAAA;IAEf,oBAAoB,EAAE,OAAO,CAAA;IAC7B,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,OAAO,CAAA;IACf,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,OAAO,CAAA;IACd,uBAAuB,EAAE,OAAO,CAAA;IAChC,OAAO,EAAE,OAAO,CAAA;IAChB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,SAAS,EAAE,MAAM,EAAE,EAAE,CAAA;IACrB,MAAM,EAAE,OAAO,CAAA;IAEf,SAAS,EAAE,OAAO,CAAA;IAClB,QAAQ,EAAE,QAAQ,CAAA;IAClB,kBAAkB,EAAE,OAAO,CAAA;IAE3B,MAAM,EAAE,KAAK,GAAG,IAAI,GAAG,QAAQ,CAAA;gBACnB,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAkC3D,QAAQ,IAAI,OAAO;IAYnB,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE;IAEjB,IAAI;IA0FJ,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IA8BhC,yBAAyB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IAiB/C,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IAoBtC,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE;IA6D7C,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IA0F1C,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,EAAE;IAkBxD,UAAU,CACR,CAAC,EAAE,MAAM,EAAE,EACX,CAAC,EAAE,MAAM,EAAE,EACX,YAAY,GAAE,OAAe,GAC5B,KAAK,GAAG,MAAM,EAAE;IA+CnB,WAAW;IAqBX,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,OAAO,GAAE,OAAe;IAiNzE,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;IAiDnC,MAAM;IAsFN,UAAU,CAAC,CAAC,EAAE,MAAM;IAepB,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,UAAe;IAiEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
{
"type": "commonjs"
}

View File

@@ -0,0 +1,17 @@
import { MinimatchOptions } from './index.js';
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link windowsPathsNoEscape} option is used, then square-brace
* escapes are removed, but not backslash escapes. For example, it will turn
* the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
* becuase `\` is a path separator in `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both brace escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*/
export declare const unescape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, 'windowsPathsNoEscape'>) => string;
//# sourceMappingURL=unescape.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,QAAQ,MAChB,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAKlD,CAAA"}

View File

@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.unescape = void 0;
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link windowsPathsNoEscape} option is used, then square-brace
* escapes are removed, but not backslash escapes. For example, it will turn
* the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
* becuase `\` is a path separator in `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both brace escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*/
const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
return windowsPathsNoEscape
? s.replace(/\[([^\/\\])\]/g, '$1')
: s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
};
exports.unescape = unescape;
//# sourceMappingURL=unescape.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":";;;AACA;;;;;;;;;;;;;GAaG;AACI,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;QACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC,CAAA;AAChF,CAAC,CAAA;AATY,QAAA,QAAQ,YASpB","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes. For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n"]}

View File

@@ -0,0 +1,2 @@
export declare const assertValidPattern: (pattern: any) => void;
//# sourceMappingURL=assert-valid-pattern.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"assert-valid-pattern.d.ts","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AACA,eAAO,MAAM,kBAAkB,EAAE,CAAC,OAAO,EAAE,GAAG,KAAK,IAUlD,CAAA"}

View File

@@ -0,0 +1,10 @@
const MAX_PATTERN_LENGTH = 1024 * 64;
export const assertValidPattern = (pattern) => {
if (typeof pattern !== 'string') {
throw new TypeError('invalid pattern');
}
if (pattern.length > MAX_PATTERN_LENGTH) {
throw new TypeError('pattern is too long');
}
};
//# sourceMappingURL=assert-valid-pattern.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"assert-valid-pattern.js","sourceRoot":"","sources":["../../src/assert-valid-pattern.ts"],"names":[],"mappings":"AAAA,MAAM,kBAAkB,GAAG,IAAI,GAAG,EAAE,CAAA;AACpC,MAAM,CAAC,MAAM,kBAAkB,GAA2B,CACxD,OAAY,EACe,EAAE;IAC7B,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;QAC/B,MAAM,IAAI,SAAS,CAAC,iBAAiB,CAAC,CAAA;KACvC;IAED,IAAI,OAAO,CAAC,MAAM,GAAG,kBAAkB,EAAE;QACvC,MAAM,IAAI,SAAS,CAAC,qBAAqB,CAAC,CAAA;KAC3C;AACH,CAAC,CAAA","sourcesContent":["const MAX_PATTERN_LENGTH = 1024 * 64\nexport const assertValidPattern: (pattern: any) => void = (\n pattern: any\n): asserts pattern is string => {\n if (typeof pattern !== 'string') {\n throw new TypeError('invalid pattern')\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new TypeError('pattern is too long')\n }\n}\n"]}

View File

@@ -0,0 +1,20 @@
import { MinimatchOptions, MMRegExp } from './index.js';
export type ExtglobType = '!' | '?' | '+' | '*' | '@';
export declare class AST {
#private;
type: ExtglobType | null;
constructor(type: ExtglobType | null, parent?: AST, options?: MinimatchOptions);
get hasMagic(): boolean | undefined;
toString(): string;
push(...parts: (string | AST)[]): void;
toJSON(): any[];
isStart(): boolean;
isEnd(): boolean;
copyIn(part: AST | string): void;
clone(parent: AST): AST;
static fromGlob(pattern: string, options?: MinimatchOptions): AST;
toMMPattern(): MMRegExp | string;
get options(): MinimatchOptions;
toRegExpSource(allowDot?: boolean): [re: string, body: string, hasMagic: boolean, uflag: boolean];
}
//# sourceMappingURL=ast.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ast.d.ts","sourceRoot":"","sources":["../../src/ast.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,gBAAgB,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAA;AAwCvD,MAAM,MAAM,WAAW,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAA;AAkCrD,qBAAa,GAAG;;IACd,IAAI,EAAE,WAAW,GAAG,IAAI,CAAA;gBAiBtB,IAAI,EAAE,WAAW,GAAG,IAAI,EACxB,MAAM,CAAC,EAAE,GAAG,EACZ,OAAO,GAAE,gBAAqB;IAahC,IAAI,QAAQ,IAAI,OAAO,GAAG,SAAS,CAUlC;IAGD,QAAQ,IAAI,MAAM;IA+ClB,IAAI,CAAC,GAAG,KAAK,EAAE,CAAC,MAAM,GAAG,GAAG,CAAC,EAAE;IAY/B,MAAM;IAgBN,OAAO,IAAI,OAAO;IAgBlB,KAAK,IAAI,OAAO;IAYhB,MAAM,CAAC,IAAI,EAAE,GAAG,GAAG,MAAM;IAKzB,KAAK,CAAC,MAAM,EAAE,GAAG;IAsIjB,MAAM,CAAC,QAAQ,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAQ/D,WAAW,IAAI,QAAQ,GAAG,MAAM;IA2BhC,IAAI,OAAO,qBAEV;IAuED,cAAc,CACZ,QAAQ,CAAC,EAAE,OAAO,GACjB,CAAC,EAAE,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,CAAC;CAiMjE"}

View File

@@ -0,0 +1,588 @@
// parse a single path portion
import { parseClass } from './brace-expressions.js';
import { unescape } from './unescape.js';
const types = new Set(['!', '?', '+', '*', '@']);
const isExtglobType = (c) => types.has(c);
// Patterns that get prepended to bind to the start of either the
// entire string, or just a single path portion, to prevent dots
// and/or traversal patterns, when needed.
// Exts don't need the ^ or / bit, because the root binds that already.
const startNoTraversal = '(?!(?:^|/)\\.\\.?(?:$|/))';
const startNoDot = '(?!\\.)';
// characters that indicate a start of pattern needs the "no dots" bit,
// because a dot *might* be matched. ( is not in the list, because in
// the case of a child extglob, it will handle the prevention itself.
const addPatternStart = new Set(['[', '.']);
// cases where traversal is A-OK, no dot prevention needed
const justDots = new Set(['..', '.']);
const reSpecials = new Set('().*{}+?[]^$\\!');
const regExpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// any single thing other than /
const qmark = '[^/]';
// * => any number of characters
const star = qmark + '*?';
// use + when we need to ensure that *something* matches, because the * is
// the only thing in the path portion.
const starNoEmpty = qmark + '+?';
// remove the \ chars that we added if we end up doing a nonmagic compare
// const deslash = (s: string) => s.replace(/\\(.)/g, '$1')
export class AST {
type;
#root;
#hasMagic;
#uflag = false;
#parts = [];
#parent;
#parentIndex;
#negs;
#filledNegs = false;
#options;
#toString;
// set to true if it's an extglob with no children
// (which really means one child of '')
#emptyExt = false;
constructor(type, parent, options = {}) {
this.type = type;
// extglobs are inherently magical
if (type)
this.#hasMagic = true;
this.#parent = parent;
this.#root = this.#parent ? this.#parent.#root : this;
this.#options = this.#root === this ? options : this.#root.#options;
this.#negs = this.#root === this ? [] : this.#root.#negs;
if (type === '!' && !this.#root.#filledNegs)
this.#negs.push(this);
this.#parentIndex = this.#parent ? this.#parent.#parts.length : 0;
}
get hasMagic() {
/* c8 ignore start */
if (this.#hasMagic !== undefined)
return this.#hasMagic;
/* c8 ignore stop */
for (const p of this.#parts) {
if (typeof p === 'string')
continue;
if (p.type || p.hasMagic)
return (this.#hasMagic = true);
}
// note: will be undefined until we generate the regexp src and find out
return this.#hasMagic;
}
// reconstructs the pattern
toString() {
if (this.#toString !== undefined)
return this.#toString;
if (!this.type) {
return (this.#toString = this.#parts.map(p => String(p)).join(''));
}
else {
return (this.#toString =
this.type + '(' + this.#parts.map(p => String(p)).join('|') + ')');
}
}
#fillNegs() {
/* c8 ignore start */
if (this !== this.#root)
throw new Error('should only call on root');
if (this.#filledNegs)
return this;
/* c8 ignore stop */
// call toString() once to fill this out
this.toString();
this.#filledNegs = true;
let n;
while ((n = this.#negs.pop())) {
if (n.type !== '!')
continue;
// walk up the tree, appending everthing that comes AFTER parentIndex
let p = n;
let pp = p.#parent;
while (pp) {
for (let i = p.#parentIndex + 1; !pp.type && i < pp.#parts.length; i++) {
for (const part of n.#parts) {
/* c8 ignore start */
if (typeof part === 'string') {
throw new Error('string part in extglob AST??');
}
/* c8 ignore stop */
part.copyIn(pp.#parts[i]);
}
}
p = pp;
pp = p.#parent;
}
}
return this;
}
push(...parts) {
for (const p of parts) {
if (p === '')
continue;
/* c8 ignore start */
if (typeof p !== 'string' && !(p instanceof AST && p.#parent === this)) {
throw new Error('invalid part: ' + p);
}
/* c8 ignore stop */
this.#parts.push(p);
}
}
toJSON() {
const ret = this.type === null
? this.#parts.slice().map(p => (typeof p === 'string' ? p : p.toJSON()))
: [this.type, ...this.#parts.map(p => p.toJSON())];
if (this.isStart() && !this.type)
ret.unshift([]);
if (this.isEnd() &&
(this === this.#root ||
(this.#root.#filledNegs && this.#parent?.type === '!'))) {
ret.push({});
}
return ret;
}
isStart() {
if (this.#root === this)
return true;
// if (this.type) return !!this.#parent?.isStart()
if (!this.#parent?.isStart())
return false;
if (this.#parentIndex === 0)
return true;
// if everything AHEAD of this is a negation, then it's still the "start"
const p = this.#parent;
for (let i = 0; i < this.#parentIndex; i++) {
const pp = p.#parts[i];
if (!(pp instanceof AST && pp.type === '!')) {
return false;
}
}
return true;
}
isEnd() {
if (this.#root === this)
return true;
if (this.#parent?.type === '!')
return true;
if (!this.#parent?.isEnd())
return false;
if (!this.type)
return this.#parent?.isEnd();
// if not root, it'll always have a parent
/* c8 ignore start */
const pl = this.#parent ? this.#parent.#parts.length : 0;
/* c8 ignore stop */
return this.#parentIndex === pl - 1;
}
copyIn(part) {
if (typeof part === 'string')
this.push(part);
else
this.push(part.clone(this));
}
clone(parent) {
const c = new AST(this.type, parent);
for (const p of this.#parts) {
c.copyIn(p);
}
return c;
}
static #parseAST(str, ast, pos, opt) {
let escaping = false;
let inBrace = false;
let braceStart = -1;
let braceNeg = false;
if (ast.type === null) {
// outside of a extglob, append until we find a start
let i = pos;
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
if (!opt.noext && isExtglobType(c) && str.charAt(i) === '(') {
ast.push(acc);
acc = '';
const ext = new AST(c, ast);
i = AST.#parseAST(str, ext, i, opt);
ast.push(ext);
continue;
}
acc += c;
}
ast.push(acc);
return i;
}
// some kind of extglob, pos is at the (
// find the next | or )
let i = pos + 1;
let part = new AST(null, ast);
const parts = [];
let acc = '';
while (i < str.length) {
const c = str.charAt(i++);
// still accumulate escapes at this point, but we do ignore
// starts that are escaped
if (escaping || c === '\\') {
escaping = !escaping;
acc += c;
continue;
}
if (inBrace) {
if (i === braceStart + 1) {
if (c === '^' || c === '!') {
braceNeg = true;
}
}
else if (c === ']' && !(i === braceStart + 2 && braceNeg)) {
inBrace = false;
}
acc += c;
continue;
}
else if (c === '[') {
inBrace = true;
braceStart = i;
braceNeg = false;
acc += c;
continue;
}
if (isExtglobType(c) && str.charAt(i) === '(') {
part.push(acc);
acc = '';
const ext = new AST(c, part);
part.push(ext);
i = AST.#parseAST(str, ext, i, opt);
continue;
}
if (c === '|') {
part.push(acc);
acc = '';
parts.push(part);
part = new AST(null, ast);
continue;
}
if (c === ')') {
if (acc === '' && ast.#parts.length === 0) {
ast.#emptyExt = true;
}
part.push(acc);
acc = '';
ast.push(...parts, part);
return i;
}
acc += c;
}
// unfinished extglob
// if we got here, it was a malformed extglob! not an extglob, but
// maybe something else in there.
ast.type = null;
ast.#hasMagic = undefined;
ast.#parts = [str.substring(pos - 1)];
return i;
}
static fromGlob(pattern, options = {}) {
const ast = new AST(null, undefined, options);
AST.#parseAST(pattern, ast, 0, options);
return ast;
}
// returns the regular expression if there's magic, or the unescaped
// string if not.
toMMPattern() {
// should only be called on root
/* c8 ignore start */
if (this !== this.#root)
return this.#root.toMMPattern();
/* c8 ignore stop */
const glob = this.toString();
const [re, body, hasMagic, uflag] = this.toRegExpSource();
// if we're in nocase mode, and not nocaseMagicOnly, then we do
// still need a regular expression if we have to case-insensitively
// match capital/lowercase characters.
const anyMagic = hasMagic ||
this.#hasMagic ||
(this.#options.nocase &&
!this.#options.nocaseMagicOnly &&
glob.toUpperCase() !== glob.toLowerCase());
if (!anyMagic) {
return body;
}
const flags = (this.#options.nocase ? 'i' : '') + (uflag ? 'u' : '');
return Object.assign(new RegExp(`^${re}$`, flags), {
_src: re,
_glob: glob,
});
}
get options() {
return this.#options;
}
// returns the string match, the regexp source, whether there's magic
// in the regexp (so a regular expression is required) and whether or
// not the uflag is needed for the regular expression (for posix classes)
// TODO: instead of injecting the start/end at this point, just return
// the BODY of the regexp, along with the start/end portions suitable
// for binding the start/end in either a joined full-path makeRe context
// (where we bind to (^|/), or a standalone matchPart context (where
// we bind to ^, and not /). Otherwise slashes get duped!
//
// In part-matching mode, the start is:
// - if not isStart: nothing
// - if traversal possible, but not allowed: ^(?!\.\.?$)
// - if dots allowed or not possible: ^
// - if dots possible and not allowed: ^(?!\.)
// end is:
// - if not isEnd(): nothing
// - else: $
//
// In full-path matching mode, we put the slash at the START of the
// pattern, so start is:
// - if first pattern: same as part-matching mode
// - if not isStart(): nothing
// - if traversal possible, but not allowed: /(?!\.\.?(?:$|/))
// - if dots allowed or not possible: /
// - if dots possible and not allowed: /(?!\.)
// end is:
// - if last pattern, same as part-matching mode
// - else nothing
//
// Always put the (?:$|/) on negated tails, though, because that has to be
// there to bind the end of the negated pattern portion, and it's easier to
// just stick it in now rather than try to inject it later in the middle of
// the pattern.
//
// We can just always return the same end, and leave it up to the caller
// to know whether it's going to be used joined or in parts.
// And, if the start is adjusted slightly, can do the same there:
// - if not isStart: nothing
// - if traversal possible, but not allowed: (?:/|^)(?!\.\.?$)
// - if dots allowed or not possible: (?:/|^)
// - if dots possible and not allowed: (?:/|^)(?!\.)
//
// But it's better to have a simpler binding without a conditional, for
// performance, so probably better to return both start options.
//
// Then the caller just ignores the end if it's not the first pattern,
// and the start always gets applied.
//
// But that's always going to be $ if it's the ending pattern, or nothing,
// so the caller can just attach $ at the end of the pattern when building.
//
// So the todo is:
// - better detect what kind of start is needed
// - return both flavors of starting pattern
// - attach $ at the end of the pattern when creating the actual RegExp
//
// Ah, but wait, no, that all only applies to the root when the first pattern
// is not an extglob. If the first pattern IS an extglob, then we need all
// that dot prevention biz to live in the extglob portions, because eg
// +(*|.x*) can match .xy but not .yx.
//
// So, return the two flavors if it's #root and the first child is not an
// AST, otherwise leave it to the child AST to handle it, and there,
// use the (?:^|/) style of start binding.
//
// Even simplified further:
// - Since the start for a join is eg /(?!\.) and the start for a part
// is ^(?!\.), we can just prepend (?!\.) to the pattern (either root
// or start or whatever) and prepend ^ or / at the Regexp construction.
toRegExpSource(allowDot) {
const dot = allowDot ?? !!this.#options.dot;
if (this.#root === this)
this.#fillNegs();
if (!this.type) {
const noEmpty = this.isStart() && this.isEnd();
const src = this.#parts
.map(p => {
const [re, _, hasMagic, uflag] = typeof p === 'string'
? AST.#parseGlob(p, this.#hasMagic, noEmpty)
: p.toRegExpSource(allowDot);
this.#hasMagic = this.#hasMagic || hasMagic;
this.#uflag = this.#uflag || uflag;
return re;
})
.join('');
let start = '';
if (this.isStart()) {
if (typeof this.#parts[0] === 'string') {
// this is the string that will match the start of the pattern,
// so we need to protect against dots and such.
// '.' and '..' cannot match unless the pattern is that exactly,
// even if it starts with . or dot:true is set.
const dotTravAllowed = this.#parts.length === 1 && justDots.has(this.#parts[0]);
if (!dotTravAllowed) {
const aps = addPatternStart;
// check if we have a possibility of matching . or ..,
// and prevent that.
const needNoTrav =
// dots are allowed, and the pattern starts with [ or .
(dot && aps.has(src.charAt(0))) ||
// the pattern starts with \., and then [ or .
(src.startsWith('\\.') && aps.has(src.charAt(2))) ||
// the pattern starts with \.\., and then [ or .
(src.startsWith('\\.\\.') && aps.has(src.charAt(4)));
// no need to prevent dots if it can't match a dot, or if a
// sub-pattern will be preventing it anyway.
const needNoDot = !dot && !allowDot && aps.has(src.charAt(0));
start = needNoTrav ? startNoTraversal : needNoDot ? startNoDot : '';
}
}
}
// append the "end of path portion" pattern to negation tails
let end = '';
if (this.isEnd() &&
this.#root.#filledNegs &&
this.#parent?.type === '!') {
end = '(?:$|\\/)';
}
const final = start + src + end;
return [
final,
unescape(src),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
// We need to calculate the body *twice* if it's a repeat pattern
// at the start, once in nodot mode, then again in dot mode, so a
// pattern like *(?) can match 'x.y'
const repeated = this.type === '*' || this.type === '+';
// some kind of extglob
const start = this.type === '!' ? '(?:(?!(?:' : '(?:';
let body = this.#partsToRegExp(dot);
if (this.isStart() && this.isEnd() && !body && this.type !== '!') {
// invalid extglob, has to at least be *something* present, if it's
// the entire path portion.
const s = this.toString();
this.#parts = [s];
this.type = null;
this.#hasMagic = undefined;
return [s, unescape(this.toString()), false, false];
}
// XXX abstract out this map method
let bodyDotAllowed = !repeated || allowDot || dot || !startNoDot
? ''
: this.#partsToRegExp(true);
if (bodyDotAllowed === body) {
bodyDotAllowed = '';
}
if (bodyDotAllowed) {
body = `(?:${body})(?:${bodyDotAllowed})*?`;
}
// an empty !() is exactly equivalent to a starNoEmpty
let final = '';
if (this.type === '!' && this.#emptyExt) {
final = (this.isStart() && !dot ? startNoDot : '') + starNoEmpty;
}
else {
const close = this.type === '!'
? // !() must match something,but !(x) can match ''
'))' +
(this.isStart() && !dot && !allowDot ? startNoDot : '') +
star +
')'
: this.type === '@'
? ')'
: this.type === '?'
? ')?'
: this.type === '+' && bodyDotAllowed
? ')'
: this.type === '*' && bodyDotAllowed
? `)?`
: `)${this.type}`;
final = start + body + close;
}
return [
final,
unescape(body),
(this.#hasMagic = !!this.#hasMagic),
this.#uflag,
];
}
#partsToRegExp(dot) {
return this.#parts
.map(p => {
// extglob ASTs should only contain parent ASTs
/* c8 ignore start */
if (typeof p === 'string') {
throw new Error('string type in extglob ast??');
}
/* c8 ignore stop */
// can ignore hasMagic, because extglobs are already always magic
const [re, _, _hasMagic, uflag] = p.toRegExpSource(dot);
this.#uflag = this.#uflag || uflag;
return re;
})
.filter(p => !(this.isStart() && this.isEnd()) || !!p)
.join('|');
}
static #parseGlob(glob, hasMagic, noEmpty = false) {
let escaping = false;
let re = '';
let uflag = false;
for (let i = 0; i < glob.length; i++) {
const c = glob.charAt(i);
if (escaping) {
escaping = false;
re += (reSpecials.has(c) ? '\\' : '') + c;
continue;
}
if (c === '\\') {
if (i === glob.length - 1) {
re += '\\\\';
}
else {
escaping = true;
}
continue;
}
if (c === '[') {
const [src, needUflag, consumed, magic] = parseClass(glob, i);
if (consumed) {
re += src;
uflag = uflag || needUflag;
i += consumed - 1;
hasMagic = hasMagic || magic;
continue;
}
}
if (c === '*') {
if (noEmpty && glob === '*')
re += starNoEmpty;
else
re += star;
hasMagic = true;
continue;
}
if (c === '?') {
re += qmark;
hasMagic = true;
continue;
}
re += regExpEscape(c);
}
return [re, unescape(glob), !!hasMagic, uflag];
}
}
//# sourceMappingURL=ast.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,8 @@
export type ParseClassResult = [
src: string,
uFlag: boolean,
consumed: number,
hasMagic: boolean
];
export declare const parseClass: (glob: string, position: number) => ParseClassResult;
//# sourceMappingURL=brace-expressions.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"brace-expressions.d.ts","sourceRoot":"","sources":["../../src/brace-expressions.ts"],"names":[],"mappings":"AA+BA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,GAAG,EAAE,MAAM;IACX,KAAK,EAAE,OAAO;IACd,QAAQ,EAAE,MAAM;IAChB,QAAQ,EAAE,OAAO;CAClB,CAAA;AAQD,eAAO,MAAM,UAAU,SACf,MAAM,YACF,MAAM,qBA8HjB,CAAA"}

View File

@@ -0,0 +1,148 @@
// translate the various posix character classes into unicode properties
// this works across all unicode locales
// { <posix class>: [<translation>, /u flag required, negated]
const posixClasses = {
'[:alnum:]': ['\\p{L}\\p{Nl}\\p{Nd}', true],
'[:alpha:]': ['\\p{L}\\p{Nl}', true],
'[:ascii:]': ['\\x' + '00-\\x' + '7f', false],
'[:blank:]': ['\\p{Zs}\\t', true],
'[:cntrl:]': ['\\p{Cc}', true],
'[:digit:]': ['\\p{Nd}', true],
'[:graph:]': ['\\p{Z}\\p{C}', true, true],
'[:lower:]': ['\\p{Ll}', true],
'[:print:]': ['\\p{C}', true],
'[:punct:]': ['\\p{P}', true],
'[:space:]': ['\\p{Z}\\t\\r\\n\\v\\f', true],
'[:upper:]': ['\\p{Lu}', true],
'[:word:]': ['\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}', true],
'[:xdigit:]': ['A-Fa-f0-9', false],
};
// only need to escape a few things inside of brace expressions
// escapes: [ \ ] -
const braceEscape = (s) => s.replace(/[[\]\\-]/g, '\\$&');
// escape all regexp magic characters
const regexpEscape = (s) => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&');
// everything has already been escaped, we just have to join
const rangesToString = (ranges) => ranges.join('');
// takes a glob string at a posix brace expression, and returns
// an equivalent regular expression source, and boolean indicating
// whether the /u flag needs to be applied, and the number of chars
// consumed to parse the character class.
// This also removes out of order ranges, and returns ($.) if the
// entire class just no good.
export const parseClass = (glob, position) => {
const pos = position;
/* c8 ignore start */
if (glob.charAt(pos) !== '[') {
throw new Error('not in a brace expression');
}
/* c8 ignore stop */
const ranges = [];
const negs = [];
let i = pos + 1;
let sawStart = false;
let uflag = false;
let escaping = false;
let negate = false;
let endPos = pos;
let rangeStart = '';
WHILE: while (i < glob.length) {
const c = glob.charAt(i);
if ((c === '!' || c === '^') && i === pos + 1) {
negate = true;
i++;
continue;
}
if (c === ']' && sawStart && !escaping) {
endPos = i + 1;
break;
}
sawStart = true;
if (c === '\\') {
if (!escaping) {
escaping = true;
i++;
continue;
}
// escaped \ char, fall through and treat like normal char
}
if (c === '[' && !escaping) {
// either a posix class, a collation equivalent, or just a [
for (const [cls, [unip, u, neg]] of Object.entries(posixClasses)) {
if (glob.startsWith(cls, i)) {
// invalid, [a-[] is fine, but not [a-[:alpha]]
if (rangeStart) {
return ['$.', false, glob.length - pos, true];
}
i += cls.length;
if (neg)
negs.push(unip);
else
ranges.push(unip);
uflag = uflag || u;
continue WHILE;
}
}
}
// now it's just a normal character, effectively
escaping = false;
if (rangeStart) {
// throw this range away if it's not valid, but others
// can still match.
if (c > rangeStart) {
ranges.push(braceEscape(rangeStart) + '-' + braceEscape(c));
}
else if (c === rangeStart) {
ranges.push(braceEscape(c));
}
rangeStart = '';
i++;
continue;
}
// now might be the start of a range.
// can be either c-d or c-] or c<more...>] or c] at this point
if (glob.startsWith('-]', i + 1)) {
ranges.push(braceEscape(c + '-'));
i += 2;
continue;
}
if (glob.startsWith('-', i + 1)) {
rangeStart = c;
i += 2;
continue;
}
// not the start of a range, just a single character
ranges.push(braceEscape(c));
i++;
}
if (endPos < i) {
// didn't see the end of the class, not a valid class,
// but might still be valid as a literal match.
return ['', false, 0, false];
}
// if we got no ranges and no negates, then we have a range that
// cannot possibly match anything, and that poisons the whole glob
if (!ranges.length && !negs.length) {
return ['$.', false, glob.length - pos, true];
}
// if we got one positive range, and it's a single character, then that's
// not actually a magic pattern, it's just that one literal character.
// we should not treat that as "magic", we should just return the literal
// character. [_] is a perfectly valid way to escape glob magic chars.
if (negs.length === 0 &&
ranges.length === 1 &&
/^\\?.$/.test(ranges[0]) &&
!negate) {
const r = ranges[0].length === 2 ? ranges[0].slice(-1) : ranges[0];
return [regexpEscape(r), false, endPos - pos, false];
}
const sranges = '[' + (negate ? '^' : '') + rangesToString(ranges) + ']';
const snegs = '[' + (negate ? '' : '^') + rangesToString(negs) + ']';
const comb = ranges.length && negs.length
? '(' + sranges + '|' + snegs + ')'
: ranges.length
? sranges
: snegs;
return [comb, uflag, endPos - pos, true];
};
//# sourceMappingURL=brace-expressions.js.map

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,12 @@
import { MinimatchOptions } from './index.js';
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*/
export declare const escape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, 'windowsPathsNoEscape'>) => string;
//# sourceMappingURL=escape.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"escape.d.ts","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;GAQG;AACH,eAAO,MAAM,MAAM,MACd,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAQlD,CAAA"}

View File

@@ -0,0 +1,18 @@
/**
* Escape all magic characters in a glob pattern.
*
* If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}
* option is used, then characters are escaped by wrapping in `[]`, because
* a magic character wrapped in a character class can only be satisfied by
* that exact character. In this mode, `\` is _not_ escaped, because it is
* not interpreted as a magic character, but instead as a path separator.
*/
export const escape = (s, { windowsPathsNoEscape = false, } = {}) => {
// don't need to escape +@! because we escape the parens
// that make those magic, and escaping ! as [!] isn't valid,
// because [!]] is a valid glob class meaning not ']'.
return windowsPathsNoEscape
? s.replace(/[?*()[\]]/g, '[$&]')
: s.replace(/[?*()[\]\\]/g, '\\$&');
};
//# sourceMappingURL=escape.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"escape.js","sourceRoot":"","sources":["../../src/escape.ts"],"names":[],"mappings":"AACA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,MAAM,GAAG,CACpB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,wDAAwD;IACxD,4DAA4D;IAC5D,sDAAsD;IACtD,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,MAAM,CAAC;QACjC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,EAAE,MAAM,CAAC,CAAA;AACvC,CAAC,CAAA","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Escape all magic characters in a glob pattern.\n *\n * If the {@link windowsPathsNoEscape | GlobOptions.windowsPathsNoEscape}\n * option is used, then characters are escaped by wrapping in `[]`, because\n * a magic character wrapped in a character class can only be satisfied by\n * that exact character. In this mode, `\\` is _not_ escaped, because it is\n * not interpreted as a magic character, but instead as a path separator.\n */\nexport const escape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n // don't need to escape +@! because we escape the parens\n // that make those magic, and escaping ! as [!] isn't valid,\n // because [!]] is a valid glob class meaning not ']'.\n return windowsPathsNoEscape\n ? s.replace(/[?*()[\\]]/g, '[$&]')\n : s.replace(/[?*()[\\]\\\\]/g, '\\\\$&')\n}\n"]}

View File

@@ -0,0 +1,94 @@
import { AST } from './ast.js';
type Platform = 'aix' | 'android' | 'darwin' | 'freebsd' | 'haiku' | 'linux' | 'openbsd' | 'sunos' | 'win32' | 'cygwin' | 'netbsd';
export interface MinimatchOptions {
nobrace?: boolean;
nocomment?: boolean;
nonegate?: boolean;
debug?: boolean;
noglobstar?: boolean;
noext?: boolean;
nonull?: boolean;
windowsPathsNoEscape?: boolean;
allowWindowsEscape?: boolean;
partial?: boolean;
dot?: boolean;
nocase?: boolean;
nocaseMagicOnly?: boolean;
magicalBraces?: boolean;
matchBase?: boolean;
flipNegate?: boolean;
preserveMultipleSlashes?: boolean;
optimizationLevel?: number;
platform?: Platform;
windowsNoMagicRoot?: boolean;
}
export declare const minimatch: {
(p: string, pattern: string, options?: MinimatchOptions): boolean;
sep: Sep;
GLOBSTAR: typeof GLOBSTAR;
filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
defaults: (def: MinimatchOptions) => typeof minimatch;
braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
AST: typeof AST;
Minimatch: typeof Minimatch;
escape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
unescape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
};
type Sep = '\\' | '/';
export declare const sep: Sep;
export declare const GLOBSTAR: unique symbol;
export declare const filter: (pattern: string, options?: MinimatchOptions) => (p: string) => boolean;
export declare const defaults: (def: MinimatchOptions) => typeof minimatch;
export declare const braceExpand: (pattern: string, options?: MinimatchOptions) => string[];
export declare const makeRe: (pattern: string, options?: MinimatchOptions) => false | MMRegExp;
export declare const match: (list: string[], pattern: string, options?: MinimatchOptions) => string[];
export type MMRegExp = RegExp & {
_src?: string;
_glob?: string;
};
export type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
export type ParseReturn = ParseReturnFiltered | false;
export declare class Minimatch {
options: MinimatchOptions;
set: ParseReturnFiltered[][];
pattern: string;
windowsPathsNoEscape: boolean;
nonegate: boolean;
negate: boolean;
comment: boolean;
empty: boolean;
preserveMultipleSlashes: boolean;
partial: boolean;
globSet: string[];
globParts: string[][];
nocase: boolean;
isWindows: boolean;
platform: Platform;
windowsNoMagicRoot: boolean;
regexp: false | null | MMRegExp;
constructor(pattern: string, options?: MinimatchOptions);
hasMagic(): boolean;
debug(..._: any[]): void;
make(): void;
preprocess(globParts: string[][]): string[][];
adjascentGlobstarOptimize(globParts: string[][]): string[][];
levelOneOptimize(globParts: string[][]): string[][];
levelTwoFileOptimize(parts: string | string[]): string[];
firstPhasePreProcess(globParts: string[][]): string[][];
secondPhasePreProcess(globParts: string[][]): string[][];
partsMatch(a: string[], b: string[], emptyGSMatch?: boolean): false | string[];
parseNegate(): void;
matchOne(file: string[], pattern: ParseReturn[], partial?: boolean): boolean;
braceExpand(): string[];
parse(pattern: string): ParseReturn;
makeRe(): false | MMRegExp;
slashSplit(p: string): string[];
match(f: string, partial?: boolean): boolean;
static defaults(def: MinimatchOptions): typeof Minimatch;
}
export { AST } from './ast.js';
export { escape } from './escape.js';
export { unescape } from './unescape.js';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,GAAG,EAAe,MAAM,UAAU,CAAA;AAI3C,KAAK,QAAQ,GACT,KAAK,GACL,SAAS,GACT,QAAQ,GACR,SAAS,GACT,OAAO,GACP,OAAO,GACP,SAAS,GACT,OAAO,GACP,OAAO,GACP,QAAQ,GACR,QAAQ,CAAA;AAEZ,MAAM,WAAW,gBAAgB;IAC/B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,QAAQ,CAAC,EAAE,OAAO,CAAA;IAClB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,KAAK,CAAC,EAAE,OAAO,CAAA;IACf,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,oBAAoB,CAAC,EAAE,OAAO,CAAA;IAC9B,kBAAkB,CAAC,EAAE,OAAO,CAAA;IAC5B,OAAO,CAAC,EAAE,OAAO,CAAA;IACjB,GAAG,CAAC,EAAE,OAAO,CAAA;IACb,MAAM,CAAC,EAAE,OAAO,CAAA;IAChB,eAAe,CAAC,EAAE,OAAO,CAAA;IACzB,aAAa,CAAC,EAAE,OAAO,CAAA;IACvB,SAAS,CAAC,EAAE,OAAO,CAAA;IACnB,UAAU,CAAC,EAAE,OAAO,CAAA;IACpB,uBAAuB,CAAC,EAAE,OAAO,CAAA;IACjC,iBAAiB,CAAC,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,EAAE,QAAQ,CAAA;IACnB,kBAAkB,CAAC,EAAE,OAAO,CAAA;CAC7B;AAED,eAAO,MAAM,SAAS;QACjB,MAAM,WACA,MAAM,YACN,gBAAgB;;;sBAuGf,MAAM,YAAW,gBAAgB,SACvC,MAAM;oBAOkB,gBAAgB,KAAG,gBAAgB;2BA6EtD,MAAM,YACN,gBAAgB;sBA2BK,MAAM,YAAW,gBAAgB;kBAKzD,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB;;;;;CArN1B,CAAA;AA+DD,KAAK,GAAG,GAAG,IAAI,GAAG,GAAG,CAAA;AAOrB,eAAO,MAAM,GAAG,KAAgE,CAAA;AAGhF,eAAO,MAAM,QAAQ,eAAwB,CAAA;AAmB7C,eAAO,MAAM,MAAM,YACP,MAAM,YAAW,gBAAgB,SACvC,MAAM,YACsB,CAAA;AAMlC,eAAO,MAAM,QAAQ,QAAS,gBAAgB,KAAG,gBA+DhD,CAAA;AAaD,eAAO,MAAM,WAAW,YACb,MAAM,YACN,gBAAgB,aAY1B,CAAA;AAeD,eAAO,MAAM,MAAM,YAAa,MAAM,YAAW,gBAAgB,qBACvB,CAAA;AAG1C,eAAO,MAAM,KAAK,SACV,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB,aAQ1B,CAAA;AAQD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,QAAQ,CAAA;AACrE,MAAM,MAAM,WAAW,GAAG,mBAAmB,GAAG,KAAK,CAAA;AAErD,qBAAa,SAAS;IACpB,OAAO,EAAE,gBAAgB,CAAA;IACzB,GAAG,EAAE,mBAAmB,EAAE,EAAE,CAAA;IAC5B,OAAO,EAAE,MAAM,CAAA;IAEf,oBAAoB,EAAE,OAAO,CAAA;IAC7B,QAAQ,EAAE,OAAO,CAAA;IACjB,MAAM,EAAE,OAAO,CAAA;IACf,OAAO,EAAE,OAAO,CAAA;IAChB,KAAK,EAAE,OAAO,CAAA;IACd,uBAAuB,EAAE,OAAO,CAAA;IAChC,OAAO,EAAE,OAAO,CAAA;IAChB,OAAO,EAAE,MAAM,EAAE,CAAA;IACjB,SAAS,EAAE,MAAM,EAAE,EAAE,CAAA;IACrB,MAAM,EAAE,OAAO,CAAA;IAEf,SAAS,EAAE,OAAO,CAAA;IAClB,QAAQ,EAAE,QAAQ,CAAA;IAClB,kBAAkB,EAAE,OAAO,CAAA;IAE3B,MAAM,EAAE,KAAK,GAAG,IAAI,GAAG,QAAQ,CAAA;gBACnB,OAAO,EAAE,MAAM,EAAE,OAAO,GAAE,gBAAqB;IAkC3D,QAAQ,IAAI,OAAO;IAYnB,KAAK,CAAC,GAAG,CAAC,EAAE,GAAG,EAAE;IAEjB,IAAI;IA0FJ,UAAU,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IA8BhC,yBAAyB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IAiB/C,gBAAgB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IAoBtC,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE;IA6D7C,oBAAoB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE;IA0F1C,qBAAqB,CAAC,SAAS,EAAE,MAAM,EAAE,EAAE,GAAG,MAAM,EAAE,EAAE;IAkBxD,UAAU,CACR,CAAC,EAAE,MAAM,EAAE,EACX,CAAC,EAAE,MAAM,EAAE,EACX,YAAY,GAAE,OAAe,GAC5B,KAAK,GAAG,MAAM,EAAE;IA+CnB,WAAW;IAqBX,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,EAAE,EAAE,OAAO,GAAE,OAAe;IAiNzE,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW;IAiDnC,MAAM;IAsFN,UAAU,CAAC,CAAC,EAAE,MAAM;IAepB,KAAK,CAAC,CAAC,EAAE,MAAM,EAAE,OAAO,UAAe;IAiEvC,MAAM,CAAC,QAAQ,CAAC,GAAG,EAAE,gBAAgB;CAGtC;AAED,OAAO,EAAE,GAAG,EAAE,MAAM,UAAU,CAAA;AAC9B,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"}

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,3 @@
{
"type": "module"
}

View File

@@ -0,0 +1,17 @@
import { MinimatchOptions } from './index.js';
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link windowsPathsNoEscape} option is used, then square-brace
* escapes are removed, but not backslash escapes. For example, it will turn
* the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
* becuase `\` is a path separator in `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both brace escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*/
export declare const unescape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, 'windowsPathsNoEscape'>) => string;
//# sourceMappingURL=unescape.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"unescape.d.ts","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,gBAAgB,EAAE,MAAM,YAAY,CAAA;AAC7C;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,QAAQ,MAChB,MAAM,8BAGN,KAAK,gBAAgB,EAAE,sBAAsB,CAAC,WAKlD,CAAA"}

View File

@@ -0,0 +1,20 @@
/**
* Un-escape a string that has been escaped with {@link escape}.
*
* If the {@link windowsPathsNoEscape} option is used, then square-brace
* escapes are removed, but not backslash escapes. For example, it will turn
* the string `'[*]'` into `*`, but it will not turn `'\\*'` into `'*'`,
* becuase `\` is a path separator in `windowsPathsNoEscape` mode.
*
* When `windowsPathsNoEscape` is not set, then both brace escapes and
* backslash escapes are removed.
*
* Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped
* or unescaped.
*/
export const unescape = (s, { windowsPathsNoEscape = false, } = {}) => {
return windowsPathsNoEscape
? s.replace(/\[([^\/\\])\]/g, '$1')
: s.replace(/((?!\\).|^)\[([^\/\\])\]/g, '$1$2').replace(/\\([^\/])/g, '$1');
};
//# sourceMappingURL=unescape.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"unescape.js","sourceRoot":"","sources":["../../src/unescape.ts"],"names":[],"mappings":"AACA;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,QAAQ,GAAG,CACtB,CAAS,EACT,EACE,oBAAoB,GAAG,KAAK,MACsB,EAAE,EACtD,EAAE;IACF,OAAO,oBAAoB;QACzB,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,gBAAgB,EAAE,IAAI,CAAC;QACnC,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,2BAA2B,EAAE,MAAM,CAAC,CAAC,OAAO,CAAC,YAAY,EAAE,IAAI,CAAC,CAAA;AAChF,CAAC,CAAA","sourcesContent":["import { MinimatchOptions } from './index.js'\n/**\n * Un-escape a string that has been escaped with {@link escape}.\n *\n * If the {@link windowsPathsNoEscape} option is used, then square-brace\n * escapes are removed, but not backslash escapes. For example, it will turn\n * the string `'[*]'` into `*`, but it will not turn `'\\\\*'` into `'*'`,\n * becuase `\\` is a path separator in `windowsPathsNoEscape` mode.\n *\n * When `windowsPathsNoEscape` is not set, then both brace escapes and\n * backslash escapes are removed.\n *\n * Slashes (and backslashes in `windowsPathsNoEscape` mode) cannot be escaped\n * or unescaped.\n */\nexport const unescape = (\n s: string,\n {\n windowsPathsNoEscape = false,\n }: Pick<MinimatchOptions, 'windowsPathsNoEscape'> = {}\n) => {\n return windowsPathsNoEscape\n ? s.replace(/\\[([^\\/\\\\])\\]/g, '$1')\n : s.replace(/((?!\\\\).|^)\\[([^\\/\\\\])\\]/g, '$1$2').replace(/\\\\([^\\/])/g, '$1')\n}\n"]}

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