前端 uni-app 重写: 9页面 H5

This commit is contained in:
zhiqui
2026-11-15 15:09:37 +08:00
parent 513b53672e
commit ea7c2529e9
24104 changed files with 3667749 additions and 0 deletions
+202
View File
@@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+18
View File
@@ -0,0 +1,18 @@
# @dcloudio/vite-plugin-uni
## Install
```shell
npm i @dcloudio/vite-plugin-uni
```
## Useage
```ts
import { defineConfig } from "vite";
import uni from "@dcloudio/vite-plugin-uni";
export default defineConfig({
plugins: [uni()],
});
```
+111
View File
@@ -0,0 +1,111 @@
#!/usr/bin/env node
// 尽可能提前加载 alias
require('@dcloudio/uni-cli-shared/dist/alias')
// 尽可能提前加载 polyfill
require('@dcloudio/uni-cli-shared/dist/polyfill')
// 暂时忽略 cjs 警告
process.env.VITE_CJS_IGNORE_WARNING = true
const { performance } = require('perf_hooks')
global.__vite_start_time = performance.now()
const debugIndex = process.argv.findIndex((arg) => /^(?:-d|--debug)$/.test(arg))
const filterIndex = process.argv.findIndex((arg) =>
/^(?:-f|--filter)$/.test(arg)
)
if (debugIndex > 0) {
let value = process.argv[debugIndex + 1]
if (!value || value.startsWith('-')) {
value = 'vite:*,uni:*'
}
process.env.DEBUG = value
if (filterIndex > 0) {
const filter = process.argv[filterIndex + 1]
if (filter && !filter.startsWith('-')) {
process.env.VITE_DEBUG_FILTER = filter
}
}
}
// uni-cli-shared 引入了 @vue/compiler-core,需要提前设置NODE_ENV,才能保证 @vue/compiler-core 加载的是对应环境的代码
if (
process.argv[2] === 'build' &&
!process.argv.some((arg) => /^(?:-w|--watch)$/.test(arg))
) {
if (process.env.UNI_COMPILE_TARGET === 'uni_modules') {
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'production'
}
} else {
process.env.NODE_ENV = 'production'
}
}
// 临时逻辑
if (process.env.UNI_INPUT_DIR) {
const fs = require('fs')
const path = require('path')
const tscFile = path.resolve(process.env.UNI_INPUT_DIR, 'TSC')
if (fs.existsSync(tscFile)) {
const debugFileStat = fs.statSync(tscFile)
if (debugFileStat.isFile()) {
process.env.UNI_APP_X_TSC = 'true'
}
}
}
function initDebug() {
if (!process.env.DEBUG && process.env.UNI_INPUT_DIR) {
const fs = require('fs')
const path = require('path')
const debugFile = path.resolve(process.env.UNI_INPUT_DIR, 'DEBUG')
if (fs.existsSync(debugFile)) {
const debugFileStat = fs.statSync(debugFile)
if (debugFileStat.isFile()) {
process.env.DEBUG = fs.readFileSync(debugFile, 'utf8').trim()
}
}
}
if (process.env.DEBUG) {
const debug = require('debug')
const mod = require('module')
const { PerformanceObserver } = require('perf_hooks')
const debugRequire = debug('uni:require')
// Monkey patch the require function
mod.Module.prototype.require = performance.timerify(
mod.Module.prototype.require
)
require = performance.timerify(require)
// Activate the observer
const obs = new PerformanceObserver((list) => {
const entries = list.getEntries()
entries.sort((a, b) => b.duration - a.duration).filter(e => e.duration > 20).forEach((entry) => {
debugRequire(entry[0], entry.duration)
})
obs.disconnect()
})
obs.observe({
entryTypes: ['function'],
buffered: true,
})
if (process.env.DEBUG === "*") {
const inspector = require('inspector')
const session = (global.__vite_profile_session = new inspector.Session())
session.connect()
session.post('Profiler.enable', () => {
session.post('Profiler.start', () => {
require('../dist/cli/index.js')
})
})
}
}
}
initDebug()
if (!global.__vite_profile_session) {
require('../dist/cli/index.js')
}
@@ -0,0 +1,5 @@
import { type BuildOptions, type ServerOptions } from 'vite';
import type { CliOptions } from '.';
export declare function runDev(options: CliOptions & ServerOptions): Promise<undefined>;
export declare function runBuild(options: CliOptions & BuildOptions): Promise<void>;
export declare const stopProfiler: (log: (message: string) => void) => void | Promise<void>;
+288
View File
@@ -0,0 +1,288 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.stopProfiler = exports.runBuild = exports.runDev = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const shared_1 = require("@vue/shared");
const vite_1 = require("vite");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const build_1 = require("./build");
const server_1 = require("./server");
const utils_1 = require("./utils");
const easycom_1 = require("../utils/easycom");
const uvue_1 = require("./uvue");
const configResolved_1 = require("../configResolved");
async function runDev(options) {
var _a;
if (process.platform === 'win32') {
// Windows 上 Chokidar 的原生监听可能占用被监听的目录,导致目录重命名失败。
// 升级 Chokidar v6 可以解决该问题,但 Vite 内置了 Chokidar,暂以环境变量启用轮询,减少改动。
// 轮询会增加文件系统访问和 CPU 开销,监听的文件越多,开销可能越大。
// 外部已设置该环境变量时,保留其值。
(_a = process.env).CHOKIDAR_USEPOLLING ?? (_a.CHOKIDAR_USEPOLLING = '1');
}
(0, shared_1.extend)(options, {
watch: {},
});
if (process.env.UNI_MINIMIZE === 'true') {
;
options.minify = true;
}
(0, utils_1.initEnv)('dev', options);
if ((0, uni_cli_shared_1.isUniAppXAndroidNative)()) {
return (0, uvue_1.runUVueAndroidDev)(options);
}
const createLogger = await Promise.resolve().then(() => __importStar(require('vite'))).then(({ createLogger }) => createLogger);
try {
if (options.platform === 'h5') {
const server = await (options.ssr
? (0, server_1.createSSRServer)(options)
: (0, server_1.createServer)(options));
(0, easycom_1.initEasycom)(server.watcher);
}
else {
(0, easycom_1.initEasycom)();
let isFirstStart = true;
let isFirstEnd = true;
await (0, build_1.build)(options, async (event) => {
if (event.code === 'BUNDLE_START') {
if (isFirstStart) {
isFirstStart = false;
return;
}
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.start']);
}
else if (event.code === 'BUNDLE_END') {
event.result.close();
if (isFirstEnd) {
// 首次全量同步
if (options.platform === 'app' ||
options.platform === 'app-harmony' ||
options.platform === 'mp-harmony') {
process.env.UNI_APP_CHANGED_FILES = '';
process.env.UNI_APP_UTS_CHANGED = '';
}
if (options.platform === 'app') {
process.env.UNI_APP_CHANGED_PAGES = '';
process.env.UNI_APP_UTS_CHANGED_FILES = '';
}
isFirstEnd = false;
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
(0, utils_1.showRunPrompt)(options.platform);
(0, utils_1.printStartupDuration)(createLogger(options.logLevel), false);
if (process.env.UNI_UTS_ERRORS) {
console.error(process.env.UNI_UTS_ERRORS);
}
if (process.env.UNI_UTS_TIPS) {
console.warn(process.env.UNI_UTS_TIPS);
}
await (0, exports.stopProfiler)((message) => createLogger(options.logLevel).info(message));
return;
}
const utsChanged = process.env.UNI_APP_UTS_CHANGED === 'true';
process.env.UNI_APP_UTS_CHANGED = '';
const pagesJsonChanged = process.env.UNI_APP_X_DOM2_PAGES_JSON_CHANGED === 'true';
process.env.UNI_APP_X_DOM2_PAGES_JSON_CHANGED = '';
let changedFiles = '';
let hasBinFiles = false;
if (options.platform === 'app') {
const files = process.env.UNI_APP_CHANGED_FILES;
const pages = process.env.UNI_APP_CHANGED_PAGES;
const dex = process.env.UNI_APP_UTS_CHANGED_FILES;
hasBinFiles = getHasBinFiles();
changedFiles = pages || files;
process.env.UNI_APP_CHANGED_PAGES = '';
process.env.UNI_APP_CHANGED_FILES = '';
process.env.UNI_APP_UTS_CHANGED_FILES = '';
if (process.env.UNI_APP_X_DOM2_DYNAMIC === 'true') {
process.env.UNI_APP_X_DOM2_BIN_CHANGED_FILES = '';
}
const hasIncrementalFiles = changedFiles &&
!changedFiles.includes(uni_cli_shared_1.APP_CONFIG_SERVICE) &&
!changedFiles.includes(uni_cli_shared_1.APP_SERVICE_FILENAME);
if (
// 目前动态渲染下,只要bin有变更,就需要全量同步,后续可以优化成bin变更时输出bin变更文件列表
!hasBinFiles &&
!pagesJsonChanged &&
(hasIncrementalFiles || dex)) {
if (pages) {
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.pages'].replace('{pages}', changedFiles));
}
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.files'].replace('{files}', JSON.stringify(JSON.parse(changedFiles || JSON.stringify([])).concat(JSON.parse(dex || JSON.stringify([]))))));
}
}
else if (options.platform === 'app-harmony' ||
options.platform === 'mp-harmony') {
hasBinFiles = getHasBinFiles();
// 动态化且没有uts插件变更时,输出变更文件列表
if (process.env.UNI_APP_X_DOM2_DYNAMIC === 'true' &&
!utsChanged &&
!hasBinFiles) {
const changed = [];
const files = process.env.UNI_APP_CHANGED_FILES;
process.env.UNI_APP_CHANGED_PAGES = '';
if (files) {
try {
changed.push(...JSON.parse(files));
}
catch { }
}
// 鸿蒙平台暂不启用 bin 文件热更新,先不合并到 changes 中。
// const binFiles = process.env.UNI_APP_X_DOM2_BIN_CHANGED_FILES
process.env.UNI_APP_X_DOM2_BIN_CHANGED_FILES = '';
// if (binFiles) {
// try {
// changed.push(...JSON.parse(binFiles))
// } catch {}
// }
if (!pagesJsonChanged && changed.length) {
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.files'].replace('{files}', JSON.stringify(changed)));
}
}
// 鸿蒙平台cpp/uts插件变更需要整体编译
if (process.env.UNI_APP_X_DOM2_CPP_CHANGED !== 'true' &&
!utsChanged &&
!hasBinFiles) {
const files = process.env.UNI_APP_CHANGED_FILES;
process.env.UNI_APP_CHANGED_FILES = '';
if (!pagesJsonChanged && files) {
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.files'].replace('{files}', files));
}
}
}
// dom2 下仅 cpp/uts插件 变更需要整体编译
// 如果有changedFiles就增量输出,否则就不要输出,而是打印无变更,静态资源走额外的全量同步
// 之前之所以没有增量就全量同步,是为了兼容性,怕出意外。
if (process.env.UNI_APP_X_DOM2 === 'true') {
if (process.env.UNI_APP_X_DOM2_CPP_CHANGED === 'true' ||
utsChanged ||
pagesJsonChanged) {
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
}
// 没有cpp/uts插件变更,且没有增量js/bin文件变更,就输出无变更
if (!changedFiles && !hasBinFiles) {
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['uvue.dev.watching.end.empty']);
}
}
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
}
else if (event.code === 'END') {
// 重要:1.0 的APP端是自实现的AppWatcher,它是不会触发END事件的,这里边的逻辑只有非1.0的APP端会触发
if (process.env.UNI_AUTOMATOR_WS_ENDPOINT) {
setTimeout(() => {
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['build.failed']);
process.exit(0);
}, 2000);
}
}
else if (event.code === 'ERROR') {
if ((0, uni_cli_shared_1.runByHBuilderX)()) {
setTimeout(() => {
console.error(`Build failed with errors.`);
});
}
}
});
}
}
catch (e) {
if (options.platform === 'h5') {
console.error(`error when starting dev server:\n${e.stack || e}`);
}
else {
console.error(`error during build:\n${e.stack || e}`);
}
process.exit(1);
}
}
exports.runDev = runDev;
async function runBuild(options) {
(0, utils_1.initEnv)('build', options);
if ((0, uni_cli_shared_1.isUniAppXAndroidNative)()) {
return (0, uvue_1.runUVueAndroidBuild)(options);
}
try {
await (options.ssr && options.platform === 'h5'
? (0, build_1.buildSSR)(options)
: (0, build_1.build)(options));
await (0, exports.stopProfiler)((message) => (0, vite_1.createLogger)(options.logLevel).info(message));
console.log(uni_cli_shared_1.M['build.done']);
if (options.platform !== 'h5') {
(0, utils_1.showRunPrompt)(options.platform);
}
// 开发者可能用了三方插件,三方插件有可能阻止退出,导致HBuilderX打包状态识别不正确
if ((0, uni_cli_shared_1.isInHBuilderX)() ||
/* 需要排查为什么ext-api编译时没有自动结束 */ process.env
.UNI_COMPILE_TARGET === 'ext-api') {
process.exit(0);
}
}
catch (e) {
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
(0, configResolved_1.initLogger)({
logger: (0, vite_1.createLogger)(options.logLevel),
}).error(e.message || e);
}
else {
console.error(e.message || e);
}
console.error(`Build failed with errors.`);
process.exit(1);
}
}
exports.runBuild = runBuild;
let profileSession = global.__vite_profile_session;
let profileCount = 0;
const stopProfiler = (log) => {
if (!profileSession)
return;
return new Promise((res, rej) => {
profileSession.post('Profiler.stop', (err, result) => {
// Write profile to disk, upload, etc.
if (!err) {
const outPath = path_1.default.resolve(process.env.UNI_INPUT_DIR, `./profile-${profileCount++}.cpuprofile`);
fs_1.default.writeFileSync(outPath, JSON.stringify(result.profile));
log(picocolors_1.default.yellow(`CPU profile written to ${picocolors_1.default.white(picocolors_1.default.dim(outPath))}`));
profileSession = undefined;
res();
}
else {
rej(err);
}
});
});
};
exports.stopProfiler = stopProfiler;
function getHasBinFiles() {
const binFiles = process.env.UNI_APP_X_DOM2_DYNAMIC === 'true'
? process.env.UNI_APP_X_DOM2_BIN_CHANGED_FILES
: '';
return !!(binFiles && binFiles !== '[]');
}
@@ -0,0 +1,7 @@
import type { BuildOptions, InlineConfig } from 'vite';
import type { CliOptions } from '.';
import type { RollupWatcher, RollupWatcherEvent } from 'rollup';
export declare function buildByVite(inlineConfig: InlineConfig): Promise<import("rollup").RollupOutput | import("rollup").RollupOutput[] | RollupWatcher>;
export declare function build(options: CliOptions, callback?: (event: RollupWatcherEvent) => void): Promise<void>;
export declare function buildSSR(options: CliOptions): Promise<void>;
export declare function initBuildOptions(options: CliOptions, build: BuildOptions): InlineConfig;
+216
View File
@@ -0,0 +1,216 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initBuildOptions = exports.buildSSR = exports.build = exports.buildByVite = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("./utils");
async function buildByVite(inlineConfig) {
return Promise.resolve().then(() => __importStar(require('vite'))).then(({ build }) => build(inlineConfig));
}
exports.buildByVite = buildByVite;
async function build(options, callback) {
if (process.env.UNI_APP_X !== 'true' && options.platform === 'app') {
await buildApp(options, callback);
return;
}
const watcher = await buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, (0, utils_1.cleanOptions)(options))));
if (callback && typeof watcher === 'object' && 'on' in watcher) {
watcher.on('event', callback);
}
}
exports.build = build;
async function buildSSR(options) {
const outputDir = process.env.UNI_OUTPUT_DIR;
const ssrClientDir = path_1.default.resolve(outputDir, 'client');
process.env.UNI_OUTPUT_DIR = ssrClientDir;
const ssrBuildClientOptions = (0, utils_1.cleanOptions)(options);
ssrBuildClientOptions.ssrManifest = 'ssr-manifest.json';
ssrBuildClientOptions.outDir = process.env.UNI_OUTPUT_DIR;
process.env.UNI_SSR_CLIENT = 'true';
await buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, ssrBuildClientOptions)));
const ssrServerDir = path_1.default.resolve(outputDir, 'server');
process.env.UNI_OUTPUT_DIR = ssrServerDir;
const ssrBuildServerOptions = (0, utils_1.cleanOptions)(options);
ssrBuildServerOptions.ssr = path_1.default.resolve(process.env.UNI_INPUT_DIR, 'entry-server.js');
// 强制 cjs 输出
ssrBuildServerOptions.rollupOptions = {
output: {
format: 'cjs',
},
};
ssrBuildServerOptions.outDir = process.env.UNI_OUTPUT_DIR;
process.env.UNI_SSR_CLIENT = '';
process.env.UNI_SSR_SERVER = 'true';
await buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, ssrBuildServerOptions)));
// copy ssr-manfiest.json to server
const assets = ['ssr-manifest.json', 'index.html'];
assets.forEach((asset) => {
const ssrManifestFile = path_1.default.join(ssrClientDir, asset);
if (fs_extra_1.default.existsSync(ssrManifestFile)) {
fs_extra_1.default.copyFileSync(ssrManifestFile, path_1.default.join(ssrServerDir, asset));
}
});
}
exports.buildSSR = buildSSR;
function initBuildOptions(options, build) {
return {
root: process.env.VITE_ROOT_DIR,
configFile: options.config,
base: options.base,
logLevel: options.logLevel,
clearScreen: options.clearScreen,
mode: options.mode,
build,
};
}
exports.initBuildOptions = initBuildOptions;
function buildManifestJson() {
const platform = 'app';
const inputDir = process.env.UNI_INPUT_DIR;
const outputDir = process.env.UNI_OUTPUT_DIR;
const pkg = require(path_1.default.resolve(__dirname, '../../package.json'));
process.env.UNI_COMPILER_VERSION =
process.env.UNI_COMPILER_VERSION ||
pkg['uni-app']?.['compilerVersion'] ||
'';
const manifestJson = (0, uni_cli_shared_1.normalizeAppManifestJson)((0, uni_cli_shared_1.parseManifestJsonOnce)(inputDir), (0, uni_cli_shared_1.parsePagesJsonOnce)(inputDir, platform));
fs_extra_1.default.outputFileSync(path_1.default.resolve(outputDir, 'manifest.json'), JSON.stringify(manifestJson, null, 2));
}
async function buildApp(options, callback) {
if (options.manifest) {
return buildManifestJson();
}
let appWatcher;
if (options.watch) {
appWatcher = new AppWatcher();
if (callback) {
appWatcher.on('event', callback);
}
}
if (process.env.UNI_RENDERER === 'native') {
// 纯原生渲染时,main.js + App.vue 需要跟页面分开,独立编译(因为需要包含 Vuex 等共享内容)
process.env.UNI_COMPILER = 'nvue';
process.env.UNI_RENDERER_NATIVE = 'appService';
const nvueAppBuilder = await buildByVite((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvueAppService: true, nvue: true }, initBuildOptions(options, (0, utils_1.cleanOptions)(options)))));
if (appWatcher) {
appWatcher.setFirstWatcher(nvueAppBuilder);
}
process.env.UNI_RENDERER_NATIVE = 'pages';
const nvueBuilder = await buildByVite((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvue: true }, initBuildOptions(options, (0, utils_1.cleanOptions)(options)))));
if (appWatcher) {
appWatcher.setSecondWatcher(nvueBuilder);
return appWatcher;
}
return;
}
// 指定为 vue 方便 App 插件初始化 vue 所需插件列表
process.env.UNI_COMPILER = 'vue';
const vueBuilder = await buildByVite((0, utils_1.addConfigFile)(initBuildOptions(options, (0, utils_1.cleanOptions)(options))));
if (!(0, uni_cli_shared_1.isNormalCompileTarget)()) {
// 不需要 nvue 编译器
return vueBuilder;
}
if (appWatcher) {
appWatcher.setFirstWatcher(vueBuilder);
}
// 临时指定为 nvue 方便 App 插件初始化 nvue 所需插件列表
process.env.UNI_COMPILER = 'nvue';
const nvueBuilder = await buildByVite((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvue: true }, initBuildOptions(options, (0, utils_1.cleanOptions)(options)))));
// 还原为 vue
process.env.UNI_COMPILER = 'vue';
if (appWatcher) {
appWatcher.setSecondWatcher(nvueBuilder);
return appWatcher;
}
}
class AppWatcher {
constructor() {
this._firstStart = false;
this._firstEnd = false;
this._secondStart = false;
this._secondEnd = false;
}
on(_event, callback) {
this._callback = callback;
}
setFirstWatcher(firstWatcher) {
firstWatcher.on('event', (event) => {
if (event.code === 'BUNDLE_START') {
this._bundleFirstStart(event);
}
else if (event.code === 'BUNDLE_END') {
this._bundleFirstEnd(event);
}
else if (event.code === 'ERROR') {
this._callback?.(event);
}
});
}
setSecondWatcher(secondWatcher) {
secondWatcher.on('event', (event) => {
if (event.code === 'BUNDLE_START') {
this._bundleSecondStart(event);
}
else if (event.code === 'BUNDLE_END') {
this._bundleSecondEnd(event);
}
else if (event.code === 'ERROR') {
this._callback?.(event);
}
});
}
_bundleFirstStart(event) {
this._firstStart = true;
this._bundleStart(event);
}
_bundleFirstEnd(event) {
this._firstEnd = true;
this._bundleEnd(event);
}
_bundleSecondStart(event) {
this._secondStart = true;
this._bundleStart(event);
}
_bundleSecondEnd(event) {
this._secondEnd = true;
this._bundleEnd(event);
}
_bundleStart(event) {
if (this._firstStart && this._secondStart) {
this._callback?.(event);
}
}
_bundleEnd(event) {
if (this._firstEnd && this._secondEnd) {
this._callback?.(event);
}
}
}
@@ -0,0 +1,26 @@
import type { LogLevel } from 'vite';
export interface CliOptions {
'--'?: string[];
c?: boolean | string;
config?: string;
platform?: string;
p?: string;
ssr?: boolean;
base?: string;
debug?: boolean | string;
d?: boolean | string;
filter?: string;
f?: string;
logLevel?: LogLevel;
l?: LogLevel;
m?: string;
mode?: string;
clearScreen?: boolean;
autoHost?: string;
autoPort?: number;
devtools?: boolean;
devtoolsHost?: string;
devtoolsPort?: number;
subpackage?: string;
plugin?: string;
}
+57
View File
@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const cac_1 = require("cac");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("./utils");
const action_1 = require("./action");
(0, uni_cli_shared_1.fixBinaryPath)();
const cli = (0, cac_1.cac)('uni');
cli
.option('-c, --config <file>', `[string] use specified config file`)
.option('-p, --platform [platform]', '[string] ' + utils_1.PLATFORMS.join(' | '), {
default: 'h5',
})
.option('--base <path>', `[string] public base path (default: /)`)
.option('-ssr', '[boolean] server-side rendering', {
default: false,
})
.option('-l, --logLevel <level>', `[string] silent | error | warn | all`)
.option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
.option('-d, --debug [feat]', `[string | boolean] show debug logs`)
.option('-f, --filter <filter>', `[string] filter debug logs`)
.option('-m, --mode <mode>', `[string] set env mode`)
.option('--minify [minifier]', `[boolean | "terser" | "esbuild"] enable/disable minification, ` +
`or specify minifier to use (default: terser)`)
.option('--autoHost [autoHost]', `[string] specify automator hostname`)
.option('--autoPort [autoPort]', `[number] specify automator port`)
.option('--devtools', `[boolean] enable devtools`)
.option('--devtoolsHost [devtoolsHost]', `[string] specify devtools hostname`)
.option('--devtoolsPort [devtoolsPort]', `[number] specify devtools port`)
.option('--subpackage [subpackage]', `[string] specify subpackage to build`)
.option('--plugin [plugin]', `[string] specify plugin to build`);
cli
.command('')
.alias('dev')
.option('--host [host]', `[string] specify hostname`)
.option('--port <port>', `[number] specify port`)
.option('--https', `[boolean] use TLS + HTTP/2`)
.option('--open [path]', `[boolean | string] open browser on startup`)
.option('--cors', `[boolean] enable CORS`)
.option('--strictPort', `[boolean] exit if specified port is already in use`)
.option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
.action(action_1.runDev);
cli
.command('build')
.option('--outDir <dir>', `[string] output directory (default: dist)`)
.option('--assetsInlineLimit <number>', `[number] static asset base64 inline threshold in bytes (default: 4096)`)
.option('--sourcemap', `[boolean] output source maps for build (default: false)`)
.option('--manifest', `[boolean] emit build manifest json`)
.option('--ssrManifest', `[boolean] emit ssr manifest json`)
.option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`, {
default: true,
})
.option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
.action(action_1.runBuild);
cli.help();
cli.version(require('../../package.json').version);
cli.parse();
@@ -0,0 +1 @@
export declare function initNVueEnv(): void;
+27
View File
@@ -0,0 +1,27 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initNVueEnv = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function initNVueEnv() {
if (process.env.UNI_APP_X === 'true') {
return;
}
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
if ((0, uni_cli_shared_1.getAppRenderer)(manifestJson) === 'native') {
process.env.UNI_RENDERER = 'native';
}
const nvueCompiler = (0, uni_cli_shared_1.getNVueCompiler)(manifestJson);
if (nvueCompiler === 'uni-app') {
process.env.UNI_NVUE_COMPILER = 'uni-app';
}
else if (nvueCompiler === 'vue') {
process.env.UNI_NVUE_COMPILER = 'vue';
}
if ((0, uni_cli_shared_1.getNVueStyleCompiler)(manifestJson) === 'uni-app') {
process.env.UNI_NVUE_STYLE_COMPILER = 'uni-app';
}
if ((0, uni_cli_shared_1.getAppCodeSplitting)(manifestJson)) {
process.env.UNI_APP_CODE_SPLITTING = 'true';
}
}
exports.initNVueEnv = initNVueEnv;
@@ -0,0 +1,4 @@
import type { ServerOptions, ViteDevServer } from 'vite';
import type { CliOptions } from '.';
export declare function createServer(options: CliOptions & ServerOptions): Promise<ViteDevServer>;
export declare function createSSRServer(options: CliOptions & ServerOptions): Promise<ViteDevServer>;
+229
View File
@@ -0,0 +1,229 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createSSRServer = exports.createServer = void 0;
const fs_1 = __importDefault(require("fs"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("./utils");
function createLogger(level, options) {
return Promise.resolve().then(() => __importStar(require('vite'))).then(({ createLogger }) => createLogger(level, options));
}
function createViteServer(inlineConfig) {
return Promise.resolve().then(() => __importStar(require('vite'))).then(({ createServer }) => createServer(inlineConfig));
}
async function createServer(options) {
const server = await createViteServer((0, utils_1.addConfigFile)({
root: process.env.VITE_ROOT_DIR,
configFile: options.config,
base: options.base,
mode: options.mode,
logLevel: options.logLevel || 'info',
clearScreen: options.clearScreen,
server: (0, utils_1.cleanOptions)(options),
}));
await server.listen();
const logger = server.config.logger;
logger.info(picocolors_1.default.cyan(`\n vite v${require('vite/package.json').version}`) +
picocolors_1.default.green(` dev server running at:\n`), {
clear: !server.config.logger.hasWarned,
});
server.printUrls();
// printUrls 会在 nextTick 中输出
process.nextTick(() => (0, utils_1.printStartupDuration)(logger));
return server;
}
exports.createServer = createServer;
async function createSSRServer(options) {
// 延迟加载
const app = (await Promise.resolve().then(() => __importStar(require('express')))).default();
/**
* @type {import('vite').ViteDevServer}
*/
const vite = await createViteServer((0, utils_1.addConfigFile)({
// custom: don't include HTML middlewares
appType: 'custom',
root: process.env.VITE_ROOT_DIR,
configFile: options.config,
base: options.base,
mode: options.mode,
logLevel: options.logLevel || 'info',
clearScreen: options.clearScreen,
server: {
middlewareMode: true,
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
usePolling: true,
interval: 100,
},
},
}));
// use vite's connect instance as middleware
app.use(vite.middlewares);
app.use('*', async (req, res) => {
try {
const manifestJson = (0, uni_cli_shared_1.parseManifestJson)(process.env.UNI_INPUT_DIR);
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifestJson, 'h5');
const base = (h5 && h5.router && h5.router.base) || '';
const url = req.originalUrl.replace(base, '');
const template = await vite.transformIndexHtml(url, fs_1.default.readFileSync(path_1.default.resolve(process.env.VITE_ROOT_DIR, 'index.html'), 'utf-8'));
const render = (await vite.ssrLoadModule(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'entry-server.js'))).render;
const { title, headMeta, preloadLinks, appHtml, appContext } = await render(url);
const icon = template.includes('rel="icon"')
? ''
: '<link rel="icon" href="data:," />\n';
const html = template
.replace(/<title>(.*?)<\/title>/, `${icon}<title>${title}</title>`)
.replace(`<!--head-meta-->`, headMeta)
.replace(`<!--preload-links-->`, preloadLinks)
.replace(`<!--app-html-->`, appHtml)
.replace(`<!--app-context-->`, appContext);
res.status(200).set({ 'Content-Type': 'text/html' }).end(html);
}
catch (e) {
vite && vite.ssrFixStacktrace(e);
res.status(500).end(e.stack);
}
});
const logger = await createLogger(options.logLevel);
const serverOptions = vite.config.server || {};
let port = options.port || serverOptions.port || 5173;
let hostname;
if (options.host === 'localhost') {
// Use a secure default
hostname = '127.0.0.1';
}
else if (options.host === undefined || options.host === true) {
// probably passed --host in the CLI, without arguments
hostname = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
}
else {
hostname = options.host;
}
return new Promise((resolve, reject) => {
const onSuccess = () => {
printHttpServerUrls(server, vite.config);
process.nextTick(() => (0, utils_1.printStartupDuration)(logger));
resolve(vite);
};
const onError = (e) => {
if (e.code === 'EADDRINUSE') {
if (options.strictPort) {
server.off('error', onError);
reject(new Error(`Port ${port} is already in use`));
}
else {
logger.info(`Port ${port} is in use, trying another one...`);
server = app.listen(++port, hostname, onSuccess).on('error', onError);
}
}
else {
server.off('error', onError);
reject(e);
}
};
let server = app.listen(port, hostname, onSuccess).on('error', onError);
});
}
exports.createSSRServer = createSSRServer;
function printHttpServerUrls(server, config) {
printCommonServerUrls(server, config.server, config);
}
function printCommonServerUrls(server, options, config) {
const address = server.address();
const isAddressInfo = (x) => x?.address;
if (isAddressInfo(address)) {
const hostname = resolveHostname(options.host);
const protocol = options.https ? 'https' : 'http';
printServerUrls(hostname, protocol, address.port, config.base, config.logger.info);
}
}
function printServerUrls(hostname, protocol, port, base, info) {
if (hostname.host === '127.0.0.1') {
const url = `${protocol}://${hostname.name}:${picocolors_1.default.bold(port)}${base}`;
info(` - Local: ${picocolors_1.default.cyan(url)}`);
if (hostname.name !== '127.0.0.1') {
info(` - Network: ${picocolors_1.default.dim('use `--host` to expose')}`);
}
}
else {
Object.values(os_1.default.networkInterfaces())
.flatMap((nInterface) => nInterface ?? [])
.filter((detail) => detail &&
detail.address &&
// Node < v18
((typeof detail.family === 'string' && detail.family === 'IPv4') ||
// Node >= v18
// @ts-expect-error
(typeof detail.family === 'number' && detail.family === 4)))
.map((detail) => {
const type = detail.address.includes('127.0.0.1')
? ' - Local: '
: ' * Network: ';
const host = detail.address.replace('127.0.0.1', hostname.name);
const url = `${protocol}://${host}:${picocolors_1.default.bold(port)}${base}`;
return `${type} ${picocolors_1.default.cyan(url)}`;
})
.sort((msg1) => {
return msg1.indexOf('- Local') > -1 ? -1 : 1;
})
.forEach((msg, index, arr) => {
if (arr.length - 1 === index) {
info(msg.replace('* Network', '- Network'));
}
else {
info(msg);
}
});
}
}
function resolveHostname(optionsHost) {
let host;
if (optionsHost === undefined || optionsHost === false) {
// Use a secure default
host = '127.0.0.1';
}
else if (optionsHost === true) {
// If passed --host in the CLI without arguments
host = undefined; // undefined typically means 0.0.0.0 or :: (listen on all IPs)
}
else {
host = optionsHost;
}
// Set host name to localhost when possible, unless the user explicitly asked for '127.0.0.1'
const name = (optionsHost !== '127.0.0.1' && host === '127.0.0.1') ||
host === '0.0.0.0' ||
host === '::' ||
host === undefined
? 'localhost'
: host;
return { host, name };
}
@@ -0,0 +1,34 @@
import type { InlineConfig, Logger } from 'vite';
import type { CliOptions } from '.';
export declare function formatStyleIsolationVersionMessage(version: string): string;
export declare const PLATFORMS: string[];
export type PLATFORM = 'app' | 'mp-alipay' | 'mp-baidu' | 'mp-kuaishou' | 'mp-lark' | 'mp-qq' | 'mp-toutiao' | 'mp-weixin' | 'mp-xhs' | 'mp-jd' | 'mp-harmony' | 'quickapp-webview' | 'quickapp-webview-huawei' | 'quickapp-webview-union';
export declare function addConfigFile(inlineConfig: InlineConfig): InlineConfig;
export declare function initEnv(type: 'unknown' | 'dev' | 'build', options: CliOptions): void;
export declare function cleanOptions(options: CliOptions): {
'--'?: string[] | undefined;
c?: string | boolean | undefined;
config?: string | undefined;
platform?: string | undefined;
p?: string | undefined;
ssr?: boolean | undefined;
base?: string | undefined;
debug?: string | boolean | undefined;
d?: string | boolean | undefined;
filter?: string | undefined;
f?: string | undefined;
logLevel?: import("vite").LogLevel | undefined;
l?: import("vite").LogLevel | undefined;
m?: string | undefined;
mode?: string | undefined;
clearScreen?: boolean | undefined;
autoHost?: string | undefined;
autoPort?: number | undefined;
devtools?: boolean | undefined;
devtoolsHost?: string | undefined;
devtoolsPort?: number | undefined;
subpackage?: string | undefined;
plugin?: string | undefined;
};
export declare function printStartupDuration(logger: Logger, whitespace?: boolean): void;
export declare function showRunPrompt(platform: PLATFORM): void;
+444
View File
@@ -0,0 +1,444 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.showRunPrompt = exports.printStartupDuration = exports.cleanOptions = exports.initEnv = exports.addConfigFile = exports.PLATFORMS = exports.formatStyleIsolationVersionMessage = void 0;
const fs_1 = __importDefault(require("fs"));
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const perf_hooks_1 = require("perf_hooks");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const nvue_1 = require("./nvue");
const uvue_1 = require("./uvue");
function formatStyleIsolationVersionMessage(version) {
const versionNumber = Number(version);
const shouldUpgrade = versionNumber !== 2;
const message = uni_cli_shared_1.M[shouldUpgrade
? 'style.isolation.version.upgrade'
: 'style.isolation.version'];
const displayVersion = Number.isInteger(versionNumber)
? versionNumber.toFixed(1)
: version;
return message.replace('{version}', displayVersion);
}
exports.formatStyleIsolationVersionMessage = formatStyleIsolationVersionMessage;
// uni -p
exports.PLATFORMS = [
'app',
'h5',
'mp-alipay',
'mp-baidu',
'mp-kuaishou',
'mp-lark',
'mp-qq',
'mp-toutiao',
'mp-weixin',
'mp-xhs',
'mp-jd',
'mp-harmony',
'quickapp-webview',
'quickapp-webview-huawei',
'quickapp-webview-union',
];
function resolveConfigFile() {
const extname = ['.js', '.ts', '.mjs', '.mts'].find((ext) => {
return fs_1.default.existsSync(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'vite.config' + ext));
});
if (extname) {
return path_1.default.resolve(process.env.UNI_INPUT_DIR, 'vite.config' + extname);
}
return path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'vite.config.js');
}
function addConfigFile(inlineConfig) {
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
inlineConfig.configFile = resolveConfigFile();
}
return inlineConfig;
}
exports.addConfigFile = addConfigFile;
let initialized = false;
function initEnv(type, options) {
var _a;
// 默认隐藏浏览器数据过期提示,保留用户显式设置的值
(_a = process.env).BROWSERSLIST_IGNORE_OLD_DATA ?? (_a.BROWSERSLIST_IGNORE_OLD_DATA = 'true');
if (initialized) {
return;
}
initialized = true;
if (options.platform === 'mp-360') {
console.error(uni_cli_shared_1.M['mp.360.unsupported']);
process.exit(0);
}
if (options.platform === 'web') {
options.platform = 'h5';
}
if (options.plugin) {
process.env.UNI_MP_PLUGIN = options.plugin;
}
// TODO 需要识别 mode
if (type === 'dev') {
process.env.NODE_ENV = 'development';
}
else if (type === 'build') {
if (options.watch) {
process.env.NODE_ENV = 'development';
}
else {
if (!(0, uni_cli_shared_1.isNormalCompileTarget)()) {
if (!process.env.NODE_ENV) {
process.env.NODE_ENV = 'production';
}
}
else {
process.env.NODE_ENV = 'production';
}
}
}
if (!options.mode) {
options.mode = process.env.NODE_ENV;
}
// vite 会修改 NODE_ENV,存储在 UNI_NODE_ENV 中,稍后校正 NODE_ENV
process.env.UNI_NODE_ENV = process.env.VITE_USER_NODE_ENV =
process.env.NODE_ENV;
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
const cliContext = (0, uni_cli_shared_1.resolveHBuilderXPluginPath)('uniapp-cli-vite');
if (!cliContext) {
throw new Error('HBuilder plugin "uniapp-cli-vite" is required');
}
process.env.UNI_CLI_CONTEXT = cliContext;
}
else {
process.env.UNI_CLI_CONTEXT = process.cwd();
}
// TODO 待优化
initUTSPlatform(options);
if (options.platform === 'quickapp-webview-huawei' ||
options.platform === 'quickapp-webview-union') {
process.env.UNI_SUB_PLATFORM = options.platform;
options.platform = 'quickapp-webview';
}
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
process.env.VITE_ROOT_DIR =
process.env.VITE_ROOT_DIR || process.env.UNI_INPUT_DIR || process.cwd();
}
else {
process.env.VITE_ROOT_DIR = process.env.VITE_ROOT_DIR || process.cwd();
}
process.env.UNI_INPUT_DIR =
process.env.UNI_INPUT_DIR || path_1.default.resolve(process.cwd(), 'src');
initCustomScripts(options);
process.env.UNI_PLATFORM = options.platform;
(0, uni_cli_shared_1.normalizeUniAppXVaporEnv)();
// 需要提前初始化
(0, uvue_1.initUVueEnv)();
if (process.env.UNI_PLATFORM === 'app-harmony') {
if (process.env.UNI_APP_HARMONY_PROJECT_PATH) {
// 先通过原始outputDir设置,因为下边会修改原始的outputDir到鸿蒙项目里,而这些临时目录不应该影响到鸿蒙项目
process.env.UNI_APP_X_TSC_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.tsc');
process.env.UNI_APP_X_UVUE_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.uvue');
const baseOutDir = path_1.default.basename(process.env.UNI_OUTPUT_DIR);
process.env.UNI_APP_X_CACHE_DIR =
process.env.UNI_APP_X_CACHE_DIR ||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../cache/.' + baseOutDir);
process.env.UNI_APP_X_TSC_CACHE_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, `tsc`);
// 指定了鸿蒙项目根目录
process.env.UNI_OUTPUT_DIR = path_1.default.resolve(process.env.UNI_APP_HARMONY_PROJECT_PATH, `entry/src/main/resources/resfile/apps/HBuilder/www`);
}
}
const hasOutputDir = !!process.env.UNI_OUTPUT_DIR;
if (hasOutputDir) {
;
options.outDir = process.env.UNI_OUTPUT_DIR;
}
else {
if (!options.outDir) {
;
options.outDir = path_1.default.resolve(process.cwd(), 'dist', process.env.NODE_ENV === 'production' ? 'build' : 'dev', (0, uni_cli_shared_1.getPlatformDir)());
}
process.env.UNI_OUTPUT_DIR = options.outDir;
}
// 编译为插件、分包时,需提前计算缓存目录位置
process.env.UNI_APP_X_CACHE_DIR =
process.env.UNI_APP_X_CACHE_DIR ||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../cache/.' + path_1.default.basename(process.env.UNI_OUTPUT_DIR));
// 兼容 HBuilderX 旧参数
if (process.env.UNI_SUBPACKGE) {
options.subpackage = process.env.UNI_SUBPACKGE;
}
if (options.subpackage) {
process.env.UNI_SUBPACKAGE = options.subpackage;
if (!hasOutputDir) {
// 未指定,则自动补充
process.env.UNI_OUTPUT_DIR = options.outDir =
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, options.subpackage);
}
}
if (options.plugin) {
if (!hasOutputDir) {
// 未指定,则自动补充
process.env.UNI_OUTPUT_DIR = options.outDir =
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, options.plugin);
}
}
const baseOutDir = path_1.default.basename(process.env.UNI_OUTPUT_DIR);
if ((0, uni_cli_shared_1.isNormalCompileTarget)()) {
process.env.HX_DEPENDENCIES_DIR =
process.env.HX_DEPENDENCIES_DIR ||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../hx/' + baseOutDir);
}
process.env.UNI_MODULES_ENCRYPT_CACHE_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, '.encrypt', process.env.NODE_ENV === 'development' ? 'dev' : 'build', process.env.UNI_UTS_PLATFORM);
// 默认开启 tsc
process.env.UNI_APP_X_TSC = 'true';
try {
// 部分模式下缺少manifest.json,比如内部编译ext-api时
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
// 留个开关
if (manifestJson['app']?.['utsCompilerVersion'] === 'v1' ||
manifestJson['app-plus']?.['utsCompilerVersion'] === 'v1') {
process.env.UNI_APP_X_TSC = 'false';
}
if (manifestJson['uni-app-x']?.['styleIsolationVersion'] == 2) {
process.env.UNI_APP_STYLE_ISOLATION_VERSION = '2';
}
if ((0, uni_cli_shared_1.isUniAppXVapor)() &&
process.env.UNI_PLATFORM === 'app-harmony' &&
!process.env.UNI_APP_X_HARMONY_SCRIPT_ENGINE) {
process.env.UNI_APP_X_HARMONY_SCRIPT_ENGINE =
(0, uni_cli_shared_1.resolveUniAppXHarmonyScriptEngine)(manifestJson);
}
if (process.env.UNI_APP_X_HARMONY_SCRIPT_ENGINE === 'jsvm') {
process.env.UNI_APP_X_UVUE_SCRIPT_ENGINE = 'js';
}
}
catch (e) { }
if (!process.env.UNI_APP_X_TSC_DIR) {
process.env.UNI_APP_X_TSC_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.tsc');
}
if (!process.env.UNI_APP_X_UVUE_DIR) {
process.env.UNI_APP_X_UVUE_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.uvue');
}
if (!process.env.UNI_APP_X_TSC_CACHE_DIR) {
process.env.UNI_APP_X_TSC_CACHE_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, `tsc`);
}
initAutomator(options);
initDevtools(options);
if (process.env.UNI_PLATFORM === 'app') {
(0, nvue_1.initNVueEnv)();
}
if (process.env.NODE_ENV === 'development') {
console.log(uni_cli_shared_1.M['dev.performance'] +
(process.env.UNI_PLATFORM.startsWith('mp-')
? uni_cli_shared_1.M['dev.performance.mp']
: '') +
(process.env.UNI_PLATFORM === 'web' || process.env.UNI_PLATFORM === 'h5'
? uni_cli_shared_1.M['dev.performance.web']
: ''));
}
// 兼容旧版本 SOURCEMAP 参数
if (process.env.SOURCEMAP) {
process.env.UNI_APP_SOURCEMAP = process.env.SOURCEMAP;
}
if (options.sourcemap &&
process.env.NODE_ENV !== 'development') {
process.env.UNI_APP_SOURCEMAP = 'true';
}
(0, uni_cli_shared_1.initModulePaths)();
const pkg = require('../../package.json');
process.env.UNI_COMPILER_VERSION =
process.env.UNI_COMPILER_VERSION ||
pkg['uni-app']?.['compilerVersion'] ||
'';
process.env.UNI_COMPILER_VERSION_TYPE = pkg.version.includes('alpha')
? 'a'
: 'r';
process.env.UNI_HX_VERSION_DEV =
process.env.HX_Version && process.env.HX_Version.includes('-dev')
? 'true'
: 'false';
(0, uni_cli_shared_1.initPreContext)(process.env.UNI_PLATFORM, process.env.UNI_CUSTOM_CONTEXT, process.env.UNI_UTS_PLATFORM, process.env.UNI_APP_X === 'true');
const isX = (0, uni_cli_shared_1.isUniAppX)();
const renderMode = isX && !process.env.UNI_PLATFORM.startsWith('mp-')
? (0, uni_cli_shared_1.isUniAppXVapor)()
? '蒸汽模式'
: 'VDOM模式'
: '';
console.log(uni_cli_shared_1.M['app.compiler.version'].replace('{version}', process.env.UNI_COMPILER_VERSION +
`(${isX ? 'uni-app x' : 'vue3'})` +
renderMode));
const vaporScriptPlatform = process.env.UNI_UTS_PLATFORM || process.env.UNI_PLATFORM;
const isVaporScriptPlatform = (0, uni_cli_shared_1.isUniAppXVapor)() ||
(isX &&
(vaporScriptPlatform === 'web' ||
vaporScriptPlatform?.startsWith('mp-') === true));
if (isVaporScriptPlatform) {
if (process.env.UNI_PLATFORM === 'app' ||
process.env.UNI_PLATFORM === 'app-harmony') {
console.log(uni_cli_shared_1.M['view.render.compiler.target'].replace('{target}', process.env.UNI_APP_X_DOM2_DYNAMIC === 'true'
? uni_cli_shared_1.M['view.render.compiler.target.bytecode']
: uni_cli_shared_1.M['view.render.compiler.target.nativecode']));
}
console.log(uni_cli_shared_1.M['vapor.default.script.lang'].replace('{lang}', (0, uni_cli_shared_1.getUniAppXVaporScriptLang)(process.env.UNI_INPUT_DIR)));
}
if ((0, uni_cli_shared_1.isUniAppXVapor)() && process.env.UNI_APP_X_HARMONY_SCRIPT_ENGINE) {
console.log(uni_cli_shared_1.M['harmony.vapor.script.runtime'].replace('{runtime}', process.env.UNI_APP_X_HARMONY_SCRIPT_ENGINE));
}
if (isX && !(0, uni_cli_shared_1.isUniAppXVapor)()) {
console.log(formatStyleIsolationVersionMessage(process.env.UNI_APP_STYLE_ISOLATION_VERSION || '1'));
}
console.log(uni_cli_shared_1.M['compiling']);
}
exports.initEnv = initEnv;
function initUTSPlatform(options) {
if (options.platform === 'app-android') {
process.env.UNI_UTS_PLATFORM = 'app-android';
options.platform = 'app';
}
else if (options.platform === 'app-ios') {
process.env.UNI_UTS_PLATFORM = 'app-ios';
options.platform = 'app';
}
else {
// 运行时,可能传入了 UNI_APP_PLATFORM = 'android'|'ios'
if (process.env.UNI_APP_PLATFORM === 'android') {
process.env.UNI_UTS_PLATFORM = 'app-android';
}
if (process.env.UNI_APP_PLATFORM === 'ios') {
process.env.UNI_UTS_PLATFORM = 'app-ios';
}
if (options.platform === 'app-plus') {
options.platform = 'app';
}
if (options.platform === 'app') {
// app 平台未指定 UTS_PLATFORM 时,设置未 app,一般是发行模式
if (!process.env.UNI_UTS_PLATFORM) {
process.env.UNI_UTS_PLATFORM = 'app';
}
}
}
if (options.platform === 'h5') {
process.env.UNI_UTS_PLATFORM = 'web';
}
// 非 app 平台,自动补充 UNI_UTS_PLATFORM
// app 平台,必须主动传入
if (options.platform !== 'app') {
if (!process.env.UNI_UTS_PLATFORM) {
process.env.UNI_UTS_PLATFORM = options.platform;
}
}
process.env.UNI_UTS_TARGET_LANGUAGE = 'javascript';
if (process.env.UNI_UTS_PLATFORM === 'app-android') {
process.env.UNI_UTS_TARGET_LANGUAGE = 'kotlin';
}
else if (process.env.UNI_UTS_PLATFORM === 'app-ios') {
process.env.UNI_UTS_TARGET_LANGUAGE = 'swift';
}
else if (process.env.UNI_UTS_PLATFORM === 'app-harmony') {
process.env.UNI_UTS_TARGET_LANGUAGE = 'arkts';
}
}
function initDevtools({ devtools, devtoolsHost, devtoolsPort }) {
if (!devtools) {
return;
}
process.env.__VUE_PROD_DEVTOOLS__ = 'true';
if (devtoolsHost) {
process.env.__VUE_DEVTOOLS_HOST__ = devtoolsHost;
}
if (devtoolsPort) {
process.env.__VUE_DEVTOOLS_PORT__ = devtoolsPort + '';
}
}
function initAutomator({ autoHost, autoPort }) {
const hasAutoHostOrPort = autoHost || autoPort || process.env.UNI_AUTOMATOR_HOST;
// 发行分包,插件也不需要自动化测试
if (!hasAutoHostOrPort ||
process.env.UNI_SUBPACKAGE ||
process.env.UNI_MP_PLUGIN) {
return;
}
process.env.UNI_AUTOMATOR_WS_ENDPOINT =
'ws://' +
(autoHost || process.env.UNI_AUTOMATOR_HOST || resolveHostname()) +
':' +
(autoPort || process.env.UNI_AUTOMATOR_PORT);
}
function resolveHostname() {
const interfaces = os_1.default.networkInterfaces();
const keys = Object.keys(interfaces);
for (const key of keys) {
const interfaceInfos = interfaces[key];
if (!interfaceInfos) {
continue;
}
for (const info of interfaceInfos) {
if ((info.family === 'IPv4' ||
/* Node >= v18 */ info.family === 4) &&
!info.address.includes('127.0.0.1')) {
return info.address;
}
}
}
return 'localhost';
}
function cleanOptions(options) {
const ret = { ...options };
delete ret['--'];
delete ret.c;
delete ret.config;
delete ret.platform;
delete ret.p;
delete ret.ssr;
delete ret.base;
delete ret.debug;
delete ret.d;
delete ret.filter;
delete ret.f;
delete ret.logLevel;
delete ret.l;
delete ret.clearScreen;
delete ret.m;
delete ret.mode;
delete ret.autoHost;
delete ret.autoPort;
return ret;
}
exports.cleanOptions = cleanOptions;
function printStartupDuration(logger, whitespace = true) {
if (global.__vite_start_time) {
const startupDuration = perf_hooks_1.performance.now() - global.__vite_start_time;
logger.info(`${whitespace ? `\n ` : ''}${picocolors_1.default.cyan(`ready in ${Math.ceil(startupDuration)}ms.`)}\n`);
}
}
exports.printStartupDuration = printStartupDuration;
function initCustomScripts(options) {
const custom = (0, uni_cli_shared_1.parseScripts)(process.env.UNI_SCRIPT || options.platform, // process.env.UNI_SCRIPT 是 HBuilderX 传递的
path_1.default.join(process.env.VITE_ROOT_DIR, 'package.json'));
if (!custom) {
return;
}
options.platform = custom.platform;
process.env.UNI_CUSTOM_SCRIPT = custom.name;
process.env.UNI_CUSTOM_DEFINE = JSON.stringify(custom.define);
process.env.UNI_CUSTOM_CONTEXT = JSON.stringify(custom.context);
}
function showRunPrompt(platform) {
if (!(0, uni_cli_shared_1.runByHBuilderX)()) {
const devtools = getPlatformDevtools(getOriginalPlatform(platform));
const outputDir = path_1.default.relative(process.env.UNI_CLI_CONTEXT, process.env.UNI_OUTPUT_DIR);
(0, uni_cli_shared_1.output)('log', `${uni_cli_shared_1.M['prompt.run.message']
.replace('{devtools}', uni_cli_shared_1.M[devtools])
.replace('{outputDir}', picocolors_1.default.cyan(outputDir))}`);
}
}
exports.showRunPrompt = showRunPrompt;
function getOriginalPlatform(platform) {
if (platform.startsWith('quickapp-webview') && process.env.UNI_SUB_PLATFORM) {
return process.env.UNI_SUB_PLATFORM;
}
return platform;
}
function getPlatformDevtools(platform) {
return `prompt.run.devtools.${platform}`;
}
+16
View File
@@ -0,0 +1,16 @@
import { type BuildOptions, type ServerOptions } from 'vite';
import type { RollupWatcher } from 'rollup';
import type { CliOptions } from '.';
export declare function initUVueEnv(): void;
export declare function runUVueAndroidDev(options: CliOptions & ServerOptions): Promise<undefined>;
export declare function runUVueAndroidBuild(options: CliOptions & BuildOptions): Promise<void>;
/**
* 目前的简易实现逻辑
* node层:
* 1. 监听项目,生成资源到临时目录 .uts/android
* 2. uvue 文件,做解析,拆分生成 render.kt, css.kt, uts.uvue
* 3. static 文件,copy 到最终目录
* 4. uvue、vue、uts 文件发生变化,调用 uts 编译器
* @param options
*/
export declare function buildUVue(options: CliOptions): Promise<RollupWatcher | void>;
+126
View File
@@ -0,0 +1,126 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.buildUVue = exports.runUVueAndroidBuild = exports.runUVueAndroidDev = exports.initUVueEnv = void 0;
const vite_1 = require("vite");
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const build_1 = require("./build");
const utils_1 = require("./utils");
const easycom_1 = require("../utils/easycom");
const action_1 = require("./action");
function initUVueEnv() {
// 直接指定了
if (process.env.UNI_APP_X === 'false') {
return;
}
// 没有手动指定时,才需要动态读取 manifest.json
if (process.env.UNI_APP_X !== 'true') {
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
if (!(0, shared_1.hasOwn)(manifestJson, 'uni-app-x')) {
return;
}
process.env.UNI_APP_X = 'true';
if (manifestJson['uni-app-x']?.singleThread === false) {
process.env.UNI_APP_X_SINGLE_THREAD = 'false';
}
}
if (process.env.UNI_PLATFORM === 'app') {
process.env.UNI_APP_X_UVUE_SCRIPT_ENGINE = 'native';
// App X iOS 与 Android Vapor 统一使用 JS 引擎
if ((0, uni_cli_shared_1.isUniAppXIOS)() || (0, uni_cli_shared_1.isUniAppXAndroidVapor)()) {
process.env.UNI_APP_X_UVUE_SCRIPT_ENGINE = 'js';
}
}
}
exports.initUVueEnv = initUVueEnv;
async function runUVueAndroidDev(options) {
if (options.platform !== 'app') {
(0, uni_cli_shared_1.output)('error', uni_cli_shared_1.M['uvue.unsupported'].replace('{platform}', options.platform));
return process.exit(0);
}
(0, easycom_1.initEasycom)();
const watcher = (await buildUVue(options));
let isFirstStart = true;
let isFirstEnd = true;
watcher.on('event', async (event) => {
if (event.code === 'BUNDLE_START') {
if (isFirstStart) {
isFirstStart = false;
return;
}
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.start']);
// 重置一下,uts编译报错会导致下一次开始差量编译紧接着上一次的差量编译,导致无法正常输出
(0, uni_cli_shared_1.resetOutput)('log');
}
else if (event.code === 'BUNDLE_END') {
event.result.close();
const dex = process.env.UNI_APP_UTS_CHANGED_FILES;
process.env.UNI_APP_UTS_CHANGED_FILES = '';
if (isFirstEnd) {
// 首次全量同步
isFirstEnd = false;
(0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
(0, utils_1.printStartupDuration)((0, vite_1.createLogger)(options.logLevel), false);
await (0, action_1.stopProfiler)((message) => (0, vite_1.createLogger)(options.logLevel).info(message));
return;
}
if (dex) {
const files = JSON.parse(dex);
if (!files.length) {
// 本次无变动,重要:这里的打印信息,HBuilderX也会用到,如果调整了文案,需要同步调整HBuilderX的文案
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['uvue.dev.watching.end.empty']);
}
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end.files'].replace('{files}', JSON.stringify(files)));
}
return (0, uni_cli_shared_1.output)('log', uni_cli_shared_1.M['dev.watching.end']);
}
else if (event.code === 'ERROR') {
if ((0, uni_cli_shared_1.runByHBuilderX)()) {
setTimeout(() => {
console.error(`Build failed with errors.`);
}, 50); // 目前需要延迟50ms执行,因为莫名其妙的这个setTimeout执行会比createStderrListener里边创建的setTimeout更早执行
}
}
});
}
exports.runUVueAndroidDev = runUVueAndroidDev;
async function runUVueAndroidBuild(options) {
try {
(0, uni_cli_shared_1.initEasycomsOnce)(process.env.UNI_INPUT_DIR, {
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
platform: process.env.UNI_PLATFORM,
isX: true,
});
await buildUVue(options);
await (0, action_1.stopProfiler)((message) => (0, vite_1.createLogger)(options.logLevel).info(message));
console.log(uni_cli_shared_1.M['build.done']);
// 开发者可能用了三方插件,三方插件有可能阻止退出,导致HBuilderX打包状态识别不正确
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
process.exit(0);
}
}
catch (e) {
if (e.customPrint) {
e.customPrint();
}
else {
console.error(e.message || e);
}
console.error(`Build failed with errors.`);
process.exit(1);
}
}
exports.runUVueAndroidBuild = runUVueAndroidBuild;
/**
* 目前的简易实现逻辑
* node层:
* 1. 监听项目,生成资源到临时目录 .uts/android
* 2. uvue 文件,做解析,拆分生成 render.kt, css.kt, uts.uvue
* 3. static 文件,copy 到最终目录
* 4. uvue、vue、uts 文件发生变化,调用 uts 编译器
* @param options
*/
async function buildUVue(options) {
return (0, build_1.buildByVite)((0, utils_1.addConfigFile)((0, shared_1.extend)({ nvueAppService: true, uvue: true }, (0, build_1.initBuildOptions)(options, (0, utils_1.cleanOptions)(options)))));
}
exports.buildUVue = buildUVue;
@@ -0,0 +1,3 @@
import type { UserConfig } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare function createBuild(options: VitePluginUniResolvedOptions, config: UserConfig): UserConfig['build'];
@@ -0,0 +1,68 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createBuild = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const shared_1 = require("@vue/shared");
function createBuild(options, config) {
(0, uni_cli_shared_1.initEasycomsOnce)(options.inputDir, {
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
platform: process.env.UNI_PLATFORM,
isX: process.env.UNI_APP_X === 'true',
});
const rollupOutputOption = config.build?.rollupOptions?.output;
const sourcemap = process.env.UNI_APP_SOURCEMAP === 'true'
? 'hidden'
: config.build?.sourcemap;
/**
* arkts编译器处理字符串模板内使用逗号操作符时有问题,禁用 reduce_vars 减少产出此类代码
* 如下代码在 arkts 内编译报错,Error Message: Unexpected token, expected '}'.
* function test () {
* return 0
* }
* let n: number = 0
* console.log(`${n = test(), n === 0 ? 0 : 1}px`)
*/
const isHarmonyArkTs = process.env.UNI_UTS_PLATFORM === 'app-harmony' &&
process.env.UNI_APP_X_HARMONY_SCRIPT_ENGINE !== 'jsvm';
return {
sourcemap,
cssTarget: uni_cli_shared_1.cssTarget,
chunkSizeWarningLimit: 100000000,
minify: config.build && (0, shared_1.hasOwn)(config.build, 'minify')
? config.build.minify
: process.env.NODE_ENV === 'production'
? 'terser'
: false,
terserOptions: process.env.NODE_ENV !== 'production'
? { compress: { drop_console: false, reduce_vars: !isHarmonyArkTs } }
: isHarmonyArkTs
? { compress: { reduce_vars: false } }
: undefined,
rollupOptions: {
onwarn(warning, warn) {
if (warning.code === 'EMPTY_BUNDLE') {
// 忽略空包警告,通常是条件编译之类导致的
// Generated an empty chunk:
return;
}
if (warning.code === 'UNUSED_EXTERNAL_IMPORT') {
const { message } = warning;
// ignore
if (message.includes('"vue"') ||
message.includes('"resolveComponent"') ||
message.includes('"@dcloudio/uni-h5"')) {
return;
}
}
warn(warning);
},
output: {
sourcemapExcludeSources: !(0, shared_1.isArray)(rollupOutputOption) &&
rollupOutputOption?.sourcemapExcludeSources === false
? false
: process.env.UNI_APP_SOURCEMAP === 'true',
},
},
};
}
exports.createBuild = createBuild;
@@ -0,0 +1,3 @@
import type { UserConfig } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare function createCss(options: VitePluginUniResolvedOptions, config: UserConfig): UserConfig['css'];
+32
View File
@@ -0,0 +1,32 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createCss = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function resolveAdditionalData(inputDir, config) {
const uniScssFile = path_1.default.resolve(inputDir, 'uni.scss');
const userAdditionalData = config.css?.preprocessorOptions?.scss?.additionalData || '';
if (!fs_extra_1.default.existsSync(uniScssFile)) {
return userAdditionalData;
}
let content = fs_extra_1.default.readFileSync(uniScssFile, 'utf8');
if (content.includes('#endif')) {
content = (0, uni_cli_shared_1.preCss)(content, uniScssFile);
}
return content + '\n' + userAdditionalData;
}
function createCss(options, config) {
return {
preprocessorOptions: {
scss: {
charset: false,
additionalData: resolveAdditionalData(options.inputDir, config),
},
},
};
}
exports.createCss = createCss;
@@ -0,0 +1,3 @@
import type { UserConfig } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare function createDefine(_: VitePluginUniResolvedOptions): UserConfig['define'];
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createDefine = void 0;
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function createDefine(_) {
const isX = process.env.UNI_APP_X === 'true';
return (0, shared_1.extend)({
// uni-app x 不支持 vue-i18n 基于运行时 render 的内置组件和 Legacy API
__VUE_I18N_FULL_INSTALL__: !isX,
__VUE_I18N_LEGACY_API__: !isX,
__VUE_I18N_PROD_DEVTOOLS__: false,
__INTLIFY_PROD_DEVTOOLS__: false,
__INTLIFY_DROP_MESSAGE_COMPILER__: false,
}, (0, uni_cli_shared_1.initDefine)());
}
exports.createDefine = createDefine;
@@ -0,0 +1,3 @@
import type { Plugin } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare function createConfig(options: VitePluginUniResolvedOptions, _uniPlugins: Plugin[]): Plugin['config'];
@@ -0,0 +1,52 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createConfig = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const css_1 = require("./css");
const resolve_1 = require("./resolve");
const build_1 = require("./build");
const optimizeDeps_1 = require("./optimizeDeps");
const define_1 = require("./define");
function createConfig(options, _uniPlugins) {
return (config, env) => {
options.command = env.command;
let base = config.base;
if (!base) {
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(options.inputDir);
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifestJson, 'h5');
base = (h5 && h5.router && h5.router.base) || '';
}
if (!base) {
base = '/';
}
options.base = base;
const pluginConfig = {
base: process.env.UNI_H5_BASE || base,
root: process.env.VITE_ROOT_DIR,
// TODO 临时设置为__static__,屏蔽警告:https://github.com/vitejs/vite/blob/824d042535033a5c3d7006978c0d05c201cd1c25/packages/vite/src/node/server/middlewares/transform.ts#L125
publicDir: config.publicDir || '__static__',
define: (0, define_1.createDefine)(options),
resolve: (0, resolve_1.createResolve)(options, config),
logLevel: config.logLevel || 'warn', // 默认使用 warn 等级,因为 info 等级vite:report 会输出文件列表等信息
optimizeDeps: (0, optimizeDeps_1.createOptimizeDeps)(options),
build: (0, build_1.createBuild)(options, config),
css: (0, css_1.createCss)(options, config),
esbuild: {
include: (0, uni_cli_shared_1.isUniAppXStandardScriptSupported)()
? /(?:\.(?:tsx?|jsx)$|[?&]lang\.(?:tsx?|jsx)(?:&|$))/
: /(?:\.(?:tsx?|jsx|uts)$|[?&]lang\.(?:tsx?|jsx|uts)(?:&|$))/,
exclude: /\.js$/,
loader: 'ts',
},
};
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
pluginConfig.cacheDir = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../../cache/.vite');
}
return pluginConfig;
};
}
exports.createConfig = createConfig;
@@ -0,0 +1,3 @@
import type { UserConfig } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare function createOptimizeDeps(_options: VitePluginUniResolvedOptions): UserConfig['optimizeDeps'];
@@ -0,0 +1,20 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createOptimizeDeps = void 0;
function createOptimizeDeps(_options) {
return {
exclude: [
'vue',
'vuex',
'vue-i18n',
'vue-router',
'@dcloudio/uni-app',
'@dcloudio/uni-components',
'@dcloudio/uni-i18n',
'@dcloudio/uni-shared',
'@dcloudio/uni-stacktracey',
'pinia',
],
};
}
exports.createOptimizeDeps = createOptimizeDeps;
@@ -0,0 +1,4 @@
import type { ResolverFunction, UserConfig } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare const customResolver: ResolverFunction;
export declare function createResolve(options: VitePluginUniResolvedOptions, _config: UserConfig): UserConfig['resolve'];
@@ -0,0 +1,84 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createResolve = exports.customResolver = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function resolveUTSModuleProxyFile(id, importer) {
const file = (0, uni_cli_shared_1.resolveUTSAppModule)(process.env.UNI_UTS_PLATFORM, id, importer);
if (file) {
// app-js 脚本入口直接交给对应的 Vite 编译器,不需要 uts-proxy。
if (file.endsWith('.uts') || file.endsWith('.ts') || file.endsWith('.js')) {
return file;
}
return file + '?uts-proxy';
}
}
const customResolver = function (updatedId, importer, resolveOptions) {
const independentRoot = (0, uni_cli_shared_1.resolveIndependentRoot)(updatedId, importer, process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
updatedId = (0, uni_cli_shared_1.withoutIndependentRoot)(updatedId);
const filename = updatedId.split('?')[0];
if ((0, uni_cli_shared_1.isUniAppXStandardScriptSupported)() && filename.endsWith('.json')) {
// alias 先于用户 pre 插件执行,JSON 需要重新进入插件链,才能根据 UTS/TS/JS 导入方分流。
return this.resolve(updatedId, importer, {
...resolveOptions,
skipSelf: true,
}).then((resolved) => {
if (!resolved || resolved.external) {
return resolved;
}
return {
...resolved,
id: (0, uni_cli_shared_1.withIndependentRootIfNeeded)(uni_cli_shared_1.isWindows ? (0, uni_cli_shared_1.normalizePath)(resolved.id) : resolved.id, independentRoot, process.env.UNI_INPUT_DIR),
};
});
}
updatedId = filename;
const utsImporter = importer
? path_1.default.dirname(importer)
: process.env.UNI_INPUT_DIR;
const utsModuleFile = process.env.UNI_PLATFORM === 'app' ||
process.env.UNI_PLATFORM === 'app-harmony'
? resolveUTSModuleProxyFile(updatedId, utsImporter)
: (0, uni_cli_shared_1.resolveUTSModule)(updatedId, utsImporter);
if (utsModuleFile) {
return (0, uni_cli_shared_1.withIndependentRootIfNeeded)(uni_cli_shared_1.isWindows ? (0, uni_cli_shared_1.normalizePath)(utsModuleFile) : utsModuleFile, independentRoot, process.env.UNI_INPUT_DIR);
}
const resolveId = (0, uni_cli_shared_1.resolveEncryptUniModule)((0, uni_cli_shared_1.normalizePath)(updatedId), process.env.UNI_UTS_PLATFORM, process.env.UNI_APP_X === 'true');
if (resolveId) {
return (0, uni_cli_shared_1.withIndependentRootIfNeeded)(resolveId, independentRoot, process.env.UNI_INPUT_DIR);
}
const resolvedId = (0, uni_cli_shared_1.requireResolve)(updatedId, importer || process.env.UNI_INPUT_DIR);
return (0, uni_cli_shared_1.withIndependentRootIfNeeded)(uni_cli_shared_1.isWindows ? (0, uni_cli_shared_1.normalizePath)(resolvedId) : resolvedId, independentRoot, process.env.UNI_INPUT_DIR);
};
exports.customResolver = customResolver;
function createResolve(options, _config) {
const alias = [];
if ((0, uni_cli_shared_1.isNormalCompileTarget)()) {
// 加密组件内部使用的 vue export helper,需要重新映射回来
alias.push({
find: 'plugin-vue:export-helper',
replacement: '\0plugin-vue:export-helper',
});
}
return {
// 必须使用alias解析,插件定制的resolveId,不会被应用到css等预处理器中
alias: [
// because @rollup/plugin-alias' type doesn't allow function
// replacement, but its implementation does work with function values.
{
find: /^(~@|@)\/(.*)/,
replacement(_str, _$1, $2) {
return (0, uni_cli_shared_1.normalizePath)(path_1.default.resolve(options.inputDir, $2));
},
customResolver: exports.customResolver,
},
...alias,
],
extensions: process.env.UNI_APP_X === 'true' ? uni_cli_shared_1.uni_app_x_extensions : uni_cli_shared_1.extensions,
preserveSymlinks: true,
};
}
exports.createResolve = createResolve;
@@ -0,0 +1,2 @@
import type { ResolvedConfig } from 'vite';
export declare function initEnv(config: ResolvedConfig): void;
@@ -0,0 +1,31 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initEnv = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function initEnv(config) {
if (!process.env.UNI_PLATFORM) {
process.env.UNI_PLATFORM = 'h5';
}
if (!process.env.UNI_CLI_CONTEXT) {
process.env.UNI_CLI_CONTEXT = process.cwd();
}
if (!process.env.UNI_INPUT_DIR) {
process.env.UNI_INPUT_DIR = path_1.default.resolve(config.root, 'src');
}
if (!process.env.UNI_OUTPUT_DIR) {
process.env.UNI_OUTPUT_DIR = path_1.default.resolve(config.root, config.build.outDir);
}
process.env.VUE_APP_DARK_MODE =
(0, uni_cli_shared_1.getPlatformManifestJsonOnce)().darkmode || false;
process.env.BROWSERSLIST_CONFIG = [
path_1.default.resolve(process.env.UNI_INPUT_DIR, '.browserslistrc'),
path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'package.json'),
path_1.default.resolve(process.cwd(), 'package.json'),
].find((file) => fs_1.default.existsSync(file));
}
exports.initEnv = initEnv;
@@ -0,0 +1,7 @@
import type { Logger, Plugin } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare function createConfigResolved(options: VitePluginUniResolvedOptions): Plugin['configResolved'];
export declare function initLogger({ logger, nvue, }: {
logger: Logger;
nvue?: boolean;
}): Logger;
@@ -0,0 +1,62 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initLogger = exports.createConfigResolved = void 0;
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const env_1 = require("./env");
const options_1 = require("./options");
const plugins_1 = require("./plugins");
const resolve_1 = require("../config/resolve");
function createConfigResolved(options) {
return (config) => {
// 如果是混合编译且是 nvue 时,部分逻辑无需执行
if (!(0, uni_cli_shared_1.isInHybridNVue)(config)) {
(0, env_1.initEnv)(config);
}
initLogger(config);
(0, options_1.initOptions)(options, config);
(0, plugins_1.initPlugins)(config, options);
if (!(0, uni_cli_shared_1.isInHybridNVue)(config)) {
initCheckUpdate();
}
if (uni_cli_shared_1.isWindows) {
// TODO 等 https://github.com/vitejs/vite/issues/3331 修复后,可以移除下列代码
// 2.8.0 已修复,但为了兼容旧版本,先不移除
const item = config.resolve.alias.find((item) => !(0, shared_1.isString)(item.find) ? item.find.test('@/') : false);
if (item) {
item.customResolver = resolve_1.customResolver;
}
}
};
}
exports.createConfigResolved = createConfigResolved;
function initCheckUpdate() {
(0, uni_cli_shared_1.checkUpdate)({
inputDir: process.env.UNI_INPUT_DIR,
compilerVersion: process.env.UNI_COMPILER_VERSION,
versionType: process.env.UNI_COMPILER_VERSION_TYPE,
});
}
function initLogger({ logger, nvue, }) {
const { info, warn, error } = logger;
logger.info = (msg, opts) => {
msg = (0, uni_cli_shared_1.formatInfoMsg)(msg, (0, shared_1.extend)(opts || {}, { nvue }));
if (msg) {
return info(msg, opts);
}
};
logger.warn = (msg, opts) => {
msg = (0, uni_cli_shared_1.formatWarnMsg)(msg, opts);
if (msg) {
return warn(msg, opts);
}
};
logger.error = (msg, opts) => {
msg = (0, uni_cli_shared_1.formatErrMsg)(msg, opts);
if (msg) {
return error(msg, opts);
}
};
return logger;
}
exports.initLogger = initLogger;
@@ -0,0 +1,3 @@
import type { VitePluginUniResolvedOptions } from '..';
import type { ResolvedConfig } from 'vite';
export declare function initOptions(options: VitePluginUniResolvedOptions, config: ResolvedConfig): void;
@@ -0,0 +1,15 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initOptions = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function resolveBase() {
const manifest = (0, uni_cli_shared_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
const webManifest = (0, uni_cli_shared_1.getPlatformManifestJson)(manifest, 'h5');
return (webManifest && webManifest.router && webManifest.router.base) || '/';
}
function initOptions(options, config) {
options.base = resolveBase();
options.outputDir = process.env.UNI_OUTPUT_DIR;
options.assetsDir = config.build.assetsDir;
}
exports.initOptions = initOptions;
@@ -0,0 +1,8 @@
import type { ResolvedConfig } from 'vite';
import type { FilterPattern } from '@rollup/pluginutils';
import type { VitePluginUniResolvedOptions } from '../..';
export interface UniPluginFilterOptions extends VitePluginUniResolvedOptions {
include?: FilterPattern;
exclude?: FilterPattern;
}
export declare function initPlugins(config: ResolvedConfig, options: VitePluginUniResolvedOptions): void;
@@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initPlugins = void 0;
// import debug from 'debug'
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const json_1 = require("./json");
const preCss_1 = require("./preCss");
const static_1 = require("./static");
const preVue_1 = require("./preVue");
const ssr_1 = require("./ssr");
const resolveId_1 = require("./resolveId");
const UNI_H5_RE = /@dcloudio\/uni-h5/;
function initPlugins(config, options) {
const uniPrePluginOptions = {
exclude: [...uni_cli_shared_1.COMMON_EXCLUDE, UNI_H5_RE],
};
const uniPreCssPluginOptions = {
exclude: [...uni_cli_shared_1.COMMON_EXCLUDE],
};
const plugins = config.plugins;
addPlugin(plugins, (0, resolveId_1.uniResolveIdPlugin)(options), 'vite:resolve', 'pre');
addPlugin(plugins, (0, uni_cli_shared_1.uniPrePlugin)(config, (0, shared_1.extend)(uniPrePluginOptions, options)), 0, 'pre');
addPlugin(plugins, (0, preCss_1.uniPreCssPlugin)(config, (0, shared_1.extend)(uniPreCssPluginOptions, options)), 'vite:css');
addPlugin(plugins, (0, preVue_1.uniPreVuePlugin)(), 'vite:vue', 'pre');
addPlugin(plugins, (0, ssr_1.uniSSRPlugin)(config, (0, shared_1.extend)({ exclude: [...uni_cli_shared_1.COMMON_EXCLUDE, /\/@dcloudio\/uni-app/] }, options)), process.env.UNI_APP_X === 'true' ? 'uts' : 'vite:vue');
addPlugin(plugins, (0, json_1.uniJsonPlugin)(options), 'vite:json', 'pre');
addPlugin(plugins, (0, static_1.uniStaticPlugin)(options, config), 'vite:asset', 'pre');
if ((0, uni_cli_shared_1.resolveHBuilderXPluginPath)('uni_helpers') && (0, uni_cli_shared_1.isNormalCompileTarget)()) {
try {
const { V } = (0, uni_cli_shared_1.requireUniHelpers)();
addPlugin(plugins, V({
dir: process.env.UNI_INPUT_DIR,
cacheDir: process.env.UNI_MODULES_ENCRYPT_CACHE_DIR,
}), 0, 'pre');
}
catch (e) { }
}
if (!(0, uni_cli_shared_1.runByHBuilderX)() && process.env.UNI_PLATFORM === 'mp-weixin') {
try {
const { PreprocessorVitePlugin, } = require('@dcloudio/uni-cli-shared/lib/preprocessor');
addPlugin(plugins, PreprocessorVitePlugin(), 0, 'pre');
}
catch (e) { }
}
// if (process.env.DEBUG) {
// debugPlugin(plugins.length)
// debugPlugin(plugins.map((p) => (p as Plugin).name))
// }
}
exports.initPlugins = initPlugins;
function addPlugin(plugins, plugin, index, type = 'post') {
if ((0, shared_1.isString)(index)) {
index = plugins.findIndex((plugin) => plugin.name === index);
}
return plugins.splice(index + (type === 'pre' ? 0 : 1), 0, plugin);
}
@@ -0,0 +1,3 @@
import type { Plugin } from 'vite';
import type { VitePluginUniResolvedOptions } from '../..';
export declare function uniJsonPlugin(options: VitePluginUniResolvedOptions): Plugin;
@@ -0,0 +1,33 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniJsonPlugin = void 0;
const jsonc_parser_1 = require("jsonc-parser");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const jsonExtRE = /\.json($|\?)(?!commonjs-proxy)/;
const SPECIAL_QUERY_RE = /[\?&](?:worker|sharedworker|raw|url)\b/;
function uniJsonPlugin(options) {
return {
name: 'uni:json',
transform(code, id) {
if (!jsonExtRE.test(id))
return null;
if (SPECIAL_QUERY_RE.test(id))
return null;
if (id.endsWith('.json.js'))
return null;
// preprocess
if (code.includes('#endif')) {
code = (0, uni_cli_shared_1.preJs)(code, id);
}
let jsonObj = (0, jsonc_parser_1.parse)(code);
if ((0, uni_cli_shared_1.isUniAppLocaleFile)(id)) {
jsonObj = jsonObj.common || {};
}
return {
code: JSON.stringify(jsonObj),
map: null,
};
},
};
}
exports.uniJsonPlugin = uniJsonPlugin;
@@ -0,0 +1,7 @@
import type { Plugin, ResolvedConfig } from 'vite';
import type { UniPluginFilterOptions } from '.';
/**
* preprocess css
* @param options
*/
export declare function uniPreCssPlugin(config: ResolvedConfig, options: UniPluginFilterOptions): Plugin;
@@ -0,0 +1,43 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPreCssPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const pluginutils_1 = require("@rollup/pluginutils");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugPre = (0, debug_1.default)('uni:pre-css');
// const debugPreTry = debug('uni:pre-css-try')
const cssLangs = `\\.(css|less|sass|scss|styl|stylus|postcss)($|\\?)`;
const cssLangRE = new RegExp(cssLangs);
/**
* preprocess css
* @param options
*/
function uniPreCssPlugin(config, options) {
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
const isNVue = config.nvue;
const preJsFile = isNVue ? uni_cli_shared_1.preNVueJs : uni_cli_shared_1.preJs;
return {
name: 'uni:pre-css',
transform(code, id) {
if (!cssLangRE.test(id)) {
return;
}
if (!filter(id)) {
return;
}
// debugPreTry(id)
if (!code.includes('#endif')) {
return;
}
debugPre(id);
return {
code: preJsFile(code, id),
map: (0, uni_cli_shared_1.withSourcemap)(config) ? this.getCombinedSourcemap() : null,
};
},
};
}
exports.uniPreCssPlugin = uniPreCssPlugin;
@@ -0,0 +1,2 @@
import type { Plugin } from 'vite';
export declare function uniPreVuePlugin(): Plugin;
@@ -0,0 +1,40 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniPreVuePlugin = void 0;
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function uniPreVuePlugin() {
let isNVue = false;
return {
name: 'uni:pre-vue',
config(config) {
isNVue = config.nvue;
},
async transform(code, id) {
const { filename, query } = (0, uni_cli_shared_1.parseVueRequest)(id);
if (query.vue) {
return;
}
if (!(process.env.UNI_APP_X === 'true' ? uni_cli_shared_1.X_EXTNAME_VUE : uni_cli_shared_1.EXTNAME_VUE).includes(path_1.default.extname(filename))) {
return;
}
// 清空当前页面已缓存的 filter 信息
(0, uni_cli_shared_1.clearMiniProgramTemplateFilter)((0, uni_cli_shared_1.removeExt)((0, uni_cli_shared_1.normalizeMiniProgramFilename)(id, process.env.UNI_INPUT_DIR)));
if (process.env.UNI_APP_X_DOM2 === 'true' &&
process.env.UNI_INPUT_DIR &&
(0, uni_cli_shared_1.isUniPageFile)(filename)) {
// dom2 页面模板编译会读取 pages.json 中的页面配置,
// 需要让 pages.json 变更时重新 transform 页面,避免复用旧模板产物。
this.addWatchFile(path_1.default.resolve(process.env.UNI_INPUT_DIR, 'pages.json'));
}
return {
code: (0, uni_cli_shared_1.parseVueCode)(code, isNVue).code, // 暂不提供sourcemap,意义不大
map: null,
};
},
};
}
exports.uniPreVuePlugin = uniPreVuePlugin;
@@ -0,0 +1,17 @@
import type { Plugin } from 'vite';
import type { VitePluginUniResolvedOptions } from '../..';
declare const BUILT_IN_MODULES: {
'vue-router': string;
vuex: string;
'vue-i18n': string;
'@dcloudio/uni-app': string;
'@dcloudio/uni-cloud': string;
'@dcloudio/uni-i18n': string;
'@dcloudio/uni-shared': string;
'@dcloudio/uni-stacktracey': string;
'@vue/shared': string;
pinia: string;
};
export type BuiltInModulesKey = keyof typeof BUILT_IN_MODULES;
export declare function uniResolveIdPlugin(options: VitePluginUniResolvedOptions): Plugin;
export {};
@@ -0,0 +1,82 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniResolveIdPlugin = void 0;
const path_1 = __importDefault(require("path"));
// import debug from 'debug'
const fs_extra_1 = __importDefault(require("fs-extra"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
// const debugResolve = debug('uni:resolve-id')
let isPiniaVersion3 = false;
try {
isPiniaVersion3 =
Number(fs_extra_1.default
.readJSONSync(path_1.default.join((0, uni_cli_shared_1.resolveBuiltIn)('pinia/package.json')))
.version.split('.')[0]) >= 3;
}
catch (error) { }
const BUILT_IN_MODULES = {
'vue-router': 'dist/vue-router.esm-bundler.js',
vuex: 'dist/vuex.esm-bundler.js',
'vue-i18n': 'dist/vue-i18n.esm-bundler.js',
'@dcloudio/uni-app': 'dist/uni-app.es.js',
'@dcloudio/uni-cloud': 'dist/uni-cloud.es.js',
'@dcloudio/uni-i18n': 'dist/uni-i18n.es.js',
'@dcloudio/uni-shared': 'dist/uni-shared.es.js',
'@dcloudio/uni-stacktracey': 'dist/uni-stacktracey.es.js',
'@vue/shared': 'dist/shared.esm-bundler.js',
pinia: isPiniaVersion3 ? '' : 'dist/pinia.mjs',
};
function uniResolveIdPlugin(options) {
const resolveCache = {};
const isX = process.env.UNI_APP_X === 'true';
const isVapor = process.env.UNI_APP_X_VAPOR === 'true';
const builtInAliases = isX
? {
...(0, uni_cli_shared_1.resolveVueI18nAlias)(),
...(0, uni_cli_shared_1.resolvePiniaAlias)(),
}
: {};
if ((0, uni_cli_shared_1.isUniAppXWebVapor)()) {
builtInAliases['vue-router'] = (0, uni_cli_shared_1.resolveWebVaporPackage)('vue-router/dist/vue-router.js');
}
if (isX) {
BUILT_IN_MODULES['@dcloudio/uni-app'] = 'dist-x/uni-app.es.js';
BUILT_IN_MODULES['@dcloudio/uni-cloud'] = isVapor
? 'dist/uni-cloud-x-vapor.es.js'
: 'dist/uni-cloud-x.es.js';
}
return {
name: 'uni:resolve-id',
resolveId(id, importer) {
if (isX && process.env.UNI_UTS_PLATFORM.startsWith('mp-')) {
// TODO 优化此逻辑,目前unicloud-db等内置组件依赖UTSJSONObject时会自动引用tslib,此处逻辑防止内置组件引用插件内置tslib
if (id === 'tslib') {
return '\0tslib.js';
}
}
const cache = resolveCache[id];
if (cache) {
// debugResolve('cache', id, cache)
return cache;
}
if (builtInAliases[id]) {
return (resolveCache[id] = builtInAliases[id]);
}
if (isX && (id === 'vue-i18n' || id === 'pinia')) {
// 未返回内置别名表示项目已安装依赖,应交给 Vite 继续解析,不能回退到 CLI 内置旧版本。
return;
}
if (BUILT_IN_MODULES[id]) {
// 模块 ID 必须使用正斜杠,否则 Windows 会绕过 module-alias 的包名前缀匹配。
return (resolveCache[id] = (0, uni_cli_shared_1.resolveBuiltIn)(path_1.default.posix.join(id, BUILT_IN_MODULES[id])));
}
if (process.env.UNI_PLATFORM !== 'app') {
return (0, uni_cli_shared_1.resolveUTSModule)(id, importer ? path_1.default.dirname(importer) : process.env.UNI_INPUT_DIR);
}
},
};
}
exports.uniResolveIdPlugin = uniResolveIdPlugin;
@@ -0,0 +1,3 @@
import type { Plugin, ResolvedConfig } from 'vite';
import type { UniPluginFilterOptions } from '.';
export declare function uniSSRPlugin(config: ResolvedConfig, options: UniPluginFilterOptions): Plugin;
@@ -0,0 +1,63 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniSSRPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const crypto_1 = __importDefault(require("crypto"));
const estree_walker_1 = require("estree-walker");
const pluginutils_1 = require("@rollup/pluginutils");
const magic_string_1 = __importDefault(require("magic-string"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugSSR = (0, debug_1.default)('uni:ssr');
const KEYED_FUNC_RE = /(ssrRef|shallowSsrRef)/;
function uniSSRPlugin(config, options) {
const filter = (0, pluginutils_1.createFilter)(options.include, options.exclude);
return {
name: 'uni:ssr:ref',
transform(code, id) {
if (!filter(id))
return null;
if (!KEYED_FUNC_RE.test(code)) {
return;
}
debugSSR('try', id);
const ast = this.parse(code);
const s = new magic_string_1.default(code);
(0, estree_walker_1.walk)(ast, {
enter(node) {
if (!(0, uni_cli_shared_1.isCallExpression)(node)) {
return;
}
const { callee, arguments: args } = node;
if (args.length !== 1) {
return;
}
const name = (0, uni_cli_shared_1.isIdentifier)(callee)
? callee.name
: (0, uni_cli_shared_1.isMemberExpression)(callee) && (0, uni_cli_shared_1.isIdentifier)(callee.property)
? callee.property.name
: '';
if (name !== 'ssrRef' && name !== 'shallowSsrRef') {
return;
}
const { end } = node;
const key = id + '-' + node.end;
debugSSR(key, name);
s.appendLeft(end - 1, ", '" + createKey(`${id}-${end}`) + "'");
},
});
return {
code: s.toString(),
map: (0, uni_cli_shared_1.withSourcemap)(config) ? s.generateMap().toString() : null,
};
},
};
}
exports.uniSSRPlugin = uniSSRPlugin;
function createKey(source) {
const hash = crypto_1.default.createHash('md5');
hash.update(source);
return hash.digest('base64').toString();
}
@@ -0,0 +1,9 @@
import type { Plugin, ResolvedConfig } from 'vite';
import type { UniPluginFilterOptions } from '.';
/**
* 提供static等目录静态资源加载
* @param _options
* @param config
* @returns
*/
export declare function uniStaticPlugin(_options: UniPluginFilterOptions, config: ResolvedConfig): Plugin;
@@ -0,0 +1,44 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniStaticPlugin = void 0;
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../../utils");
const debugStatic = (0, debug_1.default)('uni:static');
/**
* 提供static等目录静态资源加载
* @param _options
* @param config
* @returns
*/
function uniStaticPlugin(_options, config) {
const filter = (0, utils_1.createPublicFileFilter)();
return {
name: 'uni:static',
resolveId(id) {
if (!config.assetsInclude((0, uni_cli_shared_1.cleanUrl)(id))) {
return;
}
const publicFile = filter(id);
if (publicFile) {
debugStatic(id);
return id;
}
},
async load(id) {
if (!config.assetsInclude((0, uni_cli_shared_1.cleanUrl)(id))) {
return;
}
if (filter(id)) {
return `export default ${JSON.stringify(fileToUrl(id, config))}`;
}
},
};
}
exports.uniStaticPlugin = uniStaticPlugin;
function fileToUrl(id, config) {
return config.base + id.slice(1);
}
+28
View File
@@ -0,0 +1,28 @@
import type { Plugin, ResolvedConfig, ViteDevServer } from 'vite';
import type { Options as VueOptions } from '@vitejs/plugin-vue';
import type ViteLegacyPlugin from '@vitejs/plugin-legacy';
import type { VueJSXPluginOptions } from '@vue/babel-plugin-jsx';
import { type AutoImportOptions, type CopyOptions } from '@dcloudio/uni-cli-shared';
export type ViteLegacyOptions = Parameters<typeof ViteLegacyPlugin>[0];
export interface VitePluginUniOptions {
uvue?: boolean;
vueOptions?: VueOptions;
vueJsxOptions?: (VueJSXPluginOptions & {
babelPlugins?: any[];
}) | boolean;
viteLegacyOptions?: ViteLegacyOptions | false;
autoImportOptions?: AutoImportOptions;
}
export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
base: string;
command: ResolvedConfig['command'];
platform: UniApp.PLATFORM;
inputDir: string;
outputDir: string;
assetsDir: string;
devServer?: ViteDevServer;
copyOptions?: Required<CopyOptions>;
}
export { runDev, runBuild } from './cli/action';
export default function uniPlugin(rawOptions?: VitePluginUniOptions): Plugin[];
export declare function shouldMoveSourceMapFromCache(): boolean | "";
+200
View File
@@ -0,0 +1,200 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.shouldMoveSourceMapFromCache = exports.runBuild = exports.runDev = void 0;
const fs_1 = __importDefault(require("fs"));
const vite_1 = __importDefault(require("unplugin-auto-import/vite"));
const plugin_vue_jsx_1 = __importDefault(require("@vitejs/plugin-vue-jsx"));
const plugin_legacy_1 = __importDefault(require("@vitejs/plugin-legacy"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const config_1 = require("./config");
const configResolved_1 = require("./configResolved");
const copy_1 = require("./plugins/copy");
const move_1 = require("./plugins/move");
const utils_1 = require("./utils");
const vue_1 = require("./vue");
const utils_2 = require("./cli/utils");
const plugins_1 = require("./uvue/plugins");
const path_1 = __importDefault(require("path"));
const rewriteImportVue_1 = require("./uvue/plugins/rewriteImportVue");
var action_1 = require("./cli/action");
Object.defineProperty(exports, "runDev", { enumerable: true, get: function () { return action_1.runDev; } });
Object.defineProperty(exports, "runBuild", { enumerable: true, get: function () { return action_1.runBuild; } });
let isFirst = true;
function uniPlugin(rawOptions = {}) {
// 重写readFileSync,拦截.scss 等文件读取,实现条件编译,
(0, uni_cli_shared_1.rewriteScssReadFileSync)();
if ((0, uni_cli_shared_1.isInHBuilderX)()) {
(0, uni_cli_shared_1.rewriteExistsSyncHasRootFile)();
}
// 三方插件(如vitest)可能提供了自己的入口命令,需要补充 env 初始化逻辑
(0, utils_2.initEnv)('unknown', { platform: process.env.UNI_PLATFORM || 'h5' });
const options = {
...rawOptions,
base: '/',
assetsDir: 'assets',
inputDir: '',
outputDir: '',
command: 'serve',
platform: 'h5',
};
options.platform = process.env.UNI_PLATFORM || 'h5';
options.inputDir = process.env.UNI_INPUT_DIR;
const plugins = (0, uni_cli_shared_1.isUniAppXAndroidNative)()
? createUVueAndroidPlugins(options)
: createPlugins(options);
// x 提供 auto import(非android、android自行处理)
if (process.env.UNI_APP_X === 'true' && !(0, uni_cli_shared_1.isUniAppXAndroidNative)()) {
plugins.unshift((0, vite_1.default)((0, uni_cli_shared_1.initAutoImportOptions)(process.env.UNI_UTS_PLATFORM, options.autoImportOptions || {})));
}
plugins.unshift((0, uni_cli_shared_1.uniJsonPlugin)());
if (process.env.UNI_APP_OUTPUT_FORMAT === 'esm') {
plugins.push((0, rewriteImportVue_1.rewriteImportVuePlugin)());
}
return plugins;
}
exports.default = uniPlugin;
function createPlugins(options) {
const plugins = [];
// 框架 ext-api 不需要 inject 本地 ext-api
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
// uni x 需要插入到指定位置,此插件执行太早,又会引发 vue 文件的不支持,该插件是解析ast的,所以必须是合法的js或ts代码
if (process.env.UNI_APP_X === 'true' &&
// iOS 暂不使用该机制
process.env.UNI_UTS_PLATFORM !== 'app-ios' &&
// harmony 同 iOS
process.env.UNI_UTS_PLATFORM !== 'app-harmony' &&
// Android Vapor 暂不使用该机制(只有 Android Native 会进入该方法,不需要额外判断)
process.env.UNI_UTS_PLATFORM !== 'app-android') {
plugins.push((0, uni_cli_shared_1.uniUTSExtApiReplace)());
}
else {
const injects = (0, uni_cli_shared_1.parseUniExtApisOnce)(true, process.env.UNI_UTS_PLATFORM, process.env.UNI_UTS_TARGET_LANGUAGE);
if (Object.keys(injects).length) {
plugins.push((0, uni_cli_shared_1.uniViteInjectPlugin)('uni:ext-api-inject', injects));
}
}
}
// 仅限 h5
if (options.viteLegacyOptions && options.platform === 'h5') {
plugins.push(...(0, plugin_legacy_1.default)((0, vue_1.initPluginViteLegacyOptions)(options)));
}
const uniPlugins = (0, utils_1.initExtraPlugins)(process.env.UNI_CLI_CONTEXT || process.cwd(), process.env.UNI_PLATFORM || 'h5', options);
// debugUni(uniPlugins)
const uniPluginOptions = (0, utils_1.initPluginUniOptions)(uniPlugins);
options.copyOptions = uniPluginOptions.copyOptions;
if (options.vueJsxOptions) {
plugins.push((0, plugin_vue_jsx_1.default)((0, vue_1.initPluginVueJsxOptions)(options, uniPluginOptions.compilerOptions, uniPluginOptions.jsxOptions)));
}
plugins.push({
name: 'uni',
config: (0, config_1.createConfig)(options, uniPlugins),
configResolved: (0, configResolved_1.createConfigResolved)(options),
});
plugins.push(...uniPlugins);
// plugins.push(...initFixedEsbuildInitTSConfck(process.env.UNI_INPUT_DIR))
// 执行 build 命令时,vite 强制了 NODE_ENV
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/build.ts#L405
// const config = await resolveConfig(inlineConfig, 'build', 'production')
// 在 @vitejs/plugin-vue 之前校正回来
if (process.env.UNI_NODE_ENV &&
process.env.UNI_NODE_ENV !== process.env.NODE_ENV) {
process.env.NODE_ENV = process.env.UNI_NODE_ENV;
}
plugins.unshift((0, vue_1.createPluginVueInstance)((0, vue_1.initPluginVueOptions)(options, uniPluginOptions)));
let addCopyPlugin = false;
if (options.platform !== 'app') {
addCopyPlugin = true;
}
else {
// 仅在 vue 或 纯原生 App.vue 编译时做 copy
if (process.env.UNI_COMPILER !== 'nvue' ||
(process.env.UNI_RENDERER === 'native' &&
process.env.UNI_RENDERER_NATIVE === 'appService')) {
addCopyPlugin = true;
}
else if (process.env.UNI_APP_X === 'true') {
// app-ios
addCopyPlugin = true;
}
}
// 之前限制的是只有标准编译目标才 copy,现在 ext-api 也需要 copy 资源,暂时只排除 uni_modules
if (process.env.UNI_COMPILE_TARGET === 'uni_modules') {
addCopyPlugin = false;
}
if (addCopyPlugin) {
plugins.push((0, copy_1.uniCopyPlugin)({
outputDir: process.env.UNI_OUTPUT_DIR,
copyOptions: options.copyOptions,
}));
}
if (process.env.UNI_APP_SOURCEMAP === 'true') {
// 清空之前的 sourcemap 目录
const sourceMapPath = (0, uni_cli_shared_1.resolveSourceMapPath)();
if (isFirst) {
// 避免重复清空
isFirst = false;
if (fs_1.default.existsSync(sourceMapPath)) {
(0, uni_cli_shared_1.emptyDir)(sourceMapPath);
}
if (shouldMoveSourceMapFromCache()) {
plugins.push((0, move_1.uniMovePlugin)({
apply: 'build',
enforce: 'post',
cwd: resolveSourceMapDirByCacheDir(),
pattern: '**/*.js.map',
dest: sourceMapPath,
}));
}
else {
plugins.push((0, move_1.uniMovePlugin)({
apply: 'build',
enforce: 'post',
cwd: process.env.UNI_OUTPUT_DIR,
pattern: '**/*.js.map',
dest: sourceMapPath,
}));
}
}
}
(0, utils_1.rewriteCompilerSfcParse)();
return plugins;
}
function createUVueAndroidPlugins(options) {
const plugins = [];
options.uvue = true;
const uniPlugins = (0, utils_1.initExtraPlugins)(process.env.UNI_CLI_CONTEXT || process.cwd(), process.env.UNI_PLATFORM || 'h5', options);
// debugUni(uniPlugins)
const uniPluginOptions = (0, utils_1.initPluginUniOptions)(uniPlugins);
options.copyOptions = uniPluginOptions.copyOptions;
plugins.push((0, plugins_1.uniUVuePlugin)(options));
plugins.push(...uniPlugins);
// plugins.push(...initFixedEsbuildInitTSConfck(process.env.UNI_INPUT_DIR))
// 执行 build 命令时,vite 强制了 NODE_ENV
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/build.ts#L405
// const config = await resolveConfig(inlineConfig, 'build', 'production')
// 在 @vitejs/plugin-vue 之前校正回来
if (process.env.UNI_NODE_ENV &&
process.env.UNI_NODE_ENV !== process.env.NODE_ENV) {
process.env.NODE_ENV = process.env.UNI_NODE_ENV;
}
if ((0, uni_cli_shared_1.isNormalCompileTarget)()) {
plugins.push((0, copy_1.uniCopyPlugin)({
outputDir: process.env.UNI_OUTPUT_DIR,
copyOptions: options.copyOptions,
}));
}
return plugins;
}
function resolveSourceMapDirByCacheDir() {
return path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR, 'sourcemap');
}
function shouldMoveSourceMapFromCache() {
return (process.env.UNI_APP_X === 'true' &&
process.env.UNI_APP_X_CACHE_DIR &&
process.env.NODE_ENV !== 'development' &&
((0, uni_cli_shared_1.isUniAppXIOS)() || (0, uni_cli_shared_1.isUniAppXAndroidJsEngine)()));
}
exports.shouldMoveSourceMapFromCache = shouldMoveSourceMapFromCache;
@@ -0,0 +1,4 @@
import type { Plugin } from 'vite';
import type { VitePluginUniResolvedOptions } from '..';
export declare function uniCopyPlugin({ outputDir, copyOptions, }: Pick<VitePluginUniResolvedOptions, 'outputDir' | 'copyOptions'>): Plugin;
export declare function isSameOrSubPath(filename: string, dir: string): boolean;
@@ -0,0 +1,156 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isSameOrSubPath = exports.uniCopyPlugin = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugCopy = (0, debug_1.default)('uni:copy');
function uniCopyPlugin({ outputDir, copyOptions, }) {
const staticDir = uni_cli_shared_1.PUBLIC_DIR + '/**/*';
const uniModulesStaticDir = 'uni_modules/*/' + uni_cli_shared_1.PUBLIC_DIR + '/**/*';
const isDom2 = process.env.UNI_APP_X_DOM2 === 'true';
const uniModulesCppDir = isDom2 ? 'uni_modules/*/cppsdk/**/*' : '';
const assets = [staticDir, uniModulesStaticDir];
const cppAssets = [];
if (uniModulesCppDir) {
cppAssets.push(uniModulesCppDir);
}
const subpackages = (0, uni_cli_shared_1.parseSubpackagesRootOnce)(process.env.UNI_INPUT_DIR, process.env.UNI_PLATFORM);
subpackages.forEach((root) => {
assets.push((0, uni_cli_shared_1.normalizePath)(path_1.default.join(root, staticDir)));
assets.push((0, uni_cli_shared_1.normalizePath)(path_1.default.join(root, uniModulesStaticDir)));
if (uniModulesCppDir) {
cppAssets.push((0, uni_cli_shared_1.normalizePath)(path_1.default.join(root, uniModulesCppDir)));
}
});
copyOptions.assets.forEach((asset) => {
assets.push(asset);
});
const inputDir = (0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR);
const inputDirGlob = (0, uni_cli_shared_1.pathToGlob)(inputDir, '');
const platform = process.env.UNI_PLATFORM;
const utsPlatform = process.env.UNI_UTS_PLATFORM;
// 非当前平台 static 目录
const ignorePlatformStaticDirs = createIgnorePlatformDirs(uni_cli_shared_1.PUBLIC_DIR, platform, utsPlatform);
// 非当前平台 cppsdk 目录
const ignorePlatformCppDirs = uniModulesCppDir
? createIgnorePlatformDirs('cppsdk', platform, utsPlatform)
: [];
const targets = [
{
src: assets,
dest: outputDir,
watchOptions: {
readyTimeout: getReadyTimeout(),
ignored(path) {
const normalizedPath = (0, uni_cli_shared_1.normalizePath)(path);
if (ignorePlatformStaticDirs.find((dir) =>
// dir都是以 / 结尾,所以这里也要以 / 结尾
(normalizedPath + '/').includes(dir))) {
return fs_1.default.statSync(normalizedPath).isDirectory();
}
// 应该是软链
if (!isSameOrSubPath(normalizedPath, inputDir) &&
!isSameOrSubPath(normalizedPath, inputDirGlob) &&
// glob 转义会使 chokidar 从项目上级目录开始遍历,不能忽略这些目录
!isSameOrSubPath(inputDir, normalizedPath)) {
// 目前仅简单处理static
if (normalizedPath.includes('/static/')) {
return false;
}
return true;
}
return false;
},
},
},
];
targets.push(...copyOptions.targets);
if (process.env.UNI_APP_X_DOM2_CPP_DIR && cppAssets.length) {
targets.push({
src: cppAssets,
dest: process.env.UNI_APP_X_DOM2_CPP_DIR,
watchOptions: {
readyTimeout: getReadyTimeout(),
ignored(path) {
const normalizedPath = (0, uni_cli_shared_1.normalizePath)(path);
if (ignorePlatformCppDirs.find((dir) =>
// dir都是以 / 结尾,所以这里也要以 / 结尾
(normalizedPath + '/').includes(dir))) {
return fs_1.default.statSync(normalizedPath).isDirectory();
}
return false;
},
},
});
}
debugCopy(targets);
checkIgnoreStatic(ignorePlatformStaticDirs.map((dir) => dir.substring(1).split('/')));
return (0, uni_cli_shared_1.uniViteCopyPlugin)({
targets,
});
}
exports.uniCopyPlugin = uniCopyPlugin;
function isSameOrSubPath(filename, dir) {
filename = (0, uni_cli_shared_1.normalizePath)(filename);
dir = (0, uni_cli_shared_1.normalizePath)(dir);
return (filename === dir || filename.startsWith(dir.endsWith('/') ? dir : dir + '/'));
}
exports.isSameOrSubPath = isSameOrSubPath;
let isIgnoreChecked = false;
function checkIgnoreStatic(ignoreStatic) {
if (isIgnoreChecked) {
return;
}
isIgnoreChecked = true;
const existIgnore = new Set();
ignoreStatic.forEach((ignore) => {
const dir = path_1.default.resolve(process.env.UNI_INPUT_DIR, ...ignore);
if (fs_1.default.existsSync(dir)) {
existIgnore.add(ignore.join('/'));
}
});
if (existIgnore.size) {
console.log('已忽略静态资源目录:' +
[...existIgnore].join('、') +
'。详见:https://uniapp.dcloud.net.cn/tutorial/platform.html#static');
}
}
function getReadyTimeout() {
// chokidar 在部分 windows 上 ready 会触发较早,导致文件还没被全部 copy 过去
if (!uni_cli_shared_1.isWindows) {
return 1000;
}
if (process.env.NODE_ENV === 'development') {
return 1000;
}
// 仅在生产环境使用
return 4000;
}
function createIgnorePlatformDirs(dir, platform, utsPlatform) {
return ((0, uni_cli_shared_1.getPlatforms)()
.filter((p) => {
if (platform === 'app') {
if (process.env.UNI_APP_X === 'true') {
if (p === 'app-android' || p === 'app-ios' || p === 'app-harmony') {
return p !== utsPlatform;
}
return p !== 'app';
}
return p !== 'app' && p !== 'app-plus';
}
else if (platform === 'h5' || platform === 'web') {
return p !== 'h5' && p !== 'web';
}
else if (platform.startsWith('app-')) {
return p !== 'app' && p !== platform;
}
return p !== platform;
})
// 在最后增加 / 是为了避免误判以 platform 开头的目录,比如 app-test
.map((p) => '/' + dir + '/' + p + '/'));
}
@@ -0,0 +1,19 @@
import type { Plugin } from 'vite';
interface UniMovePluginOptions {
apply: Plugin['apply'];
enforce: Plugin['enforce'];
/**
* 原始根目录
*/
cwd: string;
/**
* glob pattern 如:**\/*.js.mp)
*/
pattern: string;
/**
* 目标目录
*/
dest: string;
}
export declare function uniMovePlugin({ apply, enforce, cwd, pattern, dest, }: UniMovePluginOptions): Plugin;
export {};
@@ -0,0 +1,28 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniMovePlugin = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const fast_glob_1 = __importDefault(require("fast-glob"));
function uniMovePlugin({ apply, enforce, cwd, pattern, dest, }) {
return {
name: 'uni:move',
apply,
enforce,
async writeBundle() {
await Promise.all(fast_glob_1.default
.sync(pattern, {
cwd,
})
.map((filename) => {
return fs_extra_1.default.move(path_1.default.resolve(cwd, filename), path_1.default.resolve(dest, filename), {
overwrite: true,
});
}));
},
};
}
exports.uniMovePlugin = uniMovePlugin;
@@ -0,0 +1,2 @@
import type { FSWatcher } from 'chokidar';
export declare const initEasycom: (watcher?: FSWatcher) => void;
@@ -0,0 +1,41 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initEasycom = void 0;
const debug_1 = __importDefault(require("debug"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const debugEasycom = (0, debug_1.default)('uni:easycom');
const initEasycom = (watcher) => {
const { filter, refresh, easyComOptions } = (0, uni_cli_shared_1.initEasycomsOnce)(process.env.UNI_INPUT_DIR, {
dirs: (0, uni_cli_shared_1.resolveComponentsLibDirs)(),
platform: process.env.UNI_PLATFORM,
isX: process.env.UNI_APP_X === 'true',
});
if (!watcher) {
// build 模式,手动初始化 watcher
const dirs = easyComOptions.dirs.concat([
(0, uni_cli_shared_1.normalizePath)(process.env.UNI_INPUT_DIR + '/uni_modules'),
]);
debugEasycom('initWatch', dirs);
watcher = uni_cli_shared_1.chokidar.watch(dirs, {
ignored: ['**/node_modules/**', '**/.git/**'],
ignoreInitial: true,
ignorePermissionErrors: true,
disableGlobbing: true,
});
}
const refreshEasycom = (0, uni_shared_1.debounce)(refresh, 100, { setTimeout, clearTimeout });
watcher.on('all', (eventName, path) => {
if (!['add', 'unlink'].includes(eventName)) {
return;
}
if (filter(path)) {
debugEasycom('watch', eventName, path);
refreshEasycom();
}
});
};
exports.initEasycom = initEasycom;
@@ -0,0 +1 @@
export declare function createPublicFileFilter(base?: string): (id: unknown) => boolean;
@@ -0,0 +1,15 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createPublicFileFilter = void 0;
const path_1 = __importDefault(require("path"));
const pluginutils_1 = require("@rollup/pluginutils");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function createPublicFileFilter(base = '/') {
const publicDir = (0, uni_cli_shared_1.normalizePath)(path_1.default.join(base, uni_cli_shared_1.PUBLIC_DIR + '/**/*'));
const uniModulesDir = (0, uni_cli_shared_1.normalizePath)(path_1.default.join(base, 'uni_modules/*/' + uni_cli_shared_1.PUBLIC_DIR + '/**/*'));
return (0, pluginutils_1.createFilter)([publicDir, uniModulesDir]);
}
exports.createPublicFileFilter = createPublicFileFilter;
@@ -0,0 +1,4 @@
export * from './filter';
export * from './plugin';
export * from './polyfill';
export * from './nvue';
@@ -0,0 +1,20 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./filter"), exports);
__exportStar(require("./plugin"), exports);
__exportStar(require("./polyfill"), exports);
__exportStar(require("./nvue"), exports);
@@ -0,0 +1,5 @@
/**
* nvue 需要移除 scoped
* @param nvuePages
*/
export declare function createNVueCompiler(): any;
+25
View File
@@ -0,0 +1,25 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.createNVueCompiler = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const shared_1 = require("@vue/shared");
/**
* nvue 需要移除 scoped
* @param nvuePages
*/
function createNVueCompiler() {
const compileSfc = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-sfc'));
const { parse } = compileSfc;
return (0, shared_1.extend)({}, compileSfc, {
parse(source, options = {}) {
const result = parse(source, options);
result.descriptor.styles.forEach((style) => {
if (style.scoped) {
delete style.scoped;
}
});
return result;
},
});
}
exports.createNVueCompiler = createNVueCompiler;
@@ -0,0 +1,17 @@
import type { Plugin } from 'vite';
import { type UniViteCopyPluginTarget, type UniVitePlugin } from '@dcloudio/uni-cli-shared';
import type { TemplateCompiler } from '@vue/compiler-sfc';
import type { VitePluginUniResolvedOptions } from '..';
export declare function initPluginUniOptions(UniVitePlugins: UniVitePlugin[]): {
compiler?: TemplateCompiler;
uniAppXVaporScriptTransform?: NonNullable<UniVitePlugin['uni']>['uniAppXVaporScriptTransform'];
copyOptions: {
assets: string[];
targets: UniViteCopyPluginTarget[];
};
transformEvent: Record<string, string>;
compilerOptions: Required<Required<UniVitePlugin>['uni']>['compilerOptions'];
jsxOptions: Required<Required<UniVitePlugin>['uni']>['jsxOptions'];
styleOptions: Required<Required<UniVitePlugin>['uni']>['styleOptions'];
};
export declare function initExtraPlugins(cliRoot: string, platform: UniApp.PLATFORM, options: VitePluginUniResolvedOptions): Plugin<any>[];
@@ -0,0 +1,162 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initExtraPlugins = exports.initPluginUniOptions = void 0;
const path_1 = __importDefault(require("path"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const shared_1 = require("@vue/shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
function initPluginUniOptions(UniVitePlugins) {
const assets = [];
const targets = [];
const transformEvent = Object.create(null);
const compilerOptions = {};
const jsxOptions = {};
const styleOptions = {};
let compiler;
let uniAppXVaporScriptTransform;
UniVitePlugins.forEach((plugin) => {
const { compiler: pluginTemplateCompiler, uniAppXVaporScriptTransform: pluginUniAppXVaporScriptTransform, copyOptions: pluginCopyOptions, compilerOptions: pluginCompilerOptions, jsxOptions: pluginJsxOptions, styleOptions: pluginStyleOpitons, } = plugin.uni || {};
if (pluginTemplateCompiler) {
compiler = pluginTemplateCompiler;
}
if (pluginUniAppXVaporScriptTransform) {
uniAppXVaporScriptTransform = pluginUniAppXVaporScriptTransform;
}
if (pluginCompilerOptions) {
(0, shared_1.extend)(compilerOptions, pluginCompilerOptions);
}
if (pluginJsxOptions) {
(0, shared_1.extend)(jsxOptions, pluginJsxOptions);
}
if (pluginStyleOpitons) {
(0, shared_1.extend)(styleOptions, pluginStyleOpitons);
}
if (pluginCopyOptions) {
let copyOptions = pluginCopyOptions;
if ((0, shared_1.isFunction)(pluginCopyOptions)) {
copyOptions = pluginCopyOptions();
}
if (copyOptions.assets) {
assets.push(...copyOptions.assets);
}
if (copyOptions.targets) {
targets.push(...copyOptions.targets);
}
}
});
return {
compiler,
uniAppXVaporScriptTransform,
copyOptions: {
assets,
targets,
},
transformEvent,
compilerOptions,
jsxOptions,
styleOptions,
};
}
exports.initPluginUniOptions = initPluginUniOptions;
function initExtraPlugins(cliRoot, platform, options) {
return initPlugins(cliRoot, process.env.UNI_COMPILE_TARGET === 'ext-api' &&
process.env.UNI_APP_NEXT_WORKSPACE
? resolvePluginsByWorkSpace(process.env.UNI_APP_NEXT_WORKSPACE, platform, options.uvue)
: resolvePluginsByCliRoot(cliRoot, platform, options.uvue), options);
}
exports.initExtraPlugins = initExtraPlugins;
function initPlugin(_cliRoot, { pluginPath, config: { main } }, options) {
let plugin = require(path_1.default.join(pluginPath, main || '/lib/uni.plugin.js'));
plugin = plugin.default || plugin;
if ((0, shared_1.isFunction)(plugin)) {
plugin = plugin(options);
}
return plugin;
}
function initPlugins(cliRoot, plugins, options) {
return plugins
.map((plugin) => initPlugin(cliRoot, plugin, options))
.flat()
.filter(Boolean)
.map((plugin) => {
if ((0, shared_1.isFunction)(plugin)) {
return plugin(options);
}
return plugin;
})
.flat();
}
function resolvePluginsByCliRoot(cliRoot, platform, uvue = false) {
const pkg = require(path_1.default.join(cliRoot, 'package.json'));
return resolvePlugins(Object.keys(pkg.devDependencies || {})
.concat(Object.keys(pkg.dependencies || {}))
.map((id) => {
try {
const pkgFileName = require.resolve(id + '/package.json', {
paths: [cliRoot],
});
const pkg = require(pkgFileName);
return {
...pkg,
pluginPath: path_1.default.dirname(pkgFileName),
};
}
catch (e) { }
})
.filter(Boolean), platform, uvue);
}
function resolvePluginsByWorkSpace(workspaceFolder, platform, uvue = false) {
const pkgDirs = path_1.default.resolve(workspaceFolder, 'packages');
return resolvePlugins(fs_extra_1.default
.readdirSync(pkgDirs)
.map((dir) => {
const pluginPath = path_1.default.join(pkgDirs, dir);
const pkgFileName = path_1.default.join(pluginPath, 'package.json');
if (fs_extra_1.default.existsSync(pkgFileName)) {
return {
...require(pkgFileName),
pluginPath,
};
}
})
.filter(Boolean), platform, uvue);
}
function resolvePlugins(pkgs, platform, uvue = false) {
return pkgs
.map((pkg) => {
try {
const config = pkg['uni-app'];
if (!config || !config.name) {
return;
}
const { apply } = config;
if ((0, shared_1.isArray)(apply)) {
// 注册所有平台
apply.forEach((p) => (0, uni_cli_shared_1.registerPlatform)(p));
if (!apply.includes(platform)) {
return;
}
}
else if ((0, shared_1.isString)(apply)) {
if (!new RegExp(apply).test(platform)) {
return;
}
}
// 插件必须支持 uvue
if (uvue && !config.uvue) {
return;
}
return {
id: pkg.name,
name: config.name,
pluginPath: pkg.pluginPath,
config,
};
}
catch (e) { }
})
.filter(Boolean);
}
@@ -0,0 +1,13 @@
import type { Plugin } from 'vite';
/**
* TODO 临时重写,解决 @vitejs/plugin-vue 的 Bug
*/
export declare function rewriteCompilerSfcParse(): void;
/**
* 已废弃,交由 rewriteExistsSyncHasRootFile 实现,因为新的 vite 版本在 configResolved 中重写已经晚了
* 解决 HBuilderX 项目未包含 package.json 时,initTSConfck 可能导致查找过慢,或递归目录时权限不足报错
* 即:未包含 package.json 时,直接移除 initTSConfck 相关逻辑
* @param inputDir
* @returns
*/
export declare function initFixedEsbuildInitTSConfck(inputDir: string): Plugin[];
@@ -0,0 +1,71 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initFixedEsbuildInitTSConfck = exports.rewriteCompilerSfcParse = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const shared_1 = require("@vue/shared");
/**
* TODO 临时重写,解决 @vitejs/plugin-vue 的 Bug
*/
function rewriteCompilerSfcParse() {
const compilerSfc = require((0, uni_cli_shared_1.resolveBuiltIn)('@vue/compiler-sfc'));
const { parse } = compilerSfc;
let extname_vue = process.env.UNI_APP_X === 'true' ? uni_cli_shared_1.X_EXTNAME_VUE : uni_cli_shared_1.EXTNAME_VUE;
compilerSfc.parse = (source, options) => {
if (options?.filename) {
const extname = path_1.default.extname(options.filename);
// wxs、filter、renderjs
if (extname && !extname_vue.includes(extname)) {
const tag = extname.slice(1);
source = `<${tag}>` + source + `</${tag}>`;
}
}
return parse(source, options);
};
}
exports.rewriteCompilerSfcParse = rewriteCompilerSfcParse;
/**
* 已废弃,交由 rewriteExistsSyncHasRootFile 实现,因为新的 vite 版本在 configResolved 中重写已经晚了
* 解决 HBuilderX 项目未包含 package.json 时,initTSConfck 可能导致查找过慢,或递归目录时权限不足报错
* 即:未包含 package.json 时,直接移除 initTSConfck 相关逻辑
* @param inputDir
* @returns
*/
function initFixedEsbuildInitTSConfck(inputDir) {
if (!(0, uni_cli_shared_1.isInHBuilderX)()) {
return [];
}
if (fs_1.default.existsSync(path_1.default.resolve(inputDir, 'package.json'))) {
return [];
}
// 'vite:esbuild', 'vite:esbuild-transpile' initTSConfck
const existsSync = fs_1.default.existsSync;
// 根目录 lerna.json 路径
const lernaJsonPath = (0, uni_cli_shared_1.normalizePath)(path_1.default.resolve(inputDir, 'lerna.json'));
return [
{
name: 'uni:fixed-HBuilderX-initTSConfck-before',
enforce: 'pre',
configResolved() {
// 在 HBuilderX 项目中,缺少 package.json 时, 确保 searchForWorkspaceRoot 使用项目根目录, 否则 initTSConfck 会查找很费时,且可能访问目录权限报错
// https://github.com/vitejs/vite/blob/43b7b78b1834a4c7128d8a5d987f66a4defcbd93/packages/vite/src/node/plugins/esbuild.ts#L407
fs_1.default.existsSync = (p) => {
if ((0, shared_1.isString)(p)) {
// 访问根目录 lerna.json 时,直接返回 true
// https://github.com/vitejs/vite/blob/43b7b78b1834a4c7128d8a5d987f66a4defcbd93/packages/vite/src/node/server/searchRoot.ts#L35
if (p.endsWith('lerna.json') &&
lernaJsonPath === (0, uni_cli_shared_1.normalizePath)(p)) {
return true;
}
}
return existsSync(p);
};
},
},
];
}
exports.initFixedEsbuildInitTSConfck = initFixedEsbuildInitTSConfck;
@@ -0,0 +1,3 @@
import type { Plugin } from 'vite';
import type { VitePluginUniResolvedOptions } from '../..';
export declare function uniUVuePlugin(options: VitePluginUniResolvedOptions): Plugin;
@@ -0,0 +1,44 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniUVuePlugin = void 0;
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const define_1 = require("../../config/define");
const resolve_1 = require("../../config/resolve");
const css_1 = require("../../config/css");
const configResolved_1 = require("../../configResolved");
function uniUVuePlugin(options) {
return {
name: 'uni:uvue',
config(config, env) {
options.command = env.command;
let base = config.base;
if (!base) {
const manifestJson = (0, uni_cli_shared_1.parseManifestJsonOnce)(options.inputDir);
const h5 = (0, uni_cli_shared_1.getPlatformManifestJson)(manifestJson, 'h5');
base = (h5 && h5.router && h5.router.base) || '';
}
if (!base) {
base = '/';
}
options.base = base;
return {
base: process.env.UNI_H5_BASE || base,
root: process.env.VITE_ROOT_DIR,
// TODO 临时设置为__static__,屏蔽警告:https://github.com/vitejs/vite/blob/824d042535033a5c3d7006978c0d05c201cd1c25/packages/vite/src/node/server/middlewares/transform.ts#L125
publicDir: config.publicDir || '__static__',
define: (0, define_1.createDefine)(options),
resolve: (0, resolve_1.createResolve)(options, config),
logLevel: config.logLevel || 'warn', // 默认使用 warn 等级,因为 info 等级vite:report 会输出文件列表等信息
optimizeDeps: {
noDiscovery: true,
include: [],
},
css: (0, css_1.createCss)(options, config),
};
},
configResolved(config) {
(0, configResolved_1.initLogger)(config);
},
};
}
exports.uniUVuePlugin = uniUVuePlugin;
@@ -0,0 +1,19 @@
import { type ImportSpecifier } from 'es-module-lexer';
import MagicString from 'magic-string';
import type { Plugin } from 'vite';
/**
* 如下情况会生成import vue的代码:
* 1. uvue页面编译产物通过helpers方式导入的vue相关api,defineComponent、unref等
* 2. 用户代码script中的ref、reactive、computed等
* 3. onLoad等从@dcloudio/uni-app导入的api等
* 4. 用户代码script中import vue的api
*
* 如果在transform中处理,需要确保此插件在autoImport之后,否则此时2、3尚未生成import vue的代码。
* 如果在renderChunk中处理,能保证所有代码都已经生成import vue的代码,但是此时热更新会触发所有文件重新处理import vue。
*/
export declare function rewriteImportVuePlugin(): Plugin;
/**
* import { xx as yy, zz } from 'vue' =>
* const { xx: yy, zz } = globalThis.Vue
*/
export declare function rewriteImportVue(input: string, importRanges?: Pick<ImportSpecifier, 'ss' | 'se'>[]): MagicString;
@@ -0,0 +1,108 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.rewriteImportVue = exports.rewriteImportVuePlugin = void 0;
const parser_1 = require("@babel/parser");
const es_module_lexer_1 = require("es-module-lexer");
const magic_string_1 = __importDefault(require("magic-string"));
/**
* 如下情况会生成import vue的代码:
* 1. uvue页面编译产物通过helpers方式导入的vue相关api,defineComponent、unref等
* 2. 用户代码script中的ref、reactive、computed等
* 3. onLoad等从@dcloudio/uni-app导入的api等
* 4. 用户代码script中import vue的api
*
* 如果在transform中处理,需要确保此插件在autoImport之后,否则此时2、3尚未生成import vue的代码。
* 如果在renderChunk中处理,能保证所有代码都已经生成import vue的代码,但是此时热更新会触发所有文件重新处理import vue。
*/
function rewriteImportVuePlugin() {
return {
name: 'uni:rewrite-import-vue',
enforce: 'post',
async transform(source, id) {
await es_module_lexer_1.init;
const [imports] = (0, es_module_lexer_1.parse)(source);
const vueImportRanges = imports.filter((specifier) => specifier.n === 'vue' && specifier.d === -1);
if (!vueImportRanges.length) {
return;
}
const rewritten = rewriteImportVue(source, vueImportRanges);
if (rewritten.hasChanged()) {
return {
code: rewritten.toString(),
// 必须指定hires,不然部分情况可能会无法正确映射行号。
map: rewritten.generateMap({ hires: 'boundary' }),
};
}
},
};
}
exports.rewriteImportVuePlugin = rewriteImportVuePlugin;
/**
* import { xx as yy, zz } from 'vue' =>
* const { xx: yy, zz } = globalThis.Vue
*/
function rewriteImportVue(input, importRanges) {
const s = new magic_string_1.default(input);
if (importRanges) {
importRanges.forEach(({ ss, se }) => {
const rewritten = rewriteImportVueStatement(input.slice(ss, se));
if (rewritten !== undefined) {
s.overwrite(ss, se, rewritten);
}
});
}
else {
const ast = (0, parser_1.parse)(input, {
sourceType: 'module',
}).program.body;
ast.forEach((node) => {
if (node.type === 'ImportDeclaration' && node.source.value === 'vue') {
const rewritten = createImportVueReplacement(node);
if (rewritten !== undefined) {
s.overwrite(node.start, node.end, rewritten);
}
}
});
}
return s;
}
exports.rewriteImportVue = rewriteImportVue;
function rewriteImportVueStatement(input) {
const node = (0, parser_1.parse)(input, {
sourceType: 'module',
}).program.body[0];
if (node?.type === 'ImportDeclaration' && node.source.value === 'vue') {
return createImportVueReplacement(node);
}
}
function createImportVueReplacement(node) {
const imports = [];
const declarations = [];
node.specifiers.forEach((specifier) => {
if (specifier.type === 'ImportSpecifier') {
const imported = specifier.imported.name;
const local = specifier.local.name;
if (imported === local) {
imports.push(imported);
}
else {
imports.push(`${imported}: ${local}`);
}
}
else if (specifier.type === 'ImportDefaultSpecifier') {
const local = specifier.local.name;
imports.push(`default: ${local}`);
}
else if (specifier.type === 'ImportNamespaceSpecifier') {
const local = specifier.local.name;
declarations.push(`const ${local} = globalThis.Vue`);
}
});
if (imports.length > 0) {
declarations.push(`const { ${imports.join(', ')} } = globalThis.Vue`);
}
return declarations.join(';');
}
@@ -0,0 +1 @@
export * from './options';
+17
View File
@@ -0,0 +1,17 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./options"), exports);
@@ -0,0 +1,14 @@
import type { Plugin } from 'vite';
import type { Options as VueOptions } from '@vitejs/plugin-vue';
import { type UniVitePlugin } from '@dcloudio/uni-cli-shared';
import type { ViteLegacyOptions, VitePluginUniResolvedOptions } from '..';
/**
* 每次创建新的 plugin-vue 实例。因为该插件内部会 cache descriptor,而相同的vue文件在编译到vue页面和nvue页面时,不能共享缓存(条件编译,css scoped等均不同)
* @returns
*/
export declare function createPluginVueInstance(options: VueOptions): Plugin<any>;
export declare function initPluginVueOptions(options: VitePluginUniResolvedOptions, uniPluginOptions: Required<Omit<Required<UniVitePlugin>['uni'], 'compiler' | 'uniAppXVaporScriptTransform'>> & Pick<NonNullable<UniVitePlugin['uni']>, 'compiler' | 'uniAppXVaporScriptTransform'>): VueOptions;
export declare function initPluginVueJsxOptions(options: VitePluginUniResolvedOptions, { isCustomElement, }: Required<Required<UniVitePlugin>['uni']>['compilerOptions'], jsxOptions: Required<Required<UniVitePlugin>['uni']>['jsxOptions']): import("@vue/babel-plugin-jsx").VueJSXPluginOptions & {
babelPlugins?: any[] | undefined;
};
export declare function initPluginViteLegacyOptions(options: VitePluginUniResolvedOptions): ViteLegacyOptions;
+352
View File
@@ -0,0 +1,352 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initPluginViteLegacyOptions = exports.initPluginVueJsxOptions = exports.initPluginVueOptions = exports.createPluginVueInstance = void 0;
const path_1 = __importDefault(require("path"));
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const uni_cli_shared_1 = require("@dcloudio/uni-cli-shared");
const utils_1 = require("../utils");
const pluginVuePath = require.resolve('@vitejs/plugin-vue');
const normalizedPluginVuePath = (0, uni_cli_shared_1.normalizePath)(pluginVuePath);
/**
* 每次创建新的 plugin-vue 实例。因为该插件内部会 cache descriptor,而相同的vue文件在编译到vue页面和nvue页面时,不能共享缓存(条件编译,css scoped等均不同)
* @returns
*/
function createPluginVueInstance(options) {
delete require.cache[pluginVuePath];
delete require.cache[normalizedPluginVuePath];
const vuePluginModule = require(pluginVuePath);
const vuePlugin = vuePluginModule.default || vuePluginModule;
const vuePluginInstance = vuePlugin(options);
if (process.env.NODE_ENV === 'development') {
// 删除 buildEnd 逻辑,因为里边清理了缓存,导致 watch 模式失效 https://github.com/vitejs/vite-plugin-vue/commit/96dbb220ff210d2f7391f43a807bcd8cfb0da776
delete vuePluginInstance.buildEnd;
}
return vuePluginInstance;
}
exports.createPluginVueInstance = createPluginVueInstance;
function initPluginVueOptions(options, uniPluginOptions) {
const vueOptions = options.vueOptions || (options.vueOptions = {});
// if (!hasOwn(vueOptions, 'reactivityTransform')) {
// vueOptions.reactivityTransform = true
// }
if (!vueOptions.include) {
vueOptions.include = [];
}
if (!(0, shared_1.isArray)(vueOptions.include)) {
vueOptions.include = [vueOptions.include];
}
vueOptions.include.push(uni_cli_shared_1.EXTNAME_VUE_RE);
const styleOptions = vueOptions.style || (vueOptions.style = {});
if (!styleOptions.postcssPlugins) {
styleOptions.postcssPlugins = [];
}
// 解析 scoped 中 deep 等特殊语法
styleOptions.postcssPlugins.push((0, uni_cli_shared_1.uniPostcssScopedPlugin)());
// 小程序平台下处理 externalClasses 的样式隔离与优先级
if (process.env.UNI_APP_STYLE_ISOLATION_VERSION === '2' &&
process.env.UNI_APP_X === 'true') {
styleOptions.postcssPlugins.push((0, uni_cli_shared_1.uniPostcssExternalPlugin)());
}
const templateOptions = vueOptions.template || (vueOptions.template = {});
const compilerOptions = templateOptions.compilerOptions || (templateOptions.compilerOptions = {});
const isDom2 = process.env.UNI_APP_X_DOM2 === 'true';
const isWebVapor = (0, uni_cli_shared_1.isUniAppXWebVapor)();
compilerOptions.isX = process.env.UNI_APP_X === 'true';
compilerOptions.dom2 = isDom2;
// 默认就移除comments节点
compilerOptions.comments = false;
const { compiler, styleOptions: { postcssPlugins }, compilerOptions: { miniProgram, isNativeTag, isVoidTag, isCustomElement, nodeTransforms, directiveTransforms, ssrPreTagTransforms, whitespace, }, } = uniPluginOptions;
if (postcssPlugins) {
styleOptions.postcssPlugins.push(...postcssPlugins);
}
if (compiler) {
templateOptions.compiler = compiler;
}
if (isWebVapor) {
const features = vueOptions.features || (vueOptions.features = {});
features.vapor = true;
features.componentIdGenerator = createAppComponentIdGenerator(options.inputDir, features.componentIdGenerator);
Object.assign(compilerOptions, {
isUniPage(filename) {
// 自定义窗口同样接收 App 样式,名单随配置更新,不能读取首次解析的旧配置。
return ((0, uni_cli_shared_1.isUniPageFile)(filename, options.inputDir) ||
uni_cli_shared_1.windowsCacheSet.has((0, uni_cli_shared_1.normalizePath)(path_1.default.relative(options.inputDir, filename))));
},
});
// plugin-vue 的 compiler 是完整 SFC compiler;显式传入 Web Vapor 定制版,
// 避免从项目根目录解析到标准 Vue compiler-sfc。
vueOptions.compiler = require('vue/compiler-sfc');
if (ssrPreTagTransforms) {
Object.assign(compilerOptions, { ssrPreTagTransforms });
}
}
if (miniProgram) {
;
compilerOptions.miniProgram = miniProgram;
}
const isDevX = process.env.UNI_HX_VERSION_DEV === 'true' &&
process.env.UNI_APP_X === 'true';
if (isNativeTag) {
const userIsNativeTag = compilerOptions.isNativeTag;
compilerOptions.isNativeTag = (tag) => {
if (isDevX) {
const source = (0, uni_cli_shared_1.matchEasycom)(tag);
// 不能是uts插件的easycom组件
if (source && !source.includes('?uts-proxy')) {
return false;
}
}
if (isNativeTag(tag)) {
return true;
}
if (userIsNativeTag && userIsNativeTag(tag)) {
return true;
}
return false;
};
}
if (isVoidTag) {
const userIsVoidTag = compilerOptions.isVoidTag;
compilerOptions.isVoidTag = (tag) => {
if (isVoidTag(tag)) {
return true;
}
if (userIsVoidTag && userIsVoidTag(tag)) {
return true;
}
return false;
};
}
if (whitespace) {
compilerOptions.whitespace = whitespace;
}
if (isCustomElement) {
const userIsCustomElement = compilerOptions.isCustomElement;
compilerOptions.isCustomElement = (tag) => {
if (isCustomElement(tag)) {
return true;
}
if (userIsCustomElement && userIsCustomElement(tag)) {
return true;
}
return false;
};
}
compilerOptions.directiveTransforms = {
...compilerOptions.directiveTransforms,
...directiveTransforms,
};
if (!compilerOptions.nodeTransforms) {
compilerOptions.nodeTransforms = [];
}
// 合并 transformAssetUrls
// 内置配置
const builtInTransformAssetUrls = (0, uni_cli_shared_1.createUniVueTransformAssetUrls)((0, uni_cli_shared_1.isExternalUrl)(options.base) ? options.base : '');
// 用户传递配置 eg: transformAssetUrls.tags = {'my-image': ['src']}
// docs: https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue
const userOptionsTransformAssetUrls = templateOptions.transformAssetUrls;
templateOptions.transformAssetUrls = builtInTransformAssetUrls;
if (typeof userOptionsTransformAssetUrls !== 'boolean' &&
!!userOptionsTransformAssetUrls?.tags &&
!(0, shared_1.isArray)(userOptionsTransformAssetUrls.tags)) {
templateOptions.transformAssetUrls = {
...builtInTransformAssetUrls,
...userOptionsTransformAssetUrls,
tags: {
...builtInTransformAssetUrls.tags,
...userOptionsTransformAssetUrls.tags,
},
};
}
if (options.platform !== 'h5' && options.platform !== 'web') {
compilerOptions.nodeTransforms.push(...(0, uni_cli_shared_1.getBaseNodeTransforms)(options.base, isDom2 ? (0, uni_cli_shared_1.createResolveStaticAsset)(options.inputDir) : undefined));
}
if (nodeTransforms) {
compilerOptions.nodeTransforms.push(...nodeTransforms);
}
// const compatConfig = parseCompatConfigOnce(options.inputDir)
// compilerOptions.compatConfig = extend(
// compilerOptions.compatConfig || {},
// compatConfig
// )
// App,MP 平台不支持使用静态节点
compilerOptions.hoistStatic = false;
compilerOptions.root = process.env.UNI_INPUT_DIR;
const isX = process.env.UNI_APP_X === 'true';
// app-nvue | app-uvue 需要启用 customElement 机制来内联 styles
if (process.env.UNI_COMPILER === 'nvue' ||
(isX && (options.platform === 'app' || options.platform === 'app-harmony'))) {
vueOptions.customElement = true;
if (process.env.UNI_RENDERER_NATIVE !== 'appService' || isX) {
// nvue 需要使用自己的 compiler,来移除 scoped
vueOptions.compiler = (0, utils_1.createNVueCompiler)();
}
}
if (!vueOptions.script) {
vueOptions.script = {};
}
// TODO 目前暂不支持通过@/开头引入文件,因为需要tsconfig.json配置,建议使用相对路径
// https://github.com/vuejs/core/blob/main/packages/compiler-sfc/src/script/resolveType.ts#L911
require('@vue/compiler-sfc').registerTS(() => {
if (isX) {
return (0, uni_cli_shared_1.resolveUniTypeScript)();
}
return require('typescript');
});
if (!vueOptions.script.fs) {
vueOptions.script.fs = (0, uni_cli_shared_1.createVueCompilerFs)();
}
if (isX) {
// DOM2 的定制 compiler-sfc 会根据 script lang 选择 parser,避免 JS 被按 TS 解析。
if (!isDom2) {
if (!vueOptions.script) {
vueOptions.script = {
babelParserPlugins: [],
};
}
if (!vueOptions.script.babelParserPlugins) {
vueOptions.script.babelParserPlugins = [];
}
// Android VDOM 保持原有 UTS 兼容;标准脚本平台由 compiler-sfc 按 lang 启用 TypeScript。
if (!(0, uni_cli_shared_1.isUniAppXStandardScriptSupported)() &&
!vueOptions.script.babelParserPlugins.includes('typescript')) {
vueOptions.script.babelParserPlugins.push('typescript');
}
// 旧 compiler-sfc 仅用 includes('decorators') 识别现代装饰器,tuple 配置仍需字符串哨兵。
const hasDecoratorParser = vueOptions.script.babelParserPlugins.some((plugin) => plugin === 'decorators' || plugin === 'decorators-legacy');
if (!hasDecoratorParser) {
vueOptions.script.babelParserPlugins.push('decorators');
}
}
if (isDom2) {
// 该扩展点依赖定制 plugin-vue,仅用于 compileScript 后的 DOM2 SharedData 等转换。
;
vueOptions.uniAppXVaporScriptTransform =
uniPluginOptions.uniAppXVaporScriptTransform;
const utsPlatform = process.env.UNI_UTS_PLATFORM || process.env.UNI_PLATFORM;
if ((0, uni_cli_shared_1.isUniAppXAppPlatform)(utsPlatform)) {
const defaultLang = (0, uni_cli_shared_1.getUniAppXVaporScriptLang)(process.env.UNI_INPUT_DIR);
vueOptions.uniAppXVaporSfcTransform = (descriptor) => {
const scripts = [descriptor.script, descriptor.scriptSetup].filter((script) => !!script);
// compiler-sfc 可能复用缓存中的 descriptor,保留首次处理时记录的隐式 lang 状态。
let hasImplicitLang = descriptor.__uniAppXVaporSfcMeta?.hasImplicitLang === true;
scripts.forEach((script) => {
if (script.lang == null) {
script.lang = defaultLang;
script.attrs.lang = defaultLang;
hasImplicitLang = true;
}
});
if (descriptor.scriptSetup) {
;
descriptor.vapor = true;
}
const scriptLang = descriptor.scriptSetup?.lang ||
descriptor.script?.lang ||
defaultLang;
descriptor.__uniAppXVaporSfcMeta = {
scriptLang,
...(process.env.NODE_ENV === 'development'
? { hasImplicitLang, defaultLang }
: {}),
};
};
}
const appVue = (0, uni_cli_shared_1.resolveAppVue)(process.env.UNI_INPUT_DIR);
function isAppVue(id) {
return (0, uni_cli_shared_1.normalizePath)(id) === appVue;
}
;
compilerOptions.isEasyComponent = (tag) => {
return (0, uni_shared_1.isDom2VueComponentTag)(tag) || !!(0, uni_cli_shared_1.matchEasycom)(tag);
};
compilerOptions.isUserComponent = (element) => {
return (0, uni_shared_1.isDom2AppUserVueComponentTag)(element.tag);
};
vueOptions.script.extraOptions = (descriptor) => {
return {
// Web 只需要组件类型,不使用 App 的 SharedData,也不依赖 HBuilderX 插件。
...(isWebVapor
? {}
: {
isWatch: process.env.NODE_ENV === 'development',
// TODO 目前使用全局开关,后续可能是页面级别的开关?
dynamicSharedData: process.env.UNI_APP_X_DOM2_DYNAMIC === 'true',
helper: (0, uni_cli_shared_1.requireUniHelpers)(),
}),
componentType: (0, uni_cli_shared_1.isUniPageFile)(descriptor.filename)
? 'page'
: isAppVue(descriptor.filename)
? 'app'
: 'component',
};
};
if (!isWebVapor) {
;
vueOptions.template.compilerOptions.extraOptions = (descriptor) => {
return (0, uni_cli_shared_1.initVueTemplateCompilerExtraOptions)(descriptor);
};
}
}
else {
// 如果是 easyComponent 组件,则不需要从setup中导入组件且不支持 self 引用
;
compilerOptions.isEasyComponent = (tag) => {
return (0, uni_shared_1.isBuiltInComponent)(tag) || !!(0, uni_cli_shared_1.matchEasycom)(tag);
};
}
}
if (isWebVapor) {
// Web Vapor 内置组件与项目 Easycom 均应优先于同名 setup 绑定。
;
compilerOptions.isEasyComponent = (tag) => {
const name = tag.startsWith('v-uni-') ? tag.slice(6) : tag;
return (0, uni_shared_1.isDom2WebVueComponentTag)(name) || !!(0, uni_cli_shared_1.matchEasycom)(name);
};
}
return vueOptions;
}
exports.initPluginVueOptions = initPluginVueOptions;
function initPluginVueJsxOptions(options, { isCustomElement, }, jsxOptions) {
const vueJsxOptions = (0, shared_1.isPlainObject)(options.vueJsxOptions)
? options.vueJsxOptions
: (options.vueJsxOptions = {});
if (!(0, shared_1.hasOwn)(vueJsxOptions, 'optimize')) {
vueJsxOptions.optimize = true;
}
vueJsxOptions.isCustomElement = isCustomElement;
if (!vueJsxOptions.babelPlugins) {
vueJsxOptions.babelPlugins = [];
}
if ((0, shared_1.isArray)(jsxOptions.babelPlugins)) {
vueJsxOptions.babelPlugins.push(...jsxOptions.babelPlugins);
}
return vueJsxOptions;
}
exports.initPluginVueJsxOptions = initPluginVueJsxOptions;
function initPluginViteLegacyOptions(options) {
const viteLegacyOptions = options.viteLegacyOptions || (options.viteLegacyOptions = {});
return viteLegacyOptions;
}
exports.initPluginViteLegacyOptions = initPluginViteLegacyOptions;
// 仅固定根 App 的 ID;其他组件保留 plugin-vue 的默认策略及开发者配置。
function createAppComponentIdGenerator(inputDir, generator) {
const appFilename = (0, uni_cli_shared_1.normalizePath)(path_1.default.relative(process.env.VITE_ROOT_DIR || process.cwd(), (0, uni_cli_shared_1.resolveAppVue)(inputDir)));
const { UNI_APP_SCOPE_ID } = require('@dcloudio/compiler-vapor-web');
const appId = UNI_APP_SCOPE_ID.slice(7);
return (filename, source, isProduction, getHash) => {
if (filename === appFilename)
return appId;
if (typeof generator === 'function') {
return generator(filename, source, isProduction, getHash);
}
return getHash(filename +
(generator === 'filepath-source' || (!generator && isProduction)
? source
: ''));
};
}
+1
View File
@@ -0,0 +1 @@
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017-present, Jon Schlinkert.
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.
@@ -0,0 +1,743 @@
<h1 align="center">Picomatch</h1>
<p align="center">
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/v/picomatch.svg" alt="version">
</a>
<a href="https://github.com/micromatch/picomatch/actions/workflows/test.yml">
<img src="https://github.com/micromatch/picomatch/actions/workflows/test.yml/badge.svg?branch=master" alt="test status">
</a>
<a href="https://coveralls.io/github/micromatch/picomatch">
<img src="https://img.shields.io/coveralls/github/micromatch/picomatch/master.svg" alt="coverage status">
</a>
<a href="https://npmjs.org/package/picomatch">
<img src="https://img.shields.io/npm/dm/picomatch" alt="downloads">
</a>
</p>
<br>
<br>
<p align="center">
<strong>Blazing fast and accurate glob matcher written in JavaScript.</strong></br>
<em>No dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.</em>
</p>
<br>
<br>
## Why picomatch?
* **Lightweight** - No dependencies
* **Minimal** - Tiny API surface. Main export is a function that takes a glob pattern and returns a matcher function.
* **Fast** - Loads in about 2ms (that's several times faster than a [single frame of a HD movie](http://www.endmemo.com/sconvert/framespersecondframespermillisecond.php) at 60fps)
* **Performant** - Use the returned matcher function to speed up repeat matching (like when watching files)
* **Accurate matching** - Using wildcards (`*` and `?`), globstars (`**`) for nested directories, [advanced globbing](#advanced-globbing) with extglobs, braces, and POSIX brackets, and support for escaping special characters with `\` or quotes.
* **Well tested** - Thousands of unit tests
See the [library comparison](#library-comparisons) to other libraries.
<br>
<br>
## Table of Contents
<details><summary> Click to expand </summary>
- [Install](#install)
- [Usage](#usage)
- [API](#api)
* [picomatch](#picomatch)
* [.test](#test)
* [.matchBase](#matchbase)
* [.isMatch](#ismatch)
* [.parse](#parse)
* [.scan](#scan)
* [.compileRe](#compilere)
* [.makeRe](#makere)
* [.toRegex](#toregex)
- [Options](#options)
* [Picomatch options](#picomatch-options)
* [Scan Options](#scan-options)
* [Options Examples](#options-examples)
- [Globbing features](#globbing-features)
* [Basic globbing](#basic-globbing)
* [Advanced globbing](#advanced-globbing)
* [Braces](#braces)
* [Matching special characters as literals](#matching-special-characters-as-literals)
- [Library Comparisons](#library-comparisons)
- [Benchmarks](#benchmarks)
- [Philosophies](#philosophies)
- [About](#about)
* [Author](#author)
* [License](#license)
_(TOC generated by [verb](https://github.com/verbose/verb) using [markdown-toc](https://github.com/jonschlinkert/markdown-toc))_
</details>
<br>
<br>
## Install
Install with [npm](https://www.npmjs.com/):
```sh
npm install --save picomatch
```
<br>
## Usage
The main export is a function that takes a glob pattern and an options object and returns a function for matching strings.
```js
const pm = require('picomatch');
const isMatch = pm('*.js');
console.log(isMatch('abcd')); //=> false
console.log(isMatch('a.js')); //=> true
console.log(isMatch('a.md')); //=> false
console.log(isMatch('a/b.js')); //=> false
```
<br>
## API
### [picomatch](lib/picomatch.js#L43)
Creates a matcher function from one or more glob patterns. The returned function takes a string to match as its first argument, and returns true if the string is a match. The returned matcher function also takes a boolean as the second argument that, when true, returns an object with additional information.
**Params**
* `globs` **{String|Array}**: One or more glob patterns.
* `options` **{Object=}**
* `returns` **{Function=}**: Returns a matcher function.
**Example**
```js
const picomatch = require('picomatch');
// picomatch(glob[, options]);
const isMatch = picomatch('*.!(*a)');
console.log(isMatch('a.a')); //=> false
console.log(isMatch('a.b')); //=> true
// For environments without `node.js`, `picomatch/posix` provides you a dependency-free matcher, without automatic OS detection.
const picomatch = require('picomatch/posix');
// the same API, defaulting to posix paths
const isMatch = picomatch('a/*');
console.log(isMatch('a\\b')); //=> false
console.log(isMatch('a/b')); //=> true
// you can still configure the matcher function to accept windows paths
const isMatch = picomatch('a/*', { options: windows });
console.log(isMatch('a\\b')); //=> true
console.log(isMatch('a/b')); //=> true
```
### [.test](lib/picomatch.js#L128)
Test `input` with the given `regex`. This is used by the main `picomatch()` function to test the input string.
**Params**
* `input` **{String}**: String to test.
* `regex` **{RegExp}**
* `returns` **{Object}**: Returns an object with matching info.
**Example**
```js
const picomatch = require('picomatch');
// picomatch.test(input, regex[, options]);
console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
// { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
```
### [.matchBase](lib/picomatch.js#L172)
Match the basename of a filepath.
**Params**
* `input` **{String}**: String to test.
* `glob` **{RegExp|String}**: Glob pattern or regex created by [.makeRe](#makeRe).
* `returns` **{Boolean}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.matchBase(input, glob[, options]);
console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
```
### [.isMatch](lib/picomatch.js#L194)
Returns true if **any** of the given glob `patterns` match the specified `string`.
**Params**
* **{String|Array}**: str The string to test.
* **{String|Array}**: patterns One or more glob patterns to use for matching.
* **{Object}**: See available [options](#options).
* `returns` **{Boolean}**: Returns true if any patterns match `str`
**Example**
```js
const picomatch = require('picomatch');
// picomatch.isMatch(string, patterns[, options]);
console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
```
### [.parse](lib/picomatch.js#L210)
Parse a glob pattern to create the source string for a regular expression.
**Params**
* `pattern` **{String}**
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with useful properties and output to be used as a regex source string.
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.parse(pattern[, options]);
```
### [.scan](lib/picomatch.js#L242)
Scan a glob pattern to separate the pattern into segments.
**Params**
* `input` **{String}**: Glob pattern to scan.
* `options` **{Object}**
* `returns` **{Object}**: Returns an object with
**Example**
```js
const picomatch = require('picomatch');
// picomatch.scan(input[, options]);
const result = picomatch.scan('!./foo/*.js');
console.log(result);
{ prefix: '!./',
input: '!./foo/*.js',
start: 3,
base: 'foo',
glob: '*.js',
isBrace: false,
isBracket: false,
isGlob: true,
isExtglob: false,
isGlobstar: false,
negated: true }
```
### [.compileRe](lib/picomatch.js#L264)
Compile a regular expression from the `state` object returned by the [parse()](#parse) method.
**Params**
* `state` **{Object}**
* `options` **{Object}**
* `returnOutput` **{Boolean}**: Intended for implementors, this argument allows you to return the raw output from the parser.
* `returnState` **{Boolean}**: Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* `returns` **{RegExp}**
**Example**
```js
const picomatch = require('picomatch');
const state = picomatch.parse('*.js');
// picomatch.compileRe(state[, options]);
console.log(picomatch.compileRe(state));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
### [.makeRe](lib/picomatch.js#L305)
Create a regular expression from a parsed glob pattern.
**Params**
* `state` **{String}**: The object returned from the `.parse` method.
* `options` **{Object}**
* `returnOutput` **{Boolean}**: Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* `returnState` **{Boolean}**: Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* `returns` **{RegExp}**: Returns a regex created from the given pattern.
**Example**
```js
const picomatch = require('picomatch');
// picomatch.makeRe(state[, options]);
const result = picomatch.makeRe('*.js');
console.log(result);
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
### [.toRegex](lib/picomatch.js#L340)
Create a regular expression from the given regex source string.
**Params**
* `source` **{String}**: Regular expression source string.
* `options` **{Object}**
* `returns` **{RegExp}**
**Example**
```js
const picomatch = require('picomatch');
// picomatch.toRegex(source[, options]);
const { output } = picomatch.parse('*.js');
console.log(picomatch.toRegex(output));
//=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
```
<br>
## Options
### Picomatch options
The following options may be used with the main `picomatch()` function or any of the methods on the picomatch API.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `basename` | `boolean` | `false` | 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`. |
| `bash` | `boolean` | `false` | Follow bash matching rules more strictly - disallows backslashes as escape characters, and treats single stars as globstars (`**`). |
| `capture` | `boolean` | `undefined` | Return regex matches in supporting methods. |
| `contains` | `boolean` | `undefined` | Allows glob to match any part of the given string(s). |
| `debug` | `boolean` | `undefined` | Debug regular expressions when an error is thrown. |
| `dot` | `boolean` | `false` | Enable dotfile matching. By default, dotfiles are ignored unless a `.` is explicitly defined in the pattern, or `options.dot` is true |
| `expandRange` | `function` | `undefined` | Custom function for expanding ranges in brace patterns, such as `{a..z}`. The function receives the range values as two arguments, and it must return a string to be used in the generated regex. It's recommended that returned strings be wrapped in parentheses. |
| `fastpaths` | `boolean` | `true` | To speed up processing, full parsing is skipped for a handful common glob patterns. Disable this behavior by setting this option to `false`. |
| `flags` | `string` | `undefined` | Regex flags to use in the generated regex. If defined, the `nocase` option will be overridden. |
| [format](#optionsformat) | `function` | `undefined` | Custom function for formatting the returned string. This is useful for removing leading slashes, converting Windows paths to Posix paths, etc. |
| `ignore` | `array\|string` | `undefined` | One or more glob patterns for excluding strings that should not be matched from the result. |
| `keepQuotes` | `boolean` | `false` | Retain quotes in the generated regex, since quotes may also be used as an alternative to backslashes. |
| `literalBrackets` | `boolean` | `undefined` | When `true`, brackets in the glob pattern will be escaped so that only literal brackets will be matched. |
| `matchBase` | `boolean` | `false` | Alias for `basename` |
| `maxLength` | `number` | `65536` | Limit the max length of the input string. An error is thrown if the input string is longer than this value. |
| `maxExtglobRecursion` | `number\|boolean` | `0` | Limit nested quantified extglobs and other risky repeated extglob forms. When the limit is exceeded, the extglob is treated as a literal string instead of being compiled to regex. Set to `false` to disable this safeguard. |
| `nobrace` | `boolean` | `false` | Disable brace matching, so that `{a,b}` and `{1..3}` would be treated as literal characters. |
| `nobracket` | `boolean` | `undefined` | Disable matching with regex brackets. |
| `nocase` | `boolean` | `false` | Make matching case-insensitive. Equivalent to the regex `i` flag. Note that this option is overridden by the `flags` option. |
| `noext` | `boolean` | `false` | Alias for `noextglob` |
| `noextglob` | `boolean` | `false` | Disable support for matching with extglobs (like `+(a\|b)`) |
| `noglobstar` | `boolean` | `false` | Disable support for matching nested directories with globstars (`**`) |
| `nonegate` | `boolean` | `false` | Disable support for negating with leading `!` |
| [onIgnore](#optionsonIgnore) | `function` | `undefined` | Function to be called on ignored items. |
| [onMatch](#optionsonMatch) | `function` | `undefined` | Function to be called on matched items. |
| [onResult](#optionsonResult) | `function` | `undefined` | Function to be called on all items, regardless of whether or not they are matched or ignored. |
| `posix` | `boolean` | `false` | Support POSIX character classes ("posix brackets"). |
| `prepend` | `boolean` | `undefined` | String to prepend to the generated regex used for matching. |
| `regex` | `boolean` | `false` | Use regular expression rules for `+` (instead of matching literal `+`), and for stars that follow closing parentheses or brackets (as in `)*` and `]*`). |
| `strictBrackets` | `boolean` | `undefined` | Throw an error if brackets, braces, or parens are imbalanced. |
| `strictSlashes` | `boolean` | `undefined` | When true, picomatch won't match trailing slashes with single stars. |
| `unescape` | `boolean` | `undefined` | Remove backslashes preceding escaped characters in the glob pattern. By default, backslashes are retained. |
| `windows` | `boolean` | `false` | Also accept backslashes as the path separator. |
### Scan Options
In addition to the main [picomatch options](#picomatch-options), the following options may also be used with the [.scan](#scan) method.
| **Option** | **Type** | **Default value** | **Description** |
| --- | --- | --- | --- |
| `tokens` | `boolean` | `false` | When `true`, the returned object will include an array of tokens (objects), representing each path "segment" in the scanned glob pattern |
| `parts` | `boolean` | `false` | When `true`, the returned object will include an array of strings representing each path "segment" in the scanned glob pattern. This is automatically enabled when `options.tokens` is true |
**Example**
```js
const picomatch = require('picomatch');
const result = picomatch.scan('!./foo/*.js', { tokens: true });
console.log(result);
// {
// prefix: '!./',
// input: '!./foo/*.js',
// start: 3,
// base: 'foo',
// glob: '*.js',
// isBrace: false,
// isBracket: false,
// isGlob: true,
// isExtglob: false,
// isGlobstar: false,
// negated: true,
// maxDepth: 2,
// tokens: [
// { value: '!./', depth: 0, isGlob: false, negated: true, isPrefix: true },
// { value: 'foo', depth: 1, isGlob: false },
// { value: '*.js', depth: 1, isGlob: true }
// ],
// slashes: [ 2, 6 ],
// parts: [ 'foo', '*.js' ]
// }
```
<br>
### Options Examples
#### options.expandRange
**Type**: `function`
**Default**: `undefined`
Custom function for expanding ranges in brace patterns. The [fill-range](https://github.com/jonschlinkert/fill-range) library is ideal for this purpose, or you can use custom code to do whatever you need.
**Example**
The following example shows how to create a glob that matches a folder
```js
const fill = require('fill-range');
const regex = pm.makeRe('foo/{01..25}/bar', {
expandRange(a, b) {
return `(${fill(a, b, { toRegex: true })})`;
}
});
console.log(regex);
//=> /^(?:foo\/((?:0[1-9]|1[0-9]|2[0-5]))\/bar)$/
console.log(regex.test('foo/00/bar')) // false
console.log(regex.test('foo/01/bar')) // true
console.log(regex.test('foo/10/bar')) // true
console.log(regex.test('foo/22/bar')) // true
console.log(regex.test('foo/25/bar')) // true
console.log(regex.test('foo/26/bar')) // false
```
#### options.format
**Type**: `function`
**Default**: `undefined`
Custom function for formatting strings before they're matched.
**Example**
```js
// strip leading './' from strings
const format = str => str.replace(/^\.\//, '');
const isMatch = picomatch('foo/*.js', { format });
console.log(isMatch('./foo/bar.js')); //=> true
```
#### options.onMatch
```js
const onMatch = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onMatch });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onIgnore
```js
const onIgnore = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onIgnore, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
#### options.onResult
```js
const onResult = ({ glob, regex, input, output }) => {
console.log({ glob, regex, input, output });
};
const isMatch = picomatch('*', { onResult, ignore: 'f*' });
isMatch('foo');
isMatch('bar');
isMatch('baz');
```
<br>
<br>
## Globbing features
* [Basic globbing](#basic-globbing) (Wildcard matching)
* [Advanced globbing](#advanced-globbing) (extglobs, posix brackets, brace matching)
### Basic globbing
| **Character** | **Description** |
| --- | --- |
| `*` | Matches any character zero or more times, excluding path separators. Does _not match_ path separators or hidden files or directories ("dotfiles"), unless explicitly enabled by setting the `dot` option to `true`. |
| `**` | Matches any character zero or more times, including path separators. Note that `**` will only match path separators (`/`, and `\\` with the `windows` option) when they are the only characters in a path segment. Thus, `foo**/bar` is equivalent to `foo*/bar`, and `foo/a**b/bar` is equivalent to `foo/a*b/bar`, and _more than two_ consecutive stars in a glob path segment are regarded as _a single star_. Thus, `foo/***/bar` is equivalent to `foo/*/bar`. |
| `?` | Matches any character excluding path separators one time. Does _not match_ path separators or leading dots. |
| `[abc]` | Matches any characters inside the brackets. For example, `[abc]` would match the characters `a`, `b` or `c`, and nothing else. |
#### Matching behavior vs. Bash
Picomatch's matching features and expected results in unit tests are based on Bash's unit tests and the Bash 4.3 specification, with the following exceptions:
* Bash will match `foo/bar/baz` with `*`. Picomatch only matches nested directories with `**`.
* Bash greedily matches with negated extglobs. For example, Bash 4.3 says that `!(foo)*` should match `foo` and `foobar`, since the trailing `*` bracktracks to match the preceding pattern. This is very memory-inefficient, and IMHO, also incorrect. Picomatch would return `false` for both `foo` and `foobar`.
<br>
### Advanced globbing
* [extglobs](#extglobs)
* [POSIX brackets](#posix-brackets)
* [Braces](#brace-expansion)
#### Extglobs
| **Pattern** | **Description** |
| --- | --- |
| `@(pattern)` | Match _only one_ consecutive occurrence of `pattern` |
| `*(pattern)` | Match _zero or more_ consecutive occurrences of `pattern` |
| `+(pattern)` | Match _one or more_ consecutive occurrences of `pattern` |
| `?(pattern)` | Match _zero or **one**_ consecutive occurrences of `pattern` |
| `!(pattern)` | Match _anything but_ `pattern` |
**Examples**
```js
const pm = require('picomatch');
// *(pattern) matches ZERO or more of "pattern"
console.log(pm.isMatch('a', 'a*(z)')); // true
console.log(pm.isMatch('az', 'a*(z)')); // true
console.log(pm.isMatch('azzz', 'a*(z)')); // true
// +(pattern) matches ONE or more of "pattern"
console.log(pm.isMatch('a', 'a+(z)')); // false
console.log(pm.isMatch('az', 'a+(z)')); // true
console.log(pm.isMatch('azzz', 'a+(z)')); // true
// supports multiple extglobs
console.log(pm.isMatch('foo.bar', '!(foo).!(bar)')); // false
// supports nested extglobs
console.log(pm.isMatch('foo.bar', '!(!(foo)).!(!(bar))')); // true
// risky quantified extglobs are treated literally by default
console.log(pm.makeRe('+(a|aa)'));
//=> /^(?:\+\(a\|aa\))$/
// increase the limit to allow a small amount of nested quantified extglobs
console.log(pm.isMatch('aaa', '+(+(a))', { maxExtglobRecursion: 1 })); // true
```
#### POSIX brackets
POSIX classes are disabled by default. Enable this feature by setting the `posix` option to true.
**Enable POSIX bracket support**
```js
console.log(pm.makeRe('[[:word:]]+', { posix: true }));
//=> /^(?:(?=.)[A-Za-z0-9_]+\/?)$/
```
**Supported POSIX classes**
The following named POSIX bracket expressions are supported:
* `[:alnum:]` - Alphanumeric characters, equ `[a-zA-Z0-9]`
* `[:alpha:]` - Alphabetical characters, equivalent to `[a-zA-Z]`.
* `[:ascii:]` - ASCII characters, equivalent to `[\\x00-\\x7F]`.
* `[:blank:]` - Space and tab characters, equivalent to `[ \\t]`.
* `[:cntrl:]` - Control characters, equivalent to `[\\x00-\\x1F\\x7F]`.
* `[:digit:]` - Numerical digits, equivalent to `[0-9]`.
* `[:graph:]` - Graph characters, equivalent to `[\\x21-\\x7E]`.
* `[:lower:]` - Lowercase letters, equivalent to `[a-z]`.
* `[:print:]` - Print characters, equivalent to `[\\x20-\\x7E ]`.
* `[:punct:]` - Punctuation and symbols, equivalent to `[\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~]`.
* `[:space:]` - Extended space characters, equivalent to `[ \\t\\r\\n\\v\\f]`.
* `[:upper:]` - Uppercase letters, equivalent to `[A-Z]`.
* `[:word:]` - Word characters (letters, numbers and underscores), equivalent to `[A-Za-z0-9_]`.
* `[:xdigit:]` - Hexadecimal digits, equivalent to `[A-Fa-f0-9]`.
See the [Bash Reference Manual](https://www.gnu.org/software/bash/manual/html_node/Pattern-Matching.html) for more information.
### Braces
Picomatch only does [brace expansion](https://www.gnu.org/software/bash/manual/html_node/Brace-Expansion.html) of comma-delimited lists (e.g. `a/{b,c}/d`). For advanced matching with braces, use [micromatch](https://github.com/micromatch/micromatch), which supports advanced syntax such as ranges (e.g. `{01..03}`) and increments (e.g. `{2..10..2}`).
### Matching special characters as literals
If you wish to match the following special characters in a filepath, and you want to use these characters in your glob pattern, they must be escaped with backslashes or quotes:
**Special Characters**
Some characters that are used for matching in regular expressions are also regarded as valid file path characters on some platforms.
To match any of the following characters as literals: `$^*+?()[]
Examples:
```js
console.log(pm.makeRe('foo/bar \\(1\\)'));
console.log(pm.makeRe('foo/bar \\(1\\)'));
```
<br>
<br>
## Library Comparisons
The following table shows which features are supported by [minimatch](https://github.com/isaacs/minimatch), [micromatch](https://github.com/micromatch/micromatch), [picomatch](https://github.com/micromatch/picomatch), [nanomatch](https://github.com/micromatch/nanomatch), [extglob](https://github.com/micromatch/extglob), [braces](https://github.com/micromatch/braces), and [expand-brackets](https://github.com/micromatch/expand-brackets).
| **Feature** | `minimatch` | `micromatch` | `picomatch` | `nanomatch` | `extglob` | `braces` | `expand-brackets` |
| --- | --- | --- | --- | --- | --- | --- | --- |
| Wildcard matching (`*?+`) | ✔ | ✔ | ✔ | ✔ | - | - | - |
| Advancing globbing | ✔ | ✔ | ✔ | - | - | - | - |
| Brace _matching_ | ✔ | ✔ | ✔ | - | - | ✔ | - |
| Brace _expansion_ | ✔ | ✔ | - | - | - | ✔ | - |
| Extglobs | partial | ✔ | ✔ | - | ✔ | - | - |
| Posix brackets | - | ✔ | ✔ | - | - | - | ✔ |
| Regular expression syntax | - | ✔ | ✔ | ✔ | ✔ | - | ✔ |
| File system operations | - | - | - | - | - | - | - |
<br>
<br>
## Benchmarks
Performance comparison of picomatch and minimatch.
```
# .makeRe star (*)
picomatch x 3,251,247 ops/sec ±0.25% (95 runs sampled)
minimatch x 497,224 ops/sec ±0.11% (100 runs sampled)
# .makeRe star; dot=true (*)
picomatch x 2,624,035 ops/sec ±0.16% (98 runs sampled)
minimatch x 446,244 ops/sec ±0.63% (99 runs sampled)
# .makeRe globstar (**)
picomatch x 2,524,465 ops/sec ±0.13% (99 runs sampled)
minimatch x 1,396,257 ops/sec ±0.58% (96 runs sampled)
# .makeRe globstars (**/**/**)
picomatch x 2,545,674 ops/sec ±0.10% (99 runs sampled)
minimatch x 1,196,835 ops/sec ±0.63% (98 runs sampled)
# .makeRe with leading star (*.txt)
picomatch x 2,537,708 ops/sec ±0.11% (100 runs sampled)
minimatch x 345,284 ops/sec ±0.64% (96 runs sampled)
# .makeRe - basic braces ({a,b,c}*.txt)
picomatch x 505,430 ops/sec ±1.04% (94 runs sampled)
minimatch x 107,991 ops/sec ±0.54% (99 runs sampled)
# .makeRe - short ranges ({a..z}*.txt)
picomatch x 371,179 ops/sec ±2.91% (77 runs sampled)
minimatch x 14,104 ops/sec ±0.61% (99 runs sampled)
# .makeRe - medium ranges ({1..100000}*.txt)
picomatch x 384,958 ops/sec ±1.70% (82 runs sampled)
minimatch x 2.55 ops/sec ±3.22% (11 runs sampled)
# .makeRe - long ranges ({1..10000000}*.txt)
picomatch x 382,552 ops/sec ±1.52% (71 runs sampled)
minimatch x 0.83 ops/sec ±5.67% (7 runs sampled))
```
<br>
<br>
## Philosophies
The goal of this library is to be blazing fast, without compromising on accuracy.
**Accuracy**
The number one of goal of this library is accuracy. However, it's not unusual for different glob implementations to have different rules for matching behavior, even with simple wildcard matching. It gets increasingly more complicated when combinations of different features are combined, like when extglobs are combined with globstars, braces, slashes, and so on: `!(**/{a,b,*/c})`.
Thus, given that there is no canonical glob specification to use as a single source of truth when differences of opinion arise regarding behavior, sometimes we have to implement our best judgement and rely on feedback from users to make improvements.
**Performance**
Although this library performs well in benchmarks, and in most cases it's faster than other popular libraries we benchmarked against, we will always choose accuracy over performance. It's not helpful to anyone if our library is faster at returning the wrong answer.
<br>
<br>
## About
<details>
<summary><strong>Contributing</strong></summary>
Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new).
Please read the [contributing guide](.github/contributing.md) for advice on opening issues, pull requests, and coding standards.
</details>
<details>
<summary><strong>Running Tests</strong></summary>
Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:
```sh
npm install && npm test
```
</details>
<details>
<summary><strong>Building docs</strong></summary>
_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_
To generate the readme, run the following command:
```sh
npm install -g verbose/verb#dev verb-generate-readme && verb
```
</details>
### Author
**Jon Schlinkert**
* [GitHub Profile](https://github.com/jonschlinkert)
* [Twitter Profile](https://twitter.com/jonschlinkert)
* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert)
### License
Copyright © 2017-present, [Jon Schlinkert](https://github.com/jonschlinkert).
Released under the [MIT License](LICENSE).
@@ -0,0 +1,17 @@
'use strict';
const pico = require('./lib/picomatch');
const utils = require('./lib/utils');
function picomatch(glob, options, returnState = false) {
// default to os.platform()
if (options && (options.windows === null || options.windows === undefined)) {
// don't mutate the original options object
options = { ...options, windows: utils.isWindows() };
}
return pico(glob, options, returnState);
}
Object.assign(picomatch, pico);
module.exports = picomatch;
@@ -0,0 +1,184 @@
'use strict';
const WIN_SLASH = '\\\\/';
const WIN_NO_SLASH = `[^${WIN_SLASH}]`;
const DEFAULT_MAX_EXTGLOB_RECURSION = 0;
/**
* Posix glob regex
*/
const DOT_LITERAL = '\\.';
const PLUS_LITERAL = '\\+';
const QMARK_LITERAL = '\\?';
const SLASH_LITERAL = '\\/';
const ONE_CHAR = '(?=.)';
const QMARK = '[^/]';
const END_ANCHOR = `(?:${SLASH_LITERAL}|$)`;
const START_ANCHOR = `(?:^|${SLASH_LITERAL})`;
const DOTS_SLASH = `${DOT_LITERAL}{1,2}${END_ANCHOR}`;
const NO_DOT = `(?!${DOT_LITERAL})`;
const NO_DOTS = `(?!${START_ANCHOR}${DOTS_SLASH})`;
const NO_DOT_SLASH = `(?!${DOT_LITERAL}{0,1}${END_ANCHOR})`;
const NO_DOTS_SLASH = `(?!${DOTS_SLASH})`;
const QMARK_NO_DOT = `[^.${SLASH_LITERAL}]`;
const STAR = `${QMARK}*?`;
const SEP = '/';
const POSIX_CHARS = {
DOT_LITERAL,
PLUS_LITERAL,
QMARK_LITERAL,
SLASH_LITERAL,
ONE_CHAR,
QMARK,
END_ANCHOR,
DOTS_SLASH,
NO_DOT,
NO_DOTS,
NO_DOT_SLASH,
NO_DOTS_SLASH,
QMARK_NO_DOT,
STAR,
START_ANCHOR,
SEP
};
/**
* Windows glob regex
*/
const WINDOWS_CHARS = {
...POSIX_CHARS,
SLASH_LITERAL: `[${WIN_SLASH}]`,
QMARK: WIN_NO_SLASH,
STAR: `${WIN_NO_SLASH}*?`,
DOTS_SLASH: `${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$)`,
NO_DOT: `(?!${DOT_LITERAL})`,
NO_DOTS: `(?!(?:^|[${WIN_SLASH}])${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
NO_DOT_SLASH: `(?!${DOT_LITERAL}{0,1}(?:[${WIN_SLASH}]|$))`,
NO_DOTS_SLASH: `(?!${DOT_LITERAL}{1,2}(?:[${WIN_SLASH}]|$))`,
QMARK_NO_DOT: `[^.${WIN_SLASH}]`,
START_ANCHOR: `(?:^|[${WIN_SLASH}])`,
END_ANCHOR: `(?:[${WIN_SLASH}]|$)`,
SEP: '\\'
};
/**
* POSIX Bracket Regex
*/
const POSIX_REGEX_SOURCE = {
__proto__: null,
alnum: 'a-zA-Z0-9',
alpha: 'a-zA-Z',
ascii: '\\x00-\\x7F',
blank: ' \\t',
cntrl: '\\x00-\\x1F\\x7F',
digit: '0-9',
graph: '\\x21-\\x7E',
lower: 'a-z',
print: '\\x20-\\x7E ',
punct: '\\-!"#$%&\'()\\*+,./:;<=>?@[\\]^_`{|}~',
space: ' \\t\\r\\n\\v\\f',
upper: 'A-Z',
word: 'A-Za-z0-9_',
xdigit: 'A-Fa-f0-9'
};
module.exports = {
DEFAULT_MAX_EXTGLOB_RECURSION,
MAX_LENGTH: 1024 * 64,
POSIX_REGEX_SOURCE,
// regular expressions
REGEX_BACKSLASH: /\\(?![*+?^${}(|)[\]])/g,
REGEX_NON_SPECIAL_CHARS: /^[^@![\].,$*+?^{}()|\\/]+/,
REGEX_SPECIAL_CHARS: /[-*+?.^${}(|)[\]]/,
REGEX_SPECIAL_CHARS_BACKREF: /(\\?)((\W)(\3*))/g,
REGEX_SPECIAL_CHARS_GLOBAL: /([-*+?.^${}(|)[\]])/g,
REGEX_REMOVE_BACKSLASH: /(?:\[.*?[^\\]\]|\\(?=.))/g,
// Replace globs with equivalent patterns to reduce parsing time.
REPLACEMENTS: {
__proto__: null,
'***': '*',
'**/**': '**',
'**/**/**': '**'
},
// Digits
CHAR_0: 48, /* 0 */
CHAR_9: 57, /* 9 */
// Alphabet chars.
CHAR_UPPERCASE_A: 65, /* A */
CHAR_LOWERCASE_A: 97, /* a */
CHAR_UPPERCASE_Z: 90, /* Z */
CHAR_LOWERCASE_Z: 122, /* z */
CHAR_LEFT_PARENTHESES: 40, /* ( */
CHAR_RIGHT_PARENTHESES: 41, /* ) */
CHAR_ASTERISK: 42, /* * */
// Non-alphabetic chars.
CHAR_AMPERSAND: 38, /* & */
CHAR_AT: 64, /* @ */
CHAR_BACKWARD_SLASH: 92, /* \ */
CHAR_CARRIAGE_RETURN: 13, /* \r */
CHAR_CIRCUMFLEX_ACCENT: 94, /* ^ */
CHAR_COLON: 58, /* : */
CHAR_COMMA: 44, /* , */
CHAR_DOT: 46, /* . */
CHAR_DOUBLE_QUOTE: 34, /* " */
CHAR_EQUAL: 61, /* = */
CHAR_EXCLAMATION_MARK: 33, /* ! */
CHAR_FORM_FEED: 12, /* \f */
CHAR_FORWARD_SLASH: 47, /* / */
CHAR_GRAVE_ACCENT: 96, /* ` */
CHAR_HASH: 35, /* # */
CHAR_HYPHEN_MINUS: 45, /* - */
CHAR_LEFT_ANGLE_BRACKET: 60, /* < */
CHAR_LEFT_CURLY_BRACE: 123, /* { */
CHAR_LEFT_SQUARE_BRACKET: 91, /* [ */
CHAR_LINE_FEED: 10, /* \n */
CHAR_NO_BREAK_SPACE: 160, /* \u00A0 */
CHAR_PERCENT: 37, /* % */
CHAR_PLUS: 43, /* + */
CHAR_QUESTION_MARK: 63, /* ? */
CHAR_RIGHT_ANGLE_BRACKET: 62, /* > */
CHAR_RIGHT_CURLY_BRACE: 125, /* } */
CHAR_RIGHT_SQUARE_BRACKET: 93, /* ] */
CHAR_SEMICOLON: 59, /* ; */
CHAR_SINGLE_QUOTE: 39, /* ' */
CHAR_SPACE: 32, /* */
CHAR_TAB: 9, /* \t */
CHAR_UNDERSCORE: 95, /* _ */
CHAR_VERTICAL_LINE: 124, /* | */
CHAR_ZERO_WIDTH_NOBREAK_SPACE: 65279, /* \uFEFF */
/**
* Create EXTGLOB_CHARS
*/
extglobChars(chars) {
return {
'!': { type: 'negate', open: '(?:(?!(?:', close: `))${chars.STAR})` },
'?': { type: 'qmark', open: '(?:', close: ')?' },
'+': { type: 'plus', open: '(?:', close: ')+' },
'*': { type: 'star', open: '(?:', close: ')*' },
'@': { type: 'at', open: '(?:', close: ')' }
};
},
/**
* Create GLOB_CHARS
*/
globChars(win32) {
return win32 === true ? WINDOWS_CHARS : POSIX_CHARS;
}
};
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,361 @@
'use strict';
const scan = require('./scan');
const parse = require('./parse');
const utils = require('./utils');
const constants = require('./constants');
const isObject = val => val && typeof val === 'object' && !Array.isArray(val);
/**
* Creates a matcher function from one or more glob patterns. The
* returned function takes a string to match as its first argument,
* and returns true if the string is a match. The returned matcher
* function also takes a boolean as the second argument that, when true,
* returns an object with additional information.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch(glob[, options]);
*
* const isMatch = picomatch('*.!(*a)');
* console.log(isMatch('a.a')); //=> false
* console.log(isMatch('a.b')); //=> true
*
* // For environments without `node.js`, `picomatch/posix` provides you a dependency-free matcher, without automatic OS detection.
* const picomatch = require('picomatch/posix');
* // the same API, defaulting to posix paths
* const isMatch = picomatch('a/*');
* console.log(isMatch('a\\b')); //=> false
* console.log(isMatch('a/b')); //=> true
*
* // you can still configure the matcher function to accept windows paths
* const isMatch = picomatch('a/*', { options: windows });
* console.log(isMatch('a\\b')); //=> true
* console.log(isMatch('a/b')); //=> true
* ```
* @name picomatch
* @param {String|Array} `globs` One or more glob patterns.
* @param {Object=} `options`
* @return {Function=} Returns a matcher function.
* @api public
*/
const picomatch = (glob, options, returnState = false) => {
if (Array.isArray(glob)) {
const fns = glob.map(input => picomatch(input, options, returnState));
const arrayMatcher = str => {
for (const isMatch of fns) {
const state = isMatch(str);
if (state) return state;
}
return false;
};
return arrayMatcher;
}
const isState = isObject(glob) && glob.tokens && glob.input;
if (glob === '' || (typeof glob !== 'string' && !isState)) {
throw new TypeError('Expected pattern to be a non-empty string');
}
const opts = options || {};
const posix = opts.windows;
const regex = isState
? picomatch.compileRe(glob, options)
: picomatch.makeRe(glob, options, false, true);
const state = regex.state;
delete regex.state;
let isIgnored = () => false;
if (opts.ignore) {
const ignoreOpts = { ...options, ignore: null, onMatch: null, onResult: null };
isIgnored = picomatch(opts.ignore, ignoreOpts, returnState);
}
const matcher = (input, returnObject = false) => {
const { isMatch, match, output } = picomatch.test(input, regex, options, { glob, posix });
const result = { glob, state, regex, posix, input, output, match, isMatch };
if (typeof opts.onResult === 'function') {
opts.onResult(result);
}
if (isMatch === false) {
result.isMatch = false;
return returnObject ? result : false;
}
if (isIgnored(input)) {
if (typeof opts.onIgnore === 'function') {
opts.onIgnore(result);
}
result.isMatch = false;
return returnObject ? result : false;
}
if (typeof opts.onMatch === 'function') {
opts.onMatch(result);
}
return returnObject ? result : true;
};
if (returnState) {
matcher.state = state;
}
return matcher;
};
/**
* Test `input` with the given `regex`. This is used by the main
* `picomatch()` function to test the input string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.test(input, regex[, options]);
*
* console.log(picomatch.test('foo/bar', /^(?:([^/]*?)\/([^/]*?))$/));
* // { isMatch: true, match: [ 'foo/', 'foo', 'bar' ], output: 'foo/bar' }
* ```
* @param {String} `input` String to test.
* @param {RegExp} `regex`
* @return {Object} Returns an object with matching info.
* @api public
*/
picomatch.test = (input, regex, options, { glob, posix } = {}) => {
if (typeof input !== 'string') {
throw new TypeError('Expected input to be a string');
}
if (input === '') {
return { isMatch: false, output: '' };
}
const opts = options || {};
const format = opts.format || (posix ? utils.toPosixSlashes : null);
let match = input === glob;
let output = (match && format) ? format(input) : input;
if (match === false) {
output = format ? format(input) : input;
match = output === glob;
}
if (match === false || opts.capture === true) {
if (opts.matchBase === true || opts.basename === true) {
match = picomatch.matchBase(input, regex, options, posix);
} else {
match = regex.exec(output);
}
}
return { isMatch: Boolean(match), match, output };
};
/**
* Match the basename of a filepath.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.matchBase(input, glob[, options]);
* console.log(picomatch.matchBase('foo/bar.js', '*.js'); // true
* ```
* @param {String} `input` String to test.
* @param {RegExp|String} `glob` Glob pattern or regex created by [.makeRe](#makeRe).
* @return {Boolean}
* @api public
*/
picomatch.matchBase = (input, glob, options, posix = options && options.windows) => {
const regex = glob instanceof RegExp ? glob : picomatch.makeRe(glob, options);
return regex.test(utils.basename(input, { windows: posix }));
};
/**
* Returns true if **any** of the given glob `patterns` match the specified `string`.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.isMatch(string, patterns[, options]);
*
* console.log(picomatch.isMatch('a.a', ['b.*', '*.a'])); //=> true
* console.log(picomatch.isMatch('a.a', 'b.*')); //=> false
* ```
* @param {String|Array} str The string to test.
* @param {String|Array} patterns One or more glob patterns to use for matching.
* @param {Object} [options] See available [options](#options).
* @return {Boolean} Returns true if any patterns match `str`
* @api public
*/
picomatch.isMatch = (str, patterns, options) => picomatch(patterns, options)(str);
/**
* Parse a glob pattern to create the source string for a regular
* expression.
*
* ```js
* const picomatch = require('picomatch');
* const result = picomatch.parse(pattern[, options]);
* ```
* @param {String} `pattern`
* @param {Object} `options`
* @return {Object} Returns an object with useful properties and output to be used as a regex source string.
* @api public
*/
picomatch.parse = (pattern, options) => {
if (Array.isArray(pattern)) return pattern.map(p => picomatch.parse(p, options));
return parse(pattern, { ...options, fastpaths: false });
};
/**
* Scan a glob pattern to separate the pattern into segments.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.scan(input[, options]);
*
* const result = picomatch.scan('!./foo/*.js');
* console.log(result);
* { prefix: '!./',
* input: '!./foo/*.js',
* start: 3,
* base: 'foo',
* glob: '*.js',
* isBrace: false,
* isBracket: false,
* isGlob: true,
* isExtglob: false,
* isGlobstar: false,
* negated: true }
* ```
* @param {String} `input` Glob pattern to scan.
* @param {Object} `options`
* @return {Object} Returns an object with
* @api public
*/
picomatch.scan = (input, options) => scan(input, options);
/**
* Compile a regular expression from the `state` object returned by the
* [parse()](#parse) method.
*
* ```js
* const picomatch = require('picomatch');
* const state = picomatch.parse('*.js');
* // picomatch.compileRe(state[, options]);
*
* console.log(picomatch.compileRe(state));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {Object} `state`
* @param {Object} `options`
* @param {Boolean} `returnOutput` Intended for implementors, this argument allows you to return the raw output from the parser.
* @param {Boolean} `returnState` Adds the state to a `state` property on the returned regex. Useful for implementors and debugging.
* @return {RegExp}
* @api public
*/
picomatch.compileRe = (state, options, returnOutput = false, returnState = false) => {
if (returnOutput === true) {
return state.output;
}
const opts = options || {};
const prepend = opts.contains ? '' : '^';
const append = opts.contains ? '' : '$';
let source = `${prepend}(?:${state.output})${append}`;
if (state && state.negated === true) {
source = `^(?!${source}).*$`;
}
const regex = picomatch.toRegex(source, options);
if (returnState === true) {
regex.state = state;
}
return regex;
};
/**
* Create a regular expression from a parsed glob pattern.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.makeRe(state[, options]);
*
* const result = picomatch.makeRe('*.js');
* console.log(result);
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `state` The object returned from the `.parse` method.
* @param {Object} `options`
* @param {Boolean} `returnOutput` Implementors may use this argument to return the compiled output, instead of a regular expression. This is not exposed on the options to prevent end-users from mutating the result.
* @param {Boolean} `returnState` Implementors may use this argument to return the state from the parsed glob with the returned regular expression.
* @return {RegExp} Returns a regex created from the given pattern.
* @api public
*/
picomatch.makeRe = (input, options = {}, returnOutput = false, returnState = false) => {
if (!input || typeof input !== 'string') {
throw new TypeError('Expected a non-empty string');
}
let parsed = { negated: false, fastpaths: true };
if (options.fastpaths !== false && (input[0] === '.' || input[0] === '*')) {
parsed.output = parse.fastpaths(input, options);
}
if (!parsed.output) {
parsed = parse(input, options);
}
return picomatch.compileRe(parsed, options, returnOutput, returnState);
};
/**
* Create a regular expression from the given regex source string.
*
* ```js
* const picomatch = require('picomatch');
* // picomatch.toRegex(source[, options]);
*
* const { output } = picomatch.parse('*.js');
* console.log(picomatch.toRegex(output));
* //=> /^(?:(?!\.)(?=.)[^/]*?\.js)$/
* ```
* @param {String} `source` Regular expression source string.
* @param {Object} `options`
* @return {RegExp}
* @api public
*/
picomatch.toRegex = (source, options) => {
try {
const opts = options || {};
return new RegExp(source, opts.flags || (opts.nocase ? 'i' : ''));
} catch (err) {
if (options && options.debug === true) throw err;
return /$^/;
}
};
/**
* Picomatch constants.
* @return {Object}
*/
picomatch.constants = constants;
/**
* Expose "picomatch"
*/
module.exports = picomatch;
@@ -0,0 +1,403 @@
'use strict';
const utils = require('./utils');
const {
CHAR_ASTERISK, /* * */
CHAR_AT, /* @ */
CHAR_BACKWARD_SLASH, /* \ */
CHAR_COMMA, /* , */
CHAR_DOT, /* . */
CHAR_EXCLAMATION_MARK, /* ! */
CHAR_FORWARD_SLASH, /* / */
CHAR_LEFT_CURLY_BRACE, /* { */
CHAR_LEFT_PARENTHESES, /* ( */
CHAR_LEFT_SQUARE_BRACKET, /* [ */
CHAR_PLUS, /* + */
CHAR_QUESTION_MARK, /* ? */
CHAR_RIGHT_CURLY_BRACE, /* } */
CHAR_RIGHT_PARENTHESES, /* ) */
CHAR_RIGHT_SQUARE_BRACKET /* ] */
} = require('./constants');
const isPathSeparator = code => {
return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH;
};
const depth = token => {
if (token.isPrefix !== true) {
token.depth = token.isGlobstar ? Infinity : 1;
}
};
/**
* Quickly scans a glob pattern and returns an object with a handful of
* useful properties, like `isGlob`, `path` (the leading non-glob, if it exists),
* `glob` (the actual pattern), `negated` (true if the path starts with `!` but not
* with `!(`) and `negatedExtglob` (true if the path starts with `!(`).
*
* ```js
* const pm = require('picomatch');
* console.log(pm.scan('foo/bar/*.js'));
* { isGlob: true, input: 'foo/bar/*.js', base: 'foo/bar', glob: '*.js' }
* ```
* @param {String} `str`
* @param {Object} `options`
* @return {Object} Returns an object with tokens and regex source string.
* @api public
*/
const scan = (input, options) => {
const opts = options || {};
const length = input.length - 1;
const scanToEnd = opts.parts === true || opts.tokens === true || opts.scanToEnd === true;
const slashes = [];
const tokens = [];
const parts = [];
let str = input;
let index = -1;
let start = 0;
let lastIndex = 0;
let isBrace = false;
let isBracket = false;
let isGlob = false;
let isExtglob = false;
let isGlobstar = false;
let braceEscaped = false;
let backslashes = false;
let negated = false;
let negatedExtglob = false;
let finished = false;
let braces = 0;
let prev;
let code;
let token = { value: '', depth: 0, isGlob: false };
const eos = () => index >= length;
const peek = () => str.charCodeAt(index + 1);
const advance = () => {
prev = code;
return str.charCodeAt(++index);
};
while (index < length) {
code = advance();
let next;
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
code = advance();
if (code === CHAR_LEFT_CURLY_BRACE) {
braceEscaped = true;
}
continue;
}
if (braceEscaped === true || code === CHAR_LEFT_CURLY_BRACE) {
braces++;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_CURLY_BRACE) {
braces++;
continue;
}
if (braceEscaped !== true && code === CHAR_DOT && (code = advance()) === CHAR_DOT) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (braceEscaped !== true && code === CHAR_COMMA) {
isBrace = token.isBrace = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_RIGHT_CURLY_BRACE) {
braces--;
if (braces === 0) {
braceEscaped = false;
isBrace = token.isBrace = true;
finished = true;
break;
}
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_FORWARD_SLASH) {
slashes.push(index);
tokens.push(token);
token = { value: '', depth: 0, isGlob: false };
if (finished === true) continue;
if (prev === CHAR_DOT && index === (start + 1)) {
start += 2;
continue;
}
lastIndex = index + 1;
continue;
}
if (opts.noext !== true) {
const isExtglobChar = code === CHAR_PLUS
|| code === CHAR_AT
|| code === CHAR_ASTERISK
|| code === CHAR_QUESTION_MARK
|| code === CHAR_EXCLAMATION_MARK;
if (isExtglobChar === true && peek() === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
isExtglob = token.isExtglob = true;
finished = true;
if (code === CHAR_EXCLAMATION_MARK && index === start) {
negatedExtglob = true;
}
if (scanToEnd === true) {
let parens = 0;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_PARENTHESES) {
parens++;
continue;
}
if (code === CHAR_RIGHT_PARENTHESES && --parens === 0) {
finished = true;
break;
}
}
continue;
}
break;
}
}
if (code === CHAR_ASTERISK) {
if (prev === CHAR_ASTERISK) isGlobstar = token.isGlobstar = true;
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_QUESTION_MARK) {
isGlob = token.isGlob = true;
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
if (code === CHAR_LEFT_SQUARE_BRACKET) {
while (eos() !== true && (next = advance())) {
if (next === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (next === CHAR_RIGHT_SQUARE_BRACKET) {
isBracket = token.isBracket = true;
isGlob = token.isGlob = true;
finished = true;
break;
}
}
if (scanToEnd === true) {
continue;
}
break;
}
if (opts.nonegate !== true && code === CHAR_EXCLAMATION_MARK && index === start) {
negated = token.negated = true;
start++;
continue;
}
if (opts.noparen !== true && code === CHAR_LEFT_PARENTHESES) {
isGlob = token.isGlob = true;
if (scanToEnd === true) {
let parens = 1;
while (eos() !== true && (code = advance())) {
if (code === CHAR_BACKWARD_SLASH) {
backslashes = token.backslashes = true;
advance();
continue;
}
if (code === CHAR_LEFT_PARENTHESES) {
parens++;
continue;
}
if (code === CHAR_RIGHT_PARENTHESES && --parens === 0) {
finished = true;
break;
}
}
continue;
}
break;
}
if (isGlob === true) {
finished = true;
if (scanToEnd === true) {
continue;
}
break;
}
}
if (opts.noext === true) {
isExtglob = false;
isGlob = false;
}
let base = str;
let prefix = '';
let glob = '';
if (start > 0) {
prefix = str.slice(0, start);
str = str.slice(start);
lastIndex -= start;
}
if (base && isGlob === true && lastIndex > 0) {
base = str.slice(0, lastIndex);
glob = str.slice(lastIndex);
} else if (isGlob === true) {
base = '';
glob = str;
} else {
base = str;
}
if (base && base !== '' && base !== '/' && base !== str) {
if (isPathSeparator(base.charCodeAt(base.length - 1))) {
base = base.slice(0, -1);
}
}
if (opts.unescape === true) {
if (glob) glob = utils.removeBackslashes(glob);
if (base && backslashes === true) {
base = utils.removeBackslashes(base);
}
}
const state = {
prefix,
input,
start,
base,
glob,
isBrace,
isBracket,
isGlob,
isExtglob,
isGlobstar,
negated,
negatedExtglob
};
if (opts.tokens === true) {
state.maxDepth = 0;
if (!isPathSeparator(code)) {
tokens.push(token);
}
state.tokens = tokens;
}
if (opts.parts === true || opts.tokens === true) {
let prevIndex;
for (let idx = 0; idx < slashes.length; idx++) {
const n = prevIndex !== undefined ? prevIndex + 1 : start;
const i = slashes[idx];
const value = input.slice(n, i);
if (opts.tokens) {
if (idx === 0 && start !== 0) {
tokens[idx].isPrefix = true;
tokens[idx].value = prefix;
} else {
tokens[idx].value = value;
}
depth(tokens[idx]);
state.maxDepth += tokens[idx].depth;
}
if (i >= start) {
parts.push(value);
prevIndex = i;
}
}
const n = prevIndex !== undefined ? prevIndex + 1 : start;
const value = input.slice(n);
parts.push(value);
if (opts.tokens && prevIndex && prevIndex + 1 < input.length) {
tokens[tokens.length - 1].value = value;
depth(tokens[tokens.length - 1]);
state.maxDepth += tokens[tokens.length - 1].depth;
}
state.slashes = slashes;
state.parts = parts;
}
return state;
};
module.exports = scan;
@@ -0,0 +1,72 @@
/*global navigator*/
'use strict';
const {
REGEX_BACKSLASH,
REGEX_REMOVE_BACKSLASH,
REGEX_SPECIAL_CHARS,
REGEX_SPECIAL_CHARS_GLOBAL
} = require('./constants');
exports.isObject = val => val !== null && typeof val === 'object' && !Array.isArray(val);
exports.hasRegexChars = str => REGEX_SPECIAL_CHARS.test(str);
exports.isRegexChar = str => str.length === 1 && exports.hasRegexChars(str);
exports.escapeRegex = str => str.replace(REGEX_SPECIAL_CHARS_GLOBAL, '\\$1');
exports.toPosixSlashes = str => str.replace(REGEX_BACKSLASH, '/');
exports.isWindows = () => {
if (typeof navigator !== 'undefined' && navigator.platform) {
const platform = navigator.platform.toLowerCase();
return platform === 'win32' || platform === 'windows';
}
if (typeof process !== 'undefined' && process.platform) {
return process.platform === 'win32';
}
return false;
};
exports.removeBackslashes = str => {
return str.replace(REGEX_REMOVE_BACKSLASH, match => {
return match === '\\' ? '' : match;
});
};
exports.escapeLast = (input, char, lastIdx) => {
const idx = input.lastIndexOf(char, lastIdx);
if (idx === -1) return input;
if (input[idx - 1] === '\\') return exports.escapeLast(input, char, idx - 1);
return `${input.slice(0, idx)}\\${input.slice(idx)}`;
};
exports.removePrefix = (input, state = {}) => {
let output = input;
if (output.startsWith('./')) {
output = output.slice(2);
state.prefix = './';
}
return output;
};
exports.wrapOutput = (input, state = {}, options = {}) => {
const prepend = options.contains ? '' : '^';
const append = options.contains ? '' : '$';
let output = `${prepend}(?:${input})${append}`;
if (state.negated === true) {
output = `(?:^(?!${output}).*$)`;
}
return output;
};
exports.basename = (path, { windows } = {}) => {
const segs = path.split(windows ? /[\\/]/ : '/');
const last = segs[segs.length - 1];
if (last === '') {
return segs[segs.length - 2];
}
return last;
};
@@ -0,0 +1,83 @@
{
"name": "picomatch",
"description": "Blazing fast and accurate glob matcher written in JavaScript, with no dependencies and full support for standard and extended Bash glob features, including braces, extglobs, POSIX brackets, and regular expressions.",
"version": "4.0.7",
"homepage": "https://github.com/micromatch/picomatch",
"author": "Jon Schlinkert (https://github.com/jonschlinkert)",
"funding": "https://github.com/sponsors/jonschlinkert",
"repository": "micromatch/picomatch",
"bugs": {
"url": "https://github.com/micromatch/picomatch/issues"
},
"license": "MIT",
"files": [
"index.js",
"posix.js",
"lib"
],
"sideEffects": false,
"main": "index.js",
"engines": {
"node": ">=12"
},
"scripts": {
"lint": "eslint --cache --cache-location node_modules/.cache/.eslintcache --report-unused-disable-directives --ignore-path .gitignore .",
"mocha": "mocha --reporter dot",
"test": "npm run lint && npm run mocha",
"test:ci": "npm run test:cover",
"test:cover": "nyc npm run mocha"
},
"devDependencies": {
"eslint": "^8.57.0",
"fill-range": "^7.0.1",
"gulp-format-md": "^2.0.0",
"mocha": "^10.4.0",
"nyc": "^15.1.0"
},
"keywords": [
"glob",
"match",
"picomatch"
],
"nyc": {
"reporter": [
"html",
"lcov",
"text-summary",
"cobertura"
]
},
"verb": {
"toc": {
"render": true,
"method": "preWrite",
"maxdepth": 3
},
"layout": "empty",
"tasks": [
"readme"
],
"plugins": [
"gulp-format-md"
],
"lint": {
"reflinks": true
},
"related": {
"list": [
"braces",
"micromatch"
]
},
"reflinks": [
"braces",
"expand-brackets",
"extglob",
"fill-range",
"micromatch",
"minimatch",
"nanomatch",
"picomatch"
]
}
}
@@ -0,0 +1,3 @@
'use strict';
module.exports = require('./lib/picomatch');
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2021-PRESENT Anthony Fu <https://github.com/antfu>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,476 @@
# unplugin-auto-import
[![NPM version](https://img.shields.io/npm/v/unplugin-auto-import?color=a1b858&label=)](https://www.npmjs.com/package/unplugin-auto-import)
Auto import APIs on-demand for Vite, Webpack, Rspack, Rollup and esbuild. With TypeScript support. Powered by [unplugin](https://github.com/unjs/unplugin).
---
without
```ts
import { computed, ref } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
```
with
```ts
const count = ref(0)
const doubled = computed(() => count.value * 2)
```
---
without
```tsx
import { useState } from 'react'
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
```
with
```tsx
export function Counter() {
const [count, setCount] = useState(0)
return <div>{ count }</div>
}
```
## Install
```bash
npm i -D unplugin-auto-import
```
<details>
<summary>Vite</summary><br>
```ts
// vite.config.ts
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({ /* options */ }),
],
})
```
Example: [`playground/`](./playground/)
<br></details>
<details>
<summary>Rollup</summary><br>
```ts
// rollup.config.js
import AutoImport from 'unplugin-auto-import/rollup'
export default {
plugins: [
AutoImport({ /* options */ }),
// other plugins
],
}
```
<br></details>
<details>
<summary>Webpack</summary><br>
```ts
// webpack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/webpack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Rspack</summary><br>
```ts
// rspack.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/rspack').default({ /* options */ }),
],
}
```
<br></details>
<details>
<summary>Nuxt</summary><br>
> You **don't need** this plugin for Nuxt, it's already built-in.
<br></details>
<details>
<summary>Vue CLI</summary><br>
```ts
// vue.config.js
module.exports = {
/* ... */
plugins: [
require('unplugin-auto-import/webpack').default({ /* options */ }),
],
}
```
You can also rename the Vue configuration file to `vue.config.mjs` and use static import syntax (you should use latest `@vue/cli-service ^5.0.8`):
```ts
// vue.config.mjs
import AutoImport from 'unplugin-auto-import/webpack'
export default {
configureWebpack: {
plugins: [
AutoImport({ /* options */ }),
],
},
}
```
<br></details>
<details>
<summary>Quasar</summary><br>
```ts
// vite.config.js [Vite]
import AutoImport from 'unplugin-auto-import/vite'
import { defineConfig } from 'vite'
export default defineConfig({
plugins: [
AutoImport({ /* options */ })
]
})
```
```ts
// quasar.conf.js [Webpack]
const AutoImportPlugin = require('unplugin-auto-import/webpack').default
module.exports = {
build: {
chainWebpack(chain) {
chain.plugin('unplugin-auto-import').use(
AutoImportPlugin({ /* options */ }),
)
},
},
}
```
<br></details>
<details>
<summary>esbuild</summary><br>
```ts
// esbuild.config.js
import { build } from 'esbuild'
import AutoImport from 'unplugin-auto-import/esbuild'
build({
/* ... */
plugins: [
AutoImport({
/* options */
}),
],
})
```
<br></details>
<details>
<summary>Astro</summary><br>
```ts
// astro.config.mjs
import AutoImport from 'unplugin-auto-import/astro'
export default defineConfig({
integrations: [
AutoImport({
/* options */
})
],
})
```
<br></details>
## Configuration
```ts
AutoImport({
// targets to transform
include: [
/\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
/\.vue$/,
/\.vue\?vue/, // .vue
/\.md$/, // .md
],
// global imports to register
imports: [
// presets
'vue',
'vue-router',
// custom
{
'@vueuse/core': [
// named imports
'useMouse', // import { useMouse } from '@vueuse/core',
// alias
['useFetch', 'useMyFetch'], // import { useFetch as useMyFetch } from '@vueuse/core',
],
'axios': [
// default imports
['default', 'axios'], // import { default as axios } from 'axios',
],
'[package-name]': [
'[import-names]',
// alias
['[from]', '[alias]'],
],
},
// example type import
{
from: 'vue-router',
imports: ['RouteLocationRaw'],
type: true,
},
],
// Array of strings of regexes that contains imports meant to be filtered out.
ignore: [
'useMouse',
'useFetch'
],
// Enable auto import by filename for default module exports under directories
defaultExportByFilename: false,
// Options for scanning directories for auto import
dirsScanOptions: {
types: true // Enable auto import the types under the directories
},
// Auto import for module exports under directories
// by default it only scan one level of modules under the directory
dirs: [
'./hooks',
'./composables', // only root modules
'./composables/**', // all nested modules
// ...
{
glob: './hooks',
types: true // enable import the types
},
{
glob: './composables',
types: false // If top level dirsScanOptions.types importing enabled, just only disable this directory
}
// ...
],
// Filepath to generate corresponding .d.ts file.
// Defaults to './auto-imports.d.ts' when `typescript` is installed locally.
// Set `false` to disable.
dts: './auto-imports.d.ts',
// Array of strings of regexes that contains imports meant to be ignored during
// the declaration file generation. You may find this useful when you need to provide
// a custom signature for a function.
ignoreDts: [
'ignoredFunction',
/^ignore_/
],
// Auto import inside Vue template
// see https://github.com/unjs/unimport/pull/15 and https://github.com/unjs/unimport/pull/72
vueTemplate: false,
// Auto import directives inside Vue template
// see https://github.com/unjs/unimport/pull/374
vueDirectives: undefined,
// Custom resolvers, compatible with `unplugin-vue-components`
// see https://github.com/antfu/unplugin-auto-import/pull/23/
resolvers: [
/* ... */
],
// Include auto-imported packages in Vite's `optimizeDeps` options
// Recommend to enable
viteOptimizeDeps: true,
// Inject the imports at the end of other imports
injectAtEnd: true,
// Generate corresponding .eslintrc-auto-import.json file.
// eslint globals Docs - https://eslint.org/docs/user-guide/configuring/language-options#specifying-globals
eslintrc: {
enabled: false, // Default `false`
// provide path ending with `.mjs` or `.cjs` to generate the file with the respective format
filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
},
// Generate corresponding .biomelintrc-auto-import.json file.
// biomejs extends Docs - https://biomejs.dev/guides/how-biome-works/#the-extends-option
biomelintrc: {
enabled: false, // Default `false`
filepath: './.biomelintrc-auto-import.json', // Default `./.biomelintrc-auto-import.json`
},
// Save unimport items into a JSON file for other tools to consume
dumpUnimportItems: './auto-imports.json', // Default `false`
})
```
Refer to the [type definitions](./src/types.ts) for more options.
## Presets
See [src/presets](./src/presets).
## Package Presets
We only provide presets for the most popular packages, to use any package not included here you can install it as dev dependency and add it to the `packagePresets` array option:
```ts
AutoImport({
/* other options */
packagePresets: ['detect-browser-es'/* other local package names */]
})
```
You can check the [Svelte example](./examples/vite-svelte) for a working example registering `detect-browser-es` package preset and auto importing `detect` function in [App.svelte](./examples/vite-svelte/src/App.svelte).
Please refer to the [unimport PackagePresets jsdocs](https://github.com/unjs/unimport/blob/main/src/types.ts) for more information about options like `ignore` or `cache`.
**Note**: ensure local packages used have package exports configured properly, otherwise the corresponding modules exports will not be detected.
## TypeScript
In order to properly hint types for auto-imported APIs
<table>
<tr>
<td width="400px" valign="top">
1. Enable `options.dts` so that `auto-imports.d.ts` file is automatically generated
2. Make sure `auto-imports.d.ts` is not excluded in `tsconfig.json`
</td>
<td width="600px"><br>
```ts
AutoImport({
dts: true // or a custom path
})
```
</td>
</tr>
</table>
## ESLint
> 💡 When using TypeScript, we recommend to **disable** `no-undef` rule directly as TypeScript already check for them and you don't need to worry about this.
If you have encountered ESLint error of `no-undef`:
<table>
<tr>
<td width="400px">
1. Enable `eslintrc.enabled`
</td>
<td width="600px"><br>
```ts
AutoImport({
eslintrc: {
enabled: true, // <-- this
},
})
```
</td></tr></table>
<table><tr><td width="400px">
2. Update your `eslintrc`:
[Extending Configuration Files](https://eslint.org/docs/user-guide/configuring/configuration-files#extending-configuration-files)
</td>
<td width="600px"><br>
```ts
// .eslintrc.js
module.exports = {
extends: [
'./.eslintrc-auto-import.json',
],
}
```
</td>
</tr>
</table>
## FAQ
### Compare to [`unimport`](https://github.com/unjs/unimport)
From v0.8.0, `unplugin-auto-import` **uses** `unimport` underneath. `unimport` is designed to be a lower-level tool (it also powered Nuxt's auto import). You can think `unplugin-auto-import` is a wrapper of it that provides more user-friendly config APIs and capabilities like resolvers. Development of new features will mostly happen in `unimport` from now.
### Compare to [`vue-global-api`](https://github.com/antfu/vue-global-api)
You can think of this plugin as a successor to `vue-global-api`, but offering much more flexibility and bindings with libraries other than Vue (e.g. React).
###### Pros
- Flexible and customizable
- Tree-shakable (on-demand transforming)
- No global population
###### Cons
- Relying on build tools integrations (while `vue-global-api` is pure runtime) - but hey, we have supported quite a few of them already!
## Sponsors
<p align="center">
<a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
<img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
</a>
</p>
## License
[MIT](./LICENSE) License © 2021-PRESENT [Anthony Fu](https://github.com/antfu)
@@ -0,0 +1,179 @@
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
export {}
declare global {
const $: typeof import('vue/macros')['$']
const $$: typeof import('vue/macros')['$$']
const $computed: typeof import('vue/macros')['$computed']
const $customRef: typeof import('vue/macros')['$customRef']
const $ref: typeof import('vue/macros')['$ref']
const $shallowRef: typeof import('vue/macros')['$shallowRef']
const $toRef: typeof import('vue/macros')['$toRef']
const EffectScope: typeof import('vue')['EffectScope']
const THREE: typeof import('three.js')
const acceptHMRUpdate: typeof import('pinia')['acceptHMRUpdate']
const afterAll: typeof import('vitest')['afterAll']
const afterEach: typeof import('vitest')['afterEach']
const afterUpdate: typeof import('svelte')['afterUpdate']
const assert: typeof import('vitest')['assert']
const backIn: typeof import('svelte/easing')['backIn']
const backInOut: typeof import('svelte/easing')['backInOut']
const backOut: typeof import('svelte/easing')['backOut']
const beforeAll: typeof import('vitest')['beforeAll']
const beforeEach: typeof import('vitest')['beforeEach']
const beforeUpdate: typeof import('svelte')['beforeUpdate']
const blur: typeof import('svelte/transition')['blur']
const bounceIn: typeof import('svelte/easing')['bounceIn']
const bounceInOut: typeof import('svelte/easing')['bounceInOut']
const bounceOut: typeof import('svelte/easing')['bounceOut']
const chai: typeof import('vitest')['chai']
const circIn: typeof import('svelte/easing')['circIn']
const circInOut: typeof import('svelte/easing')['circInOut']
const circOut: typeof import('svelte/easing')['circOut']
const computed: typeof import('vue')['computed']
const createApp: typeof import('vue')['createApp']
const createEventDispatcher: typeof import('svelte')['createEventDispatcher']
const createPinia: typeof import('pinia')['createPinia']
const createRef: typeof import('react')['createRef']
const crossfade: typeof import('svelte/transition')['crossfade']
const cubicIn: typeof import('svelte/easing')['cubicIn']
const cubicInOut: typeof import('svelte/easing')['cubicInOut']
const cubicOut: typeof import('svelte/easing')['cubicOut']
const customDefault: typeof import('custom')['default']
const customDefaultAlias: typeof import('custom')['default']
const customNamed: typeof import('custom')['customNamed']
const customRef: typeof import('vue')['customRef']
const defineAsyncComponent: typeof import('vue')['defineAsyncComponent']
const defineComponent: typeof import('vue')['defineComponent']
const defineStore: typeof import('pinia')['defineStore']
const derived: typeof import('svelte/store')['derived']
const describe: typeof import('vitest')['describe']
const draw: typeof import('svelte/transition')['draw']
const effectScope: typeof import('vue')['effectScope']
const elasticIn: typeof import('svelte/easing')['elasticIn']
const elasticInOut: typeof import('svelte/easing')['elasticInOut']
const elasticOut: typeof import('svelte/easing')['elasticOut']
const expect: typeof import('vitest')['expect']
const expoIn: typeof import('svelte/easing')['expoIn']
const expoInOut: typeof import('svelte/easing')['expoInOut']
const expoOut: typeof import('svelte/easing')['expoOut']
const fade: typeof import('svelte/transition')['fade']
const flip: typeof import('svelte/animate')['flip']
const fly: typeof import('svelte/transition')['fly']
const forwardRef: typeof import('react')['forwardRef']
const get: typeof import('svelte/store')['get']
const getActivePinia: typeof import('pinia')['getActivePinia']
const getAllContexts: typeof import('svelte')['getAllContexts']
const getContext: typeof import('svelte')['getContext']
const getCurrentInstance: typeof import('vue')['getCurrentInstance']
const getCurrentScope: typeof import('vue')['getCurrentScope']
const h: typeof import('vue')['h']
const hasContext: typeof import('svelte')['hasContext']
const inject: typeof import('vue')['inject']
const isProxy: typeof import('vue')['isProxy']
const isReactive: typeof import('vue')['isReactive']
const isReadonly: typeof import('vue')['isReadonly']
const isRef: typeof import('vue')['isRef']
const it: typeof import('vitest')['it']
const lazy: typeof import('react')['lazy']
const linear: typeof import('svelte/easing')['linear']
const mapActions: typeof import('pinia')['mapActions']
const mapGetters: typeof import('pinia')['mapGetters']
const mapState: typeof import('pinia')['mapState']
const mapStores: typeof import('pinia')['mapStores']
const mapWritableState: typeof import('pinia')['mapWritableState']
const markRaw: typeof import('vue')['markRaw']
const memo: typeof import('react')['memo']
const nextTick: typeof import('vue')['nextTick']
const onActivated: typeof import('vue')['onActivated']
const onBeforeMount: typeof import('vue')['onBeforeMount']
const onBeforeUnmount: typeof import('vue')['onBeforeUnmount']
const onBeforeUpdate: typeof import('vue')['onBeforeUpdate']
const onDeactivated: typeof import('vue')['onDeactivated']
const onDestroy: typeof import('svelte')['onDestroy']
const onErrorCaptured: typeof import('vue')['onErrorCaptured']
const onMount: typeof import('svelte')['onMount']
const onMounted: typeof import('vue')['onMounted']
const onRenderTracked: typeof import('vue')['onRenderTracked']
const onRenderTriggered: typeof import('vue')['onRenderTriggered']
const onScopeDispose: typeof import('vue')['onScopeDispose']
const onServerPrefetch: typeof import('vue')['onServerPrefetch']
const onUnmounted: typeof import('vue')['onUnmounted']
const onUpdated: typeof import('vue')['onUpdated']
const onWatcherCleanup: typeof import('vue')['onWatcherCleanup']
const provide: typeof import('vue')['provide']
const quadIn: typeof import('svelte/easing')['quadIn']
const quadInOut: typeof import('svelte/easing')['quadInOut']
const quadOut: typeof import('svelte/easing')['quadOut']
const quartIn: typeof import('svelte/easing')['quartIn']
const quartInOut: typeof import('svelte/easing')['quartInOut']
const quartOut: typeof import('svelte/easing')['quartOut']
const quintIn: typeof import('svelte/easing')['quintIn']
const quintInOut: typeof import('svelte/easing')['quintInOut']
const quintOut: typeof import('svelte/easing')['quintOut']
const reactive: typeof import('vue')['reactive']
const readable: typeof import('svelte/store')['readable']
const readonly: typeof import('vue')['readonly']
const ref: typeof import('vue')['ref']
const resolveComponent: typeof import('vue')['resolveComponent']
const scale: typeof import('svelte/transition')['scale']
const setActivePinia: typeof import('pinia')['setActivePinia']
const setContext: typeof import('svelte')['setContext']
const setMapStoreSuffix: typeof import('pinia')['setMapStoreSuffix']
const shallowReactive: typeof import('vue')['shallowReactive']
const shallowReadonly: typeof import('vue')['shallowReadonly']
const shallowRef: typeof import('vue')['shallowRef']
const sineIn: typeof import('svelte/easing')['sineIn']
const sineInOut: typeof import('svelte/easing')['sineInOut']
const sineOut: typeof import('svelte/easing')['sineOut']
const slide: typeof import('svelte/transition')['slide']
const spring: typeof import('svelte/motion')['spring']
const startTransition: typeof import('react')['startTransition']
const storeToRefs: typeof import('pinia')['storeToRefs']
const suite: typeof import('vitest')['suite']
const test: typeof import('vitest')['test']
const tick: typeof import('svelte')['tick']
const toRaw: typeof import('vue')['toRaw']
const toRef: typeof import('vue')['toRef']
const toRefs: typeof import('vue')['toRefs']
const toValue: typeof import('vue')['toValue']
const triggerRef: typeof import('vue')['triggerRef']
const tweened: typeof import('svelte/motion')['tweened']
const unref: typeof import('vue')['unref']
const useAttrs: typeof import('vue')['useAttrs']
const useCallback: typeof import('react')['useCallback']
const useContext: typeof import('react')['useContext']
const useCssModule: typeof import('vue')['useCssModule']
const useCssVars: typeof import('vue')['useCssVars']
const useDebugValue: typeof import('react')['useDebugValue']
const useDeferredValue: typeof import('react')['useDeferredValue']
const useDialogPluginComponent: typeof import('quasar')['useDialogPluginComponent']
const useEffect: typeof import('react')['useEffect']
const useFormChild: typeof import('quasar')['useFormChild']
const useId: typeof import('react')['useId']
const useImperativeHandle: typeof import('react')['useImperativeHandle']
const useInsertionEffect: typeof import('react')['useInsertionEffect']
const useLayoutEffect: typeof import('react')['useLayoutEffect']
const useMemo: typeof import('react')['useMemo']
const useMeta: typeof import('quasar')['useMeta']
const useModel: typeof import('vue')['useModel']
const useQuasar: typeof import('quasar')['useQuasar']
const useReducer: typeof import('react')['useReducer']
const useRef: typeof import('react')['useRef']
const useSlots: typeof import('vue')['useSlots']
const useState: typeof import('react')['useState']
const useSyncExternalStore: typeof import('react')['useSyncExternalStore']
const useTemplateRef: typeof import('vue')['useTemplateRef']
const useTransition: typeof import('react')['useTransition']
const vi: typeof import('vitest')['vi']
const vitest: typeof import('vitest')['vitest']
const watch: typeof import('vue')['watch']
const watchEffect: typeof import('vue')['watchEffect']
const watchPostEffect: typeof import('vue')['watchPostEffect']
const watchSyncEffect: typeof import('vue')['watchSyncEffect']
const writable: typeof import('svelte/store')['writable']
}
@@ -0,0 +1,21 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/astro.ts
function astro_default(options) {
return {
name: "unplugin-auto-import",
hooks: {
"astro:config:setup": async (astro) => {
var _a;
(_a = astro.config.vite).plugins || (_a.plugins = []);
astro.config.vite.plugins.push(_chunkA6NGEVNDcjs.unplugin_default.vite(options));
}
}
};
}
exports.default = astro_default;
@@ -0,0 +1,13 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare function export_default(options: Options): {
name: string;
hooks: {
'astro:config:setup': (astro: any) => Promise<void>;
};
};
export { export_default as default };
@@ -0,0 +1,13 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare function export_default(options: Options): {
name: string;
hooks: {
'astro:config:setup': (astro: any) => Promise<void>;
};
};
export { export_default as default };
@@ -0,0 +1,21 @@
import {
unplugin_default
} from "./chunk-WD3TZPPT.js";
import "./chunk-DTT25XJ5.js";
// src/astro.ts
function astro_default(options) {
return {
name: "unplugin-auto-import",
hooks: {
"astro:config:setup": async (astro) => {
var _a;
(_a = astro.config.vite).plugins || (_a.plugins = []);
astro.config.vite.plugins.push(unplugin_default.vite(options));
}
}
};
}
export {
astro_default as default
};
@@ -0,0 +1,608 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/presets/index.ts
var _unimport = require('unimport');
// src/presets/ahooks.ts
var _fs = require('fs');
var _localpkg = require('local-pkg');
var _cache;
var ahooks_default = () => {
if (!_cache) {
let indexesJson;
try {
const path = _localpkg.resolveModule.call(void 0, "ahooks/metadata.json");
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
}
if (indexesJson) {
_cache = {
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
};
}
}
return _cache || {};
};
// src/presets/jotai.ts
var jotai = {
jotai: [
"atom",
"useAtom",
"useAtomValue",
"useSetAtom"
]
};
var jotaiUtils = {
"jotai/utils": [
"atomWithReset",
"useResetAtom",
"useReducerAtom",
"atomWithReducer",
"atomFamily",
"selectAtom",
"useAtomCallback",
"freezeAtom",
"freezeAtomCreator",
"splitAtom",
"atomWithDefault",
"waitForAll",
"atomWithStorage",
"atomWithHash",
"createJSONStorage",
"atomWithObservable",
"useHydrateAtoms",
"loadable"
]
};
// src/presets/mobx.ts
var mobx = [
// https://mobx.js.org/api.html
"makeObservable",
"makeAutoObservable",
"extendObservable",
"observable",
"action",
"runInAction",
"flow",
"flowResult",
"computed",
"autorun",
"reaction",
"when",
"onReactionError",
"intercept",
"observe",
"onBecomeObserved",
"onBecomeUnobserved",
"toJS"
];
var mobx_default = {
mobx: [
// https://mobx.js.org/api.html
...mobx
]
};
// src/presets/mobx-react-lite.ts
var mobx_react_lite_default = {
// https://mobx.js.org/api.html
"mobx-react-lite": [
"observer",
"Observer",
"useLocalObservable"
]
};
// src/presets/preact.ts
var preact_default = {
"preact/hooks": [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer"
]
};
// src/presets/quasar.ts
var quasar_default = {
quasar: [
// https://quasar.dev/vue-composables
"useQuasar",
"useDialogPluginComponent",
"useFormChild",
"useMeta"
]
};
// src/presets/react.ts
var CommonReactAPI = [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer",
"useImperativeHandle",
"useDebugValue",
"useDeferredValue",
"useLayoutEffect",
"useTransition",
"startTransition",
"useSyncExternalStore",
"useInsertionEffect",
"useId",
"lazy",
"memo",
"createRef",
"forwardRef"
];
var react_default = {
react: CommonReactAPI
};
// src/presets/react-i18next.ts
var react_i18next_default = {
"react-i18next": ["useTranslation"]
};
// src/presets/react-router.ts
var ReactRouterHooks = [
"useOutletContext",
"useHref",
"useInRouterContext",
"useLocation",
"useNavigationType",
"useNavigate",
"useOutlet",
"useParams",
"useResolvedPath",
"useRoutes"
];
var react_router_default = {
"react-router": [
...ReactRouterHooks
]
};
// src/presets/react-router-dom.ts
var react_router_dom_default = {
"react-router-dom": [
...ReactRouterHooks,
// react-router-dom only hooks
"useLinkClickHandler",
"useSearchParams",
// react-router-dom Component
// call once in general
// 'BrowserRouter',
// 'HashRouter',
// 'MemoryRouter',
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Routes"
]
};
// src/presets/recoil.ts
var recoil_default = {
// https://recoiljs.org/docs/api-reference/core/atom/
recoil: [
"atom",
"selector",
"useRecoilState",
"useRecoilValue",
"useSetRecoilState",
"useResetRecoilState",
"useRecoilStateLoadable",
"useRecoilValueLoadable",
"isRecoilValue",
"useRecoilCallback"
]
};
// src/presets/solid.ts
var solidCore = {
"solid-js": [
"createSignal",
"createEffect",
"createMemo",
"createResource",
"onMount",
"onCleanup",
"onError",
"untrack",
"batch",
"on",
"createRoot",
"mergeProps",
"splitProps",
"useTransition",
"observable",
"mapArray",
"indexArray",
"createContext",
"useContext",
"children",
"lazy",
"createDeferred",
"createRenderEffect",
"createSelector",
"For",
"Show",
"Switch",
"Match",
"Index",
"ErrorBoundary",
"Suspense",
"SuspenseList"
]
};
var solidStore = {
"solid-js/store": [
"createStore",
"produce",
"reconcile",
"createMutable"
]
};
var solidWeb = {
"solid-js/web": [
"Dynamic",
"hydrate",
"render",
"renderToString",
"renderToStringAsync",
"renderToStream",
"isServer",
"Portal"
]
};
var solid_default = {
...solidCore,
...solidStore,
...solidWeb
};
// src/presets/solid-app-router.ts
var solid_app_router_default = {
"solid-app-router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/solid-router.ts
var solid_router_default = {
"@solidjs/router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/svelte.ts
var svelteAnimate = {
"svelte/animate": [
"flip"
]
};
var svelteEasing = {
"svelte/easing": [
"back",
"bounce",
"circ",
"cubic",
"elastic",
"expo",
"quad",
"quart",
"quint",
"sine"
].reduce((acc, e) => {
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
return acc;
}, ["linear"])
};
var svelteStore = {
"svelte/store": [
"writable",
"readable",
"derived",
"get"
]
};
var svelteMotion = {
"svelte/motion": [
"tweened",
"spring"
]
};
var svelteTransition = {
"svelte/transition": [
"fade",
"blur",
"fly",
"slide",
"scale",
"draw",
"crossfade"
]
};
var svelte = {
svelte: [
// lifecycle
"onMount",
"beforeUpdate",
"afterUpdate",
"onDestroy",
// tick
"tick",
// context
"setContext",
"getContext",
"hasContext",
"getAllContexts",
// event dispatcher
"createEventDispatcher"
]
};
// src/presets/uni-app.ts
var uni_app_default = {
"@dcloudio/uni-app": [
"onAddToFavorites",
"onBackPress",
"onError",
"onHide",
"onLaunch",
"onLoad",
"onNavigationBarButtonTap",
"onNavigationBarSearchInputChanged",
"onNavigationBarSearchInputClicked",
"onNavigationBarSearchInputConfirmed",
"onNavigationBarSearchInputFocusChanged",
"onPageNotFound",
"onPageScroll",
"onPullDownRefresh",
"onReachBottom",
"onReady",
"onResize",
"onShareAppMessage",
"onShareTimeline",
"onShow",
"onTabItemTap",
"onThemeChange",
"onUnhandledRejection",
"onUnload"
]
};
// src/presets/vee-validate.ts
var vee_validate_default = {
"vee-validate": [
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
"validate",
"defineRule",
"configure",
"useField",
"useForm",
"useFieldArray",
"useResetForm",
"useIsFieldDirty",
"useIsFieldTouched",
"useIsFieldValid",
"useIsSubmitting",
"useValidateField",
"useIsFormDirty",
"useIsFormTouched",
"useIsFormValid",
"useValidateForm",
"useSubmitCount",
"useFieldValue",
"useFormValues",
"useFormErrors",
"useFieldError",
"useSubmitForm",
"FormContextKey",
"FieldContextKey"
]
};
// src/presets/vitepress.ts
var vitepress_default = {
vitepress: [
// helper methods
"useData",
"useRoute",
"useRouter",
"withBase"
]
};
// src/presets/vue-router.ts
var vue_router_default = {
"vue-router": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vue-router-composables.ts
var vue_router_composables_default = {
"vue-router/composables": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vueuse-core.ts
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _cache2;
var vueuse_core_default = () => {
const excluded = ["toRefs", "utils", "toRef", "toValue"];
if (!_cache2) {
let indexesJson;
try {
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
const path = _localpkg.resolveModule.call(void 0, "@vueuse/core/indexes.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
}
if (indexesJson) {
_cache2 = {
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
};
}
}
return _cache2 || {};
};
// src/presets/vueuse-head.ts
var vueuse_head_default = {
"@vueuse/head": [
"useHead",
"useSeoMeta"
]
};
// src/presets/vueuse-math.ts
var _cache3;
var vueuse_math_default = () => {
if (!_cache3) {
let indexesJson;
try {
const corePath = _localpkg.resolveModule.call(void 0, "@vueuse/core") || _process2.default.cwd();
const path = _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json") || _localpkg.resolveModule.call(void 0, "@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(_fs.readFileSync.call(void 0, path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
}
if (indexesJson) {
_cache3 = {
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
};
}
}
return _cache3 || {};
};
// src/presets/vuex.ts
var vuex_default = {
vuex: [
// https://next.vuex.vuejs.org/api/#createstore
"createStore",
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
"createLogger",
// https://next.vuex.vuejs.org/api/#component-binding-helpers
"mapState",
"mapGetters",
"mapActions",
"mapMutations",
"createNamespacedHelpers",
// https://next.vuex.vuejs.org/api/#composable-functions
"useStore"
]
};
// src/presets/index.ts
var presets = {
..._unimport.builtinPresets,
"ahooks": ahooks_default,
"@vueuse/core": vueuse_core_default,
"@vueuse/math": vueuse_math_default,
"@vueuse/head": vueuse_head_default,
"mobx": mobx_default,
"mobx-react-lite": mobx_react_lite_default,
"preact": preact_default,
"quasar": quasar_default,
"react": react_default,
"react-router": react_router_default,
"react-router-dom": react_router_dom_default,
"react-i18next": react_i18next_default,
"svelte": svelte,
"svelte/animate": svelteAnimate,
"svelte/easing": svelteEasing,
"svelte/motion": svelteMotion,
"svelte/store": svelteStore,
"svelte/transition": svelteTransition,
"vee-validate": vee_validate_default,
"vitepress": vitepress_default,
"vue-router": vue_router_default,
"vue-router/composables": vue_router_composables_default,
"vuex": vuex_default,
"uni-app": uni_app_default,
"solid-js": solid_default,
"@solidjs/router": solid_router_default,
"solid-app-router": solid_app_router_default,
"jotai": jotai,
"jotai/utils": jotaiUtils,
"recoil": recoil_default
};
exports.presets = presets;
@@ -0,0 +1,504 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var _chunk6BSQ6ZKCcjs = require('./chunk-6BSQ6ZKC.cjs');
// node_modules/.pnpm/@antfu+utils@9.0.0/node_modules/@antfu/utils/dist/index.mjs
function toArray(array) {
array = array != null ? array : [];
return Array.isArray(array) ? array : [array];
}
var VOID = Symbol("p-void");
function slash(str) {
return str.replace(/\\/g, "/");
}
function throttle$1(delay, callback, options) {
var _ref = options || {}, _ref$noTrailing = _ref.noTrailing, noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing, _ref$noLeading = _ref.noLeading, noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading, _ref$debounceMode = _ref.debounceMode, debounceMode = _ref$debounceMode === void 0 ? void 0 : _ref$debounceMode;
var timeoutID;
var cancelled = false;
var lastExec = 0;
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
}
function cancel(options2) {
var _ref2 = options2 || {}, _ref2$upcomingOnly = _ref2.upcomingOnly, upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
}
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
function clear() {
timeoutID = void 0;
}
if (!noLeading && debounceMode && !timeoutID) {
exec();
}
clearExistingTimeout();
if (debounceMode === void 0 && elapsed > delay) {
if (noLeading) {
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
exec();
}
} else if (noTrailing !== true) {
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === void 0 ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel;
return wrapper;
}
function throttle(...args) {
return throttle$1(...args);
}
// src/core/unplugin.ts
var _localpkg = require('local-pkg');
var _picomatch = require('picomatch'); var _picomatch2 = _interopRequireDefault(_picomatch);
var _unplugin = require('unplugin');
// src/core/ctx.ts
var _fs = require('fs');
var _path = require('path');
var _process = require('process'); var _process2 = _interopRequireDefault(_process);
var _magicstring = require('magic-string'); var _magicstring2 = _interopRequireDefault(_magicstring);
var _unimport = require('unimport');
var _unpluginutils = require('unplugin-utils');
// src/core/biomelintrc.ts
function generateBiomeLintConfigs(imports) {
const names = imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort();
const config = { javascript: { globals: names } };
const jsonBody = JSON.stringify(config, null, 2);
return jsonBody;
}
// src/core/eslintrc.ts
function generateESLintConfigs(imports, eslintrc, globals = {}) {
const eslintConfigs = { globals };
imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort().forEach((name) => {
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
});
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
return jsonBody;
}
// src/core/resolvers.ts
function normalizeImport(info, name) {
if (typeof info === "string") {
return {
name: "default",
as: name,
from: info
};
}
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return {
name,
as: name,
...info
};
}
async function firstMatchedResolver(resolvers, fullname) {
let name = fullname;
for (const resolver of resolvers) {
if (typeof resolver === "object" && resolver.type === "directive") {
if (name.startsWith("v"))
name = name.slice(1);
else
continue;
}
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
if (resolved)
return normalizeImport(resolved, fullname);
}
}
function resolversAddon(resolvers) {
return {
name: "unplugin-auto-import:resolvers",
async matchImports(names, matched) {
if (!resolvers.length)
return;
const dynamic = [];
const sideEffects = [];
await Promise.all([...names].map(async (name) => {
const matchedImport = matched.find((i) => i.as === name);
if (matchedImport) {
if ("sideEffects" in matchedImport)
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
return;
}
const resolved = await firstMatchedResolver(resolvers, name);
if (resolved)
dynamic.push(resolved);
if (resolved == null ? void 0 : resolved.sideEffects)
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
}));
if (dynamic.length) {
this.dynamicImports.push(...dynamic);
this.invalidate();
}
if (dynamic.length || sideEffects.length)
return [...matched, ...dynamic, ...sideEffects];
}
};
}
// src/core/ctx.ts
function createContext(options = {}, root = _process2.default.cwd()) {
var _a, _b, _c;
root = slash(root);
const {
dts: preferDTS = _localpkg.isPackageExists.call(void 0, "typescript"),
dirsScanOptions,
dirs,
vueDirectives,
vueTemplate
} = options;
const eslintrc = options.eslintrc || {};
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
const biomelintrc = options.biomelintrc || {};
biomelintrc.enabled = biomelintrc.enabled !== void 0;
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
const dumpUnimportItems = options.dumpUnimportItems === true ? "./.unimport-items.json" : (_a = options.dumpUnimportItems) != null ? _a : false;
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
const injectAtEnd = options.injectAtEnd !== false;
const unimport = _unimport.createUnimport.call(void 0, {
imports: [],
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
dirsScanOptions: {
...dirsScanOptions,
cwd: root
},
dirs,
injectAtEnd,
parser: options.parser,
addons: {
addons: [
resolversAddon(resolvers),
{
name: "unplugin-auto-import:dts",
declaration(dts2) {
return `${`
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
${dts2}`.trim()}
`;
}
}
],
vueDirectives,
vueTemplate
}
});
const importsPromise = flattenImports(options.imports).then((imports) => {
var _a2, _b2;
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
const compare = (left, right) => {
return right instanceof RegExp ? right.test(left) : right === left;
};
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.disabled = true;
});
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.dtsDisabled = true;
});
return unimport.getInternalContext().replaceImports(imports);
});
const filter = _unpluginutils.createFilter.call(void 0,
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
);
const dts = preferDTS === false ? false : preferDTS === true ? _path.resolve.call(void 0, root, "auto-imports.d.ts") : _path.resolve.call(void 0, root, preferDTS);
const multilineCommentsRE = /\/\*.*?\*\//gs;
const singlelineCommentsRE = /\/\/.*$/gm;
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
function parseDTS(dts2) {
var _a2;
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
if (!code)
return;
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
}
async function generateDTS(file) {
await importsPromise;
const dir = _path.dirname.call(void 0, file);
const originalContent = _fs.existsSync.call(void 0, file) ? await _fs.promises.readFile(file, "utf-8") : "";
const originalDTS = parseDTS(originalContent);
let currentContent = await unimport.generateTypeDeclarations({
resolvePath: (i) => {
if (i.from.startsWith(".") || _path.isAbsolute.call(void 0, i.from)) {
const related = slash(_path.relative.call(void 0, dir, i.from).replace(/\.ts(x)?$/, ""));
return !related.startsWith(".") ? `./${related}` : related;
}
return i.from;
}
});
const currentDTS = parseDTS(currentContent);
if (options.vueTemplate) {
currentContent = currentContent.replace(
componentCustomPropertiesReg,
($1) => `interface GlobalComponents {}
${$1}`
);
}
if (originalDTS) {
Object.keys(currentDTS).forEach((key) => {
originalDTS[key] = currentDTS[key];
});
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
return currentContent.replace(dtsReg, () => `declare global {
${dtsList.join("\n")}
}`);
}
return currentContent;
}
async function parseESLint() {
if (!eslintrc.filepath)
return {};
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
return {};
const configStr = _fs.existsSync.call(void 0, eslintrc.filepath) ? await _fs.promises.readFile(eslintrc.filepath, "utf-8") : "";
const config = JSON.parse(configStr || '{ "globals": {} }');
return config.globals;
}
async function generateESLint() {
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
}
async function generateBiomeLint() {
return generateBiomeLintConfigs(await unimport.getImports());
}
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
async function writeFile(filePath, content = "") {
await _fs.promises.mkdir(_path.dirname.call(void 0, filePath), { recursive: true });
return await _fs.promises.writeFile(filePath, content, "utf-8");
}
let lastDTS;
let lastESLint;
let lastBiomeLint;
let lastUnimportItems;
async function writeConfigFiles() {
const promises = [];
if (dts) {
promises.push(
generateDTS(dts).then((content) => {
if (content !== lastDTS) {
lastDTS = content;
return writeFile(dts, content);
}
})
);
}
if (eslintrc.enabled && eslintrc.filepath) {
const filepath = eslintrc.filepath;
promises.push(
generateESLint().then(async (content) => {
if (filepath.endsWith(".cjs"))
content = `module.exports = ${content}`;
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
content = `export default ${content}`;
content = `${content}
`;
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
lastESLint = content;
return writeFile(eslintrc.filepath, content);
}
})
);
}
if (biomelintrc.enabled) {
promises.push(
generateBiomeLint().then((content) => {
if (content !== lastBiomeLint) {
lastBiomeLint = content;
return writeFile(biomelintrc.filepath, content);
}
})
);
}
if (dumpUnimportItems) {
promises.push(
unimport.getImports().then((items) => {
if (!dumpUnimportItems)
return;
const content = JSON.stringify(items, null, 2);
if (content !== lastUnimportItems) {
lastUnimportItems = content;
return writeFile(dumpUnimportItems, content);
}
})
);
}
return Promise.all(promises);
}
async function scanDirs() {
await unimport.modifyDynamicImports(async (imports) => {
const exports_ = await unimport.scanImportsFromDir();
exports_.forEach((i) => i.__source = "dir");
return modifyDefaultExportsAlias([
...imports.filter((i) => i.__source !== "dir"),
...exports_
], options);
});
writeConfigFilesThrottled();
}
async function transform(code, id) {
await importsPromise;
const s = new (0, _magicstring2.default)(code);
await unimport.injectImports(s, id);
if (!s.hasChanged())
return;
writeConfigFilesThrottled();
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true, hires: true })
};
}
return {
root,
dirs,
filter,
scanDirs,
writeConfigFiles,
writeConfigFilesThrottled,
transform,
generateDTS,
generateESLint,
unimport
};
}
async function flattenImports(map) {
const promises = await Promise.all(toArray(map).map(async (definition) => {
if (typeof definition === "string") {
if (!_chunk6BSQ6ZKCcjs.presets[definition])
throw new Error(`[auto-import] preset ${definition} not found`);
const preset = _chunk6BSQ6ZKCcjs.presets[definition];
definition = typeof preset === "function" ? preset() : preset;
}
if ("from" in definition && "imports" in definition) {
return await _unimport.resolvePreset.call(void 0, definition);
} else {
const resolved = [];
for (const mod of Object.keys(definition)) {
for (const id of definition[mod]) {
const meta = {
from: mod
};
if (Array.isArray(id)) {
meta.name = id[0];
meta.as = id[1];
} else {
meta.name = id;
meta.as = id;
}
resolved.push(meta);
}
}
return resolved;
}
}));
return promises.flat();
}
function modifyDefaultExportsAlias(imports, options) {
if (options.defaultExportByFilename) {
imports.forEach((i) => {
var _a, _b, _c;
if (i.name === "default")
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
});
}
return imports;
}
// src/core/unplugin.ts
var unplugin_default = _unplugin.createUnplugin.call(void 0, (options) => {
let ctx = createContext(options);
return {
name: "unplugin-auto-import",
enforce: "post",
transformInclude(id) {
return ctx.filter(id);
},
async transform(code, id) {
return ctx.transform(code, id);
},
async buildStart() {
await ctx.scanDirs();
},
async buildEnd() {
await ctx.writeConfigFiles();
},
vite: {
async config(config) {
var _a;
if (options.viteOptimizeDeps === false)
return;
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i) && _localpkg.isPackageExists.call(void 0, i)));
if (!imports.size)
return;
return {
optimizeDeps: {
include: [...imports]
}
};
},
async handleHotUpdate({ file }) {
var _a;
if ((_a = ctx.dirs) == null ? void 0 : _a.some((dir) => _picomatch2.default.isMatch(slash(file), slash(typeof dir === "string" ? dir : dir.glob))))
await ctx.scanDirs();
},
async configResolved(config) {
if (ctx.root !== config.root) {
ctx = createContext(options, config.root);
await ctx.scanDirs();
}
}
}
};
});
exports.unplugin_default = unplugin_default;
@@ -0,0 +1,608 @@
// src/presets/index.ts
import { builtinPresets } from "unimport";
// src/presets/ahooks.ts
import { readFileSync } from "node:fs";
import { resolveModule } from "local-pkg";
var _cache;
var ahooks_default = () => {
if (!_cache) {
let indexesJson;
try {
const path = resolveModule("ahooks/metadata.json");
indexesJson = JSON.parse(readFileSync(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load ahooks, have you installed it?");
}
if (indexesJson) {
_cache = {
ahooks: indexesJson.functions.flatMap((i) => [i.name, ...i.alias || []])
};
}
}
return _cache || {};
};
// src/presets/jotai.ts
var jotai = {
jotai: [
"atom",
"useAtom",
"useAtomValue",
"useSetAtom"
]
};
var jotaiUtils = {
"jotai/utils": [
"atomWithReset",
"useResetAtom",
"useReducerAtom",
"atomWithReducer",
"atomFamily",
"selectAtom",
"useAtomCallback",
"freezeAtom",
"freezeAtomCreator",
"splitAtom",
"atomWithDefault",
"waitForAll",
"atomWithStorage",
"atomWithHash",
"createJSONStorage",
"atomWithObservable",
"useHydrateAtoms",
"loadable"
]
};
// src/presets/mobx.ts
var mobx = [
// https://mobx.js.org/api.html
"makeObservable",
"makeAutoObservable",
"extendObservable",
"observable",
"action",
"runInAction",
"flow",
"flowResult",
"computed",
"autorun",
"reaction",
"when",
"onReactionError",
"intercept",
"observe",
"onBecomeObserved",
"onBecomeUnobserved",
"toJS"
];
var mobx_default = {
mobx: [
// https://mobx.js.org/api.html
...mobx
]
};
// src/presets/mobx-react-lite.ts
var mobx_react_lite_default = {
// https://mobx.js.org/api.html
"mobx-react-lite": [
"observer",
"Observer",
"useLocalObservable"
]
};
// src/presets/preact.ts
var preact_default = {
"preact/hooks": [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer"
]
};
// src/presets/quasar.ts
var quasar_default = {
quasar: [
// https://quasar.dev/vue-composables
"useQuasar",
"useDialogPluginComponent",
"useFormChild",
"useMeta"
]
};
// src/presets/react.ts
var CommonReactAPI = [
"useState",
"useCallback",
"useMemo",
"useEffect",
"useRef",
"useContext",
"useReducer",
"useImperativeHandle",
"useDebugValue",
"useDeferredValue",
"useLayoutEffect",
"useTransition",
"startTransition",
"useSyncExternalStore",
"useInsertionEffect",
"useId",
"lazy",
"memo",
"createRef",
"forwardRef"
];
var react_default = {
react: CommonReactAPI
};
// src/presets/react-i18next.ts
var react_i18next_default = {
"react-i18next": ["useTranslation"]
};
// src/presets/react-router.ts
var ReactRouterHooks = [
"useOutletContext",
"useHref",
"useInRouterContext",
"useLocation",
"useNavigationType",
"useNavigate",
"useOutlet",
"useParams",
"useResolvedPath",
"useRoutes"
];
var react_router_default = {
"react-router": [
...ReactRouterHooks
]
};
// src/presets/react-router-dom.ts
var react_router_dom_default = {
"react-router-dom": [
...ReactRouterHooks,
// react-router-dom only hooks
"useLinkClickHandler",
"useSearchParams",
// react-router-dom Component
// call once in general
// 'BrowserRouter',
// 'HashRouter',
// 'MemoryRouter',
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Routes"
]
};
// src/presets/recoil.ts
var recoil_default = {
// https://recoiljs.org/docs/api-reference/core/atom/
recoil: [
"atom",
"selector",
"useRecoilState",
"useRecoilValue",
"useSetRecoilState",
"useResetRecoilState",
"useRecoilStateLoadable",
"useRecoilValueLoadable",
"isRecoilValue",
"useRecoilCallback"
]
};
// src/presets/solid.ts
var solidCore = {
"solid-js": [
"createSignal",
"createEffect",
"createMemo",
"createResource",
"onMount",
"onCleanup",
"onError",
"untrack",
"batch",
"on",
"createRoot",
"mergeProps",
"splitProps",
"useTransition",
"observable",
"mapArray",
"indexArray",
"createContext",
"useContext",
"children",
"lazy",
"createDeferred",
"createRenderEffect",
"createSelector",
"For",
"Show",
"Switch",
"Match",
"Index",
"ErrorBoundary",
"Suspense",
"SuspenseList"
]
};
var solidStore = {
"solid-js/store": [
"createStore",
"produce",
"reconcile",
"createMutable"
]
};
var solidWeb = {
"solid-js/web": [
"Dynamic",
"hydrate",
"render",
"renderToString",
"renderToStringAsync",
"renderToStream",
"isServer",
"Portal"
]
};
var solid_default = {
...solidCore,
...solidStore,
...solidWeb
};
// src/presets/solid-app-router.ts
var solid_app_router_default = {
"solid-app-router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/solid-router.ts
var solid_router_default = {
"@solidjs/router": [
"Link",
"NavLink",
"Navigate",
"Outlet",
"Route",
"Router",
"Routes",
"_mergeSearchString",
"createIntegration",
"hashIntegration",
"normalizeIntegration",
"pathIntegration",
"staticIntegration",
"useHref",
"useIsRouting",
"useLocation",
"useMatch",
"useNavigate",
"useParams",
"useResolvedPath",
"useRouteData",
"useRoutes",
"useSearchParams"
]
};
// src/presets/svelte.ts
var svelteAnimate = {
"svelte/animate": [
"flip"
]
};
var svelteEasing = {
"svelte/easing": [
"back",
"bounce",
"circ",
"cubic",
"elastic",
"expo",
"quad",
"quart",
"quint",
"sine"
].reduce((acc, e) => {
acc.push(`${e}In`, `${e}Out`, `${e}InOut`);
return acc;
}, ["linear"])
};
var svelteStore = {
"svelte/store": [
"writable",
"readable",
"derived",
"get"
]
};
var svelteMotion = {
"svelte/motion": [
"tweened",
"spring"
]
};
var svelteTransition = {
"svelte/transition": [
"fade",
"blur",
"fly",
"slide",
"scale",
"draw",
"crossfade"
]
};
var svelte = {
svelte: [
// lifecycle
"onMount",
"beforeUpdate",
"afterUpdate",
"onDestroy",
// tick
"tick",
// context
"setContext",
"getContext",
"hasContext",
"getAllContexts",
// event dispatcher
"createEventDispatcher"
]
};
// src/presets/uni-app.ts
var uni_app_default = {
"@dcloudio/uni-app": [
"onAddToFavorites",
"onBackPress",
"onError",
"onHide",
"onLaunch",
"onLoad",
"onNavigationBarButtonTap",
"onNavigationBarSearchInputChanged",
"onNavigationBarSearchInputClicked",
"onNavigationBarSearchInputConfirmed",
"onNavigationBarSearchInputFocusChanged",
"onPageNotFound",
"onPageScroll",
"onPullDownRefresh",
"onReachBottom",
"onReady",
"onResize",
"onShareAppMessage",
"onShareTimeline",
"onShow",
"onTabItemTap",
"onThemeChange",
"onUnhandledRejection",
"onUnload"
]
};
// src/presets/vee-validate.ts
var vee_validate_default = {
"vee-validate": [
// https://vee-validate.logaretm.com/v4/guide/composition-api/api-review
// https://github.com/logaretm/vee-validate/blob/main/packages/vee-validate/src/index.ts
"validate",
"defineRule",
"configure",
"useField",
"useForm",
"useFieldArray",
"useResetForm",
"useIsFieldDirty",
"useIsFieldTouched",
"useIsFieldValid",
"useIsSubmitting",
"useValidateField",
"useIsFormDirty",
"useIsFormTouched",
"useIsFormValid",
"useValidateForm",
"useSubmitCount",
"useFieldValue",
"useFormValues",
"useFormErrors",
"useFieldError",
"useSubmitForm",
"FormContextKey",
"FieldContextKey"
]
};
// src/presets/vitepress.ts
var vitepress_default = {
vitepress: [
// helper methods
"useData",
"useRoute",
"useRouter",
"withBase"
]
};
// src/presets/vue-router.ts
var vue_router_default = {
"vue-router": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vue-router-composables.ts
var vue_router_composables_default = {
"vue-router/composables": [
"useRouter",
"useRoute",
"useLink",
"onBeforeRouteLeave",
"onBeforeRouteUpdate"
]
};
// src/presets/vueuse-core.ts
import { readFileSync as readFileSync2 } from "node:fs";
import process from "node:process";
import { resolveModule as resolveModule2 } from "local-pkg";
var _cache2;
var vueuse_core_default = () => {
const excluded = ["toRefs", "utils", "toRef", "toValue"];
if (!_cache2) {
let indexesJson;
try {
const corePath = resolveModule2("@vueuse/core") || process.cwd();
const path = resolveModule2("@vueuse/core/indexes.json") || resolveModule2("@vueuse/metadata/index.json") || resolveModule2("@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(readFileSync2(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/core, have you installed it?");
}
if (indexesJson) {
_cache2 = {
"@vueuse/core": indexesJson.functions.filter((i) => ["core", "shared"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4 && !excluded.includes(i))
};
}
}
return _cache2 || {};
};
// src/presets/vueuse-head.ts
var vueuse_head_default = {
"@vueuse/head": [
"useHead",
"useSeoMeta"
]
};
// src/presets/vueuse-math.ts
import { readFileSync as readFileSync3 } from "node:fs";
import process2 from "node:process";
import { resolveModule as resolveModule3 } from "local-pkg";
var _cache3;
var vueuse_math_default = () => {
if (!_cache3) {
let indexesJson;
try {
const corePath = resolveModule3("@vueuse/core") || process2.cwd();
const path = resolveModule3("@vueuse/metadata/index.json") || resolveModule3("@vueuse/metadata/index.json", { paths: [corePath] });
indexesJson = JSON.parse(readFileSync3(path, "utf-8"));
} catch (error) {
console.error(error);
throw new Error("[auto-import] failed to load @vueuse/math, have you installed it?");
}
if (indexesJson) {
_cache3 = {
"@vueuse/math": indexesJson.functions.filter((i) => ["math"].includes(i.package)).flatMap((i) => [i.name, ...i.alias || []]).filter((i) => i && i.length >= 4)
};
}
}
return _cache3 || {};
};
// src/presets/vuex.ts
var vuex_default = {
vuex: [
// https://next.vuex.vuejs.org/api/#createstore
"createStore",
// https://github.com/vuejs/vuex/blob/4.0/types/logger.d.ts#L20
"createLogger",
// https://next.vuex.vuejs.org/api/#component-binding-helpers
"mapState",
"mapGetters",
"mapActions",
"mapMutations",
"createNamespacedHelpers",
// https://next.vuex.vuejs.org/api/#composable-functions
"useStore"
]
};
// src/presets/index.ts
var presets = {
...builtinPresets,
"ahooks": ahooks_default,
"@vueuse/core": vueuse_core_default,
"@vueuse/math": vueuse_math_default,
"@vueuse/head": vueuse_head_default,
"mobx": mobx_default,
"mobx-react-lite": mobx_react_lite_default,
"preact": preact_default,
"quasar": quasar_default,
"react": react_default,
"react-router": react_router_default,
"react-router-dom": react_router_dom_default,
"react-i18next": react_i18next_default,
"svelte": svelte,
"svelte/animate": svelteAnimate,
"svelte/easing": svelteEasing,
"svelte/motion": svelteMotion,
"svelte/store": svelteStore,
"svelte/transition": svelteTransition,
"vee-validate": vee_validate_default,
"vitepress": vitepress_default,
"vue-router": vue_router_default,
"vue-router/composables": vue_router_composables_default,
"vuex": vuex_default,
"uni-app": uni_app_default,
"solid-js": solid_default,
"@solidjs/router": solid_router_default,
"solid-app-router": solid_app_router_default,
"jotai": jotai,
"jotai/utils": jotaiUtils,
"recoil": recoil_default
};
export {
presets
};
@@ -0,0 +1,504 @@
import {
presets
} from "./chunk-DTT25XJ5.js";
// node_modules/.pnpm/@antfu+utils@9.0.0/node_modules/@antfu/utils/dist/index.mjs
function toArray(array) {
array = array != null ? array : [];
return Array.isArray(array) ? array : [array];
}
var VOID = Symbol("p-void");
function slash(str) {
return str.replace(/\\/g, "/");
}
function throttle$1(delay, callback, options) {
var _ref = options || {}, _ref$noTrailing = _ref.noTrailing, noTrailing = _ref$noTrailing === void 0 ? false : _ref$noTrailing, _ref$noLeading = _ref.noLeading, noLeading = _ref$noLeading === void 0 ? false : _ref$noLeading, _ref$debounceMode = _ref.debounceMode, debounceMode = _ref$debounceMode === void 0 ? void 0 : _ref$debounceMode;
var timeoutID;
var cancelled = false;
var lastExec = 0;
function clearExistingTimeout() {
if (timeoutID) {
clearTimeout(timeoutID);
}
}
function cancel(options2) {
var _ref2 = options2 || {}, _ref2$upcomingOnly = _ref2.upcomingOnly, upcomingOnly = _ref2$upcomingOnly === void 0 ? false : _ref2$upcomingOnly;
clearExistingTimeout();
cancelled = !upcomingOnly;
}
function wrapper() {
for (var _len = arguments.length, arguments_ = new Array(_len), _key = 0; _key < _len; _key++) {
arguments_[_key] = arguments[_key];
}
var self = this;
var elapsed = Date.now() - lastExec;
if (cancelled) {
return;
}
function exec() {
lastExec = Date.now();
callback.apply(self, arguments_);
}
function clear() {
timeoutID = void 0;
}
if (!noLeading && debounceMode && !timeoutID) {
exec();
}
clearExistingTimeout();
if (debounceMode === void 0 && elapsed > delay) {
if (noLeading) {
lastExec = Date.now();
if (!noTrailing) {
timeoutID = setTimeout(debounceMode ? clear : exec, delay);
}
} else {
exec();
}
} else if (noTrailing !== true) {
timeoutID = setTimeout(debounceMode ? clear : exec, debounceMode === void 0 ? delay - elapsed : delay);
}
}
wrapper.cancel = cancel;
return wrapper;
}
function throttle(...args) {
return throttle$1(...args);
}
// src/core/unplugin.ts
import { isPackageExists as isPackageExists2 } from "local-pkg";
import pm from "picomatch";
import { createUnplugin } from "unplugin";
// src/core/ctx.ts
import { existsSync, promises as fs } from "node:fs";
import { dirname, isAbsolute, relative, resolve } from "node:path";
import process from "node:process";
import { isPackageExists } from "local-pkg";
import MagicString from "magic-string";
import { createUnimport, resolvePreset } from "unimport";
import { createFilter } from "unplugin-utils";
// src/core/biomelintrc.ts
function generateBiomeLintConfigs(imports) {
const names = imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort();
const config = { javascript: { globals: names } };
const jsonBody = JSON.stringify(config, null, 2);
return jsonBody;
}
// src/core/eslintrc.ts
function generateESLintConfigs(imports, eslintrc, globals = {}) {
const eslintConfigs = { globals };
imports.map((i) => {
var _a;
return (_a = i.as) != null ? _a : i.name;
}).filter(Boolean).sort().forEach((name) => {
eslintConfigs.globals[name] = eslintrc.globalsPropValue;
});
const jsonBody = JSON.stringify(eslintConfigs, null, 2);
return jsonBody;
}
// src/core/resolvers.ts
function normalizeImport(info, name) {
if (typeof info === "string") {
return {
name: "default",
as: name,
from: info
};
}
if ("path" in info) {
return {
from: info.path,
as: info.name,
name: info.importName,
sideEffects: info.sideEffects
};
}
return {
name,
as: name,
...info
};
}
async function firstMatchedResolver(resolvers, fullname) {
let name = fullname;
for (const resolver of resolvers) {
if (typeof resolver === "object" && resolver.type === "directive") {
if (name.startsWith("v"))
name = name.slice(1);
else
continue;
}
const resolved = await (typeof resolver === "function" ? resolver(name) : resolver.resolve(name));
if (resolved)
return normalizeImport(resolved, fullname);
}
}
function resolversAddon(resolvers) {
return {
name: "unplugin-auto-import:resolvers",
async matchImports(names, matched) {
if (!resolvers.length)
return;
const dynamic = [];
const sideEffects = [];
await Promise.all([...names].map(async (name) => {
const matchedImport = matched.find((i) => i.as === name);
if (matchedImport) {
if ("sideEffects" in matchedImport)
sideEffects.push(...toArray(matchedImport.sideEffects).map((i) => normalizeImport(i, "")));
return;
}
const resolved = await firstMatchedResolver(resolvers, name);
if (resolved)
dynamic.push(resolved);
if (resolved == null ? void 0 : resolved.sideEffects)
sideEffects.push(...toArray(resolved == null ? void 0 : resolved.sideEffects).map((i) => normalizeImport(i, "")));
}));
if (dynamic.length) {
this.dynamicImports.push(...dynamic);
this.invalidate();
}
if (dynamic.length || sideEffects.length)
return [...matched, ...dynamic, ...sideEffects];
}
};
}
// src/core/ctx.ts
function createContext(options = {}, root = process.cwd()) {
var _a, _b, _c;
root = slash(root);
const {
dts: preferDTS = isPackageExists("typescript"),
dirsScanOptions,
dirs,
vueDirectives,
vueTemplate
} = options;
const eslintrc = options.eslintrc || {};
eslintrc.enabled = eslintrc.enabled === void 0 ? false : eslintrc.enabled;
eslintrc.filepath = eslintrc.filepath || "./.eslintrc-auto-import.json";
eslintrc.globalsPropValue = eslintrc.globalsPropValue === void 0 ? true : eslintrc.globalsPropValue;
const biomelintrc = options.biomelintrc || {};
biomelintrc.enabled = biomelintrc.enabled !== void 0;
biomelintrc.filepath = biomelintrc.filepath || "./.biomelintrc-auto-import.json";
const dumpUnimportItems = options.dumpUnimportItems === true ? "./.unimport-items.json" : (_a = options.dumpUnimportItems) != null ? _a : false;
const resolvers = options.resolvers ? [options.resolvers].flat(2) : [];
const injectAtEnd = options.injectAtEnd !== false;
const unimport = createUnimport({
imports: [],
presets: (_c = (_b = options.packagePresets) == null ? void 0 : _b.map((p) => typeof p === "string" ? { package: p } : p)) != null ? _c : [],
dirsScanOptions: {
...dirsScanOptions,
cwd: root
},
dirs,
injectAtEnd,
parser: options.parser,
addons: {
addons: [
resolversAddon(resolvers),
{
name: "unplugin-auto-import:dts",
declaration(dts2) {
return `${`
/* eslint-disable */
/* prettier-ignore */
// @ts-nocheck
// noinspection JSUnusedGlobalSymbols
// Generated by unplugin-auto-import
// biome-ignore lint: disable
${dts2}`.trim()}
`;
}
}
],
vueDirectives,
vueTemplate
}
});
const importsPromise = flattenImports(options.imports).then((imports) => {
var _a2, _b2;
if (!imports.length && !resolvers.length && !(dirs == null ? void 0 : dirs.length))
console.warn("[auto-import] plugin installed but no imports has defined, see https://github.com/antfu/unplugin-auto-import#configurations for configurations");
const compare = (left, right) => {
return right instanceof RegExp ? right.test(left) : right === left;
};
(_a2 = options.ignore) == null ? void 0 : _a2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.disabled = true;
});
(_b2 = options.ignoreDts) == null ? void 0 : _b2.forEach((name) => {
const i = imports.find((i2) => compare(i2.as, name));
if (i)
i.dtsDisabled = true;
});
return unimport.getInternalContext().replaceImports(imports);
});
const filter = createFilter(
options.include || [/\.[jt]sx?$/, /\.astro$/, /\.vue$/, /\.vue\?vue/, /\.svelte$/],
options.exclude || [/[\\/]node_modules[\\/]/, /[\\/]\.git[\\/]/]
);
const dts = preferDTS === false ? false : preferDTS === true ? resolve(root, "auto-imports.d.ts") : resolve(root, preferDTS);
const multilineCommentsRE = /\/\*.*?\*\//gs;
const singlelineCommentsRE = /\/\/.*$/gm;
const dtsReg = /declare\s+global\s*\{(.*?)[\n\r]\}/s;
const componentCustomPropertiesReg = /interface\s+ComponentCustomProperties\s*\{(.*?)[\n\r]\}/gs;
function parseDTS(dts2) {
var _a2;
dts2 = dts2.replace(multilineCommentsRE, "").replace(singlelineCommentsRE, "");
const code = (_a2 = dts2.match(dtsReg)) == null ? void 0 : _a2[0];
if (!code)
return;
return Object.fromEntries(Array.from(code.matchAll(/['"]?(const\s*[^\s'"]+)['"]?\s*:\s*(.+?)[,;\r\n]/g)).map((i) => [i[1], i[2]]));
}
async function generateDTS(file) {
await importsPromise;
const dir = dirname(file);
const originalContent = existsSync(file) ? await fs.readFile(file, "utf-8") : "";
const originalDTS = parseDTS(originalContent);
let currentContent = await unimport.generateTypeDeclarations({
resolvePath: (i) => {
if (i.from.startsWith(".") || isAbsolute(i.from)) {
const related = slash(relative(dir, i.from).replace(/\.ts(x)?$/, ""));
return !related.startsWith(".") ? `./${related}` : related;
}
return i.from;
}
});
const currentDTS = parseDTS(currentContent);
if (options.vueTemplate) {
currentContent = currentContent.replace(
componentCustomPropertiesReg,
($1) => `interface GlobalComponents {}
${$1}`
);
}
if (originalDTS) {
Object.keys(currentDTS).forEach((key) => {
originalDTS[key] = currentDTS[key];
});
const dtsList = Object.keys(originalDTS).sort().map((k) => ` ${k}: ${originalDTS[k]}`);
return currentContent.replace(dtsReg, () => `declare global {
${dtsList.join("\n")}
}`);
}
return currentContent;
}
async function parseESLint() {
if (!eslintrc.filepath)
return {};
if (eslintrc.filepath.match(/\.[cm]?[jt]sx?$/))
return {};
const configStr = existsSync(eslintrc.filepath) ? await fs.readFile(eslintrc.filepath, "utf-8") : "";
const config = JSON.parse(configStr || '{ "globals": {} }');
return config.globals;
}
async function generateESLint() {
return generateESLintConfigs(await unimport.getImports(), eslintrc, await parseESLint());
}
async function generateBiomeLint() {
return generateBiomeLintConfigs(await unimport.getImports());
}
const writeConfigFilesThrottled = throttle(500, writeConfigFiles, { noLeading: false });
async function writeFile(filePath, content = "") {
await fs.mkdir(dirname(filePath), { recursive: true });
return await fs.writeFile(filePath, content, "utf-8");
}
let lastDTS;
let lastESLint;
let lastBiomeLint;
let lastUnimportItems;
async function writeConfigFiles() {
const promises = [];
if (dts) {
promises.push(
generateDTS(dts).then((content) => {
if (content !== lastDTS) {
lastDTS = content;
return writeFile(dts, content);
}
})
);
}
if (eslintrc.enabled && eslintrc.filepath) {
const filepath = eslintrc.filepath;
promises.push(
generateESLint().then(async (content) => {
if (filepath.endsWith(".cjs"))
content = `module.exports = ${content}`;
else if (filepath.endsWith(".mjs") || filepath.endsWith(".js"))
content = `export default ${content}`;
content = `${content}
`;
if (content.trim() !== (lastESLint == null ? void 0 : lastESLint.trim())) {
lastESLint = content;
return writeFile(eslintrc.filepath, content);
}
})
);
}
if (biomelintrc.enabled) {
promises.push(
generateBiomeLint().then((content) => {
if (content !== lastBiomeLint) {
lastBiomeLint = content;
return writeFile(biomelintrc.filepath, content);
}
})
);
}
if (dumpUnimportItems) {
promises.push(
unimport.getImports().then((items) => {
if (!dumpUnimportItems)
return;
const content = JSON.stringify(items, null, 2);
if (content !== lastUnimportItems) {
lastUnimportItems = content;
return writeFile(dumpUnimportItems, content);
}
})
);
}
return Promise.all(promises);
}
async function scanDirs() {
await unimport.modifyDynamicImports(async (imports) => {
const exports_ = await unimport.scanImportsFromDir();
exports_.forEach((i) => i.__source = "dir");
return modifyDefaultExportsAlias([
...imports.filter((i) => i.__source !== "dir"),
...exports_
], options);
});
writeConfigFilesThrottled();
}
async function transform(code, id) {
await importsPromise;
const s = new MagicString(code);
await unimport.injectImports(s, id);
if (!s.hasChanged())
return;
writeConfigFilesThrottled();
return {
code: s.toString(),
map: s.generateMap({ source: id, includeContent: true, hires: true })
};
}
return {
root,
dirs,
filter,
scanDirs,
writeConfigFiles,
writeConfigFilesThrottled,
transform,
generateDTS,
generateESLint,
unimport
};
}
async function flattenImports(map) {
const promises = await Promise.all(toArray(map).map(async (definition) => {
if (typeof definition === "string") {
if (!presets[definition])
throw new Error(`[auto-import] preset ${definition} not found`);
const preset = presets[definition];
definition = typeof preset === "function" ? preset() : preset;
}
if ("from" in definition && "imports" in definition) {
return await resolvePreset(definition);
} else {
const resolved = [];
for (const mod of Object.keys(definition)) {
for (const id of definition[mod]) {
const meta = {
from: mod
};
if (Array.isArray(id)) {
meta.name = id[0];
meta.as = id[1];
} else {
meta.name = id;
meta.as = id;
}
resolved.push(meta);
}
}
return resolved;
}
}));
return promises.flat();
}
function modifyDefaultExportsAlias(imports, options) {
if (options.defaultExportByFilename) {
imports.forEach((i) => {
var _a, _b, _c;
if (i.name === "default")
i.as = (_c = (_b = (_a = i.from.split("/").pop()) == null ? void 0 : _a.split(".")) == null ? void 0 : _b.shift()) != null ? _c : i.as;
});
}
return imports;
}
// src/core/unplugin.ts
var unplugin_default = createUnplugin((options) => {
let ctx = createContext(options);
return {
name: "unplugin-auto-import",
enforce: "post",
transformInclude(id) {
return ctx.filter(id);
},
async transform(code, id) {
return ctx.transform(code, id);
},
async buildStart() {
await ctx.scanDirs();
},
async buildEnd() {
await ctx.writeConfigFiles();
},
vite: {
async config(config) {
var _a;
if (options.viteOptimizeDeps === false)
return;
const exclude = ((_a = config.optimizeDeps) == null ? void 0 : _a.exclude) || [];
const imports = new Set((await ctx.unimport.getImports()).map((i) => i.from).filter((i) => i.match(/^[a-z@]/) && !exclude.includes(i) && isPackageExists2(i)));
if (!imports.size)
return;
return {
optimizeDeps: {
include: [...imports]
}
};
},
async handleHotUpdate({ file }) {
var _a;
if ((_a = ctx.dirs) == null ? void 0 : _a.some((dir) => pm.isMatch(slash(file), slash(typeof dir === "string" ? dir : dir.glob))))
await ctx.scanDirs();
},
async configResolved(config) {
if (ctx.root !== config.root) {
ctx = createContext(options, config.root);
await ctx.scanDirs();
}
}
}
};
});
export {
unplugin_default
};
@@ -0,0 +1,10 @@
"use strict";Object.defineProperty(exports, "__esModule", {value: true});
var _chunkA6NGEVNDcjs = require('./chunk-A6NGEVND.cjs');
require('./chunk-6BSQ6ZKC.cjs');
// src/esbuild.ts
var esbuild_default = _chunkA6NGEVNDcjs.unplugin_default.esbuild;
exports.default = esbuild_default;
@@ -0,0 +1,8 @@
import { Options } from './types.cjs';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };
@@ -0,0 +1,8 @@
import { Options } from './types.js';
import '@antfu/utils';
import 'unimport';
import 'unplugin-utils';
declare const _default: (options?: Options) => any;
export { _default as default };

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