初始化fy

This commit is contained in:
yziiy
2025-08-11 11:51:38 +08:00
parent 98ce20e897
commit 7e21160e13
19770 changed files with 3108698 additions and 0 deletions

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 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,392 @@
# unplugin-vue-components
[![NPM version](https://img.shields.io/npm/v/unplugin-vue-components?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-vue-components)
On-demand components auto importing for Vue.
###### Features
- 💚 Supports both Vue 2 and Vue 3 out-of-the-box.
- ✨ Supports both components and directives.
- ⚡️ Supports Vite, Webpack, Vue CLI, Rollup, esbuild and more, powered by <a href="https://github.com/unjs/unplugin">unplugin</a>.
- 🏝 Tree-shakable, only registers the components you use.
- 🪐 Folder names as namespaces.
- 🦾 Full TypeScript support.
- 🌈 [Built-in resolvers](#importing-from-ui-libraries) for popular UI libraries.
- 😃 Works perfectly with [unplugin-icons](https://github.com/antfu/unplugin-icons).
<br>
<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>
<br>
## Installation
```bash
npm i unplugin-vue-components -D
```
> **`vite-plugin-components` has been renamed to `unplugin-vue-components`**, see the [migration guide](#migrate-from-vite-plugin-components).
<details>
<summary>Vite</summary><br>
```ts
// vite.config.ts
import Components from 'unplugin-vue-components/vite'
export default defineConfig({
plugins: [
Components({ /* options */ }),
],
})
```
<br></details>
<details>
<summary>Rollup</summary><br>
```ts
// rollup.config.js
import Components from 'unplugin-vue-components/rollup'
export default {
plugins: [
Components({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Webpack</summary><br>
```ts
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-vue-components/webpack')({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Nuxt</summary><br>
You might not need this plugin for Nuxt. Use [`@nuxt/components`](https://github.com/nuxt/components) instead.
<br></details>
<details>
<summary>Vue CLI</summary><br>
```ts
// vue.config.js
module.exports = {
configureWebpack: {
plugins: [
require('unplugin-vue-components/webpack')({ /* options */ }),
],
},
}
```
<br></details>
<details>
<summary>esbuild</summary><br>
```ts
// esbuild.config.js
import { build } from 'esbuild'
build({
/* ... */
plugins: [
require('unplugin-vue-components/esbuild')({
/* options */
}),
],
})
```
<br></details>
## Usage
Use components in templates as you would usually do, it will import components on demand, and there is no `import` and `component registration` required anymore! If you register the parent component asynchronously (or lazy route), the auto-imported components will be code-split along with their parent.
It will automatically turn this
```html
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
export default {
name: 'App'
}
</script>
```
into this
```html
<template>
<div>
<HelloWorld msg="Hello Vue 3.0 + Vite" />
</div>
</template>
<script>
import HelloWorld from './src/components/HelloWorld.vue'
export default {
name: 'App',
components: {
HelloWorld
}
}
</script>
```
> **Note**
> By default this plugin will import components in the `src/components` path. You can customize it using the `dirs` option.
## TypeScript
To get TypeScript support for auto-imported components, there is [a PR](https://github.com/vuejs/core/pull/3399) to Vue 3 extending the interface of global components. Currently, [Volar](https://github.com/johnsoncodehk/volar) has supported this usage already. If you are using Volar, you can change the config as following to get the support.
```ts
Components({
dts: true, // enabled by default if `typescript` is installed
})
```
Once the setup is done, a `components.d.ts` will be generated and updates automatically with the type definitions. Feel free to commit it into git or not as you want.
> **Make sure you also add `components.d.ts` to your `tsconfig.json` under `include`.**
## Importing from UI Libraries
We have several built-in resolvers for popular UI libraries like **Vuetify**, **Ant Design Vue**, and **Element Plus**, where you can enable them by:
Supported Resolvers:
- [Ant Design Vue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/antdv.ts)
- [Arco Design Vue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/arco.ts)
- [BootstrapVue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/bootstrap-vue.ts)
- [Element Plus](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/element-plus.ts)
- [Element UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/element-ui.ts)
- [Headless UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/headless-ui.ts)
- [IDux](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/idux.ts)
- [Inkline](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/inkline.ts)
- [Ionic](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/ionic.ts)
- [Naive UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/naive-ui.ts)
- [Prime Vue](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/prime-vue.ts)
- [Quasar](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/quasar.ts)
- [TDesign](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/tdesign.ts)
- [Vant](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vant.ts)
- [Varlet UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/varlet-ui.ts)
- [VEUI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/veui.ts)
- [View UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/view-ui.ts)
- [Vuetify](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vuetify.ts)
- [VueUse Components](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vueuse.ts)
- [VueUse Directives](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/vueuse-directive.ts)
- [Dev UI](https://github.com/antfu/unplugin-vue-components/blob/main/src/core/resolvers/devui.ts)
```ts
// vite.config.js
import Components from 'unplugin-vue-components/vite'
import {
AntDesignVueResolver,
ElementPlusResolver,
VantResolver,
} from 'unplugin-vue-components/resolvers'
// your plugin installation
Components({
resolvers: [
AntDesignVueResolver(),
ElementPlusResolver(),
VantResolver(),
],
})
```
You can also write your own resolver quickly:
```ts
Components({
resolvers: [
// example of importing Vant
(componentName) => {
// where `componentName` is always CapitalCase
if (componentName.startsWith('Van'))
return { name: componentName.slice(3), from: 'vant' }
},
],
})
```
> [We no longer accept new resolvers](./src/core/resolvers/_READ_BEFORE_CONTRIBUTE.md).
## Types for global registered components
Some libraries might register some global components for you to use anywhere (e.g. Vue Router provides `<RouterLink>` and `<RouterView>`). Since they are global available, there is no need for this plugin to import them. However, those are commonly not TypeScript friendly, and you might need to register their types manually.
Thus `unplugin-vue-components` provided a way to only register types for global components.
```ts
Components({
dts: true,
types: [{
from: 'vue-router',
names: ['RouterLink', 'RouterView'],
}],
})
```
So the `RouterLink` and `RouterView` will be presented in `components.d.ts`.
By default, `unplugin-vue-components` detects supported libraries automatically (e.g. `vue-router`) when they are installed in the workspace. If you want to disable it completely, you can pass an empty array to it:
```ts
Components({
// Disable type only registration
types: [],
})
```
## Migrate from `vite-plugin-components`
`package.json`
```diff
{
"devDependencies": {
- "vite-plugin-components": "*",
+ "unplugin-vue-components": "^0.14.0",
}
}
```
`vite.config.js`
```diff
- import Components, { ElementPlusResolver } from 'vite-plugin-components'
+ import Components from 'unplugin-vue-components/vite'
+ import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
export default {
plugins: [
/* ... */
Components({
/* ... */
// `customComponentsResolvers` has renamed to `resolver`
- customComponentsResolvers: [
+ resolvers: [
ElementPlusResolver(),
],
// `globalComponentsDeclaration` has renamed to `dts`
- globalComponentsDeclaration: true,
+ dts: true,
// `customLoaderMatcher` is depreacted, use `include` instead
- customLoaderMatcher: id => id.endsWith('.md'),
+ include: [/\.vue$/, /\.vue\?vue/, /\.md$/],
}),
],
}
```
## Configuration
The following show the default values of the configuration
```ts
Components({
// relative paths to the directory to search for components.
dirs: ['src/components'],
// valid file extensions for components.
extensions: ['vue'],
// Glob patterns to match file names to be detected as components.
// When specified, the `dirs` and `extensions` options will be ignored.
globs: ['src/components/*.{vue}'],
// search for subdirectories
deep: true,
// resolvers for custom components
resolvers: [],
// generate `components.d.ts` global declarations,
// also accepts a path for custom filename
// default: `true` if package typescript is installed
dts: false,
// Allow subdirectories as namespace prefix for components.
directoryAsNamespace: false,
// Collapse same prefixes (camel-sensitive) of folders and components
// to prevent duplication inside namespaced component name.
// works when `directoryAsNamespace: true`
collapseSamePrefixes: false,
// Subdirectory paths for ignoring namespace prefixes.
// works when `directoryAsNamespace: true`
globalNamespaces: [],
// auto import for directives
// default: `true` for Vue 3, `false` for Vue 2
// Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
// To install Babel, run: `npm install -D @babel/parser`
directives: true,
// Transform path before resolving
importPathTransform: v => v,
// Allow for components to override other components with the same name
allowOverrides: false,
// filters for transforming targets
include: [/\.vue$/, /\.vue\?vue/],
exclude: [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/],
// Vue version of project. It will detect automatically if not specified.
// Acceptable value: 2 | 2.7 | 3
version: 2.7,
// Only provide types of components in library (registered globally)
types: []
})
```
## Example
[Vitesse](https://github.com/antfu/vitesse) starter template.
## Thanks
Thanks to [@brattonross](https://github.com/brattonross), this project is heavily inspired by [vite-plugin-voie](https://github.com/vamplate/vite-plugin-voie).
## License
MIT License © 2020-PRESENT [Anthony Fu](https://github.com/antfu)

View File

@@ -0,0 +1 @@
"use strict";

View File

@@ -0,0 +1,195 @@
// src/core/utils.ts
import { parse } from "path";
import minimatch from "minimatch";
import resolve from "resolve";
import { slash, toArray } from "@antfu/utils";
import {
getPackageInfo,
isPackageExists
} from "local-pkg";
// src/core/constants.ts
var DISABLE_COMMENT = "/* unplugin-vue-components disabled */";
var DIRECTIVE_IMPORT_PREFIX = "v";
// src/core/utils.ts
var isSSR = Boolean(process.env.SSR || process.env.SSG || process.env.VITE_SSR || process.env.VITE_SSG);
function pascalCase(str) {
return capitalize(camelCase(str));
}
function camelCase(str) {
return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
}
function kebabCase(key) {
const result = key.replace(/([A-Z])/g, " $1").trim();
return result.split(" ").join("-").toLowerCase();
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function parseId(id) {
const index = id.indexOf("?");
if (index < 0) {
return { path: id, query: {} };
} else {
const query = Object.fromEntries(new URLSearchParams(id.slice(index)));
return {
path: id.slice(0, index),
query
};
}
}
function isEmpty(value) {
if (!value || value === null || value === void 0 || Array.isArray(value) && Object.keys(value).length <= 0)
return true;
else
return false;
}
function matchGlobs(filepath, globs) {
for (const glob of globs) {
if (minimatch(slash(filepath), glob))
return true;
}
return false;
}
function getTransformedPath(path, importPathTransform) {
if (importPathTransform) {
const result = importPathTransform(path);
if (result != null)
path = result;
}
return path;
}
function stringifyImport(info) {
if (typeof info === "string")
return `import '${info}'`;
if (!info.as)
return `import '${info.from}'`;
else if (info.name)
return `import { ${info.name} as ${info.as} } from '${info.from}'`;
else
return `import ${info.as} from '${info.from}'`;
}
function normalizeComponetInfo(info) {
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return info;
}
function stringifyComponentImport({ as: name, from: path, name: importName, sideEffects }, ctx) {
path = getTransformedPath(path, ctx.options.importPathTransform);
const imports = [
stringifyImport({ as: name, from: path, name: importName })
];
if (sideEffects)
toArray(sideEffects).forEach((i) => imports.push(stringifyImport(i)));
return imports.join(";");
}
function getNameFromFilePath(filePath, options) {
const { resolvedDirs, directoryAsNamespace, globalNamespaces, collapseSamePrefixes, root } = options;
const parsedFilePath = parse(slash(filePath));
let strippedPath = "";
for (const dir of resolvedDirs) {
if (parsedFilePath.dir.startsWith(dir)) {
strippedPath = parsedFilePath.dir.slice(dir.length);
break;
}
}
let folders = strippedPath.slice(1).split("/").filter(Boolean);
let filename = parsedFilePath.name;
if (filename === "index" && !directoryAsNamespace) {
if (isEmpty(folders))
folders = parsedFilePath.dir.slice(root.length + 1).split("/").filter(Boolean);
filename = `${folders.slice(-1)[0]}`;
return filename;
}
if (directoryAsNamespace) {
if (globalNamespaces.some((name) => folders.includes(name)))
folders = folders.filter((f) => !globalNamespaces.includes(f));
folders = folders.map((f) => f.replace(/[^a-zA-Z0-9\-]/g, ""));
if (filename.toLowerCase() === "index")
filename = "";
if (!isEmpty(folders)) {
let namespaced = [...folders, filename];
if (collapseSamePrefixes) {
const collapsed = [];
for (const fileOrFolderName of namespaced) {
let cumulativePrefix = "";
let didCollapse = false;
for (const parentFolder of [...collapsed].reverse()) {
cumulativePrefix = `${capitalize(parentFolder)}${cumulativePrefix}`;
if (pascalCase(fileOrFolderName).startsWith(pascalCase(cumulativePrefix))) {
const collapseSamePrefix = fileOrFolderName.slice(cumulativePrefix.length);
collapsed.push(collapseSamePrefix);
didCollapse = true;
break;
}
}
if (!didCollapse)
collapsed.push(fileOrFolderName);
}
namespaced = collapsed;
}
filename = namespaced.filter(Boolean).join("-");
}
return filename;
}
return filename;
}
function resolveAlias(filepath, alias) {
const result = filepath;
if (Array.isArray(alias)) {
for (const { find, replacement } of alias)
result.replace(find, replacement);
}
return result;
}
async function getPkgVersion(pkgName, defaultVersion) {
var _a;
try {
const isExist = isPackageExists(pkgName);
if (isExist) {
const pkg = await getPackageInfo(pkgName);
return (_a = pkg == null ? void 0 : pkg.version) != null ? _a : defaultVersion;
} else {
return defaultVersion;
}
} catch (err) {
console.error(err);
return defaultVersion;
}
}
function shouldTransform(code) {
if (code.includes(DISABLE_COMMENT))
return false;
return true;
}
function resolveImportPath(importName) {
return resolve.sync(importName, {
preserveSymlinks: false
});
}
export {
DISABLE_COMMENT,
DIRECTIVE_IMPORT_PREFIX,
isSSR,
pascalCase,
camelCase,
kebabCase,
parseId,
matchGlobs,
getTransformedPath,
normalizeComponetInfo,
stringifyComponentImport,
getNameFromFilePath,
resolveAlias,
getPkgVersion,
shouldTransform,
resolveImportPath
};

View File

@@ -0,0 +1,32 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined")
return require.apply(this, arguments);
throw new Error('Dynamic require of "' + x + '" is not supported');
});
exports.__spreadValues = __spreadValues; exports.__spreadProps = __spreadProps; exports.__require = __require;

View File

@@ -0,0 +1,195 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/core/utils.ts
var _path = require('path');
var _minimatch = require('minimatch'); var _minimatch2 = _interopRequireDefault(_minimatch);
var _resolve = require('resolve'); var _resolve2 = _interopRequireDefault(_resolve);
var _utils = require('@antfu/utils');
var _localpkg = require('local-pkg');
// src/core/constants.ts
var DISABLE_COMMENT = "/* unplugin-vue-components disabled */";
var DIRECTIVE_IMPORT_PREFIX = "v";
// src/core/utils.ts
var isSSR = Boolean(process.env.SSR || process.env.SSG || process.env.VITE_SSR || process.env.VITE_SSG);
function pascalCase(str) {
return capitalize(camelCase(str));
}
function camelCase(str) {
return str.replace(/-(\w)/g, (_, c) => c ? c.toUpperCase() : "");
}
function kebabCase(key) {
const result = key.replace(/([A-Z])/g, " $1").trim();
return result.split(" ").join("-").toLowerCase();
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1);
}
function parseId(id) {
const index = id.indexOf("?");
if (index < 0) {
return { path: id, query: {} };
} else {
const query = Object.fromEntries(new URLSearchParams(id.slice(index)));
return {
path: id.slice(0, index),
query
};
}
}
function isEmpty(value) {
if (!value || value === null || value === void 0 || Array.isArray(value) && Object.keys(value).length <= 0)
return true;
else
return false;
}
function matchGlobs(filepath, globs) {
for (const glob of globs) {
if (_minimatch2.default.call(void 0, _utils.slash.call(void 0, filepath), glob))
return true;
}
return false;
}
function getTransformedPath(path, importPathTransform) {
if (importPathTransform) {
const result = importPathTransform(path);
if (result != null)
path = result;
}
return path;
}
function stringifyImport(info) {
if (typeof info === "string")
return `import '${info}'`;
if (!info.as)
return `import '${info.from}'`;
else if (info.name)
return `import { ${info.name} as ${info.as} } from '${info.from}'`;
else
return `import ${info.as} from '${info.from}'`;
}
function normalizeComponetInfo(info) {
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return info;
}
function stringifyComponentImport({ as: name, from: path, name: importName, sideEffects }, ctx) {
path = getTransformedPath(path, ctx.options.importPathTransform);
const imports = [
stringifyImport({ as: name, from: path, name: importName })
];
if (sideEffects)
_utils.toArray.call(void 0, sideEffects).forEach((i) => imports.push(stringifyImport(i)));
return imports.join(";");
}
function getNameFromFilePath(filePath, options) {
const { resolvedDirs, directoryAsNamespace, globalNamespaces, collapseSamePrefixes, root } = options;
const parsedFilePath = _path.parse.call(void 0, _utils.slash.call(void 0, filePath));
let strippedPath = "";
for (const dir of resolvedDirs) {
if (parsedFilePath.dir.startsWith(dir)) {
strippedPath = parsedFilePath.dir.slice(dir.length);
break;
}
}
let folders = strippedPath.slice(1).split("/").filter(Boolean);
let filename = parsedFilePath.name;
if (filename === "index" && !directoryAsNamespace) {
if (isEmpty(folders))
folders = parsedFilePath.dir.slice(root.length + 1).split("/").filter(Boolean);
filename = `${folders.slice(-1)[0]}`;
return filename;
}
if (directoryAsNamespace) {
if (globalNamespaces.some((name) => folders.includes(name)))
folders = folders.filter((f) => !globalNamespaces.includes(f));
folders = folders.map((f) => f.replace(/[^a-zA-Z0-9\-]/g, ""));
if (filename.toLowerCase() === "index")
filename = "";
if (!isEmpty(folders)) {
let namespaced = [...folders, filename];
if (collapseSamePrefixes) {
const collapsed = [];
for (const fileOrFolderName of namespaced) {
let cumulativePrefix = "";
let didCollapse = false;
for (const parentFolder of [...collapsed].reverse()) {
cumulativePrefix = `${capitalize(parentFolder)}${cumulativePrefix}`;
if (pascalCase(fileOrFolderName).startsWith(pascalCase(cumulativePrefix))) {
const collapseSamePrefix = fileOrFolderName.slice(cumulativePrefix.length);
collapsed.push(collapseSamePrefix);
didCollapse = true;
break;
}
}
if (!didCollapse)
collapsed.push(fileOrFolderName);
}
namespaced = collapsed;
}
filename = namespaced.filter(Boolean).join("-");
}
return filename;
}
return filename;
}
function resolveAlias(filepath, alias) {
const result = filepath;
if (Array.isArray(alias)) {
for (const { find, replacement } of alias)
result.replace(find, replacement);
}
return result;
}
async function getPkgVersion(pkgName, defaultVersion) {
var _a;
try {
const isExist = _localpkg.isPackageExists.call(void 0, pkgName);
if (isExist) {
const pkg = await _localpkg.getPackageInfo.call(void 0, pkgName);
return (_a = pkg == null ? void 0 : pkg.version) != null ? _a : defaultVersion;
} else {
return defaultVersion;
}
} catch (err) {
console.error(err);
return defaultVersion;
}
}
function shouldTransform(code) {
if (code.includes(DISABLE_COMMENT))
return false;
return true;
}
function resolveImportPath(importName) {
return _resolve2.default.sync(importName, {
preserveSymlinks: false
});
}
exports.DISABLE_COMMENT = DISABLE_COMMENT; exports.DIRECTIVE_IMPORT_PREFIX = DIRECTIVE_IMPORT_PREFIX; exports.isSSR = isSSR; exports.pascalCase = pascalCase; exports.camelCase = camelCase; exports.kebabCase = kebabCase; exports.parseId = parseId; exports.matchGlobs = matchGlobs; exports.getTransformedPath = getTransformedPath; exports.normalizeComponetInfo = normalizeComponetInfo; exports.stringifyComponentImport = stringifyComponentImport; exports.getNameFromFilePath = getNameFromFilePath; exports.resolveAlias = resolveAlias; exports.getPkgVersion = getPkgVersion; exports.shouldTransform = shouldTransform; exports.resolveImportPath = resolveImportPath;

View File

@@ -0,0 +1,751 @@
import {
DIRECTIVE_IMPORT_PREFIX,
DISABLE_COMMENT,
getNameFromFilePath,
getTransformedPath,
matchGlobs,
normalizeComponetInfo,
parseId,
pascalCase,
resolveAlias,
shouldTransform,
stringifyComponentImport
} from "./chunk-BPHJA2FM.mjs";
import {
__spreadProps,
__spreadValues
} from "./chunk-ZKNUHGJ4.mjs";
// src/core/unplugin.ts
import { existsSync as existsSync2 } from "fs";
import { createUnplugin } from "unplugin";
import { createFilter } from "@rollup/pluginutils";
import chokidar from "chokidar";
// src/core/context.ts
import { relative as relative2 } from "path";
import Debug5 from "debug";
import { slash as slash3, throttle, toArray as toArray2 } from "@antfu/utils";
// src/core/options.ts
import { join, resolve } from "path";
import { slash, toArray } from "@antfu/utils";
import { getPackageInfoSync, isPackageExists as isPackageExists2 } from "local-pkg";
// src/core/type-imports/detect.ts
import { isPackageExists } from "local-pkg";
import { notNullish } from "@antfu/utils";
// src/core/type-imports/index.ts
var TypeImportPresets = [
{
from: "vue-router",
names: [
"RouterView",
"RouterLink"
]
},
{
from: "vue-starport",
names: [
"Starport",
"StarportCarrier"
]
}
];
// src/core/type-imports/detect.ts
function detectTypeImports() {
return TypeImportPresets.map((i) => isPackageExists(i.from) ? i : void 0).filter(notNullish);
}
function resolveTypeImports(imports) {
return imports.flatMap((i) => i.names.map((n) => ({ from: i.from, name: n, as: n })));
}
// src/core/options.ts
var defaultOptions = {
dirs: "src/components",
extensions: "vue",
deep: true,
dts: isPackageExists2("typescript"),
directoryAsNamespace: false,
collapseSamePrefixes: false,
globalNamespaces: [],
resolvers: [],
importPathTransform: (v) => v,
allowOverrides: false
};
function normalizeResolvers(resolvers) {
return toArray(resolvers).flat().map((r) => typeof r === "function" ? { resolve: r, type: "component" } : r);
}
function resolveOptions(options, root) {
var _a;
const resolved = Object.assign({}, defaultOptions, options);
resolved.resolvers = normalizeResolvers(resolved.resolvers);
resolved.extensions = toArray(resolved.extensions);
if (resolved.globs) {
resolved.globs = toArray(resolved.globs).map((glob) => slash(resolve(root, glob)));
resolved.resolvedDirs = [];
} else {
const extsGlob = resolved.extensions.length === 1 ? resolved.extensions : `{${resolved.extensions.join(",")}}`;
resolved.dirs = toArray(resolved.dirs);
resolved.resolvedDirs = resolved.dirs.map((i) => slash(resolve(root, i)));
resolved.globs = resolved.resolvedDirs.map(
(i) => resolved.deep ? slash(join(i, `**/*.${extsGlob}`)) : slash(join(i, `*.${extsGlob}`))
);
if (!resolved.extensions.length)
throw new Error("[unplugin-vue-components] `extensions` option is required to search for components");
}
resolved.dts = !resolved.dts ? false : resolve(
root,
typeof resolved.dts === "string" ? resolved.dts : "components.d.ts"
);
if (!resolved.types && resolved.dts)
resolved.types = detectTypeImports();
resolved.types = resolved.types || [];
resolved.root = root;
resolved.version = (_a = resolved.version) != null ? _a : getVueVersion(root);
if (resolved.version < 2 || resolved.version >= 4)
throw new Error(`[unplugin-vue-components] unsupported version: ${resolved.version}`);
resolved.transformer = options.transformer || `vue${Math.trunc(resolved.version)}`;
resolved.directives = typeof options.directives === "boolean" ? options.directives : !resolved.resolvers.some((i) => i.type === "directive") ? false : resolved.version >= 3;
return resolved;
}
function getVueVersion(root) {
var _a;
const raw = ((_a = getPackageInfoSync("vue", { paths: [root] })) == null ? void 0 : _a.version) || "3";
const version = +raw.split(".").slice(0, 2).join(".");
if (version === 2.7)
return 2.7;
else if (version < 2.7)
return 2;
return 3;
}
// src/core/fs/glob.ts
import fg from "fast-glob";
import Debug from "debug";
var debug = Debug("unplugin-vue-components:glob");
function searchComponents(ctx) {
var _a;
debug(`started with: [${ctx.options.globs.join(", ")}]`);
const root = ctx.root;
const files = fg.sync(ctx.options.globs, {
ignore: ["node_modules"],
onlyFiles: true,
cwd: root,
absolute: true
});
if (!files.length && !((_a = ctx.options.resolvers) == null ? void 0 : _a.length))
console.warn("[unplugin-vue-components] no components found");
debug(`${files.length} components found.`);
ctx.addComponents(files);
}
// src/core/declaration.ts
import { dirname, isAbsolute, relative } from "path";
import { existsSync } from "fs";
import { mkdir, readFile, writeFile as writeFile_ } from "fs/promises";
import { notNullish as notNullish2, slash as slash2 } from "@antfu/utils";
var multilineCommentsRE = new RegExp("\\/\\*.*?\\*\\/", "gms");
var singlelineCommentsRE = /\/\/.*$/gm;
function extractImports(code) {
return Object.fromEntries(Array.from(code.matchAll(/['"]?([^\s'"]+)['"]?\s*:\s*(.+?)[,;\n]/g)).map((i) => [i[1], i[2]]));
}
function parseDeclaration(code) {
var _a, _b;
if (!code)
return;
code = code.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const imports = {
component: {},
directive: {}
};
const componentDeclaration = (_a = new RegExp("export\\s+interface\\s+GlobalComponents\\s*{(.*?)}", "s").exec(code)) == null ? void 0 : _a[0];
if (componentDeclaration)
imports.component = extractImports(componentDeclaration);
const directiveDeclaration = (_b = new RegExp("export\\s+interface\\s+ComponentCustomProperties\\s*{(.*?)}", "s").exec(code)) == null ? void 0 : _b[0];
if (directiveDeclaration)
imports.directive = extractImports(directiveDeclaration);
return imports;
}
function stringifyComponentInfo(filepath, { from: path, as: name, name: importName }, importPathTransform) {
if (!name)
return void 0;
path = getTransformedPath(path, importPathTransform);
const related = isAbsolute(path) ? `./${relative(dirname(filepath), path)}` : path;
const entry = `typeof import('${slash2(related)}')['${importName || "default"}']`;
return [name, entry];
}
function stringifyComponentsInfo(filepath, components, importPathTransform) {
return Object.fromEntries(
components.map((info) => stringifyComponentInfo(filepath, info, importPathTransform)).filter(notNullish2)
);
}
function getDeclarationImports(ctx, filepath) {
const component = stringifyComponentsInfo(filepath, [
...Object.values(__spreadValues(__spreadValues({}, ctx.componentNameMap), ctx.componentCustomMap)),
...resolveTypeImports(ctx.options.types)
], ctx.options.importPathTransform);
const directive = stringifyComponentsInfo(
filepath,
Object.values(ctx.directiveCustomMap),
ctx.options.importPathTransform
);
if (Object.keys(component).length + Object.keys(directive).length === 0)
return;
return { component, directive };
}
function stringifyDeclarationImports(imports) {
return Object.entries(imports).sort(([a], [b]) => a.localeCompare(b)).map(([name, v]) => {
if (!/^\w+$/.test(name))
name = `'${name}'`;
return `${name}: ${v}`;
});
}
function getDeclaration(ctx, filepath, originalImports) {
const imports = getDeclarationImports(ctx, filepath);
if (!imports)
return;
const declarations = {
component: stringifyDeclarationImports(__spreadValues(__spreadValues({}, originalImports == null ? void 0 : originalImports.component), imports.component)),
directive: stringifyDeclarationImports(__spreadValues(__spreadValues({}, originalImports == null ? void 0 : originalImports.directive), imports.directive))
};
const head = ctx.options.version === 2.7 ? `export {}
declare module 'vue' {` : `import '@vue/runtime-core'
export {}
declare module '@vue/runtime-core' {`;
let code = `/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
${head}`;
if (Object.keys(declarations.component).length > 0) {
code += `
export interface GlobalComponents {
${declarations.component.join("\n ")}
}`;
}
if (Object.keys(declarations.directive).length > 0) {
code += `
export interface ComponentCustomProperties {
${declarations.directive.join("\n ")}
}`;
}
code += "\n}\n";
return code;
}
async function writeFile(filePath, content) {
await mkdir(dirname(filePath), { recursive: true });
return await writeFile_(filePath, content, "utf-8");
}
async function writeDeclaration(ctx, filepath, removeUnused = false) {
const originalContent = existsSync(filepath) ? await readFile(filepath, "utf-8") : "";
const originalImports = removeUnused ? void 0 : parseDeclaration(originalContent);
const code = getDeclaration(ctx, filepath, originalImports);
if (!code)
return;
if (code !== originalContent)
await writeFile(filepath, code);
}
// src/core/transformer.ts
import Debug4 from "debug";
import MagicString from "magic-string";
// src/core/transforms/component.ts
import Debug2 from "debug";
var debug2 = Debug2("unplugin-vue-components:transform:component");
var resolveVue2 = (code, s) => {
const results = [];
for (const match of code.matchAll(/\b(_c|h)\([\s\n\t]*['"](.+?)["']([,)])/g)) {
const [full, renderFunctionName, matchedName, append] = match;
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + full.length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, `${renderFunctionName}(${resolved}${append}`)
});
}
}
return results;
};
var resolveVue3 = (code, s) => {
const results = [];
for (const match of code.matchAll(/_resolveComponent[0-9]*\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
};
async function transformComponent(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = transformer2 === "vue2" ? resolveVue2(code, s) : resolveVue3(code, s);
for (const { rawName, replace } of results) {
debug2(`| ${rawName}`);
const name = pascalCase(rawName);
ctx.updateUsageMap(sfcPath, [name]);
const component = await ctx.findComponent(name, "component", [sfcPath]);
if (component) {
const varName = `__unplugin_components_${no}`;
s.prepend(`${stringifyComponentImport(__spreadProps(__spreadValues({}, component), { as: varName }), ctx)};
`);
no += 1;
replace(varName);
}
}
debug2(`^ (${no})`);
}
// src/core/transforms/directive/index.ts
import Debug3 from "debug";
// src/core/transforms/directive/vue2.ts
import { importModule, isPackageExists as isPackageExists3 } from "local-pkg";
var getRenderFnStart = (program) => {
var _a, _b;
const renderFn = program.body.find(
(node) => node.type === "VariableDeclaration" && node.declarations[0].id.type === "Identifier" && ["render", "_sfc_render"].includes(node.declarations[0].id.name)
);
const start = (_b = (_a = renderFn == null ? void 0 : renderFn.declarations[0].init) == null ? void 0 : _a.body) == null ? void 0 : _b.start;
if (start === null || start === void 0)
throw new Error("[unplugin-vue-components:directive] Cannot find render function position.");
return start + 1;
};
async function resolveVue22(code, s) {
var _a, _b, _c;
if (!isPackageExists3("@babel/parser"))
throw new Error('[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"');
const { parse } = await importModule("@babel/parser");
const { program } = parse(code, {
sourceType: "module"
});
const nodes = [];
const { walk } = await import("./src-EJAVKJEF.mjs");
walk(program, {
enter(node) {
if (node.type === "CallExpression")
nodes.push(node);
}
});
if (nodes.length === 0)
return [];
let _renderStart;
const getRenderStart = () => {
if (_renderStart !== void 0)
return _renderStart;
return _renderStart = getRenderFnStart(program);
};
const results = [];
for (const node of nodes) {
const { callee, arguments: args } = node;
if (callee.type !== "Identifier" || callee.name !== "_c" || ((_a = args[1]) == null ? void 0 : _a.type) !== "ObjectExpression")
continue;
const directives = (_b = args[1].properties.find(
(property) => property.type === "ObjectProperty" && property.key.type === "Identifier" && property.key.name === "directives"
)) == null ? void 0 : _b.value;
if (!directives || directives.type !== "ArrayExpression")
continue;
for (const directive of directives.elements) {
if ((directive == null ? void 0 : directive.type) !== "ObjectExpression")
continue;
const nameNode = (_c = directive.properties.find(
(p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name"
)) == null ? void 0 : _c.value;
if ((nameNode == null ? void 0 : nameNode.type) !== "StringLiteral")
continue;
const name = nameNode.value;
if (!name || name.startsWith("_"))
continue;
results.push({
rawName: name,
replace: (resolved) => {
s.prependLeft(getRenderStart(), `
this.$options.directives["${name}"] = ${resolved};`);
}
});
}
}
return results;
}
// src/core/transforms/directive/vue3.ts
function resolveVue32(code, s) {
const results = [];
for (const match of code.matchAll(/_resolveDirective\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
}
// src/core/transforms/directive/index.ts
var debug3 = Debug3("unplugin-vue-components:transform:directive");
async function transformDirective(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = await (transformer2 === "vue2" ? resolveVue22(code, s) : resolveVue32(code, s));
for (const { rawName, replace } of results) {
debug3(`| ${rawName}`);
const name = `${DIRECTIVE_IMPORT_PREFIX}${pascalCase(rawName)}`;
ctx.updateUsageMap(sfcPath, [name]);
const directive = await ctx.findComponent(name, "directive", [sfcPath]);
if (!directive)
continue;
const varName = `__unplugin_directives_${no}`;
s.prepend(`${stringifyComponentImport(__spreadProps(__spreadValues({}, directive), { as: varName }), ctx)};
`);
no += 1;
replace(varName);
}
debug3(`^ (${no})`);
}
// src/core/transformer.ts
var debug4 = Debug4("unplugin-vue-components:transformer");
function transformer(ctx, transformer2) {
return async (code, id, path) => {
ctx.searchGlob();
const sfcPath = ctx.normalizePath(path);
debug4(sfcPath);
const s = new MagicString(code);
await transformComponent(code, transformer2, s, ctx, sfcPath);
if (ctx.options.directives)
await transformDirective(code, transformer2, s, ctx, sfcPath);
s.prepend(DISABLE_COMMENT);
const result = { code: s.toString() };
if (ctx.sourcemap)
result.map = s.generateMap({ source: id, includeContent: true });
return result;
};
}
// src/core/context.ts
var debug5 = {
components: Debug5("unplugin-vue-components:context:components"),
search: Debug5("unplugin-vue-components:context:search"),
hmr: Debug5("unplugin-vue-components:context:hmr"),
decleration: Debug5("unplugin-vue-components:decleration"),
env: Debug5("unplugin-vue-components:env")
};
var Context = class {
constructor(rawOptions) {
this.rawOptions = rawOptions;
this.transformer = void 0;
this._componentPaths = /* @__PURE__ */ new Set();
this._componentNameMap = {};
this._componentUsageMap = {};
this._componentCustomMap = {};
this._directiveCustomMap = {};
this.root = process.cwd();
this.sourcemap = true;
this.alias = {};
this._searched = false;
this.options = resolveOptions(rawOptions, this.root);
this.generateDeclaration = throttle(500, this._generateDeclaration.bind(this), { noLeading: false });
this.setTransformer(this.options.transformer);
}
setRoot(root) {
if (this.root === root)
return;
debug5.env("root", root);
this.root = root;
this.options = resolveOptions(this.rawOptions, this.root);
}
setTransformer(name) {
debug5.env("transformer", name);
this.transformer = transformer(this, name || "vue3");
}
transform(code, id) {
const { path, query } = parseId(id);
return this.transformer(code, id, path, query);
}
setupViteServer(server) {
if (this._server === server)
return;
this._server = server;
this.setupWatcher(server.watcher);
}
setupWatcher(watcher) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.removeComponents(path);
this.onUpdate(path);
});
watcher.on("add", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.addComponents(path);
this.onUpdate(path);
});
}
/**
* start watcher for webpack
*/
setupWatcherWebpack(watcher, emitUpdate) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.removeComponents(path);
emitUpdate(path, "unlink");
});
watcher.on("add", (path) => {
if (!matchGlobs(path, globs))
return;
path = slash3(path);
this.addComponents(path);
emitUpdate(path, "add");
});
}
/**
* Record the usage of components
* @param path
* @param paths paths of used components
*/
updateUsageMap(path, paths) {
if (!this._componentUsageMap[path])
this._componentUsageMap[path] = /* @__PURE__ */ new Set();
paths.forEach((p) => {
this._componentUsageMap[path].add(p);
});
}
addComponents(paths) {
debug5.components("add", paths);
const size = this._componentPaths.size;
toArray2(paths).forEach((p) => this._componentPaths.add(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
addCustomComponents(info) {
if (info.as)
this._componentCustomMap[info.as] = info;
}
addCustomDirectives(info) {
if (info.as)
this._directiveCustomMap[info.as] = info;
}
removeComponents(paths) {
debug5.components("remove", paths);
const size = this._componentPaths.size;
toArray2(paths).forEach((p) => this._componentPaths.delete(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
onUpdate(path) {
this.generateDeclaration();
if (!this._server)
return;
const payload = {
type: "update",
updates: []
};
const timestamp = +/* @__PURE__ */ new Date();
const name = pascalCase(getNameFromFilePath(path, this.options));
Object.entries(this._componentUsageMap).forEach(([key, values]) => {
if (values.has(name)) {
const r = `/${slash3(relative2(this.root, key))}`;
payload.updates.push({
acceptedPath: r,
path: r,
timestamp,
type: "js-update"
});
}
});
if (payload.updates.length)
this._server.ws.send(payload);
}
updateComponentNameMap() {
this._componentNameMap = {};
Array.from(this._componentPaths).forEach((path) => {
const name = pascalCase(getNameFromFilePath(path, this.options));
if (this._componentNameMap[name] && !this.options.allowOverrides) {
console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`);
return;
}
this._componentNameMap[name] = {
as: name,
from: path
};
});
}
async findComponent(name, type, excludePaths = []) {
let info = this._componentNameMap[name];
if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
return info;
for (const resolver of this.options.resolvers) {
if (resolver.type !== type)
continue;
const result = await resolver.resolve(type === "directive" ? name.slice(DIRECTIVE_IMPORT_PREFIX.length) : name);
if (!result)
continue;
if (typeof result === "string") {
info = {
as: name,
from: result
};
} else {
info = __spreadValues({
as: name
}, normalizeComponetInfo(result));
}
if (type === "component")
this.addCustomComponents(info);
else if (type === "directive")
this.addCustomDirectives(info);
return info;
}
return void 0;
}
normalizePath(path) {
var _a, _b, _c;
return resolveAlias(path, ((_b = (_a = this.viteConfig) == null ? void 0 : _a.resolve) == null ? void 0 : _b.alias) || ((_c = this.viteConfig) == null ? void 0 : _c.alias) || []);
}
relative(path) {
if (path.startsWith("/") && !path.startsWith(this.root))
return slash3(path.slice(1));
return slash3(relative2(this.root, path));
}
/**
* This search for components in with the given options.
* Will be called multiple times to ensure file loaded,
* should normally run only once.
*/
searchGlob() {
if (this._searched)
return;
searchComponents(this);
debug5.search(this._componentNameMap);
this._searched = true;
}
_generateDeclaration(removeUnused = !this._server) {
if (!this.options.dts)
return;
debug5.decleration("generating");
return writeDeclaration(this, this.options.dts, removeUnused);
}
get componentNameMap() {
return this._componentNameMap;
}
get componentCustomMap() {
return this._componentCustomMap;
}
get directiveCustomMap() {
return this._directiveCustomMap;
}
};
// src/core/unplugin.ts
var PLUGIN_NAME = "unplugin:webpack";
var unplugin_default = createUnplugin((options = {}) => {
const filter = createFilter(
options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
);
const ctx = new Context(options);
const api = {
async findComponent(name, filename) {
return await ctx.findComponent(name, "component", filename ? [filename] : []);
},
stringifyImport(info) {
return stringifyComponentImport(info, ctx);
}
};
return {
name: "unplugin-vue-components",
enforce: "post",
api,
transformInclude(id) {
return filter(id);
},
async transform(code, id) {
if (!shouldTransform(code))
return null;
try {
const result = await ctx.transform(code, id);
ctx.generateDeclaration();
return result;
} catch (e) {
this.error(e);
}
},
vite: {
configResolved(config) {
ctx.setRoot(config.root);
ctx.sourcemap = true;
if (config.plugins.find((i) => i.name === "vite-plugin-vue2"))
ctx.setTransformer("vue2");
if (ctx.options.dts) {
ctx.searchGlob();
if (!existsSync2(ctx.options.dts))
ctx.generateDeclaration();
}
if (config.build.watch && config.command === "build")
ctx.setupWatcher(chokidar.watch(ctx.options.globs));
},
configureServer(server) {
ctx.setupViteServer(server);
}
},
webpack(compiler) {
let watcher;
let fileDepQueue = [];
compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
if (!watcher && compiler.watching) {
watcher = compiler.watching;
ctx.setupWatcherWebpack(chokidar.watch(ctx.options.globs), (path, type) => {
fileDepQueue.push({ path, type });
process.nextTick(() => {
watcher.invalidate();
});
});
}
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (fileDepQueue.length) {
fileDepQueue.forEach(({ path, type }) => {
if (type === "unlink")
compilation.fileDependencies.delete(path);
else
compilation.fileDependencies.add(path);
});
fileDepQueue = [];
}
});
}
};
});
export {
unplugin_default
};

View File

@@ -0,0 +1,751 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _chunkHCIFGIWSjs = require('./chunk-HCIFGIWS.js');
var _chunkBTQOTIPQjs = require('./chunk-BTQOTIPQ.js');
// src/core/unplugin.ts
var _fs = require('fs');
var _unplugin = require('unplugin');
var _pluginutils = require('@rollup/pluginutils');
var _chokidar = require('chokidar'); var _chokidar2 = _interopRequireDefault(_chokidar);
// src/core/context.ts
var _path = require('path');
var _debug = require('debug'); var _debug2 = _interopRequireDefault(_debug);
var _utils = require('@antfu/utils');
// src/core/options.ts
var _localpkg = require('local-pkg');
// src/core/type-imports/detect.ts
// src/core/type-imports/index.ts
var TypeImportPresets = [
{
from: "vue-router",
names: [
"RouterView",
"RouterLink"
]
},
{
from: "vue-starport",
names: [
"Starport",
"StarportCarrier"
]
}
];
// src/core/type-imports/detect.ts
function detectTypeImports() {
return TypeImportPresets.map((i) => _localpkg.isPackageExists.call(void 0, i.from) ? i : void 0).filter(_utils.notNullish);
}
function resolveTypeImports(imports) {
return imports.flatMap((i) => i.names.map((n) => ({ from: i.from, name: n, as: n })));
}
// src/core/options.ts
var defaultOptions = {
dirs: "src/components",
extensions: "vue",
deep: true,
dts: _localpkg.isPackageExists.call(void 0, "typescript"),
directoryAsNamespace: false,
collapseSamePrefixes: false,
globalNamespaces: [],
resolvers: [],
importPathTransform: (v) => v,
allowOverrides: false
};
function normalizeResolvers(resolvers) {
return _utils.toArray.call(void 0, resolvers).flat().map((r) => typeof r === "function" ? { resolve: r, type: "component" } : r);
}
function resolveOptions(options, root) {
var _a;
const resolved = Object.assign({}, defaultOptions, options);
resolved.resolvers = normalizeResolvers(resolved.resolvers);
resolved.extensions = _utils.toArray.call(void 0, resolved.extensions);
if (resolved.globs) {
resolved.globs = _utils.toArray.call(void 0, resolved.globs).map((glob) => _utils.slash.call(void 0, _path.resolve.call(void 0, root, glob)));
resolved.resolvedDirs = [];
} else {
const extsGlob = resolved.extensions.length === 1 ? resolved.extensions : `{${resolved.extensions.join(",")}}`;
resolved.dirs = _utils.toArray.call(void 0, resolved.dirs);
resolved.resolvedDirs = resolved.dirs.map((i) => _utils.slash.call(void 0, _path.resolve.call(void 0, root, i)));
resolved.globs = resolved.resolvedDirs.map(
(i) => resolved.deep ? _utils.slash.call(void 0, _path.join.call(void 0, i, `**/*.${extsGlob}`)) : _utils.slash.call(void 0, _path.join.call(void 0, i, `*.${extsGlob}`))
);
if (!resolved.extensions.length)
throw new Error("[unplugin-vue-components] `extensions` option is required to search for components");
}
resolved.dts = !resolved.dts ? false : _path.resolve.call(void 0,
root,
typeof resolved.dts === "string" ? resolved.dts : "components.d.ts"
);
if (!resolved.types && resolved.dts)
resolved.types = detectTypeImports();
resolved.types = resolved.types || [];
resolved.root = root;
resolved.version = (_a = resolved.version) != null ? _a : getVueVersion(root);
if (resolved.version < 2 || resolved.version >= 4)
throw new Error(`[unplugin-vue-components] unsupported version: ${resolved.version}`);
resolved.transformer = options.transformer || `vue${Math.trunc(resolved.version)}`;
resolved.directives = typeof options.directives === "boolean" ? options.directives : !resolved.resolvers.some((i) => i.type === "directive") ? false : resolved.version >= 3;
return resolved;
}
function getVueVersion(root) {
var _a;
const raw = ((_a = _localpkg.getPackageInfoSync.call(void 0, "vue", { paths: [root] })) == null ? void 0 : _a.version) || "3";
const version = +raw.split(".").slice(0, 2).join(".");
if (version === 2.7)
return 2.7;
else if (version < 2.7)
return 2;
return 3;
}
// src/core/fs/glob.ts
var _fastglob = require('fast-glob'); var _fastglob2 = _interopRequireDefault(_fastglob);
var debug = _debug2.default.call(void 0, "unplugin-vue-components:glob");
function searchComponents(ctx) {
var _a;
debug(`started with: [${ctx.options.globs.join(", ")}]`);
const root = ctx.root;
const files = _fastglob2.default.sync(ctx.options.globs, {
ignore: ["node_modules"],
onlyFiles: true,
cwd: root,
absolute: true
});
if (!files.length && !((_a = ctx.options.resolvers) == null ? void 0 : _a.length))
console.warn("[unplugin-vue-components] no components found");
debug(`${files.length} components found.`);
ctx.addComponents(files);
}
// src/core/declaration.ts
var _promises = require('fs/promises');
var multilineCommentsRE = new RegExp("\\/\\*.*?\\*\\/", "gms");
var singlelineCommentsRE = /\/\/.*$/gm;
function extractImports(code) {
return Object.fromEntries(Array.from(code.matchAll(/['"]?([^\s'"]+)['"]?\s*:\s*(.+?)[,;\n]/g)).map((i) => [i[1], i[2]]));
}
function parseDeclaration(code) {
var _a, _b;
if (!code)
return;
code = code.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const imports = {
component: {},
directive: {}
};
const componentDeclaration = (_a = new RegExp("export\\s+interface\\s+GlobalComponents\\s*{(.*?)}", "s").exec(code)) == null ? void 0 : _a[0];
if (componentDeclaration)
imports.component = extractImports(componentDeclaration);
const directiveDeclaration = (_b = new RegExp("export\\s+interface\\s+ComponentCustomProperties\\s*{(.*?)}", "s").exec(code)) == null ? void 0 : _b[0];
if (directiveDeclaration)
imports.directive = extractImports(directiveDeclaration);
return imports;
}
function stringifyComponentInfo(filepath, { from: path, as: name, name: importName }, importPathTransform) {
if (!name)
return void 0;
path = _chunkHCIFGIWSjs.getTransformedPath.call(void 0, path, importPathTransform);
const related = _path.isAbsolute.call(void 0, path) ? `./${_path.relative.call(void 0, _path.dirname.call(void 0, filepath), path)}` : path;
const entry = `typeof import('${_utils.slash.call(void 0, related)}')['${importName || "default"}']`;
return [name, entry];
}
function stringifyComponentsInfo(filepath, components, importPathTransform) {
return Object.fromEntries(
components.map((info) => stringifyComponentInfo(filepath, info, importPathTransform)).filter(_utils.notNullish)
);
}
function getDeclarationImports(ctx, filepath) {
const component = stringifyComponentsInfo(filepath, [
...Object.values(_chunkBTQOTIPQjs.__spreadValues.call(void 0, _chunkBTQOTIPQjs.__spreadValues.call(void 0, {}, ctx.componentNameMap), ctx.componentCustomMap)),
...resolveTypeImports(ctx.options.types)
], ctx.options.importPathTransform);
const directive = stringifyComponentsInfo(
filepath,
Object.values(ctx.directiveCustomMap),
ctx.options.importPathTransform
);
if (Object.keys(component).length + Object.keys(directive).length === 0)
return;
return { component, directive };
}
function stringifyDeclarationImports(imports) {
return Object.entries(imports).sort(([a], [b]) => a.localeCompare(b)).map(([name, v]) => {
if (!/^\w+$/.test(name))
name = `'${name}'`;
return `${name}: ${v}`;
});
}
function getDeclaration(ctx, filepath, originalImports) {
const imports = getDeclarationImports(ctx, filepath);
if (!imports)
return;
const declarations = {
component: stringifyDeclarationImports(_chunkBTQOTIPQjs.__spreadValues.call(void 0, _chunkBTQOTIPQjs.__spreadValues.call(void 0, {}, originalImports == null ? void 0 : originalImports.component), imports.component)),
directive: stringifyDeclarationImports(_chunkBTQOTIPQjs.__spreadValues.call(void 0, _chunkBTQOTIPQjs.__spreadValues.call(void 0, {}, originalImports == null ? void 0 : originalImports.directive), imports.directive))
};
const head = ctx.options.version === 2.7 ? `export {}
declare module 'vue' {` : `import '@vue/runtime-core'
export {}
declare module '@vue/runtime-core' {`;
let code = `/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// Generated by unplugin-vue-components
// Read more: https://github.com/vuejs/core/pull/3399
${head}`;
if (Object.keys(declarations.component).length > 0) {
code += `
export interface GlobalComponents {
${declarations.component.join("\n ")}
}`;
}
if (Object.keys(declarations.directive).length > 0) {
code += `
export interface ComponentCustomProperties {
${declarations.directive.join("\n ")}
}`;
}
code += "\n}\n";
return code;
}
async function writeFile(filePath, content) {
await _promises.mkdir.call(void 0, _path.dirname.call(void 0, filePath), { recursive: true });
return await _promises.writeFile.call(void 0, filePath, content, "utf-8");
}
async function writeDeclaration(ctx, filepath, removeUnused = false) {
const originalContent = _fs.existsSync.call(void 0, filepath) ? await _promises.readFile.call(void 0, filepath, "utf-8") : "";
const originalImports = removeUnused ? void 0 : parseDeclaration(originalContent);
const code = getDeclaration(ctx, filepath, originalImports);
if (!code)
return;
if (code !== originalContent)
await writeFile(filepath, code);
}
// src/core/transformer.ts
var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
// src/core/transforms/component.ts
var debug2 = _debug2.default.call(void 0, "unplugin-vue-components:transform:component");
var resolveVue2 = (code, s) => {
const results = [];
for (const match of code.matchAll(/\b(_c|h)\([\s\n\t]*['"](.+?)["']([,)])/g)) {
const [full, renderFunctionName, matchedName, append] = match;
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + full.length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, `${renderFunctionName}(${resolved}${append}`)
});
}
}
return results;
};
var resolveVue3 = (code, s) => {
const results = [];
for (const match of code.matchAll(/_resolveComponent[0-9]*\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
};
async function transformComponent(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = transformer2 === "vue2" ? resolveVue2(code, s) : resolveVue3(code, s);
for (const { rawName, replace } of results) {
debug2(`| ${rawName}`);
const name = _chunkHCIFGIWSjs.pascalCase.call(void 0, rawName);
ctx.updateUsageMap(sfcPath, [name]);
const component = await ctx.findComponent(name, "component", [sfcPath]);
if (component) {
const varName = `__unplugin_components_${no}`;
s.prepend(`${_chunkHCIFGIWSjs.stringifyComponentImport.call(void 0, _chunkBTQOTIPQjs.__spreadProps.call(void 0, _chunkBTQOTIPQjs.__spreadValues.call(void 0, {}, component), { as: varName }), ctx)};
`);
no += 1;
replace(varName);
}
}
debug2(`^ (${no})`);
}
// src/core/transforms/directive/index.ts
// src/core/transforms/directive/vue2.ts
var getRenderFnStart = (program) => {
var _a, _b;
const renderFn = program.body.find(
(node) => node.type === "VariableDeclaration" && node.declarations[0].id.type === "Identifier" && ["render", "_sfc_render"].includes(node.declarations[0].id.name)
);
const start = (_b = (_a = renderFn == null ? void 0 : renderFn.declarations[0].init) == null ? void 0 : _a.body) == null ? void 0 : _b.start;
if (start === null || start === void 0)
throw new Error("[unplugin-vue-components:directive] Cannot find render function position.");
return start + 1;
};
async function resolveVue22(code, s) {
var _a, _b, _c;
if (!_localpkg.isPackageExists.call(void 0, "@babel/parser"))
throw new Error('[unplugin-vue-components:directive] To use Vue 2 directive you will need to install Babel first: "npm install -D @babel/parser"');
const { parse } = await _localpkg.importModule.call(void 0, "@babel/parser");
const { program } = parse(code, {
sourceType: "module"
});
const nodes = [];
const { walk } = await Promise.resolve().then(() => require("./src-FZTNZZMC.js"));
walk(program, {
enter(node) {
if (node.type === "CallExpression")
nodes.push(node);
}
});
if (nodes.length === 0)
return [];
let _renderStart;
const getRenderStart = () => {
if (_renderStart !== void 0)
return _renderStart;
return _renderStart = getRenderFnStart(program);
};
const results = [];
for (const node of nodes) {
const { callee, arguments: args } = node;
if (callee.type !== "Identifier" || callee.name !== "_c" || ((_a = args[1]) == null ? void 0 : _a.type) !== "ObjectExpression")
continue;
const directives = (_b = args[1].properties.find(
(property) => property.type === "ObjectProperty" && property.key.type === "Identifier" && property.key.name === "directives"
)) == null ? void 0 : _b.value;
if (!directives || directives.type !== "ArrayExpression")
continue;
for (const directive of directives.elements) {
if ((directive == null ? void 0 : directive.type) !== "ObjectExpression")
continue;
const nameNode = (_c = directive.properties.find(
(p) => p.type === "ObjectProperty" && p.key.type === "Identifier" && p.key.name === "name"
)) == null ? void 0 : _c.value;
if ((nameNode == null ? void 0 : nameNode.type) !== "StringLiteral")
continue;
const name = nameNode.value;
if (!name || name.startsWith("_"))
continue;
results.push({
rawName: name,
replace: (resolved) => {
s.prependLeft(getRenderStart(), `
this.$options.directives["${name}"] = ${resolved};`);
}
});
}
}
return results;
}
// src/core/transforms/directive/vue3.ts
function resolveVue32(code, s) {
const results = [];
for (const match of code.matchAll(/_resolveDirective\("(.+?)"\)/g)) {
const matchedName = match[1];
if (match.index != null && matchedName && !matchedName.startsWith("_")) {
const start = match.index;
const end = start + match[0].length;
results.push({
rawName: matchedName,
replace: (resolved) => s.overwrite(start, end, resolved)
});
}
}
return results;
}
// src/core/transforms/directive/index.ts
var debug3 = _debug2.default.call(void 0, "unplugin-vue-components:transform:directive");
async function transformDirective(code, transformer2, s, ctx, sfcPath) {
let no = 0;
const results = await (transformer2 === "vue2" ? resolveVue22(code, s) : resolveVue32(code, s));
for (const { rawName, replace } of results) {
debug3(`| ${rawName}`);
const name = `${_chunkHCIFGIWSjs.DIRECTIVE_IMPORT_PREFIX}${_chunkHCIFGIWSjs.pascalCase.call(void 0, rawName)}`;
ctx.updateUsageMap(sfcPath, [name]);
const directive = await ctx.findComponent(name, "directive", [sfcPath]);
if (!directive)
continue;
const varName = `__unplugin_directives_${no}`;
s.prepend(`${_chunkHCIFGIWSjs.stringifyComponentImport.call(void 0, _chunkBTQOTIPQjs.__spreadProps.call(void 0, _chunkBTQOTIPQjs.__spreadValues.call(void 0, {}, directive), { as: varName }), ctx)};
`);
no += 1;
replace(varName);
}
debug3(`^ (${no})`);
}
// src/core/transformer.ts
var debug4 = _debug2.default.call(void 0, "unplugin-vue-components:transformer");
function transformer(ctx, transformer2) {
return async (code, id, path) => {
ctx.searchGlob();
const sfcPath = ctx.normalizePath(path);
debug4(sfcPath);
const s = new (0, _magicstring2.default)(code);
await transformComponent(code, transformer2, s, ctx, sfcPath);
if (ctx.options.directives)
await transformDirective(code, transformer2, s, ctx, sfcPath);
s.prepend(_chunkHCIFGIWSjs.DISABLE_COMMENT);
const result = { code: s.toString() };
if (ctx.sourcemap)
result.map = s.generateMap({ source: id, includeContent: true });
return result;
};
}
// src/core/context.ts
var debug5 = {
components: _debug2.default.call(void 0, "unplugin-vue-components:context:components"),
search: _debug2.default.call(void 0, "unplugin-vue-components:context:search"),
hmr: _debug2.default.call(void 0, "unplugin-vue-components:context:hmr"),
decleration: _debug2.default.call(void 0, "unplugin-vue-components:decleration"),
env: _debug2.default.call(void 0, "unplugin-vue-components:env")
};
var Context = class {
constructor(rawOptions) {
this.rawOptions = rawOptions;
this.transformer = void 0;
this._componentPaths = /* @__PURE__ */ new Set();
this._componentNameMap = {};
this._componentUsageMap = {};
this._componentCustomMap = {};
this._directiveCustomMap = {};
this.root = process.cwd();
this.sourcemap = true;
this.alias = {};
this._searched = false;
this.options = resolveOptions(rawOptions, this.root);
this.generateDeclaration = _utils.throttle.call(void 0, 500, this._generateDeclaration.bind(this), { noLeading: false });
this.setTransformer(this.options.transformer);
}
setRoot(root) {
if (this.root === root)
return;
debug5.env("root", root);
this.root = root;
this.options = resolveOptions(this.rawOptions, this.root);
}
setTransformer(name) {
debug5.env("transformer", name);
this.transformer = transformer(this, name || "vue3");
}
transform(code, id) {
const { path, query } = _chunkHCIFGIWSjs.parseId.call(void 0, id);
return this.transformer(code, id, path, query);
}
setupViteServer(server) {
if (this._server === server)
return;
this._server = server;
this.setupWatcher(server.watcher);
}
setupWatcher(watcher) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.removeComponents(path);
this.onUpdate(path);
});
watcher.on("add", (path) => {
if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.addComponents(path);
this.onUpdate(path);
});
}
/**
* start watcher for webpack
*/
setupWatcherWebpack(watcher, emitUpdate) {
const { globs } = this.options;
watcher.on("unlink", (path) => {
if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.removeComponents(path);
emitUpdate(path, "unlink");
});
watcher.on("add", (path) => {
if (!_chunkHCIFGIWSjs.matchGlobs.call(void 0, path, globs))
return;
path = _utils.slash.call(void 0, path);
this.addComponents(path);
emitUpdate(path, "add");
});
}
/**
* Record the usage of components
* @param path
* @param paths paths of used components
*/
updateUsageMap(path, paths) {
if (!this._componentUsageMap[path])
this._componentUsageMap[path] = /* @__PURE__ */ new Set();
paths.forEach((p) => {
this._componentUsageMap[path].add(p);
});
}
addComponents(paths) {
debug5.components("add", paths);
const size = this._componentPaths.size;
_utils.toArray.call(void 0, paths).forEach((p) => this._componentPaths.add(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
addCustomComponents(info) {
if (info.as)
this._componentCustomMap[info.as] = info;
}
addCustomDirectives(info) {
if (info.as)
this._directiveCustomMap[info.as] = info;
}
removeComponents(paths) {
debug5.components("remove", paths);
const size = this._componentPaths.size;
_utils.toArray.call(void 0, paths).forEach((p) => this._componentPaths.delete(p));
if (this._componentPaths.size !== size) {
this.updateComponentNameMap();
return true;
}
return false;
}
onUpdate(path) {
this.generateDeclaration();
if (!this._server)
return;
const payload = {
type: "update",
updates: []
};
const timestamp = +/* @__PURE__ */ new Date();
const name = _chunkHCIFGIWSjs.pascalCase.call(void 0, _chunkHCIFGIWSjs.getNameFromFilePath.call(void 0, path, this.options));
Object.entries(this._componentUsageMap).forEach(([key, values]) => {
if (values.has(name)) {
const r = `/${_utils.slash.call(void 0, _path.relative.call(void 0, this.root, key))}`;
payload.updates.push({
acceptedPath: r,
path: r,
timestamp,
type: "js-update"
});
}
});
if (payload.updates.length)
this._server.ws.send(payload);
}
updateComponentNameMap() {
this._componentNameMap = {};
Array.from(this._componentPaths).forEach((path) => {
const name = _chunkHCIFGIWSjs.pascalCase.call(void 0, _chunkHCIFGIWSjs.getNameFromFilePath.call(void 0, path, this.options));
if (this._componentNameMap[name] && !this.options.allowOverrides) {
console.warn(`[unplugin-vue-components] component "${name}"(${path}) has naming conflicts with other components, ignored.`);
return;
}
this._componentNameMap[name] = {
as: name,
from: path
};
});
}
async findComponent(name, type, excludePaths = []) {
let info = this._componentNameMap[name];
if (info && !excludePaths.includes(info.from) && !excludePaths.includes(info.from.slice(1)))
return info;
for (const resolver of this.options.resolvers) {
if (resolver.type !== type)
continue;
const result = await resolver.resolve(type === "directive" ? name.slice(_chunkHCIFGIWSjs.DIRECTIVE_IMPORT_PREFIX.length) : name);
if (!result)
continue;
if (typeof result === "string") {
info = {
as: name,
from: result
};
} else {
info = _chunkBTQOTIPQjs.__spreadValues.call(void 0, {
as: name
}, _chunkHCIFGIWSjs.normalizeComponetInfo.call(void 0, result));
}
if (type === "component")
this.addCustomComponents(info);
else if (type === "directive")
this.addCustomDirectives(info);
return info;
}
return void 0;
}
normalizePath(path) {
var _a, _b, _c;
return _chunkHCIFGIWSjs.resolveAlias.call(void 0, path, ((_b = (_a = this.viteConfig) == null ? void 0 : _a.resolve) == null ? void 0 : _b.alias) || ((_c = this.viteConfig) == null ? void 0 : _c.alias) || []);
}
relative(path) {
if (path.startsWith("/") && !path.startsWith(this.root))
return _utils.slash.call(void 0, path.slice(1));
return _utils.slash.call(void 0, _path.relative.call(void 0, this.root, path));
}
/**
* This search for components in with the given options.
* Will be called multiple times to ensure file loaded,
* should normally run only once.
*/
searchGlob() {
if (this._searched)
return;
searchComponents(this);
debug5.search(this._componentNameMap);
this._searched = true;
}
_generateDeclaration(removeUnused = !this._server) {
if (!this.options.dts)
return;
debug5.decleration("generating");
return writeDeclaration(this, this.options.dts, removeUnused);
}
get componentNameMap() {
return this._componentNameMap;
}
get componentCustomMap() {
return this._componentCustomMap;
}
get directiveCustomMap() {
return this._directiveCustomMap;
}
};
// src/core/unplugin.ts
var PLUGIN_NAME = "unplugin:webpack";
var unplugin_default = _unplugin.createUnplugin.call(void 0, (options = {}) => {
const filter = _pluginutils.createFilter.call(void 0,
options.include || [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/, /[\\/]\.nuxt[\\/]/]
);
const ctx = new Context(options);
const api = {
async findComponent(name, filename) {
return await ctx.findComponent(name, "component", filename ? [filename] : []);
},
stringifyImport(info) {
return _chunkHCIFGIWSjs.stringifyComponentImport.call(void 0, info, ctx);
}
};
return {
name: "unplugin-vue-components",
enforce: "post",
api,
transformInclude(id) {
return filter(id);
},
async transform(code, id) {
if (!_chunkHCIFGIWSjs.shouldTransform.call(void 0, code))
return null;
try {
const result = await ctx.transform(code, id);
ctx.generateDeclaration();
return result;
} catch (e) {
this.error(e);
}
},
vite: {
configResolved(config) {
ctx.setRoot(config.root);
ctx.sourcemap = true;
if (config.plugins.find((i) => i.name === "vite-plugin-vue2"))
ctx.setTransformer("vue2");
if (ctx.options.dts) {
ctx.searchGlob();
if (!_fs.existsSync.call(void 0, ctx.options.dts))
ctx.generateDeclaration();
}
if (config.build.watch && config.command === "build")
ctx.setupWatcher(_chokidar2.default.watch(ctx.options.globs));
},
configureServer(server) {
ctx.setupViteServer(server);
}
},
webpack(compiler) {
let watcher;
let fileDepQueue = [];
compiler.hooks.watchRun.tap(PLUGIN_NAME, () => {
if (!watcher && compiler.watching) {
watcher = compiler.watching;
ctx.setupWatcherWebpack(_chokidar2.default.watch(ctx.options.globs), (path, type) => {
fileDepQueue.push({ path, type });
process.nextTick(() => {
watcher.invalidate();
});
});
}
});
compiler.hooks.compilation.tap(PLUGIN_NAME, (compilation) => {
if (fileDepQueue.length) {
fileDepQueue.forEach(({ path, type }) => {
if (type === "unlink")
compilation.fileDependencies.delete(path);
else
compilation.fileDependencies.add(path);
});
fileDepQueue = [];
}
});
}
};
});
exports.unplugin_default = unplugin_default;

View File

@@ -0,0 +1,32 @@
var __defProp = Object.defineProperty;
var __defProps = Object.defineProperties;
var __getOwnPropDescs = Object.getOwnPropertyDescriptors;
var __getOwnPropSymbols = Object.getOwnPropertySymbols;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __propIsEnum = Object.prototype.propertyIsEnumerable;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __spreadValues = (a, b) => {
for (var prop in b || (b = {}))
if (__hasOwnProp.call(b, prop))
__defNormalProp(a, prop, b[prop]);
if (__getOwnPropSymbols)
for (var prop of __getOwnPropSymbols(b)) {
if (__propIsEnum.call(b, prop))
__defNormalProp(a, prop, b[prop]);
}
return a;
};
var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b));
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined")
return require.apply(this, arguments);
throw new Error('Dynamic require of "' + x + '" is not supported');
});
export {
__spreadValues,
__spreadProps,
__require
};

View File

@@ -0,0 +1,9 @@
import * as esbuild from 'esbuild';
import { Options } from './types.js';
import '@rollup/pluginutils';
import 'unplugin';
import '@antfu/utils';
declare const _default: (options: Options) => esbuild.Plugin;
export { _default as default };

View File

@@ -0,0 +1,13 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZ3TQFCNGjs = require('./chunk-Z3TQFCNG.js');
require('./chunk-HCIFGIWS.js');
require('./chunk-BTQOTIPQ.js');
require('./chunk-6F4PWJZI.js');
// src/esbuild.ts
var esbuild_default = _chunkZ3TQFCNGjs.unplugin_default.esbuild;
module.exports = esbuild_default;
exports.default = module.exports;

View File

@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-WVTE3GCL.mjs";
import "./chunk-BPHJA2FM.mjs";
import "./chunk-ZKNUHGJ4.mjs";
import "./chunk-WBQAMGXK.mjs";
// src/esbuild.ts
var esbuild_default = unplugin_default.esbuild;
export {
esbuild_default as default
};

View File

@@ -0,0 +1,13 @@
import { Options } from './types.js';
export { ComponentInfo, ComponentResolveResult, ComponentResolver, ComponentResolverFunction, ComponentResolverObject, ComponentsImportMap, ImportInfo, ImportInfoLegacy, Matcher, PublicPluginAPI, ResolvedOptions, SideEffectsInfo, SupportedTransformer, Transformer, TypeImport } from './types.js';
import * as unplugin from 'unplugin';
import '@rollup/pluginutils';
import '@antfu/utils';
declare const _default: unplugin.UnpluginInstance<Options, boolean>;
declare function pascalCase(str: string): string;
declare function camelCase(str: string): string;
declare function kebabCase(key: string): string;
export { Options, camelCase, _default as default, kebabCase, pascalCase };

View File

@@ -0,0 +1,16 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZ3TQFCNGjs = require('./chunk-Z3TQFCNG.js');
var _chunkHCIFGIWSjs = require('./chunk-HCIFGIWS.js');
require('./chunk-BTQOTIPQ.js');
require('./chunk-6F4PWJZI.js');
exports.camelCase = _chunkHCIFGIWSjs.camelCase; exports.default = _chunkZ3TQFCNGjs.unplugin_default; exports.kebabCase = _chunkHCIFGIWSjs.kebabCase; exports.pascalCase = _chunkHCIFGIWSjs.pascalCase;

View File

@@ -0,0 +1,16 @@
import {
unplugin_default
} from "./chunk-WVTE3GCL.mjs";
import {
camelCase,
kebabCase,
pascalCase
} from "./chunk-BPHJA2FM.mjs";
import "./chunk-ZKNUHGJ4.mjs";
import "./chunk-WBQAMGXK.mjs";
export {
camelCase,
unplugin_default as default,
kebabCase,
pascalCase
};

View File

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

View File

@@ -0,0 +1,19 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZ3TQFCNGjs = require('./chunk-Z3TQFCNG.js');
require('./chunk-HCIFGIWS.js');
require('./chunk-BTQOTIPQ.js');
require('./chunk-6F4PWJZI.js');
// src/nuxt.ts
var _kit = require('@nuxt/kit');
var nuxt_default = _kit.defineNuxtModule.call(void 0, {
setup(options) {
_kit.addWebpackPlugin.call(void 0, _chunkZ3TQFCNGjs.unplugin_default.webpack(options));
_kit.addVitePlugin.call(void 0, _chunkZ3TQFCNGjs.unplugin_default.vite(options));
}
});
module.exports = nuxt_default;
exports.default = module.exports;

View File

@@ -0,0 +1,18 @@
import {
unplugin_default
} from "./chunk-WVTE3GCL.mjs";
import "./chunk-BPHJA2FM.mjs";
import "./chunk-ZKNUHGJ4.mjs";
import "./chunk-WBQAMGXK.mjs";
// src/nuxt.ts
import { addVitePlugin, addWebpackPlugin, defineNuxtModule } from "@nuxt/kit";
var nuxt_default = defineNuxtModule({
setup(options) {
addWebpackPlugin(unplugin_default.webpack(options));
addVitePlugin(unplugin_default.vite(options));
}
});
export {
nuxt_default as default
};

View File

@@ -0,0 +1,525 @@
import { ComponentResolver, ComponentResolveResult } from './types.js';
import '@rollup/pluginutils';
import 'unplugin';
import '@antfu/utils';
interface AntDesignVueResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string[];
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* resolve `ant-design-vue' icons
*
* requires package `@ant-design/icons-vue`
*
* @default false
*/
resolveIcons?: boolean;
/**
* @deprecated use `importStyle: 'css'` instead
*/
importCss?: boolean;
/**
* @deprecated use `importStyle: 'less'` instead
*/
importLess?: boolean;
/**
* use commonjs build default false
*/
cjs?: boolean;
/**
* rename package
*
* @default 'ant-design-vue'
*/
packageName?: string;
}
/**
* Resolver for Ant Design Vue
*
* Requires ant-design-vue@v2.2.0-beta.6 or later
*
* See https://github.com/antfu/unplugin-vue-components/issues/26#issuecomment-789767941 for more details
*
* @author @yangss3
* @link https://antdv.com/
*/
declare function AntDesignVueResolver(options?: AntDesignVueResolverOptions): ComponentResolver;
interface ElementPlusResolverOptions {
/**
* import style css or sass with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'sass';
/**
* use commonjs lib & source css or scss for ssr
*/
ssr?: boolean;
/**
* specify element-plus version to load style
*
* @default installed version
*/
version?: string;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* exclude component name, if match do not resolve the name
*/
exclude?: RegExp;
/**
* a list of component names that have no styles, so resolving their styles file should be prevented
*/
noStylesComponents?: string[];
}
/**
* Resolver for Element Plus
*
* See https://github.com/antfu/vite-plugin-components/pull/28 for more details
* See https://github.com/antfu/vite-plugin-components/issues/117 for more details
*
* @author @develar @nabaonan @sxzz
* @link https://element-plus.org/ for element-plus
*
*/
declare function ElementPlusResolver(options?: ElementPlusResolverOptions): ComponentResolver[];
interface ElementUiResolverOptions {
/**
* import style css or sass with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'sass';
/**
* exclude component name, if match do not resolve the name
*/
exclude?: RegExp;
}
/**
* Resolver for Element-UI
* @link https://element.eleme.cn/#/zh-CN
* @version @element-ui ^2.15.3, @vue ^2.6.14
* @author @nabaonan
*/
declare function ElementUiResolver(options?: ElementUiResolverOptions): ComponentResolver;
interface HeadlessUiResolverOptions {
/**
* prefix for headless ui components used in templates
*
* @default ""
*/
prefix?: string;
}
/**
* Resolver for headlessui
*
* @link https://github.com/tailwindlabs/headlessui
*/
declare function HeadlessUiResolver(options?: HeadlessUiResolverOptions): ComponentResolver;
interface IduxResolverOptions {
/**
* exclude components that do not require automatic import
*
* @default []
*/
exclude?: string[];
/**
* import style along with components
*/
importStyle?: 'css' | 'less';
/**
* theme for import style
*
* @default 'default'
*/
importStyleTheme?: string;
/**
* The scope of the packages.
*
* @default '@idux'
*/
scope?: string;
}
/**
* Resolver for `@idux/cdk`, `@idux/components` and ``@idux/pro``
*
* @link https://idux.site
*/
declare function IduxResolver(options?: IduxResolverOptions): ComponentResolver;
/**
* Resolver for Inkline
*
* @author @alexgrozav
* @link https://github.com/inkline/inkline
*/
declare function InklineResolver(): ComponentResolver;
/**
* Resolver for Naive UI
*
* @author @antfu
* @link https://www.naiveui.com/
*/
declare function NaiveUiResolver(): ComponentResolver;
interface PrimeVueResolverOptions {
/**
* import style along with components
*
* @default true
*/
importStyle?: boolean;
/**
* import `primeicons' icons
*
* requires package `primeicons`
*
* @default true
*/
importIcons?: boolean;
/**
* imports a free theme - set theme name here (e.g. saga-blue)
*
* @default ''
*/
importTheme?: string;
/**
* prefix for components (e.g. 'P' to resolve Menu from PMenu)
*
* @default ''
*/
prefix?: string;
}
/**
* Resolver for PrimeVue - If you're using a component with the same tag as an native HTML element (e.g. button) the component must be in uppercase
*
* @link https://github.com/primefaces/primevue
*/
declare function PrimeVueResolver(options?: PrimeVueResolverOptions): ComponentResolver;
interface VantResolverOptions {
/**
* import style css or less along with components
*
* @default true
*/
importStyle?: boolean | 'css' | 'less';
}
/**
* Resolver for Vant
*
* @link https://github.com/youzan/vant
*/
declare function VantResolver(options?: VantResolverOptions): ComponentResolver;
interface VarletUIResolverOptions {
/**
* support vue version
* vue3 use @varlet/ui, vue2 use @varlet-vue2/ui
*
* @default 'vue3'
*/
version?: 'vue3' | 'vue2';
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* compatible with unplugin-auto-import
*
* @default false
*/
autoImport?: boolean;
/**
* @deprecated use `importStyle: 'css'` instead
*/
importCss?: boolean;
/**
* @deprecated use `importStyle: 'less'` instead
*/
importLess?: boolean;
}
declare function getResolved(name: string, options: VarletUIResolverOptions): ComponentResolveResult;
/**
* Resolver for VarletUI
*
* @link https://github.com/varletjs/varlet
* @link https://github.com/varletjs/varlet-vue2
*/
declare function VarletUIResolver(options?: VarletUIResolverOptions): ComponentResolver[];
interface VeuiPeerConfig {
/**
* The package name of the peer module.
*/
package: string;
/**
* The directory path of the peer module.
* @default 'components'
*/
path?: string;
/**
* The file name template for the peer module.
* @default '{module}.css'
*/
fileName?: `${string}{module}${string}`;
/**
* The text transform to be applied to the '{module}' part of the file name.
* @default 'kebab-case'
*/
transform?: 'kebab-case' | 'camelCase' | 'PascalCase' | false;
}
type SupportedLocale = 'en-US' | 'zh-Hans';
interface VeuiResolverOptions {
/**
* The alias of 'veui` package.
* @default 'veui'
*/
alias?: string;
/**
* Peer modules to be injected.
*/
modules?: VeuiPeerConfig[];
/**
* Locale modules to be injected.
* @default 'zh-Hans'
*/
locale?: SupportedLocale | SupportedLocale[] | false;
/**
* Global modules to be injected to all components.
* @default []
*/
global?: string[];
}
/**
* Resolver for VEUI
*
* @link https://github.com/ecomfe/veui
*/
declare function VeuiResolver(options?: VeuiResolverOptions): ComponentResolver;
/**
* Resolver for View UI
* @requires @originjs/vite-plugin-commonjs
* @author @nabaonan
* @link https://www.iviewui.com/
* @description has known problems list below
* - select component render error PR: https://github.com/view-design/ViewUI/pull/944, choose can't display value,because click option trigger twice,at second time,select value turn into undefined.
* - scroll component has a template syntax called lang='html',it is require html-loader,but vite plugin not support yet,remove it can run. relate pr: https://github.com/view-design/ViewUI/pull/985
*/
declare function ViewUiResolver(): ComponentResolver;
/**
* Resolver for Vuetify
*
* @link https://github.com/vuetifyjs/vuetify
*/
declare function VuetifyResolver(): ComponentResolver;
/**
* Resolver for Vuetify 3 Beta
*
* @link https://github.com/vuetifyjs/vuetify
*/
declare function Vuetify3Resolver(): ComponentResolver;
/**
* Resolver for VueUse
*
* @link https://github.com/vueuse/vueuse
*/
declare function VueUseComponentsResolver(): ComponentResolver;
/**
* Resolver for VueUse
*
* @link https://github.com/vueuse/vueuse
*/
declare function VueUseDirectiveResolver(): ComponentResolver;
/**
* Resolver for Quasar
*
* @link https://github.com/quasarframework/quasar
*/
declare function QuasarResolver(): ComponentResolver;
interface DevResolverOptions {
/**
* bring in components and styles
*
* @default true
*/
importStyle?: boolean;
/**
* auto import for directives
*
* @default true
*/
directives?: boolean;
/**
* use umd lib file
*/
ssr?: boolean;
}
declare function DevUiResolver(options?: DevResolverOptions): ComponentResolver[];
type DisallowResolveIconOption = undefined | false | {
enable: false;
};
type AllowResolveIconOption = true | {
enable: true;
iconPrefix?: string;
};
type ResolveIconsOption = DisallowResolveIconOption | AllowResolveIconOption;
interface ArcoResolverOptions {
/**
* import style css or less with components
*
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* resolve icons
*
* @default false
*/
resolveIcons?: ResolveIconsOption;
/**
* Control style automatic import
*
* @default true
*/
sideEffect?: boolean;
}
/**
* Resolver for Arco Design Vue
*
* Requires arco-design/web-vue@2.11.0 or later
*
* @author @flsion
* @link https://arco.design/ for arco-design
*
*/
declare function ArcoResolver(options?: ArcoResolverOptions): ComponentResolver;
interface TDesignResolverOptions {
/**
* import style along with components
* @default 'css'
*/
importStyle?: boolean | 'css' | 'less';
/**
* select the specified library
* @default 'vue'
*/
library?: 'vue' | 'vue-next' | 'react' | 'mobile-vue' | 'mobile-react';
/**
* resolve `tdesign-icons'
* @default false
*/
resolveIcons?: boolean;
/**
* whether to import ESM version
* @default false
*/
esm?: boolean;
/**
* exclude component name, if match do not resolve the name
*
*/
exclude?: string | RegExp | (string | RegExp)[];
}
declare function TDesignResolver(options?: TDesignResolverOptions): ComponentResolver;
interface LayuiVueResolverOptions {
/**
* import style along with components
*
* @default 'css'
*/
importStyle?: boolean | 'css';
/**
* resolve '@layui/layui-vue' icons
* requires package `@layui/icons-vue`
*
* @default false
*/
resolveIcons?: boolean;
/**
* exclude components that do not require automatic import
*
*/
exclude?: Array<string | RegExp>;
}
/**
* Resolver for layui-vue
*
* @link http://www.layui-vue.com/ for layui-vue
*
*/
declare function LayuiVueResolver(options?: LayuiVueResolverOptions): ComponentResolver;
interface BootstrapVueResolverOptions {
/**
* Auto import for directives.
*
* @default true
*/
directives?: boolean;
}
/**
* Resolver for BootstrapVue
*
* @link https://github.com/bootstrap-vue/bootstrap-vue
*/
declare const BootstrapVueResolver: (_options?: BootstrapVueResolverOptions) => ComponentResolver[];
/**
* Resolver for BootstrapVueNext
*
* @link https://github.com/bootstrap-vue/bootstrap-vue-next
*/
declare const BootstrapVueNextResolver: (_options?: BootstrapVueResolverOptions) => Array<ComponentResolver>;
/**
* Resolver for legacy BootstrapVue3 apps
*
* @deprecated use BootstrapVueNextResolver with https://github.com/bootstrap-vue/bootstrap-vue-next
* @link https://www.npmjs.com/package/bootstrap-vue-3
*/
declare const BootstrapVue3Resolver: (_options?: BootstrapVueResolverOptions) => Array<ComponentResolver>;
/**
* Resolver for ionic framework
*
* @author @mathsgod
* @link https://github.com/mathsgod
*/
declare function IonicResolver(): ComponentResolver;
export { AllowResolveIconOption, AntDesignVueResolver, AntDesignVueResolverOptions, ArcoResolver, ArcoResolverOptions, BootstrapVue3Resolver, BootstrapVueNextResolver, BootstrapVueResolver, BootstrapVueResolverOptions, DevResolverOptions, DevUiResolver, DisallowResolveIconOption, ElementPlusResolver, ElementPlusResolverOptions, ElementUiResolver, ElementUiResolverOptions, HeadlessUiResolver, HeadlessUiResolverOptions, IduxResolver, IduxResolverOptions, InklineResolver, IonicResolver, LayuiVueResolver, LayuiVueResolverOptions, NaiveUiResolver, PrimeVueResolver, PrimeVueResolverOptions, QuasarResolver, ResolveIconsOption, TDesignResolver, TDesignResolverOptions, VantResolver, VantResolverOptions, VarletUIResolver, VarletUIResolverOptions, VeuiResolver, VeuiResolverOptions, ViewUiResolver, VueUseComponentsResolver, VueUseDirectiveResolver, Vuetify3Resolver, VuetifyResolver, getResolved };

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,9 @@
import * as rollup from 'rollup';
import { Options } from './types.js';
import '@rollup/pluginutils';
import 'unplugin';
import '@antfu/utils';
declare const _default: (options: Options) => rollup.Plugin | rollup.Plugin[];
export { _default as default };

View File

@@ -0,0 +1,13 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZ3TQFCNGjs = require('./chunk-Z3TQFCNG.js');
require('./chunk-HCIFGIWS.js');
require('./chunk-BTQOTIPQ.js');
require('./chunk-6F4PWJZI.js');
// src/rollup.ts
var rollup_default = _chunkZ3TQFCNGjs.unplugin_default.rollup;
module.exports = rollup_default;
exports.default = module.exports;

View File

@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-WVTE3GCL.mjs";
import "./chunk-BPHJA2FM.mjs";
import "./chunk-ZKNUHGJ4.mjs";
import "./chunk-WBQAMGXK.mjs";
// src/rollup.ts
var rollup_default = unplugin_default.rollup;
export {
rollup_default as default
};

View File

@@ -0,0 +1,268 @@
import "./chunk-ZKNUHGJ4.mjs";
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
var WalkerBase = class {
constructor() {
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== void 0) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
};
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
var SyncWalker = class extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped)
return node;
if (removed)
return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed)
return null;
}
}
return node;
}
};
function isNode(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/async.js
var AsyncWalker = class extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped)
return node;
if (removed)
return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode2(item)) {
if (!await this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode2(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed)
return null;
}
}
return node;
}
};
function isNode2(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}
export {
asyncWalk,
walk
};

