UNPKG

38.8 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 return retv
311}
312
313/**
314 * https://dom.spec.whatwg.org/#set-the-canceled-flag
315 * @param data {PrivateData} private data.
316 */
317function setCancelFlag(data) {
318 if (data.passiveListener != null) {
319 if (
320 typeof console !== "undefined" &&
321 typeof console.error === "function"
322 ) {
323 console.error(
324 "Unable to preventDefault inside passive event listener invocation.",
325 data.passiveListener
326 );
327 }
328 return
329 }
330 if (!data.event.cancelable) {
331 return
332 }
333
334 data.canceled = true;
335 if (typeof data.event.preventDefault === "function") {
336 data.event.preventDefault();
337 }
338}
339
340/**
341 * @see https://dom.spec.whatwg.org/#interface-event
342 * @private
343 */
344/**
345 * The event wrapper.
346 * @constructor
347 * @param {EventTarget} eventTarget The event target of this dispatching.
348 * @param {Event|{type:string}} event The original event to wrap.
349 */
350function Event(eventTarget, event) {
351 privateData.set(this, {
352 eventTarget,
353 event,
354 eventPhase: 2,
355 currentTarget: eventTarget,
356 canceled: false,
357 stopped: false,
358 immediateStopped: false,
359 passiveListener: null,
360 timeStamp: event.timeStamp || Date.now(),
361 });
362
363 // https://heycam.github.io/webidl/#Unforgeable
364 Object.defineProperty(this, "isTrusted", { value: false, enumerable: true });
365
366 // Define accessors
367 const keys = Object.keys(event);
368 for (let i = 0; i < keys.length; ++i) {
369 const key = keys[i];
370 if (!(key in this)) {
371 Object.defineProperty(this, key, defineRedirectDescriptor(key));
372 }
373 }
374}
375
376// Should be enumerable, but class methods are not enumerable.
377Event.prototype = {
378 /**
379 * The type of this event.
380 * @type {string}
381 */
382 get type() {
383 return pd(this).event.type
384 },
385
386 /**
387 * The target of this event.
388 * @type {EventTarget}
389 */
390 get target() {
391 return pd(this).eventTarget
392 },
393
394 /**
395 * The target of this event.
396 * @type {EventTarget}
397 */
398 get currentTarget() {
399 return pd(this).currentTarget
400 },
401
402 /**
403 * @returns {EventTarget[]} The composed path of this event.
404 */
405 composedPath() {
406 const currentTarget = pd(this).currentTarget;
407 if (currentTarget == null) {
408 return []
409 }
410 return [currentTarget]
411 },
412
413 /**
414 * Constant of NONE.
415 * @type {number}
416 */
417 get NONE() {
418 return 0
419 },
420
421 /**
422 * Constant of CAPTURING_PHASE.
423 * @type {number}
424 */
425 get CAPTURING_PHASE() {
426 return 1
427 },
428
429 /**
430 * Constant of AT_TARGET.
431 * @type {number}
432 */
433 get AT_TARGET() {
434 return 2
435 },
436
437 /**
438 * Constant of BUBBLING_PHASE.
439 * @type {number}
440 */
441 get BUBBLING_PHASE() {
442 return 3
443 },
444
445 /**
446 * The target of this event.
447 * @type {number}
448 */
449 get eventPhase() {
450 return pd(this).eventPhase
451 },
452
453 /**
454 * Stop event bubbling.
455 * @returns {void}
456 */
457 stopPropagation() {
458 const data = pd(this);
459
460 data.stopped = true;
461 if (typeof data.event.stopPropagation === "function") {
462 data.event.stopPropagation();
463 }
464 },
465
466 /**
467 * Stop event bubbling.
468 * @returns {void}
469 */
470 stopImmediatePropagation() {
471 const data = pd(this);
472
473 data.stopped = true;
474 data.immediateStopped = true;
475 if (typeof data.event.stopImmediatePropagation === "function") {
476 data.event.stopImmediatePropagation();
477 }
478 },
479
480 /**
481 * The flag to be bubbling.
482 * @type {boolean}
483 */
484 get bubbles() {
485 return Boolean(pd(this).event.bubbles)
486 },
487
488 /**
489 * The flag to be cancelable.
490 * @type {boolean}
491 */
492 get cancelable() {
493 return Boolean(pd(this).event.cancelable)
494 },
495
496 /**
497 * Cancel this event.
498 * @returns {void}
499 */
500 preventDefault() {
501 setCancelFlag(pd(this));
502 },
503
504 /**
505 * The flag to indicate cancellation state.
506 * @type {boolean}
507 */
508 get defaultPrevented() {
509 return pd(this).canceled
510 },
511
512 /**
513 * The flag to be composed.
514 * @type {boolean}
515 */
516 get composed() {
517 return Boolean(pd(this).event.composed)
518 },
519
520 /**
521 * The unix time of this event.
522 * @type {number}
523 */
524 get timeStamp() {
525 return pd(this).timeStamp
526 },
527
528 /**
529 * The target of this event.
530 * @type {EventTarget}
531 * @deprecated
532 */
533 get srcElement() {
534 return pd(this).eventTarget
535 },
536
537 /**
538 * The flag to stop event bubbling.
539 * @type {boolean}
540 * @deprecated
541 */
542 get cancelBubble() {
543 return pd(this).stopped
544 },
545 set cancelBubble(value) {
546 if (!value) {
547 return
548 }
549 const data = pd(this);
550
551 data.stopped = true;
552 if (typeof data.event.cancelBubble === "boolean") {
553 data.event.cancelBubble = true;
554 }
555 },
556
557 /**
558 * The flag to indicate cancellation state.
559 * @type {boolean}
560 * @deprecated
561 */
562 get returnValue() {
563 return !pd(this).canceled
564 },
565 set returnValue(value) {
566 if (!value) {
567 setCancelFlag(pd(this));
568 }
569 },
570
571 /**
572 * Initialize this event object. But do nothing under event dispatching.
573 * @param {string} type The event type.
574 * @param {boolean} [bubbles=false] The flag to be possible to bubble up.
575 * @param {boolean} [cancelable=false] The flag to be possible to cancel.
576 * @deprecated
577 */
578 initEvent() {
579 // Do nothing.
580 },
581};
582
583// `constructor` is not enumerable.
584Object.defineProperty(Event.prototype, "constructor", {
585 value: Event,
586 configurable: true,
587 writable: true,
588});
589
590// Ensure `event instanceof window.Event` is `true`.
591if (typeof window !== "undefined" && typeof window.Event !== "undefined") {
592 Object.setPrototypeOf(Event.prototype, window.Event.prototype);
593
594 // Make association for wrappers.
595 wrappers.set(window.Event.prototype, Event);
596}
597
598/**
599 * Get the property descriptor to redirect a given property.
600 * @param {string} key Property name to define property descriptor.
601 * @returns {PropertyDescriptor} The property descriptor to redirect the property.
602 * @private
603 */
604function defineRedirectDescriptor(key) {
605 return {
606 get() {
607 return pd(this).event[key]
608 },
609 set(value) {
610 pd(this).event[key] = value;
611 },
612 configurable: true,
613 enumerable: true,
614 }
615}
616
617/**
618 * Get the property descriptor to call a given method property.
619 * @param {string} key Property name to define property descriptor.
620 * @returns {PropertyDescriptor} The property descriptor to call the method property.
621 * @private
622 */
623function defineCallDescriptor(key) {
624 return {
625 value() {
626 const event = pd(this).event;
627 return event[key].apply(event, arguments)
628 },
629 configurable: true,
630 enumerable: true,
631 }
632}
633
634/**
635 * Define new wrapper class.
636 * @param {Function} BaseEvent The base wrapper class.
637 * @param {Object} proto The prototype of the original event.
638 * @returns {Function} The defined wrapper class.
639 * @private
640 */
641function defineWrapper(BaseEvent, proto) {
642 const keys = Object.keys(proto);
643 if (keys.length === 0) {
644 return BaseEvent
645 }
646
647 /** CustomEvent */
648 function CustomEvent(eventTarget, event) {
649 BaseEvent.call(this, eventTarget, event);
650 }
651
652 CustomEvent.prototype = Object.create(BaseEvent.prototype, {
653 constructor: { value: CustomEvent, configurable: true, writable: true },
654 });
655
656 // Define accessors.
657 for (let i = 0; i < keys.length; ++i) {
658 const key = keys[i];
659 if (!(key in BaseEvent.prototype)) {
660 const descriptor = Object.getOwnPropertyDescriptor(proto, key);
661 const isFunc = typeof descriptor.value === "function";
662 Object.defineProperty(
663 CustomEvent.prototype,
664 key,
665 isFunc
666 ? defineCallDescriptor(key)
667 : defineRedirectDescriptor(key)
668 );
669 }
670 }
671
672 return CustomEvent
673}
674
675/**
676 * Get the wrapper class of a given prototype.
677 * @param {Object} proto The prototype of the original event to get its wrapper.
678 * @returns {Function} The wrapper class.
679 * @private
680 */
681function getWrapper(proto) {
682 if (proto == null || proto === Object.prototype) {
683 return Event
684 }
685
686 let wrapper = wrappers.get(proto);
687 if (wrapper == null) {
688 wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);
689 wrappers.set(proto, wrapper);
690 }
691 return wrapper
692}
693
694/**
695 * Wrap a given event to management a dispatching.
696 * @param {EventTarget} eventTarget The event target of this dispatching.
697 * @param {Object} event The event to wrap.
698 * @returns {Event} The wrapper instance.
699 * @private
700 */
701function wrapEvent(eventTarget, event) {
702 const Wrapper = getWrapper(Object.getPrototypeOf(event));
703 return new Wrapper(eventTarget, event)
704}
705
706/**
707 * Get the immediateStopped flag of a given event.
708 * @param {Event} event The event to get.
709 * @returns {boolean} The flag to stop propagation immediately.
710 * @private
711 */
712function isStopped(event) {
713 return pd(event).immediateStopped
714}
715
716/**
717 * Set the current event phase of a given event.
718 * @param {Event} event The event to set current target.
719 * @param {number} eventPhase New event phase.
720 * @returns {void}
721 * @private
722 */
723function setEventPhase(event, eventPhase) {
724 pd(event).eventPhase = eventPhase;
725}
726
727/**
728 * Set the current target of a given event.
729 * @param {Event} event The event to set current target.
730 * @param {EventTarget|null} currentTarget New current target.
731 * @returns {void}
732 * @private
733 */
734function setCurrentTarget(event, currentTarget) {
735 pd(event).currentTarget = currentTarget;
736}
737
738/**
739 * Set a passive listener of a given event.
740 * @param {Event} event The event to set current target.
741 * @param {Function|null} passiveListener New passive listener.
742 * @returns {void}
743 * @private
744 */
745function setPassiveListener(event, passiveListener) {
746 pd(event).passiveListener = passiveListener;
747}
748
749/**
750 * @typedef {object} ListenerNode
751 * @property {Function} listener
752 * @property {1|2|3} listenerType
753 * @property {boolean} passive
754 * @property {boolean} once
755 * @property {ListenerNode|null} next
756 * @private
757 */
758
759/**
760 * @type {WeakMap<object, Map<string, ListenerNode>>}
761 * @private
762 */
763const listenersMap = new WeakMap();
764
765// Listener types
766const CAPTURE = 1;
767const BUBBLE = 2;
768const ATTRIBUTE = 3;
769
770/**
771 * Check whether a given value is an object or not.
772 * @param {any} x The value to check.
773 * @returns {boolean} `true` if the value is an object.
774 */
775function isObject(x) {
776 return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax
777}
778
779/**
780 * Get listeners.
781 * @param {EventTarget} eventTarget The event target to get.
782 * @returns {Map<string, ListenerNode>} The listeners.
783 * @private
784 */
785function getListeners(eventTarget) {
786 const listeners = listenersMap.get(eventTarget);
787 if (listeners == null) {
788 throw new TypeError(
789 "'this' is expected an EventTarget object, but got another value."
790 )
791 }
792 return listeners
793}
794
795/**
796 * Get the property descriptor for the event attribute of a given event.
797 * @param {string} eventName The event name to get property descriptor.
798 * @returns {PropertyDescriptor} The property descriptor.
799 * @private
800 */
801function defineEventAttributeDescriptor(eventName) {
802 return {
803 get() {
804 const listeners = getListeners(this);
805 let node = listeners.get(eventName);
806 while (node != null) {
807 if (node.listenerType === ATTRIBUTE) {
808 return node.listener
809 }
810 node = node.next;
811 }
812 return null
813 },
814
815 set(listener) {
816 if (typeof listener !== "function" && !isObject(listener)) {
817 listener = null; // eslint-disable-line no-param-reassign
818 }
819 const listeners = getListeners(this);
820
821 // Traverse to the tail while removing old value.
822 let prev = null;
823 let node = listeners.get(eventName);
824 while (node != null) {
825 if (node.listenerType === ATTRIBUTE) {
826 // Remove old value.
827 if (prev !== null) {
828 prev.next = node.next;
829 } else if (node.next !== null) {
830 listeners.set(eventName, node.next);
831 } else {
832 listeners.delete(eventName);
833 }
834 } else {
835 prev = node;
836 }
837
838 node = node.next;
839 }
840
841 // Add new value.
842 if (listener !== null) {
843 const newNode = {
844 listener,
845 listenerType: ATTRIBUTE,
846 passive: false,
847 once: false,
848 next: null,
849 };
850 if (prev === null) {
851 listeners.set(eventName, newNode);
852 } else {
853 prev.next = newNode;
854 }
855 }
856 },
857 configurable: true,
858 enumerable: true,
859 }
860}
861
862/**
863 * Define an event attribute (e.g. `eventTarget.onclick`).
864 * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.
865 * @param {string} eventName The event name to define.
866 * @returns {void}
867 */
868function defineEventAttribute(eventTargetPrototype, eventName) {
869 Object.defineProperty(
870 eventTargetPrototype,
871 `on${eventName}`,
872 defineEventAttributeDescriptor(eventName)
873 );
874}
875
876/**
877 * Define a custom EventTarget with event attributes.
878 * @param {string[]} eventNames Event names for event attributes.
879 * @returns {EventTarget} The custom EventTarget.
880 * @private
881 */
882function defineCustomEventTarget(eventNames) {
883 /** CustomEventTarget */
884 function CustomEventTarget() {
885 EventTarget.call(this);
886 }
887
888 CustomEventTarget.prototype = Object.create(EventTarget.prototype, {
889 constructor: {
890 value: CustomEventTarget,
891 configurable: true,
892 writable: true,
893 },
894 });
895
896 for (let i = 0; i < eventNames.length; ++i) {
897 defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);
898 }
899
900 return CustomEventTarget
901}
902
903/**
904 * EventTarget.
905 *
906 * - This is constructor if no arguments.
907 * - This is a function which returns a CustomEventTarget constructor if there are arguments.
908 *
909 * For example:
910 *
911 * class A extends EventTarget {}
912 * class B extends EventTarget("message") {}
913 * class C extends EventTarget("message", "error") {}
914 * class D extends EventTarget(["message", "error"]) {}
915 */
916function EventTarget() {
917 /*eslint-disable consistent-return */
918 if (this instanceof EventTarget) {
919 listenersMap.set(this, new Map());
920 return
921 }
922 if (arguments.length === 1 && Array.isArray(arguments[0])) {
923 return defineCustomEventTarget(arguments[0])
924 }
925 if (arguments.length > 0) {
926 const types = new Array(arguments.length);
927 for (let i = 0; i < arguments.length; ++i) {
928 types[i] = arguments[i];
929 }
930 return defineCustomEventTarget(types)
931 }
932 throw new TypeError("Cannot call a class as a function")
933 /*eslint-enable consistent-return */
934}
935
936// Should be enumerable, but class methods are not enumerable.
937EventTarget.prototype = {
938 /**
939 * Add a given listener to this event target.
940 * @param {string} eventName The event name to add.
941 * @param {Function} listener The listener to add.
942 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
943 * @returns {void}
944 */
945 addEventListener(eventName, listener, options) {
946 if (listener == null) {
947 return
948 }
949 if (typeof listener !== "function" && !isObject(listener)) {
950 throw new TypeError("'listener' should be a function or an object.")
951 }
952
953 const listeners = getListeners(this);
954 const optionsIsObj = isObject(options);
955 const capture = optionsIsObj
956 ? Boolean(options.capture)
957 : Boolean(options);
958 const listenerType = capture ? CAPTURE : BUBBLE;
959 const newNode = {
960 listener,
961 listenerType,
962 passive: optionsIsObj && Boolean(options.passive),
963 once: optionsIsObj && Boolean(options.once),
964 next: null,
965 };
966
967 // Set it as the first node if the first node is null.
968 let node = listeners.get(eventName);
969 if (node === undefined) {
970 listeners.set(eventName, newNode);
971 return
972 }
973
974 // Traverse to the tail while checking duplication..
975 let prev = null;
976 while (node != null) {
977 if (
978 node.listener === listener &&
979 node.listenerType === listenerType
980 ) {
981 // Should ignore duplication.
982 return
983 }
984 prev = node;
985 node = node.next;
986 }
987
988 // Add it.
989 prev.next = newNode;
990 },
991
992 /**
993 * Remove a given listener from this event target.
994 * @param {string} eventName The event name to remove.
995 * @param {Function} listener The listener to remove.
996 * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.
997 * @returns {void}
998 */
999 removeEventListener(eventName, listener, options) {
1000 if (listener == null) {
1001 return
1002 }
1003
1004 const listeners = getListeners(this);
1005 const capture = isObject(options)
1006 ? Boolean(options.capture)
1007 : Boolean(options);
1008 const listenerType = capture ? CAPTURE : BUBBLE;
1009
1010 let prev = null;
1011 let node = listeners.get(eventName);
1012 while (node != null) {
1013 if (
1014 node.listener === listener &&
1015 node.listenerType === listenerType
1016 ) {
1017 if (prev !== null) {
1018 prev.next = node.next;
1019 } else if (node.next !== null) {
1020 listeners.set(eventName, node.next);
1021 } else {
1022 listeners.delete(eventName);
1023 }
1024 return
1025 }
1026
1027 prev = node;
1028 node = node.next;
1029 }
1030 },
1031
1032 /**
1033 * Dispatch a given event.
1034 * @param {Event|{type:string}} event The event to dispatch.
1035 * @returns {boolean} `false` if canceled.
1036 */
1037 dispatchEvent(event) {
1038 if (event == null || typeof event.type !== "string") {
1039 throw new TypeError('"event.type" should be a string.')
1040 }
1041
1042 // If listeners aren't registered, terminate.
1043 const listeners = getListeners(this);
1044 const eventName = event.type;
1045 let node = listeners.get(eventName);
1046 if (node == null) {
1047 return true
1048 }
1049
1050 // Since we cannot rewrite several properties, so wrap object.
1051 const wrappedEvent = wrapEvent(this, event);
1052
1053 // This doesn't process capturing phase and bubbling phase.
1054 // This isn't participating in a tree.
1055 let prev = null;
1056 while (node != null) {
1057 // Remove this listener if it's once
1058 if (node.once) {
1059 if (prev !== null) {
1060 prev.next = node.next;
1061 } else if (node.next !== null) {
1062 listeners.set(eventName, node.next);
1063 } else {
1064 listeners.delete(eventName);
1065 }
1066 } else {
1067 prev = node;
1068 }
1069
1070 // Call this listener
1071 setPassiveListener(
1072 wrappedEvent,
1073 node.passive ? node.listener : null
1074 );
1075 if (typeof node.listener === "function") {
1076 try {
1077 node.listener.call(this, wrappedEvent);
1078 } catch (err) {
1079 if (
1080 typeof console !== "undefined" &&
1081 typeof console.error === "function"
1082 ) {
1083 console.error(err);
1084 }
1085 }
1086 } else if (
1087 node.listenerType !== ATTRIBUTE &&
1088 typeof node.listener.handleEvent === "function"
1089 ) {
1090 node.listener.handleEvent(wrappedEvent);
1091 }
1092
1093 // Break if `event.stopImmediatePropagation` was called.
1094 if (isStopped(wrappedEvent)) {
1095 break
1096 }
1097
1098 node = node.next;
1099 }
1100 setPassiveListener(wrappedEvent, null);
1101 setEventPhase(wrappedEvent, 0);
1102 setCurrentTarget(wrappedEvent, null);
1103
1104 return !wrappedEvent.defaultPrevented
1105 },
1106};
1107
1108// `constructor` is not enumerable.
1109Object.defineProperty(EventTarget.prototype, "constructor", {
1110 value: EventTarget,
1111 configurable: true,
1112 writable: true,
1113});
1114
1115// Ensure `eventTarget instanceof window.EventTarget` is `true`.
1116if (
1117 typeof window !== "undefined" &&
1118 typeof window.EventTarget !== "undefined"
1119) {
1120 Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);
1121}
1122
1123var WS = /** @class */ (function (_super) {
1124 __extends$1(WS, _super);
1125 function WS(url, protocol) {
1126 var _this = _super.call(this) || this;
1127 _this._readyState = WS.CLOSED;
1128 if (!url) {
1129 throw new TypeError("Failed to construct 'WebSocket': url required");
1130 }
1131 _this._url = url;
1132 _this._protocol = protocol;
1133 return _this;
1134 }
1135 Object.defineProperty(WS.prototype, "url", {
1136 get: function () {
1137 return this._url;
1138 },
1139 enumerable: false,
1140 configurable: true
1141 });
1142 Object.defineProperty(WS.prototype, "protocol", {
1143 get: function () {
1144 return this._protocol;
1145 },
1146 enumerable: false,
1147 configurable: true
1148 });
1149 Object.defineProperty(WS.prototype, "readyState", {
1150 get: function () {
1151 return this._readyState;
1152 },
1153 enumerable: false,
1154 configurable: true
1155 });
1156 WS.CONNECTING = 0;
1157 WS.OPEN = 1;
1158 WS.CLOSING = 2;
1159 WS.CLOSED = 3;
1160 return WS;
1161}(EventTarget("open", "error", "message", "close")));
1162var WechatWS = /** @class */ (function (_super) {
1163 __extends$1(WechatWS, _super);
1164 function WechatWS(url, protocol) {
1165 var _this = _super.call(this, url, protocol) || this;
1166 if (protocol &&
1167 !(wx.canIUse && wx.canIUse("connectSocket.object.protocols"))) {
1168 throw new Error("subprotocol not supported in weapp");
1169 }
1170 _this._readyState = WS.CONNECTING;
1171 var errorHandler = function (event) {
1172 _this._readyState = WS.CLOSED;
1173 _this.dispatchEvent({
1174 type: "error",
1175 message: event.errMsg,
1176 });
1177 };
1178 var socketTask = wx.connectSocket({
1179 url: url,
1180 protocols: _this._protocol === undefined || Array.isArray(_this._protocol)
1181 ? _this._protocol
1182 : [_this._protocol],
1183 fail: function (error) { return setTimeout(function () { return errorHandler(error); }, 0); },
1184 });
1185 _this._socketTask = socketTask;
1186 socketTask.onOpen(function () {
1187 _this._readyState = WS.OPEN;
1188 _this.dispatchEvent({
1189 type: "open",
1190 });
1191 });
1192 socketTask.onError(errorHandler);
1193 socketTask.onMessage(function (event) {
1194 var data = event.data;
1195 _this.dispatchEvent({
1196 data: data,
1197 type: "message",
1198 });
1199 });
1200 socketTask.onClose(function (event) {
1201 _this._readyState = WS.CLOSED;
1202 var code = event.code, reason = event.reason;
1203 _this.dispatchEvent({
1204 code: code,
1205 reason: reason,
1206 type: "close",
1207 });
1208 });
1209 return _this;
1210 }
1211 WechatWS.prototype.close = function () {
1212 if (this.readyState === WS.CLOSED)
1213 return;
1214 if (this.readyState === WS.CONNECTING) {
1215 console.warn("close WebSocket which is connecting might not work");
1216 }
1217 this._socketTask.close({});
1218 };
1219 WechatWS.prototype.send = function (data) {
1220 if (this.readyState !== WS.OPEN) {
1221 throw new Error("INVALID_STATE_ERR");
1222 }
1223 if (!(typeof data === "string" || data instanceof ArrayBuffer)) {
1224 throw new TypeError("only String/ArrayBuffer supported");
1225 }
1226 this._socketTask.send({
1227 data: data,
1228 });
1229 };
1230 return WechatWS;
1231}(WS));
1232var WebSocket = WechatWS;
1233
1234var platformInfo = {
1235 name: "Weapp",
1236};
1237
1238exports.WebSocket = WebSocket;
1239exports.getAuthInfo = getAuthInfo;
1240exports.platformInfo = platformInfo;
1241exports.request = request;
1242exports.storage = storage;
1243exports.upload = upload;
1244//# sourceMappingURL=index.js.map