更新
This commit is contained in:
+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
Reference in New Issue
Block a user