uni.api.esm.js 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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 jd.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(`京东小程序 ${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(`京东小程序 暂不支持${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 = jd[options.name || methodName].apply(jd, 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(jd.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 = jd) {
  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. jd.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 = "mp-jd".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. {
  912. hostVersion = fromRes.hostVersionName;
  913. }
  914. // deviceType
  915. let deviceType = getGetDeviceType(fromRes, model);
  916. // deviceModel
  917. let deviceBrand = getDeviceBrand(brand);
  918. // hostName
  919. let _hostName = getHostName(fromRes);
  920. // deviceOrientation
  921. let _deviceOrientation = deviceOrientation; // 仅 微信 百度 支持
  922. // devicePixelRatio
  923. let _devicePixelRatio = pixelRatio;
  924. // SDKVersion
  925. let _SDKVersion = SDKVersion;
  926. // hostLanguage
  927. const hostLanguage = language.replace(/_/g, '-');
  928. // wx.getAccountInfoSync
  929. const parameters = {
  930. appId: process.env.UNI_APP_ID,
  931. appName: process.env.UNI_APP_NAME,
  932. appVersion: process.env.UNI_APP_VERSION_NAME,
  933. appVersionCode: process.env.UNI_APP_VERSION_CODE,
  934. appLanguage: getAppLanguage(hostLanguage),
  935. uniCompileVersion: process.env.UNI_COMPILER_VERSION,
  936. uniRuntimeVersion: process.env.UNI_COMPILER_VERSION,
  937. uniPlatform: process.env.UNI_SUB_PLATFORM || process.env.UNI_PLATFORM,
  938. deviceBrand,
  939. deviceModel: model,
  940. deviceType,
  941. devicePixelRatio: _devicePixelRatio,
  942. deviceOrientation: _deviceOrientation,
  943. osName: osName.toLocaleLowerCase(),
  944. osVersion,
  945. hostTheme: theme,
  946. hostVersion,
  947. hostLanguage,
  948. hostName: _hostName,
  949. hostSDKVersion: _SDKVersion,
  950. hostFontSizeSetting: fontSizeSetting,
  951. windowTop: 0,
  952. windowBottom: 0,
  953. // TODO
  954. osLanguage: undefined,
  955. osTheme: undefined,
  956. ua: undefined,
  957. hostPackageName: undefined,
  958. browserName: undefined,
  959. browserVersion: undefined,
  960. };
  961. extend(toRes, parameters);
  962. }
  963. function getGetDeviceType(fromRes, model) {
  964. // deviceType
  965. let deviceType = fromRes.deviceType || 'phone';
  966. {
  967. const deviceTypeMaps = {
  968. ipad: 'pad',
  969. windows: 'pc',
  970. mac: 'pc',
  971. };
  972. const deviceTypeMapsKeys = Object.keys(deviceTypeMaps);
  973. const _model = model.toLocaleLowerCase();
  974. for (let index = 0; index < deviceTypeMapsKeys.length; index++) {
  975. const _m = deviceTypeMapsKeys[index];
  976. if (_model.indexOf(_m) !== -1) {
  977. deviceType = deviceTypeMaps[_m];
  978. break;
  979. }
  980. }
  981. }
  982. return deviceType;
  983. }
  984. function getDeviceBrand(brand) {
  985. // deviceModel
  986. let deviceBrand = brand;
  987. if (deviceBrand) {
  988. deviceBrand = deviceBrand.toLocaleLowerCase();
  989. }
  990. return deviceBrand;
  991. }
  992. function getAppLanguage(defaultLanguage) {
  993. return getLocale ? getLocale() : defaultLanguage;
  994. }
  995. function getHostName(fromRes) {
  996. const _platform = "mp-jd".split('-')[1];
  997. let _hostName = fromRes.hostName || _platform; // mp-jd
  998. return _hostName;
  999. }
  1000. const getSystemInfo = {
  1001. returnValue: (fromRes, toRes) => {
  1002. addSafeAreaInsets(fromRes, toRes);
  1003. useDeviceId()(fromRes, toRes);
  1004. populateParameters(fromRes, toRes);
  1005. },
  1006. };
  1007. const getSystemInfoSync = getSystemInfo;
  1008. const redirectTo = {};
  1009. const previewImage = {
  1010. args(fromArgs, toArgs) {
  1011. let currentIndex = parseInt(fromArgs.current);
  1012. if (isNaN(currentIndex)) {
  1013. return;
  1014. }
  1015. const urls = fromArgs.urls;
  1016. if (!isArray(urls)) {
  1017. return;
  1018. }
  1019. const len = urls.length;
  1020. if (!len) {
  1021. return;
  1022. }
  1023. if (currentIndex < 0) {
  1024. currentIndex = 0;
  1025. }
  1026. else if (currentIndex >= len) {
  1027. currentIndex = len - 1;
  1028. }
  1029. if (currentIndex > 0) {
  1030. toArgs.current = urls[currentIndex];
  1031. toArgs.urls = urls.filter((item, index) => index < currentIndex ? item !== urls[currentIndex] : true);
  1032. }
  1033. else {
  1034. toArgs.current = urls[0];
  1035. }
  1036. return {
  1037. indicator: false,
  1038. loop: false,
  1039. };
  1040. },
  1041. };
  1042. const eventChannels = {};
  1043. let id = 0;
  1044. function initEventChannel(events, cache = true) {
  1045. id++;
  1046. const eventChannel = new jd.EventChannel(id, events);
  1047. if (cache) {
  1048. eventChannels[id] = eventChannel;
  1049. }
  1050. return eventChannel;
  1051. }
  1052. function getEventChannel(id) {
  1053. const eventChannel = eventChannels[id];
  1054. delete eventChannels[id];
  1055. return eventChannel;
  1056. }
  1057. const navigateTo$1 = () => {
  1058. let eventChannel;
  1059. return {
  1060. args(fromArgs) {
  1061. eventChannel = initEventChannel(fromArgs.events);
  1062. if (fromArgs.url) {
  1063. fromArgs.url =
  1064. fromArgs.url +
  1065. (fromArgs.url.indexOf('?') === -1 ? '?' : '&') +
  1066. '__id__=' +
  1067. eventChannel.id;
  1068. }
  1069. },
  1070. returnValue(fromRes) {
  1071. fromRes.eventChannel = eventChannel;
  1072. },
  1073. };
  1074. };
  1075. const baseApis = {
  1076. $on,
  1077. $off,
  1078. $once,
  1079. $emit,
  1080. upx2px,
  1081. interceptors,
  1082. addInterceptor,
  1083. removeInterceptor,
  1084. onCreateVueApp,
  1085. invokeCreateVueAppHook,
  1086. getLocale,
  1087. setLocale,
  1088. onLocaleChange,
  1089. getPushClientId,
  1090. onPushMessage,
  1091. offPushMessage,
  1092. invokePushCallback,
  1093. };
  1094. function initUni(api, protocols, platform = jd) {
  1095. const wrapper = initWrapper(protocols);
  1096. const UniProxyHandlers = {
  1097. get(target, key) {
  1098. if (hasOwn(target, key)) {
  1099. return target[key];
  1100. }
  1101. if (hasOwn(api, key)) {
  1102. return promisify(key, api[key]);
  1103. }
  1104. if (hasOwn(baseApis, key)) {
  1105. return promisify(key, baseApis[key]);
  1106. }
  1107. // event-api
  1108. // provider-api?
  1109. return promisify(key, wrapper(key, platform[key]));
  1110. },
  1111. };
  1112. // 处理 api mp 打包后为不同js,getEventChannel 无法共享问题
  1113. {
  1114. platform.getEventChannel = getEventChannel;
  1115. }
  1116. return new Proxy({}, UniProxyHandlers);
  1117. }
  1118. function initGetProvider(providers) {
  1119. return function getProvider({ service, success, fail, complete, }) {
  1120. let res;
  1121. if (providers[service]) {
  1122. res = {
  1123. errMsg: 'getProvider:ok',
  1124. service,
  1125. provider: providers[service],
  1126. };
  1127. isFunction(success) && success(res);
  1128. }
  1129. else {
  1130. res = {
  1131. errMsg: 'getProvider:fail:服务[' + service + ']不存在',
  1132. };
  1133. isFunction(fail) && fail(res);
  1134. }
  1135. isFunction(complete) && complete(res);
  1136. };
  1137. }
  1138. const getProvider = initGetProvider({
  1139. oauth: ['jd'],
  1140. share: ['jd'],
  1141. payment: ['jd'],
  1142. push: ['jd'],
  1143. });
  1144. var shims = /*#__PURE__*/Object.freeze({
  1145. __proto__: null,
  1146. getProvider: getProvider
  1147. });
  1148. const navigateTo = navigateTo$1();
  1149. var protocols = /*#__PURE__*/Object.freeze({
  1150. __proto__: null,
  1151. getSystemInfo: getSystemInfo,
  1152. getSystemInfoSync: getSystemInfoSync,
  1153. navigateTo: navigateTo,
  1154. previewImage: previewImage,
  1155. redirectTo: redirectTo
  1156. });
  1157. var index = initUni(shims, protocols);
  1158. export { index as default };