View File

@@ -0,0 +1,269 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});require('./chunk-BTQOTIPQ.js');
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/walker.js
var WalkerBase = class {
constructor() {
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
* @param {Node} node
*/
replace(parent, prop, index, node) {
if (parent && prop) {
if (index != null) {
parent[prop][index] = node;
} else {
parent[prop] = node;
}
}
}
/**
* @template {Node} Parent
* @param {Parent | null | undefined} parent
* @param {keyof Parent | null | undefined} prop
* @param {number | null | undefined} index
*/
remove(parent, prop, index) {
if (parent && prop) {
if (index !== null && index !== void 0) {
parent[prop].splice(index, 1);
} else {
delete parent[prop];
}
}
}
};
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/sync.js
var SyncWalker = class extends WalkerBase {
/**
*
* @param {SyncHandler} [enter]
* @param {SyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Node | null}
*/
visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped)
return node;
if (removed)
return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode(item)) {
if (!this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode(value)) {
this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed)
return null;
}
}
return node;
}
};
function isNode(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/async.js
var AsyncWalker = class extends WalkerBase {
/**
*
* @param {AsyncHandler} [enter]
* @param {AsyncHandler} [leave]
*/
constructor(enter, leave) {
super();
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
this.context = {
skip: () => this.should_skip = true,
remove: () => this.should_remove = true,
replace: (node) => this.replacement = node
};
this.enter = enter;
this.leave = leave;
}
/**
* @template {Node} Parent
* @param {Node} node
* @param {Parent | null} parent
* @param {keyof Parent} [prop]
* @param {number | null} [index]
* @returns {Promise<Node | null>}
*/
async visit(node, parent, prop, index) {
if (node) {
if (this.enter) {
const _should_skip = this.should_skip;
const _should_remove = this.should_remove;
const _replacement = this.replacement;
this.should_skip = false;
this.should_remove = false;
this.replacement = null;
await this.enter.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const skipped = this.should_skip;
const removed = this.should_remove;
this.should_skip = _should_skip;
this.should_remove = _should_remove;
this.replacement = _replacement;
if (skipped)
return node;
if (removed)
return null;
}
let key;
for (key in node) {
const value = node[key];
if (value && typeof value === "object") {
if (Array.isArray(value)) {
const nodes = (
/** @type {Array<unknown>} */
value
);
for (let i = 0; i < nodes.length; i += 1) {
const item = nodes[i];
if (isNode2(item)) {
if (!await this.visit(item, node, key, i)) {
i--;
}
}
}
} else if (isNode2(value)) {
await this.visit(value, node, key, null);
}
}
}
if (this.leave) {
const _replacement = this.replacement;
const _should_remove = this.should_remove;
this.replacement = null;
this.should_remove = false;
await this.leave.call(this.context, node, parent, prop, index);
if (this.replacement) {
node = this.replacement;
this.replace(parent, prop, index, node);
}
if (this.should_remove) {
this.remove(parent, prop, index);
}
const removed = this.should_remove;
this.replacement = _replacement;
this.should_remove = _should_remove;
if (removed)
return null;
}
}
return node;
}
};
function isNode2(value) {
return value !== null && typeof value === "object" && "type" in value && typeof value.type === "string";
}
// node_modules/.pnpm/estree-walker@3.0.3/node_modules/estree-walker/src/index.js
function walk(ast, { enter, leave }) {
const instance = new SyncWalker(enter, leave);
return instance.visit(ast, null);
}
async function asyncWalk(ast, { enter, leave }) {
const instance = new AsyncWalker(enter, leave);
return await instance.visit(ast, null);
}
exports.asyncWalk = asyncWalk; exports.walk = walk;
exports.default = module.exports;

View File

@@ -0,0 +1,168 @@
import { FilterPattern } from '@rollup/pluginutils';
import { TransformResult } from 'unplugin';
import { Awaitable } from '@antfu/utils';
interface ImportInfoLegacy {
/**
* @deprecated renamed to `as`
*/
name?: string;
/**
* @deprecated renamed to `name`
*/
importName?: string;
/**
* @deprecated renamed to `from`
*/
path: string;
sideEffects?: SideEffectsInfo;
}
interface ImportInfo {
as?: string;
name?: string;
from: string;
}
type SideEffectsInfo = (ImportInfo | string)[] | ImportInfo | string | undefined;
interface ComponentInfo extends ImportInfo {
sideEffects?: SideEffectsInfo;
}
type ComponentResolveResult = Awaitable<string | ComponentInfo | null | undefined | void>;
type ComponentResolverFunction = (name: string) => ComponentResolveResult;
interface ComponentResolverObject {
type: 'component' | 'directive';
resolve: ComponentResolverFunction;
}
type ComponentResolver = ComponentResolverFunction | ComponentResolverObject;
type Matcher = (id: string) => boolean | null | undefined;
type Transformer = (code: string, id: string, path: string, query: Record<string, string>) => Awaitable<TransformResult | null>;
type SupportedTransformer = 'vue3' | 'vue2';
interface PublicPluginAPI {
/**
* Resolves a component using the configured resolvers.
*/
findComponent: (name: string, filename?: string) => Promise<ComponentInfo | undefined>;
/**
* Obtain an import statement for a resolved component.
*/
stringifyImport: (info: ComponentInfo) => string;
}
/**
* Plugin options.
*/
interface Options {
/**
* RegExp or glob to match files to be transformed
*/
include?: FilterPattern;
/**
* RegExp or glob to match files to NOT be transformed
*/
exclude?: FilterPattern;
/**
* Relative paths to the directory to search for components.
* @default 'src/components'
*/
dirs?: string | string[];
/**
* Valid file extensions for components.
* @default ['vue']
*/
extensions?: string | string[];
/**
* Glob patterns to match file names to be detected as components.
*
* When specified, the `dirs` and `extensions` options will be ignored.
*/
globs?: string | string[];
/**
* Search for subdirectories
* @default true
*/
deep?: boolean;
/**
* Allow subdirectories as namespace prefix for components
* @default false
*/
directoryAsNamespace?: boolean;
/**
* Collapse same prefixes (camel-sensitive) of folders and components
* to prevent duplication inside namespaced component name.
*
* Works when `directoryAsNamespace: true`
* @default false
*/
collapseSamePrefixes?: boolean;
/**
* Subdirectory paths for ignoring namespace prefixes
*
* Works when `directoryAsNamespace: true`
* @default "[]"
*/
globalNamespaces?: string[];
/**
* Pass a custom function to resolve the component importing path from the component name.
*
* The component names are always in PascalCase
*/
resolvers?: (ComponentResolver | ComponentResolver[])[];
/**
* Apply custom transform over the path for importing
*/
importPathTransform?: (path: string) => string | undefined;
/**
* Transformer to apply
*
* @default 'vue3'
*/
transformer?: SupportedTransformer;
/**
* Generate TypeScript declaration for global components
*
* Accept boolean or a path related to project root
*
* @see https://github.com/vuejs/core/pull/3399
* @see https://github.com/johnsoncodehk/volar#using
* @default true
*/
dts?: boolean | string;
/**
* Do not emit warning on component overriding
*
* @default false
*/
allowOverrides?: boolean;
/**
* auto import for directives.
*
* default: `true` for Vue 3, `false` for Vue 2
*
* Babel is needed to do the transformation for Vue 2, it's disabled by default for performance concerns.
* To install Babel, run: `npm install -D @babel/parser`
* @default undefined
*/
directives?: boolean;
/**
* Only provide types of components in library (registered globally)
**/
types?: TypeImport[];
/**
* Vue version of project. It will detect automatically if not specified.
*/
version?: 2 | 2.7 | 3;
}
type ResolvedOptions = Omit<Required<Options>, 'resolvers' | 'extensions' | 'dirs' | 'globalComponentsDeclaration'> & {
resolvers: ComponentResolverObject[];
extensions: string[];
dirs: string[];
resolvedDirs: string[];
globs: string[];
dts: string | false;
root: string;
};
type ComponentsImportMap = Record<string, string[] | undefined>;
interface TypeImport {
from: string;
names: string[];
}
export { ComponentInfo, ComponentResolveResult, ComponentResolver, ComponentResolverFunction, ComponentResolverObject, ComponentsImportMap, ImportInfo, ImportInfoLegacy, Matcher, Options, PublicPluginAPI, ResolvedOptions, SideEffectsInfo, SupportedTransformer, Transformer, TypeImport };

View File

@@ -0,0 +1,2 @@
"use strict";require('./chunk-6F4PWJZI.js');
exports.default = module.exports;

View File

@@ -0,0 +1 @@
import "./chunk-WBQAMGXK.mjs";

View File

@@ -0,0 +1,11 @@
import { Plugin } from 'vite';
import { Options, PublicPluginAPI } from './types.js';
import '@rollup/pluginutils';
import 'unplugin';
import '@antfu/utils';
declare const _default: (options?: Options | undefined) => Plugin & {
api: PublicPluginAPI;
};
export { _default as default };

View File

@@ -0,0 +1,13 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZ3TQFCNGjs = require('./chunk-Z3TQFCNG.js');
require('./chunk-HCIFGIWS.js');
require('./chunk-BTQOTIPQ.js');
require('./chunk-6F4PWJZI.js');
// src/vite.ts
var vite_default = _chunkZ3TQFCNGjs.unplugin_default.vite;
module.exports = vite_default;
exports.default = module.exports;

View File

@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-WVTE3GCL.mjs";
import "./chunk-BPHJA2FM.mjs";
import "./chunk-ZKNUHGJ4.mjs";
import "./chunk-WBQAMGXK.mjs";
// src/vite.ts
var vite_default = unplugin_default.vite;
export {
vite_default as default
};

View File

@@ -0,0 +1,9 @@
import * as webpack from 'webpack';
import { Options } from './types.js';
import '@rollup/pluginutils';
import 'unplugin';
import '@antfu/utils';
declare const _default: (options: Options) => webpack.WebpackPluginInstance;
export { _default as default };

View File

@@ -0,0 +1,13 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkZ3TQFCNGjs = require('./chunk-Z3TQFCNG.js');
require('./chunk-HCIFGIWS.js');
require('./chunk-BTQOTIPQ.js');
require('./chunk-6F4PWJZI.js');
// src/webpack.ts
var webpack_default = _chunkZ3TQFCNGjs.unplugin_default.webpack;
module.exports = webpack_default;
exports.default = module.exports;

View File

@@ -0,0 +1,12 @@
import {
unplugin_default
} from "./chunk-WVTE3GCL.mjs";
import "./chunk-BPHJA2FM.mjs";
import "./chunk-ZKNUHGJ4.mjs";
import "./chunk-WBQAMGXK.mjs";
// src/webpack.ts
var webpack_default = unplugin_default.webpack;
export {
webpack_default as default
};

View File

@@ -0,0 +1,255 @@
[npm]: https://img.shields.io/npm/v/@rollup/pluginutils
[npm-url]: https://www.npmjs.com/package/@rollup/pluginutils
[size]: https://packagephobia.now.sh/badge?p=@rollup/pluginutils
[size-url]: https://packagephobia.now.sh/result?p=@rollup/pluginutils
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/pluginutils
A set of utility functions commonly used by 🍣 Rollup plugins.
## Requirements
The plugin utils require an [LTS](https://github.com/nodejs/Release) Node version (v14.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/pluginutils --save-dev
```
## Usage
```js
import utils from '@rollup/pluginutils';
//...
```
## API
Available utility functions are listed below:
_Note: Parameter names immediately followed by a `?` indicate that the parameter is optional._
### addExtension
Adds an extension to a module ID if one does not exist.
Parameters: `(filename: String, ext?: String)`<br>
Returns: `String`
```js
import { addExtension } from '@rollup/pluginutils';
export default function myPlugin(options = {}) {
return {
resolveId(code, id) {
// only adds an extension if there isn't one already
id = addExtension(id); // `foo` -> `foo.js`, `foo.js` -> `foo.js`
id = addExtension(id, '.myext'); // `foo` -> `foo.myext`, `foo.js` -> `foo.js`
}
};
}
```
### attachScopes
Attaches `Scope` objects to the relevant nodes of an AST. Each `Scope` object has a `scope.contains(name)` method that returns `true` if a given name is defined in the current scope or a parent scope.
Parameters: `(ast: Node, propertyName?: String)`<br>
Returns: `Object`
See [rollup-plugin-inject](https://github.com/rollup/rollup-plugin-inject) or [rollup-plugin-commonjs](https://github.com/rollup/rollup-plugin-commonjs) for an example of usage.
```js
import { attachScopes } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
export default function myPlugin(options = {}) {
return {
transform(code) {
const ast = this.parse(code);
let scope = attachScopes(ast, 'scope');
walk(ast, {
enter(node) {
if (node.scope) scope = node.scope;
if (!scope.contains('foo')) {
// `foo` is not defined, so if we encounter it,
// we assume it's a global
}
},
leave(node) {
if (node.scope) scope = scope.parent;
}
});
}
};
}
```
### createFilter
Constructs a filter function which can be used to determine whether or not certain modules should be operated upon.
Parameters: `(include?: <picomatch>, exclude?: <picomatch>, options?: Object)`<br>
Returns: `String`
#### `include` and `exclude`
Type: `String | RegExp | Array[...String|RegExp]`<br>
A valid [`picomatch`](https://github.com/micromatch/picomatch#globbing-features) pattern, or array of patterns. If `options.include` is omitted or has zero length, filter will return `true` by default. Otherwise, an ID must match one or more of the `picomatch` patterns, and must not match any of the `options.exclude` patterns.
Note that `picomatch` patterns are very similar to [`minimatch`](https://github.com/isaacs/minimatch#readme) patterns, and in most use cases, they are interchangeable. If you have more specific pattern matching needs, you can view [this comparison table](https://github.com/micromatch/picomatch#library-comparisons) to learn more about where the libraries differ.
#### `options`
##### `resolve`
Type: `String | Boolean | null`
Optionally resolves the patterns against a directory other than `process.cwd()`. If a `String` is specified, then the value will be used as the base directory. Relative paths will be resolved against `process.cwd()` first. If `false`, then the patterns will not be resolved against any directory. This can be useful if you want to create a filter for virtual module names.
#### Usage
```js
import { createFilter } from '@rollup/pluginutils';
export default function myPlugin(options = {}) {
// assume that the myPlugin accepts options of `options.include` and `options.exclude`
var filter = createFilter(options.include, options.exclude, {
resolve: '/my/base/dir'
});
return {
transform(code, id) {
if (!filter(id)) return;
// proceed with the transformation...
}
};
}
```
### dataToEsm
Transforms objects into tree-shakable ES Module imports.
Parameters: `(data: Object)`<br>
Returns: `String`
#### `data`
Type: `Object`
An object to transform into an ES module.
#### Usage
```js
import { dataToEsm } from '@rollup/pluginutils';
const esModuleSource = dataToEsm(
{
custom: 'data',
to: ['treeshake']
},
{
compact: false,
indent: '\t',
preferConst: false,
objectShorthand: false,
namedExports: true
}
);
/*
Outputs the string ES module source:
export const custom = 'data';
export const to = ['treeshake'];
export default { custom, to };
*/
```
### extractAssignedNames
Extracts the names of all assignment targets based upon specified patterns.
Parameters: `(param: Node)`<br>
Returns: `Array[...String]`
#### `param`
Type: `Node`
An `acorn` AST Node.
#### Usage
```js
import { extractAssignedNames } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
export default function myPlugin(options = {}) {
return {
transform(code) {
const ast = this.parse(code);
walk(ast, {
enter(node) {
if (node.type === 'VariableDeclarator') {
const declaredNames = extractAssignedNames(node.id);
// do something with the declared names
// e.g. for `const {x, y: z} = ...` => declaredNames = ['x', 'z']
}
}
});
}
};
}
```
### makeLegalIdentifier
Constructs a bundle-safe identifier from a `String`.
Parameters: `(str: String)`<br>
Returns: `String`
#### Usage
```js
import { makeLegalIdentifier } from '@rollup/pluginutils';
makeLegalIdentifier('foo-bar'); // 'foo_bar'
makeLegalIdentifier('typeof'); // '_typeof'
```
### normalizePath
Converts path separators to forward slash.
Parameters: `(filename: String)`<br>
Returns: `String`
#### Usage
```js
import { normalizePath } from '@rollup/pluginutils';
normalizePath('foo\\bar'); // 'foo/bar'
normalizePath('foo/bar'); // 'foo/bar'
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View File

@@ -0,0 +1,340 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
var path = require('path');
var estreeWalker = require('estree-walker');
var pm = require('picomatch');
const addExtension = function addExtension(filename, ext = '.js') {
let result = `${filename}`;
if (!path.extname(filename))
result += ext;
return result;
};
const extractors = {
ArrayPattern(names, param) {
for (const element of param.elements) {
if (element)
extractors[element.type](names, element);
}
},
AssignmentPattern(names, param) {
extractors[param.left.type](names, param.left);
},
Identifier(names, param) {
names.push(param.name);
},
MemberExpression() { },
ObjectPattern(names, param) {
for (const prop of param.properties) {
// @ts-ignore Typescript reports that this is not a valid type
if (prop.type === 'RestElement') {
extractors.RestElement(names, prop);
}
else {
extractors[prop.value.type](names, prop.value);
}
}
},
RestElement(names, param) {
extractors[param.argument.type](names, param.argument);
}
};
const extractAssignedNames = function extractAssignedNames(param) {
const names = [];
extractors[param.type](names, param);
return names;
};
const blockDeclarations = {
const: true,
let: true
};
class Scope {
constructor(options = {}) {
this.parent = options.parent;
this.isBlockScope = !!options.block;
this.declarations = Object.create(null);
if (options.params) {
options.params.forEach((param) => {
extractAssignedNames(param).forEach((name) => {
this.declarations[name] = true;
});
});
}
}
addDeclaration(node, isBlockDeclaration, isVar) {
if (!isBlockDeclaration && this.isBlockScope) {
// it's a `var` or function node, and this
// is a block scope, so we need to go up
this.parent.addDeclaration(node, isBlockDeclaration, isVar);
}
else if (node.id) {
extractAssignedNames(node.id).forEach((name) => {
this.declarations[name] = true;
});
}
}
contains(name) {
return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
}
}
const attachScopes = function attachScopes(ast, propertyName = 'scope') {
let scope = new Scope();
estreeWalker.walk(ast, {
enter(n, parent) {
const node = n;
// function foo () {...}
// class Foo {...}
if (/(Function|Class)Declaration/.test(node.type)) {
scope.addDeclaration(node, false, false);
}
// var foo = 1
if (node.type === 'VariableDeclaration') {
const { kind } = node;
const isBlockDeclaration = blockDeclarations[kind];
node.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
let newScope;
// create new function scope
if (/Function/.test(node.type)) {
const func = node;
newScope = new Scope({
parent: scope,
block: false,
params: func.params
});
// named function expressions - the name is considered
// part of the function's scope
if (func.type === 'FunctionExpression' && func.id) {
newScope.addDeclaration(func, false, false);
}
}
// create new for scope
if (/For(In|Of)?Statement/.test(node.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// create new block scope
if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// catch clause has its own block scope
if (node.type === 'CatchClause') {
newScope = new Scope({
parent: scope,
params: node.param ? [node.param] : [],
block: true
});
}
if (newScope) {
Object.defineProperty(node, propertyName, {
value: newScope,
configurable: true
});
scope = newScope;
}
},
leave(n) {
const node = n;
if (node[propertyName])
scope = scope.parent;
}
});
return scope;
};
// Helper since Typescript can't detect readonly arrays with Array.isArray
function isArray(arg) {
return Array.isArray(arg);
}
function ensureArray(thing) {
if (isArray(thing))
return thing;
if (thing == null)
return [];
return [thing];
}
const normalizePath = function normalizePath(filename) {
return filename.split(path.win32.sep).join(path.posix.sep);
};
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false || path.isAbsolute(id) || id.startsWith('*')) {
return normalizePath(id);
}
// resolve('') is valid and will default to process.cwd()
const basePath = normalizePath(path.resolve(resolutionBase || ''))
// escape all possible (posix + win) path characters that might interfere with regex
.replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
// Note that we use posix.join because:
// 1. the basePath has been normalized to use /
// 2. the incoming glob (id) matcher, also uses /
// otherwise Node will force backslash (\) on windows
return path.posix.join(basePath, normalizePath(id));
}
const createFilter = function createFilter(include, exclude, options) {
const resolutionBase = options && options.resolve;
const getMatcher = (id) => id instanceof RegExp
? id
: {
test: (what) => {
// this refactor is a tad overly verbose but makes for easy debugging
const pattern = getMatcherString(id, resolutionBase);
const fn = pm(pattern, { dot: true });
const result = fn(what);
return result;
}
};
const includeMatchers = ensureArray(include).map(getMatcher);
const excludeMatchers = ensureArray(exclude).map(getMatcher);
return function result(id) {
if (typeof id !== 'string')
return false;
if (/\0/.test(id))
return false;
const pathId = normalizePath(id);
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher.test(pathId))
return true;
}
return !includeMatchers.length;
};
};
const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
forbiddenIdentifiers.add('');
const makeLegalIdentifier = function makeLegalIdentifier(str) {
let identifier = str
.replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
.replace(/[^$_a-zA-Z0-9]/g, '_');
if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
identifier = `_${identifier}`;
}
return identifier || '_';
};
function stringify(obj) {
return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
}
function serializeArray(arr, indent, baseIndent) {
let output = '[';
const separator = indent ? `\n${baseIndent}${indent}` : '';
for (let i = 0; i < arr.length; i++) {
const key = arr[i];
output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}]`;
}
function serializeObject(obj, indent, baseIndent) {
let output = '{';
const separator = indent ? `\n${baseIndent}${indent}` : '';
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) {
const [key, value] = entries[i];
const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}}`;
}
function serialize(obj, indent, baseIndent) {
if (typeof obj === 'object' && obj !== null) {
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
return serializeObject(obj, indent, baseIndent);
}
if (typeof obj === 'number') {
if (obj === Infinity)
return 'Infinity';
if (obj === -Infinity)
return '-Infinity';
if (obj === 0)
return 1 / obj === Infinity ? '0' : '-0';
if (obj !== obj)
return 'NaN'; // eslint-disable-line no-self-compare
}
if (typeof obj === 'symbol') {
const key = Symbol.keyFor(obj);
// eslint-disable-next-line no-undefined
if (key !== undefined)
return `Symbol.for(${stringify(key)})`;
}
if (typeof obj === 'bigint')
return `${obj}n`;
return stringify(obj);
}
const dataToEsm = function dataToEsm(data, options = {}) {
const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
const _ = options.compact ? '' : ' ';
const n = options.compact ? '' : '\n';
const declarationType = options.preferConst ? 'const' : 'var';
if (options.namedExports === false ||
typeof data !== 'object' ||
Array.isArray(data) ||
data instanceof Date ||
data instanceof RegExp ||
data === null) {
const code = serialize(data, options.compact ? null : t, '');
const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
return `export default${magic}${code};`;
}
let namedExportCode = '';
const defaultExportRows = [];
for (const [key, value] of Object.entries(data)) {
if (key === makeLegalIdentifier(key)) {
if (options.objectShorthand)
defaultExportRows.push(key);
else
defaultExportRows.push(`${key}:${_}${key}`);
namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
}
else {
defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
}
}
return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
};
// TODO: remove this in next major
var index = {
addExtension,
attachScopes,
createFilter,
dataToEsm,
extractAssignedNames,
makeLegalIdentifier,
normalizePath
};
exports.addExtension = addExtension;
exports.attachScopes = attachScopes;
exports.createFilter = createFilter;
exports.dataToEsm = dataToEsm;
exports.default = index;
exports.extractAssignedNames = extractAssignedNames;
exports.makeLegalIdentifier = makeLegalIdentifier;
exports.normalizePath = normalizePath;
module.exports = Object.assign(exports.default, exports);
//# sourceMappingURL=index.js.map

