UNPKG

38.9 kBJavaScriptView Raw
1'use strict';
2
3Object.defineProperty(exports, '__esModule', { value: true });
4
5/******************************************************************************
6Copyright (c) Microsoft Corporation.
7
8Permission to use, copy, modify, and/or distribute this software for any
9purpose with or without fee is hereby granted.
10
11THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
12REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
13AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
14INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
15LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
16OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
17PERFORMANCE OF THIS SOFTWARE.
18***************************************************************************** */
19/* global Reflect, Promise */
20
21var extendStatics$1 = function(d, b) {
22 extendStatics$1 = Object.setPrototypeOf ||
23 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
24 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
25 return extendStatics$1(d, b);
26};
27
28function __extends$1(d, b) {
29 if (typeof b !== "function" && b !== null)
30 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
31 extendStatics$1(d, b);
32 function __() { this.constructor = d; }
33 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
34}
35
36var __assign = function() {
37 __assign = Object.assign || function __assign(t) {
38 for (var s, i = 1, n = arguments.length; i < n; i++) {
39 s = arguments[i];
40 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
41 }
42 return t;
43 };
44 return __assign.apply(this, arguments);
45};
46
47function __rest(s, e) {
48 var t = {};
49 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
50 t[p] = s[p];
51 if (s != null && typeof Object.getOwnPropertySymbols === "function")
52 for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
53 if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
54 t[p[i]] = s[p[i]];
55 }
56 return t;
57}
58
59function __awaiter(thisArg, _arguments, P, generator) {
60 function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
61 return new (P || (P = Promise))(function (resolve, reject) {
62 function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
63 function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
64 function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
65 step((generator = generator.apply(thisArg, _arguments || [])).next());
66 });
67}
68
69function __generator(thisArg, body) {
70 var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
71 return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
72 function verb(n) { return function (v) { return step([n, v]); }; }
73 function step(op) {
74 if (f) throw new TypeError("Generator is already executing.");
75 while (_) try {
76 if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
77 if (y = 0, t) op = [op[0] & 2, t.value];
78 switch (op[0]) {
79 case 0: case 1: t = op; break;
80 case 4: _.label++; return { value: op[1], done: false };
81 case 5: _.label++; y = op[1]; op = [0]; continue;
82 case 7: op = _.ops.pop(); _.trys.pop(); continue;
83 default:
84 if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
85 if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
86 if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
87 if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
88 if (t[2]) _.ops.pop();
89 _.trys.pop(); continue;
90 }
91 op = body.call(thisArg, _);
92 } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
93 if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
94 }
95}
96
97var PROVIDER = "lc_weapp";
98var PLATFORM = "weixin";
99function getLoginCode() {
100 return new Promise(function (resolve, reject) {
101 wx.login({
102 success: function (res) {
103 return res.code ? resolve(res.code) : reject(new Error(res.errMsg));
104 },
105 fail: function (_a) {
106 var errMsg = _a.errMsg;
107 return reject(new Error(errMsg));
108 },
109 });
110 });
111}
112var getAuthInfo = function (_a) {
113 var _b = _a === void 0 ? {} : _a, _c = _b.platform, platform = _c === void 0 ? PLATFORM : _c, _d = _b.preferUnionId, preferUnionId = _d === void 0 ? false : _d, _e = _b.asMainAccount, asMainAccount = _e === void 0 ? false : _e;
114 return __awaiter(this, void 0, void 0, function () {
115 var code, authData;
116 return __generator(this, function (_f) {
117 switch (_f.label) {
118 case 0: return [4 /*yield*/, getLoginCode()];
119 case 1:
120 code = _f.sent();
121 authData = { code: code };
122 if (preferUnionId) {
123 authData.platform = platform;
124 authData.main_account = asMainAccount;
125 }
126 return [2 /*return*/, {
127 authData: authData,
128 platform: platform,
129 provider: PROVIDER,
130 }];
131 }
132 });
133 });
134};
135
136var storage = {
137 getItem: function (key) {
138 return wx.getStorageSync(key);
139 },
140 setItem: function (key, value) {
141 return wx.setStorageSync(key, value);
142 },
143 removeItem: function (key) {
144 return wx.removeStorageSync(key);
145 },
146 clear: function () {
147 return wx.clearStorageSync();
148 },
149};
150
151/******************************************************************************
152Copyright (c) Microsoft Corporation.
153
154Permission to use, copy, modify, and/or distribute this software for any
155purpose with or without fee is hereby granted.
156
157THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
158REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
159AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
160INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
161LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
162OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
163PERFORMANCE OF THIS SOFTWARE.
164***************************************************************************** */
165/* global Reflect, Promise */
166
167var extendStatics = function(d, b) {
168 extendStatics = Object.setPrototypeOf ||
169 ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
170 function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
171 return extendStatics(d, b);
172};
173
174function __extends(d, b) {
175 if (typeof b !== "function" && b !== null)
176 throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
177 extendStatics(d, b);
178 function __() { this.constructor = d; }
179 d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
180}
181
182var AbortError = /** @class */ (function (_super) {
183 __extends(AbortError, _super);
184 function AbortError() {
185 var _this = _super !== null && _super.apply(this, arguments) || this;
186 _this.name = "AbortError";
187 return _this;
188 }
189 return AbortError;
190}(Error));
191
192var request = function (url, options) {
193 if (options === void 0) { options = {}; }
194 var method = options.method, data = options.data, headers = options.headers, signal = options.signal;
195 if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
196 return Promise.reject(new AbortError("Request aborted"));
197 }
198 return new Promise(function (resolve, reject) {
199 var task = wx.request({
200 url: url,
201 method: method,
202 data: data,
203 header: headers,
204 complete: function (res) {
205 signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", abortListener);
206 if (!res.statusCode) {
207 reject(new Error(res.errMsg));
208 return;
209 }
210 resolve({
211 ok: !(res.statusCode >= 400),
212 status: res.statusCode,
213 headers: res.header,
214 data: res.data,
215 });
216 },
217 });
218 var abortListener = function () {
219 reject(new AbortError("Request aborted"));
220 task.abort();
221 };
222 signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", abortListener);
223 });
224};
225var upload = function (url, file, options) {
226 if (options === void 0) { options = {}; }
227 var headers = options.headers, data = options.data, onprogress = options.onprogress, signal = options.signal;
228 if (signal === null || signal === void 0 ? void 0 : signal.aborted) {
229 return Promise.reject(new AbortError("Request aborted"));
230 }
231 if (!(file && file.data && file.data.uri)) {
232 return Promise.reject(new TypeError("File data must be an object like { uri: localPath }."));
233 }
234 return new Promise(function (resolve, reject) {
235 var task = wx.uploadFile({
236 url: url,
237 header: headers,
238 filePath: file.data.uri,
239 name: file.field,
240 formData: data,
241 success: function (response) {
242 var status = response.statusCode, data = response.data, rest = __rest(response, ["statusCode", "data"]);
243 resolve(__assign(__assign({}, rest), { data: typeof data === "string" ? JSON.parse(data) : data, status: status, ok: !(status >= 400) }));
244 },
245 fail: function (response) {
246 reject(new Error(response.errMsg));
247 },
248 complete: function () {
249 signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", abortListener);
250 },
251 });
252 var abortListener = function () {
253 reject(new AbortError("Request aborted"));
254 task.abort();
255 };
256 signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", abortListener);
257 if (onprogress) {
258 task.onProgressUpdate(function (event) {
259 return onprogress({
260 loaded: event.totalBytesSent,
261 total: event.totalBytesExpectedToSend,
262 percent: event.progress,
263 });
264 });
265 }
266 });
267};
268
269/**
270 * @author Toru Nagashima <https://github.com/mysticatea>
271 * @copyright 2015 Toru Nagashima. All rights reserved.
272 * See LICENSE file in root directory for full license.
273 */
274/**
275 * @typedef {object} PrivateData
276 * @property {EventTarget} eventTarget The event target.
277 * @property {{type:string}} event The original event object.
278 * @property {number} eventPhase The current event phase.
279 * @property {EventTarget|null} currentTarget The current event target.
280 * @property {boolean} canceled The flag to prevent default.
281 * @property {boolean} stopped The flag to stop propagation.
282 * @property {boolean} immediateStopped The flag to stop propagation immediately.
283 * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.
284 * @property {number} timeStamp The unix time.
285 * @private
286 */
287
288/**
289 * Private data for event wrappers.
290 * @type {WeakMap<Event, PrivateData>}
291 * @private
292 */
293const privateData = new WeakMap();
294
295/**
296 * Cache for wrapper classes.
297 * @type {WeakMap<Object, Function>}
298 * @private
299 */
300const wrappers = new WeakMap();
301
302/**
303 * Get private data.
304 * @param {Event} event The event object to get private data.
305 * @returns {PrivateData} The private data of the event.
306 * @private
307 */
308function pd(event) {
309 const retv = privateData.get(event);
310 console.assert(
311 retv != null,
312 "'this' is expected an Event object, but got",
313 event
314 );
315 return retv
316}
317
318/**
319 * https://dom.spec.whatwg.org/#set-the-canceled-flag
320 * @param data {PrivateData} private data.
321 */
322function setCancelFlag(data) {
323 if (data.passiveListener != null) {
324 if (
325 typeof console !== "undefined" &&
326 typeof console.error === "function"
327 ) {
328 console.error(
329 "Unable to preventDefault inside passive event listener invocation.",
330 data.passiveListener
331 );
332 }
333 return
334 }
335 if (!data.event.cancelable) {
336 return
337 }
338
339 data.canceled = true;
340 if (typeof data.event.preventDefault === "function") {
341 data.event.preventDefault();
342 }
343}
344
345/**
346 * @see https://dom.spec.whatwg.org/#interface-event
347 * @private
348 */
349/**
350 * The event wrapper.
351 * @constructor
352 * @param {EventTarget} eventTarget The event target of this dispatching.
353 * @param {Event|{type:string}} event The original event to wrap.
354 */
355function Event(eventTarget, event) {
356 privateData.set(this, {
357 eventTarget,
358 event,
359 eventPhase: 2,
360 currentTarget: eventTarget,
361 canceled: false,
362 stopped: false,
363 immediateStopped: false,
364 passiveListener: null,
365 timeStamp: event.timeStamp || Date.now(),
366 });
367
368 // https://heycam.github.io/webidl/#Unforgeable
369 Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
370
371 // Define accessors
372 const keys = Object.keys(event);
373 for (let i = 0; i < keys.length; ++i) {
374 const key = keys[i];
375 if (!(key in this)) {
376 Object.defineProperty(this, key, defineRedirectDescriptor(key));
377 }
378 }
379}
380
381// Should be enumerable, but class methods are not enumerable.
382Event.prototype = {
383 /**
384 * The type of this event.
385 * @type {string}
386 */
387 get type() {
388 return pd(this).event.type
389 },
390
391 /**
392 * The target of this event.
393 * @type {EventTarget}
394 */
395 get target() {
396 return pd(this).eventTarget
397 },
398
399 /**
400 * The target of this event.
401 * @type {EventTarget}
402 */
403 get currentTarget() {
404 return pd(this).currentTarget
405 },
406
407 /**
408 * @returns {EventTarget[]} The composed path of this event.
409 */
410 composedPath() {
411 const currentTarget = pd(this).currentTarget;
412 if (currentTarget == null) {
413 return []
414 }
415 return [currentTarget]
416 },
417
418 /**
419 * Constant of NONE.
420 * @type {number}
421 */
422 get NONE() {
423 return 0
424 },
425
426 /**
427 * Constant of CAPTURING_PHASE.
428 * @type {number}
429 */
430 get CAPTURING_PHASE() {
431 return 1
432 },
433
434 /**
435 * Constant of AT_TARGET.
436 * @type {number}
437 */
438 get AT_TARGET() {
439 return 2
440 },
441
442 /**
443 * Constant of BUBBLING_PHASE.
444 * @type {number}
445 */
446 get BUBBLING_PHASE() {
447 return 3
448 },
449
450 /**
451 * The target of this event.
452 * @type {number}
453 */
454 get eventPhase() {
455 return pd(this).eventPhase
456 },
457
458 /**
459 * Stop event bubbling.
460 * @returns {void}
461 */
462 stopPropagation() {
463 const data = pd(this);
464
465 data.stopped = true;
466 if (typeof data.event.stopPropagation === "function") {
467 data.event.stopPropagation();
468 }
469 },
470
471 /**
472 * Stop event bubbling.
473 * @returns {void}
474 */
475 stopImmediatePropagation() {
476 const data = pd(this);
477
478 data.stopped = true;
479 data.immediateStopped = true;
480 if (typeof data.event.stopImmediatePropagation === "function") {
481 data.event.stopImmediatePropagation();
482 }
483 },
484
485 /**
486 * The flag to be bubbling.
487 * @type {boolean}
488 */
489 get bubbles() {
490 return Boolean(pd(this).event.bubbles)
491 },
492
493 /**
494 * The flag to be cancelable.
495 * @type {boolean}
496 */
497 get cancelable() {
498 return Boolean(pd(this).event.cancelable)
499 },
500
501 /**
502 * Cancel this event.
503 * @returns {void}
504 */
505 preventDefault() {
506 setCancelFlag(pd(this));
507 },
508
509 /**
510 * The flag to indicate cancellation state.
511 * @type {boolean}
512 */
513 get defaultPrevented() {
514 return pd(this).canceled
515 },
516
517 /**
518 * The flag to be composed.
519 * @type {boolean}
520 */
521 get composed() {
522 return Boolean(pd(this).event.composed)
523 },
524
525 /**
526 * The unix time of this event.
527 * @type {number}
528 */
529 get timeStamp() {
530 return pd(this).timeStamp
531 },
532
533 /**
534 * The target of this event.
535 * @type {EventTarget}
536 * @deprecated
537 */
538 get srcElement() {
539 return pd(this).eventTarget
540 },
541
542 /**
543 * The flag to stop event bubbling.
544 * @type {boolean}
545 * @deprecated
546 */
547 get cancelBubble() {
548 return pd(this).stopped
549 },
550 set cancelBubble(value) {
551 if (!value) {
552 return
553 }
554 const data = pd(this);
555
556 data.stopped = true;
557 if (typeof data.event.cancelBubble === "boolean") {
558 data.event.cancelBubble = true;
559 }
560 },
561
562 /**
563 * The flag to indicate cancellation state.
564 * @type {boolean}
565 * @deprecated
566 */
567 get returnValue() {
568 return !pd(this).canceled
569 },
570 set returnValue(value) {
571 if (!value) {
572 setCancelFlag(pd(this));
573 }
574 },
575
576 /**
577 * Initialize this event object. But do nothing under event dispatching.
578 * @param {string} type The event type.
579 * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
580 * @param {boolean} [cancelable=false] The flag to be possible to cancel.
581 * @deprecated
582 */
583 initEvent() {
584 // Do nothing.
585 },
586};
587
588// `constructor` is not enumerable.
589Object.defineProperty(Event.prototype, "constructor", {
590 value: Event,
591 configurable: true,
592 writable: true,
593});
594
595// Ensure `event instanceof window.Event` is `true`.
596if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
597 Object.setPrototypeOf(Event.prototype, window.Event.prototype);
598
599 // Make association for wrappers.
600 wrappers.set(window.Event.prototype, Event);
601}
602
603/**
604 * Get the property descriptor to redirect a given property.
605 * @param {string} key Property name to define property descriptor.
606 * @returns {PropertyDescriptor} The property descriptor to redirect the property.
607 * @private
608 */
609function defineRedirectDescriptor(key) {
610 return {
611 get() {
612 return pd(this).event[key]
613 },
614 set(value) {
615 pd(this).event[key] = value;
616 },
617 configurable: true,
618 enumerable: true,
619 }
620}
621
622/**
623 * Get the property descriptor to call a given method property.
624 * @param {string} key Property name to define property descriptor.
625 * @returns {PropertyDescriptor} The property descriptor to call the method property.
626 * @private
627 */
628function defineCallDescriptor(key) {
629 return {
630 value() {
631 const event = pd(this).event;
632 return event[key].apply(event, arguments)
633 },
634 configurable: true,
635 enumerable: true,
636 }
637}
638
639/**
640 * Define new wrapper class.
641 * @param {Function} BaseEvent The base wrapper class.
642 * @param {Object} proto The prototype of the original event.
643 * @returns {Function} The defined wrapper class.
644 * @private
645 */
646function defineWrapper(BaseEvent, proto) {
647 const keys = Object.keys(proto);
648 if (keys.length === 0) {
649 return BaseEvent
650 }
651
652 /** CustomEvent */
653 function CustomEvent(eventTarget, event) {
654 BaseEvent.call(this, eventTarget, event);
655 }
656
657 CustomEvent.prototype = Object.create(BaseEvent.prototype, {
658 constructor: { value: CustomEvent, configurable: true, writable: true },
659 });
660
661 // Define accessors.
662 for (let i = 0; i < keys.length; ++i) {
663 const key = keys[i];
664 if (!(key in BaseEvent.prototype)) {
665 const descriptor = Object.getOwnPropertyDescriptor(proto, key);
666 const isFunc = typeof descriptor.value === "function";
667 Object.defineProperty(
668 CustomEvent.prototype,
669 key,
670 isFunc
671 ? defineCallDescriptor(key)
672 : defineRedirectDescriptor(key)
673 );
674 }
675 }
676
677 return CustomEvent
678}
679
680/**
681 * Get the wrapper class of a given prototype.
682 * @param {Object} proto The prototype of the original event to get its wrapper.
683 * @returns {Function} The wrapper class.
684 * @private
685 */
686function getWrapper(proto) {
687 if (proto == null || proto === Object.prototype) {
688 return Event
689 }
690
691 let wrapper = wrappers.get(proto);
692 if (wrapper == null) {
693 wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
694 wrappers.set(proto, wrapper);
695 }
696 return wrapper
697}
698
699/**
700 * Wrap a given event to management a dispatching.
701 * @param {EventTarget} eventTarget The event target of this dispatching.
702 * @param {Object} event The event to wrap.
703 * @returns {Event} The wrapper instance.
704 * @private
705 */
706function wrapEvent(eventTarget, event) {
707 const Wrapper = getWrapper(Object.getPrototypeOf(event));
708 return new Wrapper(eventTarget, event)
709}
710
711/**
712 * Get the immediateStopped flag of a given event.
713 * @param {Event} event The event to get.
714 * @returns {boolean} The flag to stop propagation immediately.
715 * @private
716 */
717function isStopped(event) {
718 return pd(event).immediateStopped
719}
720
721/**
722 * Set the current event phase of a given event.
723 * @param {Event} event The event to set current target.
724 * @param {number} eventPhase New event phase.
725 * @returns {void}
726 * @private
727 */
728function setEventPhase(event, eventPhase) {
729 pd(event).eventPhase = eventPhase;
730}
731
732/**
733 * Set the current target of a given event.
734 * @param {Event} event The event to set current target.
735 * @param {EventTarget|null} currentTarget New current target.
736 * @returns {void}
737 * @private
738 */
739function setCurrentTarget(event, currentTarget) {
740 pd(event).currentTarget = currentTarget;
741}
742
743/**
744 * Set a passive listener of a given event.
745 * @param {Event} event The event to set current target.
746 * @param {Function|null} passiveListener New passive listener.
747 * @returns {void}
748 * @private
749 */
750function setPassiveListener(event, passiveListener) {
751 pd(event).passiveListener = passiveListener;
752}
753
754/**
755 * @typedef {object} ListenerNode
756 * @property {Function} listener
757 * @property {1|2|3} listenerType
758 * @property {boolean} passive
759 * @property {boolean} once
760 * @property {ListenerNode|null} next
761 * @private
762 */
763
764/**
765 * @type {WeakMap<object, Map<string, ListenerNode>>}
766 * @private
767 */
768const listenersMap = new WeakMap();
769
770// Listener types
771const CAPTURE = 1;
772const BUBBLE = 2;
773const ATTRIBUTE = 3;
774
775/**
776 * Check whether a given value is an object or not.
777 * @param {any} x The value to check.
778 * @returns {boolean} `true` if the value is an object.
779 */
780function isObject(x) {
781 return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
782}
783
784/**
785 * Get listeners.
786 * @param {EventTarget} eventTarget The event target to get.
787 * @returns {Map<string, ListenerNode>} The listeners.
788 * @private
789 */
790function getListeners(eventTarget) {
791 const listeners = listenersMap.get(eventTarget);
792 if (listeners == null) {
793 throw new TypeError(
794 "'this' is expected an EventTarget object, but got another value."
795 )
796 }
797 return listeners
798}
799
800/**
801 * Get the property descriptor for the event attribute of a given event.
802 * @param {string} eventName The event name to get property descriptor.
803 * @returns {PropertyDescriptor} The property descriptor.
804 * @private
805 */
806function defineEventAttributeDescriptor(eventName) {
807 return {
808 get() {
809 const listeners = getListeners(this);
810 let node = listeners.get(eventName);
811 while (node != null) {
812 if (node.listenerType === ATTRIBUTE) {
813 return node.listener
814 }
815 node = node.next;
816 }
817 return null
818 },
819
820 set(listener) {
821 if (typeof listener !== "function" && !isObject(listener)) {
822 listener = null; // eslint-disable-line no-param-reassign
823 }
824 const listeners = getListeners(this);
825
826 // Traverse to the tail while removing old value.
827 let prev = null;
828 let node = listeners.get(eventName);
829 while (node != null) {
830 if (node.listenerType === ATTRIBUTE) {
831 // Remove old value.
832 if (prev !== null) {
833 prev.next = node.next;
834 } else if (node.next !== null) {
835 listeners.set(eventName, node.next);
836 } else {
837 listeners.delete(eventName);
838 }
839 } else {
840 prev = node;
841 }
842
843 node = node.next;
844 }
845
846 // Add new value.
847 if (listener !== null) {
848 const newNode = {
849 listener,
850 listenerType: ATTRIBUTE,
851 passive: false,
852 once: false,
853 next: null,
854 };
855 if (prev === null) {
856 listeners.set(eventName, newNode);
857 } else {
858 prev.next = newNode;
859 }
860 }
861 },
862 configurable: true,
863 enumerable: true,
864 }
865}
866
867/**
868 * Define an event attribute (e.g. `eventTarget.onclick`).
869 * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
870 * @param {string} eventName The event name to define.
871 * @returns {void}
872 */
873function defineEventAttribute(eventTargetPrototype, eventName) {
874 Object.defineProperty(
875 eventTargetPrototype,
876 `on${eventName}`,
877 defineEventAttributeDescriptor(eventName)
878 );
879}
880
881/**
882 * Define a custom EventTarget with event attributes.
883 * @param {string[]} eventNames Event names for event attributes.
884 * @returns {EventTarget} The custom EventTarget.
885 * @private
886 */
887function defineCustomEventTarget(eventNames) {
888 /** CustomEventTarget */
889 function CustomEventTarget() {
890 EventTarget.call(this);
891 }
892
893 CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
894 constructor: {
895 value: CustomEventTarget,
896 configurable: true,
897 writable: true,
898 },
899 });
900
901 for (let i = 0; i < eventNames.length; ++i) {
902 defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
903 }
904
905 return CustomEventTarget
906}
907
908/**
909 * EventTarget.
910 *
911 * - This is constructor if no arguments.
912 * - This is a function which returns a CustomEventTarget constructor if there are arguments.
913 *
914 * For example:
915 *
916 * class A extends EventTarget {}
917 * class B extends EventTarget("message") {}
918 * class C extends EventTarget("message", "error") {}
919 * class D extends EventTarget(["message", "error"]) {}
920 */
921function EventTarget() {
922 /*eslint-disable consistent-return */
923 if (this instanceof EventTarget) {
924 listenersMap.set(this, new Map());
925 return
926 }
927 if (arguments.length === 1 && Array.isArray(arguments[0])) {
928 return defineCustomEventTarget(arguments[0])
929 }
930 if (arguments.length > 0) {
931 const types = new Array(arguments.length);
932 for (let i = 0; i < arguments.length; ++i) {
933 types[i] = arguments[i];
934 }
935 return defineCustomEventTarget(types)
936 }
937 throw new TypeError("Cannot call a class as a function")
938 /*eslint-enable consistent-return */
939}
940
941// Should be enumerable, but class methods are not enumerable.
942EventTarget.prototype = {
943 /**
944 * Add a given listener to this event target.
945 * @param {string} eventName The event name to add.
946 * @param {Function} listener The listener to add.
947 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
948 * @returns {void}
949 */
950 addEventListener(eventName, listener, options) {
951 if (listener == null) {
952 return
953 }
954 if (typeof listener !== "function" && !isObject(listener)) {
955 throw new TypeError("'listener' should be a function or an object.")
956 }
957
958 const listeners = getListeners(this);
959 const optionsIsObj = isObject(options);
960 const capture = optionsIsObj
961 ? Boolean(options.capture)
962 : Boolean(options);
963 const listenerType = capture ? CAPTURE : BUBBLE;
964 const newNode = {
965 listener,
966 listenerType,
967 passive: optionsIsObj && Boolean(options.passive),
968 once: optionsIsObj && Boolean(options.once),
969 next: null,
970 };
971
972 // Set it as the first node if the first node is null.
973 let node = listeners.get(eventName);
974 if (node === undefined) {
975 listeners.set(eventName, newNode);
976 return
977 }
978
979 // Traverse to the tail while checking duplication..
980 let prev = null;
981 while (node != null) {
982 if (
983 node.listener === listener &&
984 node.listenerType === listenerType
985 ) {
986 // Should ignore duplication.
987 return
988 }
989 prev = node;
990 node = node.next;
991 }
992
993 // Add it.
994 prev.next = newNode;
995 },
996
997 /**
998 * Remove a given listener from this event target.
999 * @param {string} eventName The event name to remove.
1000 * @param {Function} listener The listener to remove.
1001 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
1002 * @returns {void}
1003 */
1004 removeEventListener(eventName, listener, options) {
1005 if (listener == null) {
1006 return
1007 }
1008
1009 const listeners = getListeners(this);
1010 const capture = isObject(options)
1011 ? Boolean(options.capture)
1012 : Boolean(options);
1013 const listenerType = capture ? CAPTURE : BUBBLE;
1014
1015 let prev = null;
1016 let node = listeners.get(eventName);
1017 while (node != null) {
1018 if (
1019 node.listener === listener &&
1020 node.listenerType === listenerType
1021 ) {
1022 if (prev !== null) {
1023 prev.next = node.next;
1024 } else if (node.next !== null) {
1025 listeners.set(eventName, node.next);
1026 } else {
1027 listeners.delete(eventName);
1028 }
1029 return
1030 }
1031
1032 prev = node;
1033 node = node.next;
1034 }
1035 },
1036
1037 /**
1038 * Dispatch a given event.
1039 * @param {Event|{type:string}} event The event to dispatch.
1040 * @returns {boolean} `false` if canceled.
1041 */
1042 dispatchEvent(event) {
1043 if (event == null || typeof event.type !== "string") {
1044 throw new TypeError('"event.type" should be a string.')
1045 }
1046
1047 // If listeners aren't registered, terminate.
1048 const listeners = getListeners(this);
1049 const eventName = event.type;
1050 let node = listeners.get(eventName);
1051 if (node == null) {
1052 return true
1053 }
1054
1055 // Since we cannot rewrite several properties, so wrap object.
1056 const wrappedEvent = wrapEvent(this, event);
1057
1058 // This doesn't process capturing phase and bubbling phase.
1059 // This isn't participating in a tree.
1060 let prev = null;
1061 while (node != null) {
1062 // Remove this listener if it's once
1063 if (node.once) {
1064 if (prev !== null) {
1065 prev.next = node.next;
1066 } else if (node.next !== null) {
1067 listeners.set(eventName, node.next);
1068 } else {
1069 listeners.delete(eventName);
1070 }
1071 } else {
1072 prev = node;
1073 }
1074
1075 // Call this listener
1076 setPassiveListener(
1077 wrappedEvent,
1078 node.passive ? node.listener : null
1079 );
1080 if (typeof node.listener === "function") {
1081 try {
1082 node.listener.call(this, wrappedEvent);
1083 } catch (err) {
1084 if (
1085 typeof console !== "undefined" &&
1086 typeof console.error === "function"
1087 ) {
1088 console.error(err);
1089 }
1090 }
1091 } else if (
1092 node.listenerType !== ATTRIBUTE &&
1093 typeof node.listener.handleEvent === "function"
1094 ) {
1095 node.listener.handleEvent(wrappedEvent);
1096 }
1097
1098 // Break if `event.stopImmediatePropagation` was called.
1099 if (isStopped(wrappedEvent)) {
1100 break
1101 }
1102
1103 node = node.next;
1104 }
1105 setPassiveListener(wrappedEvent, null);
1106 setEventPhase(wrappedEvent, 0);
1107 setCurrentTarget(wrappedEvent, null);
1108
1109 return !wrappedEvent.defaultPrevented
1110 },
1111};
1112
1113// `constructor` is not enumerable.
1114Object.defineProperty(EventTarget.prototype, "constructor", {
1115 value: EventTarget,
1116 configurable: true,
1117 writable: true,
1118});
1119
1120// Ensure `eventTarget instanceof window.EventTarget` is `true`.
1121if (
1122 typeof window !== "undefined" &&
1123 typeof window.EventTarget !== "undefined"
1124) {
1125 Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
1126}
1127
1128var WS = /** @class */ (function (_super) {
1129 __extends$1(WS, _super);
1130 function WS(url, protocol) {
1131 var _this = _super.call(this) || this;
1132 _this._readyState = WS.CLOSED;
1133 if (!url) {
1134 throw new TypeError("Failed to construct 'WebSocket': url required");
1135 }
1136 _this._url = url;
1137 _this._protocol = protocol;
1138 return _this;
1139 }
1140 Object.defineProperty(WS.prototype, "url", {
1141 get: function () {
1142 return this._url;
1143 },
1144 enumerable: false,
1145 configurable: true
1146 });
1147 Object.defineProperty(WS.prototype, "protocol", {
1148 get: function () {
1149 return this._protocol;
1150 },
1151 enumerable: false,
1152 configurable: true
1153 });
1154 Object.defineProperty(WS.prototype, "readyState", {
1155 get: function () {
1156 return this._readyState;
1157 },
1158 enumerable: false,
1159 configurable: true
1160 });
1161 WS.CONNECTING = 0;
1162 WS.OPEN = 1;
1163 WS.CLOSING = 2;
1164 WS.CLOSED = 3;
1165 return WS;
1166}(EventTarget("open", "error", "message", "close")));
1167var WechatWS = /** @class */ (function (_super) {
1168 __extends$1(WechatWS, _super);
1169 function WechatWS(url, protocol) {
1170 var _this = _super.call(this, url, protocol) || this;
1171 if (protocol &&
1172 !(wx.canIUse && wx.canIUse("connectSocket.object.protocols"))) {
1173 throw new Error("subprotocol not supported in weapp");
1174 }
1175 _this._readyState = WS.CONNECTING;
1176 var errorHandler = function (event) {
1177 _this._readyState = WS.CLOSED;
1178 _this.dispatchEvent({
1179 type: "error",
1180 message: event.errMsg,
1181 });
1182 };
1183 var socketTask = wx.connectSocket({
1184 url: url,
1185 protocols: _this._protocol === undefined || Array.isArray(_this._protocol)
1186 ? _this._protocol
1187 : [_this._protocol],
1188 fail: function (error) { return setTimeout(function () { return errorHandler(error); }, 0); },
1189 });
1190 _this._socketTask = socketTask;
1191 socketTask.onOpen(function () {
1192 _this._readyState = WS.OPEN;
1193 _this.dispatchEvent({
1194 type: "open",
1195 });
1196 });
1197 socketTask.onError(errorHandler);
1198 socketTask.onMessage(function (event) {
1199 var data = event.data;
1200 _this.dispatchEvent({
1201 data: data,
1202 type: "message",
1203 });
1204 });
1205 socketTask.onClose(function (event) {
1206 _this._readyState = WS.CLOSED;
1207 var code = event.code, reason = event.reason;
1208 _this.dispatchEvent({
1209 code: code,
1210 reason: reason,
1211 type: "close",
1212 });
1213 });
1214 return _this;
1215 }
1216 WechatWS.prototype.close = function () {
1217 if (this.readyState === WS.CLOSED)
1218 return;
1219 if (this.readyState === WS.CONNECTING) {
1220 console.warn("close WebSocket which is connecting might not work");
1221 }
1222 this._socketTask.close({});
1223 };
1224 WechatWS.prototype.send = function (data) {
1225 if (this.readyState !== WS.OPEN) {
1226 throw new Error("INVALID_STATE_ERR");
1227 }
1228 if (!(typeof data === "string" || data instanceof ArrayBuffer)) {
1229 throw new TypeError("only String/ArrayBuffer supported");
1230 }
1231 this._socketTask.send({
1232 data: data,
1233 });
1234 };
1235 return WechatWS;
1236}(WS));
1237var WebSocket = WechatWS;
1238
1239var platformInfo = {
1240 name: "Weapp",
1241};
1242
1243exports.WebSocket = WebSocket;
1244exports.getAuthInfo = getAuthInfo;
1245exports.platformInfo = platformInfo;
1246exports.request = request;
1247exports.storage = storage;
1248exports.upload = upload;
1249//# sourceMappingURL=index.js.map