@dcloudio/uni-mp-toutiao 3.0.0-alpha-4030320241109001 → 3.0.0-alpha-4030320241109002

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