更新
This commit is contained in:
+202
@@ -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.
|
||||
+2756
File diff suppressed because one or more lines are too long
+142
@@ -0,0 +1,142 @@
|
||||
import { defineAsyncApi as originalDefineAsyncApi, defineOffApi as originalDefineOffApi, defineOnApi as originalDefineOnApi, defineSyncApi as originalDefineSyncApi, defineTaskApi as originalDefineTaskApi } from "@dcloudio/uni-mp-sdk";
|
||||
interface UniProvider {
|
||||
id: string;
|
||||
description: string;
|
||||
}
|
||||
const providers: Map<String, Map<String, UniProvider>> = new Map();
|
||||
function getUniProvider<T extends UniProvider>(service: string, providerName: String): T | null {
|
||||
return providers.get(service)?.get(providerName) as T | null;
|
||||
}
|
||||
function getUniProviders(service: string): UniProvider[] {
|
||||
const result: UniProvider[] = [];
|
||||
providers.get(service)?.forEach((provider)=>{
|
||||
result.push(provider);
|
||||
});
|
||||
return result;
|
||||
}
|
||||
function registerUniProvider<T extends UniProvider>(service: string, providerName: string, provider: T) {
|
||||
if (!providers.has(service)) {
|
||||
providers.set(service, new Map());
|
||||
}
|
||||
providers.get(service)?.set(providerName, provider);
|
||||
}
|
||||
type Anything = Object | null | undefined;
|
||||
type NullType = null | undefined;
|
||||
type FormatArgsValueType = Function | string | number | boolean;
|
||||
interface AsyncApiSuccessResult {
|
||||
}
|
||||
interface AsyncApiResult {
|
||||
}
|
||||
interface ApiError {
|
||||
errMsg?: string | null;
|
||||
errCode?: number | null;
|
||||
}
|
||||
interface ApiExecutor<K> {
|
||||
resolve: (res?: K | void) => void;
|
||||
reject: (errMsg?: string, errRes?: ApiError) => void;
|
||||
}
|
||||
interface ProtocolOptions {
|
||||
name?: string | null;
|
||||
type?: string | null;
|
||||
required?: boolean | null;
|
||||
validator?: (value: Object) => boolean | undefined | string;
|
||||
}
|
||||
interface ApiOptions<T> {
|
||||
beforeInvoke?: (args: Object) => boolean | void | string;
|
||||
beforeAll?: (res: Object) => void;
|
||||
beforeSuccess?: (res: Object, args: T) => void;
|
||||
formatArgs?: Map<string, FormatArgsValueType>;
|
||||
}
|
||||
interface AsyncMethodOptionLike {
|
||||
success?: Function | null;
|
||||
}
|
||||
const TYPE_MAP = new Map<string, Object>([
|
||||
[
|
||||
'string',
|
||||
String
|
||||
],
|
||||
[
|
||||
'number',
|
||||
Number
|
||||
],
|
||||
[
|
||||
'boolean',
|
||||
Boolean
|
||||
],
|
||||
[
|
||||
'array',
|
||||
Array
|
||||
],
|
||||
[
|
||||
'object',
|
||||
Object
|
||||
]
|
||||
]);
|
||||
function getPropType(type: string | NullType): Anything {
|
||||
if (!type) {
|
||||
return;
|
||||
}
|
||||
return TYPE_MAP.get(type);
|
||||
}
|
||||
function buildProtocol(protocol: Map<string, ProtocolOptions> | null = null) {
|
||||
const originalProtocol = {} as Record<string, Object>;
|
||||
protocol?.forEach((value, key)=>{
|
||||
const protocol = originalProtocol[key] = {} as Record<string, Anything>;
|
||||
protocol.name = value.name;
|
||||
protocol.type = getPropType(value.type);
|
||||
protocol.required = value.required;
|
||||
protocol.validator = value.validator;
|
||||
});
|
||||
return originalProtocol;
|
||||
}
|
||||
function buildOptions(options: ApiOptions<AsyncMethodOptionLike> | null = null) {
|
||||
const originalFormatArgs = {} as Record<string, FormatArgsValueType>;
|
||||
const originalOptions = {} as Record<string, Anything>;
|
||||
if (options) {
|
||||
if (options.formatArgs) {
|
||||
options.formatArgs.forEach((value, key)=>{
|
||||
originalFormatArgs[key] = value;
|
||||
});
|
||||
}
|
||||
originalOptions.beforeInvoke = options.beforeInvoke;
|
||||
originalOptions.beforeAll = options.beforeAll;
|
||||
originalOptions.beforeSuccess = options.beforeSuccess;
|
||||
originalOptions.formatArgs = originalFormatArgs;
|
||||
}
|
||||
return originalOptions;
|
||||
}
|
||||
function defineAsyncApi<T extends AsyncMethodOptionLike, K>(name: string, fn: (options: T, res: ApiExecutor<K>) => void, protocol: Map<string, ProtocolOptions> | null = null, options: ApiOptions<T> | null = null): Function {
|
||||
const originalProtocol = buildProtocol(protocol);
|
||||
const originalOptions = buildOptions(options as ApiOptions<AsyncMethodOptionLike>);
|
||||
return originalDefineAsyncApi(name, fn, originalProtocol, originalOptions);
|
||||
}
|
||||
function defineTaskApi<T, K, TASK>(name: string, fn: (options: T, res: ApiExecutor<K>) => TASK, protocol: Map<string, ProtocolOptions>, options: ApiOptions<T>): Object {
|
||||
const originalProtocol = buildProtocol(protocol);
|
||||
const originalOptions = buildOptions(options as ApiOptions<AsyncMethodOptionLike>);
|
||||
return originalDefineTaskApi(name, fn, originalProtocol, originalOptions);
|
||||
}
|
||||
function defineSyncApi<K>(name: string, fn: Function, protocol: Map<string, ProtocolOptions> | null = null, options: ApiOptions<Object> | null = null): (...args: Object[]) => K {
|
||||
const originalProtocol = buildProtocol(protocol);
|
||||
const originalOptions = buildOptions(options as ApiOptions<AsyncMethodOptionLike>);
|
||||
return originalDefineSyncApi(name, fn, originalProtocol, originalOptions);
|
||||
}
|
||||
function defineOnApi<T>(name: string, fn: () => void, options: ApiOptions<T> | null = null): Function {
|
||||
const originalOptions = buildOptions(options as ApiOptions<AsyncMethodOptionLike>);
|
||||
return originalDefineOnApi(name, fn, originalOptions);
|
||||
}
|
||||
function defineOffApi<T>(name: string, fn: () => void, options: ApiOptions<T> | null = null): Function {
|
||||
const originalOptions = buildOptions(options as ApiOptions<AsyncMethodOptionLike>);
|
||||
return originalDefineOffApi(name, fn, originalOptions);
|
||||
}
|
||||
export { UniProvider as UniProvider, getUniProvider as getUniProvider, getUniProviders as getUniProviders, registerUniProvider as registerUniProvider };
|
||||
export { AsyncApiSuccessResult as AsyncApiSuccessResult };
|
||||
export { AsyncApiResult as AsyncApiResult };
|
||||
export { ApiError as ApiError };
|
||||
export { ApiExecutor as ApiExecutor };
|
||||
export { ProtocolOptions as ProtocolOptions };
|
||||
export { ApiOptions as ApiOptions };
|
||||
export { defineAsyncApi as defineAsyncApi };
|
||||
export { defineTaskApi as defineTaskApi };
|
||||
export { defineSyncApi as defineSyncApi };
|
||||
export { defineOnApi as defineOnApi };
|
||||
export { defineOffApi as defineOffApi };
|
||||
+26711
File diff suppressed because it is too large
Load Diff
+10585
File diff suppressed because it is too large
Load Diff
+615
@@ -0,0 +1,615 @@
|
||||
import { isArray, hasOwn, isString, isPlainObject, isObject, toRawType, capitalize, makeMap, isFunction, isPromise, extend, remove } from '@vue/shared';
|
||||
|
||||
function validateProtocolFail(name, msg) {
|
||||
console.warn(`${name}: ${msg}`);
|
||||
}
|
||||
function validateProtocol(name, data, protocol, onFail) {
|
||||
if (!onFail) {
|
||||
onFail = validateProtocolFail;
|
||||
}
|
||||
for (const key in protocol) {
|
||||
const errMsg = validateProp(key, data[key], protocol[key], !hasOwn(data, key));
|
||||
if (isString(errMsg)) {
|
||||
onFail(name, errMsg);
|
||||
}
|
||||
}
|
||||
}
|
||||
function validateProtocols(name, args, protocol, onFail) {
|
||||
if (!protocol) {
|
||||
return;
|
||||
}
|
||||
if (!isArray(protocol)) {
|
||||
return validateProtocol(name, args[0] || Object.create(null), protocol, onFail);
|
||||
}
|
||||
const len = protocol.length;
|
||||
const argsLen = args.length;
|
||||
for (let i = 0; i < len; i++) {
|
||||
const opts = protocol[i];
|
||||
const data = Object.create(null);
|
||||
if (argsLen > i) {
|
||||
data[opts.name] = args[i];
|
||||
}
|
||||
validateProtocol(name, data, { [opts.name]: opts }, onFail);
|
||||
}
|
||||
}
|
||||
function validateProp(name, value, prop, isAbsent) {
|
||||
if (!isPlainObject(prop)) {
|
||||
prop = { type: prop };
|
||||
}
|
||||
const { type, required, validator } = prop;
|
||||
// required!
|
||||
if (required && isAbsent) {
|
||||
return 'Missing required args: "' + name + '"';
|
||||
}
|
||||
// missing but optional
|
||||
if (value == null && !required) {
|
||||
return;
|
||||
}
|
||||
// type check
|
||||
if (type != null) {
|
||||
let isValid = false;
|
||||
const types = isArray(type) ? type : [type];
|
||||
const expectedTypes = [];
|
||||
// value is valid as long as one of the specified types match
|
||||
for (let i = 0; i < types.length && !isValid; i++) {
|
||||
const { valid, expectedType } = assertType(value, types[i]);
|
||||
expectedTypes.push(expectedType || '');
|
||||
isValid = valid;
|
||||
}
|
||||
if (!isValid) {
|
||||
return getInvalidTypeMessage(name, value, expectedTypes);
|
||||
}
|
||||
}
|
||||
// custom validator
|
||||
if (validator) {
|
||||
return validator(value);
|
||||
}
|
||||
}
|
||||
const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
|
||||
function assertType(value, type) {
|
||||
let valid;
|
||||
const expectedType = getType(type);
|
||||
if (isSimpleType(expectedType)) {
|
||||
const t = typeof value;
|
||||
valid = t === expectedType.toLowerCase();
|
||||
// for primitive wrapper objects
|
||||
if (!valid && t === 'object') {
|
||||
valid = value instanceof type;
|
||||
}
|
||||
}
|
||||
else if (expectedType === 'Object') {
|
||||
valid = isObject(value);
|
||||
}
|
||||
else if (expectedType === 'Array') {
|
||||
valid = isArray(value);
|
||||
}
|
||||
else {
|
||||
if (__PLATFORM__ === 'app') {
|
||||
// App平台ArrayBuffer等参数跨实例传输,无法通过 instanceof 识别
|
||||
valid = value instanceof type || toRawType(value) === getType(type);
|
||||
}
|
||||
else {
|
||||
valid = value instanceof type;
|
||||
}
|
||||
}
|
||||
return {
|
||||
valid,
|
||||
expectedType,
|
||||
};
|
||||
}
|
||||
function getInvalidTypeMessage(name, value, expectedTypes) {
|
||||
let message = `Invalid args: type check failed for args "${name}".` +
|
||||
` Expected ${expectedTypes.map(capitalize).join(', ')}`;
|
||||
const expectedType = expectedTypes[0];
|
||||
const receivedType = toRawType(value);
|
||||
const expectedValue = styleValue(value, expectedType);
|
||||
const receivedValue = styleValue(value, receivedType);
|
||||
// check if we need to specify expected value
|
||||
if (expectedTypes.length === 1 &&
|
||||
isExplicable(expectedType) &&
|
||||
!isBoolean(expectedType, receivedType)) {
|
||||
message += ` with value ${expectedValue}`;
|
||||
}
|
||||
message += `, got ${receivedType} `;
|
||||
// check if we need to specify received value
|
||||
if (isExplicable(receivedType)) {
|
||||
message += `with value ${receivedValue}.`;
|
||||
}
|
||||
return message;
|
||||
}
|
||||
function getType(ctor) {
|
||||
const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
|
||||
return match ? match[1] : '';
|
||||
}
|
||||
function styleValue(value, type) {
|
||||
if (type === 'String') {
|
||||
return `"${value}"`;
|
||||
}
|
||||
else if (type === 'Number') {
|
||||
return `${Number(value)}`;
|
||||
}
|
||||
else {
|
||||
return `${value}`;
|
||||
}
|
||||
}
|
||||
function isExplicable(type) {
|
||||
const explicitTypes = ['string', 'number', 'boolean'];
|
||||
return explicitTypes.some((elem) => type.toLowerCase() === elem);
|
||||
}
|
||||
function isBoolean(...args) {
|
||||
return args.some((elem) => elem.toLowerCase() === 'boolean');
|
||||
}
|
||||
|
||||
function tryCatch(fn) {
|
||||
return function () {
|
||||
try {
|
||||
return fn.apply(fn, arguments);
|
||||
}
|
||||
catch (e) {
|
||||
// TODO
|
||||
console.error(e);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
let invokeCallbackId = 1;
|
||||
const invokeCallbacks = {};
|
||||
function addInvokeCallback(id, name, callback, keepAlive = false) {
|
||||
invokeCallbacks[id] = {
|
||||
name,
|
||||
keepAlive,
|
||||
callback,
|
||||
};
|
||||
return id;
|
||||
}
|
||||
// onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
|
||||
function invokeCallback(id, res, extras) {
|
||||
if (typeof id === 'number') {
|
||||
const opts = invokeCallbacks[id];
|
||||
if (opts) {
|
||||
if (!opts.keepAlive) {
|
||||
delete invokeCallbacks[id];
|
||||
}
|
||||
return opts.callback(res, extras);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
function findInvokeCallbackByName(name) {
|
||||
for (const key in invokeCallbacks) {
|
||||
if (invokeCallbacks[key].name === name) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function removeKeepAliveApiCallback(name, callback) {
|
||||
for (const key in invokeCallbacks) {
|
||||
const item = invokeCallbacks[key];
|
||||
if (item.callback === callback && item.name === name) {
|
||||
delete invokeCallbacks[key];
|
||||
}
|
||||
}
|
||||
}
|
||||
function offKeepAliveApiCallback(name) {
|
||||
UniServiceJSBridge.off('api.' + name);
|
||||
}
|
||||
function onKeepAliveApiCallback(name) {
|
||||
UniServiceJSBridge.on('api.' + name, (res) => {
|
||||
for (const key in invokeCallbacks) {
|
||||
const opts = invokeCallbacks[key];
|
||||
if (opts.name === name) {
|
||||
opts.callback(res);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
function createKeepAliveApiCallback(name, callback) {
|
||||
return addInvokeCallback(invokeCallbackId++, name, callback, true);
|
||||
}
|
||||
const API_SUCCESS = 'success';
|
||||
const API_FAIL = 'fail';
|
||||
const API_COMPLETE = 'complete';
|
||||
function getApiCallbacks(args) {
|
||||
const apiCallbacks = {};
|
||||
for (const name in args) {
|
||||
const fn = args[name];
|
||||
if (isFunction(fn)) {
|
||||
apiCallbacks[name] = tryCatch(fn);
|
||||
delete args[name];
|
||||
}
|
||||
}
|
||||
return apiCallbacks;
|
||||
}
|
||||
function normalizeErrMsg(errMsg, name) {
|
||||
if (!errMsg || errMsg.indexOf(':fail') === -1) {
|
||||
return name + ':ok';
|
||||
}
|
||||
return name + errMsg.substring(errMsg.indexOf(':fail'));
|
||||
}
|
||||
function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
|
||||
if (!isPlainObject(args)) {
|
||||
args = {};
|
||||
}
|
||||
const { success, fail, complete } = getApiCallbacks(args);
|
||||
const hasSuccess = isFunction(success);
|
||||
const hasFail = isFunction(fail);
|
||||
const hasComplete = isFunction(complete);
|
||||
const callbackId = invokeCallbackId++;
|
||||
addInvokeCallback(callbackId, name, (res) => {
|
||||
res = res || {};
|
||||
res.errMsg = normalizeErrMsg(res.errMsg, name);
|
||||
isFunction(beforeAll) && beforeAll(res);
|
||||
if (res.errMsg === name + ':ok') {
|
||||
isFunction(beforeSuccess) && beforeSuccess(res, args);
|
||||
hasSuccess && success(res);
|
||||
}
|
||||
else {
|
||||
hasFail && fail(res);
|
||||
}
|
||||
hasComplete && complete(res);
|
||||
});
|
||||
return callbackId;
|
||||
}
|
||||
|
||||
const HOOK_SUCCESS = 'success';
|
||||
const HOOK_FAIL = 'fail';
|
||||
const HOOK_COMPLETE = 'complete';
|
||||
const globalInterceptors = {};
|
||||
const scopedInterceptors = {};
|
||||
function wrapperHook(hook, params) {
|
||||
return function (data) {
|
||||
return hook(data, params) || data;
|
||||
};
|
||||
}
|
||||
function queue(hooks, data, params) {
|
||||
let promise = false;
|
||||
for (let i = 0; i < hooks.length; i++) {
|
||||
const hook = hooks[i];
|
||||
if (promise) {
|
||||
promise = Promise.resolve(wrapperHook(hook, params));
|
||||
}
|
||||
else {
|
||||
const res = hook(data, params);
|
||||
if (isPromise(res)) {
|
||||
promise = Promise.resolve(res);
|
||||
}
|
||||
if (res === false) {
|
||||
return {
|
||||
then() { },
|
||||
catch() { },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return (promise || {
|
||||
then(callback) {
|
||||
return callback(data);
|
||||
},
|
||||
catch() { },
|
||||
});
|
||||
}
|
||||
function wrapperOptions(interceptors, options = {}) {
|
||||
[HOOK_SUCCESS, HOOK_FAIL, HOOK_COMPLETE].forEach((name) => {
|
||||
const hooks = interceptors[name];
|
||||
if (!isArray(hooks)) {
|
||||
return;
|
||||
}
|
||||
const oldCallback = options[name];
|
||||
options[name] = function callbackInterceptor(res) {
|
||||
queue(hooks, res, options).then((res) => {
|
||||
return (isFunction(oldCallback) && oldCallback(res)) || res;
|
||||
});
|
||||
};
|
||||
});
|
||||
return options;
|
||||
}
|
||||
function wrapperReturnValue(method, returnValue) {
|
||||
const returnValueHooks = [];
|
||||
if (isArray(globalInterceptors.returnValue)) {
|
||||
returnValueHooks.push(...globalInterceptors.returnValue);
|
||||
}
|
||||
const interceptor = scopedInterceptors[method];
|
||||
if (interceptor && isArray(interceptor.returnValue)) {
|
||||
returnValueHooks.push(...interceptor.returnValue);
|
||||
}
|
||||
returnValueHooks.forEach((hook) => {
|
||||
returnValue = hook(returnValue) || returnValue;
|
||||
});
|
||||
return returnValue;
|
||||
}
|
||||
function getApiInterceptorHooks(method) {
|
||||
const interceptor = Object.create(null);
|
||||
Object.keys(globalInterceptors).forEach((hook) => {
|
||||
if (hook !== 'returnValue') {
|
||||
interceptor[hook] = globalInterceptors[hook].slice();
|
||||
}
|
||||
});
|
||||
const scopedInterceptor = scopedInterceptors[method];
|
||||
if (scopedInterceptor) {
|
||||
Object.keys(scopedInterceptor).forEach((hook) => {
|
||||
if (hook !== 'returnValue') {
|
||||
interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
|
||||
}
|
||||
});
|
||||
}
|
||||
return interceptor;
|
||||
}
|
||||
function invokeApi(method, api, options, params) {
|
||||
const interceptor = getApiInterceptorHooks(method);
|
||||
if (interceptor && Object.keys(interceptor).length) {
|
||||
if (isArray(interceptor.invoke)) {
|
||||
const res = queue(interceptor.invoke, options);
|
||||
return res.then((options) => {
|
||||
// 重新访问 getApiInterceptorHooks, 允许 invoke 中再次调用 addInterceptor,removeInterceptor
|
||||
return api(wrapperOptions(getApiInterceptorHooks(method), options), ...params);
|
||||
});
|
||||
}
|
||||
else {
|
||||
return api(wrapperOptions(interceptor, options), ...params);
|
||||
}
|
||||
}
|
||||
return api(options, ...params);
|
||||
}
|
||||
|
||||
function hasCallback(args) {
|
||||
if (isPlainObject(args) &&
|
||||
[API_SUCCESS, API_FAIL, API_COMPLETE].find((cb) => isFunction(args[cb]))) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
function handlePromise(promise) {
|
||||
// if (__UNI_FEATURE_PROMISE__) {
|
||||
// return promise
|
||||
// .then((data) => {
|
||||
// return [null, data]
|
||||
// })
|
||||
// .catch((err) => [err])
|
||||
// }
|
||||
return promise;
|
||||
}
|
||||
function promisify(name, fn) {
|
||||
return (args = {}, ...rest) => {
|
||||
if (hasCallback(args)) {
|
||||
return wrapperReturnValue(name, invokeApi(name, fn, args, rest));
|
||||
}
|
||||
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
|
||||
invokeApi(name, fn, extend(args, { success: resolve, fail: reject }), rest);
|
||||
})));
|
||||
};
|
||||
}
|
||||
|
||||
function formatApiArgs(args, options) {
|
||||
const params = args[0];
|
||||
if (!options ||
|
||||
!options.formatArgs ||
|
||||
(!isPlainObject(options.formatArgs) && isPlainObject(params))) {
|
||||
return;
|
||||
}
|
||||
const formatArgs = options.formatArgs;
|
||||
const keys = Object.keys(formatArgs);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const name = keys[i];
|
||||
const formatterOrDefaultValue = formatArgs[name];
|
||||
if (isFunction(formatterOrDefaultValue)) {
|
||||
const errMsg = formatterOrDefaultValue(args[0][name], params);
|
||||
if (isString(errMsg)) {
|
||||
return errMsg;
|
||||
}
|
||||
}
|
||||
else {
|
||||
// defaultValue
|
||||
if (!hasOwn(params, name)) {
|
||||
params[name] = formatterOrDefaultValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
function invokeSuccess(id, name, res) {
|
||||
const result = {
|
||||
errMsg: name + ':ok',
|
||||
};
|
||||
{
|
||||
result.errSubject = name;
|
||||
}
|
||||
return invokeCallback(id, extend((res || {}), result));
|
||||
}
|
||||
function invokeFail(id, name, errMsg, errRes = {}) {
|
||||
const errMsgPrefix = name + ':fail';
|
||||
let apiErrMsg = '';
|
||||
if (!errMsg) {
|
||||
apiErrMsg = errMsgPrefix;
|
||||
}
|
||||
else if (errMsg.indexOf(errMsgPrefix) === 0) {
|
||||
apiErrMsg = errMsg;
|
||||
}
|
||||
else {
|
||||
apiErrMsg = errMsgPrefix + ' ' + errMsg;
|
||||
}
|
||||
let res = extend({ errMsg: apiErrMsg }, errRes);
|
||||
{
|
||||
if (typeof UniError !== 'undefined') {
|
||||
res =
|
||||
typeof errRes.errCode !== 'undefined'
|
||||
? new UniError(name, errRes.errCode, apiErrMsg)
|
||||
: new UniError(apiErrMsg, errRes);
|
||||
}
|
||||
}
|
||||
return invokeCallback(id, res);
|
||||
}
|
||||
function beforeInvokeApi(name, args, protocol, options) {
|
||||
if ((process.env.NODE_ENV !== 'production')) {
|
||||
validateProtocols(name, args, protocol);
|
||||
}
|
||||
if (options && options.beforeInvoke) {
|
||||
const errMsg = options.beforeInvoke(args);
|
||||
if (isString(errMsg)) {
|
||||
return errMsg;
|
||||
}
|
||||
}
|
||||
const errMsg = formatApiArgs(args, options);
|
||||
if (errMsg) {
|
||||
return errMsg;
|
||||
}
|
||||
}
|
||||
function checkCallback(callback) {
|
||||
if (!isFunction(callback)) {
|
||||
throw new Error('Invalid args: type check failed for args "callback". Expected Function');
|
||||
}
|
||||
}
|
||||
function wrapperOnApi(name, fn, options) {
|
||||
return (callback) => {
|
||||
checkCallback(callback);
|
||||
const errMsg = beforeInvokeApi(name, [callback], undefined, options);
|
||||
if (errMsg) {
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
// 是否是首次调用on,如果是首次,需要初始化onMethod监听
|
||||
const isFirstInvokeOnApi = !findInvokeCallbackByName(name);
|
||||
createKeepAliveApiCallback(name, callback);
|
||||
if (isFirstInvokeOnApi) {
|
||||
onKeepAliveApiCallback(name);
|
||||
fn();
|
||||
}
|
||||
};
|
||||
}
|
||||
function wrapperOffApi(name, fn, options) {
|
||||
return (callback) => {
|
||||
checkCallback(callback);
|
||||
const errMsg = beforeInvokeApi(name, [callback], undefined, options);
|
||||
if (errMsg) {
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
name = name.replace('off', 'on');
|
||||
removeKeepAliveApiCallback(name, callback);
|
||||
// 是否还存在监听,若已不存在,则移除onMethod监听
|
||||
const hasInvokeOnApi = findInvokeCallbackByName(name);
|
||||
if (!hasInvokeOnApi) {
|
||||
offKeepAliveApiCallback(name);
|
||||
fn();
|
||||
}
|
||||
};
|
||||
}
|
||||
function parseErrMsg(errMsg) {
|
||||
if (!errMsg || isString(errMsg)) {
|
||||
return errMsg;
|
||||
}
|
||||
if (errMsg.stack) {
|
||||
return errMsg.message;
|
||||
}
|
||||
return errMsg;
|
||||
}
|
||||
function wrapperTaskApi(name, fn, protocol, options) {
|
||||
return (args) => {
|
||||
const id = createAsyncApiCallback(name, args, options);
|
||||
const errMsg = beforeInvokeApi(name, [args], protocol, options);
|
||||
if (errMsg) {
|
||||
return invokeFail(id, name, errMsg);
|
||||
}
|
||||
return fn(args, {
|
||||
resolve: (res) => invokeSuccess(id, name, res),
|
||||
reject: (errMsg, errRes) => invokeFail(id, name, parseErrMsg(errMsg), errRes),
|
||||
});
|
||||
};
|
||||
}
|
||||
function wrapperSyncApi(name, fn, protocol, options) {
|
||||
return (...args) => {
|
||||
const errMsg = beforeInvokeApi(name, args, protocol, options);
|
||||
if (errMsg) {
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
return fn.apply(null, args);
|
||||
};
|
||||
}
|
||||
function wrapperAsyncApi(name, fn, protocol, options) {
|
||||
return wrapperTaskApi(name, fn, protocol, options);
|
||||
}
|
||||
function defineOnApi(name, fn, options) {
|
||||
return wrapperOnApi(name, fn, options);
|
||||
}
|
||||
function defineOffApi(name, fn, options) {
|
||||
return wrapperOffApi(name, fn, options);
|
||||
}
|
||||
function defineTaskApi(name, fn, protocol, options) {
|
||||
return promisify(name, wrapperTaskApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
|
||||
}
|
||||
function defineSyncApi(name, fn, protocol, options) {
|
||||
return wrapperSyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
|
||||
}
|
||||
function defineAsyncApi(name, fn, protocol, options) {
|
||||
return promisify(name, wrapperAsyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
|
||||
}
|
||||
|
||||
const API_ADD_INTERCEPTOR = 'addInterceptor';
|
||||
const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
|
||||
const AddInterceptorProtocol = [
|
||||
{
|
||||
name: 'method',
|
||||
type: [String, Object],
|
||||
required: true,
|
||||
},
|
||||
];
|
||||
const RemoveInterceptorProtocol = AddInterceptorProtocol;
|
||||
|
||||
function mergeInterceptorHook(interceptors, interceptor) {
|
||||
Object.keys(interceptor).forEach((hook) => {
|
||||
if (isFunction(interceptor[hook])) {
|
||||
interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]);
|
||||
}
|
||||
});
|
||||
}
|
||||
function removeInterceptorHook(interceptors, interceptor) {
|
||||
if (!interceptors || !interceptor) {
|
||||
return;
|
||||
}
|
||||
Object.keys(interceptor).forEach((name) => {
|
||||
const hooks = interceptors[name];
|
||||
const hook = interceptor[name];
|
||||
if (isArray(hooks) && isFunction(hook)) {
|
||||
remove(hooks, hook);
|
||||
}
|
||||
});
|
||||
}
|
||||
function mergeHook(parentVal, childVal) {
|
||||
const res = childVal
|
||||
? parentVal
|
||||
? parentVal.concat(childVal)
|
||||
: isArray(childVal)
|
||||
? childVal
|
||||
: [childVal]
|
||||
: parentVal;
|
||||
return res ? dedupeHooks(res) : res;
|
||||
}
|
||||
function dedupeHooks(hooks) {
|
||||
const res = [];
|
||||
for (let i = 0; i < hooks.length; i++) {
|
||||
if (res.indexOf(hooks[i]) === -1) {
|
||||
res.push(hooks[i]);
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
|
||||
if (isString(method) && isPlainObject(interceptor)) {
|
||||
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
|
||||
}
|
||||
else if (isPlainObject(method)) {
|
||||
mergeInterceptorHook(globalInterceptors, method);
|
||||
}
|
||||
}, AddInterceptorProtocol);
|
||||
const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
|
||||
if (isString(method)) {
|
||||
if (isPlainObject(interceptor)) {
|
||||
removeInterceptorHook(scopedInterceptors[method], interceptor);
|
||||
}
|
||||
else {
|
||||
delete scopedInterceptors[method];
|
||||
}
|
||||
}
|
||||
else if (isPlainObject(method)) {
|
||||
removeInterceptorHook(globalInterceptors, method);
|
||||
}
|
||||
}, RemoveInterceptorProtocol);
|
||||
|
||||
export { addInterceptor, defineAsyncApi, defineOffApi, defineOnApi, defineSyncApi, defineTaskApi, removeInterceptor };
|
||||
+557
@@ -0,0 +1,557 @@
|
||||
'use strict';
|
||||
|
||||
Object.defineProperty(exports, '__esModule', { value: true });
|
||||
|
||||
var appVite = require('@dcloudio/uni-app-vite');
|
||||
var uniAppUts = require('@dcloudio/uni-app-uts');
|
||||
var path = require('path');
|
||||
var uniCliShared = require('@dcloudio/uni-cli-shared');
|
||||
|
||||
function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
|
||||
|
||||
var appVite__default = /*#__PURE__*/_interopDefault(appVite);
|
||||
var path__default = /*#__PURE__*/_interopDefault(path);
|
||||
|
||||
var ExternalModuls = [
|
||||
{
|
||||
type: "extapi",
|
||||
plugin: "uni-facialVerify",
|
||||
apis: [
|
||||
"startFacialRecognitionVerify",
|
||||
"getFacialRecognitionMetaInfo"
|
||||
],
|
||||
version: "1.0.2"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-getLocation-system",
|
||||
provider: "system",
|
||||
service: "location",
|
||||
version: "1.0.0"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-oauth-huawei",
|
||||
provider: "huawei",
|
||||
service: "oauth",
|
||||
version: "1.0.2"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-payment-alipay",
|
||||
provider: "alipay",
|
||||
service: "payment",
|
||||
version: "1.0.2"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-payment-huawei",
|
||||
provider: "huawei",
|
||||
service: "payment",
|
||||
version: "1.0.0"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-payment-wxpay",
|
||||
provider: "wxpay",
|
||||
service: "payment",
|
||||
version: "1.0.0"
|
||||
},
|
||||
{
|
||||
type: "extapi",
|
||||
plugin: "uni-push",
|
||||
apis: [
|
||||
"getPushClientId",
|
||||
"onPushMessage",
|
||||
"offPushMessage",
|
||||
"createPushMessage",
|
||||
"setAppBadgeNumber"
|
||||
],
|
||||
version: "1.0.2"
|
||||
}
|
||||
];
|
||||
|
||||
var ExternalModulesX = [
|
||||
{
|
||||
type: "extapi",
|
||||
plugin: "uni-facialVerify",
|
||||
apis: [
|
||||
"startFacialRecognitionVerify",
|
||||
"getFacialRecognitionMetaInfo"
|
||||
],
|
||||
version: "1.0.2"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-getLocation-system",
|
||||
provider: "system",
|
||||
service: "location",
|
||||
version: "1.0.0"
|
||||
},
|
||||
{
|
||||
type: "extapi",
|
||||
plugin: "uni-map-tencent",
|
||||
apis: [
|
||||
"createMapContext"
|
||||
],
|
||||
version: "1.0.0"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-oauth-huawei",
|
||||
provider: "huawei",
|
||||
service: "oauth",
|
||||
version: "1.0.2"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-payment-alipay",
|
||||
provider: "alipay",
|
||||
service: "payment",
|
||||
version: "1.0.2"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-payment-huawei",
|
||||
provider: "huawei",
|
||||
service: "payment",
|
||||
version: "1.0.0"
|
||||
},
|
||||
{
|
||||
type: "provider",
|
||||
plugin: "uni-payment-wxpay",
|
||||
provider: "wxpay",
|
||||
service: "payment",
|
||||
version: "1.0.0"
|
||||
},
|
||||
{
|
||||
type: "extapi",
|
||||
plugin: "uni-push",
|
||||
apis: [
|
||||
"getPushClientId",
|
||||
"onPushMessage",
|
||||
"offPushMessage",
|
||||
"createPushMessage",
|
||||
"setAppBadgeNumber"
|
||||
],
|
||||
version: "1.0.2"
|
||||
}
|
||||
];
|
||||
|
||||
/**
|
||||
* uni-app内部extapi发行到ohpm的uni_modules组织下的包列表
|
||||
* 注意此列表会同时被框架编译器和用户项目编译器引用
|
||||
*/
|
||||
// type ExternalModuleSubType = 'customElements' | 'components' | 'pages' | 'utssdk'
|
||||
// TODO 未来component类型的provider需要重构,比如uni-map-tencent需要依赖内置基础模块uni-map,先基于现状实现。
|
||||
const ComponentsWithProvider = [];
|
||||
const ComponentsWithProviderX = ['uni-map'];
|
||||
|
||||
const isX = process.env.UNI_APP_X === 'true';
|
||||
const StandaloneExtApis = isX ? ExternalModulesX : ExternalModuls;
|
||||
const Providers = StandaloneExtApis.filter((item) => item.type === 'provider');
|
||||
const ComponentWithProviderList = isX
|
||||
? ComponentsWithProviderX
|
||||
: ComponentsWithProvider;
|
||||
if (isX) {
|
||||
Providers.push({
|
||||
type: 'provider',
|
||||
plugin: 'uni-map',
|
||||
provider: 'tencent',
|
||||
service: 'map',
|
||||
version: '1.0.0',
|
||||
});
|
||||
}
|
||||
const ApiModules = StandaloneExtApis.filter((item) => item.type === 'extapi');
|
||||
const commandGlobals = {
|
||||
vue: 'Vue',
|
||||
'@vue/shared': 'uni.VueShared',
|
||||
};
|
||||
const harmonyGlobals = [
|
||||
/^@ohos\./,
|
||||
/^@kit\./,
|
||||
/^@hms\./,
|
||||
/^@arkts\./,
|
||||
/^@system\./,
|
||||
'@ohos/hypium',
|
||||
'@ohos/hamock',
|
||||
];
|
||||
function isHarmonyGlobal(id) {
|
||||
return harmonyGlobals.some((harmonyGlobal) => typeof harmonyGlobal === 'string'
|
||||
? harmonyGlobal === id
|
||||
: harmonyGlobal.test(id));
|
||||
}
|
||||
function generateHarmonyImportSpecifier(id) {
|
||||
return id.replace(/([@\/\.])/g, function (_, $1) {
|
||||
switch ($1) {
|
||||
case '.':
|
||||
return '_';
|
||||
case '/':
|
||||
return '__';
|
||||
default:
|
||||
return '';
|
||||
}
|
||||
});
|
||||
}
|
||||
function generateHarName(moduleName) {
|
||||
return moduleName.replace(/@/g, '').replace(/\//g, '__').replace(/-/g, '_');
|
||||
}
|
||||
function generateHarmonyImportExternalCode(harmonyPackageNames) {
|
||||
return harmonyPackageNames
|
||||
.filter((harmonyPackageName) => isHarmonyGlobal(harmonyPackageName))
|
||||
.map((harmonyPackageName) => `import ${generateHarmonyImportSpecifier(harmonyPackageName)} from '${harmonyPackageName}';`)
|
||||
.join('');
|
||||
}
|
||||
function uniAppHarmonyPlugin() {
|
||||
return {
|
||||
name: 'uni:app-harmony',
|
||||
apply: 'build',
|
||||
config() {
|
||||
return {
|
||||
build: {
|
||||
rollupOptions: {
|
||||
external: [...Object.keys(commandGlobals), ...harmonyGlobals],
|
||||
output: {
|
||||
globals: function (id) {
|
||||
if (id.startsWith('@kit.')) {
|
||||
console.warn('@kit开头的包无法在页面或组件内正常使用,请改用其他方式引用,或使用uts插件引用。');
|
||||
}
|
||||
return (commandGlobals[id] ||
|
||||
(isHarmonyGlobal(id)
|
||||
? generateHarmonyImportSpecifier(id)
|
||||
: ''));
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
async generateBundle(_, bundle) {
|
||||
const utsExtApis = new Set();
|
||||
const utsPlugins = uniCliShared.getCurrentCompiledUTSPlugins();
|
||||
const utsProviders = uniCliShared.getCurrentCompiledUTSProviders();
|
||||
// utsPlugins.difference(utsProviders)
|
||||
utsPlugins.forEach((plugin) => {
|
||||
if (utsProviders.has(plugin)) {
|
||||
return;
|
||||
}
|
||||
utsExtApis.add(plugin);
|
||||
});
|
||||
if (uniCliShared.isNormalCompileTarget()) {
|
||||
// 此方法仅需要处理非provider
|
||||
genAppHarmonyUniModules(this, process.env.UNI_INPUT_DIR, utsExtApis);
|
||||
for (const key in bundle) {
|
||||
const serviceBundle = bundle[key];
|
||||
if (serviceBundle.code) {
|
||||
serviceBundle.code =
|
||||
generateHarmonyImportExternalCode(serviceBundle.imports) +
|
||||
serviceBundle.code;
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
async writeBundle() {
|
||||
if (!uniCliShared.isNormalCompileTarget()) {
|
||||
return;
|
||||
}
|
||||
// 1.0 特有逻辑,x 上由其他插件完成
|
||||
if (process.env.UNI_APP_X !== 'true') {
|
||||
// x 上暂时编译所有uni ext api,不管代码里是否调用了
|
||||
await uniCliShared.buildUniExtApis();
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
/**
|
||||
* TODO 微信支付上线时,务必提醒相关同事统一使用wxpay,不要用weixin
|
||||
*/
|
||||
function getProviders(module, allProviders) {
|
||||
return allProviders.filter((item) => item.plugin.startsWith(module + '-'));
|
||||
}
|
||||
const DefaultModule = {
|
||||
// 'uni-getLocation': {
|
||||
// system: {},
|
||||
// },
|
||||
};
|
||||
function getManifestModules(inputDir) {
|
||||
const manifest = uniCliShared.parseManifestJsonOnce(inputDir);
|
||||
const modules = manifest?.[isX ? 'app' : 'app-harmony']?.distribute?.modules;
|
||||
const realModules = {};
|
||||
for (const moduleName in modules) {
|
||||
if (DefaultModule[moduleName]) {
|
||||
realModules[moduleName] = Object.assign({}, DefaultModule[moduleName], modules[moduleName]);
|
||||
}
|
||||
else {
|
||||
realModules[moduleName] = modules[moduleName];
|
||||
}
|
||||
}
|
||||
return realModules;
|
||||
}
|
||||
/**
|
||||
* 获取manifest.json中勾选的provider
|
||||
* 仅处理payment等参数内包含provider的api,地图模块不在此处理
|
||||
*/
|
||||
function getRelatedProviders(inputDir, allProviders) {
|
||||
const relatedProviders = [];
|
||||
const manifestModules = getManifestModules(inputDir);
|
||||
if (!manifestModules) {
|
||||
return relatedProviders;
|
||||
}
|
||||
for (const uniModule in manifestModules) {
|
||||
const providers = getProviders(uniModule, allProviders);
|
||||
if (!providers.length) {
|
||||
continue;
|
||||
}
|
||||
const manifestModule = manifestModules[uniModule];
|
||||
for (const name in manifestModule) {
|
||||
const providerConf = manifestModule[name];
|
||||
if (!providerConf) {
|
||||
continue;
|
||||
}
|
||||
if (!isHarmonyOSProvider(providerConf)) {
|
||||
continue;
|
||||
}
|
||||
const plugin = uniModule + '-' + name;
|
||||
const provider = providers.find((item) => item.plugin === plugin);
|
||||
if (!provider) {
|
||||
continue;
|
||||
}
|
||||
relatedProviders.push({
|
||||
service: provider.service,
|
||||
name,
|
||||
plugin: uniModule + '-' + name,
|
||||
});
|
||||
}
|
||||
}
|
||||
return relatedProviders;
|
||||
}
|
||||
function isHarmonyOSProvider(providerConf) {
|
||||
return (!providerConf.__platform__ ||
|
||||
!Array.isArray(providerConf.__platform__) ||
|
||||
providerConf.__platform__.includes('harmonyos'));
|
||||
}
|
||||
const ModuleAlias = {
|
||||
'uni-facialRecognitionVerify': 'uni-facialVerify',
|
||||
};
|
||||
// 获取uni_modules中的相关模块
|
||||
function getRelatedModules(inputDir) {
|
||||
const modules = [];
|
||||
const manifestModules = getManifestModules(inputDir);
|
||||
if (!manifestModules) {
|
||||
return modules;
|
||||
}
|
||||
for (let manifestModuleName in manifestModules) {
|
||||
if (ComponentWithProviderList.includes(manifestModuleName)) {
|
||||
const manifestModuleInfo = manifestModules[manifestModuleName];
|
||||
for (const provider in manifestModuleInfo) {
|
||||
const manifestPlugin = manifestModuleName + '-' + provider;
|
||||
const providerConf = manifestModuleInfo[provider];
|
||||
if (!isHarmonyOSProvider(providerConf)) {
|
||||
continue;
|
||||
}
|
||||
const apiModule = ApiModules.find((item) => item.plugin === manifestPlugin);
|
||||
if (apiModule) {
|
||||
modules.push(manifestPlugin);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (ModuleAlias[manifestModuleName]) {
|
||||
manifestModuleName = ModuleAlias[manifestModuleName];
|
||||
}
|
||||
const apiModule = ApiModules.find((item) => item.plugin === manifestModuleName);
|
||||
if (!apiModule) {
|
||||
continue;
|
||||
}
|
||||
modules.push(manifestModuleName);
|
||||
}
|
||||
return modules;
|
||||
}
|
||||
function genAppHarmonyUniModules(context, inputDir, utsPlugins) {
|
||||
const uniModulesDir = path__default.default.resolve(inputDir, 'uni_modules');
|
||||
const importCodes = [];
|
||||
const extApiCodes = [];
|
||||
const registerCodes = [];
|
||||
const projectDeps = [];
|
||||
Array.from(utsPlugins)
|
||||
.sort()
|
||||
.forEach((plugin) => {
|
||||
const injects = uniCliShared.parseUniExtApi(path__default.default.resolve(uniModulesDir, plugin), plugin, true, 'app-harmony', 'arkts');
|
||||
const harmonyPackageName = `@uni_modules/${plugin.toLowerCase()}`;
|
||||
if (injects) {
|
||||
Object.keys(injects).forEach((key) => {
|
||||
const inject = injects[key];
|
||||
if (Array.isArray(inject) && inject.length > 1) {
|
||||
const apiName = inject[1];
|
||||
importCodes.push(`import { ${inject[1]} } from '${harmonyPackageName}'`);
|
||||
extApiCodes.push(`uni.${apiName} = ${apiName}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
const ident = uniCliShared.camelize(plugin);
|
||||
importCodes.push(`import * as ${ident} from '${harmonyPackageName}'`);
|
||||
registerCodes.push(`uni.registerUTSPlugin('uni_modules/${plugin}', ${ident})`);
|
||||
projectDeps.push({
|
||||
moduleSpecifier: harmonyPackageName,
|
||||
plugin,
|
||||
source: 'local',
|
||||
});
|
||||
});
|
||||
const relatedModules = getRelatedModules(inputDir);
|
||||
relatedModules.sort().forEach((module) => {
|
||||
const harmonyModuleName = `@uni_modules/${module.toLowerCase()}`;
|
||||
if (utsPlugins.has(module)) ;
|
||||
else {
|
||||
const matchedStandaloneExtApi = StandaloneExtApis.find((item) => item.plugin === module);
|
||||
if (matchedStandaloneExtApi) {
|
||||
projectDeps.push({
|
||||
moduleSpecifier: harmonyModuleName,
|
||||
plugin: module,
|
||||
source: 'ohpm',
|
||||
version: '*',
|
||||
});
|
||||
matchedStandaloneExtApi.apis?.forEach((apiName) => {
|
||||
importCodes.push(`import { ${apiName} } from '${harmonyModuleName}'`);
|
||||
extApiCodes.push(`uni.${apiName} = ${apiName}`);
|
||||
});
|
||||
if (module.startsWith('uni-map-')) {
|
||||
// TODO 临时处理,后续需要内置基础uni-map模块并优化此问题
|
||||
importCodes.push(`import { UniMapElement } from '${harmonyModuleName}'`);
|
||||
extApiCodes.push(`globalThis.UniMapElement = UniMapElement`);
|
||||
const ident = uniCliShared.camelize(module);
|
||||
importCodes.push(`import * as ${ident} from '${harmonyModuleName}'`);
|
||||
registerCodes.push(`uni.registerUTSPlugin('uni_modules/${module}', ${ident})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
const importProviderCodes = [];
|
||||
const registerProviderCodes = [];
|
||||
const providers = uniCliShared.getUniExtApiProviderRegisters();
|
||||
const allProviders = providers.map((provider) => {
|
||||
return {
|
||||
service: provider.service,
|
||||
name: provider.name,
|
||||
moduleSpecifier: `@uni_modules/${provider.plugin.toLowerCase()}`,
|
||||
plugin: provider.plugin,
|
||||
source: 'local',
|
||||
version: undefined,
|
||||
};
|
||||
});
|
||||
Providers.forEach((provider) => {
|
||||
if (allProviders.find((item) => item.plugin === provider.plugin)) {
|
||||
return;
|
||||
}
|
||||
allProviders.push({
|
||||
service: provider.service,
|
||||
name: provider.provider,
|
||||
moduleSpecifier: `@uni_modules/${provider.plugin.toLowerCase()}`,
|
||||
plugin: provider.plugin,
|
||||
source: 'ohpm',
|
||||
version: '*',
|
||||
});
|
||||
});
|
||||
const relatedProviders = getRelatedProviders(inputDir, allProviders);
|
||||
relatedProviders.sort().forEach((relatedProvider) => {
|
||||
const provider = allProviders.find((item) => item.service === relatedProvider.service &&
|
||||
item.name === relatedProvider.name);
|
||||
if (!provider) {
|
||||
return;
|
||||
}
|
||||
projectDeps.push({
|
||||
moduleSpecifier: provider.moduleSpecifier,
|
||||
plugin: provider.plugin,
|
||||
source: provider.source,
|
||||
version: provider.version,
|
||||
});
|
||||
const className = uniCliShared.formatExtApiProviderName(provider.service, provider.name);
|
||||
importProviderCodes.push(`import { ${className} } from '${provider.moduleSpecifier}'`);
|
||||
registerProviderCodes.push(`registerUniProvider('${provider.service}', '${provider.name}', new ${className}())`);
|
||||
});
|
||||
if (importProviderCodes.length) {
|
||||
importCodes.push(...importProviderCodes);
|
||||
extApiCodes.push(...registerProviderCodes);
|
||||
}
|
||||
const pluginCustomElements = uniCliShared.getUTSPluginCustomElements();
|
||||
Object.keys(pluginCustomElements)
|
||||
.sort()
|
||||
.forEach((pluginId) => {
|
||||
if (!utsPlugins.has(pluginId)) {
|
||||
// 可能没使用,没编译
|
||||
return;
|
||||
}
|
||||
const elements = [...pluginCustomElements[pluginId]];
|
||||
if (elements.length) {
|
||||
importCodes.push(`import { ${elements
|
||||
.map((name) => uniCliShared.capitalize(uniCliShared.camelize(name)) + 'Element')
|
||||
.join(', ')} } from '@uni_modules/${pluginId.toLowerCase()}'`);
|
||||
elements.forEach((element) => {
|
||||
registerCodes.push(`customElements.define('${element.replace('uni-', '')}', ${uniCliShared.capitalize(uniCliShared.camelize(element)) + 'Element'})`);
|
||||
});
|
||||
}
|
||||
});
|
||||
const importIds = [];
|
||||
if (relatedProviders.length) {
|
||||
importIds.push('registerUniProvider');
|
||||
}
|
||||
if (Object.keys(pluginCustomElements).length) {
|
||||
importIds.push('customElements');
|
||||
}
|
||||
importIds.push('uni');
|
||||
importCodes.unshift(`import { ${importIds.join(', ')} } from '${process.env.UNI_APP_X !== 'true'
|
||||
? '@dcloudio/uni-app-runtime'
|
||||
: '@dcloudio/uni-app-x-runtime'}'`);
|
||||
context.emitFile({
|
||||
type: 'asset',
|
||||
fileName: 'uni_modules/index.generated.ets',
|
||||
source: `// This file is automatically generated by uni-app.
|
||||
// Do not modify this file -- YOUR CHANGES WILL BE ERASED!
|
||||
${importCodes.join('\n')}
|
||||
|
||||
export function initUniModules() {
|
||||
initUniExtApi()
|
||||
${registerCodes.join('\n ')}
|
||||
}
|
||||
|
||||
function initUniExtApi() {
|
||||
${extApiCodes.join('\n ')}
|
||||
}
|
||||
`,
|
||||
});
|
||||
const dependencies = {};
|
||||
const modules = [];
|
||||
projectDeps.forEach((dep) => {
|
||||
if (dep.source === 'local') {
|
||||
const depPath = './uni_modules/' + dep.plugin;
|
||||
dependencies[dep.moduleSpecifier] = depPath;
|
||||
modules.push({
|
||||
name: generateHarName(dep.moduleSpecifier),
|
||||
srcPath: depPath,
|
||||
});
|
||||
}
|
||||
else {
|
||||
if (!dependencies[dep.moduleSpecifier]) {
|
||||
dependencies[dep.moduleSpecifier] = `./libs/${generateHarName(dep.moduleSpecifier)}.har`;
|
||||
}
|
||||
}
|
||||
});
|
||||
context.emitFile({
|
||||
type: 'asset',
|
||||
fileName: 'uni_modules/oh-package.json5',
|
||||
source: JSON.stringify({ dependencies }, null, 2),
|
||||
});
|
||||
context.emitFile({
|
||||
type: 'asset',
|
||||
fileName: 'uni_modules/build-profile.json5',
|
||||
source: JSON.stringify({ modules }, null, 2),
|
||||
});
|
||||
}
|
||||
|
||||
const externalModulesX = ExternalModulesX;
|
||||
var index = [
|
||||
process.env.UNI_APP_X === 'true' ? uniAppUts.initUniAppXHarmonyPlugin : appVite__default.default,
|
||||
uniAppHarmonyPlugin,
|
||||
];
|
||||
|
||||
exports.default = index;
|
||||
exports.externalModulesX = externalModulesX;
|
||||
+13769
File diff suppressed because it is too large
Load Diff
+15
File diff suppressed because one or more lines are too long
+1
File diff suppressed because one or more lines are too long
+1
@@ -0,0 +1 @@
|
||||
[https://dcloud.io/license/uni-app.html](https://dcloud.io/license/uni-app.html)
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"name": "@dcloudio/uni-app-harmony",
|
||||
"version": "3.0.0-4060620250520001",
|
||||
"description": "@dcloudio/uni-app-harmony",
|
||||
"files": [
|
||||
"dist",
|
||||
"lib"
|
||||
],
|
||||
"sideEffects": [
|
||||
"lib/automator.js"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/dcloudio/uni-app.git",
|
||||
"directory": "packages/uni-app-harmony"
|
||||
},
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/dcloudio/uni-app/issues"
|
||||
},
|
||||
"gitHead": "33e807d66e1fe47e2ee08ad9c59247e37b8884da",
|
||||
"uni-app": {
|
||||
"name": "uni-app-harmony",
|
||||
"apply": [
|
||||
"app-harmony"
|
||||
],
|
||||
"main": "dist/uni.compiler.js"
|
||||
},
|
||||
"dependencies": {
|
||||
"debug": "^4.3.3",
|
||||
"fs-extra": "^10.0.0",
|
||||
"licia": "^1.29.0",
|
||||
"postcss-selector-parser": "^6.0.6",
|
||||
"@dcloudio/uni-app-uts": "3.0.0-4060620250520001",
|
||||
"@dcloudio/uni-app-vite": "3.0.0-4060620250520001"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/pako": "1.0.2",
|
||||
"@types/google.maps": "^3.45.6",
|
||||
"@amap/amap-jsapi-types": "^0.0.8",
|
||||
"@vue/compiler-sfc": "3.4.21",
|
||||
"autoprefixer": "^10.4.18",
|
||||
"pako": "^1.0.11",
|
||||
"postcss": "^8.4.21",
|
||||
"vue": "3.4.21",
|
||||
"@dcloudio/uni-cli-shared": "3.0.0-4060620250520001",
|
||||
"@dcloudio/uni-app-plus": "3.0.0-4060620250520001",
|
||||
"@dcloudio/uni-components": "3.0.0-4060620250520001",
|
||||
"@dcloudio/uni-i18n": "3.0.0-4060620250520001",
|
||||
"@dcloudio/uni-shared": "3.0.0-4060620250520001"
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user