uni.api.esm.js 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193
  1. import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isFunction, isPromise, extend, remove } from '@vue/shared';
  2. import { normalizeLocale, LOCALE_EN } from '@dcloudio/uni-i18n';
  3. import { LINEFEED, Emitter, onCreateVueApp, invokeCreateVueAppHook } from '@dcloudio/uni-shared';
  4. function getBaseSystemInfo() {
  5. return qa.getSystemInfoSync();
  6. }
  7. function validateProtocolFail(name, msg) {
  8. console.warn(`${name}: ${msg}`);
  9. }
  10. function validateProtocol(name, data, protocol, onFail) {
  11. if (!onFail) {
  12. onFail = validateProtocolFail;
  13. }
  14. for (const key in protocol) {
  15. const errMsg = validateProp(key, data[key], protocol[key], !hasOwn(data, key));
  16. if (isString(errMsg)) {
  17. onFail(name, errMsg);
  18. }
  19. }
  20. }
  21. function validateProtocols(name, args, protocol, onFail) {
  22. if (!protocol) {
  23. return;
  24. }
  25. if (!isArray(protocol)) {
  26. return validateProtocol(name, args[0] || Object.create(null), protocol, onFail);
  27. }
  28. const len = protocol.length;
  29. const argsLen = args.length;
  30. for (let i = 0; i < len; i++) {
  31. const opts = protocol[i];
  32. const data = Object.create(null);
  33. if (argsLen > i) {
  34. data[opts.name] = args[i];
  35. }
  36. validateProtocol(name, data, { [opts.name]: opts }, onFail);
  37. }
  38. }
  39. function validateProp(name, value, prop, isAbsent) {
  40. if (!isPlainObject(prop)) {
  41. prop = { type: prop };
  42. }
  43. const { type, required, validator } = prop;
  44. // required!
  45. if (required && isAbsent) {
  46. return 'Missing required args: "' + name + '"';
  47. }
  48. // missing but optional
  49. if (value == null && !required) {
  50. return;
  51. }
  52. // type check
  53. if (type != null) {
  54. let isValid = false;
  55. const types = isArray(type) ? type : [type];
  56. const expectedTypes = [];
  57. // value is valid as long as one of the specified types match
  58. for (let i = 0; i < types.length && !isValid; i++) {
  59. const { valid, expectedType } = assertType(value, types[i]);
  60. expectedTypes.push(expectedType || '');
  61. isValid = valid;
  62. }
  63. if (!isValid) {
  64. return getInvalidTypeMessage(name, value, expectedTypes);
  65. }
  66. }
  67. // custom validator
  68. if (validator) {
  69. return validator(value);
  70. }
  71. }
  72. const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
  73. function assertType(value, type) {
  74. let valid;
  75. const expectedType = getType(type);
  76. if (isSimpleType(expectedType)) {
  77. const t = typeof value;
  78. valid = t === expectedType.toLowerCase();
  79. // for primitive wrapper objects
  80. if (!valid && t === 'object') {
  81. valid = value instanceof type;
  82. }
  83. }
  84. else if (expectedType === 'Object') {
  85. valid = isObject(value);
  86. }
  87. else if (expectedType === 'Array') {
  88. valid = isArray(value);
  89. }
  90. else {
  91. {
  92. valid = value instanceof type;
  93. }
  94. }
  95. return {
  96. valid,
  97. expectedType,
  98. };
  99. }
  100. function getInvalidTypeMessage(name, value, expectedTypes) {
  101. let message = `Invalid args: type check failed for args "${name}".` +
  102. ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
  103. const expectedType = expectedTypes[0];
  104. const receivedType = toRawType(value);
  105. const expectedValue = styleValue(value, expectedType);
  106. const receivedValue = styleValue(value, receivedType);
  107. // check if we need to specify expected value
  108. if (expectedTypes.length === 1 &&
  109. isExplicable(expectedType) &&
  110. !isBoolean(expectedType, receivedType)) {
  111. message += ` with value ${expectedValue}`;
  112. }
  113. message += `, got ${receivedType} `;
  114. // check if we need to specify received value
  115. if (isExplicable(receivedType)) {
  116. message += `with value ${receivedValue}.`;
  117. }
  118. return message;
  119. }
  120. function getType(ctor) {
  121. const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
  122. return match ? match[1] : '';
  123. }
  124. function styleValue(value, type) {
  125. if (type === 'String') {
  126. return `"${value}"`;
  127. }
  128. else if (type === 'Number') {
  129. return `${Number(value)}`;
  130. }
  131. else {
  132. return `${value}`;
  133. }
  134. }
  135. function isExplicable(type) {
  136. const explicitTypes = ['string', 'number', 'boolean'];
  137. return explicitTypes.some((elem) => type.toLowerCase() === elem);
  138. }
  139. function isBoolean(...args) {
  140. return args.some((elem) => elem.toLowerCase() === 'boolean');
  141. }
  142. function tryCatch(fn) {
  143. return function () {
  144. try {
  145. return fn.apply(fn, arguments);
  146. }
  147. catch (e) {
  148. // TODO
  149. console.error(e);
  150. }
  151. };
  152. }
  153. let invokeCallbackId = 1;
  154. const invokeCallbacks = {};
  155. function addInvokeCallback(id, name, callback, keepAlive = false) {
  156. invokeCallbacks[id] = {
  157. name,
  158. keepAlive,
  159. callback,
  160. };
  161. return id;
  162. }
  163. // onNativeEventReceive((event,data)=>{}) 需要两个参数,目前写死最多两个参数
  164. function invokeCallback(id, res, extras) {
  165. if (typeof id === 'number') {
  166. const opts = invokeCallbacks[id];
  167. if (opts) {
  168. if (!opts.keepAlive) {
  169. delete invokeCallbacks[id];
  170. }
  171. return opts.callback(res, extras);
  172. }
  173. }
  174. return res;
  175. }
  176. const API_SUCCESS = 'success';
  177. const API_FAIL = 'fail';
  178. const API_COMPLETE = 'complete';
  179. function getApiCallbacks(args) {
  180. const apiCallbacks = {};
  181. for (const name in args) {
  182. const fn = args[name];
  183. if (isFunction(fn)) {
  184. apiCallbacks[name] = tryCatch(fn);
  185. delete args[name];
  186. }
  187. }
  188. return apiCallbacks;
  189. }
  190. function normalizeErrMsg$1(errMsg, name) {
  191. if (!errMsg || errMsg.indexOf(':fail') === -1) {
  192. return name + ':ok';
  193. }
  194. return name + errMsg.substring(errMsg.indexOf(':fail'));
  195. }
  196. function createAsyncApiCallback(name, args = {}, { beforeAll, beforeSuccess } = {}) {
  197. if (!isPlainObject(args)) {
  198. args = {};
  199. }
  200. const { success, fail, complete } = getApiCallbacks(args);
  201. const hasSuccess = isFunction(success);
  202. const hasFail = isFunction(fail);
  203. const hasComplete = isFunction(complete);
  204. const callbackId = invokeCallbackId++;
  205. addInvokeCallback(callbackId, name, (res) => {
  206. res = res || {};
  207. res.errMsg = normalizeErrMsg$1(res.errMsg, name);
  208. isFunction(beforeAll) && beforeAll(res);
  209. if (res.errMsg === name + ':ok') {
  210. isFunction(beforeSuccess) && beforeSuccess(res, args);
  211. hasSuccess && success(res);
  212. }
  213. else {
  214. hasFail && fail(res);
  215. }
  216. hasComplete && complete(res);
  217. });
  218. return callbackId;
  219. }
  220. const HOOK_SUCCESS = 'success';
  221. const HOOK_FAIL = 'fail';
  222. const HOOK_COMPLETE = 'complete';
  223. const globalInterceptors = {};
  224. const scopedInterceptors = {};
  225. function wrapperHook(hook, params) {
  226. return function (data) {
  227. return hook(data, params) || data;
  228. };
  229. }
  230. function queue(hooks, data, params) {
  231. let promise = false;
  232. for (let i = 0; i < hooks.length; i++) {
  233. const hook = hooks[i];
  234. if (promise) {
  235. promise = Promise.resolve(wrapperHook(hook, params));
  236. }
  237. else {
  238. const res = hook(data, params);
  239. if (isPromise(res)) {
  240. promise = Promise.resolve(res);
  241. }
  242. if (res === false) {
  243. return {
  244. then() { },
  245. catch() { },
  246. };
  247. }
  248. }
  249. }
  250. return (promise || {
  251. then(callback) {
  252. return callback(data);
  253. },
  254. catch() { },
  255. });
  256. }
  257. function wrapperOptions(interceptors, options = {}) {
  258. [HOOK_SUCCESS, HOOK_FAIL, HOOK_COMPLETE].forEach((name) => {
  259. const hooks = interceptors[name];
  260. if (!isArray(hooks)) {
  261. return;
  262. }
  263. const oldCallback = options[name];
  264. options[name] = function callbackInterceptor(res) {
  265. queue(hooks, res, options).then((res) => {
  266. return (isFunction(oldCallback) && oldCallback(res)) || res;
  267. });
  268. };
  269. });
  270. return options;
  271. }
  272. function wrapperReturnValue(method, returnValue) {
  273. const returnValueHooks = [];
  274. if (isArray(globalInterceptors.returnValue)) {
  275. returnValueHooks.push(...globalInterceptors.returnValue);
  276. }
  277. const interceptor = scopedInterceptors[method];
  278. if (interceptor && isArray(interceptor.returnValue)) {
  279. returnValueHooks.push(...interceptor.returnValue);
  280. }
  281. returnValueHooks.forEach((hook) => {
  282. returnValue = hook(returnValue) || returnValue;
  283. });
  284. return returnValue;
  285. }
  286. function getApiInterceptorHooks(method) {
  287. const interceptor = Object.create(null);
  288. Object.keys(globalInterceptors).forEach((hook) => {
  289. if (hook !== 'returnValue') {
  290. interceptor[hook] = globalInterceptors[hook].slice();
  291. }
  292. });
  293. const scopedInterceptor = scopedInterceptors[method];
  294. if (scopedInterceptor) {
  295. Object.keys(scopedInterceptor).forEach((hook) => {
  296. if (hook !== 'returnValue') {
  297. interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
  298. }
  299. });
  300. }
  301. return interceptor;
  302. }
  303. function invokeApi(method, api, options, params) {
  304. const interceptor = getApiInterceptorHooks(method);
  305. if (interceptor && Object.keys(interceptor).length) {
  306. if (isArray(interceptor.invoke)) {
  307. const res = queue(interceptor.invoke, options);
  308. return res.then((options) => {
  309. // 重新访问 getApiInterceptorHooks, 允许 invoke 中再次调用 addInterceptor,removeInterceptor
  310. return api(wrapperOptions(getApiInterceptorHooks(method), options), ...params);
  311. });
  312. }
  313. else {
  314. return api(wrapperOptions(interceptor, options), ...params);
  315. }
  316. }
  317. return api(options, ...params);
  318. }
  319. function hasCallback(args) {
  320. if (isPlainObject(args) &&
  321. [API_SUCCESS, API_FAIL, API_COMPLETE].find((cb) => isFunction(args[cb]))) {
  322. return true;
  323. }
  324. return false;
  325. }
  326. function handlePromise(promise) {
  327. // if (__UNI_FEATURE_PROMISE__) {
  328. // return promise
  329. // .then((data) => {
  330. // return [null, data]
  331. // })
  332. // .catch((err) => [err])
  333. // }
  334. return promise;
  335. }
  336. function promisify$1(name, fn) {
  337. return (args = {}, ...rest) => {
  338. if (hasCallback(args)) {
  339. return wrapperReturnValue(name, invokeApi(name, fn, args, rest));
  340. }
  341. return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
  342. invokeApi(name, fn, extend(args, { success: resolve, fail: reject }), rest);
  343. })));
  344. };
  345. }
  346. function formatApiArgs(args, options) {
  347. const params = args[0];
  348. if (!options ||
  349. (!isPlainObject(options.formatArgs) && isPlainObject(params))) {
  350. return;
  351. }
  352. const formatArgs = options.formatArgs;
  353. const keys = Object.keys(formatArgs);
  354. for (let i = 0; i < keys.length; i++) {
  355. const name = keys[i];
  356. const formatterOrDefaultValue = formatArgs[name];
  357. if (isFunction(formatterOrDefaultValue)) {
  358. const errMsg = formatterOrDefaultValue(args[0][name], params);
  359. if (isString(errMsg)) {
  360. return errMsg;
  361. }
  362. }
  363. else {
  364. // defaultValue
  365. if (!hasOwn(params, name)) {
  366. params[name] = formatterOrDefaultValue;
  367. }
  368. }
  369. }
  370. }
  371. function invokeSuccess(id, name, res) {
  372. const result = {
  373. errMsg: name + ':ok',
  374. };
  375. return invokeCallback(id, extend((res || {}), result));
  376. }
  377. function invokeFail(id, name, errMsg, errRes = {}) {
  378. const apiErrMsg = name + ':fail' + (errMsg ? ' ' + errMsg : '');
  379. delete errRes.errCode;
  380. return invokeCallback(id, typeof UniError !== 'undefined'
  381. ? typeof errRes.errCode !== 'undefined'
  382. ? new UniError(name, errRes.errCode, apiErrMsg)
  383. : new UniError(apiErrMsg, errRes)
  384. : extend({ errMsg: apiErrMsg }, errRes));
  385. }
  386. function beforeInvokeApi(name, args, protocol, options) {
  387. if ((process.env.NODE_ENV !== 'production')) {
  388. validateProtocols(name, args, protocol);
  389. }
  390. if (options && options.beforeInvoke) {
  391. const errMsg = options.beforeInvoke(args);
  392. if (isString(errMsg)) {
  393. return errMsg;
  394. }
  395. }
  396. const errMsg = formatApiArgs(args, options);
  397. if (errMsg) {
  398. return errMsg;
  399. }
  400. }
  401. function normalizeErrMsg(errMsg) {
  402. if (!errMsg || isString(errMsg)) {
  403. return errMsg;
  404. }
  405. if (errMsg.stack) {
  406. console.error(errMsg.message + LINEFEED + errMsg.stack);
  407. return errMsg.message;
  408. }
  409. return errMsg;
  410. }
  411. function wrapperTaskApi(name, fn, protocol, options) {
  412. return (args) => {
  413. const id = createAsyncApiCallback(name, args, options);
  414. const errMsg = beforeInvokeApi(name, [args], protocol, options);
  415. if (errMsg) {
  416. return invokeFail(id, name, errMsg);
  417. }
  418. return fn(args, {
  419. resolve: (res) => invokeSuccess(id, name, res),
  420. reject: (errMsg, errRes) => invokeFail(id, name, normalizeErrMsg(errMsg), errRes),
  421. });
  422. };
  423. }
  424. function wrapperSyncApi(name, fn, protocol, options) {
  425. return (...args) => {
  426. const errMsg = beforeInvokeApi(name, args, protocol, options);
  427. if (errMsg) {
  428. throw new Error(errMsg);
  429. }
  430. return fn.apply(null, args);
  431. };
  432. }
  433. function wrapperAsyncApi(name, fn, protocol, options) {
  434. return wrapperTaskApi(name, fn, protocol, options);
  435. }
  436. function defineSyncApi(name, fn, protocol, options) {
  437. return wrapperSyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
  438. }
  439. function defineAsyncApi(name, fn, protocol, options) {
  440. return promisify$1(name, wrapperAsyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options));
  441. }
  442. const API_UPX2PX = 'upx2px';
  443. const Upx2pxProtocol = [
  444. {
  445. name: 'upx',
  446. type: [Number, String],
  447. required: true,
  448. },
  449. ];
  450. const EPS = 1e-4;
  451. const BASE_DEVICE_WIDTH = 750;
  452. let isIOS = false;
  453. let deviceWidth = 0;
  454. let deviceDPR = 0;
  455. function checkDeviceWidth() {
  456. const { platform, pixelRatio, windowWidth } = getBaseSystemInfo();
  457. deviceWidth = windowWidth;
  458. deviceDPR = pixelRatio;
  459. isIOS = platform === 'ios';
  460. }
  461. const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
  462. if (deviceWidth === 0) {
  463. checkDeviceWidth();
  464. }
  465. number = Number(number);
  466. if (number === 0) {
  467. return 0;
  468. }
  469. let width = newDeviceWidth || deviceWidth;
  470. let result = (number / BASE_DEVICE_WIDTH) * width;
  471. if (result < 0) {
  472. result = -result;
  473. }
  474. result = Math.floor(result + EPS);
  475. if (result === 0) {
  476. if (deviceDPR === 1 || !isIOS) {
  477. result = 1;
  478. }
  479. else {
  480. result = 0.5;
  481. }
  482. }
  483. return number < 0 ? -result : result;
  484. }, Upx2pxProtocol);
  485. const API_ADD_INTERCEPTOR = 'addInterceptor';
  486. const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
  487. const AddInterceptorProtocol = [
  488. {
  489. name: 'method',
  490. type: [String, Object],
  491. required: true,
  492. },
  493. ];
  494. const RemoveInterceptorProtocol = AddInterceptorProtocol;
  495. function mergeInterceptorHook(interceptors, interceptor) {
  496. Object.keys(interceptor).forEach((hook) => {
  497. if (isFunction(interceptor[hook])) {
  498. interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]);
  499. }
  500. });
  501. }
  502. function removeInterceptorHook(interceptors, interceptor) {
  503. if (!interceptors || !interceptor) {
  504. return;
  505. }
  506. Object.keys(interceptor).forEach((name) => {
  507. const hooks = interceptors[name];
  508. const hook = interceptor[name];
  509. if (isArray(hooks) && isFunction(hook)) {
  510. remove(hooks, hook);
  511. }
  512. });
  513. }
  514. function mergeHook(parentVal, childVal) {
  515. const res = childVal
  516. ? parentVal
  517. ? parentVal.concat(childVal)
  518. : isArray(childVal)
  519. ? childVal
  520. : [childVal]
  521. : parentVal;
  522. return res ? dedupeHooks(res) : res;
  523. }
  524. function dedupeHooks(hooks) {
  525. const res = [];
  526. for (let i = 0; i < hooks.length; i++) {
  527. if (res.indexOf(hooks[i]) === -1) {
  528. res.push(hooks[i]);
  529. }
  530. }
  531. return res;
  532. }
  533. const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
  534. if (isString(method) && isPlainObject(interceptor)) {
  535. mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
  536. }
  537. else if (isPlainObject(method)) {
  538. mergeInterceptorHook(globalInterceptors, method);
  539. }
  540. }, AddInterceptorProtocol);
  541. const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
  542. if (isString(method)) {
  543. if (isPlainObject(interceptor)) {
  544. removeInterceptorHook(scopedInterceptors[method], interceptor);
  545. }
  546. else {
  547. delete scopedInterceptors[method];
  548. }
  549. }
  550. else if (isPlainObject(method)) {
  551. removeInterceptorHook(globalInterceptors, method);
  552. }
  553. }, RemoveInterceptorProtocol);
  554. const interceptors = {};
  555. const API_ON = '$on';
  556. const OnProtocol = [
  557. {
  558. name: 'event',
  559. type: String,
  560. required: true,
  561. },
  562. {
  563. name: 'callback',
  564. type: Function,
  565. required: true,
  566. },
  567. ];
  568. const API_ONCE = '$once';
  569. const OnceProtocol = OnProtocol;
  570. const API_OFF = '$off';
  571. const OffProtocol = [
  572. {
  573. name: 'event',
  574. type: [String, Array],
  575. },
  576. {
  577. name: 'callback',
  578. type: Function,
  579. },
  580. ];
  581. const API_EMIT = '$emit';
  582. const EmitProtocol = [
  583. {
  584. name: 'event',
  585. type: String,
  586. required: true,
  587. },
  588. ];
  589. const emitter = new Emitter();
  590. const $on = defineSyncApi(API_ON, (name, callback) => {
  591. emitter.on(name, callback);
  592. return () => emitter.off(name, callback);
  593. }, OnProtocol);
  594. const $once = defineSyncApi(API_ONCE, (name, callback) => {
  595. emitter.once(name, callback);
  596. return () => emitter.off(name, callback);
  597. }, OnceProtocol);
  598. const $off = defineSyncApi(API_OFF, (name, callback) => {
  599. if (!name) {
  600. emitter.e = {};
  601. return;
  602. }
  603. if (!isArray(name))
  604. name = [name];
  605. name.forEach((n) => emitter.off(n, callback));
  606. }, OffProtocol);
  607. const $emit = defineSyncApi(API_EMIT, (name, ...args) => {
  608. emitter.emit(name, ...args);
  609. }, EmitProtocol);
  610. let cid;
  611. let cidErrMsg;
  612. let enabled;
  613. function normalizePushMessage(message) {
  614. try {
  615. return JSON.parse(message);
  616. }
  617. catch (e) { }
  618. return message;
  619. }
  620. /**
  621. * @private
  622. * @param args
  623. */
  624. function invokePushCallback(args) {
  625. if (args.type === 'enabled') {
  626. enabled = true;
  627. }
  628. else if (args.type === 'clientId') {
  629. cid = args.cid;
  630. cidErrMsg = args.errMsg;
  631. invokeGetPushCidCallbacks(cid, args.errMsg);
  632. }
  633. else if (args.type === 'pushMsg') {
  634. const message = {
  635. type: 'receive',
  636. data: normalizePushMessage(args.message),
  637. };
  638. for (let i = 0; i < onPushMessageCallbacks.length; i++) {
  639. const callback = onPushMessageCallbacks[i];
  640. callback(message);
  641. // 该消息已被阻止
  642. if (message.stopped) {
  643. break;
  644. }
  645. }
  646. }
  647. else if (args.type === 'click') {
  648. onPushMessageCallbacks.forEach((callback) => {
  649. callback({
  650. type: 'click',
  651. data: normalizePushMessage(args.message),
  652. });
  653. });
  654. }
  655. }
  656. const getPushCidCallbacks = [];
  657. function invokeGetPushCidCallbacks(cid, errMsg) {
  658. getPushCidCallbacks.forEach((callback) => {
  659. callback(cid, errMsg);
  660. });
  661. getPushCidCallbacks.length = 0;
  662. }
  663. const API_GET_PUSH_CLIENT_ID = 'getPushClientId';
  664. const getPushClientId = defineAsyncApi(API_GET_PUSH_CLIENT_ID, (_, { resolve, reject }) => {
  665. Promise.resolve().then(() => {
  666. if (typeof enabled === 'undefined') {
  667. enabled = false;
  668. cid = '';
  669. cidErrMsg = 'uniPush is not enabled';
  670. }
  671. getPushCidCallbacks.push((cid, errMsg) => {
  672. if (cid) {
  673. resolve({ cid });
  674. }
  675. else {
  676. reject(errMsg);
  677. }
  678. });
  679. if (typeof cid !== 'undefined') {
  680. invokeGetPushCidCallbacks(cid, cidErrMsg);
  681. }
  682. });
  683. });
  684. const onPushMessageCallbacks = [];
  685. // 不使用 defineOnApi 实现,是因为 defineOnApi 依赖 UniServiceJSBridge ,该对象目前在小程序上未提供,故简单实现
  686. const onPushMessage = (fn) => {
  687. if (onPushMessageCallbacks.indexOf(fn) === -1) {
  688. onPushMessageCallbacks.push(fn);
  689. }
  690. };
  691. const offPushMessage = (fn) => {
  692. if (!fn) {
  693. onPushMessageCallbacks.length = 0;
  694. }
  695. else {
  696. const index = onPushMessageCallbacks.indexOf(fn);
  697. if (index > -1) {
  698. onPushMessageCallbacks.splice(index, 1);
  699. }
  700. }
  701. };
  702. const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|requireGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64|getDeviceInfo|getAppBaseInfo|getWindowInfo|getSystemSetting|getAppAuthorizeSetting/;
  703. const CONTEXT_API_RE = /^create|Manager$/;
  704. // Context例外情况
  705. const CONTEXT_API_RE_EXC = ['createBLEConnection'];
  706. // 同步例外情况
  707. const ASYNC_API = ['createBLEConnection'];
  708. const CALLBACK_API_RE = /^on|^off/;
  709. function isContextApi(name) {
  710. return CONTEXT_API_RE.test(name) && CONTEXT_API_RE_EXC.indexOf(name) === -1;
  711. }
  712. function isSyncApi(name) {
  713. return SYNC_API_RE.test(name) && ASYNC_API.indexOf(name) === -1;
  714. }
  715. function isCallbackApi(name) {
  716. return CALLBACK_API_RE.test(name) && name !== 'onPush';
  717. }
  718. function shouldPromise(name) {
  719. if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
  720. return false;
  721. }
  722. return true;
  723. }
  724. /* eslint-disable no-extend-native */
  725. if (!Promise.prototype.finally) {
  726. Promise.prototype.finally = function (onfinally) {
  727. const promise = this.constructor;
  728. return this.then((value) => promise.resolve(onfinally && onfinally()).then(() => value), (reason) => promise.resolve(onfinally && onfinally()).then(() => {
  729. throw reason;
  730. }));
  731. };
  732. }
  733. function promisify(name, api) {
  734. if (!shouldPromise(name)) {
  735. return api;
  736. }
  737. if (!isFunction(api)) {
  738. return api;
  739. }
  740. return function promiseApi(options = {}, ...rest) {
  741. if (isFunction(options.success) ||
  742. isFunction(options.fail) ||
  743. isFunction(options.complete)) {
  744. return wrapperReturnValue(name, invokeApi(name, api, options, rest));
  745. }
  746. return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
  747. invokeApi(name, api, extend({}, options, {
  748. success: resolve,
  749. fail: reject,
  750. }), rest);
  751. })));
  752. };
  753. }
  754. const CALLBACKS = ['success', 'fail', 'cancel', 'complete'];
  755. function initWrapper(protocols) {
  756. function processCallback(methodName, method, returnValue) {
  757. return function (res) {
  758. return method(processReturnValue(methodName, res, returnValue));
  759. };
  760. }
  761. function processArgs(methodName, fromArgs, argsOption = {}, returnValue = {}, keepFromArgs = false) {
  762. if (isPlainObject(fromArgs)) {
  763. // 一般 api 的参数解析
  764. const toArgs = (keepFromArgs === true ? fromArgs : {}); // returnValue 为 false 时,说明是格式化返回值,直接在返回值对象上修改赋值
  765. if (isFunction(argsOption)) {
  766. argsOption = argsOption(fromArgs, toArgs) || {};
  767. }
  768. for (const key in fromArgs) {
  769. if (hasOwn(argsOption, key)) {
  770. let keyOption = argsOption[key];
  771. if (isFunction(keyOption)) {
  772. keyOption = keyOption(fromArgs[key], fromArgs, toArgs);
  773. }
  774. if (!keyOption) {
  775. // 不支持的参数
  776. console.warn(`快应用(Webview)版 ${methodName} 暂不支持 ${key}`);
  777. }
  778. else if (isString(keyOption)) {
  779. // 重写参数 key
  780. toArgs[keyOption] = fromArgs[key];
  781. }
  782. else if (isPlainObject(keyOption)) {
  783. // {name:newName,value:value}可重新指定参数 key:value
  784. toArgs[keyOption.name ? keyOption.name : key] = keyOption.value;
  785. }
  786. }
  787. else if (CALLBACKS.indexOf(key) !== -1) {
  788. const callback = fromArgs[key];
  789. if (isFunction(callback)) {
  790. toArgs[key] = processCallback(methodName, callback, returnValue);
  791. }
  792. }
  793. else {
  794. if (!keepFromArgs && !hasOwn(toArgs, key)) {
  795. toArgs[key] = fromArgs[key];
  796. }
  797. }
  798. }
  799. return toArgs;
  800. }
  801. else if (isFunction(fromArgs)) {
  802. fromArgs = processCallback(methodName, fromArgs, returnValue);
  803. }
  804. return fromArgs;
  805. }
  806. function processReturnValue(methodName, res, returnValue, keepReturnValue = false) {
  807. if (isFunction(protocols.returnValue)) {
  808. // 处理通用 returnValue
  809. res = protocols.returnValue(methodName, res);
  810. }
  811. return processArgs(methodName, res, returnValue, {}, keepReturnValue);
  812. }
  813. return function wrapper(methodName, method) {
  814. if (!hasOwn(protocols, methodName)) {
  815. return method;
  816. }
  817. const protocol = protocols[methodName];
  818. if (!protocol) {
  819. // 暂不支持的 api
  820. return function () {
  821. console.error(`快应用(Webview)版 暂不支持${methodName}`);
  822. };
  823. }
  824. return function (arg1, arg2) {
  825. // 目前 api 最多两个参数
  826. let options = protocol;
  827. if (isFunction(protocol)) {
  828. options = protocol(arg1);
  829. }
  830. arg1 = processArgs(methodName, arg1, options.args, options.returnValue);
  831. const args = [arg1];
  832. if (typeof arg2 !== 'undefined') {
  833. args.push(arg2);
  834. }
  835. const returnValue = qa[options.name || methodName].apply(qa, args);
  836. if (isSyncApi(methodName)) {
  837. // 同步 api
  838. return processReturnValue(methodName, returnValue, options.returnValue, isContextApi(methodName));
  839. }
  840. return returnValue;
  841. };
  842. };
  843. }
  844. const getLocale = () => {
  845. // 优先使用 $locale
  846. const app = isFunction(getApp) && getApp({ allowDefault: true });
  847. if (app && app.$vm) {
  848. return app.$vm.$locale;
  849. }
  850. return normalizeLocale(qa.getSystemInfoSync().language) || LOCALE_EN;
  851. };
  852. const setLocale = (locale) => {
  853. const app = isFunction(getApp) && getApp();
  854. if (!app) {
  855. return false;
  856. }
  857. const oldLocale = app.$vm.$locale;
  858. if (oldLocale !== locale) {
  859. app.$vm.$locale = locale;
  860. onLocaleChangeCallbacks.forEach((fn) => fn({ locale }));
  861. return true;
  862. }
  863. return false;
  864. };
  865. const onLocaleChangeCallbacks = [];
  866. const onLocaleChange = (fn) => {
  867. if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
  868. onLocaleChangeCallbacks.push(fn);
  869. }
  870. };
  871. if (typeof global !== 'undefined') {
  872. global.getLocale = getLocale;
  873. }
  874. const UUID_KEY = '__DC_STAT_UUID';
  875. let deviceId;
  876. function useDeviceId(global = qa) {
  877. return function addDeviceId(_, toRes) {
  878. deviceId = deviceId || global.getStorageSync(UUID_KEY);
  879. if (!deviceId) {
  880. deviceId = Date.now() + '' + Math.floor(Math.random() * 1e7);
  881. qa.setStorage({
  882. key: UUID_KEY,
  883. data: deviceId,
  884. });
  885. }
  886. toRes.deviceId = deviceId;
  887. };
  888. }
  889. function addSafeAreaInsets(fromRes, toRes) {
  890. if (fromRes.safeArea) {
  891. const safeArea = fromRes.safeArea;
  892. toRes.safeAreaInsets = {
  893. top: safeArea.top,
  894. left: safeArea.left,
  895. right: fromRes.windowWidth - safeArea.right,
  896. bottom: fromRes.screenHeight - safeArea.bottom,
  897. };
  898. }
  899. }
  900. function populateParameters(fromRes, toRes) {
  901. const { brand = '', model = '', system = '', language = '', theme, version, platform, fontSizeSetting, SDKVersion, pixelRatio, deviceOrientation, } = fromRes;
  902. // const isQuickApp = "quickapp-webview".indexOf('quickapp-webview') !== -1
  903. // osName osVersion
  904. let osName = '';
  905. let osVersion = '';
  906. {
  907. osName = system.split(' ')[0] || '';
  908. osVersion = system.split(' ')[1] || '';
  909. }
  910. let hostVersion = version;
  911. // deviceType
  912. let deviceType = getGetDeviceType(fromRes, model);
  913. // deviceModel
  914. let deviceBrand = getDeviceBrand(brand);
  915. // hostName
  916. let _hostName = getHostName(fromRes);
  917. // deviceOrientation
  918. let _deviceOrientation = deviceOrientation; // 仅 微信 百度 支持
  919. // devicePixelRatio
  920. let _devicePixelRatio = pixelRatio;
  921. // SDKVersion
  922. let _SDKVersion = SDKVersion;
  923. // hostLanguage
  924. const hostLanguage = language.replace(/_/g, '-');
  925. // wx.getAccountInfoSync
  926. const parameters = {
  927. appId: process.env.UNI_APP_ID,
  928. appName: process.env.UNI_APP_NAME,
  929. appVersion: process.env.UNI_APP_VERSION_NAME,
  930. appVersionCode: process.env.UNI_APP_VERSION_CODE,
  931. appLanguage: getAppLanguage(hostLanguage),
  932. uniCompileVersion: process.env.UNI_COMPILER_VERSION,
  933. uniRuntimeVersion: process.env.UNI_COMPILER_VERSION,
  934. uniPlatform: process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM,
  935. deviceBrand,
  936. deviceModel: model,
  937. deviceType,
  938. devicePixelRatio: _devicePixelRatio,
  939. deviceOrientation: _deviceOrientation,
  940. osName: osName.toLocaleLowerCase(),
  941. osVersion,
  942. hostTheme: theme,
  943. hostVersion,
  944. hostLanguage,
  945. hostName: _hostName,
  946. hostSDKVersion: _SDKVersion,
  947. hostFontSizeSetting: fontSizeSetting,
  948. windowTop: 0,
  949. windowBottom: 0,
  950. // TODO
  951. osLanguage: undefined,
  952. osTheme: undefined,
  953. ua: undefined,
  954. hostPackageName: undefined,
  955. browserName: undefined,
  956. browserVersion: undefined,
  957. };
  958. extend(toRes, parameters);
  959. }
  960. function getGetDeviceType(fromRes, model) {
  961. // deviceType
  962. let deviceType = fromRes.deviceType || 'phone';
  963. {
  964. const deviceTypeMaps = {
  965. ipad: 'pad',
  966. windows: 'pc',
  967. mac: 'pc',
  968. };
  969. const deviceTypeMapsKeys = Object.keys(deviceTypeMaps);
  970. const _model = model.toLocaleLowerCase();
  971. for (let index = 0; index < deviceTypeMapsKeys.length; index++) {
  972. const _m = deviceTypeMapsKeys[index];
  973. if (_model.indexOf(_m) !== -1) {
  974. deviceType = deviceTypeMaps[_m];
  975. break;
  976. }
  977. }
  978. }
  979. return deviceType;
  980. }
  981. function getDeviceBrand(brand) {
  982. // deviceModel
  983. let deviceBrand = brand;
  984. if (deviceBrand) {
  985. deviceBrand = deviceBrand.toLocaleLowerCase();
  986. }
  987. return deviceBrand;
  988. }
  989. function getAppLanguage(defaultLanguage) {
  990. return getLocale ? getLocale() : defaultLanguage;
  991. }
  992. function getHostName(fromRes) {
  993. const _platform = "quickapp-webview".split('-')[1];
  994. let _hostName = fromRes.hostName || _platform; // mp-jd
  995. return _hostName;
  996. }
  997. const getSystemInfo = {
  998. returnValue: (fromRes, toRes) => {
  999. addSafeAreaInsets(fromRes, toRes);
  1000. useDeviceId()(fromRes, toRes);
  1001. populateParameters(fromRes, toRes);
  1002. },
  1003. };
  1004. const getSystemInfoSync = getSystemInfo;
  1005. const redirectTo = {};
  1006. const previewImage = {
  1007. args(fromArgs, toArgs) {
  1008. let currentIndex = parseInt(fromArgs.current);
  1009. if (isNaN(currentIndex)) {
  1010. return;
  1011. }
  1012. const urls = fromArgs.urls;
  1013. if (!isArray(urls)) {
  1014. return;
  1015. }
  1016. const len = urls.length;
  1017. if (!len) {
  1018. return;
  1019. }
  1020. if (currentIndex < 0) {
  1021. currentIndex = 0;
  1022. }
  1023. else if (currentIndex >= len) {
  1024. currentIndex = len - 1;
  1025. }
  1026. if (currentIndex > 0) {
  1027. toArgs.current = urls[currentIndex];
  1028. toArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true);
  1029. }
  1030. else {
  1031. toArgs.current = urls[0];
  1032. }
  1033. return {
  1034. indicator: false,
  1035. loop: false,
  1036. };
  1037. },
  1038. };
  1039. const eventChannels = {};
  1040. let id = 0;
  1041. function initEventChannel(events, cache = true) {
  1042. id++;
  1043. const eventChannel = new qa.EventChannel(id, events);
  1044. if (cache) {
  1045. eventChannels[id] = eventChannel;
  1046. }
  1047. return eventChannel;
  1048. }
  1049. function getEventChannel(id) {
  1050. const eventChannel = eventChannels[id];
  1051. delete eventChannels[id];
  1052. return eventChannel;
  1053. }
  1054. const navigateTo$1 = () => {
  1055. let eventChannel;
  1056. return {
  1057. args(fromArgs) {
  1058. eventChannel = initEventChannel(fromArgs.events);
  1059. if (fromArgs.url) {
  1060. fromArgs.url =
  1061. fromArgs.url +
  1062. (fromArgs.url.indexOf('?') === -1 ? '?' : '&') +
  1063. '__id__=' +
  1064. eventChannel.id;
  1065. }
  1066. },
  1067. returnValue(fromRes) {
  1068. fromRes.eventChannel = eventChannel;
  1069. },
  1070. };
  1071. };
  1072. const baseApis = {
  1073. $on,
  1074. $off,
  1075. $once,
  1076. $emit,
  1077. upx2px,
  1078. interceptors,
  1079. addInterceptor,
  1080. removeInterceptor,
  1081. onCreateVueApp,
  1082. invokeCreateVueAppHook,
  1083. getLocale,
  1084. setLocale,
  1085. onLocaleChange,
  1086. getPushClientId,
  1087. onPushMessage,
  1088. offPushMessage,
  1089. invokePushCallback,
  1090. };
  1091. function initUni(api, protocols, platform = qa) {
  1092. const wrapper = initWrapper(protocols);
  1093. const UniProxyHandlers = {
  1094. get(target, key) {
  1095. if (hasOwn(target, key)) {
  1096. return target[key];
  1097. }
  1098. if (hasOwn(api, key)) {
  1099. return promisify(key, api[key]);
  1100. }
  1101. if (hasOwn(baseApis, key)) {
  1102. return promisify(key, baseApis[key]);
  1103. }
  1104. // event-api
  1105. // provider-api?
  1106. return promisify(key, wrapper(key, platform[key]));
  1107. },
  1108. };
  1109. // 处理 api mp 打包后为不同js,getEventChannel 无法共享问题
  1110. {
  1111. platform.getEventChannel = getEventChannel;
  1112. }
  1113. return new Proxy({}, UniProxyHandlers);
  1114. }
  1115. function initGetProvider(providers) {
  1116. return function getProvider({ service, success, fail, complete, }) {
  1117. let res;
  1118. if (providers[service]) {
  1119. res = {
  1120. errMsg: 'getProvider:ok',
  1121. service,
  1122. provider: providers[service],
  1123. };
  1124. isFunction(success) && success(res);
  1125. }
  1126. else {
  1127. res = {
  1128. errMsg: 'getProvider:fail:服务[' + service + ']不存在',
  1129. };
  1130. isFunction(fail) && fail(res);
  1131. }
  1132. isFunction(complete) && complete(res);
  1133. };
  1134. }
  1135. const providers = {
  1136. oauth: [],
  1137. share: [],
  1138. payment: [],
  1139. push: [],
  1140. };
  1141. if (qa.canIUse('getAccountProvider')) {
  1142. providers.oauth.push(qa.getAccountProvider());
  1143. }
  1144. if (qa.canIUse('getVendorPaymentProvider')) {
  1145. providers.payment.push(qa.getVendorPaymentProvider());
  1146. }
  1147. const getProvider = initGetProvider(providers);
  1148. var shims = /*#__PURE__*/Object.freeze({
  1149. __proto__: null,
  1150. getProvider: getProvider
  1151. });
  1152. const navigateTo = navigateTo$1();
  1153. var protocols = /*#__PURE__*/Object.freeze({
  1154. __proto__: null,
  1155. getSystemInfo: getSystemInfo,
  1156. getSystemInfoSync: getSystemInfoSync,
  1157. navigateTo: navigateTo,
  1158. previewImage: previewImage,
  1159. redirectTo: redirectTo
  1160. });
  1161. var index = initUni(shims, protocols);
  1162. export { index as default };