@dcloudio/uni-mp-baidu 2.0.0 → 2.0.1-32920211122002

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,75 +1,197 @@
1
- import { isArray, isPromise, isFunction, isPlainObject, hasOwn, isString } from '@vue/shared';
1
+ import { isArray, hasOwn, isString, isPlainObject, isObject, capitalize, toRawType, makeMap, isPromise, isFunction, extend } from '@vue/shared';
2
+ import { injectHook } from 'vue';
2
3
 
3
- const API_TYPE_SYNC = 1;
4
- function validateProtocol(_name, _args, _protocol) {
5
- return true;
4
+ //App
5
+ const ON_LAUNCH = 'onLaunch';
6
+
7
+ const eventChannels = {};
8
+ const eventChannelStack = [];
9
+ let id = 0;
10
+ function initEventChannel(events, cache = true) {
11
+ id++;
12
+ const eventChannel = new swan.EventChannel(id, events);
13
+ if (cache) {
14
+ eventChannels[id] = eventChannel;
15
+ eventChannelStack.push(eventChannel);
16
+ }
17
+ return eventChannel;
6
18
  }
7
- function formatApiArgs(args, options) {
8
- if (!options) {
9
- return args;
19
+ function getEventChannel(id) {
20
+ if (id) {
21
+ const eventChannel = eventChannels[id];
22
+ delete eventChannels[id];
23
+ return eventChannel;
10
24
  }
25
+ return eventChannelStack.shift();
11
26
  }
12
- function createApi({ type, name, options }, fn, protocol) {
13
- return function (...args) {
14
- if (type === API_TYPE_SYNC) {
15
- if (!((process.env.NODE_ENV !== 'production') && protocol && !validateProtocol())) {
16
- return fn.apply(null, formatApiArgs(args, options));
17
- }
18
- }
19
- };
20
- }
27
+ const navigateTo = {
28
+ args(fromArgs) {
29
+ const id = initEventChannel(fromArgs.events).id;
30
+ if (fromArgs.url) {
31
+ fromArgs.url =
32
+ fromArgs.url +
33
+ (fromArgs.url.indexOf('?') === -1 ? '?' : '&') +
34
+ '__id__=' +
35
+ id;
36
+ }
37
+ },
38
+ returnValue(fromRes) {
39
+ fromRes.eventChannel = getEventChannel();
40
+ },
41
+ };
21
42
 
22
- const Upx2pxProtocol = [
23
- {
24
- name: 'upx',
25
- type: [Number, String],
26
- required: true
43
+ swan.appLaunchHooks = [];
44
+ function onAppLaunch(hook) {
45
+ const app = getApp({ allowDefault: true });
46
+ if (app && app.$vm) {
47
+ return injectHook(ON_LAUNCH, hook, app.$vm.$);
27
48
  }
28
- ];
49
+ swan.appLaunchHooks.push(hook);
50
+ }
29
51
 
30
- const EPS = 1e-4;
31
- const BASE_DEVICE_WIDTH = 750;
32
- let isIOS = false;
33
- let deviceWidth = 0;
34
- let deviceDPR = 0;
35
- function checkDeviceWidth() {
36
- const { platform, pixelRatio, windowWidth } = swan.getSystemInfoSync();
37
- deviceWidth = windowWidth;
38
- deviceDPR = pixelRatio;
39
- isIOS = platform === 'ios';
52
+ function getBaseSystemInfo() {
53
+ return swan.getSystemInfoSync()
54
+ }
55
+
56
+ function validateProtocolFail(name, msg) {
57
+ console.warn(`${name}: ${msg}`);
40
58
  }
41
- const upx2px = createApi({ type: API_TYPE_SYNC, name: 'upx2px' }, (number, newDeviceWidth) => {
42
- if (deviceWidth === 0) {
43
- checkDeviceWidth();
59
+ function validateProtocol(name, data, protocol, onFail) {
60
+ if (!onFail) {
61
+ onFail = validateProtocolFail;
44
62
  }
45
- number = Number(number);
46
- if (number === 0) {
47
- return 0;
63
+ for (const key in protocol) {
64
+ const errMsg = validateProp(key, data[key], protocol[key], !hasOwn(data, key));
65
+ if (isString(errMsg)) {
66
+ onFail(name, errMsg);
67
+ }
48
68
  }
49
- let result = (number / BASE_DEVICE_WIDTH) * (newDeviceWidth || deviceWidth);
50
- if (result < 0) {
51
- result = -result;
69
+ }
70
+ function validateProtocols(name, args, protocol, onFail) {
71
+ if (!protocol) {
72
+ return;
52
73
  }
53
- result = Math.floor(result + EPS);
54
- if (result === 0) {
55
- if (deviceDPR === 1 || !isIOS) {
56
- result = 1;
74
+ if (!isArray(protocol)) {
75
+ return validateProtocol(name, args[0] || Object.create(null), protocol, onFail);
76
+ }
77
+ const len = protocol.length;
78
+ const argsLen = args.length;
79
+ for (let i = 0; i < len; i++) {
80
+ const opts = protocol[i];
81
+ const data = Object.create(null);
82
+ if (argsLen > i) {
83
+ data[opts.name] = args[i];
57
84
  }
58
- else {
59
- result = 0.5;
85
+ validateProtocol(name, data, { [opts.name]: opts }, onFail);
86
+ }
87
+ }
88
+ function validateProp(name, value, prop, isAbsent) {
89
+ if (!isPlainObject(prop)) {
90
+ prop = { type: prop };
91
+ }
92
+ const { type, required, validator } = prop;
93
+ // required!
94
+ if (required && isAbsent) {
95
+ return 'Missing required args: "' + name + '"';
96
+ }
97
+ // missing but optional
98
+ if (value == null && !required) {
99
+ return;
100
+ }
101
+ // type check
102
+ if (type != null) {
103
+ let isValid = false;
104
+ const types = isArray(type) ? type : [type];
105
+ const expectedTypes = [];
106
+ // value is valid as long as one of the specified types match
107
+ for (let i = 0; i < types.length && !isValid; i++) {
108
+ const { valid, expectedType } = assertType(value, types[i]);
109
+ expectedTypes.push(expectedType || '');
110
+ isValid = valid;
111
+ }
112
+ if (!isValid) {
113
+ return getInvalidTypeMessage(name, value, expectedTypes);
60
114
  }
61
115
  }
62
- return number < 0 ? -result : result;
63
- }, Upx2pxProtocol);
116
+ // custom validator
117
+ if (validator) {
118
+ return validator(value);
119
+ }
120
+ }
121
+ const isSimpleType = /*#__PURE__*/ makeMap('String,Number,Boolean,Function,Symbol');
122
+ function assertType(value, type) {
123
+ let valid;
124
+ const expectedType = getType(type);
125
+ if (isSimpleType(expectedType)) {
126
+ const t = typeof value;
127
+ valid = t === expectedType.toLowerCase();
128
+ // for primitive wrapper objects
129
+ if (!valid && t === 'object') {
130
+ valid = value instanceof type;
131
+ }
132
+ }
133
+ else if (expectedType === 'Object') {
134
+ valid = isObject(value);
135
+ }
136
+ else if (expectedType === 'Array') {
137
+ valid = isArray(value);
138
+ }
139
+ else {
140
+ {
141
+ valid = value instanceof type;
142
+ }
143
+ }
144
+ return {
145
+ valid,
146
+ expectedType,
147
+ };
148
+ }
149
+ function getInvalidTypeMessage(name, value, expectedTypes) {
150
+ let message = `Invalid args: type check failed for args "${name}".` +
151
+ ` Expected ${expectedTypes.map(capitalize).join(', ')}`;
152
+ const expectedType = expectedTypes[0];
153
+ const receivedType = toRawType(value);
154
+ const expectedValue = styleValue(value, expectedType);
155
+ const receivedValue = styleValue(value, receivedType);
156
+ // check if we need to specify expected value
157
+ if (expectedTypes.length === 1 &&
158
+ isExplicable(expectedType) &&
159
+ !isBoolean(expectedType, receivedType)) {
160
+ message += ` with value ${expectedValue}`;
161
+ }
162
+ message += `, got ${receivedType} `;
163
+ // check if we need to specify received value
164
+ if (isExplicable(receivedType)) {
165
+ message += `with value ${receivedValue}.`;
166
+ }
167
+ return message;
168
+ }
169
+ function getType(ctor) {
170
+ const match = ctor && ctor.toString().match(/^\s*function (\w+)/);
171
+ return match ? match[1] : '';
172
+ }
173
+ function styleValue(value, type) {
174
+ if (type === 'String') {
175
+ return `"${value}"`;
176
+ }
177
+ else if (type === 'Number') {
178
+ return `${Number(value)}`;
179
+ }
180
+ else {
181
+ return `${value}`;
182
+ }
183
+ }
184
+ function isExplicable(type) {
185
+ const explicitTypes = ['string', 'number', 'boolean'];
186
+ return explicitTypes.some((elem) => type.toLowerCase() === elem);
187
+ }
188
+ function isBoolean(...args) {
189
+ return args.some((elem) => elem.toLowerCase() === 'boolean');
190
+ }
64
191
 
65
- var HOOKS;
66
- (function (HOOKS) {
67
- HOOKS["INVOKE"] = "invoke";
68
- HOOKS["SUCCESS"] = "success";
69
- HOOKS["FAIL"] = "fail";
70
- HOOKS["COMPLETE"] = "complete";
71
- HOOKS["RETURN_VALUE"] = "returnValue";
72
- })(HOOKS || (HOOKS = {}));
192
+ const HOOK_SUCCESS = 'success';
193
+ const HOOK_FAIL = 'fail';
194
+ const HOOK_COMPLETE = 'complete';
73
195
  const globalInterceptors = {};
74
196
  const scopedInterceptors = {};
75
197
  function wrapperHook(hook) {
@@ -92,7 +214,7 @@ function queue(hooks, data) {
92
214
  if (res === false) {
93
215
  return {
94
216
  then() { },
95
- catch() { }
217
+ catch() { },
96
218
  };
97
219
  }
98
220
  }
@@ -101,11 +223,11 @@ function queue(hooks, data) {
101
223
  then(callback) {
102
224
  return callback(data);
103
225
  },
104
- catch() { }
226
+ catch() { },
105
227
  });
106
228
  }
107
229
  function wrapperOptions(interceptors, options = {}) {
108
- [HOOKS.SUCCESS, HOOKS.FAIL, HOOKS.COMPLETE].forEach(name => {
230
+ [HOOK_SUCCESS, HOOK_FAIL, HOOK_COMPLETE].forEach((name) => {
109
231
  const hooks = interceptors[name];
110
232
  if (!isArray(hooks)) {
111
233
  return;
@@ -128,21 +250,21 @@ function wrapperReturnValue(method, returnValue) {
128
250
  if (interceptor && isArray(interceptor.returnValue)) {
129
251
  returnValueHooks.push(...interceptor.returnValue);
130
252
  }
131
- returnValueHooks.forEach(hook => {
253
+ returnValueHooks.forEach((hook) => {
132
254
  returnValue = hook(returnValue) || returnValue;
133
255
  });
134
256
  return returnValue;
135
257
  }
136
258
  function getApiInterceptorHooks(method) {
137
259
  const interceptor = Object.create(null);
138
- Object.keys(globalInterceptors).forEach(hook => {
260
+ Object.keys(globalInterceptors).forEach((hook) => {
139
261
  if (hook !== 'returnValue') {
140
262
  interceptor[hook] = globalInterceptors[hook].slice();
141
263
  }
142
264
  });
143
265
  const scopedInterceptor = scopedInterceptors[method];
144
266
  if (scopedInterceptor) {
145
- Object.keys(scopedInterceptor).forEach(hook => {
267
+ Object.keys(scopedInterceptor).forEach((hook) => {
146
268
  if (hook !== 'returnValue') {
147
269
  interceptor[hook] = (interceptor[hook] || []).concat(scopedInterceptor[hook]);
148
270
  }
@@ -155,7 +277,7 @@ function invokeApi(method, api, options, ...params) {
155
277
  if (interceptor && Object.keys(interceptor).length) {
156
278
  if (isArray(interceptor.invoke)) {
157
279
  const res = queue(interceptor.invoke, options);
158
- return res.then(options => {
280
+ return res.then((options) => {
159
281
  return api(wrapperOptions(interceptor, options), ...params);
160
282
  });
161
283
  }
@@ -166,17 +288,128 @@ function invokeApi(method, api, options, ...params) {
166
288
  return api(options, ...params);
167
289
  }
168
290
 
291
+ function handlePromise(promise) {
292
+ if (__UNI_FEATURE_PROMISE__) {
293
+ return promise
294
+ .then((data) => {
295
+ return [null, data];
296
+ })
297
+ .catch((err) => [err]);
298
+ }
299
+ return promise;
300
+ }
301
+
302
+ function formatApiArgs(args, options) {
303
+ const params = args[0];
304
+ if (!options ||
305
+ (!isPlainObject(options.formatArgs) && isPlainObject(params))) {
306
+ return;
307
+ }
308
+ const formatArgs = options.formatArgs;
309
+ const keys = Object.keys(formatArgs);
310
+ for (let i = 0; i < keys.length; i++) {
311
+ const name = keys[i];
312
+ const formatterOrDefaultValue = formatArgs[name];
313
+ if (isFunction(formatterOrDefaultValue)) {
314
+ const errMsg = formatterOrDefaultValue(args[0][name], params);
315
+ if (isString(errMsg)) {
316
+ return errMsg;
317
+ }
318
+ }
319
+ else {
320
+ // defaultValue
321
+ if (!hasOwn(params, name)) {
322
+ params[name] = formatterOrDefaultValue;
323
+ }
324
+ }
325
+ }
326
+ }
327
+ function beforeInvokeApi(name, args, protocol, options) {
328
+ if ((process.env.NODE_ENV !== 'production')) {
329
+ validateProtocols(name, args, protocol);
330
+ }
331
+ if (options && options.beforeInvoke) {
332
+ const errMsg = options.beforeInvoke(args);
333
+ if (isString(errMsg)) {
334
+ return errMsg;
335
+ }
336
+ }
337
+ const errMsg = formatApiArgs(args, options);
338
+ if (errMsg) {
339
+ return errMsg;
340
+ }
341
+ }
342
+ function wrapperSyncApi(name, fn, protocol, options) {
343
+ return (...args) => {
344
+ const errMsg = beforeInvokeApi(name, args, protocol, options);
345
+ if (errMsg) {
346
+ throw new Error(errMsg);
347
+ }
348
+ return fn.apply(null, args);
349
+ };
350
+ }
351
+ function defineSyncApi(name, fn, protocol, options) {
352
+ return wrapperSyncApi(name, fn, (process.env.NODE_ENV !== 'production') ? protocol : undefined, options);
353
+ }
354
+
355
+ const API_UPX2PX = 'upx2px';
356
+ const Upx2pxProtocol = [
357
+ {
358
+ name: 'upx',
359
+ type: [Number, String],
360
+ required: true,
361
+ },
362
+ ];
363
+
364
+ const EPS = 1e-4;
365
+ const BASE_DEVICE_WIDTH = 750;
366
+ let isIOS = false;
367
+ let deviceWidth = 0;
368
+ let deviceDPR = 0;
369
+ function checkDeviceWidth() {
370
+ const { platform, pixelRatio, windowWidth } = getBaseSystemInfo();
371
+ deviceWidth = windowWidth;
372
+ deviceDPR = pixelRatio;
373
+ isIOS = platform === 'ios';
374
+ }
375
+ const upx2px = defineSyncApi(API_UPX2PX, (number, newDeviceWidth) => {
376
+ if (deviceWidth === 0) {
377
+ checkDeviceWidth();
378
+ }
379
+ number = Number(number);
380
+ if (number === 0) {
381
+ return 0;
382
+ }
383
+ let width = newDeviceWidth || deviceWidth;
384
+ let result = (number / BASE_DEVICE_WIDTH) * width;
385
+ if (result < 0) {
386
+ result = -result;
387
+ }
388
+ result = Math.floor(result + EPS);
389
+ if (result === 0) {
390
+ if (deviceDPR === 1 || !isIOS) {
391
+ result = 1;
392
+ }
393
+ else {
394
+ result = 0.5;
395
+ }
396
+ }
397
+ return number < 0 ? -result : result;
398
+ }, Upx2pxProtocol);
399
+
400
+ const API_ADD_INTERCEPTOR = 'addInterceptor';
401
+ const API_REMOVE_INTERCEPTOR = 'removeInterceptor';
169
402
  const AddInterceptorProtocol = [
170
403
  {
171
404
  name: 'method',
172
405
  type: [String, Object],
173
- required: true
174
- }
406
+ required: true,
407
+ },
175
408
  ];
176
409
  const RemoveInterceptorProtocol = AddInterceptorProtocol;
177
410
 
178
411
  function mergeInterceptorHook(interceptors, interceptor) {
179
- Object.keys(interceptor).forEach(hook => {
412
+ Object.keys(interceptor).forEach((hook) => {
180
413
  if (isFunction(interceptor[hook])) {
181
414
  interceptors[hook] = mergeHook(interceptors[hook], interceptor[hook]);
182
415
  }
@@ -186,7 +419,7 @@ function removeInterceptorHook(interceptors, interceptor) {
186
419
  if (!interceptors || !interceptor) {
187
420
  return;
188
421
  }
189
- Object.keys(interceptor).forEach(hook => {
422
+ Object.keys(interceptor).forEach((hook) => {
190
423
  if (isFunction(interceptor[hook])) {
191
424
  removeHook(interceptors[hook], interceptor[hook]);
192
425
  }
@@ -220,7 +453,7 @@ function removeHook(hooks, hook) {
220
453
  hooks.splice(index, 1);
221
454
  }
222
455
  }
223
- const addInterceptor = createApi({ type: API_TYPE_SYNC, name: 'addInterceptor' }, (method, interceptor) => {
456
+ const addInterceptor = defineSyncApi(API_ADD_INTERCEPTOR, (method, interceptor) => {
224
457
  if (typeof method === 'string' && isPlainObject(interceptor)) {
225
458
  mergeInterceptorHook(scopedInterceptors[method] || (scopedInterceptors[method] = {}), interceptor);
226
459
  }
@@ -228,7 +461,7 @@ const addInterceptor = createApi({ type: API_TYPE_SYNC, name: 'addInterceptor' }
228
461
  mergeInterceptorHook(globalInterceptors, method);
229
462
  }
230
463
  }, AddInterceptorProtocol);
231
- const removeInterceptor = createApi({ type: API_TYPE_SYNC, name: 'removeInterceptor' }, (method, interceptor) => {
464
+ const removeInterceptor = defineSyncApi(API_REMOVE_INTERCEPTOR, (method, interceptor) => {
232
465
  if (typeof method === 'string') {
233
466
  if (isPlainObject(interceptor)) {
234
467
  removeInterceptorHook(scopedInterceptors[method], interceptor);
@@ -240,9 +473,118 @@ const removeInterceptor = createApi({ type: API_TYPE_SYNC, name: 'removeIntercep
240
473
  else if (isPlainObject(method)) {
241
474
  removeInterceptorHook(globalInterceptors, method);
242
475
  }
243
- }, RemoveInterceptorProtocol);
476
+ }, RemoveInterceptorProtocol);
477
+ const interceptors = {};
478
+
479
+ const API_ON = '$on';
480
+ const OnProtocol = [
481
+ {
482
+ name: 'event',
483
+ type: String,
484
+ required: true,
485
+ },
486
+ {
487
+ name: 'callback',
488
+ type: Function,
489
+ required: true,
490
+ },
491
+ ];
492
+ const API_ONCE = '$once';
493
+ const OnceProtocol = OnProtocol;
494
+ const API_OFF = '$off';
495
+ const OffProtocol = [
496
+ {
497
+ name: 'event',
498
+ type: [String, Array],
499
+ },
500
+ {
501
+ name: 'callback',
502
+ type: Function,
503
+ },
504
+ ];
505
+ const API_EMIT = '$emit';
506
+ const EmitProtocol = [
507
+ {
508
+ name: 'event',
509
+ type: String,
510
+ required: true,
511
+ },
512
+ ];
513
+
514
+ const E = function () {
515
+ // Keep this empty so it's easier to inherit from
516
+ // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3)
517
+ };
518
+ E.prototype = {
519
+ on: function (name, callback, ctx) {
520
+ var e = this.e || (this.e = {});
521
+ (e[name] || (e[name] = [])).push({
522
+ fn: callback,
523
+ ctx: ctx,
524
+ });
525
+ return this;
526
+ },
527
+ once: function (name, callback, ctx) {
528
+ var self = this;
529
+ function listener() {
530
+ self.off(name, listener);
531
+ callback.apply(ctx, arguments);
532
+ }
533
+ listener._ = callback;
534
+ return this.on(name, listener, ctx);
535
+ },
536
+ emit: function (name) {
537
+ var data = [].slice.call(arguments, 1);
538
+ var evtArr = ((this.e || (this.e = {}))[name] || []).slice();
539
+ var i = 0;
540
+ var len = evtArr.length;
541
+ for (i; i < len; i++) {
542
+ evtArr[i].fn.apply(evtArr[i].ctx, data);
543
+ }
544
+ return this;
545
+ },
546
+ off: function (name, callback) {
547
+ var e = this.e || (this.e = {});
548
+ var evts = e[name];
549
+ var liveEvents = [];
550
+ if (evts && callback) {
551
+ for (var i = 0, len = evts.length; i < len; i++) {
552
+ if (evts[i].fn !== callback && evts[i].fn._ !== callback)
553
+ liveEvents.push(evts[i]);
554
+ }
555
+ }
556
+ // Remove event from queue to prevent memory leak
557
+ // Suggested by https://github.com/lazd
558
+ // Ref: https://github.com/scottcorgan/tiny-emitter/commit/c6ebfaa9bc973b33d110a84a307742b7cf94c953#commitcomment-5024910
559
+ liveEvents.length ? (e[name] = liveEvents) : delete e[name];
560
+ return this;
561
+ },
562
+ };
563
+ var Emitter = E;
564
+
565
+ const emitter = new Emitter();
566
+ const $on = defineSyncApi(API_ON, (name, callback) => {
567
+ emitter.on(name, callback);
568
+ return () => emitter.off(name, callback);
569
+ }, OnProtocol);
570
+ const $once = defineSyncApi(API_ONCE, (name, callback) => {
571
+ emitter.once(name, callback);
572
+ return () => emitter.off(name, callback);
573
+ }, OnceProtocol);
574
+ const $off = defineSyncApi(API_OFF, (name, callback) => {
575
+ if (!name) {
576
+ emitter.e = {};
577
+ return;
578
+ }
579
+ if (!Array.isArray(name))
580
+ name = [name];
581
+ name.forEach((n) => emitter.off(n, callback));
582
+ }, OffProtocol);
583
+ const $emit = defineSyncApi(API_EMIT, (name, ...args) => {
584
+ emitter.emit(name, ...args);
585
+ }, EmitProtocol);
244
586
 
245
- const SYNC_API_RE = /^\$|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/;
587
+ const SYNC_API_RE = /^\$|getLocale|setLocale|sendNativeEvent|restoreGlobal|getCurrentSubNVue|getMenuButtonBoundingClientRect|^report|interceptors|Interceptor$|getSubNVueById|requireNativePlugin|upx2px|hideKeyboard|canIUse|^create|Sync$|Manager$|base64ToArrayBuffer|arrayBufferToBase64/;
246
588
  const CONTEXT_API_RE = /^create|Manager$/;
247
589
  // Context例外情况
248
590
  const CONTEXT_API_RE_EXC = ['createBLEConnection'];
@@ -258,16 +600,6 @@ function isSyncApi(name) {
258
600
  function isCallbackApi(name) {
259
601
  return CALLBACK_API_RE.test(name) && name !== 'onPush';
260
602
  }
261
- function handlePromise(promise) {
262
- if (!__UNI_PROMISE_API__) {
263
- return promise;
264
- }
265
- return promise
266
- .then(data => {
267
- return [null, data];
268
- })
269
- .catch(err => [err]);
270
- }
271
603
  function shouldPromise(name) {
272
604
  if (isContextApi(name) || isSyncApi(name) || isCallbackApi(name)) {
273
605
  return false;
@@ -278,7 +610,7 @@ function shouldPromise(name) {
278
610
  if (!Promise.prototype.finally) {
279
611
  Promise.prototype.finally = function (onfinally) {
280
612
  const promise = this.constructor;
281
- return this.then(value => promise.resolve(onfinally && onfinally()).then(() => value), reason => promise.resolve(onfinally && onfinally()).then(() => {
613
+ return this.then((value) => promise.resolve(onfinally && onfinally()).then(() => value), (reason) => promise.resolve(onfinally && onfinally()).then(() => {
282
614
  throw reason;
283
615
  }));
284
616
  };
@@ -290,17 +622,17 @@ function promisify(name, api) {
290
622
  if (!isFunction(api)) {
291
623
  return api;
292
624
  }
293
- return function promiseApi(options = {}, ...params) {
625
+ return function promiseApi(options = {}) {
294
626
  if (isFunction(options.success) ||
295
627
  isFunction(options.fail) ||
296
628
  isFunction(options.complete)) {
297
- return wrapperReturnValue(name, invokeApi(name, api, options, ...params));
629
+ return wrapperReturnValue(name, invokeApi(name, api, options));
298
630
  }
299
631
  return wrapperReturnValue(name, handlePromise(new Promise((resolve, reject) => {
300
- invokeApi(name, api, Object.assign({}, options, {
632
+ invokeApi(name, api, extend({}, options, {
301
633
  success: resolve,
302
- fail: reject
303
- }), ...params);
634
+ fail: reject,
635
+ }));
304
636
  })));
305
637
  };
306
638
  }
@@ -396,7 +728,51 @@ function initWrapper(protocols) {
396
728
  };
397
729
  }
398
730
 
399
- const baseApis = { upx2px, addInterceptor, removeInterceptor };
731
+ const getLocale = () => {
732
+ // 优先使用 $locale
733
+ const app = getApp({ allowDefault: true });
734
+ if (app && app.$vm) {
735
+ return app.$vm.$locale;
736
+ }
737
+ return swan.getSystemInfoSync().language || 'zh-Hans';
738
+ };
739
+ const setLocale = (locale) => {
740
+ const app = getApp();
741
+ if (!app) {
742
+ return false;
743
+ }
744
+ const oldLocale = app.$vm.$locale;
745
+ if (oldLocale !== locale) {
746
+ app.$vm.$locale = locale;
747
+ onLocaleChangeCallbacks.forEach((fn) => fn({ locale }));
748
+ return true;
749
+ }
750
+ return false;
751
+ };
752
+ const onLocaleChangeCallbacks = [];
753
+ const onLocaleChange = (fn) => {
754
+ if (onLocaleChangeCallbacks.indexOf(fn) === -1) {
755
+ onLocaleChangeCallbacks.push(fn);
756
+ }
757
+ };
758
+ if (typeof global !== 'undefined') {
759
+ global.getLocale = getLocale;
760
+ }
761
+
762
+ const baseApis = {
763
+ $on,
764
+ $off,
765
+ $once,
766
+ $emit,
767
+ upx2px,
768
+ interceptors,
769
+ addInterceptor,
770
+ removeInterceptor,
771
+ onAppLaunch,
772
+ getLocale,
773
+ setLocale,
774
+ onLocaleChange,
775
+ };
400
776
  function initUni(api, protocols) {
401
777
  const wrapper = initWrapper(protocols);
402
778
  const UniProxyHandlers = {
@@ -413,25 +789,25 @@ function initUni(api, protocols) {
413
789
  // event-api
414
790
  // provider-api?
415
791
  return promisify(key, wrapper(key, swan[key]));
416
- }
792
+ },
417
793
  };
418
794
  return new Proxy({}, UniProxyHandlers);
419
795
  }
420
796
 
421
797
  function initGetProvider(providers) {
422
- return function getProvider({ service, success, fail, complete }) {
798
+ return function getProvider({ service, success, fail, complete, }) {
423
799
  let res;
424
800
  if (providers[service]) {
425
801
  res = {
426
802
  errMsg: 'getProvider:ok',
427
803
  service,
428
- provider: providers[service]
804
+ provider: providers[service],
429
805
  };
430
806
  isFunction(success) && success(res);
431
807
  }
432
808
  else {
433
809
  res = {
434
- errMsg: 'getProvider:fail:服务[' + service + ']不存在'
810
+ errMsg: 'getProvider:fail:服务[' + service + ']不存在',
435
811
  };
436
812
  isFunction(fail) && fail(res);
437
813
  }
@@ -439,6 +815,26 @@ function initGetProvider(providers) {
439
815
  };
440
816
  }
441
817
 
818
+ function addSafeAreaInsets(fromRes, toRes) {
819
+ if (fromRes.safeArea) {
820
+ const safeArea = fromRes.safeArea;
821
+ toRes.safeAreaInsets = {
822
+ top: safeArea.top,
823
+ left: safeArea.left,
824
+ right: fromRes.windowWidth - safeArea.right,
825
+ bottom: fromRes.windowHeight - safeArea.bottom,
826
+ };
827
+ }
828
+ }
829
+
830
+ const getSystemInfo = {
831
+ returnValue: addSafeAreaInsets,
832
+ };
833
+
834
+ const getSystemInfoSync = getSystemInfo;
835
+
836
+ const redirectTo = {};
837
+
442
838
  const previewImage = {
443
839
  args(fromArgs, toArgs) {
444
840
  let currentIndex = parseInt(fromArgs.current);
@@ -468,44 +864,16 @@ const previewImage = {
468
864
  }
469
865
  return {
470
866
  indicator: false,
471
- loop: false
867
+ loop: false,
472
868
  };
473
- }
474
- };
475
- function addSafeAreaInsets(fromRes, toRes) {
476
- if (fromRes.safeArea) {
477
- const safeArea = fromRes.safeArea;
478
- toRes.safeAreaInsets = {
479
- top: safeArea.top,
480
- left: safeArea.left,
481
- right: fromRes.windowWidth - safeArea.right,
482
- bottom: fromRes.windowHeight - safeArea.bottom
483
- };
484
- }
485
- }
486
- const getSystemInfo = {
487
- returnValue: addSafeAreaInsets
488
- };
489
- const getSystemInfoSync = getSystemInfo;
490
- const redirectTo = {};
491
- const createCanvasContext = {
492
- returnValue(fromRes, toRes) {
493
- const measureText = fromRes.measureText;
494
- toRes.measureText = function (text, callback) {
495
- const textMetrics = measureText.call(this, text);
496
- if (typeof callback === 'function') {
497
- setTimeout(() => callback(textMetrics), 0);
498
- }
499
- return textMetrics;
500
- };
501
- }
869
+ },
502
870
  };
503
871
 
504
872
  const getProvider = initGetProvider({
505
873
  oauth: ['baidu'],
506
874
  share: ['baidu'],
507
875
  payment: ['baidu'],
508
- push: ['baidu']
876
+ push: ['baidu'],
509
877
  });
510
878
  function requestPayment(params) {
511
879
  let parseError = false;
@@ -520,7 +888,7 @@ function requestPayment(params) {
520
888
  if (parseError) {
521
889
  params.fail &&
522
890
  params.fail({
523
- errMsg: 'requestPayment:fail: 参数 orderInfo 数据结构不正确,参考:https://uniapp.dcloud.io/api/plugins/payment?id=orderinfo'
891
+ errMsg: 'requestPayment:fail: 参数 orderInfo 数据结构不正确,参考:https://uniapp.dcloud.io/api/plugins/payment?id=orderinfo',
524
892
  });
525
893
  }
526
894
  else {
@@ -529,9 +897,9 @@ function requestPayment(params) {
529
897
  }
530
898
 
531
899
  var shims = /*#__PURE__*/Object.freeze({
532
- __proto__: null,
533
- getProvider: getProvider,
534
- requestPayment: requestPayment
900
+ __proto__: null,
901
+ getProvider: getProvider,
902
+ requestPayment: requestPayment
535
903
  });
536
904
 
537
905
  function createTodoMethod(contextName, methodName) {
@@ -549,78 +917,78 @@ const request = {
549
917
  dataType(type) {
550
918
  return {
551
919
  name: 'dataType',
552
- value: type === 'json' ? type : 'string'
920
+ value: type === 'json' ? type : 'string',
553
921
  };
554
- }
922
+ },
555
923
  };
556
- }
924
+ },
557
925
  };
558
926
  const connectSocket = {
559
927
  args: {
560
- method: false
561
- }
928
+ method: false,
929
+ },
562
930
  };
563
931
  const getRecorderManager = {
564
932
  returnValue(fromRes, toRes) {
565
933
  toRes.onFrameRecorded = createTodoMethod('RecorderManager', 'onFrameRecorded');
566
- }
934
+ },
567
935
  };
568
936
  const getBackgroundAudioManager = {
569
937
  returnValue(fromRes, toRes) {
570
938
  toRes.onPrev = createTodoMethod('BackgroundAudioManager', 'onPrev');
571
939
  toRes.onNext = createTodoMethod('BackgroundAudioManager', 'onNext');
572
- }
940
+ },
573
941
  };
574
942
  const scanCode = {
575
943
  args: {
576
944
  onlyFromCamera: false,
577
- scanType: false
578
- }
945
+ scanType: false,
946
+ },
579
947
  };
580
948
  const navigateToMiniProgram = {
581
949
  name: 'navigateToSmartProgram',
582
950
  args: {
583
951
  appId: 'appKey',
584
- envVersion: false
585
- }
952
+ envVersion: false,
953
+ },
586
954
  };
587
955
  const navigateBackMiniProgram = {
588
- name: 'navigateBackSmartProgram'
956
+ name: 'navigateBackSmartProgram',
589
957
  };
590
958
  const showShareMenu = {
591
- name: 'openShare'
959
+ name: 'openShare',
592
960
  };
593
961
  const getAccountInfoSync = {
594
962
  name: 'getEnvInfoSync',
595
963
  returnValue(fromRes, toRes) {
596
964
  toRes.miniProgram = {
597
- appId: fromRes.appKey
965
+ appId: fromRes.appKey,
598
966
  };
599
967
  toRes.plugin = {
600
968
  appId: '',
601
- version: fromRes.sdkVersion
969
+ version: fromRes.sdkVersion,
602
970
  };
603
- }
971
+ },
604
972
  };
605
973
 
606
974
  var protocols = /*#__PURE__*/Object.freeze({
607
- __proto__: null,
608
- request: request,
609
- connectSocket: connectSocket,
610
- getRecorderManager: getRecorderManager,
611
- getBackgroundAudioManager: getBackgroundAudioManager,
612
- scanCode: scanCode,
613
- navigateToMiniProgram: navigateToMiniProgram,
614
- navigateBackMiniProgram: navigateBackMiniProgram,
615
- showShareMenu: showShareMenu,
616
- getAccountInfoSync: getAccountInfoSync,
617
- redirectTo: redirectTo,
618
- previewImage: previewImage,
619
- getSystemInfo: getSystemInfo,
620
- getSystemInfoSync: getSystemInfoSync,
621
- createCanvasContext: createCanvasContext
975
+ __proto__: null,
976
+ request: request,
977
+ connectSocket: connectSocket,
978
+ getRecorderManager: getRecorderManager,
979
+ getBackgroundAudioManager: getBackgroundAudioManager,
980
+ scanCode: scanCode,
981
+ navigateToMiniProgram: navigateToMiniProgram,
982
+ navigateBackMiniProgram: navigateBackMiniProgram,
983
+ showShareMenu: showShareMenu,
984
+ getAccountInfoSync: getAccountInfoSync,
985
+ redirectTo: redirectTo,
986
+ navigateTo: navigateTo,
987
+ previewImage: previewImage,
988
+ getSystemInfo: getSystemInfo,
989
+ getSystemInfoSync: getSystemInfoSync
622
990
  });
623
991
 
624
992
  var index = initUni(shims, protocols);
625
993
 
626
- export default index;
994
+ export { index as default };