uni.api.esm.js 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200
  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 ks.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 = ks[options.name || methodName].apply(ks, 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(ks.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 = ks) {
  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. ks.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-kuaishou".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 = "mp-kuaishou".split('-')[1];
  994. let _hostName = fromRes.hostName || _platform; // mp-jd
  995. {
  996. _hostName = fromRes.host;
  997. }
  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 ks.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 = ks) {
  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: ['kuaishou'],
  1140. share: ['kuaishou'],
  1141. payment: ['kuaishoupay'],
  1142. push: ['kuaishou'],
  1143. });
  1144. var shims = /*#__PURE__*/Object.freeze({
  1145. __proto__: null,
  1146. getProvider: getProvider
  1147. });
  1148. const requestPayment = {
  1149. name: ks.pay ? 'pay' : 'requestPayment',
  1150. args(fromArgs, toArgs) {
  1151. if (typeof fromArgs === 'object') {
  1152. // ks.pay 服务类型 id(固定值为 '1')
  1153. if (ks.pay && !fromArgs.serviceId)
  1154. toArgs.serviceId = '1';
  1155. }
  1156. },
  1157. };
  1158. const navigateTo = navigateTo$1();
  1159. var protocols = /*#__PURE__*/Object.freeze({
  1160. __proto__: null,
  1161. getSystemInfo: getSystemInfo,
  1162. getSystemInfoSync: getSystemInfoSync,
  1163. navigateTo: navigateTo,
  1164. previewImage: previewImage,
  1165. redirectTo: redirectTo,
  1166. requestPayment: requestPayment
  1167. });
  1168. var index = initUni(shims, protocols);
  1169. export { index as default };