前端 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.
+1
View File
@@ -0,0 +1 @@
export {};
+4
View File
@@ -0,0 +1,4 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const alias_1 = require("./hbx/alias");
(0, alias_1.initModuleAlias)();
@@ -0,0 +1,3 @@
declare function checkUpdate1(options: any): Promise<undefined>;
export declare const checkUpdate: typeof checkUpdate1;
export {};
+61
View File
@@ -0,0 +1,61 @@
/* eslint-disable */
// @ts-ignore
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.checkUpdate = void 0;
var __importDefault = this && this.__importDefault || function (mod) { return mod && mod.__esModule ? mod : { default: mod }; };
Object.defineProperty(exports, "__esModule", { value: !0 }), exports.createPostData = exports.getMac = exports.md5 = exports.checkLocalCache = exports.checkUpdate1 = void 0;
const fs_extra_1 = __importDefault(require("fs-extra")), os_1 = __importDefault(require("os")), path_1 = __importDefault(require("path")), debug_1 = __importDefault(require("debug")), crypto_1 = __importDefault(require("crypto")), https_1 = require("https"), compare_versions_1 = __importDefault(require("compare-versions")), shared_1 = require("@vue/shared"), json_1 = require("./json"), hbx_1 = require("./hbx"), debugCheckUpdate = (0, debug_1.default)("uni:check-update"), INTERVAL = 864e5;
async function checkUpdate1(options) { if (process.env.CI)
return void debugCheckUpdate("isInCI"); if ((0, hbx_1.isInHBuilderX)())
return void debugCheckUpdate("isInHBuilderX"); const { inputDir: inputDir, compilerVersion: compilerVersion } = options, updateCache = readCheckUpdateCache(inputDir); debugCheckUpdate("read.cache", updateCache); const res = checkLocalCache(updateCache, compilerVersion); res ? (0, shared_1.isString)(res) && (console.log(), console.log(res)) : await checkVersion(options, normalizeUpdateCache(updateCache, (0, json_1.parseManifestJsonOnce)(inputDir))), writeCheckUpdateCache(inputDir, statUpdateCache(normalizeUpdateCache(updateCache))); }
function normalizeUpdateCache(updateCache, manifestJson) { const platform = process.env.UNI_PLATFORM; if (updateCache[platform] || (updateCache[platform] = { appid: "", dev: 0, build: 0 }), manifestJson) {
const platformOptions = manifestJson["app" === platform ? "app-plus" : platform];
updateCache[platform].appid = platformOptions && (platformOptions.appid || platformOptions.package) || "";
} return updateCache; }
function statUpdateCache(updateCache) { debugCheckUpdate("stat.before", updateCache); const platform = process.env.UNI_PLATFORM, type = "production" === process.env.NODE_ENV ? "build" : "dev", platformOptions = updateCache[platform]; return platformOptions[type] = (platformOptions[type] || 0) + 1, debugCheckUpdate("stat.after", updateCache), updateCache; }
function getFilepath(inputDir, filename) { return path_1.default.resolve(os_1.default.tmpdir(), "uni-app-cli", md5(inputDir), filename); }
function getCheckUpdateFilepath(inputDir) { return getFilepath(inputDir, "check-update.json"); }
function generateVid() { let result = ""; for (let i = 0; i < 4; i++)
result += (65536 * (1 + Math.random()) | 0).toString(16).substring(1); return "UNI_" + result.toUpperCase(); }
function createCheckUpdateCache(vid = generateVid()) { return { vid: generateVid(), lastCheck: 0 }; }
function readCheckUpdateCache(inputDir) { const updateFilepath = getCheckUpdateFilepath(inputDir); if (debugCheckUpdate("read:", updateFilepath), fs_extra_1.default.existsSync(updateFilepath))
try {
return require(updateFilepath);
}
catch (e) {
debugCheckUpdate("read.error", e);
} return createCheckUpdateCache(); }
function checkLocalCache(updateCache, compilerVersion, interval = INTERVAL) { return updateCache.lastCheck ? Date.now() - updateCache.lastCheck > interval ? (debugCheckUpdate("cache: lastCheck > interval"), !1) : !(updateCache.newVersion && (0, compare_versions_1.default)(updateCache.newVersion, compilerVersion) > 0) || (debugCheckUpdate("cache: find new version"), updateCache.note) : (debugCheckUpdate("cache: lastCheck not found"), !1); }
function writeCheckUpdateCache(inputDir, updateCache) { const filepath = getCheckUpdateFilepath(inputDir); debugCheckUpdate("write:", filepath, updateCache); try {
fs_extra_1.default.outputFileSync(filepath, JSON.stringify(updateCache));
}
catch (e) {
debugCheckUpdate("write.error", e);
} }
function md5(str) { return crypto_1.default.createHash("md5").update(str).digest("hex"); }
function getMac() { let mac = ""; const network = os_1.default.networkInterfaces(); for (const key in network) {
const array = network[key];
for (let i = 0; i < array.length; i++) {
const item = array[i];
if (item.family && (!item.mac || "00:00:00:00:00:00" !== item.mac)) {
if ((0, shared_1.isString)(item.family) && ("IPv4" === item.family || "IPv6" === item.family)) {
mac = item.mac;
break;
}
if ("number" == typeof item.family && (4 === item.family || 6 === item.family)) {
mac = item.mac;
break;
}
}
}
} return mac; }
function createPostData({ versionType: versionType, compilerVersion: compilerVersion }, manifestJson, updateCache) { const data = { vv: 3, device: md5(getMac()), vtype: versionType, vcode: compilerVersion }; return manifestJson.appid ? data.appid = manifestJson.appid : data.vid = updateCache.vid, Object.keys(updateCache).forEach((name => { const value = updateCache[name]; (0, shared_1.isPlainObject)(value) && ((0, shared_1.hasOwn)(value, "dev") || (0, shared_1.hasOwn)(value, "build")) && (data[name] = value); })), JSON.stringify(data); }
function handleCheckVersion({ code: code, isUpdate: isUpdate, newVersion: newVersion, note: note }, updateCache) { 0 === code && (Object.keys(updateCache).forEach((key => { "vid" !== key && delete updateCache[key]; })), updateCache.lastCheck = Date.now(), isUpdate ? (updateCache.note = note, updateCache.newVersion = newVersion) : (delete updateCache.note, delete updateCache.newVersion)); }
exports.checkUpdate1 = checkUpdate1, exports.checkLocalCache = checkLocalCache, exports.md5 = md5, exports.getMac = getMac, exports.createPostData = createPostData;
const HOSTNAME = "uniapp.dcloud.net.cn", PATH = "/update/cli";
function checkVersion(options, updateCache) { return new Promise((resolve => { const postData = JSON.stringify({ id: createPostData(options, (0, json_1.parseManifestJsonOnce)(options.inputDir), updateCache) }); let responseData = ""; const req = (0, https_1.request)({ hostname: HOSTNAME, path: PATH, port: 443, method: "POST", headers: { "Content-Type": "application/json", "Content-Length": postData.length } }, (res => { res.setEncoding("utf8"), res.on("data", (chunk => { responseData += chunk; })), res.on("end", (() => { debugCheckUpdate("response: ", responseData); try {
handleCheckVersion(JSON.parse(responseData), updateCache);
}
catch (e) { } resolve(!0); })), res.on("error", (e => { debugCheckUpdate("response.error:", e), resolve(!1); })); })).on("error", (e => { debugCheckUpdate("request.error:", e), resolve(!1); })); debugCheckUpdate("request: ", postData), req.write(postData), req.end(); })); }
exports.checkUpdate = checkUpdate1;
+43
View File
@@ -0,0 +1,43 @@
export declare const PUBLIC_DIR = "static";
export declare const EXTNAME_JS: string[];
export declare const EXTNAME_TS: string[];
export declare const EXTNAME_VUE: string[];
export declare const X_EXTNAME_VUE: string[];
export declare const EXTNAME_VUE_TEMPLATE: string[];
export declare const EXTNAME_VUE_RE: RegExp;
export declare const EXTNAME_JS_RE: RegExp;
export declare const EXTNAME_TS_RE: RegExp;
export declare const DEFAULT_APPID = "__UNI__uniappx";
export declare const SPECIAL_CHARS: {
WARN_BLOCK: string;
ERROR_BLOCK: string;
};
export declare const extensions: string[];
export declare const uni_app_x_extensions: string[];
export declare const PAGES_JSON_JS = "pages-json-js";
export declare const PAGES_JSON_UTS = "pages-json-uts";
export declare const MANIFEST_JSON_JS = "manifest-json-js";
export declare const MANIFEST_JSON_UTS = "manifest-json-uts";
export declare const JSON_JS_MAP: {
readonly 'pages.json': "pages-json-js";
readonly 'manifest.json': "manifest-json-js";
};
export declare const ASSETS_INLINE_LIMIT: number;
export declare const APP_SERVICE_FILENAME = "app-service.js";
export declare const APP_CONFIG = "app-config.js";
export declare const APP_CONFIG_SERVICE = "app-config-service.js";
export declare const BINDING_COMPONENTS = "__BINDING_COMPONENTS__";
export declare const PAGE_EXTNAME_APP: string[];
export declare const PAGE_EXTNAME: string[];
export declare const X_PAGE_EXTNAME: string[];
export declare const X_PAGE_EXTNAME_APP: string[];
export declare const H5_API_STYLE_PATH = "@dcloudio/uni-h5/style/api/";
export declare const H5_FRAMEWORK_STYLE_PATH = "@dcloudio/uni-h5/style/framework/";
export declare const H5_COMPONENTS_STYLE_PATH = "@dcloudio/uni-h5/style/";
export declare const BASE_COMPONENTS_STYLE_PATH = "@dcloudio/uni-components/style/";
export declare const X_BASE_COMPONENTS_STYLE_PATH = "@dcloudio/uni-components/style-x/";
export declare const X_VAPOR_BASE_COMPONENTS_STYLE_PATH = "@dcloudio/uni-components/style-x-vapor/";
export declare const COMMON_EXCLUDE: RegExp[];
export declare const KNOWN_ASSET_TYPES: string[];
export declare const DEFAULT_ASSETS_RE: RegExp;
export declare const TEXT_STYLE: string[];
+92
View File
@@ -0,0 +1,92 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TEXT_STYLE = exports.DEFAULT_ASSETS_RE = exports.KNOWN_ASSET_TYPES = exports.COMMON_EXCLUDE = exports.X_VAPOR_BASE_COMPONENTS_STYLE_PATH = exports.X_BASE_COMPONENTS_STYLE_PATH = exports.BASE_COMPONENTS_STYLE_PATH = exports.H5_COMPONENTS_STYLE_PATH = exports.H5_FRAMEWORK_STYLE_PATH = exports.H5_API_STYLE_PATH = exports.X_PAGE_EXTNAME_APP = exports.X_PAGE_EXTNAME = exports.PAGE_EXTNAME = exports.PAGE_EXTNAME_APP = exports.BINDING_COMPONENTS = exports.APP_CONFIG_SERVICE = exports.APP_CONFIG = exports.APP_SERVICE_FILENAME = exports.ASSETS_INLINE_LIMIT = exports.JSON_JS_MAP = exports.MANIFEST_JSON_UTS = exports.MANIFEST_JSON_JS = exports.PAGES_JSON_UTS = exports.PAGES_JSON_JS = exports.uni_app_x_extensions = exports.extensions = exports.SPECIAL_CHARS = exports.DEFAULT_APPID = exports.EXTNAME_TS_RE = exports.EXTNAME_JS_RE = exports.EXTNAME_VUE_RE = exports.EXTNAME_VUE_TEMPLATE = exports.X_EXTNAME_VUE = exports.EXTNAME_VUE = exports.EXTNAME_TS = exports.EXTNAME_JS = exports.PUBLIC_DIR = void 0;
exports.PUBLIC_DIR = 'static';
exports.EXTNAME_JS = ['.js', '.ts', '.jsx', '.tsx', '.uts'];
exports.EXTNAME_TS = ['.ts', '.tsx'];
exports.EXTNAME_VUE = ['.vue', '.nvue', '.uvue'];
exports.X_EXTNAME_VUE = ['.uvue', '.vue'];
exports.EXTNAME_VUE_TEMPLATE = ['.vue', '.nvue', '.uvue', '.jsx', '.tsx'];
exports.EXTNAME_VUE_RE = /\.(vue|nvue|uvue)$/;
exports.EXTNAME_JS_RE = /\.(js|jsx|ts|uts|tsx|mjs)$/;
exports.EXTNAME_TS_RE = /\.tsx?$/;
exports.DEFAULT_APPID = '__UNI__uniappx';
exports.SPECIAL_CHARS = {
WARN_BLOCK: '\uFEFF', // 警告块前后标识
ERROR_BLOCK: '\u2060', // 错误块前后标识
};
const COMMON_EXTENSIONS = [
'.uts',
'.mjs',
'.js',
'.ts',
'.jsx',
'.tsx',
'.json',
];
exports.extensions = COMMON_EXTENSIONS.concat(exports.EXTNAME_VUE);
exports.uni_app_x_extensions = COMMON_EXTENSIONS.concat(['.uvue', '.vue']);
exports.PAGES_JSON_JS = 'pages-json-js';
exports.PAGES_JSON_UTS = 'pages-json-uts';
exports.MANIFEST_JSON_JS = 'manifest-json-js';
exports.MANIFEST_JSON_UTS = 'manifest-json-uts';
exports.JSON_JS_MAP = {
'pages.json': exports.PAGES_JSON_JS,
'manifest.json': exports.MANIFEST_JSON_JS,
};
exports.ASSETS_INLINE_LIMIT = 40 * 1024;
exports.APP_SERVICE_FILENAME = 'app-service.js';
exports.APP_CONFIG = 'app-config.js';
exports.APP_CONFIG_SERVICE = 'app-config-service.js';
exports.BINDING_COMPONENTS = '__BINDING_COMPONENTS__';
// APP 平台解析页面后缀的优先级
exports.PAGE_EXTNAME_APP = ['.nvue', '.vue', '.tsx', '.jsx', '.js'];
// 其他平台解析页面后缀的优先级
exports.PAGE_EXTNAME = ['.vue', '.nvue', '.tsx', '.jsx', '.js'];
exports.X_PAGE_EXTNAME = ['.uvue', '.vue', '.tsx', '.jsx', '.js'];
exports.X_PAGE_EXTNAME_APP = ['.uvue', '.tsx', '.jsx', '.js'];
exports.H5_API_STYLE_PATH = '@dcloudio/uni-h5/style/api/';
exports.H5_FRAMEWORK_STYLE_PATH = '@dcloudio/uni-h5/style/framework/';
exports.H5_COMPONENTS_STYLE_PATH = '@dcloudio/uni-h5/style/';
exports.BASE_COMPONENTS_STYLE_PATH = '@dcloudio/uni-components/style/';
exports.X_BASE_COMPONENTS_STYLE_PATH = '@dcloudio/uni-components/style-x/';
exports.X_VAPOR_BASE_COMPONENTS_STYLE_PATH = '@dcloudio/uni-components/style-x-vapor/';
exports.COMMON_EXCLUDE = [
/\/pages\.json\.js$/,
/\/manifest\.json\.js$/,
/\/vite\//,
/\/@vue\//,
/\/vue-router\//,
/\/vuex\//,
/\/vue-i18n\//,
/\/@dcloudio\/uni-h5-vue/,
/\/@dcloudio\/uni-shared/,
];
exports.KNOWN_ASSET_TYPES = [
// images
'png',
'jpe?g',
'gif',
'svg',
'ico',
'webp',
'avif',
// media
'mp4',
'webm',
'ogg',
'mp3',
'wav',
'flac',
'aac',
// fonts
'woff2?',
'eot',
'ttf',
'otf',
// other
'pdf',
'txt',
];
exports.DEFAULT_ASSETS_RE = new RegExp(`\\.(` + exports.KNOWN_ASSET_TYPES.join('|') + `)(\\?.*)?$`);
exports.TEXT_STYLE = ['black', 'white'];
+24
View File
@@ -0,0 +1,24 @@
export declare function resolveWebVaporComponentStyle(name: string): string | undefined;
export declare const API_DEPS_CSS: (isX: boolean) => {
showModal: string[];
showToast: string[];
showActionSheet: string[];
previewImage: string[];
openLocation: string[];
chooseLocation: string[];
showLoading: string[];
};
export declare const COMPONENT_DEPS_CSS: (isX: boolean) => {
waterflow?: string[] | undefined;
canvas: string[];
image: string[];
'movable-area': string[];
'picker-view': string[];
'picker-view-column': string[];
'rich-text': string[];
textarea: string[];
'web-view': string[];
picker: string[];
'scroll-view': string[];
'list-view': string[];
};
+118
View File
@@ -0,0 +1,118 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.COMPONENT_DEPS_CSS = exports.API_DEPS_CSS = exports.resolveWebVaporComponentStyle = void 0;
const constants_1 = require("./constants");
const x_1 = require("./x");
const uni_shared_1 = require("@dcloudio/uni-shared");
const RESIZE_SENSOR_CSS = constants_1.BASE_COMPONENTS_STYLE_PATH + 'resize-sensor.css';
const REFRESHER_CSS = constants_1.BASE_COMPONENTS_STYLE_PATH + 'refresher.css';
const webVaporStyleComponents = new Set([
'input',
'textarea',
'scroll-view',
'video',
'web-view',
'ad',
]);
// Easycom、API 和框架内部组件共用同一份路径选择,避免漏载或同时加载旧版与 Vapor 样式。
// 同步组件优先:将来接入内网实现后,自动使用其生成样式。
function resolveWebVaporComponentStyle(name) {
if ((0, uni_shared_1.hasWebVaporComponentStyle)(name)) {
return constants_1.X_VAPOR_BASE_COMPONENTS_STYLE_PATH + name + '.css';
}
if (webVaporStyleComponents.has(name)) {
return constants_1.H5_COMPONENTS_STYLE_PATH + 'vapor/' + name + '.css';
}
}
exports.resolveWebVaporComponentStyle = resolveWebVaporComponentStyle;
function componentCss(name, isWebVapor) {
return ((isWebVapor && resolveWebVaporComponentStyle(name)) ||
constants_1.BASE_COMPONENTS_STYLE_PATH + name + '.css');
}
// 框架内部的 ScrollView 已在框架构建时编译,用户项目的 Easycom 不会再次扫描。
// Web Vapor 的外层组件或 API 需显式声明其样式,避免发行裁剪时漏载。
function webVaporScrollViewCss() {
return [componentCss('scroll-view', true)];
}
const API_DEPS_CSS = (isX) => {
// API 内部组件已随框架编译,需在项目使用该 API 时加载对应渲染模式的样式。
const isWebVapor = isX && (0, x_1.isUniAppXWebVapor)();
const scrollViewCss = isWebVapor ? webVaporScrollViewCss() : [];
const deps_css = {
showModal: [],
showToast: [`${constants_1.H5_API_STYLE_PATH}toast.css`],
showActionSheet: scrollViewCss,
previewImage: [
RESIZE_SENSOR_CSS,
componentCss('swiper', isWebVapor),
componentCss('swiper-item', isWebVapor),
`${constants_1.BASE_COMPONENTS_STYLE_PATH}movable-area.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}movable-view.css`,
],
openLocation: [`${constants_1.H5_API_STYLE_PATH}location-view.css`],
chooseLocation: [],
showLoading: [],
};
if (isX) {
deps_css.showModal = [
componentCss('textarea', isWebVapor),
...scrollViewCss,
];
deps_css.chooseLocation = [
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/view.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/text.css`,
isWebVapor
? componentCss('input', true)
: `${constants_1.BASE_COMPONENTS_STYLE_PATH}/input.css`,
`${constants_1.H5_COMPONENTS_STYLE_PATH}/map.css`,
...(isWebVapor
? scrollViewCss
: [`${constants_1.BASE_COMPONENTS_STYLE_PATH}/scroll-view.css`]),
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/image.css`,
];
deps_css.showLoading = [
`${isWebVapor
? constants_1.X_VAPOR_BASE_COMPONENTS_STYLE_PATH
: constants_1.X_BASE_COMPONENTS_STYLE_PATH}loading.css`,
];
}
else {
deps_css.showModal = [`${constants_1.H5_API_STYLE_PATH}modal.css`];
deps_css.showActionSheet = [`${constants_1.H5_API_STYLE_PATH}action-sheet.css`];
deps_css.chooseLocation = [
`${constants_1.H5_API_STYLE_PATH}/location-picker.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/input.css`,
`${constants_1.H5_COMPONENTS_STYLE_PATH}/map.css`,
`${constants_1.BASE_COMPONENTS_STYLE_PATH}/scroll-view.css`,
];
}
return deps_css;
};
exports.API_DEPS_CSS = API_DEPS_CSS;
const COMPONENT_DEPS_CSS = (isX) => {
const isWebVapor = isX && (0, x_1.isUniAppXWebVapor)();
const scrollViewCss = isWebVapor ? webVaporScrollViewCss() : [];
return {
canvas: [RESIZE_SENSOR_CSS],
image: [RESIZE_SENSOR_CSS],
'movable-area': [RESIZE_SENSOR_CSS],
'picker-view': [RESIZE_SENSOR_CSS],
'picker-view-column': [RESIZE_SENSOR_CSS, ...scrollViewCss],
'rich-text': [RESIZE_SENSOR_CSS],
textarea: [RESIZE_SENSOR_CSS],
'web-view': [RESIZE_SENSOR_CSS],
picker: [
RESIZE_SENSOR_CSS,
componentCss('picker-view', isWebVapor),
componentCss('picker-view-column', isWebVapor),
...scrollViewCss,
],
'scroll-view': isWebVapor ? [] : [REFRESHER_CSS],
'list-view': [
RESIZE_SENSOR_CSS,
...(isWebVapor ? scrollViewCss : [REFRESHER_CSS]),
],
...(isWebVapor ? { waterflow: [RESIZE_SENSOR_CSS, ...scrollViewCss] } : {}),
};
};
exports.COMPONENT_DEPS_CSS = COMPONENT_DEPS_CSS;
@@ -0,0 +1,4 @@
export declare const JS_STYLE_PLACEHOLDER_MARKER = "__js_style_placeholder__";
export declare function createJsStylePlaceholder(id: string): string;
export declare function createJsStylePlaceholderRegExp(id: string): RegExp;
export declare const ANY_JS_STYLE_PLACEHOLDER_RE: RegExp;
@@ -0,0 +1,21 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ANY_JS_STYLE_PLACEHOLDER_RE = exports.createJsStylePlaceholderRegExp = exports.createJsStylePlaceholder = exports.JS_STYLE_PLACEHOLDER_MARKER = void 0;
const hash_sum_1 = __importDefault(require("hash-sum"));
exports.JS_STYLE_PLACEHOLDER_MARKER = '__js_style_placeholder__';
function createJsStylePlaceholder(id) {
const hashId = (0, hash_sum_1.default)(id);
return JSON.stringify({
[exports.JS_STYLE_PLACEHOLDER_MARKER]: hashId,
});
}
exports.createJsStylePlaceholder = createJsStylePlaceholder;
function createJsStylePlaceholderRegExp(id) {
const hashId = (0, hash_sum_1.default)(id);
return new RegExp(`\\{\\s*(?:"${exports.JS_STYLE_PLACEHOLDER_MARKER}"|'${exports.JS_STYLE_PLACEHOLDER_MARKER}'|${exports.JS_STYLE_PLACEHOLDER_MARKER})\\s*:\\s*(?:"${hashId}"|'${hashId}')\\s*\\}`, 'g');
}
exports.createJsStylePlaceholderRegExp = createJsStylePlaceholderRegExp;
exports.ANY_JS_STYLE_PLACEHOLDER_RE = new RegExp(`\\{\\s*(?:"${exports.JS_STYLE_PLACEHOLDER_MARKER}"|'${exports.JS_STYLE_PLACEHOLDER_MARKER}'|${exports.JS_STYLE_PLACEHOLDER_MARKER})\\s*:\\s*(?:"[^"]+?"|'[^']+?')\\s*\\}`, 'g');
@@ -0,0 +1,5 @@
export * from './sharedData';
export * from './script';
export * from './vue';
export * from './fontFamily';
export * from './rootScrollView';
+21
View File
@@ -0,0 +1,21 @@
"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("./sharedData"), exports);
__exportStar(require("./script"), exports);
__exportStar(require("./vue"), exports);
__exportStar(require("./fontFamily"), exports);
__exportStar(require("./rootScrollView"), exports);
@@ -0,0 +1,47 @@
export interface VueCodePosition {
line: number;
column: number;
}
export interface VueCodeEditRange {
start: VueCodePosition;
end: VueCodePosition;
/**
* 调用方替换时建议只移除非换行字符,用于尽量保持错误定位和调试行号不变。
*/
preserveLineBreaks: true;
/**
* 开始范围包含首个子节点前的缩进,调用方需要保留这段缩进,避免改变子节点格式。
*/
preserveEndIndent?: true;
}
export type VueCodeEditRangesResult = Record<string, VueCodeEditRange[]>;
/**
* 批量定位由 `#ifdef APP` 包裹的根 scroll-view 需要移除的范围。
* 只返回需要修改的行列号,不修改文件,也不返回修改后的文件内容。
*/
export declare function resolveAppRootScrollViewEditRanges(vueFiles: string[], inputDir: string): VueCodeEditRangesResult;
/**
* 蒸汽模式下,页面根节点会自动补一个 scroll-view。
* 这里仅用正则做精确匹配:命中范围宁可保守,也不能误报。
*/
export declare function hasAppRootScrollViewWrappedByIfdef(code: string): boolean;
/**
* 仅在 dom2 页面整文件预处理时定位需要提示优化建议的根 scroll-view 节点。
*/
export declare function resolveDom2RootScrollViewWarnLocation(code: string, filename: string, isVueSubRequest: boolean): {
loc: import("@vue/compiler-core").SourceLocation | {
start: {
line: number;
column: number;
offset: number;
};
end: {
line: number;
column: number;
offset: number;
};
};
source: string;
} | undefined;
export declare function warnDom2RootScrollView(code: string, filename: string, isVueSubRequest: boolean): void;
export declare function resolveAppRootScrollViewEditRangesByCode(code: string, filename: string): VueCodeEditRange[];
@@ -0,0 +1,283 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveAppRootScrollViewEditRangesByCode = exports.warnDom2RootScrollView = exports.resolveDom2RootScrollViewWarnLocation = exports.hasAppRootScrollViewWrappedByIfdef = exports.resolveAppRootScrollViewEditRanges = void 0;
const fs_extra_1 = require("fs-extra");
const path_1 = require("path");
const compiler_sfc_1 = require("@vue/compiler-sfc");
const json_1 = require("../json");
const logs_1 = require("../logs");
const messages_1 = require("../messages");
const utils_1 = require("../utils");
const utils_2 = require("../vite/plugins/vitejs/utils");
const { preprocess: preprocessHtml } = require('../../lib/preprocess');
const TEMPLATE_BLOCK_RE = /<template\b[^>]*>([\s\S]*?)<\/template>/i;
const ROOT_SCROLL_VIEW_ATTR_RE = /^\s+style\s*=\s*(["'])\s*flex\s*:\s*1\s*;?\s*\1\s*$/;
const APP_ROOT_SCROLL_VIEW_RE = /^\s*<!--\s*#ifdef APP\s*-->\s*<scroll-view([^>]*)>[\s\S]*<\/scroll-view>\s*<!--\s*#endif\s*-->\s*$/;
const SPLIT_APP_ROOT_SCROLL_VIEW_RE = /^\s*<!--\s*#ifdef APP\s*-->\s*<scroll-view([^>]*)>\s*<!--\s*#endif\s*-->[\s\S]*<!--\s*#ifdef APP\s*-->\s*<\/scroll-view>\s*<!--\s*#endif\s*-->\s*$/;
/**
* 批量定位由 `#ifdef APP` 包裹的根 scroll-view 需要移除的范围。
* 只返回需要修改的行列号,不修改文件,也不返回修改后的文件内容。
*/
function resolveAppRootScrollViewEditRanges(vueFiles, inputDir) {
const result = {};
vueFiles.forEach((file) => {
const filename = resolveVueFilename(inputDir, file);
if (!(0, fs_extra_1.existsSync)(filename)) {
return;
}
const content = (0, fs_extra_1.readFileSync)(filename, 'utf8');
const ranges = resolveAppRootScrollViewEditRangesByCode(content, filename);
if (ranges.length) {
result[file] = ranges;
}
});
return result;
}
exports.resolveAppRootScrollViewEditRanges = resolveAppRootScrollViewEditRanges;
/**
* 蒸汽模式下,页面根节点会自动补一个 scroll-view。
* 这里仅用正则做精确匹配:命中范围宁可保守,也不能误报。
*/
function hasAppRootScrollViewWrappedByIfdef(code) {
const templateContent = getTemplateContent(code);
if (!templateContent) {
return false;
}
return (matchesAppRootScrollViewTemplate(templateContent, APP_ROOT_SCROLL_VIEW_RE) ||
matchesAppRootScrollViewTemplate(templateContent, SPLIT_APP_ROOT_SCROLL_VIEW_RE));
}
exports.hasAppRootScrollViewWrappedByIfdef = hasAppRootScrollViewWrappedByIfdef;
/**
* 仅在 dom2 页面整文件预处理时定位需要提示优化建议的根 scroll-view 节点。
*/
function resolveDom2RootScrollViewWarnLocation(code, filename, isVueSubRequest) {
if (process.env.UNI_PLATFORM !== 'app' ||
process.env.UNI_APP_X_DOM2 !== 'true' ||
isVueSubRequest ||
!(0, json_1.parseUniXPageOptions)(filename) ||
!code.includes('scroll-view') ||
!code.includes('#ifdef APP')) {
return;
}
if (!hasAppRootScrollViewWrappedByIfdef(code)) {
return;
}
return resolveAppRootScrollViewNodeLocByCode(code, filename);
}
exports.resolveDom2RootScrollViewWarnLocation = resolveDom2RootScrollViewWarnLocation;
function warnDom2RootScrollView(code, filename, isVueSubRequest) {
const location = resolveDom2RootScrollViewWarnLocation(code, filename, isVueSubRequest);
if (!location) {
return;
}
(0, logs_1.onCompileLog)('warn', {
message: messages_1.M['dom2.root.scroll.view'],
name: 'Warn',
loc: location.loc,
}, createWarnCodeFrameSource(location), (0, utils_1.normalizePath)((0, path_1.relative)(process.env.UNI_INPUT_DIR, filename)));
}
exports.warnDom2RootScrollView = warnDom2RootScrollView;
function resolveVueFilename(inputDir, file) {
if ((0, path_1.isAbsolute)(file)) {
const root = (0, path_1.parse)(file).root;
// HBuilderX/uni-app 里页面路径可能写成 `/pages/a/b.uvue`,
// 这种是项目内绝对路径,不是磁盘绝对路径,需要仍然基于 inputDir 解析。
if (root === '/' || root === '\\') {
return (0, path_1.resolve)(inputDir, removeLeadingRootSlash(file));
}
return file;
}
return (0, path_1.resolve)(inputDir, file);
}
function removeLeadingRootSlash(file) {
let index = 0;
while (file.charAt(index) === '/' || file.charAt(index) === '\\') {
index++;
}
return file.slice(index);
}
function getTemplateContent(code) {
return code.match(TEMPLATE_BLOCK_RE)?.[1];
}
function matchesAppRootScrollViewTemplate(template, regex) {
const match = template.match(regex);
return !!match && ROOT_SCROLL_VIEW_ATTR_RE.test(match[1]);
}
function resolveAppRootScrollViewNodeLocByCode(code, filename) {
const template = parseSfcTemplate(code, filename);
if (!template) {
return;
}
const children = template.ast.children;
if (children.length !== 3) {
return;
}
const [, scrollViewNode] = children;
if (!isRootScrollView(scrollViewNode)) {
return;
}
return {
loc: createStartTagLoc(code, scrollViewNode),
source: resolveStartTagSource(scrollViewNode),
};
}
function createStartTagLoc(code, node) {
const source = node.loc.source || '';
const endOffsetInSource = source.indexOf('>');
if (endOffsetInSource === -1) {
return {
start: node.loc.start,
end: node.loc.end,
};
}
return (0, utils_2.offsetToStartAndEnd)(code, node.loc.start.offset, node.loc.start.offset + endOffsetInSource + 1);
}
function resolveStartTagSource(node) {
const source = node.loc.source || '';
const endOffsetInSource = source.indexOf('>');
if (endOffsetInSource === -1) {
return source;
}
return source.slice(0, endOffsetInSource + 1);
}
function createWarnCodeFrameSource(location) {
return `${'\n'.repeat(Math.max(location.loc.start.line - 1, 0))}${location.source}`;
}
function resolveAppRootScrollViewEditRangesByCode(code, filename) {
const template = parseSfcTemplate(code, filename);
if (!template) {
return [];
}
const children = template.ast.children;
if (children.length !== 3) {
return [];
}
const [ifdefNode, scrollViewNode, endifNode] = children;
if (!isAppIfdefComment(ifdefNode) ||
!isRootScrollView(scrollViewNode) ||
!isEndifComment(endifNode)) {
return [];
}
// 使用项目既有的条件编译实现先跑一遍,再交给 Vue 编译器确认 APP 分支根节点。
if (!isPreprocessedRootScrollView(template.content, filename)) {
return [];
}
return createRootScrollViewEditRanges(ifdefNode, scrollViewNode, endifNode);
}
exports.resolveAppRootScrollViewEditRangesByCode = resolveAppRootScrollViewEditRangesByCode;
function parseSfcTemplate(code, filename) {
const { descriptor, errors } = (0, compiler_sfc_1.parse)(code, {
filename,
sourceMap: false,
});
if (errors.length || !descriptor.template?.ast) {
return;
}
return {
content: descriptor.template.content,
ast: descriptor.template.ast,
};
}
function isPreprocessedRootScrollView(content, filename) {
try {
const preprocessed = preprocessHtml(content, createAppPreContext(), {
type: 'html',
});
const template = parseSfcTemplate(`<template>${preprocessed}</template>`, filename);
const root = template?.ast.children[0];
return (!!root && template.ast.children.length === 1 && root.tag === 'scroll-view');
}
catch (e) {
return false;
}
}
function createAppPreContext() {
// 这里只声明本函数需要的 APP/UVue 上下文,避免改动全局条件编译上下文。
return {
APP: true,
APP_UVUE: true,
UNI_APP_X: true,
VUE3: true,
VUE3_VAPOR: true,
};
}
function isAppIfdefComment(node) {
return (node.type === 3 /* NodeTypes.COMMENT */ && node.content?.trim() === '#ifdef APP');
}
function isEndifComment(node) {
return node.type === 3 /* NodeTypes.COMMENT */ && node.content?.trim() === '#endif';
}
function isRootScrollView(node) {
return (node.type === 1 /* NodeTypes.ELEMENT */ &&
node.tag === 'scroll-view' &&
hasOnlyFlexStyle(node));
}
function hasOnlyFlexStyle(node) {
if (!node.props || node.props.length !== 1) {
return false;
}
const style = node.props[0];
return (style.type === 6 /* NodeTypes.ATTRIBUTE */ &&
style.name === 'style' &&
!!style.value &&
normalizeFlexStyle(style.value.content) === 'flex:1');
}
function normalizeFlexStyle(style) {
let normalized = '';
for (let i = 0; i < style.length; i++) {
const char = style.charAt(i);
if (char !== ' ' && char !== '\t' && char !== '\n' && char !== '\r') {
normalized += char;
}
}
if (normalized.endsWith(';')) {
return normalized.slice(0, -1);
}
return normalized;
}
function createRootScrollViewEditRanges(ifdefNode, scrollViewNode, endifNode) {
const children = scrollViewNode.children || [];
if (!children.length) {
return [createEditRange(ifdefNode, endifNode)];
}
const firstChild = children[0];
const lastChild = children[children.length - 1];
// 兼容如下写法:条件编译分别包裹 scroll-view 的开始标签和结束标签。
// <!-- #ifdef APP -->
// <scroll-view style="flex:1">
// <!-- #endif -->
// ...
// <!-- #ifdef APP -->
// </scroll-view>
// <!-- #endif -->
if (isEndifComment(firstChild) && isAppIfdefComment(lastChild)) {
return [
createEditRangeByLoc(ifdefNode.loc.start, firstChild.loc.end),
createEditRangeByLoc(lastChild.loc.start, endifNode.loc.end),
];
}
return [
createEditRangeByLoc(ifdefNode.loc.start, firstChild.loc.start, true),
createEditRangeByLoc(lastChild.loc.end, endifNode.loc.end),
];
}
function createEditRange(startNode, endNode) {
return createEditRangeByLoc(startNode.loc.start, endNode.loc.end);
}
function createEditRangeByLoc(start, end, preserveEndIndent = false) {
const range = {
start: toPosition(start),
end: toPosition(end),
preserveLineBreaks: true,
};
if (preserveEndIndent) {
range.preserveEndIndent = true;
}
return range;
}
function toPosition(loc) {
return {
line: loc.line,
column: loc.column,
};
}
@@ -0,0 +1,8 @@
import type { UasmTransformOptions } from '../uasm';
import type { UniVitePlugin } from '../vite';
export interface UniVaporScriptPluginOptions {
sharedDataLibName?: string;
sharedDataLibAsGlobal?: boolean;
uasm?: UasmTransformOptions;
}
export declare function uniVaporScriptPlugin(options?: UniVaporScriptPluginOptions): UniVitePlugin;
+32
View File
@@ -0,0 +1,32 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.uniVaporScriptPlugin = void 0;
const uts_1 = require("../uts");
const extApi_1 = require("../uts/extApi");
const utils_1 = require("../utils");
const scriptMacros_1 = require("../uts/scriptMacros");
const sharedData_1 = require("./sharedData");
function uniVaporScriptPlugin(options = {}) {
const { uasm, ...sharedData } = options;
const { D2SP } = (0, utils_1.requireUniHelpers)();
const nodeEnv = process.env.UNI_NODE_ENV || process.env.NODE_ENV;
/**
* 鸿蒙平台push、一键登录必须获取摇树结果,因此在非开发模式下或鸿蒙平台必须执行摇树逻辑
*/
const extApi = (0, utils_1.isNormalCompileTarget)() &&
(nodeEnv !== 'development' ||
process.env.UNI_UTS_PLATFORM === 'app-harmony')
? (0, extApi_1.initUts2jsExtApiOptions)()
: undefined;
return D2SP({
typescript: (0, uts_1.resolveUTSCompiler)().getTypeScript(),
createUniAppXScriptMacrosTransformer: scriptMacros_1.createUniAppXScriptMacrosTransformer,
extApi,
uasm,
sharedData: {
...(0, sharedData_1.initUts2jsSharedDataOptions)(),
...sharedData,
},
});
}
exports.uniVaporScriptPlugin = uniVaporScriptPlugin;
@@ -0,0 +1,9 @@
import type { Plugin } from 'vite';
export declare function uniSharedDataPlugin(): Plugin;
export declare function initSourceFileCallback(): ((sourceFile: import('typescript').SourceFile) => void) | undefined;
export declare function initUts2jsSharedDataOptions(): {
resolveFieldMeta(name: string): {
fieldId: number;
};
createSharedDataTransformer: any;
} | undefined;
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initUts2jsSharedDataOptions = exports.initSourceFileCallback = exports.uniSharedDataPlugin = void 0;
const uts_1 = require("../uts");
const pages_1 = require("../json/pages");
const utils_1 = require("../utils");
const asset_1 = require("../vite/plugins/vitejs/plugins/asset");
const x_1 = require("../x");
const manifest_1 = require("../json/uni-x/manifest");
const manifest_2 = require("../json/manifest");
function initSharedDataOptions() {
const compiler = require('@dcloudio/compiler-vapor-dom2');
const manifest = (0, manifest_2.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
return {
platform: process.env.UNI_UTS_PLATFORM,
compilerVaporDom2: compiler,
utsCompiler: (0, uts_1.resolveUTSCompiler)(),
isUniPageFile: pages_1.isUniPageFile,
getSharedDataResult: compiler.getSharedDataResult,
getAssetFilenameById: asset_1.getAssetFilenameById,
uvueScriptEngine: (0, x_1.isUniAppXAndroidNative)() ? 'native' : 'js',
compilerVersion: process.env.HX_Version || process.env.UNI_COMPILER_VERSION,
androidOptions: (0, x_1.isUniAppXAndroidJsEngine)()
? {
package: process.env.UNI_COMPILE_TARGET === 'ext-api'
? 'io.dcloud.uniapp.extapi'
: (0, manifest_1.parseUniXAppAndroidPackage)(manifest.appid),
}
: undefined,
};
}
function uniSharedDataPlugin() {
return (0, utils_1.requireUniHelpers)().USDP(initSharedDataOptions());
}
exports.uniSharedDataPlugin = uniSharedDataPlugin;
function initSourceFileCallback() {
if (process.env.UNI_APP_X_DOM2 === 'true' && (0, x_1.isUniAppXAndroidNative)()) {
const { TSDBSF } = (0, utils_1.requireUniHelpers)();
const options = initSharedDataOptions();
return (sourceFile) => {
TSDBSF(sourceFile, options);
};
}
}
exports.initSourceFileCallback = initSourceFileCallback;
function initUts2jsSharedDataOptions() {
if (process.env.UNI_APP_X_DOM2 === 'true') {
const uniHelpers = (0, utils_1.requireUniHelpers)();
if (typeof uniHelpers.CSDT !== 'function') {
throw new Error('DOM2 requires the SharedData transformer (CSDT)');
}
return {
resolveFieldMeta(name) {
return require('@dcloudio/compiler-vapor-dom2').resolveSharedDataFieldMeta(name);
},
createSharedDataTransformer: uniHelpers.CSDT,
};
}
}
exports.initUts2jsSharedDataOptions = initUts2jsSharedDataOptions;
+16
View File
@@ -0,0 +1,16 @@
import type { CompilerError, SFCDescriptor } from '@vue/compiler-sfc';
export declare function initVueTemplateCompilerExtraOptions(descriptor: SFCDescriptor): {
root: string;
platform: keyof UniApp.PagesJsonPagePlatformStyle;
componentType: string;
filename: string;
relativeFilename: string;
helper: any;
enableRootScrollViewTransform: boolean;
rootScrollView: import("src/json/uni-x").UniXPageOptions | undefined;
scriptCppBlocks: any;
onVueTemplateCompileLog(type: 'warn' | 'error', error: CompilerError): void;
r: any;
className: any;
inlineRender: boolean;
};
+37
View File
@@ -0,0 +1,37 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initVueTemplateCompilerExtraOptions = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../utils");
const json_1 = require("../json");
const vue_1 = require("../vue");
function initVueTemplateCompilerExtraOptions(descriptor) {
const filename = (0, utils_1.normalizePath)(descriptor.filename.split('?')[0]);
const relativeFilename = (0, utils_1.normalizePath)(path_1.default.relative(process.env.UNI_INPUT_DIR, filename));
const rootScrollView = (0, json_1.parseUniXPageOptions)(filename);
const componentType = rootScrollView || (0, json_1.isUniPageFile)(filename) ? 'page' : 'component';
const isDynamic = process.env.UNI_APP_X_DOM2_DYNAMIC === 'true';
const helper = (0, utils_1.requireUniHelpers)();
return {
root: (0, utils_1.normalizePath)(process.env.UNI_INPUT_DIR),
platform: process.env.UNI_UTS_PLATFORM,
componentType,
filename,
relativeFilename,
helper,
enableRootScrollViewTransform: true,
// 仅页面透传 rootScrollView,避免非页面组件误触发 ROOT 自动包裹逻辑。
rootScrollView: componentType === 'page' ? rootScrollView : undefined,
scriptCppBlocks: descriptor.scriptCppBlocks,
onVueTemplateCompileLog(type, error) {
return (0, vue_1.onVueTemplateCompileLog)(type, error, descriptor.source, relativeFilename);
},
r: helper.K,
className: helper.GCN(descriptor.filename, process.env.UNI_INPUT_DIR),
inlineRender: !isDynamic && process.env.UNI_UTS_PLATFORM === 'app-android',
};
}
exports.initVueTemplateCompilerExtraOptions = initVueTemplateCompilerExtraOptions;
+38
View File
@@ -0,0 +1,38 @@
interface EasycomOption {
platform: UniApp.PLATFORM;
isX?: boolean;
dirs?: string[];
rootDir: string;
extensions: string[];
autoscan?: boolean;
custom?: EasycomCustom;
}
export interface EasycomMatcher {
name: string;
pattern: RegExp;
replacement: string;
dom2IncompatibleFile?: string;
}
interface EasycomCustom {
[key: string]: string;
}
export declare function initEasycoms(inputDir: string, { dirs, platform, isX, }: {
dirs: string[];
platform: UniApp.PLATFORM;
isX?: boolean;
}): {
easyComOptions: EasycomOption;
filter: (id: unknown) => boolean;
refresh(): void;
easycoms: EasycomMatcher[];
};
export declare const initEasycomsOnce: typeof initEasycoms;
export declare function matchEasycom(tag: string): string | false | undefined;
export declare function addImportDeclaration(importDeclarations: string[], local: string, source: string, imported?: string): string;
export declare function genResolveEasycomCode(importDeclarations: string[], code: string, name: string): string;
export declare const UNI_EASYCOM_EXCLUDE: RegExp[];
export declare function getUTSEasyComAutoImports(): Record<string, [[string, string]]>;
export declare function addUTSEasyComAutoImports(source: string, imports: [string, string]): void;
export declare function genUTSComponentPublicInstanceIdent(tagName: string): string;
export declare function genUTSComponentPublicInstanceImported(root: string, fileName: string): string;
export {};
+375
View File
@@ -0,0 +1,375 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.genUTSComponentPublicInstanceImported = exports.genUTSComponentPublicInstanceIdent = exports.addUTSEasyComAutoImports = exports.getUTSEasyComAutoImports = exports.UNI_EASYCOM_EXCLUDE = exports.genResolveEasycomCode = exports.addImportDeclaration = exports.matchEasycom = exports.initEasycomsOnce = exports.initEasycoms = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const debug_1 = __importDefault(require("debug"));
const shared_1 = require("@vue/shared");
const pluginutils_1 = require("@rollup/pluginutils");
const uni_shared_1 = require("@dcloudio/uni-shared");
const x_1 = require("./x");
const utils_1 = require("./utils");
const pages_1 = require("./json/pages");
const messages_1 = require("./messages");
const uts_1 = require("./uts");
const utsUtils_1 = require("./utsUtils");
const debugEasycom = (0, debug_1.default)('uni:easycom');
const easycoms = [];
const easycomsCache = new Map();
const easycomsInvalidCache = new Set();
let hasEasycom = false;
function clearEasycom() {
easycoms.length = 0;
easycomsCache.clear();
easycomsInvalidCache.clear();
}
function initEasycoms(inputDir, { dirs, platform, isX, }) {
const componentsDir = path_1.default.resolve(inputDir, 'components');
const uniModulesDir = path_1.default.resolve(inputDir, 'uni_modules');
const initEasycomOptions = (pagesJson) => {
// 初始化时,从once中读取缓存,refresh时,实时读取
const { easycom } = pagesJson || (0, pages_1.parsePagesJson)(inputDir, platform, false);
const easycomOptions = {
platform,
isX,
dirs: easycom && easycom.autoscan === false
? [...dirs] // 禁止自动扫描
: [
...dirs,
componentsDir,
...initUniModulesEasycomDirs(uniModulesDir),
],
rootDir: inputDir,
autoscan: !!(easycom && easycom.autoscan),
custom: (easycom && easycom.custom) || {},
extensions: [...(isX ? ['.uvue'] : []), ...['.vue', '.jsx', '.tsx']],
};
debugEasycom(easycomOptions);
return easycomOptions;
};
const easyComOptions = initEasycomOptions((0, pages_1.parsePagesJsonOnce)(inputDir, platform));
const initUTSEasycom = () => {
(0, uts_1.initUTSComponents)(inputDir, platform).forEach((item) => {
const index = easycoms.findIndex((easycom) => item.name === easycom.name);
if (index > -1) {
easycoms.splice(index, 1, item);
}
else {
easycoms.push(item);
}
});
if (isX && globalThis.uts2jsSourceCodeMap) {
;
globalThis.uts2jsSourceCodeMap.initUts2jsEasycom(easycoms);
}
// UTS / customElements 组件是在 initEasycom 之后补充进去的,
// 这里补一次状态,避免项目里只有这类组件时被误判为没有 easycom。
hasEasycom = !!easycoms.length;
};
const initUTSEasycomCustomElements = () => {
(0, uts_1.initUTSCustomElements)(inputDir, platform).forEach((item) => {
const index = easycoms.findIndex((easycom) => item.name === easycom.name);
if (index > -1) {
easycoms.splice(index, 1, item);
}
else {
easycoms.push(item);
}
});
};
const supportCustomElements = isX && process.env.UNI_APP_X_DOM2 !== 'true';
// ext-api 模式下,不存在 easycom 特性
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
clearEasycom();
(0, uts_1.clearUTSComponents)();
(0, uts_1.clearUTSCustomElements)();
initEasycom(easyComOptions);
// dom2 模式下,不需要注册 customElements 组件
if (supportCustomElements) {
initUTSEasycomCustomElements();
}
initUTSEasycom();
}
const componentExtNames = isX ? 'uvue|vue' : 'vue';
const res = {
easyComOptions,
filter: (0, pluginutils_1.createFilter)([
'components/*/*.(' + componentExtNames + '|jsx|tsx)',
'uni_modules/*/components/*/*.(' + componentExtNames + '|jsx|tsx)',
'utssdk/*/**/*.(' + componentExtNames + ')',
'uni_modules/*/utssdk/*/*.(' + componentExtNames + ')',
...(supportCustomElements
? ['uni_modules/*/customElements/*/*.uts']
: []),
], [], {
resolve: inputDir,
}),
refresh() {
res.easyComOptions = initEasycomOptions();
if (process.env.UNI_COMPILE_TARGET !== 'ext-api') {
clearEasycom();
(0, uts_1.clearUTSComponents)();
(0, uts_1.clearUTSCustomElements)();
initEasycom(res.easyComOptions);
if (supportCustomElements) {
initUTSEasycomCustomElements();
}
initUTSEasycom();
}
},
easycoms,
};
return res;
}
exports.initEasycoms = initEasycoms;
exports.initEasycomsOnce = (0, uni_shared_1.once)(initEasycoms);
function initUniModulesEasycomDirs(uniModulesDir, componentsDir = 'components') {
if (!fs_1.default.existsSync(uniModulesDir)) {
return [];
}
return fs_1.default
.readdirSync(uniModulesDir)
.map((uniModuleDir) => {
const uniModuleComponentsDir = path_1.default.resolve(uniModulesDir, uniModuleDir, componentsDir);
if (fs_1.default.existsSync(uniModuleComponentsDir)) {
return uniModuleComponentsDir;
}
})
.filter(Boolean);
}
function initEasycom({ platform, isX, dirs, rootDir, custom, extensions, }) {
rootDir = (0, utils_1.normalizePath)(rootDir);
const easycomsObj = Object.create(null);
if (dirs && dirs.length && rootDir) {
const autoEasyComObj = initAutoScanEasycoms(platform, dirs, rootDir, extensions);
if (isX) {
Object.keys(autoEasyComObj).forEach((tagName) => {
let source = autoEasyComObj[tagName];
tagName = tagName.slice(1, -1);
if (path_1.default.isAbsolute(source) && source.startsWith(rootDir)) {
source = '@/' + (0, utils_1.normalizePath)(path_1.default.relative(rootDir, source));
}
// 加密插件easycom类型导入
if (source.includes('?uts-proxy')) {
const moduleId = path_1.default.basename(source.split('?uts-proxy')[0]);
source = `uts.sdk.modules.${(0, shared_1.camelize)(moduleId)}`;
}
const ident = genUTSComponentPublicInstanceIdent(tagName);
addUTSEasyComAutoImports(source, [ident, ident]);
});
}
(0, shared_1.extend)(easycomsObj, autoEasyComObj);
}
if (custom) {
Object.keys(custom).forEach((name) => {
const componentPath = custom[name];
easycomsObj[name] = componentPath.startsWith('@/')
? (0, utils_1.normalizePath)(path_1.default.join(rootDir, componentPath.slice(2)))
: componentPath;
});
}
Object.keys(easycomsObj).forEach((name) => {
easycoms.push({
name: name.startsWith('^') && name.endsWith('$') ? name.slice(1, -1) : name,
pattern: new RegExp(name),
replacement: easycomsObj[name],
});
});
debugEasycom(easycoms);
hasEasycom = !!easycoms.length;
return easycoms;
}
function matchEasycom(tag) {
if (!hasEasycom) {
return;
}
let source = easycomsCache.get(tag);
if (source) {
return source;
}
if (easycomsInvalidCache.has(tag)) {
return false;
}
const matcher = easycoms.find((matcher) => matcher.pattern.test(tag));
if (!matcher) {
easycomsInvalidCache.add(tag);
return false;
}
// dom2 不支持旧版 uni-app 兼容模式组件,这里在 easycom 真正命中时再报错,
// 避免扫描阶段就对未使用的插件组件产生误报。
if (process.env.UNI_APP_X_DOM2 === 'true' && matcher.dom2IncompatibleFile) {
throw new Error(messages_1.M['dom2.compatible.component']
.replace('{name}', `<${tag}>`)
.replace('{file}', matcher.dom2IncompatibleFile));
}
source = tag.replace(matcher.pattern, matcher.replacement);
easycomsCache.set(tag, source);
debugEasycom('matchEasycom', tag, source);
// 检查 H5 专用组件 ask163203
const H5_ONLY_COMPONENTS = ['custom-tab-bar'];
if (H5_ONLY_COMPONENTS.includes(tag) && process.env.UNI_PLATFORM !== 'h5') {
console.warn(`[uni-app] 组件 <${tag}> 是 H5 平台专用组件,在 ${process.env.UNI_PLATFORM} 平台使用可能导致错误。如果你要引入自定义 tabBar 可重命名为其他名称。`);
}
return source;
}
exports.matchEasycom = matchEasycom;
const isDir = (path) => {
const stat = fs_1.default.lstatSync(path);
if (stat.isDirectory()) {
return true;
}
else if (stat.isSymbolicLink()) {
return fs_1.default.lstatSync(fs_1.default.realpathSync(path)).isDirectory();
}
return false;
};
function initAutoScanEasycom(platform, dir, rootDir, extensions) {
if (!path_1.default.isAbsolute(dir)) {
dir = path_1.default.resolve(rootDir, dir);
}
const easycoms = Object.create(null);
if (!fs_1.default.existsSync(dir)) {
return easycoms;
}
const isDevX = process.env.UNI_HX_VERSION_DEV === 'true' &&
process.env.UNI_APP_X === 'true';
const isMp = platform.startsWith('mp-');
const is_uni_modules = path_1.default.basename(path_1.default.resolve(dir, '../..')) === 'uni_modules';
const has_uts_sdk_dir = fs_1.default.existsSync(path_1.default.resolve(dir, '../utssdk'));
const is_easycom_encrypt_uni_modules = // uni_modules模式不需要此逻辑
process.env.UNI_COMPILE_TARGET !== 'uni_modules' &&
is_uni_modules &&
// 前端加密插件,不能包含utssdk目录
fs_1.default.existsSync(path_1.default.resolve(dir, '../encrypt')) &&
!has_uts_sdk_dir;
const uni_modules_plugin_id = is_easycom_encrypt_uni_modules && path_1.default.basename(path_1.default.resolve(dir, '..'));
fs_1.default.readdirSync(dir).forEach((name) => {
const folder = path_1.default.resolve(dir, name);
if (!isDir(folder)) {
return;
}
if (isDevX) {
if (has_uts_sdk_dir &&
process.env.UNI_UTS_PLATFORM &&
process.env.UNI_UTS_PLATFORM !== 'web' &&
(0, uni_shared_1.isBuiltInComponent)(name)) {
// dev下,如果是内置组件,且存在utssdk目录,则判断utssdk下是否存在当前平台,如果不存在,则跳过
const utsSdkPlatformDir = path_1.default.resolve(dir, '../utssdk', process.env.UNI_UTS_PLATFORM);
if (!fs_1.default.existsSync(utsSdkPlatformDir)) {
return;
}
}
}
const importDir = (0, utils_1.normalizePath)(folder);
const files = fs_1.default.readdirSync(folder);
// 读取文件夹文件列表,比对文件名(fs.existsSync在大小写不敏感的系统会匹配不准确)
for (let i = 0; i < extensions.length; i++) {
const ext = extensions[i];
if (files.includes(name + ext)) {
easycoms[`^${name}$`] =
// mp平台,这里不处理,由uniEntryPlugin处理
is_easycom_encrypt_uni_modules && !isMp
? (0, utils_1.normalizePath)(path_1.default.join(rootDir, `uni_modules/${uni_modules_plugin_id}?${(0, x_1.isUniAppXAndroidNative)() ? 'uts-proxy' : 'uni_helpers'}`))
: `${importDir}/${name}${ext}`;
break;
}
}
});
return easycoms;
}
function initAutoScanEasycoms(platform, dirs, rootDir, extensions) {
const conflict = {};
const res = dirs.reduce((easycoms, dir) => {
const curEasycoms = initAutoScanEasycom(platform, dir, rootDir, extensions);
Object.keys(curEasycoms).forEach((name) => {
// Use the first component when name conflict
const componentPath = easycoms[name];
if (!componentPath) {
easycoms[name] = curEasycoms[name];
}
else {
;
(conflict[componentPath] || (conflict[componentPath] = [])).push(normalizeComponentPath(curEasycoms[name], rootDir));
}
});
return easycoms;
}, Object.create(null));
const conflictComponents = Object.keys(conflict);
if (conflictComponents.length) {
console.warn(messages_1.M['easycom.conflict']);
conflictComponents.forEach((com) => {
console.warn([normalizeComponentPath(com, rootDir), conflict[com]].join(','));
});
}
return res;
}
function normalizeComponentPath(componentPath, rootDir) {
return (0, utils_1.normalizePath)(path_1.default.relative(rootDir, componentPath));
}
function addImportDeclaration(importDeclarations, local, source, imported) {
importDeclarations.push(createImportDeclaration(local, source, imported));
return local;
}
exports.addImportDeclaration = addImportDeclaration;
function createImportDeclaration(local, source, imported) {
if (imported && local) {
return `import { ${imported} as ${local} } from '${source}';`;
}
if (local) {
return `import ${local} from '${source}';`;
}
return `import '${source}';`;
}
const RESOLVE_EASYCOM_IMPORT_CODE = `import { resolveDynamicComponent as __resolveDynamicComponent } from 'vue';import { resolveEasycom } from '@dcloudio/uni-app';`;
function genResolveEasycomCode(importDeclarations, code, name) {
if (process.env.UNI_APP_X_DOM2 === 'true' ||
// 内部 dev 版本,需要本地开发内置组件,比如web-view,此时需要直接返回本地easycom,不然会找到基座内置的
(process.env.UNI_HX_VERSION_DEV === 'true' &&
process.env.UNI_APP_X === 'true')) {
// dom2 模式下,为了性能,不再考虑优先级问题,如果开发者需要区别,可以手动导入为其他名称
return name;
}
if (!importDeclarations.includes(RESOLVE_EASYCOM_IMPORT_CODE)) {
importDeclarations.push(RESOLVE_EASYCOM_IMPORT_CODE);
}
return `resolveEasycom(${code
.replace('_resolveComponent', '__resolveDynamicComponent')
// 移除 maybeSelfReference 逻辑,easycom 优先级高于自引用组件
.replace(', true)', ')')}, ${name})`;
}
exports.genResolveEasycomCode = genResolveEasycomCode;
exports.UNI_EASYCOM_EXCLUDE = [/@dcloudio\/uni-h5/];
const utsEasyComAutoImports = {};
function getUTSEasyComAutoImports() {
return utsEasyComAutoImports;
}
exports.getUTSEasyComAutoImports = getUTSEasyComAutoImports;
function addUTSEasyComAutoImports(source, imports) {
if (!utsEasyComAutoImports[source]) {
utsEasyComAutoImports[source] = [imports];
}
else {
if (!utsEasyComAutoImports[source].find((item) => item[0] === imports[0])) {
utsEasyComAutoImports[source].push(imports);
}
}
}
exports.addUTSEasyComAutoImports = addUTSEasyComAutoImports;
function genUTSComponentPublicInstanceIdent(tagName) {
return (0, shared_1.capitalize)((0, shared_1.camelize)(tagName)) + 'ComponentPublicInstance';
}
exports.genUTSComponentPublicInstanceIdent = genUTSComponentPublicInstanceIdent;
function genUTSComponentPublicInstanceImported(root, fileName) {
root = (0, utils_1.normalizePath)(root);
if (path_1.default.isAbsolute(fileName) && fileName.startsWith(root)) {
fileName = (0, utils_1.normalizePath)(path_1.default.relative(root, fileName));
}
if (fileName.startsWith('@/')) {
return ((0, utsUtils_1.genUTSClassName)(fileName.replace('@/', '')) + 'ComponentPublicInstance');
}
return (0, utsUtils_1.genUTSClassName)(fileName) + 'ComponentPublicInstance';
}
exports.genUTSComponentPublicInstanceImported = genUTSComponentPublicInstanceImported;
@@ -0,0 +1,24 @@
export declare function initDefine(stringifyBoolean?: boolean): {
__X_STYLE_ISOLATION__: string | boolean;
__X_STYLE_ISOLATION_UP_ARROW__: string | boolean;
'process.env.UNI_APP_X_NEW_STYLE_ISOLATION': string | boolean;
'process.env.NODE_ENV': string;
'process.env.UNI_DEBUG': string | boolean;
'process.env.UNI_APP_ID': string;
'process.env.UNI_APP_NAME': string;
'process.env.UNI_APP_VERSION_NAME': string;
'process.env.UNI_APP_VERSION_CODE': string;
'process.env.UNI_PLATFORM': string;
'process.env.UNI_SUB_PLATFORM': string;
'process.env.UNI_MP_PLUGIN': string;
'process.env.UNI_SUBPACKAGE': string;
'process.env.UNI_COMPILER_VERSION': string;
'process.env.RUN_BY_HBUILDERX': string | boolean;
'process.env.UNI_AUTOMATOR_WS_ENDPOINT': string;
'process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC': string;
'process.env.UNI_CLOUD_PROVIDER': string;
'process.env.UNICLOUD_DEBUG': string;
'process.env.VUE_APP_PLATFORM': string;
'process.env.VUE_APP_DARK_MODE': string;
__UNI_PRELOAD_SHADOW_IMAGE__: string;
};
+72
View File
@@ -0,0 +1,72 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDefine = void 0;
const utils_1 = require("../utils");
const env_1 = require("../hbx/env");
const json_1 = require("../json");
function initDefine(stringifyBoolean = false) {
const manifestJson = (0, json_1.parseManifestJsonOnce)(process.env.UNI_INPUT_DIR);
const platformManifestJson = (0, json_1.getPlatformManifestJsonOnce)();
const isRunByHBuilderX = (0, env_1.runByHBuilderX)();
const isDebug = !!manifestJson.debug;
const isX = process.env.UNI_APP_X === 'true';
const isNewStyleIsolation = process.env.UNI_APP_STYLE_ISOLATION_VERSION === '2';
// 目前仅微信小程序支持^穿透
const isNewStyleIsolationUpArrow = isNewStyleIsolation && process.env.UNI_PLATFORM === 'mp-weixin';
const isMP = process.env.UNI_PLATFORM && process.env.UNI_PLATFORM.startsWith('mp-');
process.env['UNI_APP_ID'] = manifestJson.appid;
const mpXDefine = {
__UNI_FEATURE_VIRTUAL_HOST__: isX && isMP && platformManifestJson.enableVirtualHost !== false,
};
const styleIsolation = stringifyBoolean
? JSON.stringify(isNewStyleIsolation)
: isNewStyleIsolation;
return {
...initCustomDefine(),
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
'process.env.UNI_DEBUG': stringifyBoolean
? JSON.stringify(isDebug)
: isDebug,
'process.env.UNI_APP_ID': JSON.stringify(manifestJson.appid || ''),
'process.env.UNI_APP_NAME': JSON.stringify(manifestJson.name || ''),
'process.env.UNI_APP_VERSION_NAME': JSON.stringify(manifestJson.versionName || ''),
'process.env.UNI_APP_VERSION_CODE': JSON.stringify(manifestJson.versionCode || ''),
'process.env.UNI_PLATFORM': JSON.stringify(process.env.UNI_PLATFORM),
'process.env.UNI_SUB_PLATFORM': JSON.stringify(process.env.UNI_SUB_PLATFORM || ''),
'process.env.UNI_MP_PLUGIN': JSON.stringify(process.env.UNI_MP_PLUGIN || ''),
'process.env.UNI_SUBPACKAGE': JSON.stringify(process.env.UNI_SUBPACKAGE || ''),
'process.env.UNI_COMPILER_VERSION': JSON.stringify(process.env.UNI_COMPILER_VERSION || ''),
'process.env.RUN_BY_HBUILDERX': stringifyBoolean
? JSON.stringify(isRunByHBuilderX)
: isRunByHBuilderX,
'process.env.UNI_AUTOMATOR_WS_ENDPOINT': JSON.stringify(process.env.UNI_AUTOMATOR_WS_ENDPOINT || ''),
'process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC': JSON.stringify(process.env.UNI_AUTOMATOR_APP_WEBVIEW_SRC || ''),
'process.env.UNI_CLOUD_PROVIDER': JSON.stringify(process.env.UNI_CLOUD_PROVIDER || ''),
'process.env.UNICLOUD_DEBUG': JSON.stringify(process.env.UNICLOUD_DEBUG || ''),
// 兼容旧版本
'process.env.VUE_APP_PLATFORM': JSON.stringify(process.env.UNI_PLATFORM || ''),
'process.env.VUE_APP_DARK_MODE': JSON.stringify(platformManifestJson.darkmode || false),
__UNI_PRELOAD_SHADOW_IMAGE__: JSON.stringify(process.env.UNI_PLATFORM === 'mp-weixin' ? (0, utils_1.getShadowImagePath)('grey') : ''),
...mpXDefine,
__X_STYLE_ISOLATION__: styleIsolation,
__X_STYLE_ISOLATION_UP_ARROW__: stringifyBoolean
? JSON.stringify(isNewStyleIsolationUpArrow)
: isNewStyleIsolationUpArrow,
// 下边这个主要是为web服务,因为ssr目前只能识别process.env中的内容
'process.env.UNI_APP_X_NEW_STYLE_ISOLATION': styleIsolation,
};
}
exports.initDefine = initDefine;
function initCustomDefine() {
let define = {};
if (process.env.UNI_CUSTOM_DEFINE) {
try {
define = JSON.parse(process.env.UNI_CUSTOM_DEFINE);
}
catch (e) { }
}
return Object.keys(define).reduce((res, name) => {
res['process.env.' + name] = JSON.stringify(define[name]);
return res;
}, {});
}
@@ -0,0 +1,2 @@
export { initDefine } from './define';
export { initAppProvide } from './provide';
+7
View File
@@ -0,0 +1,7 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initAppProvide = exports.initDefine = void 0;
var define_1 = require("./define");
Object.defineProperty(exports, "initDefine", { enumerable: true, get: function () { return define_1.initDefine; } });
var provide_1 = require("./provide");
Object.defineProperty(exports, "initAppProvide", { enumerable: true, get: function () { return provide_1.initAppProvide; } });
@@ -0,0 +1,8 @@
export declare function initAppProvide(): {
__f__: string[];
crypto: string[];
'window.crypto': string[];
'global.crypto': string[];
'uni.getCurrentSubNVue': string[];
'uni.requireNativePlugin': string[];
};
+20
View File
@@ -0,0 +1,20 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initAppProvide = void 0;
const path_1 = __importDefault(require("path"));
const libDir = path_1.default.resolve(__dirname, '../../lib');
function initAppProvide() {
const cryptoDefine = [path_1.default.join(libDir, 'crypto.js'), 'default'];
return {
__f__: ['@dcloudio/uni-app', 'formatAppLog'],
crypto: cryptoDefine,
'window.crypto': cryptoDefine,
'global.crypto': cryptoDefine,
'uni.getCurrentSubNVue': ['@dcloudio/uni-app', 'getCurrentSubNVue'],
'uni.requireNativePlugin': ['@dcloudio/uni-app', 'requireNativePlugin'],
};
}
exports.initAppProvide = initAppProvide;
+3
View File
@@ -0,0 +1,3 @@
import type { BuildOptions } from 'esbuild';
export declare function transformWithEsbuild(code: string, filename: string, options: BuildOptions): Promise<import("esbuild").BuildResult<BuildOptions>>;
export declare function esbuild(options: BuildOptions): Promise<import("esbuild").BuildResult<BuildOptions>>;
+46
View File
@@ -0,0 +1,46 @@
"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.esbuild = exports.transformWithEsbuild = void 0;
const path_1 = __importDefault(require("path"));
function transformWithEsbuild(code, filename, options) {
options.stdin = {
contents: code,
resolveDir: path_1.default.dirname(filename),
};
return Promise.resolve().then(() => __importStar(require('esbuild'))).then((esbuild) => {
return esbuild.build(options);
});
}
exports.transformWithEsbuild = transformWithEsbuild;
function esbuild(options) {
return Promise.resolve().then(() => __importStar(require('esbuild'))).then((esbuild) => {
return esbuild.build(options);
});
}
exports.esbuild = esbuild;
+1
View File
@@ -0,0 +1 @@
export { default as chokidar } from 'chokidar';
+8
View File
@@ -0,0 +1,8 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.chokidar = void 0;
var chokidar_1 = require("chokidar");
Object.defineProperty(exports, "chokidar", { enumerable: true, get: function () { return __importDefault(chokidar_1).default; } });
+16
View File
@@ -0,0 +1,16 @@
export declare function isWxs(id: string): boolean;
export declare function isSjs(id: string): boolean;
export declare function isRenderjs(id: string): boolean;
type FilterType = 'wxs' | 'renderjs' | 'sjs';
export declare function parseRenderjs(id: string): {
type: FilterType;
name: string;
filename: string;
} | {
readonly type: "";
readonly name: "";
readonly filename: "";
};
export declare function missingModuleName(type: FilterType, code: string): string;
export declare function parseFilterNames(lang: string, code: string): string[];
export {};
+60
View File
@@ -0,0 +1,60 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseFilterNames = exports.missingModuleName = exports.parseRenderjs = exports.isRenderjs = exports.isSjs = exports.isWxs = void 0;
const url_1 = require("./vite/utils/url");
const WXS_RE = /vue&type=wxs/;
function isWxs(id) {
return WXS_RE.test(id);
}
exports.isWxs = isWxs;
const SJS_RE = /vue&type=sjs/;
function isSjs(id) {
return SJS_RE.test(id);
}
exports.isSjs = isSjs;
const RENDERJS_RE = /vue&type=renderjs/;
function isRenderjs(id) {
return RENDERJS_RE.test(id);
}
exports.isRenderjs = isRenderjs;
function parseRenderjs(id) {
if (isWxs(id) || isRenderjs(id) || isSjs(id)) {
const { query, filename } = (0, url_1.parseVueRequest)(id);
return {
type: query.type,
name: query.name,
filename,
};
}
return {
type: '',
name: '',
filename: '',
};
}
exports.parseRenderjs = parseRenderjs;
function missingModuleName(type, code) {
return `<script module="missing module name" lang="${type}">
${code}
</script>`;
}
exports.missingModuleName = missingModuleName;
const moduleRE = /module=["'](.*?)["']/;
function parseFilterNames(lang, code) {
const names = [];
const scriptTags = code.match(/<script\b[^>]*>/gm);
if (!scriptTags) {
return names;
}
const langRE = new RegExp(`lang=["']${lang}["']`);
scriptTags.forEach((scriptTag) => {
if (langRE.test(scriptTag)) {
const matches = scriptTag.match(moduleRE);
if (matches) {
names.push(matches[1]);
}
}
});
return names;
}
exports.parseFilterNames = parseFilterNames;
+1
View File
@@ -0,0 +1 @@
export declare function emptyDir(dir: string, skip?: string[]): void;
+21
View File
@@ -0,0 +1,21 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.emptyDir = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
function emptyDir(dir, skip = []) {
try {
for (const file of fs_1.default.readdirSync(dir)) {
if (skip.includes(file)) {
continue;
}
// node >= 14.14.0
fs_1.default.rmSync(path_1.default.resolve(dir, file), { recursive: true, force: true });
}
}
catch (e) { }
}
exports.emptyDir = emptyDir;
@@ -0,0 +1,8 @@
import type { Formatter } from '../logs/format';
export declare function resolveWebVaporPackage(packageName: string): string;
export declare function initWebVaporAliases(): void;
export declare function normalizeUniAppXVaporEnv(): void;
export declare function initModuleAlias(): void;
export declare function installHBuilderXPlugin(plugin: string): void;
export declare const moduleAliasFormatter: Formatter;
export declare function formatInstallHBuilderXPluginTips(lang: string, preprocessor: string): string;
+365
View File
@@ -0,0 +1,365 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.formatInstallHBuilderXPluginTips = exports.moduleAliasFormatter = exports.installHBuilderXPlugin = exports.initModuleAlias = exports.normalizeUniAppXVaporEnv = exports.initWebVaporAliases = exports.resolveWebVaporPackage = void 0;
// 注意:该文件尽可能少依赖其他文件,否则可能会导致还没有alias的时候,就加载了目标模块
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const module_alias_1 = __importDefault(require("module-alias"));
const utils_1 = require("./utils");
const pluginPaths_1 = require("./pluginPaths");
const hbxPlugins = {
// 普通 uni-app 的 SFC 外部类型解析通过此别名加载 TypeScript,按需依赖 compile-typescript。
// uni-app x 编译链通过 resolveUniTypeScript 使用 uni-uts-v1 自带的 TypeScript,
// 不走此别名,也不依赖 compile-typescript;注册别名本身不会加载该插件。
typescript: ['compile-typescript', 'node_modules/typescript'],
less: ['compile-less', 'node_modules/less'],
sass: ['compile-dart-sass', 'node_modules/sass'],
stylus: ['compile-stylus', 'node_modules/stylus'],
pug: ['compile-pug-cli', 'node_modules/pug'],
};
const commonVuePackages = [
'@vue/compiler-core',
'@vue/compiler-dom',
'@vue/compiler-sfc',
'@vue/shared',
];
const vaporVuePackages = [...commonVuePackages, '@vue/compiler-vapor'];
const webVaporVuePackages = [
...commonVuePackages,
'@vue/compiler-ssr',
'@vue/compiler-vapor',
'@vue/server-renderer',
];
function addVaporVuePackageAliases(vueDir, packages) {
const aliases = {};
packages.forEach((pkg) => {
aliases[pkg] = path_1.default.resolve(vueDir, pkg.slice(pkg.lastIndexOf('/') + 1));
});
module_alias_1.default.addAliases(aliases);
}
function resolveWebVaporPackage(packageName) {
return path_1.default.resolve(__dirname, '../../lib/dom2/web', packageName);
}
exports.resolveWebVaporPackage = resolveWebVaporPackage;
function resolveWebVaporPluginVue() {
return resolveWebVaporPackage('@vitejs/plugin-vue/dist/index.cjs');
}
function initWebVaporAliases() {
const webDir = resolveWebVaporPackage('');
const webVueDir = path_1.default.join(webDir, '@vue');
addVaporVuePackageAliases(webVueDir, webVaporVuePackages);
module_alias_1.default.addAliases({
'@vitejs/plugin-vue': resolveWebVaporPluginVue(),
'@dcloudio/compiler-vapor-web': path_1.default.join(webVueDir, 'compiler-vapor-web'),
'vue/compiler-sfc': path_1.default.join(webVueDir, 'compiler-sfc'),
'vue/server-renderer': path_1.default.join(webVueDir, 'server-renderer'),
});
}
exports.initWebVaporAliases = initWebVaporAliases;
function addAppVaporAliases(libDir) {
const appVueDir = path_1.default.resolve(libDir, 'dom2', 'app', '@vue');
addVaporVuePackageAliases(appVueDir, vaporVuePackages);
module_alias_1.default.addAliases({
'@vitejs/plugin-vue': path_1.default.resolve(libDir, 'dom2', 'app', '@vitejs', 'plugin-vue'),
'@dcloudio/compiler-vapor-dom2': path_1.default.join(appVueDir, 'compiler-vapor-dom2'),
});
}
function addNonVaporVuePackageAliases(libDir, compilerSfcPath, serverRendererPath) {
module_alias_1.default.addAliases({
'@vue/shared': require.resolve('@vue/shared'),
'@vue/shared/dist/shared.esm-bundler.js': require.resolve('@vue/shared/dist/shared.esm-bundler.js'),
'@vue/compiler-core': path_1.default.resolve(libDir, '@vue/compiler-core'),
'@vue/compiler-dom': require.resolve('@vue/compiler-dom'),
'@vue/compiler-sfc': compilerSfcPath,
'@vue/server-renderer': serverRendererPath,
'vue/compiler-sfc': compilerSfcPath,
'vue/server-renderer': serverRendererPath,
});
}
function isWebOrMpPlatform(platform) {
return platform === 'h5' || platform === 'web' || platform?.startsWith('mp-');
}
function isWebPlatform(platform) {
return platform === 'h5' || platform === 'web';
}
function hasWebVaporConfig() {
// 框架自身生成 dist-x-vapor 时没有用户项目目录,通过内部构建标记绕过配置文件检查。
if (process.env.UNI_APP_X_VAPOR_BUILD === 'true') {
return true;
}
// HBuilderX/CLI 会在加载框架前传入项目根目录。
const inputDir = process.env.UNI_INPUT_DIR;
return !!inputDir && fs_1.default.existsSync(path_1.default.resolve(inputDir, '.vapor'));
}
function resolveUniCliPlatform() {
const entry = process.argv[1];
if (!entry || !['uni', 'uni.js'].includes(path_1.default.basename(entry))) {
return;
}
const args = process.argv.slice(2);
for (let index = 0; index < args.length; index++) {
const arg = args[index];
if (arg === '--') {
break;
}
if (arg === '-p' || arg === '--platform') {
const platform = args[index + 1];
if (platform && !platform.startsWith('-')) {
return platform;
}
}
else if (arg.startsWith('-p=') || arg.startsWith('--platform=')) {
const platform = arg.slice(arg.indexOf('=') + 1);
if (platform) {
return platform;
}
}
}
return 'h5';
}
// 在归一化前记录外部开关,避免将初始化生成的 DOM2 状态误认为外部配置。
const externalDom2 = process.env.UNI_APP_X_DOM2 === 'true';
function normalizeUniAppXVaporEnv() {
// App 使用 UNI_APP_X_VAPOR 作为对外开关;Web 还支持 .vapor 和 DOM2 环境变量。
const utsPlatform = process.env.UNI_UTS_PLATFORM;
const uniPlatform = process.env.UNI_PLATFORM;
const cliPlatform = resolveUniCliPlatform();
const platform = cliPlatform || utsPlatform || uniPlatform;
const webVaporConfigured = isWebPlatform(platform) && (externalDom2 || hasWebVaporConfig());
// HBuilderX dev 不会预先注入 UNI_APP_X,因此这里需要同步补齐 uni-app x 环境标记。
const isWebVapor = webVaporConfigured;
if (isWebVapor) {
process.env.UNI_APP_X = 'true';
// Web Vapor 固定使用新样式隔离,在加载插件前统一首次编译、HMR 和 CSS 处理规则。
process.env.UNI_APP_STYLE_ISOLATION_VERSION = '2';
}
if (process.env.UNI_APP_X_VAPOR === 'true' || isWebVapor) {
process.env.UNI_APP_X_DOM2 = 'true';
}
else if (process.env.UNI_APP_X_VAPOR === 'false') {
delete process.env.UNI_APP_X_DOM2;
}
// alias 初始化早于 CLI 环境初始化,优先读取 CLI 参数,否则使用预置的平台环境变量。
// 小程序仍关闭 Vapor,Web 平台使用独立的 Web Vapor 产物。
const shouldDisableVapor = cliPlatform
? isWebOrMpPlatform(cliPlatform) && !isWebVapor
: (isWebOrMpPlatform(utsPlatform) || isWebOrMpPlatform(uniPlatform)) &&
!isWebVapor;
if (shouldDisableVapor) {
delete process.env.UNI_APP_X_DOM2;
}
// 将平台归一化后的实际状态同步回对外开关。
if (isWebVapor) {
process.env.UNI_APP_X_VAPOR = 'true';
process.env.UNI_APP_X_DOM2 = 'true';
}
if (process.env.UNI_APP_X_DOM2 === 'true') {
process.env.UNI_APP_X_VAPOR = 'true';
}
else {
delete process.env.UNI_APP_X_DOM2;
delete process.env.UNI_APP_X_VAPOR;
delete process.env.UNI_APP_X_DOM2_DYNAMIC;
delete process.env.UNI_APP_X_VAPOR_RENDER_TARGET;
}
}
exports.normalizeUniAppXVaporEnv = normalizeUniAppXVaporEnv;
function initModuleAlias() {
normalizeUniAppXVaporEnv();
const libDir = path_1.default.resolve(__dirname, '../../lib');
const compilerSfcPath = path_1.default.resolve(libDir, '@vue/compiler-sfc');
const serverRendererPath = require.resolve('@vue/server-renderer');
if (process.env.UNI_OUTPUT_DIR) {
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);
}
// 对路径进行兼容
if (!process.env.UNI_APP_X_DOM2_CPP_DIR &&
process.env.UNI_APP_HARMONY_DOM2_CPP_DIR) {
process.env.UNI_APP_X_DOM2_CPP_DIR =
process.env.UNI_APP_HARMONY_DOM2_CPP_DIR;
}
const platform = resolveUniCliPlatform() ||
process.env.UNI_UTS_PLATFORM ||
process.env.UNI_PLATFORM;
const webVapor = process.env.UNI_APP_X_VAPOR === 'true' && isWebPlatform(platform);
if (webVapor) {
initWebVaporAliases();
}
else if (process.env.UNI_APP_X_DOM2 === 'true') {
if (process.env.UNI_OUTPUT_DIR &&
(process.env.UNI_PLATFORM === 'app' ||
process.env.UNI_PLATFORM === 'app-plus' ||
process.env.UNI_PLATFORM === 'app-harmony')) {
if (!process.env.UNI_APP_X_DOM2_CPP_DIR) {
let baseDir = '';
const isAndroid = process.env.UNI_APP_PLATFORM === 'android';
const isIOS = process.env.UNI_APP_PLATFORM === 'ios';
if (process.env.NODE_ENV !== 'development' && (isAndroid || isIOS)) {
baseDir = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '.uniappx', isAndroid ? 'android' : 'ios');
}
else {
baseDir =
process.env.UNI_PLATFORM === 'app-harmony'
? process.env.UNI_OUTPUT_DIR
: process.env.UNI_APP_X_CACHE_DIR || process.env.UNI_OUTPUT_DIR;
}
process.env.UNI_APP_X_DOM2_CPP_DIR = path_1.default.resolve(baseDir, 'cpp');
process.env.UNI_APP_X_DOM2_SO_DIR = path_1.default.resolve(baseDir, 'so');
}
if (!process.env.UNI_APP_X_DOM2_KT_DIR) {
if (process.env.NODE_ENV !== 'development') {
process.env.UNI_APP_X_DOM2_KT_DIR = path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '.uniappx/android', 'src');
}
else {
process.env.UNI_APP_X_DOM2_KT_DIR = path_1.default.resolve(process.env.UNI_APP_X_CACHE_DIR ||
path_1.default.resolve(process.env.UNI_OUTPUT_DIR, '../.cache'), 'src');
}
}
}
if (process.env.UNI_APP_PLATFORM ||
process.env.UNI_PLATFORM === 'app-harmony') {
if (!process.env.UNI_APP_X_VAPOR_RENDER_TARGET) {
// 默认 app 平台使用 bytecode 目标
process.env.UNI_APP_X_VAPOR_RENDER_TARGET = 'bytecode';
}
if (process.env.UNI_APP_X_VAPOR_RENDER_TARGET?.includes('bytecode')) {
process.env.UNI_APP_X_DOM2_DYNAMIC = 'true';
}
// 如果是 ext-api 目标,强制使用 nativecode 目标
if (process.env.UNI_COMPILE_TARGET === 'ext-api') {
delete process.env.UNI_APP_X_DOM2_DYNAMIC;
}
}
}
if (process.env.UNI_APP_X_DOM2 === 'true' && !webVapor) {
addAppVaporAliases(libDir);
}
else if (!webVapor) {
addNonVaporVuePackageAliases(libDir, compilerSfcPath, serverRendererPath);
}
if (process.env.VITEST) {
module_alias_1.default.addAliases({
vue: '@dcloudio/uni-h5-vue',
'vue/package.json': '@dcloudio/uni-h5-vue/package.json',
});
}
if ((0, utils_1.isInHBuilderX)()) {
// 又是为了复用 HBuilderX 的插件逻辑,硬编码映射
Object.keys(hbxPlugins).forEach((lang) => {
const [pluginName, subpath] = hbxPlugins[lang];
const realPath = (0, pluginPaths_1.resolveHBuilderXPluginPath)(pluginName, subpath);
module_alias_1.default.addAlias(lang,
// @ts-expect-error
() => {
try {
if (!realPath) {
throw new Error(`HBuilder plugin "${pluginName}" is not found`);
}
require.resolve(realPath);
}
catch (e) {
const msg = exports.moduleAliasFormatter.format(`Preprocessor dependency "${lang}" not found. Did you install it?`);
console.error(msg);
process.exit(0);
}
return realPath;
});
});
// web 平台用了 vite 内置 css 插件,该插件会加载预编译器如scss、less等,需要转向到 HBuilderX 的对应编译器插件
if (isWebPlatform(process.env.UNI_PLATFORM)) {
// https://github.com/vitejs/vite/blob/main/packages/vite/src/node/packages.ts#L92
// 拦截预编译器
const join = path_1.default.join;
path_1.default.join = function (...paths) {
if (paths.length === 4) {
// path.join(basedir, 'node_modules', pkgName, 'package.json')
// const basedir = paths[0]
const nodeModules = paths[1]; // = node_modules
const pkgName = paths[2];
const packageJson = paths[3]; // = package.json
if (nodeModules === 'node_modules' &&
packageJson === 'package.json' &&
hbxPlugins[pkgName]) {
const [pluginName, subpath] = hbxPlugins[pkgName];
return ((0, pluginPaths_1.resolveHBuilderXPluginPath)(pluginName, subpath, packageJson) ||
join(...paths));
}
}
return join(...paths);
};
// https://github.com/vitejs/vite/blob/892916d040a035edde1add93c192e0b0c5c9dd86/packages/vite/src/node/plugins/css.ts#L1481
// const oldSync = resovle.sync
// resovle.sync = (id: string, opts?: SyncOpts) => {
// if ((hbxPlugins as any)[id]) {
// return path.resolve(
// process.env.UNI_HBUILDERX_PLUGINS,
// hbxPlugins[id as keyof typeof hbxPlugins]
// )
// }
// return oldSync(id, opts)
// }
}
}
}
exports.initModuleAlias = initModuleAlias;
function supportAutoInstallPlugin() {
return !!process.env.HX_Version;
}
function installHBuilderXPlugin(plugin) {
if (!supportAutoInstallPlugin()) {
return;
}
return console.error(`%HXRunUniAPPPluginName%${plugin}%HXRunUniAPPPluginName%`);
}
exports.installHBuilderXPlugin = installHBuilderXPlugin;
const installPreprocessorTips = {};
exports.moduleAliasFormatter = {
test(msg) {
return msg.includes('Preprocessor dependency');
},
format(msg) {
let lang = '';
let preprocessor = '';
if (msg.includes(`"pug"`)) {
lang = 'pug';
preprocessor = 'compile-pug-cli';
}
else if (msg.includes(`"sass"`)) {
lang = 'sass';
preprocessor = 'compile-dart-sass';
}
else if (msg.includes(`"less"`)) {
lang = 'less';
preprocessor = 'compile-less';
}
else if (msg.includes('"stylus"')) {
lang = 'stylus';
preprocessor = 'compile-stylus';
}
else if (msg.includes('"typescript"')) {
lang = 'typescript';
preprocessor = 'compile-typescript';
}
if (lang) {
// 仅提醒一次
if (installPreprocessorTips[lang]) {
return '';
}
installPreprocessorTips[lang] = true;
installHBuilderXPlugin(preprocessor);
return formatInstallHBuilderXPluginTips(lang, preprocessor);
}
return msg;
},
};
function formatInstallHBuilderXPluginTips(lang, preprocessor) {
return `预编译器错误:代码使用了${lang}语言,但未安装相应的编译器插件,${supportAutoInstallPlugin() ? '正在从' : '请前往'}插件市场安装该插件:
https://ext.dcloud.net.cn/plugin?name=${preprocessor}`;
}
exports.formatInstallHBuilderXPluginTips = formatInstallHBuilderXPluginTips;
+4
View File
@@ -0,0 +1,4 @@
export { isInHBuilderX } from './utils';
export declare const runByHBuilderX: () => boolean;
export declare function initModulePaths(): void;
export declare function fixBinaryPath(): void;
+167
View File
@@ -0,0 +1,167 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.fixBinaryPath = exports.initModulePaths = exports.runByHBuilderX = exports.isInHBuilderX = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const module_1 = __importDefault(require("module"));
const url_1 = require("url");
const uni_shared_1 = require("@dcloudio/uni-shared");
const resolve_1 = require("../resolve");
const utils_1 = require("../utils");
const utils_2 = require("./utils");
var utils_3 = require("./utils");
Object.defineProperty(exports, "isInHBuilderX", { enumerable: true, get: function () { return utils_3.isInHBuilderX; } });
exports.runByHBuilderX = (0, uni_shared_1.once)(() => {
return ((!!process.env.HX_PLUGIN_PATHS || !!process.env.UNI_HBUILDERX_PLUGINS) &&
(!!process.env.RUN_BY_HBUILDERX || !!process.env.HX_Version));
});
/**
* 增加 node_modules
*/
const initializedModulePaths = new Set();
function getPackageName(specifier) {
if (!specifier ||
specifier.startsWith('.') ||
specifier.startsWith('/') ||
specifier.startsWith('\\') ||
specifier.startsWith('#') ||
specifier.includes(':') ||
/[\\%?#]/.test(specifier)) {
return;
}
const segments = specifier.split('/');
if (segments.some((segment) => !segment || segment === '.' || segment === '..') ||
(specifier.startsWith('@') &&
(segments.length < 2 || segments[0].length === 1))) {
return;
}
const packageName = specifier.startsWith('@')
? segments.slice(0, 2).join('/')
: segments[0];
return packageName;
}
function canFallbackToNodeModules(specifier, error, nodeModulesPath) {
const code = error?.code;
if (code !== 'ERR_MODULE_NOT_FOUND') {
return false;
}
const packageName = getPackageName(specifier);
return (!!packageName && fs_1.default.existsSync(path_1.default.resolve(nodeModulesPath, packageName)));
}
function initModulePaths() {
if (!(0, utils_2.isInHBuilderX)()) {
return;
}
const nodeModulesPath = path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'node_modules');
if (initializedModulePaths.has(nodeModulesPath)) {
return;
}
const parentURL = (0, url_1.pathToFileURL)(path_1.default.resolve(process.env.UNI_CLI_CONTEXT, 'package.json')).href;
const moduleApi = module_1.default;
const Module = module.constructor.length > 1 ? module.constructor : module_1.default;
const oldNodeModulePaths = Module._nodeModulePaths;
Module._nodeModulePaths = function (from) {
const paths = oldNodeModulePaths.call(this, from);
if (!paths.includes(nodeModulesPath)) {
paths.push(nodeModulesPath);
}
return paths;
};
if (moduleApi.registerHooks) {
moduleApi.registerHooks({
resolve(specifier, context, nextResolve) {
try {
return nextResolve(specifier, context);
}
catch (error) {
if (!canFallbackToNodeModules(specifier, error, nodeModulesPath)) {
throw error;
}
return nextResolve(specifier, { ...context, parentURL });
}
},
});
initializedModulePaths.add(nodeModulesPath);
return;
}
// Node 的 ESM 解析不会使用 _nodeModulePaths,需要单独回退到 HBuilderX 内置依赖。
const register = moduleApi.register;
if (register) {
const nodeModulesURL = (0, url_1.pathToFileURL)(nodeModulesPath + path_1.default.sep).href;
const loader = `
import { existsSync } from 'node:fs'
const parentURL = ${JSON.stringify(parentURL)}
const nodeModulesURL = ${JSON.stringify(nodeModulesURL)}
export async function resolve(specifier, context, nextResolve) {
try {
return await nextResolve(specifier, context)
} catch (error) {
if (
error?.code !== 'ERR_MODULE_NOT_FOUND' ||
!specifier ||
specifier.startsWith('.') ||
specifier.startsWith('/') ||
specifier.startsWith('\\\\') ||
specifier.startsWith('#') ||
specifier.includes(':') ||
/[\\\\%?#]/.test(specifier)
) {
throw error
}
const segments = specifier.split('/')
if (
segments.some(
(segment) => !segment || segment === '.' || segment === '..'
) ||
(specifier.startsWith('@') &&
(segments.length < 2 || segments[0].length === 1))
) {
throw error
}
const packageName = specifier.startsWith('@')
? segments.slice(0, 2).join('/')
: segments[0]
if (!existsSync(new URL(packageName + '/', nodeModulesURL))) {
throw error
}
return nextResolve(specifier, { ...context, parentURL })
}
}
`;
register(`data:text/javascript,${encodeURIComponent(loader)}`, (0, url_1.pathToFileURL)(process.env.UNI_CLI_CONTEXT + path_1.default.sep));
}
initializedModulePaths.add(nodeModulesPath);
}
exports.initModulePaths = initModulePaths;
function resolveEsbuildModule(name) {
try {
return path_1.default.dirname(require.resolve(name + '/package.json', {
paths: [path_1.default.dirname((0, resolve_1.resolveBuiltIn)('esbuild/package.json'))],
}));
}
catch (e) { }
return '';
}
function fixBinaryPath() {
// cli 工程在 HBuilderX 中运行
if (!(0, utils_2.isInHBuilderX)() && (0, exports.runByHBuilderX)()) {
if (utils_1.isWindows) {
const win64 = resolveEsbuildModule('esbuild-windows-64');
if (win64) {
process.env.ESBUILD_BINARY_PATH = path_1.default.join(win64, 'esbuild.exe');
}
}
else {
const arm64 = resolveEsbuildModule('esbuild-darwin-arm64');
if (arm64) {
process.env.ESBUILD_BINARY_PATH = path_1.default.join(arm64, 'bin/esbuild');
}
}
}
}
exports.fixBinaryPath = fixBinaryPath;
@@ -0,0 +1,6 @@
export { formatAtFilename, createErrorWithBlockFlag } from './log';
export * from './env';
export { resolveHBuilderXPluginPath } from './pluginPaths';
export { initWebVaporAliases, resolveWebVaporPackage, initModuleAlias, normalizeUniAppXVaporEnv, installHBuilderXPlugin, formatInstallHBuilderXPluginTips, } from './alias';
export declare function uniHBuilderXConsolePlugin(method?: string): import("vite").Plugin<any>;
export declare function isEnableConsole(): boolean;
+69
View File
@@ -0,0 +1,69 @@
"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);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.isEnableConsole = exports.uniHBuilderXConsolePlugin = exports.formatInstallHBuilderXPluginTips = exports.installHBuilderXPlugin = exports.normalizeUniAppXVaporEnv = exports.initModuleAlias = exports.resolveWebVaporPackage = exports.initWebVaporAliases = exports.resolveHBuilderXPluginPath = exports.createErrorWithBlockFlag = exports.formatAtFilename = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../utils");
const console_1 = require("../vite/plugins/console");
const workers_1 = require("../workers");
var log_1 = require("./log");
Object.defineProperty(exports, "formatAtFilename", { enumerable: true, get: function () { return log_1.formatAtFilename; } });
Object.defineProperty(exports, "createErrorWithBlockFlag", { enumerable: true, get: function () { return log_1.createErrorWithBlockFlag; } });
__exportStar(require("./env"), exports);
var pluginPaths_1 = require("./pluginPaths");
Object.defineProperty(exports, "resolveHBuilderXPluginPath", { enumerable: true, get: function () { return pluginPaths_1.resolveHBuilderXPluginPath; } });
var alias_1 = require("./alias");
Object.defineProperty(exports, "initWebVaporAliases", { enumerable: true, get: function () { return alias_1.initWebVaporAliases; } });
Object.defineProperty(exports, "resolveWebVaporPackage", { enumerable: true, get: function () { return alias_1.resolveWebVaporPackage; } });
Object.defineProperty(exports, "initModuleAlias", { enumerable: true, get: function () { return alias_1.initModuleAlias; } });
Object.defineProperty(exports, "normalizeUniAppXVaporEnv", { enumerable: true, get: function () { return alias_1.normalizeUniAppXVaporEnv; } });
Object.defineProperty(exports, "installHBuilderXPlugin", { enumerable: true, get: function () { return alias_1.installHBuilderXPlugin; } });
Object.defineProperty(exports, "formatInstallHBuilderXPluginTips", { enumerable: true, get: function () { return alias_1.formatInstallHBuilderXPluginTips; } });
function uniHBuilderXConsolePlugin(method = '__f__') {
const exclude = [];
if (process.env.UNI_APP_X === 'true') {
const workersDirs = (0, workers_1.resolveWorkersDir)(process.env.UNI_INPUT_DIR);
if (workersDirs.length) {
// 排除workers目录
for (const workersDir of workersDirs) {
exclude.push((0, utils_1.pathToGlob)(path_1.default.join(process.env.UNI_INPUT_DIR, workersDir), '**/*'));
}
}
}
return (0, console_1.uniConsolePlugin)({
method,
exclude,
filename(filename) {
filename = path_1.default.relative(process.env.UNI_INPUT_DIR, filename);
if (filename.startsWith('.') || path_1.default.isAbsolute(filename)) {
return '';
}
return (0, utils_1.normalizePath)(filename);
},
});
}
exports.uniHBuilderXConsolePlugin = uniHBuilderXConsolePlugin;
function isEnableConsole() {
return !!((process.env.NODE_ENV === 'development' ||
process.env.NODE_ENV === 'test') &&
process.env.UNI_SOCKET_HOSTS &&
process.env.UNI_SOCKET_PORT &&
process.env.UNI_SOCKET_ID);
}
exports.isEnableConsole = isEnableConsole;
+13
View File
@@ -0,0 +1,13 @@
import type { LogErrorOptions } from 'vite';
import type { Formatter } from '../logs/format';
export declare function formatAtFilename(filename: string, line?: number, column?: number): string;
export declare const h5ServeFormatter: Formatter;
export declare const removeInfoFormatter: Formatter;
export declare const removeWarnFormatter: Formatter;
export declare const removeDuplicatePluginFormatter: Formatter;
export declare const errorFormatter: Formatter<LogErrorOptions>;
interface ErrorWithBlockFlag extends Error {
__errorBlocked: true;
}
export declare function createErrorWithBlockFlag(msg: string): ErrorWithBlockFlag;
export {};
+268
View File
@@ -0,0 +1,268 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createErrorWithBlockFlag = exports.errorFormatter = exports.removeDuplicatePluginFormatter = exports.removeWarnFormatter = exports.removeInfoFormatter = exports.h5ServeFormatter = exports.formatAtFilename = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const picocolors_1 = __importDefault(require("picocolors"));
const compiler_core_1 = require("@vue/compiler-core");
const shared_1 = require("@vue/shared");
const utils_1 = require("../utils");
const utils_2 = require("./utils");
const constants_1 = require("../constants");
const ast_1 = require("../vite/utils/ast");
const utils_3 = require("../vite/plugins/vitejs/utils");
const SIGNAL_H5_LOCAL = ' ➜ Local:';
const SIGNAL_H5_NETWORK = ' ➜ Network:';
const networkLogs = [];
const ZERO_WIDTH_CHAR = {
NOTE: '',
WARNING: '\u200B',
ERROR: '\u200C',
backup0: '\u200D', // 标记换行
backup1: '\u200E',
backup2: '\u200F',
backup3: '\uFEFF',
};
function overridedConsole(name, oldFn, char) {
console[name] = function (...args) {
oldFn.apply(this, args.map((arg) => {
let item;
if ((0, utils_2.isInHBuilderX)() && typeof arg === 'string' && arg.includes('\n')) {
arg = arg
.split('\n')
.map((line) => `${char}${line}${char}`)
.join('\n');
}
if (typeof arg !== 'object') {
item = `${char}${arg}${char}`;
}
else {
item = `${char}${JSON.stringify(arg)}${char}`;
}
return item;
}));
};
}
if (typeof console !== 'undefined') {
overridedConsole('warn', console.log, ZERO_WIDTH_CHAR.WARNING);
// overridedConsole('error', console.error, ZERO_WIDTH_CHAR.ERROR)
}
function formatAtFilename(filename, line, column) {
filename = filename.replace('\x00', '').split('?')[0];
const file = process.env.UNI_INPUT_DIR
? path_1.default.relative(process.env.UNI_INPUT_DIR, filename)
: filename;
return `at ${picocolors_1.default.cyan((0, utils_1.normalizePath)(file === 'pages-json-uts' ? 'pages.json' : file) +
':' +
(line || 1) +
':' +
(column || 0))}`;
}
exports.formatAtFilename = formatAtFilename;
exports.h5ServeFormatter = {
test(msg) {
return msg.includes(SIGNAL_H5_LOCAL) || msg.includes(SIGNAL_H5_NETWORK);
},
format(msg) {
if (msg.includes(SIGNAL_H5_NETWORK)) {
networkLogs.push(msg.replace('➜ ', '*'));
process.nextTick(() => {
if (networkLogs.length) {
// 延迟打印所有 network,仅最后一个 network 替换 ➜ 为 -,通知 hbx
const len = networkLogs.length - 1;
networkLogs[len] = networkLogs[len].replace('* Network', '- Network');
console.log(networkLogs.join('\n'));
networkLogs.length = 0;
}
});
return '';
}
if (msg.includes(SIGNAL_H5_LOCAL)) {
return msg.replace('➜ ', '-');
}
return msg.replace('➜ ', '*');
},
};
const REMOVED_MSGS = [
'build started...',
(msg) => {
return /built in [0-9]+ms\./.test(msg);
},
'watching for file changes...',
];
exports.removeInfoFormatter = {
test(msg) {
return !!REMOVED_MSGS.find((m) => ((0, shared_1.isString)(m) ? msg.includes(m) : m(msg)));
},
format() {
return '';
},
};
const REMOVED_WARN_MSGS = [];
exports.removeWarnFormatter = {
test(msg) {
return !!REMOVED_WARN_MSGS.find((m) => msg.includes(m));
},
format() {
return '';
},
};
exports.removeDuplicatePluginFormatter = {
test() {
return true;
},
format(msg) {
// [plugin:vite:vue] [plugin vite:vue]
// 正则匹配获取第一个插件名称,然后移除 [plugin vite:vue]
const pluginName = msg.match(/\[plugin\s([^\]]+)\]/)?.[1];
if (pluginName) {
return msg.replace(`[plugin ${pluginName}]`, '');
}
return msg;
},
};
exports.errorFormatter = {
test(_, opts) {
return !!(opts && opts.error);
},
format(_, opts) {
return buildErrorMessage(opts.error, [], false);
},
};
function createErrorWithBlockFlag(msg) {
const error = new Error(msg);
error.__errorBlocked = true;
return error;
}
exports.createErrorWithBlockFlag = createErrorWithBlockFlag;
let shouldAddErrorBlock = null;
const VITE_ROLLUP_FAILED_TO_RESOLVE_IMPORT_RE = /\[vite\]: Rollup failed to resolve import "([^"]+)" from "([^"]+)"/;
const CANNOT_FIND_MODULE_RE = /Cannot find module '([^']+)' from '([^']+)'/;
function buildErrorMessage(err, args = [], includeStack = true) {
if (err.customPrint) {
err.customPrint();
return '';
}
if (VITE_ROLLUP_FAILED_TO_RESOLVE_IMPORT_RE.test(err.message)) {
const [, importPath, fromPath] = err.message.match(VITE_ROLLUP_FAILED_TO_RESOLVE_IMPORT_RE) || [];
err.message = `Could not resolve "${importPath}" from "${fromPath}"`;
err.id = fromPath;
}
if (CANNOT_FIND_MODULE_RE.test(err.message)) {
const [, modulePath, fromPath] = err.message.match(CANNOT_FIND_MODULE_RE) || [];
// 清理模块路径和来源路径,移除查询参数等
const cleanModulePath = modulePath.split('?')[0];
const cleanFromPath = fromPath.split('?')[0];
const relativeFromPath = toRelativePath(cleanFromPath);
// 构建更友好的错误消息
err.id = cleanFromPath;
err.message = `Cannot find module "${cleanModulePath}" from "${relativeFromPath}"`;
}
// 移除 from 后面的内容
// 主要是处理:Could not resolve "./static/logo1.png" from "../../../../../../Users/xxx/HBuilderProjects/test-x/pages/index/index.uvue?vue&type=script&lang.uts"
if (err.id && err.message.startsWith('Could not resolve ')) {
err.message = err.message.split(' from ')[0];
}
if (err.plugin) {
// 避免出现这样的错误:[plugin:vite:vue] [plugin vite:vue]
if (err.message.startsWith(`[plugin ${err.plugin}]`)) {
let msg = err.message.replace(`[plugin ${err.plugin}]`, '');
if (err.loc) {
// [plugin:vite:vue] pages/index/index.vue (2:12): v-on="" is not supported
const locStr = `(${err.loc.line}:${err.loc.column}):`;
if (msg.includes(locStr)) {
msg = msg.split(locStr)[1].trim();
}
}
args.push(`${picocolors_1.default.magenta('[plugin:' + err.plugin + ']')} ${picocolors_1.default.red(msg)}`);
}
else {
const otherMsgs = [];
if (err.message.includes(': [plugin ')) {
const messages = err.message.split(': [plugin ');
err.message = messages[0];
messages.slice(1).forEach((msg) => {
otherMsgs.push(`[plugin:${msg}`);
});
}
if (err.loc) {
// [plugin:vite:vue] pages/index/index.vue (2:12): v-on="" is not supported
const locStr = `(${err.loc.line}:${err.loc.column}):`;
if (err.message.includes(locStr)) {
err.message = err.message.split(locStr)[1].trim();
}
}
args.push(`${picocolors_1.default.magenta('[plugin:' + err.plugin + ']')} ${picocolors_1.default.red(err.message)}`);
args.push(...otherMsgs);
if (err.loc &&
err.hook === 'transform' &&
err.plugin === 'rollup-plugin-dynamic-import-variables' &&
err.id &&
constants_1.EXTNAME_VUE_RE.test(err.id)) {
try {
const ast = (0, ast_1.parseVue)(fs_1.default.readFileSync(err.id, 'utf8'), []);
const scriptNode = ast.children.find((node) => node.type === compiler_core_1.NodeTypes.ELEMENT && node.tag === 'script');
if (scriptNode) {
const scriptLoc = scriptNode.loc;
args.push(picocolors_1.default.yellow(pad((0, utils_3.generateCodeFrame)(scriptLoc.source, err.loc))));
// correct error location
err.loc.line = scriptLoc.start.line + err.loc.line - 1;
}
}
catch (e) { }
}
}
}
else {
args.push(picocolors_1.default.red(err.message));
}
if (err.id) {
args.push(formatAtFilename(err.id, err.loc?.line, err.loc?.column));
}
if (err.frame) {
args.push(picocolors_1.default.yellow(pad(err.frame)));
}
if (includeStack && err.stack) {
args.push(pad(cleanStack(err.stack)));
}
if (shouldAddErrorBlock === null) {
shouldAddErrorBlock = // 目前仅限 x 的 app 平台
process.env.UNI_APP_X === 'true' &&
(process.env.UNI_UTS_PLATFORM === 'app-android' ||
process.env.UNI_UTS_PLATFORM === 'app-ios' ||
process.env.UNI_UTS_PLATFORM === 'app-harmony');
}
if (shouldAddErrorBlock) {
if (!err.__errorBlocked) {
args[0] = constants_1.SPECIAL_CHARS.ERROR_BLOCK + args[0];
args[args.length - 1] = args[args.length - 1] + constants_1.SPECIAL_CHARS.ERROR_BLOCK;
}
}
return args.join('\n');
}
function cleanStack(stack) {
return stack
.split(/\n/g)
.filter((l) => /^\s*at/.test(l))
.join('\n');
}
const splitRE = /\r?\n/;
function pad(source, n = 2) {
const lines = source.split(splitRE);
return lines.map((l) => ` `.repeat(n) + l).join(`\n`);
}
function toRelativePath(filePath) {
if (!filePath || !process.env.UNI_INPUT_DIR) {
return filePath;
}
try {
return path_1.default.relative(process.env.UNI_INPUT_DIR, filePath);
}
catch (e) {
// 转换失败时返回原路径
return filePath;
}
}
@@ -0,0 +1 @@
export declare function resolveHBuilderXPluginPath(pluginName: string, ...subpaths: string[]): string | undefined;
@@ -0,0 +1,33 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveHBuilderXPluginPath = void 0;
const path_1 = __importDefault(require("path"));
const uni_shared_1 = require("@dcloudio/uni-shared");
const getHBuilderXPluginPaths = (0, uni_shared_1.once)(() => {
const raw = process.env.HX_PLUGIN_PATHS;
if (!raw) {
return;
}
const pluginPaths = JSON.parse(raw);
if (!pluginPaths ||
typeof pluginPaths !== 'object' ||
Array.isArray(pluginPaths)) {
throw new Error('Invalid HX_PLUGIN_PATHS');
}
return pluginPaths;
});
function resolveHBuilderXPluginPath(pluginName, ...subpaths) {
const pluginPaths = getHBuilderXPluginPaths();
const mappedPath = pluginPaths?.[pluginName];
// 缺少 key 时使用旧目录;空字符串表示显式未配置,不回退。
const pluginPath = mappedPath !== undefined
? mappedPath
: process.env.UNI_HBUILDERX_PLUGINS
? path_1.default.resolve(process.env.UNI_HBUILDERX_PLUGINS, pluginName)
: undefined;
return pluginPath ? path_1.default.resolve(pluginPath, ...subpaths) : undefined;
}
exports.resolveHBuilderXPluginPath = resolveHBuilderXPluginPath;
@@ -0,0 +1 @@
export declare const isInHBuilderX: () => boolean;
+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.isInHBuilderX = void 0;
const path_1 = __importDefault(require("path"));
const uni_shared_1 = require("@dcloudio/uni-shared");
exports.isInHBuilderX = (0, uni_shared_1.once)(() => {
// 启动端应在加载编译器前传入工程类型,CLI 工程不能因 IDE 插件路径而使用内置环境。
if (process.env.UNI_PROJECT_TYPE === 'cli') {
return false;
}
// 未传工程类型时,沿用引入 HX_PLUGIN_PATHS 之前的识别及根目录初始化逻辑。
// 自动化测试传入了 HX_APP_ROOT(其实就是UNI_HBUILDERX_PLUGINS)
if (process.env.HX_APP_ROOT) {
process.env.UNI_HBUILDERX_PLUGINS = path_1.default.resolve(process.env.HX_APP_ROOT, 'plugins');
return true;
}
try {
const { name } = require(path_1.default.resolve(process.cwd(), '../about/package.json'));
if (name === 'about') {
process.env.UNI_HBUILDERX_PLUGINS = path_1.default.resolve(process.cwd(), '..');
return true;
}
}
catch (e) {
// console.error(e)
}
// 插件路径不代表工程类型;V 的独立插件布局由启动端显式传入 hbuilder。
return process.env.UNI_PROJECT_TYPE === 'hbuilder';
});
+10
View File
@@ -0,0 +1,10 @@
export declare function initI18nOptions(platform: UniApp.PLATFORM, inputDir: string, warning?: boolean, withMessages?: boolean): {
locale: string;
locales: Record<string, Record<string, string>>;
delimiters: [string, string];
} | undefined;
export declare const initI18nOptionsOnce: typeof initI18nOptions;
export declare function isUniAppLocaleFile(filepath: string): boolean;
export declare function getLocaleFiles(cwd: string): string[];
export declare function initLocales(dir: string, withMessages?: boolean): Record<string, Record<string, string>>;
export declare function resolveI18nLocale(platform: UniApp.PLATFORM, locales: string[], locale?: string): string;
+98
View File
@@ -0,0 +1,98 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveI18nLocale = exports.initLocales = exports.getLocaleFiles = exports.isUniAppLocaleFile = exports.initI18nOptionsOnce = exports.initI18nOptions = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));
const fast_glob_1 = require("fast-glob");
const shared_1 = require("@vue/shared");
const uni_shared_1 = require("@dcloudio/uni-shared");
const json_1 = require("./json");
const messages_1 = require("./messages");
function initI18nOptions(platform, inputDir, warning = false, withMessages = true) {
const locales = initLocales(path_1.default.resolve(inputDir, 'locale'), withMessages);
if (!Object.keys(locales).length) {
return;
}
const manifestJson = (0, json_1.parseManifestJsonOnce)(inputDir);
let fallbackLocale = manifestJson.fallbackLocale || 'en';
const IS_APP_X = process.env.UNI_APP_X === 'true';
if (IS_APP_X) {
fallbackLocale = manifestJson.locale || fallbackLocale;
}
const locale = resolveI18nLocale(platform, Object.keys(locales), fallbackLocale);
if (warning) {
if (!fallbackLocale) {
console.warn(messages_1.M['i18n.fallbackLocale.default'].replace('{locale}', locale));
}
else if (locale !== fallbackLocale) {
console.warn(messages_1.M['i18n.fallbackLocale.missing'].replace('{locale}', fallbackLocale));
}
}
return {
locale,
locales,
delimiters: uni_shared_1.I18N_JSON_DELIMITERS,
};
}
exports.initI18nOptions = initI18nOptions;
exports.initI18nOptionsOnce = (0, uni_shared_1.once)(initI18nOptions);
const localeJsonRE = /uni-app.*.json/;
function isUniAppLocaleFile(filepath) {
if (!filepath) {
return false;
}
return localeJsonRE.test(path_1.default.basename(filepath));
}
exports.isUniAppLocaleFile = isUniAppLocaleFile;
function parseLocaleJson(filepath) {
let jsonObj = (0, json_1.parseJson)(fs_1.default.readFileSync(filepath, 'utf8'), false, filepath);
if (isUniAppLocaleFile(filepath)) {
jsonObj = jsonObj.common || {};
}
return jsonObj;
}
function getLocaleFiles(cwd) {
return (0, fast_glob_1.sync)('*.json', { cwd, absolute: true });
}
exports.getLocaleFiles = getLocaleFiles;
function initLocales(dir, withMessages = true) {
if (!fs_1.default.existsSync(dir)) {
return {};
}
return fs_1.default.readdirSync(dir).reduce((res, filename) => {
if (path_1.default.extname(filename) === '.json') {
try {
const locale = path_1.default
.basename(filename)
.replace(/(uni-app.)?(.*).json/, '$2');
if (withMessages) {
(0, shared_1.extend)(res[locale] || (res[locale] = {}), parseLocaleJson(path_1.default.join(dir, filename)));
}
else {
res[locale] = {};
}
}
catch (e) { }
}
return res;
}, {});
}
exports.initLocales = initLocales;
function resolveI18nLocale(platform, locales, locale) {
if (locale && locales.includes(locale)) {
return locale;
}
const defaultLocales = ['zh-Hans', 'zh-Hant'];
if (platform === 'app' || platform === 'h5') {
defaultLocales.unshift('en');
}
else {
// 小程序
defaultLocales.push('en');
}
return defaultLocales.find((locale) => locales.includes(locale)) || locales[0];
}
exports.resolveI18nLocale = resolveI18nLocale;
+37
View File
@@ -0,0 +1,37 @@
export * from './fs';
export * from './mp';
export * from './url';
export * from './env';
export * from './hbx';
export * from './ssr';
export * from './vue';
export * from './uts';
export * from './uts/extApi';
export * from './uts/scriptMacros';
export * from './x';
export * from './logs';
export * from './dom2';
export * from './i18n';
export * from './deps';
export * from './json';
export * from './vite';
export * from './utils';
export * from './easycom';
export * from './constants';
export * from './preprocess';
export * from './postcss';
export * from './filter';
export * from './esbuild';
export * from './resolve';
export * from './scripts';
export * from './platform';
export * from './utsUtils';
export * from './workers';
export * from './uasm';
export { parseUniExtApi, parseUniExtApis, parseInjects, Define, DefineOptions, Defines, getUniExtApiProviderRegisters, formatExtApiProviderName, } from './uni_modules';
export { copyEncryptUniModulesDom2Bytes, getUniModulesEncryptType, parseUniModulesArtifacts, resolveEncryptUniModule, } from './uni_modules.cloud';
import type { EncryptPackageJson } from './uni_modules.cloud';
export type EncryptArtifacts = EncryptPackageJson['uni_modules']['artifacts'];
export { M } from './messages';
export * from './exports';
export { checkUpdate } from './checkUpdate';
+63
View File
@@ -0,0 +1,63 @@
"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 });
exports.checkUpdate = exports.M = exports.resolveEncryptUniModule = exports.parseUniModulesArtifacts = exports.getUniModulesEncryptType = exports.copyEncryptUniModulesDom2Bytes = exports.formatExtApiProviderName = exports.getUniExtApiProviderRegisters = exports.parseInjects = exports.parseUniExtApis = exports.parseUniExtApi = void 0;
__exportStar(require("./fs"), exports);
__exportStar(require("./mp"), exports);
__exportStar(require("./url"), exports);
__exportStar(require("./env"), exports);
__exportStar(require("./hbx"), exports);
__exportStar(require("./ssr"), exports);
__exportStar(require("./vue"), exports);
__exportStar(require("./uts"), exports);
__exportStar(require("./uts/extApi"), exports);
__exportStar(require("./uts/scriptMacros"), exports);
__exportStar(require("./x"), exports);
__exportStar(require("./logs"), exports);
__exportStar(require("./dom2"), exports);
__exportStar(require("./i18n"), exports);
__exportStar(require("./deps"), exports);
__exportStar(require("./json"), exports);
__exportStar(require("./vite"), exports);
__exportStar(require("./utils"), exports);
__exportStar(require("./easycom"), exports);
__exportStar(require("./constants"), exports);
__exportStar(require("./preprocess"), exports);
__exportStar(require("./postcss"), exports);
__exportStar(require("./filter"), exports);
__exportStar(require("./esbuild"), exports);
__exportStar(require("./resolve"), exports);
__exportStar(require("./scripts"), exports);
__exportStar(require("./platform"), exports);
__exportStar(require("./utsUtils"), exports);
__exportStar(require("./workers"), exports);
__exportStar(require("./uasm"), exports);
var uni_modules_1 = require("./uni_modules");
Object.defineProperty(exports, "parseUniExtApi", { enumerable: true, get: function () { return uni_modules_1.parseUniExtApi; } });
Object.defineProperty(exports, "parseUniExtApis", { enumerable: true, get: function () { return uni_modules_1.parseUniExtApis; } });
Object.defineProperty(exports, "parseInjects", { enumerable: true, get: function () { return uni_modules_1.parseInjects; } });
Object.defineProperty(exports, "getUniExtApiProviderRegisters", { enumerable: true, get: function () { return uni_modules_1.getUniExtApiProviderRegisters; } });
Object.defineProperty(exports, "formatExtApiProviderName", { enumerable: true, get: function () { return uni_modules_1.formatExtApiProviderName; } });
var uni_modules_cloud_1 = require("./uni_modules.cloud");
Object.defineProperty(exports, "copyEncryptUniModulesDom2Bytes", { enumerable: true, get: function () { return uni_modules_cloud_1.copyEncryptUniModulesDom2Bytes; } });
Object.defineProperty(exports, "getUniModulesEncryptType", { enumerable: true, get: function () { return uni_modules_cloud_1.getUniModulesEncryptType; } });
Object.defineProperty(exports, "parseUniModulesArtifacts", { enumerable: true, get: function () { return uni_modules_cloud_1.parseUniModulesArtifacts; } });
Object.defineProperty(exports, "resolveEncryptUniModule", { enumerable: true, get: function () { return uni_modules_cloud_1.resolveEncryptUniModule; } });
var messages_1 = require("./messages");
Object.defineProperty(exports, "M", { enumerable: true, get: function () { return messages_1.M; } });
__exportStar(require("./exports"), exports);
var checkUpdate_1 = require("./checkUpdate");
Object.defineProperty(exports, "checkUpdate", { enumerable: true, get: function () { return checkUpdate_1.checkUpdate; } });
@@ -0,0 +1,3 @@
export * from './pages';
export * from './manifest';
export { polyfillCode, arrayBufferCode, restoreGlobalCode } from './pages/code';
@@ -0,0 +1,23 @@
"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 });
exports.restoreGlobalCode = exports.arrayBufferCode = exports.polyfillCode = void 0;
__exportStar(require("./pages"), exports);
__exportStar(require("./manifest"), exports);
var code_1 = require("./pages/code");
Object.defineProperty(exports, "polyfillCode", { enumerable: true, get: function () { return code_1.polyfillCode; } });
Object.defineProperty(exports, "arrayBufferCode", { enumerable: true, get: function () { return code_1.arrayBufferCode; } });
Object.defineProperty(exports, "restoreGlobalCode", { enumerable: true, get: function () { return code_1.restoreGlobalCode; } });
@@ -0,0 +1,2 @@
export declare function initArguments(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
export declare function parseArguments(pagesJson: UniApp.PagesJson): string | undefined;
@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseArguments = exports.initArguments = void 0;
function initArguments(manifestJson, pagesJson) {
const args = parseArguments(pagesJson);
if (args) {
manifestJson.plus.arguments = args;
}
}
exports.initArguments = initArguments;
function parseArguments(pagesJson) {
if (process.env.NODE_ENV !== 'development') {
return;
}
// 指定了入口
if (process.env.UNI_CLI_LAUNCH_PAGE_PATH) {
return JSON.stringify({
path: process.env.UNI_CLI_LAUNCH_PAGE_PATH,
query: process.env.UNI_CLI_LAUNCH_PAGE_QUERY,
});
}
const condition = pagesJson.condition;
if (condition && condition.list?.length) {
const list = condition.list;
let current = condition.current || 0;
if (current < 0) {
current = 0;
}
if (current >= list.length) {
current = 0;
}
return JSON.stringify(list[current]);
}
}
exports.parseArguments = parseArguments;
@@ -0,0 +1 @@
export declare function initCheckSystemWebview(manifestJson: Record<string, any>): void;
@@ -0,0 +1,17 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initCheckSystemWebview = void 0;
function initCheckSystemWebview(manifestJson) {
// 检查Android系统webview版本 || 下载X5后启动
let plusWebView = manifestJson.plus.webView;
if (plusWebView) {
manifestJson.plus['uni-app'].webView = plusWebView;
delete manifestJson.plus.webView;
}
else {
manifestJson.plus['uni-app'].webView = {
minUserAgentVersion: '49.0',
};
}
}
exports.initCheckSystemWebview = initCheckSystemWebview;
@@ -0,0 +1,4 @@
export declare const APP_CONFUSION_FILENAME = "app-confusion.js";
export declare function isConfusionFile(filename: string): boolean;
export declare function hasConfusionFile(inputDir?: string): boolean;
export declare function initConfusion(manifestJson: Record<string, any>): void;
@@ -0,0 +1,75 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.initConfusion = exports.hasConfusionFile = exports.isConfusionFile = exports.APP_CONFUSION_FILENAME = void 0;
const path_1 = __importDefault(require("path"));
const utils_1 = require("../../../utils");
const constants_1 = require("../../../constants");
const manifest_1 = require("../../manifest");
function isJsFile(filename) {
return constants_1.EXTNAME_JS_RE.test(filename);
}
function isStaticJsFile(filename) {
return (filename.indexOf('hybrid/html') === 0 ||
filename.indexOf('static/') === 0 ||
filename.indexOf('/static/') !== -1); // subpackages, uni_modules 中的 static 目录
}
const dynamicConfusionJsFiles = [];
exports.APP_CONFUSION_FILENAME = 'app-confusion.js';
function isConfusionFile(filename) {
return dynamicConfusionJsFiles.includes((0, utils_1.normalizePath)(filename));
}
exports.isConfusionFile = isConfusionFile;
function hasConfusionFile(inputDir) {
if (inputDir) {
const manifestJson = (0, manifest_1.parseManifestJsonOnce)(inputDir);
const resources = manifestJson['app-plus']?.confusion?.resources;
if (resources && parseConfusion(resources)[1].length) {
return true;
}
}
return !!dynamicConfusionJsFiles.length;
}
exports.hasConfusionFile = hasConfusionFile;
function parseConfusion(resources) {
const res = {};
const dynamicJsFiles = [];
Object.keys(resources).reduce((res, name) => {
const extname = path_1.default.extname(name);
if (extname === '.nvue') {
res[name.replace('.nvue', '.js')] = resources[name];
}
else if (isJsFile(name)) {
// 静态 js 加密
if (isStaticJsFile(name)) {
res[name] = resources[name];
}
else {
// 非静态 js 将被合并进 app-confusion.js
dynamicJsFiles.push(name);
}
}
else {
throw new Error(`原生混淆仅支持 nvue 页面,错误的页面路径:${name}`);
}
// TODO 旧编译器会检查要加密的 nvue 页面(包括subnvue)是否被使用?后续有时间再考虑支持吧,意义不太大
return res;
}, res);
if (dynamicJsFiles.length) {
res[exports.APP_CONFUSION_FILENAME] = {};
}
return [res, dynamicJsFiles];
}
function initConfusion(manifestJson) {
dynamicConfusionJsFiles.length = 0;
if (!manifestJson.plus.confusion?.resources) {
return;
}
const resources = manifestJson.plus.confusion.resources;
const [res, dynamicJsFiles] = parseConfusion(resources);
manifestJson.plus.confusion.resources = res;
dynamicConfusionJsFiles.push(...dynamicJsFiles);
}
exports.initConfusion = initConfusion;
@@ -0,0 +1 @@
export declare function initDefaultManifestJson(): any;
@@ -0,0 +1,47 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initDefaultManifestJson = void 0;
function initDefaultManifestJson() {
return JSON.parse(defaultManifestJson);
}
exports.initDefaultManifestJson = initDefaultManifestJson;
const defaultManifestJson = `{
"@platforms": [
"android",
"iPhone",
"iPad"
],
"id": "__WEAPP_ID",
"name": "__WEAPP_NAME",
"version": {
"name": "1.0",
"code": ""
},
"description": "",
"developer": {
"name": "",
"email": "",
"url": ""
},
"permissions": {},
"plus": {
"useragent": {
"value": "",
"concatenate": true
},
"splashscreen": {
"target":"id:1",
"autoclose": true,
"waiting": true,
"alwaysShowBeforeRender":true
},
"popGesture": "close",
"launchwebview": {}
},
"app-harmony": {
"useragent": {
"value": "",
"concatenate": true
}
}
}`;
@@ -0,0 +1,3 @@
export declare function getAppRenderer(manifestJson: Record<string, any>): "" | "native";
export declare function getAppCodeSplitting(manifestJson: Record<string, any>): boolean;
export declare function getAppStyleIsolation(manifestJson: Record<string, any>): 'apply-shared' | 'isolated' | 'shared';
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getAppStyleIsolation = exports.getAppCodeSplitting = exports.getAppRenderer = void 0;
function getAppRenderer(manifestJson) {
const platformOptions = manifestJson['app-plus'];
if (platformOptions && platformOptions.renderer === 'native') {
return 'native';
}
return '';
}
exports.getAppRenderer = getAppRenderer;
function getAppCodeSplitting(manifestJson) {
if (manifestJson['app-plus']?.optimization?.codeSplitting === true) {
return true;
}
return false;
}
exports.getAppCodeSplitting = getAppCodeSplitting;
function getAppStyleIsolation(manifestJson) {
return (manifestJson['app-plus']?.optimization?.styleIsolation ?? 'apply-shared');
}
exports.getAppStyleIsolation = getAppStyleIsolation;
@@ -0,0 +1 @@
export declare function initI18n(manifestJson: Record<string, any>): Record<string, any>;
@@ -0,0 +1,14 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initI18n = void 0;
const uni_i18n_1 = require("@dcloudio/uni-i18n");
const i18n_1 = require("../../../i18n");
function initI18n(manifestJson) {
const i18nOptions = (0, i18n_1.initI18nOptions)(process.env.UNI_PLATFORM, process.env.UNI_INPUT_DIR, true);
if (i18nOptions) {
manifestJson = JSON.parse((0, uni_i18n_1.compileI18nJsonStr)(JSON.stringify(manifestJson), i18nOptions));
manifestJson.fallbackLocale = i18nOptions.locale;
}
return manifestJson;
}
exports.initI18n = initI18n;
@@ -0,0 +1,6 @@
export declare function normalizeAppManifestJson(userManifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): Record<string, any>;
export * from './env';
export { APP_CONFUSION_FILENAME, isConfusionFile, hasConfusionFile, } from './confusion';
export { getNVueCompiler, getNVueStyleCompiler, getNVueFlexDirection, } from './nvue';
export { parseArguments } from './arguments';
export { initI18n } from './i18n';
@@ -0,0 +1,67 @@
"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 });
exports.initI18n = exports.parseArguments = exports.getNVueFlexDirection = exports.getNVueStyleCompiler = exports.getNVueCompiler = exports.hasConfusionFile = exports.isConfusionFile = exports.APP_CONFUSION_FILENAME = exports.normalizeAppManifestJson = void 0;
const shared_1 = require("@vue/shared");
const merge_1 = require("./merge");
const defaultManifestJson_1 = require("./defaultManifestJson");
const statusbar_1 = require("./statusbar");
const plus_1 = require("./plus");
const nvue_1 = require("./nvue");
const arguments_1 = require("./arguments");
const safearea_1 = require("./safearea");
const splashscreen_1 = require("./splashscreen");
const confusion_1 = require("./confusion");
const uniApp_1 = require("./uniApp");
const launchwebview_1 = require("./launchwebview");
const checksystemwebview_1 = require("./checksystemwebview");
const tabBar_1 = require("./tabBar");
const i18n_1 = require("./i18n");
const theme_1 = require("../../theme");
const manifest_1 = require("../../manifest");
function normalizeAppManifestJson(userManifestJson, pagesJson) {
const manifestJson = (0, merge_1.initRecursiveMerge)((0, defaultManifestJson_1.initDefaultManifestJson)(), userManifestJson);
const manifestJsonPlatform = (0, manifest_1.getPlatformManifestJson)(manifestJson);
const { pages, globalStyle, tabBar } = (0, theme_1.initTheme)(manifestJsonPlatform, pagesJson);
(0, shared_1.extend)(pagesJson, JSON.parse(JSON.stringify({ pages, globalStyle, tabBar })));
(0, statusbar_1.initAppStatusbar)(manifestJson, pagesJson);
(0, arguments_1.initArguments)(manifestJson, pagesJson);
(0, plus_1.initPlus)(manifestJson, pagesJson);
(0, nvue_1.initNVue)(manifestJson, pagesJson);
(0, safearea_1.initSafearea)(manifestJson, pagesJson);
(0, splashscreen_1.initSplashscreen)(manifestJson, userManifestJson);
(0, confusion_1.initConfusion)(manifestJson);
(0, uniApp_1.initUniApp)(manifestJson);
// 依赖 initArguments 先执行
(0, tabBar_1.initTabBar)((0, launchwebview_1.initLaunchwebview)(manifestJson, pagesJson), manifestJson, pagesJson);
// 依赖 initUniApp 先执行
(0, checksystemwebview_1.initCheckSystemWebview)(manifestJson);
return (0, i18n_1.initI18n)(manifestJson);
}
exports.normalizeAppManifestJson = normalizeAppManifestJson;
__exportStar(require("./env"), exports);
var confusion_2 = require("./confusion");
Object.defineProperty(exports, "APP_CONFUSION_FILENAME", { enumerable: true, get: function () { return confusion_2.APP_CONFUSION_FILENAME; } });
Object.defineProperty(exports, "isConfusionFile", { enumerable: true, get: function () { return confusion_2.isConfusionFile; } });
Object.defineProperty(exports, "hasConfusionFile", { enumerable: true, get: function () { return confusion_2.hasConfusionFile; } });
var nvue_2 = require("./nvue");
Object.defineProperty(exports, "getNVueCompiler", { enumerable: true, get: function () { return nvue_2.getNVueCompiler; } });
Object.defineProperty(exports, "getNVueStyleCompiler", { enumerable: true, get: function () { return nvue_2.getNVueStyleCompiler; } });
Object.defineProperty(exports, "getNVueFlexDirection", { enumerable: true, get: function () { return nvue_2.getNVueFlexDirection; } });
var arguments_2 = require("./arguments");
Object.defineProperty(exports, "parseArguments", { enumerable: true, get: function () { return arguments_2.parseArguments; } });
var i18n_2 = require("./i18n");
Object.defineProperty(exports, "initI18n", { enumerable: true, get: function () { return i18n_2.initI18n; } });
@@ -0,0 +1 @@
export declare function initLaunchwebview(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): string;
@@ -0,0 +1,53 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initLaunchwebview = void 0;
const shared_1 = require("@vue/shared");
function initLaunchwebview(manifestJson, pagesJson) {
let entryPagePath = pagesJson.pages[0].path;
// 依赖前置执行initArguments
if (manifestJson.plus.arguments) {
try {
const args = JSON.parse(manifestJson.plus.arguments);
if (args.path) {
entryPagePath = args.path;
}
}
catch (e) { }
}
if (manifestJson.plus.useragent.concatenate) {
if (manifestJson.plus.useragent.value) {
manifestJson.plus.useragent.value = [
'uni-app',
manifestJson.plus.useragent.value,
].join(' ');
}
else {
manifestJson.plus.useragent.value = 'uni-app';
}
}
if (manifestJson['app-harmony'].useragent.concatenate) {
if (manifestJson['app-harmony'].useragent.value) {
manifestJson['app-harmony'].useragent.value = [
'uni-app',
manifestJson['app-harmony'].useragent.value,
].join(' ');
}
else {
manifestJson['app-harmony'].useragent.value = 'uni-app';
}
}
(0, shared_1.extend)(manifestJson.plus.launchwebview, {
id: '1',
kernel: 'WKWebview',
});
// 首页为nvue
const entryPage = pagesJson.pages.find((p) => p.path === entryPagePath);
if (entryPage?.style.isNVue) {
manifestJson.plus.launchwebview.uniNView = { path: entryPagePath + '.js' };
}
else {
manifestJson.launch_path = '__uniappview.html';
}
return entryPagePath;
}
exports.initLaunchwebview = initLaunchwebview;
@@ -0,0 +1 @@
export declare function initRecursiveMerge(manifestJson: Record<string, any>, userManifestJson: Record<string, any>): Record<string, any>;
@@ -0,0 +1,22 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initRecursiveMerge = void 0;
const merge_1 = require("merge");
function initRecursiveMerge(manifestJson, userManifestJson) {
const platformConfig = {
plus: userManifestJson['app-plus'],
};
platformConfig['app-harmony'] = userManifestJson['app-harmony'];
return (0, merge_1.recursive)(true, manifestJson, {
id: userManifestJson.appid || '',
name: userManifestJson.name || '',
description: userManifestJson.description || '',
version: {
name: userManifestJson.versionName,
code: userManifestJson.versionCode,
},
locale: userManifestJson.locale,
uniStatistics: userManifestJson.uniStatistics,
}, platformConfig);
}
exports.initRecursiveMerge = initRecursiveMerge;
@@ -0,0 +1,4 @@
export declare function initNVue(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
export declare function getNVueCompiler(manifestJson: Record<string, any>): "uni-app" | "vue" | "weex" | "vite";
export declare function getNVueStyleCompiler(manifestJson: Record<string, any>): "uni-app" | "weex";
export declare function getNVueFlexDirection(manifestJson: Record<string, any>): "column" | "row" | "row-reverse" | "column-reverse";
@@ -0,0 +1,41 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getNVueFlexDirection = exports.getNVueStyleCompiler = exports.getNVueCompiler = exports.initNVue = void 0;
function initNVue(manifestJson, pagesJson) { }
exports.initNVue = initNVue;
function getNVueCompiler(manifestJson) {
const platformOptions = manifestJson['app-plus'];
if (platformOptions) {
const { nvueCompiler } = platformOptions;
if (nvueCompiler === 'weex') {
return 'weex';
}
if (nvueCompiler === 'vue') {
return 'vue';
}
if (nvueCompiler === 'vite') {
return 'vite';
}
}
return 'uni-app';
}
exports.getNVueCompiler = getNVueCompiler;
function getNVueStyleCompiler(manifestJson) {
const platformOptions = manifestJson['app-plus'];
if (platformOptions && platformOptions.nvueStyleCompiler === 'uni-app') {
return 'uni-app';
}
return 'weex';
}
exports.getNVueStyleCompiler = getNVueStyleCompiler;
const flexDirs = ['row', 'row-reverse', 'column', 'column-reverse'];
function getNVueFlexDirection(manifestJson) {
let flexDir = 'column';
const appPlusJson = manifestJson['app-plus'] || manifestJson['plus'];
if (appPlusJson?.nvue?.['flex-direction'] &&
flexDirs.includes(appPlusJson?.nvue?.['flex-direction'])) {
flexDir = appPlusJson.nvue['flex-direction'];
}
return flexDir;
}
exports.getNVueFlexDirection = getNVueFlexDirection;
@@ -0,0 +1 @@
export declare function initPlus(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
@@ -0,0 +1,139 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initPlus = void 0;
const shared_1 = require("@vue/shared");
const merge_1 = require("merge");
const wxPageOrientationMapping = {
auto: [
'portrait-primary',
'portrait-secondary',
'landscape-primary',
'landscape-secondary',
],
portrait: ['portrait-primary', 'portrait-secondary'],
landscape: ['landscape-primary', 'landscape-secondary'],
};
function initPlus(manifestJson, pagesJson) {
initUniStatistics(manifestJson);
// 转换为老版本配置
if (manifestJson.plus.modules) {
manifestJson.permissions = manifestJson.plus.modules;
delete manifestJson.plus.modules;
}
const distribute = manifestJson.plus.distribute;
if (distribute) {
if (distribute.android) {
manifestJson.plus.distribute.google = distribute.android;
delete manifestJson.plus.distribute.android;
}
if (distribute.ios) {
manifestJson.plus.distribute.apple = distribute.ios;
delete manifestJson.plus.distribute.ios;
}
if (distribute.sdkConfigs) {
manifestJson.plus.distribute.plugins = distribute.sdkConfigs;
delete manifestJson.plus.distribute.sdkConfigs;
}
if (manifestJson.plus.darkmode) {
if (!(distribute.google || (distribute.google = {})).defaultNightMode) {
distribute.google.defaultNightMode = 'auto';
}
if (!(distribute.apple || (distribute.apple = {})).UIUserInterfaceStyle) {
distribute.apple.UIUserInterfaceStyle = 'Automatic';
}
}
}
// 屏幕启动方向
if (manifestJson.plus.screenOrientation) {
// app平台优先使用 manifest 配置
manifestJson.screenOrientation = manifestJson.plus.screenOrientation;
delete manifestJson.plus.screenOrientation;
}
else if (pagesJson.globalStyle?.pageOrientation) {
// 兼容微信小程序
const pageOrientationValue = wxPageOrientationMapping[pagesJson.globalStyle
.pageOrientation];
if (pageOrientationValue) {
manifestJson.screenOrientation = pageOrientationValue;
}
}
// 全屏配置
manifestJson.fullscreen = manifestJson.plus.fullscreen;
// 地图坐标系
if (manifestJson.permissions && manifestJson.permissions.Maps) {
manifestJson.permissions.Maps.coordType = 'gcj02';
}
if (!manifestJson.permissions) {
manifestJson.permissions = {};
}
manifestJson.permissions.UniNView = {
description: 'UniNView原生渲染',
};
// 允许内联播放视频
manifestJson.plus.allowsInlineMediaPlayback = true;
if (!manifestJson.plus.distribute) {
manifestJson.plus.distribute = {
plugins: {},
};
}
if (!manifestJson.plus.distribute.plugins) {
manifestJson.plus.distribute.plugins = {};
}
// 录音支持 mp3
manifestJson.plus.distribute.plugins.audio = {
mp3: {
description: 'Android平台录音支持MP3格式文件',
},
};
// 有效值为 close,none
if (!['close', 'none'].includes(manifestJson.plus.popGesture)) {
manifestJson.plus.popGesture = 'close';
}
}
exports.initPlus = initPlus;
function initUniStatistics(manifestJson) {
// 根节点配置了统计
if (manifestJson.uniStatistics) {
manifestJson.plus.uniStatistics = (0, merge_1.recursive)(true, manifestJson.uniStatistics, manifestJson.plus.uniStatistics);
manifestJson['app-harmony'].uniStatistics = (0, merge_1.recursive)(true, manifestJson.uniStatistics, manifestJson['app-harmony'].uniStatistics);
delete manifestJson.uniStatistics;
}
if (!process.env.UNI_CLOUD_PROVIDER) {
return;
}
let spaces = [];
try {
spaces = JSON.parse(process.env.UNI_CLOUD_PROVIDER);
}
catch (e) { }
if (!(0, shared_1.isArray)(spaces) || !spaces.length) {
return;
}
const space = spaces[0];
if (!space) {
return;
}
const uniStatistics = manifestJson.plus?.uniStatistics;
if (!uniStatistics) {
return;
}
/**
* 判断是否为私有版统计:
* - 新配置:type === 'private'
* - 旧配置兼容:version === 2
*/
const isPrivateStat = uniStatistics.type === 'private' ||
uniStatistics.version === 2 ||
uniStatistics.version === '2';
if (isPrivateStat) {
if (uniStatistics.uniCloud && uniStatistics.uniCloud.spaceId) {
return;
}
uniStatistics.uniCloud = {
provider: space.provider,
spaceId: space.spaceId,
clientSecret: space.clientSecret,
endpoint: space.endpoint,
};
}
}
@@ -0,0 +1 @@
export declare function initSafearea(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
@@ -0,0 +1,35 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initSafearea = void 0;
function initSafearea(manifestJson, pagesJson) {
if (pagesJson.tabBar?.list?.length) {
// 安全区配置 仅包含 tabBar 的时候才配置
if (!manifestJson.plus.safearea) {
manifestJson.plus.safearea = {
background: pagesJson.tabBar.backgroundColor || '#FFFFFF',
bottom: {
offset: 'auto',
},
};
}
if (!manifestJson['app-harmony'].safearea) {
manifestJson['app-harmony'].safearea = {
background: pagesJson.tabBar.backgroundColor || '#FFFFFF',
bottom: {
offset: 'auto',
},
};
}
}
else {
if (!manifestJson.plus.launchwebview) {
manifestJson.plus.launchwebview = {
render: 'always',
};
}
else if (!manifestJson.plus.launchwebview.render) {
manifestJson.plus.launchwebview.render = 'always';
}
}
}
exports.initSafearea = initSafearea;
@@ -0,0 +1,5 @@
export declare function initSplashscreen(manifestJson: Record<string, any>, userManifestJson: Record<string, any>): void;
export declare function getSplashscreen(manifestJson: Record<string, any>): {
autoclose: boolean;
alwaysShowBeforeRender: boolean;
};
@@ -0,0 +1,43 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getSplashscreen = exports.initSplashscreen = void 0;
const shared_1 = require("@vue/shared");
function initSplashscreen(manifestJson, userManifestJson) {
if (!manifestJson.plus.splashscreen) {
return;
}
// 强制白屏检测
const splashscreenOptions = userManifestJson['app-plus'] && userManifestJson['app-plus'].splashscreen;
const hasAlwaysShowBeforeRender = splashscreenOptions && (0, shared_1.hasOwn)(splashscreenOptions, 'alwaysShowBeforeRender');
if (!hasAlwaysShowBeforeRender &&
manifestJson.plus.splashscreen.autoclose === false) {
// 兼容旧版本仅配置了 autoclose 为 false
manifestJson.plus.splashscreen.alwaysShowBeforeRender = false;
}
if (manifestJson.plus.splashscreen.alwaysShowBeforeRender) {
// 白屏检测
if (!manifestJson.plus.splashscreen.target) {
manifestJson.plus.splashscreen.target = 'id:1';
}
manifestJson.plus.splashscreen.autoclose = true;
manifestJson.plus.splashscreen.delay = 0;
}
else {
// 不启用白屏检测
delete manifestJson.plus.splashscreen.target;
if (manifestJson.plus.splashscreen.autoclose) {
// 启用 uni-app 框架关闭 splash
manifestJson.plus.splashscreen.autoclose = false; // 原 5+ autoclose 改为 false
}
}
delete manifestJson.plus.splashscreen.alwaysShowBeforeRender;
}
exports.initSplashscreen = initSplashscreen;
function getSplashscreen(manifestJson) {
const splashscreenOptions = manifestJson['app-plus']?.splashscreen || {};
return {
autoclose: splashscreenOptions.autoclose !== false,
alwaysShowBeforeRender: splashscreenOptions.alwaysShowBeforeRender !== false,
};
}
exports.getSplashscreen = getSplashscreen;
@@ -0,0 +1 @@
export declare function initAppStatusbar(manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): Record<string, any>;
@@ -0,0 +1,16 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initAppStatusbar = void 0;
function initAppStatusbar(manifestJson, pagesJson) {
const titleColor = pagesJson.pages[0].style.navigationBar.titleColor ||
pagesJson.globalStyle.navigationBar.titleColor ||
'#000000';
const backgroundColor = pagesJson.globalStyle.navigationBar.backgroundColor || '#000000';
manifestJson.plus.statusbar = {
immersed: 'supportedDevice',
style: titleColor === '#ffffff' ? 'light' : 'dark',
background: backgroundColor,
};
return manifestJson;
}
exports.initAppStatusbar = initAppStatusbar;
@@ -0,0 +1 @@
export declare function initTabBar(entryPagePath: string, manifestJson: Record<string, any>, pagesJson: UniApp.PagesJson): void;
@@ -0,0 +1,24 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initTabBar = void 0;
const uni_shared_1 = require("@dcloudio/uni-shared");
function initTabBar(entryPagePath, manifestJson, pagesJson) {
if (!pagesJson.tabBar?.list?.length) {
return;
}
const tabBar = JSON.parse(JSON.stringify(pagesJson.tabBar));
tabBar.borderStyle = (0, uni_shared_1.normalizeTabBarStyles)(tabBar.borderStyle);
if (!tabBar.selectedColor) {
tabBar.selectedColor = uni_shared_1.SELECTED_COLOR;
}
tabBar.height = `${parseFloat(tabBar.height) || uni_shared_1.TABBAR_HEIGHT}px`;
// 首页是 tabBar 页面
const item = tabBar.list.find((page) => page.pagePath === entryPagePath);
if (item) {
;
tabBar.child = ['lauchwebview'];
tabBar.selected = tabBar.list.indexOf(item);
}
manifestJson.plus.tabBar = tabBar;
}
exports.initTabBar = initTabBar;
@@ -0,0 +1 @@
export declare function initUniApp(manifestJson: Record<string, any>): void;
@@ -0,0 +1,19 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.initUniApp = void 0;
const nvue_1 = require("./nvue");
function initUniApp(manifestJson) {
manifestJson.plus['uni-app'] = {
control: 'uni-v3',
vueVersion: '3',
compilerVersion: process.env.UNI_COMPILER_VERSION,
nvueCompiler: (0, nvue_1.getNVueCompiler)(manifestJson),
renderer: 'auto',
nvue: {
'flex-direction': (0, nvue_1.getNVueFlexDirection)(manifestJson),
},
nvueLaunchMode: manifestJson.plus.nvueLaunchMode === 'fast' ? 'fast' : 'normal',
};
delete manifestJson.plus.nvueLaunchMode;
}
exports.initUniApp = initUniApp;
@@ -0,0 +1,4 @@
export declare const arrayBufferCode = "\nif (typeof uni !== 'undefined' && uni && uni.requireGlobal) {\n const global = uni.requireGlobal()\n ArrayBuffer = global.ArrayBuffer\n Int8Array = global.Int8Array\n Uint8Array = global.Uint8Array\n Uint8ClampedArray = global.Uint8ClampedArray\n Int16Array = global.Int16Array\n Uint16Array = global.Uint16Array\n Int32Array = global.Int32Array\n Uint32Array = global.Uint32Array\n Float32Array = global.Float32Array\n Float64Array = global.Float64Array\n BigInt64Array = global.BigInt64Array\n BigUint64Array = global.BigUint64Array\n};\n";
export declare const polyfillCode = "\nif (typeof Promise !== 'undefined' && !Promise.prototype.finally) {\n Promise.prototype.finally = function(callback) {\n const promise = this.constructor\n return this.then(\n value => promise.resolve(callback()).then(() => value),\n reason => promise.resolve(callback()).then(() => {\n throw reason\n })\n )\n }\n};\n\nif (typeof uni !== 'undefined' && uni && uni.requireGlobal) {\n const global = uni.requireGlobal()\n ArrayBuffer = global.ArrayBuffer\n Int8Array = global.Int8Array\n Uint8Array = global.Uint8Array\n Uint8ClampedArray = global.Uint8ClampedArray\n Int16Array = global.Int16Array\n Uint16Array = global.Uint16Array\n Int32Array = global.Int32Array\n Uint32Array = global.Uint32Array\n Float32Array = global.Float32Array\n Float64Array = global.Float64Array\n BigInt64Array = global.BigInt64Array\n BigUint64Array = global.BigUint64Array\n};\n\n";
export declare const restoreGlobalCode = "\nif(uni.restoreGlobal){\n uni.restoreGlobal(Vue,weex,plus,setTimeout,clearTimeout,setInterval,clearInterval)\n}\n";
export declare const globalCode: string;
@@ -0,0 +1,61 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.globalCode = exports.restoreGlobalCode = exports.polyfillCode = exports.arrayBufferCode = void 0;
exports.arrayBufferCode = `
if (typeof uni !== 'undefined' && uni && uni.requireGlobal) {
const global = uni.requireGlobal()
ArrayBuffer = global.ArrayBuffer
Int8Array = global.Int8Array
Uint8Array = global.Uint8Array
Uint8ClampedArray = global.Uint8ClampedArray
Int16Array = global.Int16Array
Uint16Array = global.Uint16Array
Int32Array = global.Int32Array
Uint32Array = global.Uint32Array
Float32Array = global.Float32Array
Float64Array = global.Float64Array
BigInt64Array = global.BigInt64Array
BigUint64Array = global.BigUint64Array
};
`;
exports.polyfillCode = `
if (typeof Promise !== 'undefined' && !Promise.prototype.finally) {
Promise.prototype.finally = function(callback) {
const promise = this.constructor
return this.then(
value => promise.resolve(callback()).then(() => value),
reason => promise.resolve(callback()).then(() => {
throw reason
})
)
}
};
${exports.arrayBufferCode}
`;
exports.restoreGlobalCode = `
if(uni.restoreGlobal){
uni.restoreGlobal(Vue,weex,plus,setTimeout,clearTimeout,setInterval,clearInterval)
}
`;
const GLOBALS = [
'global',
'window',
'document',
'frames',
'self',
'location',
'navigator',
'localStorage',
'history',
'Caches',
'screen',
'alert',
'confirm',
'prompt',
'fetch',
'XMLHttpRequest',
'WebSocket',
'webkit',
'print',
];
exports.globalCode = GLOBALS.map((g) => `${g}:u`).join(',');
@@ -0,0 +1,3 @@
export declare function staticImportPageCode(pagesJson: Record<string, any>): string;
export declare function definePageCode(pagesJson: Record<string, any>, platform?: UniApp.PLATFORM, dynamicImport?: boolean): string;
export declare function defineNVuePageCode(pagesJson: Record<string, any>): string;
@@ -0,0 +1,56 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.defineNVuePageCode = exports.definePageCode = exports.staticImportPageCode = void 0;
const utils_1 = require("../../../utils");
function staticImportPageCode(pagesJson) {
const importPagesCode = [];
pagesJson.pages.forEach((page) => {
const pagePath = page.path;
const pagePathWithExtname = (0, utils_1.normalizePagePath)(pagePath, 'app');
if (pagePathWithExtname) {
importPagesCode.push(`import '../assets/${(0, utils_1.removeExt)(pagePathWithExtname)}'`);
}
});
return importPagesCode.join('\n');
}
exports.staticImportPageCode = staticImportPageCode;
function definePageCode(pagesJson, platform = 'app', dynamicImport = false) {
const importPagesCode = [];
const definePagesCode = [];
pagesJson.pages.forEach((page) => {
if (platform === 'app' && page.style.isNVue) {
return;
}
const pagePath = page.path;
const pageIdentifier = (0, utils_1.normalizeIdentifier)(pagePath);
const pagePathWithExtname = (0, utils_1.normalizePagePath)(pagePath, platform);
if (pagePathWithExtname) {
if (dynamicImport) {
// 拆分页面
importPagesCode.push(`const ${pageIdentifier} = ()=>import('./${pagePathWithExtname}')`);
}
else {
importPagesCode.push(`import ${pageIdentifier} from './${pagePathWithExtname}'`);
}
definePagesCode.push(`__definePage('${pagePath}',${pageIdentifier})`);
}
});
return importPagesCode.join('\n') + '\n' + definePagesCode.join('\n');
}
exports.definePageCode = definePageCode;
function defineNVuePageCode(pagesJson) {
const importNVuePagesCode = [];
pagesJson.pages.forEach((page) => {
if (!page.style.isNVue) {
return;
}
const pagePathWithExtname = (0, utils_1.normalizePagePath)(page.path, 'app');
if (pagePathWithExtname) {
importNVuePagesCode.push(
// 使用 res.default 确保 rollup 不会摇树
`import('./${pagePathWithExtname}').then((res)=>{res.default})`);
}
});
return importNVuePagesCode.join('\n');
}
exports.defineNVuePageCode = defineNVuePageCode;
@@ -0,0 +1,4 @@
export { staticImportPageCode } from './definePage';
export declare function normalizeAppPagesJson(pagesJson: Record<string, any>, platform?: UniApp.PLATFORM, dynamicImport?: boolean): string;
export declare function normalizeAppNVuePagesJson(pagesJson: Record<string, any>): string;
export declare function normalizeAppConfigService(pagesJson: UniApp.PagesJson, manifestJson: Record<string, any>): string;
@@ -0,0 +1,31 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeAppConfigService = exports.normalizeAppNVuePagesJson = exports.normalizeAppPagesJson = exports.staticImportPageCode = void 0;
const code_1 = require("./code");
const definePage_1 = require("./definePage");
const uniConfig_1 = require("./uniConfig");
const uniRoutes_1 = require("./uniRoutes");
var definePage_2 = require("./definePage");
Object.defineProperty(exports, "staticImportPageCode", { enumerable: true, get: function () { return definePage_2.staticImportPageCode; } });
function normalizeAppPagesJson(pagesJson, platform = 'app', dynamicImport = false) {
return (0, definePage_1.definePageCode)(pagesJson, platform, dynamicImport);
}
exports.normalizeAppPagesJson = normalizeAppPagesJson;
function normalizeAppNVuePagesJson(pagesJson) {
return (0, definePage_1.defineNVuePageCode)(pagesJson);
}
exports.normalizeAppNVuePagesJson = normalizeAppNVuePagesJson;
function normalizeAppConfigService(pagesJson, manifestJson) {
return `
;(function(){
let u=void 0,isReady=false,onReadyCallbacks=[],isServiceReady=false,onServiceReadyCallbacks=[];
const __uniConfig = ${(0, uniConfig_1.normalizeAppUniConfig)(pagesJson, manifestJson)};
const __uniRoutes = ${(0, uniRoutes_1.normalizeAppUniRoutes)(pagesJson)}.map(uniRoute=>(uniRoute.meta.route=uniRoute.path,__uniConfig.pages.push(uniRoute.path),uniRoute.path='/'+uniRoute.path,uniRoute));
__uniConfig.styles=${process.env.UNI_NVUE_APP_STYLES || '[]'};//styles
__uniConfig.onReady=function(callback){if(__uniConfig.ready){callback()}else{onReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"ready",{get:function(){return isReady},set:function(val){isReady=val;if(!isReady){return}const callbacks=onReadyCallbacks.slice(0);onReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
__uniConfig.onServiceReady=function(callback){if(__uniConfig.serviceReady){callback()}else{onServiceReadyCallbacks.push(callback)}};Object.defineProperty(__uniConfig,"serviceReady",{get:function(){return isServiceReady},set:function(val){isServiceReady=val;if(!isServiceReady){return}const callbacks=onServiceReadyCallbacks.slice(0);onServiceReadyCallbacks.length=0;callbacks.forEach(function(callback){callback()})}});
service.register("uni-app-config",{create(a,b,c){if(!__uniConfig.viewport){var d=b.weex.config.env.scale,e=b.weex.config.env.deviceWidth,f=Math.ceil(e/d);Object.assign(__uniConfig,{viewport:f,defaultFontSize:16})}return{instance:{__uniConfig:__uniConfig,__uniRoutes:__uniRoutes,${code_1.globalCode}}}}});
})();
`;
}
exports.normalizeAppConfigService = normalizeAppConfigService;
@@ -0,0 +1,6 @@
export declare function normalizeAppUniConfig(pagesJson: UniApp.PagesJson, manifestJson: Record<string, any>): string;
export declare function parseEntryPagePath(pagesJson: UniApp.PagesJson): {
entryPagePath: string;
entryPageQuery: string;
realEntryPagePath: string;
};
@@ -0,0 +1,75 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseEntryPagePath = exports.normalizeAppUniConfig = void 0;
const path_1 = __importDefault(require("path"));
const i18n_1 = require("../../../i18n");
const manifest_1 = require("../../manifest");
const manifest_2 = require("../manifest");
const arguments_1 = require("../manifest/arguments");
const splashscreen_1 = require("../manifest/splashscreen");
const theme_1 = require("../../theme");
function normalizeAppUniConfig(pagesJson, manifestJson) {
const { autoclose, alwaysShowBeforeRender } = (0, splashscreen_1.getSplashscreen)(manifestJson);
const platformConfig = (0, manifest_1.getPlatformManifestJsonOnce)();
const config = {
pages: [],
globalStyle: pagesJson.globalStyle,
nvue: {
compiler: (0, manifest_2.getNVueCompiler)(manifestJson),
styleCompiler: (0, manifest_2.getNVueStyleCompiler)(manifestJson),
'flex-direction': (0, manifest_2.getNVueFlexDirection)(manifestJson),
},
renderer: manifestJson['app-plus']?.renderer === 'native' ? 'native' : 'auto',
appname: manifestJson.name || '',
splashscreen: {
alwaysShowBeforeRender,
autoclose,
},
compilerVersion: process.env.UNI_COMPILER_VERSION,
...parseEntryPagePath(pagesJson),
networkTimeout: (0, manifest_1.normalizeNetworkTimeout)(manifestJson.networkTimeout),
tabBar: pagesJson.tabBar,
fallbackLocale: manifestJson.fallbackLocale,
locales: (0, i18n_1.initLocales)(path_1.default.join(process.env.UNI_INPUT_DIR, 'locale')),
darkmode: platformConfig.darkmode || false,
themeConfig: (0, theme_1.normalizeThemeConfigOnce)(platformConfig),
// @ts-expect-error
qqMapKey: platformConfig?.distribute?.sdkConfigs?.maps?.tencent?.key,
};
// TODO 待支持分包
return JSON.stringify(config);
}
exports.normalizeAppUniConfig = normalizeAppUniConfig;
function parseEntryPagePath(pagesJson) {
const res = {
entryPagePath: '',
entryPageQuery: '',
realEntryPagePath: '',
};
if (!pagesJson.pages.length) {
return res;
}
res.entryPagePath = pagesJson.pages[0].path;
const argsJsonStr = (0, arguments_1.parseArguments)(pagesJson);
if (argsJsonStr) {
try {
const args = JSON.parse(argsJsonStr);
const entryPagePath = args.path || args.pathName;
const realEntryPagePath = res.entryPagePath;
if (entryPagePath && realEntryPagePath !== entryPagePath) {
res.entryPagePath = entryPagePath;
res.entryPageQuery = args.query ? '?' + args.query : '';
// non tabBar page
if (!(pagesJson.tabBar?.list || []).find((page) => page.pagePath === entryPagePath)) {
res.realEntryPagePath = realEntryPagePath;
}
}
}
catch (e) { }
}
return res;
}
exports.parseEntryPagePath = parseEntryPagePath;
@@ -0,0 +1 @@
export declare function normalizeAppUniRoutes(pagesJson: UniApp.PagesJson): string;
@@ -0,0 +1,8 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.normalizeAppUniRoutes = void 0;
const pages_1 = require("../../pages");
function normalizeAppUniRoutes(pagesJson) {
return JSON.stringify((0, pages_1.normalizePagesRoute)(pagesJson));
}
exports.normalizeAppUniRoutes = normalizeAppUniRoutes;
@@ -0,0 +1,8 @@
export * from './mp';
export * from './app';
export * from './json';
export * from './pages';
export * from './manifest';
export * from './theme';
export { normalizeUniAppXAppPagesJson, normalizeUniAppXAppConfig, parseUniXPageOptions, parseUniXFlexDirection, parseUniXSplashScreen, isUniXPageFile, getUniXPagePaths, parseUniXAppAndroidPackage, } from './uni-x';
export { checkPagesJson } from './utils';
+34
View File
@@ -0,0 +1,34 @@
"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 });
exports.checkPagesJson = exports.parseUniXAppAndroidPackage = exports.getUniXPagePaths = exports.isUniXPageFile = exports.parseUniXSplashScreen = exports.parseUniXFlexDirection = exports.parseUniXPageOptions = exports.normalizeUniAppXAppConfig = exports.normalizeUniAppXAppPagesJson = void 0;
__exportStar(require("./mp"), exports);
__exportStar(require("./app"), exports);
__exportStar(require("./json"), exports);
__exportStar(require("./pages"), exports);
__exportStar(require("./manifest"), exports);
__exportStar(require("./theme"), exports);
var uni_x_1 = require("./uni-x");
Object.defineProperty(exports, "normalizeUniAppXAppPagesJson", { enumerable: true, get: function () { return uni_x_1.normalizeUniAppXAppPagesJson; } });
Object.defineProperty(exports, "normalizeUniAppXAppConfig", { enumerable: true, get: function () { return uni_x_1.normalizeUniAppXAppConfig; } });
Object.defineProperty(exports, "parseUniXPageOptions", { enumerable: true, get: function () { return uni_x_1.parseUniXPageOptions; } });
Object.defineProperty(exports, "parseUniXFlexDirection", { enumerable: true, get: function () { return uni_x_1.parseUniXFlexDirection; } });
Object.defineProperty(exports, "parseUniXSplashScreen", { enumerable: true, get: function () { return uni_x_1.parseUniXSplashScreen; } });
Object.defineProperty(exports, "isUniXPageFile", { enumerable: true, get: function () { return uni_x_1.isUniXPageFile; } });
Object.defineProperty(exports, "getUniXPagePaths", { enumerable: true, get: function () { return uni_x_1.getUniXPagePaths; } });
Object.defineProperty(exports, "parseUniXAppAndroidPackage", { enumerable: true, get: function () { return uni_x_1.parseUniXAppAndroidPackage; } });
var utils_1 = require("./utils");
Object.defineProperty(exports, "checkPagesJson", { enumerable: true, get: function () { return utils_1.checkPagesJson; } });
@@ -0,0 +1 @@
export declare function parseJson(jsonStr: string, shouldPre: boolean | undefined, filename: string): any;

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