提交 b74ce0ad 编写于 作者: fxy060608's avatar fxy060608

feat(api): promisify

上级 bd546d1e
...@@ -70,11 +70,11 @@ export function createKeepAliveApiCallback(name: string, callback: Function) { ...@@ -70,11 +70,11 @@ export function createKeepAliveApiCallback(name: string, callback: Function) {
) )
} }
const API_SUCCSS = 'success' export const API_SUCCESS = 'success'
const API_FAIL = 'fail' export const API_FAIL = 'fail'
const API_COMPLETE = 'complete' export const API_COMPLETE = 'complete'
type CALLBACK_TYPES = typeof API_SUCCSS | typeof API_FAIL | typeof API_COMPLETE type CALLBACK_TYPES = typeof API_SUCCESS | typeof API_FAIL | typeof API_COMPLETE
type ApiCallbacks = { type ApiCallbacks = {
[key in CALLBACK_TYPES]?: Function [key in CALLBACK_TYPES]?: Function
...@@ -121,6 +121,7 @@ export function createAsyncApiCallback( ...@@ -121,6 +121,7 @@ export function createAsyncApiCallback(
callbackId, callbackId,
createInvokeCallbackName(name, callbackId), createInvokeCallbackName(name, callbackId),
(res: ApiRes) => { (res: ApiRes) => {
res = res || {}
res.errMsg = normalizeErrMsg(res.errMsg, name) res.errMsg = normalizeErrMsg(res.errMsg, name)
isFunction(beforeAll) && beforeAll(res) isFunction(beforeAll) && beforeAll(res)
if (res.errMsg === name + ':ok') { if (res.errMsg === name + ':ok') {
......
...@@ -4,19 +4,20 @@ import { ...@@ -4,19 +4,20 @@ import {
createKeepAliveApiCallback, createKeepAliveApiCallback,
invokeCallback, invokeCallback,
} from './callback' } from './callback'
import { promisify } from './promise'
type ApiProtocols = ApiProtocol | ProtocolOptions[] type ApiProtocols = ApiProtocol | ProtocolOptions[]
export const API_TYPE_ON = 0 export const API_TYPE_ON = 0
export const API_TYPE_SYNC = 1 export const API_TYPE_TASK = 1
export const API_TYPE_ASYNC = 2 export const API_TYPE_SYNC = 2
export const API_TYPE_RETURN = 3 export const API_TYPE_ASYNC = 3
type API_TYPES = type API_TYPES =
| typeof API_TYPE_ON | typeof API_TYPE_ON
| typeof API_TYPE_TASK
| typeof API_TYPE_SYNC | typeof API_TYPE_SYNC
| typeof API_TYPE_ASYNC | typeof API_TYPE_ASYNC
| typeof API_TYPE_RETURN
function validateProtocol( function validateProtocol(
_name: string, _name: string,
...@@ -35,6 +36,11 @@ function wrapperOnApi(name: string, fn: Function) { ...@@ -35,6 +36,11 @@ function wrapperOnApi(name: string, fn: Function) {
fn.apply(null, createKeepAliveApiCallback(name, callback)) fn.apply(null, createKeepAliveApiCallback(name, callback))
} }
function wrapperTaskApi(name: string, fn: Function, options?: ApiOptions) {
return (args: Record<string, any>) =>
fn.apply(null, [args, createAsyncApiCallback(name, args, options)])
}
function wrapperSyncApi(fn: Function) { function wrapperSyncApi(fn: Function) {
return (...args: any[]) => fn.apply(null, args) return (...args: any[]) => fn.apply(null, args)
} }
...@@ -42,15 +48,13 @@ function wrapperSyncApi(fn: Function) { ...@@ -42,15 +48,13 @@ function wrapperSyncApi(fn: Function) {
function wrapperAsyncApi(name: string, fn: Function, options?: ApiOptions) { function wrapperAsyncApi(name: string, fn: Function, options?: ApiOptions) {
return (args: Record<string, any>) => { return (args: Record<string, any>) => {
const callbackId = createAsyncApiCallback(name, args, options) const callbackId = createAsyncApiCallback(name, args, options)
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])) const res = fn.apply(null, [args, callbackId])
if (res) {
invokeCallback(callbackId, res)
}
} }
} }
function wrapperReturnApi(name: string, fn: Function, options?: ApiOptions) {
return (args: Record<string, any>) =>
fn.apply(null, [args, createAsyncApiCallback(name, args, options)])
}
function wrapperApi<T extends Function>( function wrapperApi<T extends Function>(
fn: Function, fn: Function,
name?: string, name?: string,
...@@ -73,31 +77,31 @@ export function createOnApi<T extends Function>( ...@@ -73,31 +77,31 @@ export function createOnApi<T extends Function>(
return createApi(API_TYPE_ON, name, fn, protocol, options) return createApi(API_TYPE_ON, name, fn, protocol, options)
} }
export function createSyncApi<T extends Function>( export function createTaskApi<T extends Function>(
name: string, name: string,
fn: T, fn: T,
protocol?: ApiProtocols, protocol?: ApiProtocols,
options?: ApiOptions options?: ApiOptions
) { ) {
return createApi(API_TYPE_SYNC, name, fn, protocol, options) return createApi(API_TYPE_TASK, name, fn, protocol, options)
} }
export function createAsyncApi<T extends Function>( export function createSyncApi<T extends Function>(
name: string, name: string,
fn: T, fn: T,
protocol?: ApiProtocols, protocol?: ApiProtocols,
options?: ApiOptions options?: ApiOptions
) { ) {
return createApi(API_TYPE_ASYNC, name, fn, protocol, options) return createApi(API_TYPE_SYNC, name, fn, protocol, options)
} }
export function createReturnApi<T extends Function>( export function createAsyncApi<T extends Function>(
name: string, name: string,
fn: T, fn: T,
protocol?: ApiProtocols, protocol?: ApiProtocols,
options?: ApiOptions options?: ApiOptions
) { ) {
return createApi(API_TYPE_RETURN, name, fn, protocol, options) return promisify(createApi(API_TYPE_ASYNC, name, fn, protocol, options))
} }
function createApi<T extends Function>( function createApi<T extends Function>(
...@@ -110,6 +114,8 @@ function createApi<T extends Function>( ...@@ -110,6 +114,8 @@ function createApi<T extends Function>(
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi<T>(wrapperOnApi(name, fn), name, protocol, options) return wrapperApi<T>(wrapperOnApi(name, fn), name, protocol, options)
case API_TYPE_TASK:
return wrapperApi<T>(wrapperTaskApi(name, fn), name, protocol, options)
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi<T>(wrapperSyncApi(fn), name, protocol, options) return wrapperApi<T>(wrapperSyncApi(fn), name, protocol, options)
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
...@@ -119,7 +125,5 @@ function createApi<T extends Function>( ...@@ -119,7 +125,5 @@ function createApi<T extends Function>(
protocol, protocol,
options options
) )
case API_TYPE_RETURN:
return wrapperApi<T>(wrapperReturnApi(name, fn), name, protocol, options)
} }
} }
import { isPlainObject, isFunction } from '@vue/shared'
import { API_SUCCESS, API_FAIL, API_COMPLETE } from './callback'
const callbacks = [API_SUCCESS, API_FAIL, API_COMPLETE]
function hasCallback(args: unknown) {
if (
isPlainObject(args) &&
callbacks.find((cb) => isFunction((args as Record<string, any>)[cb]))
) {
return true
}
return false
}
export function handlePromise(promise: Promise<unknown>) {
if (__UNI_PROMISE_API__) {
return promise
.then((data) => {
return [null, data]
})
.catch((err) => [err])
}
return promise
}
export function promisify(fn: Function) {
return (args = {}) => {
if (hasCallback(args)) {
return fn(args)
}
return handlePromise(
new Promise((resolve, reject) => {
fn(Object.assign(args, { success: resolve, fail: reject }))
})
)
}
}
...@@ -24,8 +24,10 @@ export * from './protocols/media/getImageInfo' ...@@ -24,8 +24,10 @@ export * from './protocols/media/getImageInfo'
// helpers // helpers
export { export {
createOnApi, createOnApi,
createTaskApi,
createSyncApi, createSyncApi,
createAsyncApi, createAsyncApi,
createReturnApi,
} from './helpers/api' } from './helpers/api'
export { isSyncApi, isContextApi, promisify } from './helpers/promise'
export { handlePromise } from './helpers/api/promise'
export { invokeApi, wrapperReturnValue } from './helpers/interceptor'
...@@ -2,7 +2,7 @@ import { extend } from '@vue/shared' ...@@ -2,7 +2,7 @@ import { extend } from '@vue/shared'
import { ServiceJSBridge } from '@dcloudio/uni-core' import { ServiceJSBridge } from '@dcloudio/uni-core'
import { createReturnApi } from '../../helpers/api' import { createSyncApi } from '../../helpers/api'
import { getCurrentPageVm } from '../utils' import { getCurrentPageVm } from '../utils'
const defaultOptions = { const defaultOptions = {
...@@ -120,7 +120,7 @@ class ServiceIntersectionObserver { ...@@ -120,7 +120,7 @@ class ServiceIntersectionObserver {
} }
} }
export const createIntersectionObserver = createReturnApi< export const createIntersectionObserver = createSyncApi<
typeof uni.createIntersectionObserver typeof uni.createIntersectionObserver
>('createIntersectionObserver', (context?, options?) => { >('createIntersectionObserver', (context?, options?) => {
if (!context) { if (!context) {
......
...@@ -1335,6 +1335,9 @@ function createKeepAliveApiCallback(name, callback) { ...@@ -1335,6 +1335,9 @@ function createKeepAliveApiCallback(name, callback) {
const id2 = invokeCallbackId++; const id2 = invokeCallbackId++;
return addInvokeCallback(id2, createInvokeCallbackName(name, id2), callback, true); return addInvokeCallback(id2, createInvokeCallbackName(name, id2), callback, true);
} }
const API_SUCCESS = "success";
const API_FAIL = "fail";
const API_COMPLETE = "complete";
function getApiCallbacks(args) { function getApiCallbacks(args) {
const apiCallbacks = {}; const apiCallbacks = {};
for (const name in args) { for (const name in args) {
...@@ -1362,6 +1365,7 @@ function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {} ...@@ -1362,6 +1365,7 @@ function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {}
const hasComplete = isFunction(complete); const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++; const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => { addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name); res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res); isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ":ok") { if (res.errMsg === name + ":ok") {
...@@ -1374,10 +1378,35 @@ function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {} ...@@ -1374,10 +1378,35 @@ function createAsyncApiCallback(name, args = {}, {beforeAll, beforeSuccess} = {}
}); });
return callbackId; return callbackId;
} }
const callbacks$1 = [API_SUCCESS, API_FAIL, API_COMPLETE];
function hasCallback(args) {
if (isPlainObject(args) && callbacks$1.find((cb) => isFunction(args[cb]))) {
return true;
}
return false;
}
function handlePromise(promise) {
if (__UNI_PROMISE_API__) {
return promise.then((data) => {
return [null, data];
}).catch((err) => [err]);
}
return promise;
}
function promisify(fn) {
return (args = {}) => {
if (hasCallback(args)) {
return fn(args);
}
return handlePromise(new Promise((resolve, reject) => {
fn(Object.assign(args, {success: resolve, fail: reject}));
}));
};
}
const API_TYPE_ON = 0; const API_TYPE_ON = 0;
const API_TYPE_SYNC = 1; const API_TYPE_TASK = 1;
const API_TYPE_ASYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_RETURN = 3; const API_TYPE_ASYNC = 3;
function validateProtocol(_name, _args, _protocol) { function validateProtocol(_name, _args, _protocol) {
return true; return true;
} }
...@@ -1387,18 +1416,21 @@ function formatApiArgs(args, options) { ...@@ -1387,18 +1416,21 @@ function formatApiArgs(args, options) {
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback)); return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback));
} }
function wrapperTaskApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperSyncApi(fn) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])); const res = fn.apply(null, [args, callbackId]);
if (res) {
invokeCallback(callbackId, res);
}
}; };
} }
function wrapperReturnApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function(...args) { return function(...args) {
if (!(process.env.NODE_ENV !== "production" && protocol && !validateProtocol())) { if (!(process.env.NODE_ENV !== "production" && protocol && !validateProtocol())) {
...@@ -1407,24 +1439,21 @@ function wrapperApi(fn, name, protocol, options) { ...@@ -1407,24 +1439,21 @@ function wrapperApi(fn, name, protocol, options) {
}; };
} }
function createSyncApi(name, fn, protocol, options) { function createSyncApi(name, fn, protocol, options) {
return /* @__PURE__ */ createApi(API_TYPE_SYNC, name, fn, protocol, options); return createApi(API_TYPE_SYNC, name, fn, protocol, options);
} }
function createAsyncApi(name, fn, protocol, options) { function createAsyncApi(name, fn, protocol, options) {
return /* @__PURE__ */ createApi(API_TYPE_ASYNC, name, fn, protocol, options); return promisify(createApi(API_TYPE_ASYNC, name, fn, protocol, options));
}
function createReturnApi(name, fn, protocol, options) {
return /* @__PURE__ */ createApi(API_TYPE_RETURN, name, fn, protocol, options);
} }
function createApi(type, name, fn, protocol, options) { function createApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol);
case API_TYPE_RETURN:
return wrapperApi(wrapperReturnApi(name, fn), name, protocol);
} }
} }
const Base64ToArrayBufferProtocol = [ const Base64ToArrayBufferProtocol = [
...@@ -1441,10 +1470,10 @@ const ArrayBufferToBase64Protocol = [ ...@@ -1441,10 +1470,10 @@ const ArrayBufferToBase64Protocol = [
required: true required: true
} }
]; ];
const base64ToArrayBuffer = createSyncApi("base64ToArrayBuffer", (base64) => { const base64ToArrayBuffer = /* @__PURE__ */ createSyncApi("base64ToArrayBuffer", (base64) => {
return decode(base64); return decode(base64);
}, Base64ToArrayBufferProtocol); }, Base64ToArrayBufferProtocol);
const arrayBufferToBase64 = createSyncApi("arrayBufferToBase64", (arrayBuffer) => { const arrayBufferToBase64 = /* @__PURE__ */ createSyncApi("arrayBufferToBase64", (arrayBuffer) => {
return encode(arrayBuffer); return encode(arrayBuffer);
}, ArrayBufferToBase64Protocol); }, ArrayBufferToBase64Protocol);
const Upx2pxProtocol = [ const Upx2pxProtocol = [
...@@ -1465,7 +1494,7 @@ function checkDeviceWidth() { ...@@ -1465,7 +1494,7 @@ function checkDeviceWidth() {
deviceDPR = pixelRatio2; deviceDPR = pixelRatio2;
isIOS = platform === "ios"; isIOS = platform === "ios";
} }
const upx2px = createSyncApi("upx2px", (number, newDeviceWidth) => { const upx2px = /* @__PURE__ */ createSyncApi("upx2px", (number, newDeviceWidth) => {
if (deviceWidth === 0) { if (deviceWidth === 0) {
checkDeviceWidth(); checkDeviceWidth();
} }
...@@ -1544,14 +1573,14 @@ function removeHook(hooks, hook) { ...@@ -1544,14 +1573,14 @@ function removeHook(hooks, hook) {
hooks.splice(index2, 1); hooks.splice(index2, 1);
} }
} }
const addInterceptor = createSyncApi("addInterceptor", (method, interceptor) => { const addInterceptor = /* @__PURE__ */ createSyncApi("addInterceptor", (method, interceptor) => {
if (typeof method === "string" && isPlainObject(interceptor)) { if (typeof method === "string" && isPlainObject(interceptor)) {
mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor); mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
} else if (isPlainObject(method)) { } else if (isPlainObject(method)) {
mergeInterceptorHook(globalInterceptors, method); mergeInterceptorHook(globalInterceptors, method);
} }
}, AddInterceptorProtocol); }, AddInterceptorProtocol);
const removeInterceptor = createSyncApi("removeInterceptor", (method, interceptor) => { const removeInterceptor = /* @__PURE__ */ createSyncApi("removeInterceptor", (method, interceptor) => {
if (typeof method === "string") { if (typeof method === "string") {
if (isPlainObject(interceptor)) { if (isPlainObject(interceptor)) {
removeInterceptorHook(scopedInterceptors[method], interceptor); removeInterceptorHook(scopedInterceptors[method], interceptor);
...@@ -1639,7 +1668,7 @@ class ServiceIntersectionObserver { ...@@ -1639,7 +1668,7 @@ class ServiceIntersectionObserver {
}, this._pageId); }, this._pageId);
} }
} }
const createIntersectionObserver$1 = createReturnApi("createIntersectionObserver", (context, options) => { const createIntersectionObserver$1 = /* @__PURE__ */ createSyncApi("createIntersectionObserver", (context, options) => {
if (!context) { if (!context) {
context = getCurrentPageVm(); context = getCurrentPageVm();
} }
...@@ -1687,14 +1716,6 @@ const GetImageInfoProtocol = { ...@@ -1687,14 +1716,6 @@ const GetImageInfoProtocol = {
required: true required: true
} }
}; };
if (!Promise.prototype.finally) {
Promise.prototype.finally = function(onfinally) {
const promise = this.constructor;
return this.then((value) => promise.resolve(onfinally && onfinally()).then(() => value), (reason) => promise.resolve(onfinally && onfinally()).then(() => {
throw reason;
}));
};
}
function cssSupports(css) { function cssSupports(css) {
return window.CSS && window.CSS.supports && window.CSS.supports(css); return window.CSS && window.CSS.supports && window.CSS.supports(css);
} }
...@@ -1703,19 +1724,19 @@ const SCHEMA_CSS = { ...@@ -1703,19 +1724,19 @@ const SCHEMA_CSS = {
"css.env": cssSupports("top:env(a)"), "css.env": cssSupports("top:env(a)"),
"css.constant": cssSupports("top:constant(a)") "css.constant": cssSupports("top:constant(a)")
}; };
const canIUse = createSyncApi("canIUse", (schema) => { const canIUse = /* @__PURE__ */ createSyncApi("canIUse", (schema) => {
if (hasOwn(SCHEMA_CSS, schema)) { if (hasOwn(SCHEMA_CSS, schema)) {
return SCHEMA_CSS[schema]; return SCHEMA_CSS[schema];
} }
return true; return true;
}, CanIUseProtocol); }, CanIUseProtocol);
const makePhoneCall = createAsyncApi("makePhoneCall", (option) => { const makePhoneCall = /* @__PURE__ */ createAsyncApi("makePhoneCall", (option) => {
window.location.href = `tel:${option.phoneNumber}`; window.location.href = `tel:${option.phoneNumber}`;
}, MakePhoneCallProtocol); }, MakePhoneCallProtocol);
const ua = navigator.userAgent; const ua = navigator.userAgent;
const isAndroid = /android/i.test(ua); const isAndroid = /android/i.test(ua);
const isIOS$1 = /iphone|ipad|ipod/i.test(ua); const isIOS$1 = /iphone|ipad|ipod/i.test(ua);
const getSystemInfoSync = createSyncApi("getSystemInfoSync", () => { const getSystemInfoSync = /* @__PURE__ */ createSyncApi("getSystemInfoSync", () => {
var screen = window.screen; var screen = window.screen;
var pixelRatio2 = window.devicePixelRatio; var pixelRatio2 = window.devicePixelRatio;
const screenFix = /^Apple/.test(navigator.vendor) && typeof window.orientation === "number"; const screenFix = /^Apple/.test(navigator.vendor) && typeof window.orientation === "number";
...@@ -1816,16 +1837,16 @@ const getSystemInfoSync = createSyncApi("getSystemInfoSync", () => { ...@@ -1816,16 +1837,16 @@ const getSystemInfoSync = createSyncApi("getSystemInfoSync", () => {
} }
}; };
}); });
const getSystemInfo = createAsyncApi("getSystemInfo", () => { const getSystemInfo = /* @__PURE__ */ createAsyncApi("getSystemInfo", () => {
return getSystemInfoSync(); return getSystemInfoSync();
}); });
const openDocument = createAsyncApi("openDocument", (option) => { const openDocument = /* @__PURE__ */ createAsyncApi("openDocument", (option) => {
window.open(option.filePath); window.open(option.filePath);
}, OpenDocumentProtocol); }, OpenDocumentProtocol);
function _getServiceAddress() { function _getServiceAddress() {
return window.location.protocol + "//" + window.location.host; return window.location.protocol + "//" + window.location.host;
} }
const getImageInfo = createAsyncApi("getImageInfo", ({src}, callback) => { const getImageInfo = /* @__PURE__ */ createAsyncApi("getImageInfo", ({src}, callback) => {
const img = new Image(); const img = new Image();
img.onload = function() { img.onload = function() {
callback({ callback({
...@@ -1842,9 +1863,9 @@ const getImageInfo = createAsyncApi("getImageInfo", ({src}, callback) => { ...@@ -1842,9 +1863,9 @@ const getImageInfo = createAsyncApi("getImageInfo", ({src}, callback) => {
}; };
img.src = src; img.src = src;
}, GetImageInfoProtocol, GetImageInfoOptions); }, GetImageInfoProtocol, GetImageInfoOptions);
const navigateBack = createAsyncApi("navigateBack", () => { const navigateBack = /* @__PURE__ */ createAsyncApi("navigateBack", () => {
}); });
const navigateTo = createAsyncApi("navigateTo", (options) => { const navigateTo = /* @__PURE__ */ createAsyncApi("navigateTo", (options) => {
const router = getApp().$router; const router = getApp().$router;
router.push({ router.push({
path: options.url, path: options.url,
...@@ -1852,13 +1873,13 @@ const navigateTo = createAsyncApi("navigateTo", (options) => { ...@@ -1852,13 +1873,13 @@ const navigateTo = createAsyncApi("navigateTo", (options) => {
state: createPageState("navigateTo") state: createPageState("navigateTo")
}); });
}); });
const redirectTo = createAsyncApi("redirectTo", () => { const redirectTo = /* @__PURE__ */ createAsyncApi("redirectTo", () => {
}); });
const reLaunch = createAsyncApi("reLaunch", () => { const reLaunch = /* @__PURE__ */ createAsyncApi("reLaunch", () => {
}); });
const switchTab = createAsyncApi("switchTab", () => { const switchTab = /* @__PURE__ */ createAsyncApi("switchTab", () => {
}); });
const getRealPath = createSyncApi("getRealPath", (path) => { const getRealPath = /* @__PURE__ */ createSyncApi("getRealPath", (path) => {
return path; return path;
}); });
var api = /* @__PURE__ */ Object.freeze({ var api = /* @__PURE__ */ Object.freeze({
......
...@@ -18,24 +18,26 @@ export default defineConfig({ ...@@ -18,24 +18,26 @@ export default defineConfig({
__DEV__: `(process.env.NODE_ENV !== 'production')`, __DEV__: `(process.env.NODE_ENV !== 'production')`,
__PLATFORM__: JSON.stringify('h5'), __PLATFORM__: JSON.stringify('h5'),
}, },
alias: [ resolve: {
{ alias: [
find: '@dcloudio/uni-api', {
replacement: resolve('../uni-api/src/index.ts'), find: '@dcloudio/uni-api',
}, replacement: resolve('../uni-api/src/index.ts'),
{ },
find: '@dcloudio/uni-vue', {
replacement: resolve('../uni-vue/src/index.ts'), find: '@dcloudio/uni-vue',
}, replacement: resolve('../uni-vue/src/index.ts'),
{ },
find: '@dcloudio/uni-core', {
replacement: resolve('../uni-core/src/index.ts'), find: '@dcloudio/uni-core',
}, replacement: resolve('../uni-core/src/index.ts'),
{ },
find: '@dcloudio/uni-components', {
replacement: resolve('../uni-components/src/index.ts'), find: '@dcloudio/uni-components',
}, replacement: resolve('../uni-components/src/index.ts'),
], },
],
},
plugins: [ plugins: [
vue({ vue({
template: { template: {
...@@ -54,7 +56,10 @@ export default defineConfig({ ...@@ -54,7 +56,10 @@ export default defineConfig({
preserveEntrySignatures: 'strict', preserveEntrySignatures: 'strict',
plugins: [ plugins: [
replace({ replace({
createApi: `/*#__PURE__*/ createApi`, createOnApi: `/*#__PURE__*/ createOnApi`,
createTaskApi: `/*#__PURE__*/ createTaskApi`,
createSyncApi: `/*#__PURE__*/ createSyncApi`,
createAsyncApi: `/*#__PURE__*/ createAsyncApi`,
}), }),
], ],
output: { output: {
......
...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
const hasComplete = isFunction(complete); const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++; const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => { addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name); res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res); isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') { if (res.errMsg === name + ':ok') {
...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
return callbackId; return callbackId;
} }
function handlePromise(promise) {
if (__UNI_PROMISE_API__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
return promise;
}
const API_TYPE_ON = 0; const API_TYPE_ON = 0;
const API_TYPE_SYNC = 1; const API_TYPE_TASK = 1;
const API_TYPE_ASYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_RETURN = 3; const API_TYPE_ASYNC = 3;
function validateProtocol(_name, _args, _protocol) { function validateProtocol(_name, _args, _protocol) {
return true; return true;
} }
...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) { ...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) {
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback)); return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback));
} }
function wrapperTaskApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperSyncApi(fn) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])); const res = fn.apply(null, [args, callbackId]);
if (res) {
invokeCallback(callbackId, res);
}
}; };
} }
function wrapperReturnApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) { if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) {
...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) { ...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol);
case API_TYPE_RETURN:
return wrapperApi(wrapperReturnApi(name, fn), name, protocol);
} }
} }
...@@ -384,16 +399,6 @@ function isSyncApi(name) { ...@@ -384,16 +399,6 @@ function isSyncApi(name) {
function isCallbackApi(name) { function isCallbackApi(name) {
return CALLBACK_API_RE.test(name) && name !== 'onPush'; return CALLBACK_API_RE.test(name) && name !== 'onPush';
} }
function handlePromise(promise) {
if (!__UNI_PROMISE_API__) {
return promise;
}
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
function shouldPromise(name) { function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false; return false;
...@@ -416,17 +421,17 @@ function promisify(name, api) { ...@@ -416,17 +421,17 @@ function promisify(name, api) {
if (!isFunction(api)) { if (!isFunction(api)) {
return api; return api;
} }
return function promiseApi(options = {}, ...params) { return function promiseApi(options = {}) {
if (isFunction(options.success) || if (isFunction(options.success) ||
isFunction(options.fail) || isFunction(options.fail) ||
isFunction(options.complete)) { isFunction(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); return wrapperReturnValue(name, invokeApi(name, api, options));
} }
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, { invokeApi(name, api, Object.assign({}, options, {
success: resolve, success: resolve,
fail: reject, fail: reject,
}), ...params); }));
}))); })));
}; };
} }
......
...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
const hasComplete = isFunction(complete); const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++; const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => { addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name); res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res); isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') { if (res.errMsg === name + ':ok') {
...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
return callbackId; return callbackId;
} }
function handlePromise(promise) {
if (__UNI_PROMISE_API__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
return promise;
}
const API_TYPE_ON = 0; const API_TYPE_ON = 0;
const API_TYPE_SYNC = 1; const API_TYPE_TASK = 1;
const API_TYPE_ASYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_RETURN = 3; const API_TYPE_ASYNC = 3;
function validateProtocol(_name, _args, _protocol) { function validateProtocol(_name, _args, _protocol) {
return true; return true;
} }
...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) { ...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) {
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback)); return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback));
} }
function wrapperTaskApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperSyncApi(fn) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])); const res = fn.apply(null, [args, callbackId]);
if (res) {
invokeCallback(callbackId, res);
}
}; };
} }
function wrapperReturnApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) { if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) {
...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) { ...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol);
case API_TYPE_RETURN:
return wrapperApi(wrapperReturnApi(name, fn), name, protocol);
} }
} }
...@@ -384,16 +399,6 @@ function isSyncApi(name) { ...@@ -384,16 +399,6 @@ function isSyncApi(name) {
function isCallbackApi(name) { function isCallbackApi(name) {
return CALLBACK_API_RE.test(name) && name !== 'onPush'; return CALLBACK_API_RE.test(name) && name !== 'onPush';
} }
function handlePromise(promise) {
if (!__UNI_PROMISE_API__) {
return promise;
}
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
function shouldPromise(name) { function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false; return false;
...@@ -416,17 +421,17 @@ function promisify(name, api) { ...@@ -416,17 +421,17 @@ function promisify(name, api) {
if (!isFunction(api)) { if (!isFunction(api)) {
return api; return api;
} }
return function promiseApi(options = {}, ...params) { return function promiseApi(options = {}) {
if (isFunction(options.success) || if (isFunction(options.success) ||
isFunction(options.fail) || isFunction(options.fail) ||
isFunction(options.complete)) { isFunction(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); return wrapperReturnValue(name, invokeApi(name, api, options));
} }
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, { invokeApi(name, api, Object.assign({}, options, {
success: resolve, success: resolve,
fail: reject, fail: reject,
}), ...params); }));
}))); })));
}; };
} }
......
import { hasOwn } from '@vue/shared' import { hasOwn } from '@vue/shared'
import { import { upx2px, addInterceptor, removeInterceptor } from '@dcloudio/uni-api'
upx2px,
addInterceptor,
removeInterceptor,
promisify,
} from '@dcloudio/uni-api'
import { promisify } from './promise'
import { initWrapper } from './wrapper' import { initWrapper } from './wrapper'
import { MPProtocols } from './protocols' import { MPProtocols } from './protocols'
const baseApis = { upx2px, addInterceptor, removeInterceptor } const baseApis = { upx2px, addInterceptor, removeInterceptor }
......
import { isFunction } from '@vue/shared' import { isFunction } from '@vue/shared'
import { invokeApi, wrapperReturnValue } from './interceptor' import { invokeApi, handlePromise, wrapperReturnValue } from '@dcloudio/uni-api'
const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/ const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/
...@@ -31,17 +31,6 @@ export function isTaskApi(name: string) { ...@@ -31,17 +31,6 @@ export function isTaskApi(name: string) {
return TASK_APIS.indexOf(name) !== -1 return TASK_APIS.indexOf(name) !== -1
} }
function handlePromise(promise: Promise<any>) {
if (!__UNI_PROMISE_API__) {
return promise
}
return promise
.then((data) => {
return [null, data]
})
.catch((err) => [err])
}
export function shouldPromise(name: string) { export function shouldPromise(name: string) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false return false
...@@ -72,13 +61,13 @@ export function promisify(name: string, api: unknown) { ...@@ -72,13 +61,13 @@ export function promisify(name: string, api: unknown) {
if (!isFunction(api)) { if (!isFunction(api)) {
return api return api
} }
return function promiseApi(options: Record<string, any> = {}, ...params: []) { return function promiseApi(options: Record<string, any> = {}) {
if ( if (
isFunction(options.success) || isFunction(options.success) ||
isFunction(options.fail) || isFunction(options.fail) ||
isFunction(options.complete) isFunction(options.complete)
) { ) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params)) return wrapperReturnValue(name, invokeApi(name, api, options))
} }
return wrapperReturnValue( return wrapperReturnValue(
name, name,
...@@ -90,8 +79,7 @@ export function promisify(name: string, api: unknown) { ...@@ -90,8 +79,7 @@ export function promisify(name: string, api: unknown) {
Object.assign({}, options, { Object.assign({}, options, {
success: resolve, success: resolve,
fail: reject, fail: reject,
}), })
...params
) )
}) })
) )
......
import { isFunction, isString, hasOwn, isPlainObject } from '@vue/shared' import { isFunction, isString, hasOwn, isPlainObject } from '@vue/shared'
import { isSyncApi, isContextApi } from '@dcloudio/uni-api'
import { import {
MPProtocols, MPProtocols,
MPProtocolArgsValue, MPProtocolArgsValue,
...@@ -9,6 +7,8 @@ import { ...@@ -9,6 +7,8 @@ import {
MPProtocolObject, MPProtocolObject,
} from './protocols' } from './protocols'
import { isSyncApi, isContextApi } from './promise'
const CALLBACKS = ['success', 'fail', 'cancel', 'complete'] const CALLBACKS = ['success', 'fail', 'cancel', 'complete']
export function initWrapper(protocols: MPProtocols) { export function initWrapper(protocols: MPProtocols) {
......
...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
const hasComplete = isFunction(complete); const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++; const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => { addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name); res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res); isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') { if (res.errMsg === name + ':ok') {
...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
return callbackId; return callbackId;
} }
function handlePromise(promise) {
if (__UNI_PROMISE_API__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
return promise;
}
const API_TYPE_ON = 0; const API_TYPE_ON = 0;
const API_TYPE_SYNC = 1; const API_TYPE_TASK = 1;
const API_TYPE_ASYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_RETURN = 3; const API_TYPE_ASYNC = 3;
function validateProtocol(_name, _args, _protocol) { function validateProtocol(_name, _args, _protocol) {
return true; return true;
} }
...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) { ...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) {
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback)); return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback));
} }
function wrapperTaskApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperSyncApi(fn) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])); const res = fn.apply(null, [args, callbackId]);
if (res) {
invokeCallback(callbackId, res);
}
}; };
} }
function wrapperReturnApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) { if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) {
...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) { ...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol);
case API_TYPE_RETURN:
return wrapperApi(wrapperReturnApi(name, fn), name, protocol);
} }
} }
...@@ -384,16 +399,6 @@ function isSyncApi(name) { ...@@ -384,16 +399,6 @@ function isSyncApi(name) {
function isCallbackApi(name) { function isCallbackApi(name) {
return CALLBACK_API_RE.test(name) && name !== 'onPush'; return CALLBACK_API_RE.test(name) && name !== 'onPush';
} }
function handlePromise(promise) {
if (!__UNI_PROMISE_API__) {
return promise;
}
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
function shouldPromise(name) { function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false; return false;
...@@ -416,17 +421,17 @@ function promisify(name, api) { ...@@ -416,17 +421,17 @@ function promisify(name, api) {
if (!isFunction(api)) { if (!isFunction(api)) {
return api; return api;
} }
return function promiseApi(options = {}, ...params) { return function promiseApi(options = {}) {
if (isFunction(options.success) || if (isFunction(options.success) ||
isFunction(options.fail) || isFunction(options.fail) ||
isFunction(options.complete)) { isFunction(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); return wrapperReturnValue(name, invokeApi(name, api, options));
} }
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, { invokeApi(name, api, Object.assign({}, options, {
success: resolve, success: resolve,
fail: reject, fail: reject,
}), ...params); }));
}))); })));
}; };
} }
......
...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
const hasComplete = isFunction(complete); const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++; const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => { addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name); res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res); isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') { if (res.errMsg === name + ':ok') {
...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
return callbackId; return callbackId;
} }
function handlePromise(promise) {
if (__UNI_PROMISE_API__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
return promise;
}
const API_TYPE_ON = 0; const API_TYPE_ON = 0;
const API_TYPE_SYNC = 1; const API_TYPE_TASK = 1;
const API_TYPE_ASYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_RETURN = 3; const API_TYPE_ASYNC = 3;
function validateProtocol(_name, _args, _protocol) { function validateProtocol(_name, _args, _protocol) {
return true; return true;
} }
...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) { ...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) {
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback)); return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback));
} }
function wrapperTaskApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperSyncApi(fn) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])); const res = fn.apply(null, [args, callbackId]);
if (res) {
invokeCallback(callbackId, res);
}
}; };
} }
function wrapperReturnApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) { if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) {
...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) { ...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol);
case API_TYPE_RETURN:
return wrapperApi(wrapperReturnApi(name, fn), name, protocol);
} }
} }
...@@ -384,16 +399,6 @@ function isSyncApi(name) { ...@@ -384,16 +399,6 @@ function isSyncApi(name) {
function isCallbackApi(name) { function isCallbackApi(name) {
return CALLBACK_API_RE.test(name) && name !== 'onPush'; return CALLBACK_API_RE.test(name) && name !== 'onPush';
} }
function handlePromise(promise) {
if (!__UNI_PROMISE_API__) {
return promise;
}
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
function shouldPromise(name) { function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false; return false;
...@@ -416,17 +421,17 @@ function promisify(name, api) { ...@@ -416,17 +421,17 @@ function promisify(name, api) {
if (!isFunction(api)) { if (!isFunction(api)) {
return api; return api;
} }
return function promiseApi(options = {}, ...params) { return function promiseApi(options = {}) {
if (isFunction(options.success) || if (isFunction(options.success) ||
isFunction(options.fail) || isFunction(options.fail) ||
isFunction(options.complete)) { isFunction(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); return wrapperReturnValue(name, invokeApi(name, api, options));
} }
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, { invokeApi(name, api, Object.assign({}, options, {
success: resolve, success: resolve,
fail: reject, fail: reject,
}), ...params); }));
}))); })));
}; };
} }
......
...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
const hasComplete = isFunction(complete); const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++; const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => { addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name); res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res); isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') { if (res.errMsg === name + ':ok') {
...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
return callbackId; return callbackId;
} }
function handlePromise(promise) {
if (__UNI_PROMISE_API__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
return promise;
}
const API_TYPE_ON = 0; const API_TYPE_ON = 0;
const API_TYPE_SYNC = 1; const API_TYPE_TASK = 1;
const API_TYPE_ASYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_RETURN = 3; const API_TYPE_ASYNC = 3;
function validateProtocol(_name, _args, _protocol) { function validateProtocol(_name, _args, _protocol) {
return true; return true;
} }
...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) { ...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) {
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback)); return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback));
} }
function wrapperTaskApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperSyncApi(fn) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])); const res = fn.apply(null, [args, callbackId]);
if (res) {
invokeCallback(callbackId, res);
}
}; };
} }
function wrapperReturnApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) { if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) {
...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) { ...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol);
case API_TYPE_RETURN:
return wrapperApi(wrapperReturnApi(name, fn), name, protocol);
} }
} }
...@@ -384,16 +399,6 @@ function isSyncApi(name) { ...@@ -384,16 +399,6 @@ function isSyncApi(name) {
function isCallbackApi(name) { function isCallbackApi(name) {
return CALLBACK_API_RE.test(name) && name !== 'onPush'; return CALLBACK_API_RE.test(name) && name !== 'onPush';
} }
function handlePromise(promise) {
if (!__UNI_PROMISE_API__) {
return promise;
}
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
function shouldPromise(name) { function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false; return false;
...@@ -416,17 +421,17 @@ function promisify(name, api) { ...@@ -416,17 +421,17 @@ function promisify(name, api) {
if (!isFunction(api)) { if (!isFunction(api)) {
return api; return api;
} }
return function promiseApi(options = {}, ...params) { return function promiseApi(options = {}) {
if (isFunction(options.success) || if (isFunction(options.success) ||
isFunction(options.fail) || isFunction(options.fail) ||
isFunction(options.complete)) { isFunction(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); return wrapperReturnValue(name, invokeApi(name, api, options));
} }
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, { invokeApi(name, api, Object.assign({}, options, {
success: resolve, success: resolve,
fail: reject, fail: reject,
}), ...params); }));
}))); })));
}; };
} }
......
...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -83,6 +83,7 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
const hasComplete = isFunction(complete); const hasComplete = isFunction(complete);
const callbackId = invokeCallbackId++; const callbackId = invokeCallbackId++;
addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => { addInvokeCallback(callbackId, createInvokeCallbackName(name, callbackId), (res) => {
res = res || {};
res.errMsg = normalizeErrMsg(res.errMsg, name); res.errMsg = normalizeErrMsg(res.errMsg, name);
isFunction(beforeAll) && beforeAll(res); isFunction(beforeAll) && beforeAll(res);
if (res.errMsg === name + ':ok') { if (res.errMsg === name + ':ok') {
...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = ...@@ -97,10 +98,21 @@ function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } =
return callbackId; return callbackId;
} }
function handlePromise(promise) {
if (__UNI_PROMISE_API__) {
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
return promise;
}
const API_TYPE_ON = 0; const API_TYPE_ON = 0;
const API_TYPE_SYNC = 1; const API_TYPE_TASK = 1;
const API_TYPE_ASYNC = 2; const API_TYPE_SYNC = 2;
const API_TYPE_RETURN = 3; const API_TYPE_ASYNC = 3;
function validateProtocol(_name, _args, _protocol) { function validateProtocol(_name, _args, _protocol) {
return true; return true;
} }
...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) { ...@@ -110,18 +122,21 @@ function formatApiArgs(args, options) {
function wrapperOnApi(name, fn) { function wrapperOnApi(name, fn) {
return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback)); return (callback) => fn.apply(null, createKeepAliveApiCallback(name, callback));
} }
function wrapperTaskApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperSyncApi(fn) { function wrapperSyncApi(fn) {
return (...args) => fn.apply(null, args); return (...args) => fn.apply(null, args);
} }
function wrapperAsyncApi(name, fn, options) { function wrapperAsyncApi(name, fn, options) {
return (args) => { return (args) => {
const callbackId = createAsyncApiCallback(name, args, options); const callbackId = createAsyncApiCallback(name, args, options);
return invokeCallback(callbackId, fn.apply(null, [args, callbackId])); const res = fn.apply(null, [args, callbackId]);
if (res) {
invokeCallback(callbackId, res);
}
}; };
} }
function wrapperReturnApi(name, fn, options) {
return (args) => fn.apply(null, [args, createAsyncApiCallback(name, args, options)]);
}
function wrapperApi(fn, name, protocol, options) { function wrapperApi(fn, name, protocol, options) {
return function (...args) { return function (...args) {
if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) { if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) {
...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) { ...@@ -136,12 +151,12 @@ function createApi(type, name, fn, protocol, options) {
switch (type) { switch (type) {
case API_TYPE_ON: case API_TYPE_ON:
return wrapperApi(wrapperOnApi(name, fn), name, protocol); return wrapperApi(wrapperOnApi(name, fn), name, protocol);
case API_TYPE_TASK:
return wrapperApi(wrapperTaskApi(name, fn), name, protocol);
case API_TYPE_SYNC: case API_TYPE_SYNC:
return wrapperApi(wrapperSyncApi(fn), name, protocol); return wrapperApi(wrapperSyncApi(fn), name, protocol);
case API_TYPE_ASYNC: case API_TYPE_ASYNC:
return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol); return wrapperApi(wrapperAsyncApi(name, fn, options), name, protocol);
case API_TYPE_RETURN:
return wrapperApi(wrapperReturnApi(name, fn), name, protocol);
} }
} }
...@@ -384,16 +399,6 @@ function isSyncApi(name) { ...@@ -384,16 +399,6 @@ function isSyncApi(name) {
function isCallbackApi(name) { function isCallbackApi(name) {
return CALLBACK_API_RE.test(name) && name !== 'onPush'; return CALLBACK_API_RE.test(name) && name !== 'onPush';
} }
function handlePromise(promise) {
if (!__UNI_PROMISE_API__) {
return promise;
}
return promise
.then((data) => {
return [null, data];
})
.catch((err) => [err]);
}
function shouldPromise(name) { function shouldPromise(name) {
if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) { if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
return false; return false;
...@@ -416,17 +421,17 @@ function promisify(name, api) { ...@@ -416,17 +421,17 @@ function promisify(name, api) {
if (!isFunction(api)) { if (!isFunction(api)) {
return api; return api;
} }
return function promiseApi(options = {}, ...params) { return function promiseApi(options = {}) {
if (isFunction(options.success) || if (isFunction(options.success) ||
isFunction(options.fail) || isFunction(options.fail) ||
isFunction(options.complete)) { isFunction(options.complete)) {
return wrapperReturnValue(name, invokeApi(name, api, options, ...params)); return wrapperReturnValue(name, invokeApi(name, api, options));
} }
return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => { return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
invokeApi(name, api, Object.assign({}, options, { invokeApi(name, api, Object.assign({}, options, {
success: resolve, success: resolve,
fail: reject, fail: reject,
}), ...params); }));
}))); })));
}; };
} }
......
...@@ -2,11 +2,12 @@ import { UserConfig } from 'vite' ...@@ -2,11 +2,12 @@ import { UserConfig } from 'vite'
import { VitePluginUniResolvedOptions } from '..' import { VitePluginUniResolvedOptions } from '..'
export function createDefine( export function createDefine(
_options: VitePluginUniResolvedOptions options: VitePluginUniResolvedOptions
): UserConfig['define'] { ): UserConfig['define'] {
return { return {
__UNI_WX_API__: true, __UNI_WX_API__: true,
__UNI_WXS_API__: true, __UNI_WXS_API__: true,
__UNI_PROMISE_API__: !!(options.feature && options.feature.promise),
__UNI_ROUTER_MODE__: JSON.stringify('hash'), __UNI_ROUTER_MODE__: JSON.stringify('hash'),
} }
} }
...@@ -34,7 +34,12 @@ type Injectment = string | [string, string] ...@@ -34,7 +34,12 @@ type Injectment = string | [string, string]
export interface InjectOptions extends UniPluginFilterOptions { export interface InjectOptions extends UniPluginFilterOptions {
sourceMap?: boolean sourceMap?: boolean
[str: string]: Injectment | InjectOptions['include'] | Boolean | ViteDevServer [str: string]:
| Injectment
| InjectOptions['include']
| Boolean
| ViteDevServer
| any
} }
const debugInject = debug('uni:inject') const debugInject = debug('uni:inject')
......
...@@ -10,6 +10,9 @@ import { createConfigResolved } from './configResolved' ...@@ -10,6 +10,9 @@ import { createConfigResolved } from './configResolved'
import { createConfigureServer } from './configureServer' import { createConfigureServer } from './configureServer'
export interface VitePluginUniOptions { export interface VitePluginUniOptions {
inputDir?: string inputDir?: string
feature?: {
promise: boolean
}
} }
export interface VitePluginUniResolvedOptions extends VitePluginUniOptions { export interface VitePluginUniResolvedOptions extends VitePluginUniOptions {
root: string root: string
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册