View File

@@ -0,0 +1,328 @@
import { extname, win32, posix, isAbsolute, resolve } from 'path';
import { walk } from 'estree-walker';
import pm from 'picomatch';
const addExtension = function addExtension(filename, ext = '.js') {
let result = `${filename}`;
if (!extname(filename))
result += ext;
return result;
};
const extractors = {
ArrayPattern(names, param) {
for (const element of param.elements) {
if (element)
extractors[element.type](names, element);
}
},
AssignmentPattern(names, param) {
extractors[param.left.type](names, param.left);
},
Identifier(names, param) {
names.push(param.name);
},
MemberExpression() { },
ObjectPattern(names, param) {
for (const prop of param.properties) {
// @ts-ignore Typescript reports that this is not a valid type
if (prop.type === 'RestElement') {
extractors.RestElement(names, prop);
}
else {
extractors[prop.value.type](names, prop.value);
}
}
},
RestElement(names, param) {
extractors[param.argument.type](names, param.argument);
}
};
const extractAssignedNames = function extractAssignedNames(param) {
const names = [];
extractors[param.type](names, param);
return names;
};
const blockDeclarations = {
const: true,
let: true
};
class Scope {
constructor(options = {}) {
this.parent = options.parent;
this.isBlockScope = !!options.block;
this.declarations = Object.create(null);
if (options.params) {
options.params.forEach((param) => {
extractAssignedNames(param).forEach((name) => {
this.declarations[name] = true;
});
});
}
}
addDeclaration(node, isBlockDeclaration, isVar) {
if (!isBlockDeclaration && this.isBlockScope) {
// it's a `var` or function node, and this
// is a block scope, so we need to go up
this.parent.addDeclaration(node, isBlockDeclaration, isVar);
}
else if (node.id) {
extractAssignedNames(node.id).forEach((name) => {
this.declarations[name] = true;
});
}
}
contains(name) {
return this.declarations[name] || (this.parent ? this.parent.contains(name) : false);
}
}
const attachScopes = function attachScopes(ast, propertyName = 'scope') {
let scope = new Scope();
walk(ast, {
enter(n, parent) {
const node = n;
// function foo () {...}
// class Foo {...}
if (/(Function|Class)Declaration/.test(node.type)) {
scope.addDeclaration(node, false, false);
}
// var foo = 1
if (node.type === 'VariableDeclaration') {
const { kind } = node;
const isBlockDeclaration = blockDeclarations[kind];
node.declarations.forEach((declaration) => {
scope.addDeclaration(declaration, isBlockDeclaration, true);
});
}
let newScope;
// create new function scope
if (/Function/.test(node.type)) {
const func = node;
newScope = new Scope({
parent: scope,
block: false,
params: func.params
});
// named function expressions - the name is considered
// part of the function's scope
if (func.type === 'FunctionExpression' && func.id) {
newScope.addDeclaration(func, false, false);
}
}
// create new for scope
if (/For(In|Of)?Statement/.test(node.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// create new block scope
if (node.type === 'BlockStatement' && !/Function/.test(parent.type)) {
newScope = new Scope({
parent: scope,
block: true
});
}
// catch clause has its own block scope
if (node.type === 'CatchClause') {
newScope = new Scope({
parent: scope,
params: node.param ? [node.param] : [],
block: true
});
}
if (newScope) {
Object.defineProperty(node, propertyName, {
value: newScope,
configurable: true
});
scope = newScope;
}
},
leave(n) {
const node = n;
if (node[propertyName])
scope = scope.parent;
}
});
return scope;
};
// Helper since Typescript can't detect readonly arrays with Array.isArray
function isArray(arg) {
return Array.isArray(arg);
}
function ensureArray(thing) {
if (isArray(thing))
return thing;
if (thing == null)
return [];
return [thing];
}
const normalizePath = function normalizePath(filename) {
return filename.split(win32.sep).join(posix.sep);
};
function getMatcherString(id, resolutionBase) {
if (resolutionBase === false || isAbsolute(id) || id.startsWith('*')) {
return normalizePath(id);
}
// resolve('') is valid and will default to process.cwd()
const basePath = normalizePath(resolve(resolutionBase || ''))
// escape all possible (posix + win) path characters that might interfere with regex
.replace(/[-^$*+?.()|[\]{}]/g, '\\$&');
// Note that we use posix.join because:
// 1. the basePath has been normalized to use /
// 2. the incoming glob (id) matcher, also uses /
// otherwise Node will force backslash (\) on windows
return posix.join(basePath, normalizePath(id));
}
const createFilter = function createFilter(include, exclude, options) {
const resolutionBase = options && options.resolve;
const getMatcher = (id) => id instanceof RegExp
? id
: {
test: (what) => {
// this refactor is a tad overly verbose but makes for easy debugging
const pattern = getMatcherString(id, resolutionBase);
const fn = pm(pattern, { dot: true });
const result = fn(what);
return result;
}
};
const includeMatchers = ensureArray(include).map(getMatcher);
const excludeMatchers = ensureArray(exclude).map(getMatcher);
return function result(id) {
if (typeof id !== 'string')
return false;
if (/\0/.test(id))
return false;
const pathId = normalizePath(id);
for (let i = 0; i < excludeMatchers.length; ++i) {
const matcher = excludeMatchers[i];
if (matcher.test(pathId))
return false;
}
for (let i = 0; i < includeMatchers.length; ++i) {
const matcher = includeMatchers[i];
if (matcher.test(pathId))
return true;
}
return !includeMatchers.length;
};
};
const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
const builtins = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
const forbiddenIdentifiers = new Set(`${reservedWords} ${builtins}`.split(' '));
forbiddenIdentifiers.add('');
const makeLegalIdentifier = function makeLegalIdentifier(str) {
let identifier = str
.replace(/-(\w)/g, (_, letter) => letter.toUpperCase())
.replace(/[^$_a-zA-Z0-9]/g, '_');
if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
identifier = `_${identifier}`;
}
return identifier || '_';
};
function stringify(obj) {
return (JSON.stringify(obj) || 'undefined').replace(/[\u2028\u2029]/g, (char) => `\\u${`000${char.charCodeAt(0).toString(16)}`.slice(-4)}`);
}
function serializeArray(arr, indent, baseIndent) {
let output = '[';
const separator = indent ? `\n${baseIndent}${indent}` : '';
for (let i = 0; i < arr.length; i++) {
const key = arr[i];
output += `${i > 0 ? ',' : ''}${separator}${serialize(key, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}]`;
}
function serializeObject(obj, indent, baseIndent) {
let output = '{';
const separator = indent ? `\n${baseIndent}${indent}` : '';
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) {
const [key, value] = entries[i];
const stringKey = makeLegalIdentifier(key) === key ? key : stringify(key);
output += `${i > 0 ? ',' : ''}${separator}${stringKey}:${indent ? ' ' : ''}${serialize(value, indent, baseIndent + indent)}`;
}
return `${output}${indent ? `\n${baseIndent}` : ''}}`;
}
function serialize(obj, indent, baseIndent) {
if (typeof obj === 'object' && obj !== null) {
if (Array.isArray(obj))
return serializeArray(obj, indent, baseIndent);
if (obj instanceof Date)
return `new Date(${obj.getTime()})`;
if (obj instanceof RegExp)
return obj.toString();
return serializeObject(obj, indent, baseIndent);
}
if (typeof obj === 'number') {
if (obj === Infinity)
return 'Infinity';
if (obj === -Infinity)
return '-Infinity';
if (obj === 0)
return 1 / obj === Infinity ? '0' : '-0';
if (obj !== obj)
return 'NaN'; // eslint-disable-line no-self-compare
}
if (typeof obj === 'symbol') {
const key = Symbol.keyFor(obj);
// eslint-disable-next-line no-undefined
if (key !== undefined)
return `Symbol.for(${stringify(key)})`;
}
if (typeof obj === 'bigint')
return `${obj}n`;
return stringify(obj);
}
const dataToEsm = function dataToEsm(data, options = {}) {
const t = options.compact ? '' : 'indent' in options ? options.indent : '\t';
const _ = options.compact ? '' : ' ';
const n = options.compact ? '' : '\n';
const declarationType = options.preferConst ? 'const' : 'var';
if (options.namedExports === false ||
typeof data !== 'object' ||
Array.isArray(data) ||
data instanceof Date ||
data instanceof RegExp ||
data === null) {
const code = serialize(data, options.compact ? null : t, '');
const magic = _ || (/^[{[\-\/]/.test(code) ? '' : ' '); // eslint-disable-line no-useless-escape
return `export default${magic}${code};`;
}
let namedExportCode = '';
const defaultExportRows = [];
for (const [key, value] of Object.entries(data)) {
if (key === makeLegalIdentifier(key)) {
if (options.objectShorthand)
defaultExportRows.push(key);
else
defaultExportRows.push(`${key}:${_}${key}`);
namedExportCode += `export ${declarationType} ${key}${_}=${_}${serialize(value, options.compact ? null : t, '')};${n}`;
}
else {
defaultExportRows.push(`${stringify(key)}:${_}${serialize(value, options.compact ? null : t, '')}`);
}
}
return `${namedExportCode}export default${_}{${n}${t}${defaultExportRows.join(`,${n}${t}`)}${n}};${n}`;
};
// TODO: remove this in next major
var index = {
addExtension,
attachScopes,
createFilter,
dataToEsm,
extractAssignedNames,
makeLegalIdentifier,
normalizePath
};
export { addExtension, attachScopes, createFilter, dataToEsm, index as default, extractAssignedNames, makeLegalIdentifier, normalizePath };
//# sourceMappingURL=index.js.map

View File

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

View File

@@ -0,0 +1,100 @@
{
"name": "@rollup/pluginutils",
"version": "5.0.2",
"publishConfig": {
"access": "public"
},
"description": "A set of utility functions commonly used by Rollup plugins",
"license": "MIT",
"repository": {
"url": "rollup/plugins",
"directory": "packages/pluginutils"
},
"author": "Rich Harris <richard.a.harris@gmail.com>",
"homepage": "https://github.com/rollup/plugins/tree/master/packages/pluginutils#readme",
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"main": "./dist/cjs/index.js",
"module": "./dist/es/index.js",
"type": "commonjs",
"exports": {
"types": "./types/index.d.ts",
"import": "./dist/es/index.js",
"default": "./dist/cjs/index.js"
},
"engines": {
"node": ">=14.0.0"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm build && pnpm lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm test -- --verbose",
"prebuild": "del-cli dist",
"prepare": "if [ ! -d 'dist' ]; then pnpm build; fi",
"prerelease": "pnpm build",
"pretest": "pnpm build --sourcemap",
"release": "pnpm --workspace-root plugin:release --pkg $npm_package_name",
"test": "ava",
"test:ts": "tsc --noEmit"
},
"files": [
"dist",
"!dist/**/*.map",
"types",
"README.md",
"LICENSE"
],
"keywords": [
"rollup",
"plugin",
"utils"
],
"peerDependencies": {
"rollup": "^1.20.0||^2.0.0||^3.0.0"
},
"peerDependenciesMeta": {
"rollup": {
"optional": true
}
},
"dependencies": {
"@types/estree": "^1.0.0",
"estree-walker": "^2.0.2",
"picomatch": "^2.3.1"
},
"devDependencies": {
"@rollup/plugin-commonjs": "^23.0.0",
"@rollup/plugin-node-resolve": "^15.0.0",
"@rollup/plugin-typescript": "^9.0.1",
"@types/node": "^14.18.30",
"@types/picomatch": "^2.3.0",
"acorn": "^8.8.0",
"rollup": "^3.2.3",
"typescript": "^4.8.3"
},
"types": "./types/index.d.ts",
"ava": {
"extensions": [
"ts"
],
"require": [
"ts-node/register"
],
"workerThreads": false,
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"nyc": {
"extension": [
".js",
".ts"
]
}
}

View File

@@ -0,0 +1,92 @@
import { BaseNode } from 'estree';
export interface AttachedScope {
parent?: AttachedScope;
isBlockScope: boolean;
declarations: { [key: string]: boolean };
addDeclaration(node: BaseNode, isBlockDeclaration: boolean, isVar: boolean): void;
contains(name: string): boolean;
}
export interface DataToEsmOptions {
compact?: boolean;
indent?: string;
namedExports?: boolean;
objectShorthand?: boolean;
preferConst?: boolean;
}
/**
* A valid `picomatch` glob pattern, or array of patterns.
*/
export type FilterPattern = ReadonlyArray<string | RegExp> | string | RegExp | null;
/**
* Adds an extension to a module ID if one does not exist.
*/
export function addExtension(filename: string, ext?: string): string;
/**
* Attaches `Scope` objects to the relevant nodes of an AST.
* Each `Scope` object has a `scope.contains(name)` method that returns `true`
* if a given name is defined in the current scope or a parent scope.
*/
export function attachScopes(ast: BaseNode, propertyName?: string): AttachedScope;
/**
* Constructs a filter function which can be used to determine whether or not
* certain modules should be operated upon.
* @param include If `include` is omitted or has zero length, filter will return `true` by default.
* @param exclude ID must not match any of the `exclude` patterns.
* @param options Optionally resolves the patterns against a directory other than `process.cwd()`.
* If a `string` is specified, then the value will be used as the base directory.
* Relative paths will be resolved against `process.cwd()` first.
* If `false`, then the patterns will not be resolved against any directory.
* This can be useful if you want to create a filter for virtual module names.
*/
export function createFilter(
include?: FilterPattern,
exclude?: FilterPattern,
options?: { resolve?: string | false | null }
): (id: string | unknown) => boolean;
/**
* Transforms objects into tree-shakable ES Module imports.
* @param data An object to transform into an ES module.
*/
export function dataToEsm(data: unknown, options?: DataToEsmOptions): string;
/**
* Extracts the names of all assignment targets based upon specified patterns.
* @param param An `acorn` AST Node.
*/
export function extractAssignedNames(param: BaseNode): string[];
/**
* Constructs a bundle-safe identifier from a `string`.
*/
export function makeLegalIdentifier(str: string): string;
/**
* Converts path separators to forward slash.
*/
export function normalizePath(filename: string): string;
export type AddExtension = typeof addExtension;
export type AttachScopes = typeof attachScopes;
export type CreateFilter = typeof createFilter;
export type ExtractAssignedNames = typeof extractAssignedNames;
export type MakeLegalIdentifier = typeof makeLegalIdentifier;
export type NormalizePath = typeof normalizePath;
export type DataToEsm = typeof dataToEsm;
declare const defaultExport: {
addExtension: AddExtension;
attachScopes: AttachScopes;
createFilter: CreateFilter;
dataToEsm: DataToEsm;
extractAssignedNames: ExtractAssignedNames;
makeLegalIdentifier: MakeLegalIdentifier;
normalizePath: NormalizePath;
};
export default defaultExport;

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,46 @@
{
"name": "brace-expansion",
"description": "Brace expansion as known from sh/bash",
"version": "2.0.1",
"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"
]
}
}

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,459 @@
# 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')
// default export also works
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 `Minipass.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 adjascent `**` 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,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,42 @@
declare const _default: {
(p: string, pattern: string, options?: import("./index.js").MinimatchOptions): boolean;
sep: "\\" | "/";
GLOBSTAR: typeof import("./index.js").GLOBSTAR;
filter: (pattern: string, options?: import("./index.js").MinimatchOptions) => (p: string) => boolean;
defaults: (def: import("./index.js").MinimatchOptions) => any;
braceExpand: (pattern: string, options?: import("./index.js").MinimatchOptions) => string[];
makeRe: (pattern: string, options?: import("./index.js").MinimatchOptions) => false | import("./index.js").MMRegExp;
match: (list: string[], pattern: string, options?: import("./index.js").MinimatchOptions) => string[];
Minimatch: typeof import("./index.js").Minimatch;
escape: (s: string, { windowsPathsNoEscape, }?: Pick<import("./index.js").MinimatchOptions, "windowsPathsNoEscape">) => string;
unescape: (s: string, { windowsPathsNoEscape, }?: Pick<import("./index.js").MinimatchOptions, "windowsPathsNoEscape">) => string;
} & {
default: {
(p: string, pattern: string, options?: import("./index.js").MinimatchOptions): boolean;
sep: "\\" | "/";
GLOBSTAR: typeof import("./index.js").GLOBSTAR;
filter: (pattern: string, options?: import("./index.js").MinimatchOptions) => (p: string) => boolean;
defaults: (def: import("./index.js").MinimatchOptions) => any;
braceExpand: (pattern: string, options?: import("./index.js").MinimatchOptions) => string[];
makeRe: (pattern: string, options?: import("./index.js").MinimatchOptions) => false | import("./index.js").MMRegExp;
match: (list: string[], pattern: string, options?: import("./index.js").MinimatchOptions) => string[];
Minimatch: typeof import("./index.js").Minimatch;
escape: (s: string, { windowsPathsNoEscape, }?: Pick<import("./index.js").MinimatchOptions, "windowsPathsNoEscape">) => string;
unescape: (s: string, { windowsPathsNoEscape, }?: Pick<import("./index.js").MinimatchOptions, "windowsPathsNoEscape">) => string;
};
minimatch: {
(p: string, pattern: string, options?: import("./index.js").MinimatchOptions): boolean;
sep: "\\" | "/";
GLOBSTAR: typeof import("./index.js").GLOBSTAR;
filter: (pattern: string, options?: import("./index.js").MinimatchOptions) => (p: string) => boolean;
defaults: (def: import("./index.js").MinimatchOptions) => any;
braceExpand: (pattern: string, options?: import("./index.js").MinimatchOptions) => string[];
makeRe: (pattern: string, options?: import("./index.js").MinimatchOptions) => false | import("./index.js").MMRegExp;
match: (list: string[], pattern: string, options?: import("./index.js").MinimatchOptions) => string[];
Minimatch: typeof import("./index.js").Minimatch;
escape: (s: string, { windowsPathsNoEscape, }?: Pick<import("./index.js").MinimatchOptions, "windowsPathsNoEscape">) => string;
unescape: (s: string, { windowsPathsNoEscape, }?: Pick<import("./index.js").MinimatchOptions, "windowsPathsNoEscape">) => string;
};
};
export = _default;
//# sourceMappingURL=index-cjs.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index-cjs.d.ts","sourceRoot":"","sources":["../../src/index-cjs.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,kBAAoE"}

View File

@@ -0,0 +1,7 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
const index_js_1 = __importDefault(require("./index.js"));
module.exports = Object.assign(index_js_1.default, { default: index_js_1.default, minimatch: index_js_1.default });
//# sourceMappingURL=index-cjs.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index-cjs.js","sourceRoot":"","sources":["../../src/index-cjs.ts"],"names":[],"mappings":";;;;AAAA,0DAAkC;AAElC,iBAAS,MAAM,CAAC,MAAM,CAAC,kBAAS,EAAE,EAAE,OAAO,EAAE,kBAAS,EAAE,SAAS,EAAT,kBAAS,EAAE,CAAC,CAAA","sourcesContent":["import minimatch from './index.js'\n\nexport = Object.assign(minimatch, { default: minimatch, minimatch })\n"]}

View File

@@ -0,0 +1,93 @@
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[];
Minimatch: typeof Minimatch;
escape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
unescape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
};
export default minimatch;
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;
};
type SubparseReturn = [string, boolean];
type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
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 | SubparseReturn;
makeRe(): false | MMRegExp;
slashSplit(p: string): string[];
match(f: string, partial?: boolean): boolean;
static defaults(def: MinimatchOptions): typeof Minimatch;
}
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":"AAKA,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;;;sBA+Hf,MAAM,YAAW,gBAAgB,SACvC,MAAM;oBAOkB,gBAAgB,KAAG,gBAAgB;2BA6DtD,MAAM,YACN,gBAAgB;sBAwCK,MAAM,YAAW,gBAAgB;kBAKzD,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB;;;;CA1O1B,CAAA;AAED,eAAe,SAAS,CAAA;AA+DxB,KAAK,GAAG,GAAG,IAAI,GAAG,GAAG,CAAA;AAOrB,eAAO,MAAM,GAAG,KAAgE,CAAA;AAGhF,eAAO,MAAM,QAAQ,eAAwB,CAAA;AAyC7C,eAAO,MAAM,MAAM,YACP,MAAM,YAAW,gBAAgB,SACvC,MAAM,YACsB,CAAA;AAMlC,eAAO,MAAM,QAAQ,QAAS,gBAAgB,KAAG,gBA+ChD,CAAA;AAaD,eAAO,MAAM,WAAW,YACb,MAAM,YACN,gBAAgB,aAY1B,CAAA;AA4BD,eAAO,MAAM,MAAM,YAAa,MAAM,YAAW,gBAAgB,qBACvB,CAAA;AAG1C,eAAO,MAAM,KAAK,SACV,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB,aAQ1B,CAAA;AAoBD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAED,KAAK,cAAc,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AACvC,KAAK,mBAAmB,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,QAAQ,CAAA;AAC9D,KAAK,WAAW,GAAG,mBAAmB,GAAG,KAAK,CAAA;AAE9C,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;IA6BhC,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;IAgBxD,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;IAkNzE,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,GAAG,cAAc;IAgXpD,MAAM;IAgFN,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,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,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,93 @@
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[];
Minimatch: typeof Minimatch;
escape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
unescape: (s: string, { windowsPathsNoEscape, }?: Pick<MinimatchOptions, "windowsPathsNoEscape">) => string;
};
export default minimatch;
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;
};
type SubparseReturn = [string, boolean];
type ParseReturnFiltered = string | MMRegExp | typeof GLOBSTAR;
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 | SubparseReturn;
makeRe(): false | MMRegExp;
slashSplit(p: string): string[];
match(f: string, partial?: boolean): boolean;
static defaults(def: MinimatchOptions): typeof Minimatch;
}
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":"AAKA,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;;;sBA+Hf,MAAM,YAAW,gBAAgB,SACvC,MAAM;oBAOkB,gBAAgB,KAAG,gBAAgB;2BA6DtD,MAAM,YACN,gBAAgB;sBAwCK,MAAM,YAAW,gBAAgB;kBAKzD,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB;;;;CA1O1B,CAAA;AAED,eAAe,SAAS,CAAA;AA+DxB,KAAK,GAAG,GAAG,IAAI,GAAG,GAAG,CAAA;AAOrB,eAAO,MAAM,GAAG,KAAgE,CAAA;AAGhF,eAAO,MAAM,QAAQ,eAAwB,CAAA;AAyC7C,eAAO,MAAM,MAAM,YACP,MAAM,YAAW,gBAAgB,SACvC,MAAM,YACsB,CAAA;AAMlC,eAAO,MAAM,QAAQ,QAAS,gBAAgB,KAAG,gBA+ChD,CAAA;AAaD,eAAO,MAAM,WAAW,YACb,MAAM,YACN,gBAAgB,aAY1B,CAAA;AA4BD,eAAO,MAAM,MAAM,YAAa,MAAM,YAAW,gBAAgB,qBACvB,CAAA;AAG1C,eAAO,MAAM,KAAK,SACV,MAAM,EAAE,WACL,MAAM,YACN,gBAAgB,aAQ1B,CAAA;AAoBD,MAAM,MAAM,QAAQ,GAAG,MAAM,GAAG;IAC9B,IAAI,CAAC,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AAED,KAAK,cAAc,GAAG,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;AACvC,KAAK,mBAAmB,GAAG,MAAM,GAAG,QAAQ,GAAG,OAAO,QAAQ,CAAA;AAC9D,KAAK,WAAW,GAAG,mBAAmB,GAAG,KAAK,CAAA;AAE9C,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;IA6BhC,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;IAgBxD,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;IAkNzE,WAAW;IAIX,KAAK,CAAC,OAAO,EAAE,MAAM,GAAG,WAAW,GAAG,cAAc;IAgXpD,MAAM;IAgFN,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,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"]}

View File

@@ -0,0 +1,89 @@
{
"author": "Isaac Z. Schlueter <i@izs.me> (http://blog.izs.me)",
"name": "minimatch",
"description": "a glob matcher in javascript",
"version": "7.4.6",
"publishConfig": {
"tag": "legacy-v7"
},
"repository": {
"type": "git",
"url": "git://github.com/isaacs/minimatch.git"
},
"main": "./dist/cjs/index-cjs.js",
"module": "./dist/mjs/index.js",
"types": "./dist/cjs/index.d.ts",
"exports": {
".": {
"import": {
"types": "./dist/mjs/index.d.ts",
"default": "./dist/mjs/index.js"
},
"require": {
"types": "./dist/cjs/index.d.ts",
"default": "./dist/cjs/index-cjs.js"
}
}
},
"files": [
"dist"
],
"scripts": {
"preversion": "npm test",
"postversion": "npm publish",
"prepublishOnly": "git push origin --follow-tags",
"preprepare": "rm -rf dist",
"prepare": "tsc -p tsconfig.json && tsc -p tsconfig-esm.json",
"postprepare": "bash fixup.sh",
"pretest": "npm run prepare",
"presnap": "npm run prepare",
"test": "c8 tap",
"snap": "c8 tap",
"format": "prettier --write . --loglevel warn",
"benchmark": "node benchmark/index.js",
"typedoc": "typedoc --tsconfig tsconfig-esm.json ./src/*.ts"
},
"prettier": {
"semi": false,
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"singleQuote": true,
"jsxSingleQuote": false,
"bracketSameLine": true,
"arrowParens": "avoid",
"endOfLine": "lf"
},
"engines": {
"node": ">=10"
},
"dependencies": {
"brace-expansion": "^2.0.1"
},
"devDependencies": {
"@types/brace-expansion": "^1.1.0",
"@types/node": "^18.11.9",
"@types/tap": "^15.0.7",
"c8": "^7.12.0",
"eslint-config-prettier": "^8.6.0",
"mkdirp": "1",
"prettier": "^2.8.2",
"tap": "^16.3.3",
"ts-node": "^10.9.1",
"typedoc": "^0.23.21",
"typescript": "^4.9.3"
},
"tap": {
"coverage": false,
"node-arg": [
"--no-warnings",
"--loader",
"ts-node/esm"
],
"ts": false
},
"funding": {
"url": "https://github.com/sponsors/isaacs"
},
"license": "ISC"
}

View File

@@ -0,0 +1,134 @@
{
"name": "unplugin-vue-components",
"version": "0.24.1",
"packageManager": "pnpm@7.29.0",
"description": "Components auto importing for Vue",
"author": "antfu <anthonyfu117@hotmail.com>",
"license": "MIT",
"funding": "https://github.com/sponsors/antfu",
"homepage": "https://github.com/antfu/unplugin-vue-components",
"repository": {
"type": "git",
"url": "https://github.com/antfu/unplugin-vue-components"
},
"bugs": "https://github.com/antfu/unplugin-vue-components/issues",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
},
"./nuxt": {
"types": "./dist/nuxt.d.ts",
"require": "./dist/nuxt.js",
"import": "./dist/nuxt.mjs"
},
"./resolvers": {
"types": "./dist/resolvers.d.ts",
"require": "./dist/resolvers.js",
"import": "./dist/resolvers.mjs"
},
"./rollup": {
"types": "./dist/rollup.d.ts",
"require": "./dist/rollup.js",
"import": "./dist/rollup.mjs"
},
"./types": {
"types": "./dist/types.d.ts",
"require": "./dist/types.js",
"import": "./dist/types.mjs"
},
"./vite": {
"types": "./dist/vite.d.ts",
"require": "./dist/vite.js",
"import": "./dist/vite.mjs"
},
"./webpack": {
"types": "./dist/webpack.d.ts",
"require": "./dist/webpack.js",
"import": "./dist/webpack.mjs"
},
"./esbuild": {
"types": "./dist/esbuild.d.ts",
"require": "./dist/esbuild.js",
"import": "./dist/esbuild.mjs"
},
"./*": "./*"
},
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "index.d.ts",
"typesVersions": {
"*": {
"*": [
"./dist/*"
]
}
},
"files": [
"dist"
],
"engines": {
"node": ">=14"
},
"scripts": {
"build": "tsup && esno scripts/postbuild.ts",
"dev": "tsup --watch src",
"example:build": "npm -C examples/vite-vue3 run build",
"example:dev": "npm -C examples/vite-vue3 run dev",
"prepublishOnly": "npm run build",
"lint": "eslint .",
"release": "bumpp && npm publish",
"test": "vitest",
"test:update": "vitest --u"
},
"peerDependencies": {
"@babel/parser": "^7.15.8",
"vue": "2 || 3",
"@nuxt/kit": "^3.2.2"
},
"peerDependenciesMeta": {
"@babel/parser": {
"optional": true
},
"@nuxt/kit": {
"optional": true
}
},
"dependencies": {
"@antfu/utils": "^0.7.2",
"@rollup/pluginutils": "^5.0.2",
"chokidar": "^3.5.3",
"debug": "^4.3.4",
"fast-glob": "^3.2.12",
"local-pkg": "^0.4.3",
"magic-string": "^0.30.0",
"minimatch": "^7.4.2",
"resolve": "^1.22.1",
"unplugin": "^1.1.0"
},
"devDependencies": {
"@antfu/eslint-config": "^0.36.0",
"@babel/parser": "^7.21.2",
"@babel/types": "^7.21.2",
"@nuxt/kit": "^3.2.3",
"@types/debug": "^4.1.7",
"@types/minimatch": "^5.1.2",
"@types/node": "^18.14.6",
"@types/resolve": "^1.20.2",
"@typescript-eslint/eslint-plugin": "^5.54.1",
"bumpp": "^9.0.0",
"compare-versions": "^5.0.3",
"element-plus": "^2.2.34",
"eslint": "^8.35.0",
"esno": "^0.16.3",
"estree-walker": "^3.0.3",
"pathe": "^1.1.0",
"rollup": "^3.18.0",
"tsup": "^6.6.3",
"typescript": "^4.9.5",
"vite": "^4.1.4",
"vitest": "^0.29.2",
"vue": "3.2.45"
}
}