iqiyi-player-switch

爱奇艺flash播放器与html5播放器随意切换,改善html5播放器播放体验。

当前为 2017-10-31 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name iqiyi-player-switch
  3. // @namespace https://github.com/gooyie/userscript-iqiyi-player-switch
  4. // @homepageURL https://github.com/gooyie/userscript-iqiyi-player-switch
  5. // @supportURL https://github.com/gooyie/userscript-iqiyi-player-switch/issues
  6. // @version 1.11.1
  7. // @description 爱奇艺flash播放器与html5播放器随意切换,改善html5播放器播放体验。
  8. // @author gooyie
  9. // @license MIT License
  10. //
  11. // @include *://*.iqiyi.com/*
  12. // @include *://v.baidu.com/*
  13. // @include *://music.baidu.com/mv/*
  14. // @include *://www.zybus.com/*
  15. // @grant GM_registerMenuCommand
  16. // @grant GM_xmlhttpRequest
  17. // @grant GM_addStyle
  18. // @grant GM_getValue
  19. // @grant GM_setValue
  20. // @grant GM_info
  21. // @grant unsafeWindow
  22. // @connect qiyi.com
  23. // @run-at document-start
  24. // ==/UserScript==
  25. /******/ (function(modules) { // webpackBootstrap
  26. /******/ // The module cache
  27. /******/ var installedModules = {};
  28. /******/
  29. /******/ // The require function
  30. /******/ function __webpack_require__(moduleId) {
  31. /******/
  32. /******/ // Check if module is in cache
  33. /******/ if(installedModules[moduleId]) {
  34. /******/ return installedModules[moduleId].exports;
  35. /******/ }
  36. /******/ // Create a new module (and put it into the cache)
  37. /******/ var module = installedModules[moduleId] = {
  38. /******/ i: moduleId,
  39. /******/ l: false,
  40. /******/ exports: {}
  41. /******/ };
  42. /******/
  43. /******/ // Execute the module function
  44. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  45. /******/
  46. /******/ // Flag the module as loaded
  47. /******/ module.l = true;
  48. /******/
  49. /******/ // Return the exports of the module
  50. /******/ return module.exports;
  51. /******/ }
  52. /******/
  53. /******/
  54. /******/ // expose the modules object (__webpack_modules__)
  55. /******/ __webpack_require__.m = modules;
  56. /******/
  57. /******/ // expose the module cache
  58. /******/ __webpack_require__.c = installedModules;
  59. /******/
  60. /******/ // define getter function for harmony exports
  61. /******/ __webpack_require__.d = function(exports, name, getter) {
  62. /******/ if(!__webpack_require__.o(exports, name)) {
  63. /******/ Object.defineProperty(exports, name, {
  64. /******/ configurable: false,
  65. /******/ enumerable: true,
  66. /******/ get: getter
  67. /******/ });
  68. /******/ }
  69. /******/ };
  70. /******/
  71. /******/ // getDefaultExport function for compatibility with non-harmony modules
  72. /******/ __webpack_require__.n = function(module) {
  73. /******/ var getter = module && module.__esModule ?
  74. /******/ function getDefault() { return module['default']; } :
  75. /******/ function getModuleExports() { return module; };
  76. /******/ __webpack_require__.d(getter, 'a', getter);
  77. /******/ return getter;
  78. /******/ };
  79. /******/
  80. /******/ // Object.prototype.hasOwnProperty.call
  81. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  82. /******/
  83. /******/ // __webpack_public_path__
  84. /******/ __webpack_require__.p = "";
  85. /******/
  86. /******/ // Load entry module and return exports
  87. /******/ return __webpack_require__(__webpack_require__.s = 8);
  88. /******/ })
  89. /************************************************************************/
  90. /******/ ([
  91. /* 0 */
  92. /***/ (function(module, exports, __webpack_require__) {
  93.  
  94. "use strict";
  95. /*
  96. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  97. *
  98. * Use of this source code is governed by a BSD-style license
  99. * that can be found in the LICENSE file in the root of the source
  100. * tree.
  101. */
  102. /* eslint-env node */
  103.  
  104.  
  105. var logDisabled_ = true;
  106. var deprecationWarnings_ = true;
  107.  
  108. // Utility methods.
  109. var utils = {
  110. disableLog: function(bool) {
  111. if (typeof bool !== 'boolean') {
  112. return new Error('Argument type: ' + typeof bool +
  113. '. Please use a boolean.');
  114. }
  115. logDisabled_ = bool;
  116. return (bool) ? 'adapter.js logging disabled' :
  117. 'adapter.js logging enabled';
  118. },
  119.  
  120. /**
  121. * Disable or enable deprecation warnings
  122. * @param {!boolean} bool set to true to disable warnings.
  123. */
  124. disableWarnings: function(bool) {
  125. if (typeof bool !== 'boolean') {
  126. return new Error('Argument type: ' + typeof bool +
  127. '. Please use a boolean.');
  128. }
  129. deprecationWarnings_ = !bool;
  130. return 'adapter.js deprecation warnings ' + (bool ? 'disabled' : 'enabled');
  131. },
  132.  
  133. log: function() {
  134. if (typeof window === 'object') {
  135. if (logDisabled_) {
  136. return;
  137. }
  138. if (typeof console !== 'undefined' && typeof console.log === 'function') {
  139. console.log.apply(console, arguments);
  140. }
  141. }
  142. },
  143.  
  144. /**
  145. * Shows a deprecation warning suggesting the modern and spec-compatible API.
  146. */
  147. deprecated: function(oldMethod, newMethod) {
  148. if (!deprecationWarnings_) {
  149. return;
  150. }
  151. console.warn(oldMethod + ' is deprecated, please use ' + newMethod +
  152. ' instead.');
  153. },
  154.  
  155. /**
  156. * Extract browser version out of the provided user agent string.
  157. *
  158. * @param {!string} uastring userAgent string.
  159. * @param {!string} expr Regular expression used as match criteria.
  160. * @param {!number} pos position in the version string to be returned.
  161. * @return {!number} browser version.
  162. */
  163. extractVersion: function(uastring, expr, pos) {
  164. var match = uastring.match(expr);
  165. return match && match.length >= pos && parseInt(match[pos], 10);
  166. },
  167.  
  168. /**
  169. * Browser detector.
  170. *
  171. * @return {object} result containing browser and version
  172. * properties.
  173. */
  174. detectBrowser: function(window) {
  175. var navigator = window && window.navigator;
  176.  
  177. // Returned result object.
  178. var result = {};
  179. result.browser = null;
  180. result.version = null;
  181.  
  182. // Fail early if it's not a browser
  183. if (typeof window === 'undefined' || !window.navigator) {
  184. result.browser = 'Not a browser.';
  185. return result;
  186. }
  187.  
  188. // Firefox.
  189. if (navigator.mozGetUserMedia) {
  190. result.browser = 'firefox';
  191. result.version = this.extractVersion(navigator.userAgent,
  192. /Firefox\/(\d+)\./, 1);
  193. } else if (navigator.webkitGetUserMedia) {
  194. // Chrome, Chromium, Webview, Opera, all use the chrome shim for now
  195. if (window.webkitRTCPeerConnection) {
  196. result.browser = 'chrome';
  197. result.version = this.extractVersion(navigator.userAgent,
  198. /Chrom(e|ium)\/(\d+)\./, 2);
  199. } else { // Safari (in an unpublished version) or unknown webkit-based.
  200. if (navigator.userAgent.match(/Version\/(\d+).(\d+)/)) {
  201. result.browser = 'safari';
  202. result.version = this.extractVersion(navigator.userAgent,
  203. /AppleWebKit\/(\d+)\./, 1);
  204. } else { // unknown webkit-based browser.
  205. result.browser = 'Unsupported webkit-based browser ' +
  206. 'with GUM support but no WebRTC support.';
  207. return result;
  208. }
  209. }
  210. } else if (navigator.mediaDevices &&
  211. navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)) { // Edge.
  212. result.browser = 'edge';
  213. result.version = this.extractVersion(navigator.userAgent,
  214. /Edge\/(\d+).(\d+)$/, 2);
  215. } else if (navigator.mediaDevices &&
  216. navigator.userAgent.match(/AppleWebKit\/(\d+)\./)) {
  217. // Safari, with webkitGetUserMedia removed.
  218. result.browser = 'safari';
  219. result.version = this.extractVersion(navigator.userAgent,
  220. /AppleWebKit\/(\d+)\./, 1);
  221. } else { // Default fallthrough: not supported.
  222. result.browser = 'Not a supported browser.';
  223. return result;
  224. }
  225.  
  226. return result;
  227. },
  228.  
  229. // shimCreateObjectURL must be called before shimSourceObject to avoid loop.
  230.  
  231. shimCreateObjectURL: function(window) {
  232. var URL = window && window.URL;
  233.  
  234. if (!(typeof window === 'object' && window.HTMLMediaElement &&
  235. 'srcObject' in window.HTMLMediaElement.prototype)) {
  236. // Only shim CreateObjectURL using srcObject if srcObject exists.
  237. return undefined;
  238. }
  239.  
  240. var nativeCreateObjectURL = URL.createObjectURL.bind(URL);
  241. var nativeRevokeObjectURL = URL.revokeObjectURL.bind(URL);
  242. var streams = new Map(), newId = 0;
  243.  
  244. URL.createObjectURL = function(stream) {
  245. if ('getTracks' in stream) {
  246. var url = 'polyblob:' + (++newId);
  247. streams.set(url, stream);
  248. utils.deprecated('URL.createObjectURL(stream)',
  249. 'elem.srcObject = stream');
  250. return url;
  251. }
  252. return nativeCreateObjectURL(stream);
  253. };
  254. URL.revokeObjectURL = function(url) {
  255. nativeRevokeObjectURL(url);
  256. streams.delete(url);
  257. };
  258.  
  259. var dsc = Object.getOwnPropertyDescriptor(window.HTMLMediaElement.prototype,
  260. 'src');
  261. Object.defineProperty(window.HTMLMediaElement.prototype, 'src', {
  262. get: function() {
  263. return dsc.get.apply(this);
  264. },
  265. set: function(url) {
  266. this.srcObject = streams.get(url) || null;
  267. return dsc.set.apply(this, [url]);
  268. }
  269. });
  270.  
  271. var nativeSetAttribute = window.HTMLMediaElement.prototype.setAttribute;
  272. window.HTMLMediaElement.prototype.setAttribute = function() {
  273. if (arguments.length === 2 &&
  274. ('' + arguments[0]).toLowerCase() === 'src') {
  275. this.srcObject = streams.get(arguments[1]) || null;
  276. }
  277. return nativeSetAttribute.apply(this, arguments);
  278. };
  279. }
  280. };
  281.  
  282. // Export.
  283. module.exports = {
  284. log: utils.log,
  285. deprecated: utils.deprecated,
  286. disableLog: utils.disableLog,
  287. disableWarnings: utils.disableWarnings,
  288. extractVersion: utils.extractVersion,
  289. shimCreateObjectURL: utils.shimCreateObjectURL,
  290. detectBrowser: utils.detectBrowser.bind(utils)
  291. };
  292.  
  293.  
  294. /***/ }),
  295. /* 1 */
  296. /***/ (function(module, exports, __webpack_require__) {
  297.  
  298. "use strict";
  299.  
  300.  
  301. Object.defineProperty(exports, "__esModule", {
  302. value: true
  303. });
  304.  
  305. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  306.  
  307. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  308.  
  309. /* eslint-disable no-console */
  310. var Logger = function () {
  311. function Logger(tag) {
  312. _classCallCheck(this, Logger);
  313.  
  314. this._tag = tag;
  315. }
  316.  
  317. _createClass(Logger, [{
  318. key: 'log',
  319. value: function log() {
  320. var _console;
  321.  
  322. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  323. args[_key] = arguments[_key];
  324. }
  325.  
  326. (_console = console).log.apply(_console, ['%c' + this.tag + '%c' + args.shift(), 'color: green; font-weight: bolder', 'color: blue'].concat(args));
  327. }
  328. }, {
  329. key: 'info',
  330. value: function info() {
  331. var _console2;
  332.  
  333. for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  334. args[_key2] = arguments[_key2];
  335. }
  336.  
  337. (_console2 = console).info.apply(_console2, [this.tag + args.shift()].concat(args));
  338. }
  339. }, {
  340. key: 'debug',
  341. value: function debug() {
  342. var _console3;
  343.  
  344. for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
  345. args[_key3] = arguments[_key3];
  346. }
  347.  
  348. (_console3 = console).debug.apply(_console3, [this.tag + args.shift()].concat(args));
  349. }
  350. }, {
  351. key: 'warn',
  352. value: function warn() {
  353. var _console4;
  354.  
  355. for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {
  356. args[_key4] = arguments[_key4];
  357. }
  358.  
  359. (_console4 = console).warn.apply(_console4, [this.tag + args.shift()].concat(args));
  360. }
  361. }, {
  362. key: 'error',
  363. value: function error() {
  364. var _console5;
  365.  
  366. for (var _len5 = arguments.length, args = Array(_len5), _key5 = 0; _key5 < _len5; _key5++) {
  367. args[_key5] = arguments[_key5];
  368. }
  369.  
  370. (_console5 = console).error.apply(_console5, [this.tag + args.shift()].concat(args));
  371. }
  372. }, {
  373. key: 'tag',
  374. get: function get() {
  375. return this._tag;
  376. }
  377. }]);
  378.  
  379. return Logger;
  380. }();
  381.  
  382. exports.default = new Logger('[' + GM_info.script.name + ']');
  383.  
  384. /***/ }),
  385. /* 2 */
  386. /***/ (function(module, exports, __webpack_require__) {
  387.  
  388. "use strict";
  389.  
  390.  
  391. Object.defineProperty(exports, "__esModule", {
  392. value: true
  393. });
  394.  
  395. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  396.  
  397. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  398.  
  399. var Detector = function () {
  400. function Detector() {
  401. _classCallCheck(this, Detector);
  402. }
  403.  
  404. _createClass(Detector, null, [{
  405. key: 'isSupportHtml5',
  406. value: function isSupportHtml5() {
  407. var v = document.createElement('video');
  408. return !!(v.canPlayType('audio/mp4; codecs="mp4a.40.2"') && v.canPlayType('video/mp4; codecs="avc1.640029"') && v.canPlayType('video/mp4; codecs="avc1.640029, mp4a.40.2"'));
  409. }
  410. }, {
  411. key: 'isSupportVms',
  412. value: function isSupportVms() {
  413. return !!(window.MediaSource && window.URL && window.WebSocket && window.ReadableStream && (window.RTCSessionDescription || window.webkitRTCSessionDescription) && (window.RTCPeerConnection || window.webkitRTCPeerConnection) && (window.RTCIceCandidate || window.webkitRTCIceCandidate));
  414. }
  415. }, {
  416. key: 'isSupportM3u8',
  417. value: function isSupportM3u8() {
  418. var v = document.createElement('video');
  419. return !!(v.canPlayType('application/x-mpegurl') && v.canPlayType('application/vnd.apple.mpegurl'));
  420. }
  421. }, {
  422. key: 'isChrome',
  423. value: function isChrome() {
  424. return (/chrome/i.test(navigator.userAgent)
  425. );
  426. }
  427. }, {
  428. key: 'isFirefox',
  429. value: function isFirefox() {
  430. return (/firefox/i.test(navigator.userAgent)
  431. );
  432. }
  433. }, {
  434. key: 'isEdge',
  435. value: function isEdge() {
  436. return (/edge/i.test(navigator.userAgent)
  437. );
  438. }
  439. }, {
  440. key: 'isInnerFrame',
  441. value: function isInnerFrame() {
  442. return window.top !== window.self;
  443. }
  444. }, {
  445. key: 'isOutsite',
  446. value: function isOutsite() {
  447. return !/\.iqiyi\.com$/.test(location.host);
  448. }
  449. }, {
  450. key: 'hasFlashPlugin',
  451. value: function hasFlashPlugin() {
  452. var plugins = unsafeWindow.navigator.plugins;
  453. return !!(plugins['Shockwave Flash'] && plugins['Shockwave Flash'].description);
  454. }
  455. }, {
  456. key: 'isFullScreen',
  457. value: function isFullScreen() {
  458. return !!(document.fullscreen || document.webkitIsFullScreen || document.mozFullScreen || document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement);
  459. }
  460. }]);
  461.  
  462. return Detector;
  463. }();
  464.  
  465. exports.default = Detector;
  466.  
  467. /***/ }),
  468. /* 3 */
  469. /***/ (function(module, exports) {
  470.  
  471. var g;
  472.  
  473. // This works in non-strict mode
  474. g = (function() {
  475. return this;
  476. })();
  477.  
  478. try {
  479. // This works if eval is allowed (see CSP)
  480. g = g || Function("return this")() || (1,eval)("this");
  481. } catch(e) {
  482. // This works if the window reference is available
  483. if(typeof window === "object")
  484. g = window;
  485. }
  486.  
  487. // g can still be undefined, but nothing to do about it...
  488. // We return undefined, instead of nothing here, so it's
  489. // easier to handle this case. if(!global) { ...}
  490.  
  491. module.exports = g;
  492.  
  493.  
  494. /***/ }),
  495. /* 4 */
  496. /***/ (function(module, exports, __webpack_require__) {
  497.  
  498. "use strict";
  499.  
  500.  
  501. Object.defineProperty(exports, "__esModule", {
  502. value: true
  503. });
  504.  
  505. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  506.  
  507. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  508.  
  509. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  510.  
  511. var _logger = __webpack_require__(1);
  512.  
  513. var _logger2 = _interopRequireDefault(_logger);
  514.  
  515. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  516.  
  517. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  518.  
  519. var Hooker = function () {
  520. function Hooker() {
  521. _classCallCheck(this, Hooker);
  522. }
  523.  
  524. _createClass(Hooker, null, [{
  525. key: '_hookCall',
  526. value: function _hookCall(cb) {
  527. var call = Function.prototype.call;
  528. Function.prototype.call = function () {
  529. for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
  530. args[_key] = arguments[_key];
  531. }
  532.  
  533. var ret = call.apply(this, args);
  534. try {
  535. if (args && cb(args)) {
  536. Function.prototype.call = call;
  537. cb = function cb() {};
  538. _logger2.default.log('restored call');
  539. }
  540. } catch (err) {
  541. _logger2.default.error(err.stack);
  542. }
  543. return ret;
  544. };
  545. this._hookCall = null;
  546. }
  547. }, {
  548. key: '_isModuleCall',
  549. value: function _isModuleCall(args) {
  550. // module.exports, module, module.exports, require
  551. return args.length === 4 && args[1] && Object.getPrototypeOf(args[1]) === Object.prototype && args[1].hasOwnProperty('exports');
  552. }
  553. }, {
  554. key: '_hookModuleCall',
  555. value: function _hookModuleCall(cb, pred) {
  556. var _this = this;
  557.  
  558. var callbacksMap = new Map([[pred, [cb]]]);
  559. this._hookCall(function (args) {
  560. if (!_this._isModuleCall(args)) return;
  561.  
  562. var exports = args[1].exports;
  563. var _iteratorNormalCompletion = true;
  564. var _didIteratorError = false;
  565. var _iteratorError = undefined;
  566.  
  567. try {
  568. for (var _iterator = callbacksMap[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  569. var _step$value = _slicedToArray(_step.value, 2),
  570. _pred = _step$value[0],
  571. callbacks = _step$value[1];
  572.  
  573. if (!_pred.apply(_this, [exports])) continue;
  574. callbacks.forEach(function (cb) {
  575. return cb(exports, args);
  576. });
  577. _this.keepalive || callbacksMap.delete(_pred);
  578. !callbacksMap.size && (_this._hookModuleCall = null);
  579. break;
  580. }
  581. } catch (err) {
  582. _didIteratorError = true;
  583. _iteratorError = err;
  584. } finally {
  585. try {
  586. if (!_iteratorNormalCompletion && _iterator.return) {
  587. _iterator.return();
  588. }
  589. } finally {
  590. if (_didIteratorError) {
  591. throw _iteratorError;
  592. }
  593. }
  594. }
  595.  
  596. return !callbacksMap.size;
  597. });
  598.  
  599. this._hookModuleCall = function (cb, pred) {
  600. if (callbacksMap.has(pred)) {
  601. callbacksMap.get(pred).push(cb);
  602. } else {
  603. callbacksMap.set(pred, [cb]);
  604. }
  605. };
  606. }
  607. }, {
  608. key: '_isJqueryModuleCall',
  609. value: function _isJqueryModuleCall(exports) {
  610. return exports.hasOwnProperty('fn') && exports.fn.hasOwnProperty('jquery');
  611. }
  612. }, {
  613. key: 'hookJquery',
  614. value: function hookJquery() {
  615. var cb = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : function () {};
  616.  
  617. this._hookModuleCall(cb, this._isJqueryModuleCall);
  618. }
  619. }, {
  620. key: 'hookJqueryAjax',
  621. value: function hookJqueryAjax(cb) {
  622. this.hookJquery(function (exports) {
  623. var ajax = exports.ajax.bind(exports);
  624. exports.ajax = function (url) {
  625. var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  626.  
  627. if ((typeof url === 'undefined' ? 'undefined' : _typeof(url)) === 'object') {
  628. var _ref = [url.url, url];
  629. url = _ref[0];
  630. options = _ref[1];
  631. }
  632. var isHijacked = cb(url, options);
  633. if (isHijacked) return;
  634. return ajax(url, options);
  635. };
  636. });
  637. }
  638. }, {
  639. key: '_isHttpModuleCall',
  640. value: function _isHttpModuleCall(exports) {
  641. return exports.hasOwnProperty('jsonp') && exports.hasOwnProperty('ajax');
  642. }
  643. }, {
  644. key: 'hookHttp',
  645. value: function hookHttp(cb) {
  646. this._hookModuleCall(cb, this._isHttpModuleCall);
  647. }
  648. }, {
  649. key: 'hookHttpJsonp',
  650. value: function hookHttpJsonp(cb) {
  651. this.hookHttp(function (exports) {
  652. var jsonp = exports.jsonp.bind(exports);
  653. exports.jsonp = function (options) {
  654. var isHijacked = cb(options);
  655. if (isHijacked) return;
  656. return jsonp(options);
  657. };
  658. });
  659. }
  660. }, {
  661. key: '_isLogoModuleCall',
  662. value: function _isLogoModuleCall(exports) {
  663. return 'function' === typeof exports && exports.prototype.hasOwnProperty('showLogo');
  664. }
  665. }, {
  666. key: 'hookLogo',
  667. value: function hookLogo(cb) {
  668. this._hookModuleCall(cb, this._isLogoModuleCall);
  669. }
  670. }, {
  671. key: '_isFullScreenModuleCall',
  672. value: function _isFullScreenModuleCall(exports) {
  673. return exports.__proto__ && exports.__proto__.hasOwnProperty('isFullScreen');
  674. }
  675. }, {
  676. key: 'hookFullScreen',
  677. value: function hookFullScreen(cb) {
  678. this._hookModuleCall(cb, this._isFullScreenModuleCall);
  679. }
  680. }, {
  681. key: '_isWebFullScreenModuleCall',
  682. value: function _isWebFullScreenModuleCall(exports) {
  683. return exports.__proto__ && exports.__proto__.hasOwnProperty('isWebFullScreen');
  684. }
  685. }, {
  686. key: 'hookWebFullScreen',
  687. value: function hookWebFullScreen(cb) {
  688. this._hookModuleCall(cb, this._isWebFullScreenModuleCall);
  689. }
  690. }, {
  691. key: 'hookWebFullScreenInit',
  692. value: function hookWebFullScreenInit(cb) {
  693. this.hookWebFullScreen(function (exports) {
  694. var init = exports.__proto__.init;
  695. exports.__proto__.init = function (wrapper, btn) {
  696. cb(this, wrapper, btn);
  697. init.apply(this, [wrapper, btn]);
  698. };
  699. });
  700. }
  701. }, {
  702. key: '_isPluginControlsModuleCall',
  703. value: function _isPluginControlsModuleCall(exports) {
  704. return 'function' === typeof exports && exports.prototype.hasOwnProperty('initFullScreen');
  705. }
  706. }, {
  707. key: 'hookPluginControls',
  708. value: function hookPluginControls(cb) {
  709. this._hookModuleCall(cb, this._isPluginControlsModuleCall);
  710. }
  711. }, {
  712. key: 'hookPluginControlsInit',
  713. value: function hookPluginControlsInit(cb) {
  714. this.hookPluginControls(function (exports) {
  715. var init = exports.prototype.init;
  716. exports.prototype.init = function () {
  717. cb(this);
  718. init.apply(this);
  719. };
  720. });
  721. }
  722. }, {
  723. key: 'hookInitFullScreen',
  724. value: function hookInitFullScreen(cb) {
  725. this.hookPluginControls(function (exports) {
  726. var initFullScreen = exports.prototype.initFullScreen;
  727. exports.prototype.initFullScreen = function () {
  728. cb(this);
  729. initFullScreen.apply(this);
  730. };
  731. });
  732. }
  733. }, {
  734. key: '_isCoreModuleCall',
  735. value: function _isCoreModuleCall(exports) {
  736. return 'function' === typeof exports && exports.prototype.hasOwnProperty('getdefaultvds') && exports.prototype.hasOwnProperty('getMovieInfo');
  737. }
  738. }, {
  739. key: 'hookCore',
  740. value: function hookCore(cb) {
  741. this._hookModuleCall(cb, this._isCoreModuleCall);
  742. }
  743. }, {
  744. key: '_isSkinBaseModuleCall',
  745. value: function _isSkinBaseModuleCall(exports) {
  746. return 'function' === typeof exports && exports.prototype.hasOwnProperty('_checkPlugin');
  747. }
  748. }, {
  749. key: 'hookSkinBase',
  750. value: function hookSkinBase(cb) {
  751. this._hookModuleCall(cb, this._isSkinBaseModuleCall);
  752. }
  753. }, {
  754. key: '_isPluginHotKeysModuleCall',
  755. value: function _isPluginHotKeysModuleCall(exports) {
  756. return 'function' === typeof exports && exports.prototype.hasOwnProperty('_keydown');
  757. }
  758. }, {
  759. key: 'hookPluginHotKeys',
  760. value: function hookPluginHotKeys(cb) {
  761. this._hookModuleCall(cb, this._isPluginHotKeysModuleCall);
  762. }
  763. }, {
  764. key: '_isFragmentModuleCall',
  765. value: function _isFragmentModuleCall(exports) {
  766. return 'function' === typeof exports && exports.prototype.hasOwnProperty('parseData');
  767. }
  768. }, {
  769. key: 'hookFragment',
  770. value: function hookFragment(cb) {
  771. this._hookModuleCall(cb, this._isFragmentModuleCall);
  772. }
  773. }, {
  774. key: 'hookParseData',
  775. value: function hookParseData(cb) {
  776. this.hookFragment(function (exports) {
  777. var parseData = exports.prototype.parseData;
  778. exports.prototype.parseData = function () {
  779. for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  780. args[_key2] = arguments[_key2];
  781. }
  782.  
  783. parseData.apply(this, args);
  784. cb(this);
  785. };
  786. });
  787. }
  788. }]);
  789.  
  790. return Hooker;
  791. }();
  792.  
  793. Hooker.keepalive = false;
  794.  
  795. exports.default = Hooker;
  796.  
  797. /***/ }),
  798. /* 5 */
  799. /***/ (function(module, exports, __webpack_require__) {
  800.  
  801. "use strict";
  802.  
  803.  
  804. Object.defineProperty(exports, "__esModule", {
  805. value: true
  806. });
  807.  
  808. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  809.  
  810. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  811.  
  812. var Cookies = function () {
  813. function Cookies() {
  814. _classCallCheck(this, Cookies);
  815. }
  816.  
  817. _createClass(Cookies, null, [{
  818. key: 'get',
  819. value: function get(key) {
  820. var value = void 0;
  821. if (new RegExp('^[^\\x00-\\x20\\x7f\\(\\)<>@,;:\\\\\\"\\[\\]\\?=\\{\\}\\/\\u0080-\\uffff]+$').test(key)) {
  822. // eslint-disable-line no-control-regex
  823. var re = new RegExp('(^| )' + key + '=([^;]*)(;|$)');
  824. var rs = re.exec(document.cookie);
  825. value = rs ? rs[2] : '';
  826. }
  827. return value ? decodeURIComponent(value) : '';
  828. }
  829. }, {
  830. key: 'set',
  831. value: function set(k, v) {
  832. var o = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
  833.  
  834. var n = o.expires;
  835. if ('number' == typeof o.expires) {
  836. n = new Date();
  837. n.setTime(n.getTime() + o.expires);
  838. }
  839. var key = k;
  840. var value = encodeURIComponent(v);
  841. var path = o.path ? '; path=' + o.path : '';
  842. var expires = n ? '; expires=' + n.toGMTString() : '';
  843. var domain = o.domain ? '; domain=' + o.domain : '';
  844. document.cookie = key + '=' + value + path + expires + domain;
  845. }
  846. }, {
  847. key: 'remove',
  848. value: function remove(k) {
  849. var o = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
  850.  
  851. o.expires = new Date(0);
  852. this.set(k, '', o);
  853. }
  854. }]);
  855.  
  856. return Cookies;
  857. }();
  858.  
  859. exports.default = Cookies;
  860.  
  861. /***/ }),
  862. /* 6 */
  863. /***/ (function(module, exports, __webpack_require__) {
  864.  
  865. "use strict";
  866.  
  867.  
  868. var required = __webpack_require__(24)
  869. , lolcation = __webpack_require__(25)
  870. , qs = __webpack_require__(26)
  871. , relativere = /^\/(?!\/)/;
  872.  
  873. /**
  874. * These are the parse instructions for the URL parsers, it informs the parser
  875. * about:
  876. *
  877. * 0. The char it Needs to parse, if it's a string it should be done using
  878. * indexOf, RegExp using exec and NaN means set as current value.
  879. * 1. The property we should set when parsing this value.
  880. * 2. Indication if it's backwards or forward parsing, when set as number it's
  881. * the value of extra chars that should be split off.
  882. * 3. Inherit from location if non existing in the parser.
  883. * 4. `toLowerCase` the resulting value.
  884. */
  885. var instructions = [
  886. ['#', 'hash'], // Extract from the back.
  887. ['?', 'query'], // Extract from the back.
  888. ['//', 'protocol', 2, 1, 1], // Extract from the front.
  889. ['/', 'pathname'], // Extract from the back.
  890. ['@', 'auth', 1], // Extract from the front.
  891. [NaN, 'host', undefined, 1, 1], // Set left over value.
  892. [/\:(\d+)$/, 'port'], // RegExp the back.
  893. [NaN, 'hostname', undefined, 1, 1] // Set left over.
  894. ];
  895.  
  896. /**
  897. * The actual URL instance. Instead of returning an object we've opted-in to
  898. * create an actual constructor as it's much more memory efficient and
  899. * faster and it pleases my CDO.
  900. *
  901. * @constructor
  902. * @param {String} address URL we want to parse.
  903. * @param {Boolean|function} parser Parser for the query string.
  904. * @param {Object} location Location defaults for relative paths.
  905. * @api public
  906. */
  907. function URL(address, location, parser) {
  908. if (!(this instanceof URL)) {
  909. return new URL(address, location, parser);
  910. }
  911.  
  912. var relative = relativere.test(address)
  913. , parse, instruction, index, key
  914. , type = typeof location
  915. , url = this
  916. , i = 0;
  917.  
  918. //
  919. // The following if statements allows this module two have compatibility with
  920. // 2 different API:
  921. //
  922. // 1. Node.js's `url.parse` api which accepts a URL, boolean as arguments
  923. // where the boolean indicates that the query string should also be parsed.
  924. //
  925. // 2. The `URL` interface of the browser which accepts a URL, object as
  926. // arguments. The supplied object will be used as default values / fall-back
  927. // for relative paths.
  928. //
  929. if ('object' !== type && 'string' !== type) {
  930. parser = location;
  931. location = null;
  932. }
  933.  
  934. if (parser && 'function' !== typeof parser) {
  935. parser = qs.parse;
  936. }
  937.  
  938. location = lolcation(location);
  939.  
  940. for (; i < instructions.length; i++) {
  941. instruction = instructions[i];
  942. parse = instruction[0];
  943. key = instruction[1];
  944.  
  945. if (parse !== parse) {
  946. url[key] = address;
  947. } else if ('string' === typeof parse) {
  948. if (~(index = address.indexOf(parse))) {
  949. if ('number' === typeof instruction[2]) {
  950. url[key] = address.slice(0, index);
  951. address = address.slice(index + instruction[2]);
  952. } else {
  953. url[key] = address.slice(index);
  954. address = address.slice(0, index);
  955. }
  956. }
  957. } else if (index = parse.exec(address)) {
  958. url[key] = index[1];
  959. address = address.slice(0, address.length - index[0].length);
  960. }
  961.  
  962. url[key] = url[key] || (instruction[3] || ('port' === key && relative) ? location[key] || '' : '');
  963.  
  964. //
  965. // Hostname, host and protocol should be lowercased so they can be used to
  966. // create a proper `origin`.
  967. //
  968. if (instruction[4]) {
  969. url[key] = url[key].toLowerCase();
  970. }
  971. }
  972.  
  973. //
  974. // Also parse the supplied query string in to an object. If we're supplied
  975. // with a custom parser as function use that instead of the default build-in
  976. // parser.
  977. //
  978. if (parser) url.query = parser(url.query);
  979.  
  980. //
  981. // We should not add port numbers if they are already the default port number
  982. // for a given protocol. As the host also contains the port number we're going
  983. // override it with the hostname which contains no port number.
  984. //
  985. if (!required(url.port, url.protocol)) {
  986. url.host = url.hostname;
  987. url.port = '';
  988. }
  989.  
  990. //
  991. // Parse down the `auth` for the username and password.
  992. //
  993. url.username = url.password = '';
  994. if (url.auth) {
  995. instruction = url.auth.split(':');
  996. url.username = instruction[0] || '';
  997. url.password = instruction[1] || '';
  998. }
  999.  
  1000. //
  1001. // The href is just the compiled result.
  1002. //
  1003. url.href = url.toString();
  1004. }
  1005.  
  1006. /**
  1007. * This is convenience method for changing properties in the URL instance to
  1008. * insure that they all propagate correctly.
  1009. *
  1010. * @param {String} prop Property we need to adjust.
  1011. * @param {Mixed} value The newly assigned value.
  1012. * @returns {URL}
  1013. * @api public
  1014. */
  1015. URL.prototype.set = function set(part, value, fn) {
  1016. var url = this;
  1017.  
  1018. if ('query' === part) {
  1019. if ('string' === typeof value && value.length) {
  1020. value = (fn || qs.parse)(value);
  1021. }
  1022.  
  1023. url[part] = value;
  1024. } else if ('port' === part) {
  1025. url[part] = value;
  1026.  
  1027. if (!required(value, url.protocol)) {
  1028. url.host = url.hostname;
  1029. url[part] = '';
  1030. } else if (value) {
  1031. url.host = url.hostname +':'+ value;
  1032. }
  1033. } else if ('hostname' === part) {
  1034. url[part] = value;
  1035.  
  1036. if (url.port) value += ':'+ url.port;
  1037. url.host = value;
  1038. } else if ('host' === part) {
  1039. url[part] = value;
  1040.  
  1041. if (/\:\d+/.test(value)) {
  1042. value = value.split(':');
  1043. url.hostname = value[0];
  1044. url.port = value[1];
  1045. }
  1046. } else {
  1047. url[part] = value;
  1048. }
  1049.  
  1050. url.href = url.toString();
  1051. return url;
  1052. };
  1053.  
  1054. /**
  1055. * Transform the properties back in to a valid and full URL string.
  1056. *
  1057. * @param {Function} stringify Optional query stringify function.
  1058. * @returns {String}
  1059. * @api public
  1060. */
  1061. URL.prototype.toString = function toString(stringify) {
  1062. if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;
  1063.  
  1064. var query
  1065. , url = this
  1066. , result = url.protocol +'//';
  1067.  
  1068. if (url.username) {
  1069. result += url.username;
  1070. if (url.password) result += ':'+ url.password;
  1071. result += '@';
  1072. }
  1073.  
  1074. result += url.hostname;
  1075. if (url.port) result += ':'+ url.port;
  1076.  
  1077. result += url.pathname;
  1078.  
  1079. query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  1080. if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;
  1081.  
  1082. if (url.hash) result += url.hash;
  1083.  
  1084. return result;
  1085. };
  1086.  
  1087. //
  1088. // Expose the URL parser and some additional properties that might be useful for
  1089. // others.
  1090. //
  1091. URL.qs = qs;
  1092. URL.location = lolcation;
  1093. module.exports = URL;
  1094.  
  1095.  
  1096. /***/ }),
  1097. /* 7 */
  1098. /***/ (function(module, exports, __webpack_require__) {
  1099.  
  1100. "use strict";
  1101.  
  1102.  
  1103. Object.defineProperty(exports, "__esModule", {
  1104. value: true
  1105. });
  1106.  
  1107. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  1108.  
  1109. var _logger = __webpack_require__(1);
  1110.  
  1111. var _logger2 = _interopRequireDefault(_logger);
  1112.  
  1113. var _cookies = __webpack_require__(5);
  1114.  
  1115. var _cookies2 = _interopRequireDefault(_cookies);
  1116.  
  1117. var _blueimpMd = __webpack_require__(28);
  1118.  
  1119. var _blueimpMd2 = _interopRequireDefault(_blueimpMd);
  1120.  
  1121. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1122.  
  1123. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  1124.  
  1125. var Faker = function () {
  1126. function Faker() {
  1127. _classCallCheck(this, Faker);
  1128. }
  1129.  
  1130. _createClass(Faker, null, [{
  1131. key: 'fakeMacPlatform',
  1132. value: function fakeMacPlatform() {
  1133. var PLAFORM_MAC = 'mac';
  1134. Object.defineProperty(unsafeWindow.navigator, 'platform', { get: function get() {
  1135. return PLAFORM_MAC;
  1136. } });
  1137. }
  1138. }, {
  1139. key: 'fakeSafari',
  1140. value: function fakeSafari() {
  1141. var UA_SAFARY = 'safari';
  1142. Object.defineProperty(unsafeWindow.navigator, 'userAgent', { get: function get() {
  1143. return UA_SAFARY;
  1144. } });
  1145. }
  1146. }, {
  1147. key: 'fakeChrome',
  1148. value: function fakeChrome() {
  1149. var UA_CHROME = 'chrome';
  1150. Object.defineProperty(unsafeWindow.navigator, 'userAgent', { get: function get() {
  1151. return UA_CHROME;
  1152. } });
  1153. }
  1154. }, {
  1155. key: 'fakeFlashPlugin',
  1156. value: function fakeFlashPlugin() {
  1157. var plugin = {
  1158. description: 'Shockwave Flash 26.0 r0',
  1159. filename: 'pepflashplayer64_26_0_0_131.dll',
  1160. length: 0,
  1161. name: 'Shockwave Flash'
  1162. };
  1163.  
  1164. Reflect.setPrototypeOf(plugin, Plugin.prototype);
  1165. unsafeWindow.navigator.plugins['Shockwave Flash'] = plugin;
  1166. }
  1167. }, {
  1168. key: '_calcSign',
  1169. value: function _calcSign(authcookie) {
  1170. var RESPONSE_KEY = '-0J1d9d^ESd)9jSsja';
  1171. return (0, _blueimpMd2.default)(authcookie.substring(5, 39).split('').reverse().join('') + '<1<' + RESPONSE_KEY);
  1172. }
  1173. }, {
  1174. key: 'fakeVipRes',
  1175. value: function fakeVipRes(authcookie) {
  1176. var json = {
  1177. code: 'A00000',
  1178. data: {
  1179. sign: this._calcSign(authcookie)
  1180. }
  1181. };
  1182. return json;
  1183. }
  1184. }, {
  1185. key: 'fakeAdRes',
  1186. value: function fakeAdRes() {
  1187. var json = {};
  1188. return json;
  1189. }
  1190. }, {
  1191. key: 'fakePassportCookie',
  1192. value: function fakePassportCookie() {
  1193. _cookies2.default.set('P00001', 'faked_passport', { domain: '.iqiyi.com' });
  1194. _logger2.default.log('faked passport cookie');
  1195. }
  1196. }]);
  1197.  
  1198. return Faker;
  1199. }();
  1200.  
  1201. exports.default = Faker;
  1202.  
  1203. /***/ }),
  1204. /* 8 */
  1205. /***/ (function(module, exports, __webpack_require__) {
  1206.  
  1207. "use strict";
  1208.  
  1209.  
  1210. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  1211.  
  1212. __webpack_require__(9);
  1213.  
  1214. var _logger = __webpack_require__(1);
  1215.  
  1216. var _logger2 = _interopRequireDefault(_logger);
  1217.  
  1218. var _cookies = __webpack_require__(5);
  1219.  
  1220. var _cookies2 = _interopRequireDefault(_cookies);
  1221.  
  1222. var _detector = __webpack_require__(2);
  1223.  
  1224. var _detector2 = _interopRequireDefault(_detector);
  1225.  
  1226. var _hooker = __webpack_require__(4);
  1227.  
  1228. var _hooker2 = _interopRequireDefault(_hooker);
  1229.  
  1230. var _mocker = __webpack_require__(27);
  1231.  
  1232. var _mocker2 = _interopRequireDefault(_mocker);
  1233.  
  1234. var _patcher = __webpack_require__(29);
  1235.  
  1236. var _patcher2 = _interopRequireDefault(_patcher);
  1237.  
  1238. var _outsite = __webpack_require__(30);
  1239.  
  1240. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1241.  
  1242. var PLAYER_TYPE = {
  1243. Html5VOD: 'h5_VOD',
  1244. FlashVOD: 'flash_VOD'
  1245. };
  1246.  
  1247. function forceHtml5() {
  1248. _logger2.default.log('setting player_forcedType cookie as ' + PLAYER_TYPE.Html5VOD);
  1249. _cookies2.default.set('player_forcedType', PLAYER_TYPE.Html5VOD, { domain: '.iqiyi.com' });
  1250. }
  1251.  
  1252. function forceFlash() {
  1253. _logger2.default.log('setting player_forcedType cookie as ' + PLAYER_TYPE.FlashVOD);
  1254. _cookies2.default.set('player_forcedType', PLAYER_TYPE.FlashVOD, { domain: '.iqiyi.com' });
  1255. }
  1256.  
  1257. function clean() {
  1258. _cookies2.default.remove('player_forcedType', { domain: '.iqiyi.com' });
  1259. if (_cookies2.default.get('P00001') === 'faked_passport') _cookies2.default.remove('P00001', { domain: '.iqiyi.com' });
  1260. _logger2.default.log('removed cookies.');
  1261. }
  1262.  
  1263. function switchTo(toType) {
  1264. _logger2.default.log('switching to ' + toType + ' ...');
  1265.  
  1266. GM_setValue('player_forcedType', toType);
  1267. document.location.reload();
  1268. }
  1269.  
  1270. function registerMenu() {
  1271. var MENU_NAME = {
  1272. HTML5: 'HTML5播放器',
  1273. FLASH: 'Flash播放器'
  1274. };
  1275.  
  1276. var currType = GM_getValue('player_forcedType', PLAYER_TYPE.Html5VOD); // 默认为Html5播放器,免去切换。
  1277.  
  1278. var _ref = currType === PLAYER_TYPE.Html5VOD ? [PLAYER_TYPE.FlashVOD, MENU_NAME.FLASH] : [PLAYER_TYPE.Html5VOD, MENU_NAME.HTML5],
  1279. _ref2 = _slicedToArray(_ref, 2),
  1280. toType = _ref2[0],
  1281. name = _ref2[1];
  1282.  
  1283. GM_registerMenuCommand(name, function () {
  1284. return switchTo(toType);
  1285. }, null);
  1286. _logger2.default.log('registered menu.');
  1287. }
  1288.  
  1289. //=============================================================================
  1290.  
  1291. registerMenu();
  1292.  
  1293. var currType = GM_getValue('player_forcedType', PLAYER_TYPE.Html5VOD);
  1294. if (currType === PLAYER_TYPE.Html5VOD) {
  1295. if (_detector2.default.isSupportHtml5()) {
  1296. if (_detector2.default.isOutsite()) {
  1297. (0, _outsite.replaceFlash)();
  1298. } else {
  1299. if (location.search.includes('list')) {
  1300. _hooker2.default.keepalive = true;
  1301. _logger2.default.log('keepalive hooks');
  1302. }
  1303. forceHtml5();
  1304. _mocker2.default.mock();
  1305. _patcher2.default.patchShortcuts();
  1306.  
  1307. if (_detector2.default.isInnerFrame()) (0, _outsite.adaptIframe)();
  1308. }
  1309. } else {
  1310. alert('╮(╯▽╰)╭ 你的浏览器播放不了html5视频~~~~');
  1311. }
  1312. } else {
  1313. forceFlash();
  1314. }
  1315.  
  1316. window.addEventListener('unload', function () {
  1317. return clean();
  1318. });
  1319.  
  1320. /***/ }),
  1321. /* 9 */
  1322. /***/ (function(module, exports, __webpack_require__) {
  1323.  
  1324. "use strict";
  1325.  
  1326.  
  1327. __webpack_require__(10);
  1328.  
  1329. __webpack_require__(21);
  1330.  
  1331. var _src = __webpack_require__(22);
  1332.  
  1333. var _src2 = _interopRequireDefault(_src);
  1334.  
  1335. var _logger = __webpack_require__(1);
  1336.  
  1337. var _logger2 = _interopRequireDefault(_logger);
  1338.  
  1339. var _detector = __webpack_require__(2);
  1340.  
  1341. var _detector2 = _interopRequireDefault(_detector);
  1342.  
  1343. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  1344.  
  1345. function isVideoReq(url) {
  1346. var u = new URL(url);
  1347. return u.pathname.startsWith('/videos/') && u.pathname.endsWith('.f4v');
  1348. }
  1349.  
  1350. if (_detector2.default.isFirefox()) {
  1351. var fetch = unsafeWindow.fetch.bind(unsafeWindow);
  1352.  
  1353. unsafeWindow.fetch = function (url, opts) {
  1354. if (isVideoReq(url)) {
  1355. _logger2.default.log('fetching stream ' + url);
  1356. return (0, _src2.default)(url, opts); // xhr with moz-chunked-arraybuffer
  1357. } else {
  1358. return fetch(url, opts);
  1359. }
  1360. };
  1361. }
  1362.  
  1363. /***/ }),
  1364. /* 10 */
  1365. /***/ (function(module, exports, __webpack_require__) {
  1366.  
  1367. "use strict";
  1368. /* WEBPACK VAR INJECTION */(function(global) {/*
  1369. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1370. *
  1371. * Use of this source code is governed by a BSD-style license
  1372. * that can be found in the LICENSE file in the root of the source
  1373. * tree.
  1374. */
  1375. /* eslint-env node */
  1376.  
  1377.  
  1378.  
  1379. var adapterFactory = __webpack_require__(11);
  1380. module.exports = adapterFactory({window: global.window});
  1381.  
  1382. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  1383.  
  1384. /***/ }),
  1385. /* 11 */
  1386. /***/ (function(module, exports, __webpack_require__) {
  1387.  
  1388. "use strict";
  1389. /*
  1390. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1391. *
  1392. * Use of this source code is governed by a BSD-style license
  1393. * that can be found in the LICENSE file in the root of the source
  1394. * tree.
  1395. */
  1396. /* eslint-env node */
  1397.  
  1398.  
  1399.  
  1400. // Shimming starts here.
  1401. module.exports = function(dependencies, opts) {
  1402. var window = dependencies && dependencies.window;
  1403.  
  1404. var options = Object.assign({
  1405. shimChrome: true,
  1406. shimFirefox: true,
  1407. shimEdge: true,
  1408. shimSafari: true,
  1409. }, opts);
  1410.  
  1411. // Utils.
  1412. var utils = __webpack_require__(0);
  1413. var logging = utils.log;
  1414. var browserDetails = utils.detectBrowser(window);
  1415.  
  1416. // Export to the adapter global object visible in the browser.
  1417. var adapter = {
  1418. browserDetails: browserDetails,
  1419. extractVersion: utils.extractVersion,
  1420. disableLog: utils.disableLog,
  1421. disableWarnings: utils.disableWarnings
  1422. };
  1423.  
  1424. // Uncomment the line below if you want logging to occur, including logging
  1425. // for the switch statement below. Can also be turned on in the browser via
  1426. // adapter.disableLog(false), but then logging from the switch statement below
  1427. // will not appear.
  1428. // require('./utils').disableLog(false);
  1429.  
  1430. // Browser shims.
  1431. var chromeShim = __webpack_require__(12) || null;
  1432. var edgeShim = __webpack_require__(14) || null;
  1433. var firefoxShim = __webpack_require__(18) || null;
  1434. var safariShim = __webpack_require__(20) || null;
  1435.  
  1436. // Shim browser if found.
  1437. switch (browserDetails.browser) {
  1438. case 'chrome':
  1439. if (!chromeShim || !chromeShim.shimPeerConnection ||
  1440. !options.shimChrome) {
  1441. logging('Chrome shim is not included in this adapter release.');
  1442. return adapter;
  1443. }
  1444. logging('adapter.js shimming chrome.');
  1445. // Export to the adapter global object visible in the browser.
  1446. adapter.browserShim = chromeShim;
  1447.  
  1448. chromeShim.shimGetUserMedia(window);
  1449. chromeShim.shimMediaStream(window);
  1450. utils.shimCreateObjectURL(window);
  1451. chromeShim.shimSourceObject(window);
  1452. chromeShim.shimPeerConnection(window);
  1453. chromeShim.shimOnTrack(window);
  1454. chromeShim.shimAddTrack(window);
  1455. chromeShim.shimGetSendersWithDtmf(window);
  1456. break;
  1457. case 'firefox':
  1458. if (!firefoxShim || !firefoxShim.shimPeerConnection ||
  1459. !options.shimFirefox) {
  1460. logging('Firefox shim is not included in this adapter release.');
  1461. return adapter;
  1462. }
  1463. logging('adapter.js shimming firefox.');
  1464. // Export to the adapter global object visible in the browser.
  1465. adapter.browserShim = firefoxShim;
  1466.  
  1467. firefoxShim.shimGetUserMedia(window);
  1468. utils.shimCreateObjectURL(window);
  1469. firefoxShim.shimSourceObject(window);
  1470. firefoxShim.shimPeerConnection(window);
  1471. firefoxShim.shimOnTrack(window);
  1472. break;
  1473. case 'edge':
  1474. if (!edgeShim || !edgeShim.shimPeerConnection || !options.shimEdge) {
  1475. logging('MS edge shim is not included in this adapter release.');
  1476. return adapter;
  1477. }
  1478. logging('adapter.js shimming edge.');
  1479. // Export to the adapter global object visible in the browser.
  1480. adapter.browserShim = edgeShim;
  1481.  
  1482. edgeShim.shimGetUserMedia(window);
  1483. utils.shimCreateObjectURL(window);
  1484. edgeShim.shimPeerConnection(window);
  1485. edgeShim.shimReplaceTrack(window);
  1486. break;
  1487. case 'safari':
  1488. if (!safariShim || !options.shimSafari) {
  1489. logging('Safari shim is not included in this adapter release.');
  1490. return adapter;
  1491. }
  1492. logging('adapter.js shimming safari.');
  1493. // Export to the adapter global object visible in the browser.
  1494. adapter.browserShim = safariShim;
  1495. // shim window.URL.createObjectURL Safari (technical preview)
  1496. utils.shimCreateObjectURL(window);
  1497. safariShim.shimRTCIceServerUrls(window);
  1498. safariShim.shimCallbacksAPI(window);
  1499. safariShim.shimLocalStreamsAPI(window);
  1500. safariShim.shimRemoteStreamsAPI(window);
  1501. safariShim.shimGetUserMedia(window);
  1502. break;
  1503. default:
  1504. logging('Unsupported browser!');
  1505. break;
  1506. }
  1507.  
  1508. return adapter;
  1509. };
  1510.  
  1511.  
  1512. /***/ }),
  1513. /* 12 */
  1514. /***/ (function(module, exports, __webpack_require__) {
  1515.  
  1516. "use strict";
  1517.  
  1518. /*
  1519. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  1520. *
  1521. * Use of this source code is governed by a BSD-style license
  1522. * that can be found in the LICENSE file in the root of the source
  1523. * tree.
  1524. */
  1525. /* eslint-env node */
  1526.  
  1527. var utils = __webpack_require__(0);
  1528. var logging = utils.log;
  1529.  
  1530. var chromeShim = {
  1531. shimMediaStream: function(window) {
  1532. window.MediaStream = window.MediaStream || window.webkitMediaStream;
  1533. },
  1534.  
  1535. shimOnTrack: function(window) {
  1536. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  1537. window.RTCPeerConnection.prototype)) {
  1538. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  1539. get: function() {
  1540. return this._ontrack;
  1541. },
  1542. set: function(f) {
  1543. var self = this;
  1544. if (this._ontrack) {
  1545. this.removeEventListener('track', this._ontrack);
  1546. this.removeEventListener('addstream', this._ontrackpoly);
  1547. }
  1548. this.addEventListener('track', this._ontrack = f);
  1549. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  1550. // onaddstream does not fire when a track is added to an existing
  1551. // stream. But stream.onaddtrack is implemented so we use that.
  1552. e.stream.addEventListener('addtrack', function(te) {
  1553. var receiver;
  1554. if (window.RTCPeerConnection.prototype.getReceivers) {
  1555. receiver = self.getReceivers().find(function(r) {
  1556. return r.track.id === te.track.id;
  1557. });
  1558. } else {
  1559. receiver = {track: te.track};
  1560. }
  1561.  
  1562. var event = new Event('track');
  1563. event.track = te.track;
  1564. event.receiver = receiver;
  1565. event.streams = [e.stream];
  1566. self.dispatchEvent(event);
  1567. });
  1568. e.stream.getTracks().forEach(function(track) {
  1569. var receiver;
  1570. if (window.RTCPeerConnection.prototype.getReceivers) {
  1571. receiver = self.getReceivers().find(function(r) {
  1572. return r.track.id === track.id;
  1573. });
  1574. } else {
  1575. receiver = {track: track};
  1576. }
  1577. var event = new Event('track');
  1578. event.track = track;
  1579. event.receiver = receiver;
  1580. event.streams = [e.stream];
  1581. this.dispatchEvent(event);
  1582. }.bind(this));
  1583. }.bind(this));
  1584. }
  1585. });
  1586. }
  1587. },
  1588.  
  1589. shimGetSendersWithDtmf: function(window) {
  1590. if (typeof window === 'object' && window.RTCPeerConnection &&
  1591. !('getSenders' in window.RTCPeerConnection.prototype) &&
  1592. 'createDTMFSender' in window.RTCPeerConnection.prototype) {
  1593. var shimSenderWithDtmf = function(pc, track) {
  1594. return {
  1595. track: track,
  1596. get dtmf() {
  1597. if (this._dtmf === undefined) {
  1598. if (track.kind === 'audio') {
  1599. this._dtmf = pc.createDTMFSender(track);
  1600. } else {
  1601. this._dtmf = null;
  1602. }
  1603. }
  1604. return this._dtmf;
  1605. }
  1606. };
  1607. };
  1608.  
  1609. // shim addTrack when getSenders is not available.
  1610. if (!window.RTCPeerConnection.prototype.getSenders) {
  1611. window.RTCPeerConnection.prototype.getSenders = function() {
  1612. return this._senders || [];
  1613. };
  1614. var origAddTrack = window.RTCPeerConnection.prototype.addTrack;
  1615. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  1616. var pc = this;
  1617. var sender = origAddTrack.apply(pc, arguments);
  1618. if (!sender) {
  1619. sender = shimSenderWithDtmf(pc, track);
  1620. pc._senders.push(sender);
  1621. }
  1622. return sender;
  1623. };
  1624. }
  1625. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  1626. window.RTCPeerConnection.prototype.addStream = function(stream) {
  1627. var pc = this;
  1628. pc._senders = pc._senders || [];
  1629. origAddStream.apply(pc, [stream]);
  1630. stream.getTracks().forEach(function(track) {
  1631. pc._senders.push(shimSenderWithDtmf(pc, track));
  1632. });
  1633. };
  1634.  
  1635. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1636. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  1637. var pc = this;
  1638. pc._senders = pc._senders || [];
  1639. origRemoveStream.apply(pc, [(pc._streams[stream.id] || stream)]);
  1640.  
  1641. stream.getTracks().forEach(function(track) {
  1642. var sender = pc._senders.find(function(s) {
  1643. return s.track === track;
  1644. });
  1645. if (sender) {
  1646. pc._senders.splice(pc._senders.indexOf(sender), 1); // remove sender
  1647. }
  1648. });
  1649. };
  1650. } else if (typeof window === 'object' && window.RTCPeerConnection &&
  1651. 'getSenders' in window.RTCPeerConnection.prototype &&
  1652. 'createDTMFSender' in window.RTCPeerConnection.prototype &&
  1653. window.RTCRtpSender &&
  1654. !('dtmf' in window.RTCRtpSender.prototype)) {
  1655. var origGetSenders = window.RTCPeerConnection.prototype.getSenders;
  1656. window.RTCPeerConnection.prototype.getSenders = function() {
  1657. var pc = this;
  1658. var senders = origGetSenders.apply(pc, []);
  1659. senders.forEach(function(sender) {
  1660. sender._pc = pc;
  1661. });
  1662. return senders;
  1663. };
  1664.  
  1665. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  1666. get: function() {
  1667. if (this._dtmf === undefined) {
  1668. if (this.track.kind === 'audio') {
  1669. this._dtmf = this._pc.createDTMFSender(this.track);
  1670. } else {
  1671. this._dtmf = null;
  1672. }
  1673. }
  1674. return this._dtmf;
  1675. },
  1676. });
  1677. }
  1678. },
  1679.  
  1680. shimSourceObject: function(window) {
  1681. var URL = window && window.URL;
  1682.  
  1683. if (typeof window === 'object') {
  1684. if (window.HTMLMediaElement &&
  1685. !('srcObject' in window.HTMLMediaElement.prototype)) {
  1686. // Shim the srcObject property, once, when HTMLMediaElement is found.
  1687. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  1688. get: function() {
  1689. return this._srcObject;
  1690. },
  1691. set: function(stream) {
  1692. var self = this;
  1693. // Use _srcObject as a private property for this shim
  1694. this._srcObject = stream;
  1695. if (this.src) {
  1696. URL.revokeObjectURL(this.src);
  1697. }
  1698.  
  1699. if (!stream) {
  1700. this.src = '';
  1701. return undefined;
  1702. }
  1703. this.src = URL.createObjectURL(stream);
  1704. // We need to recreate the blob url when a track is added or
  1705. // removed. Doing it manually since we want to avoid a recursion.
  1706. stream.addEventListener('addtrack', function() {
  1707. if (self.src) {
  1708. URL.revokeObjectURL(self.src);
  1709. }
  1710. self.src = URL.createObjectURL(stream);
  1711. });
  1712. stream.addEventListener('removetrack', function() {
  1713. if (self.src) {
  1714. URL.revokeObjectURL(self.src);
  1715. }
  1716. self.src = URL.createObjectURL(stream);
  1717. });
  1718. }
  1719. });
  1720. }
  1721. }
  1722. },
  1723.  
  1724. shimAddTrack: function(window) {
  1725. // shim addTrack (when getSenders is available)
  1726. if (window.RTCPeerConnection.prototype.addTrack) {
  1727. return;
  1728. }
  1729.  
  1730. // also shim pc.getLocalStreams when addTrack is shimmed
  1731. // to return the original streams.
  1732. var origGetLocalStreams = window.RTCPeerConnection.prototype
  1733. .getLocalStreams;
  1734. window.RTCPeerConnection.prototype.getLocalStreams = function() {
  1735. var self = this;
  1736. var nativeStreams = origGetLocalStreams.apply(this);
  1737. self._reverseStreams = self._reverseStreams || {};
  1738. return nativeStreams.map(function(stream) {
  1739. return self._reverseStreams[stream.id];
  1740. });
  1741. };
  1742.  
  1743. var origAddStream = window.RTCPeerConnection.prototype.addStream;
  1744. window.RTCPeerConnection.prototype.addStream = function(stream) {
  1745. var pc = this;
  1746. pc._streams = pc._streams || {};
  1747. pc._reverseStreams = pc._reverseStreams || {};
  1748.  
  1749. // Add identity mapping for consistency with addTrack.
  1750. // Unless this is being used with a stream from addTrack.
  1751. if (!pc._reverseStreams[stream.id]) {
  1752. pc._streams[stream.id] = stream;
  1753. pc._reverseStreams[stream.id] = stream;
  1754. }
  1755. origAddStream.apply(pc, [stream]);
  1756. };
  1757.  
  1758. var origRemoveStream = window.RTCPeerConnection.prototype.removeStream;
  1759. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  1760. var pc = this;
  1761. pc._streams = pc._streams || {};
  1762. pc._reverseStreams = pc._reverseStreams || {};
  1763.  
  1764. origRemoveStream.apply(pc, [(pc._streams[stream.id] || stream)]);
  1765. delete pc._reverseStreams[(pc._streams[stream.id] ?
  1766. pc._streams[stream.id].id : stream.id)];
  1767. delete pc._streams[stream.id];
  1768. };
  1769.  
  1770. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  1771. var pc = this;
  1772. if (pc.signalingState === 'closed') {
  1773. throw new DOMException(
  1774. 'The RTCPeerConnection\'s signalingState is \'closed\'.',
  1775. 'InvalidStateError');
  1776. }
  1777. var streams = [].slice.call(arguments, 1);
  1778. if (streams.length !== 1 ||
  1779. !streams[0].getTracks().find(function(t) {
  1780. return t === track;
  1781. })) {
  1782. // this is not fully correct but all we can manage without
  1783. // [[associated MediaStreams]] internal slot.
  1784. throw new DOMException(
  1785. 'The adapter.js addTrack polyfill only supports a single ' +
  1786. ' stream which is associated with the specified track.',
  1787. 'NotSupportedError');
  1788. }
  1789.  
  1790. var alreadyExists = pc.getSenders().find(function(s) {
  1791. return s.track === track;
  1792. });
  1793. if (alreadyExists) {
  1794. throw new DOMException('Track already exists.',
  1795. 'InvalidAccessError');
  1796. }
  1797.  
  1798. pc._streams = pc._streams || {};
  1799. pc._reverseStreams = pc._reverseStreams || {};
  1800. var oldStream = pc._streams[stream.id];
  1801. if (oldStream) {
  1802. // this is using odd Chrome behaviour, use with caution:
  1803. // https://bugs.chromium.org/p/webrtc/issues/detail?id=7815
  1804. oldStream.addTrack(track);
  1805. pc.dispatchEvent(new Event('negotiationneeded'));
  1806. } else {
  1807. var newStream = new window.MediaStream([track]);
  1808. pc._streams[stream.id] = newStream;
  1809. pc._reverseStreams[newStream.id] = stream;
  1810. pc.addStream(newStream);
  1811. }
  1812. return pc.getSenders().find(function(s) {
  1813. return s.track === track;
  1814. });
  1815. };
  1816. },
  1817.  
  1818. shimPeerConnection: function(window) {
  1819. var browserDetails = utils.detectBrowser(window);
  1820.  
  1821. // The RTCPeerConnection object.
  1822. if (!window.RTCPeerConnection) {
  1823. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  1824. // Translate iceTransportPolicy to iceTransports,
  1825. // see https://code.google.com/p/webrtc/issues/detail?id=4869
  1826. // this was fixed in M56 along with unprefixing RTCPeerConnection.
  1827. logging('PeerConnection');
  1828. if (pcConfig && pcConfig.iceTransportPolicy) {
  1829. pcConfig.iceTransports = pcConfig.iceTransportPolicy;
  1830. }
  1831.  
  1832. return new window.webkitRTCPeerConnection(pcConfig, pcConstraints);
  1833. };
  1834. window.RTCPeerConnection.prototype =
  1835. window.webkitRTCPeerConnection.prototype;
  1836. // wrap static methods. Currently just generateCertificate.
  1837. if (window.webkitRTCPeerConnection.generateCertificate) {
  1838. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  1839. get: function() {
  1840. return window.webkitRTCPeerConnection.generateCertificate;
  1841. }
  1842. });
  1843. }
  1844. } else {
  1845. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  1846. var OrigPeerConnection = window.RTCPeerConnection;
  1847. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  1848. if (pcConfig && pcConfig.iceServers) {
  1849. var newIceServers = [];
  1850. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  1851. var server = pcConfig.iceServers[i];
  1852. if (!server.hasOwnProperty('urls') &&
  1853. server.hasOwnProperty('url')) {
  1854. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  1855. server = JSON.parse(JSON.stringify(server));
  1856. server.urls = server.url;
  1857. newIceServers.push(server);
  1858. } else {
  1859. newIceServers.push(pcConfig.iceServers[i]);
  1860. }
  1861. }
  1862. pcConfig.iceServers = newIceServers;
  1863. }
  1864. return new OrigPeerConnection(pcConfig, pcConstraints);
  1865. };
  1866. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  1867. // wrap static methods. Currently just generateCertificate.
  1868. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  1869. get: function() {
  1870. return OrigPeerConnection.generateCertificate;
  1871. }
  1872. });
  1873. }
  1874.  
  1875. var origGetStats = window.RTCPeerConnection.prototype.getStats;
  1876. window.RTCPeerConnection.prototype.getStats = function(selector,
  1877. successCallback, errorCallback) {
  1878. var self = this;
  1879. var args = arguments;
  1880.  
  1881. // If selector is a function then we are in the old style stats so just
  1882. // pass back the original getStats format to avoid breaking old users.
  1883. if (arguments.length > 0 && typeof selector === 'function') {
  1884. return origGetStats.apply(this, arguments);
  1885. }
  1886.  
  1887. // When spec-style getStats is supported, return those when called with
  1888. // either no arguments or the selector argument is null.
  1889. if (origGetStats.length === 0 && (arguments.length === 0 ||
  1890. typeof arguments[0] !== 'function')) {
  1891. return origGetStats.apply(this, []);
  1892. }
  1893.  
  1894. var fixChromeStats_ = function(response) {
  1895. var standardReport = {};
  1896. var reports = response.result();
  1897. reports.forEach(function(report) {
  1898. var standardStats = {
  1899. id: report.id,
  1900. timestamp: report.timestamp,
  1901. type: {
  1902. localcandidate: 'local-candidate',
  1903. remotecandidate: 'remote-candidate'
  1904. }[report.type] || report.type
  1905. };
  1906. report.names().forEach(function(name) {
  1907. standardStats[name] = report.stat(name);
  1908. });
  1909. standardReport[standardStats.id] = standardStats;
  1910. });
  1911.  
  1912. return standardReport;
  1913. };
  1914.  
  1915. // shim getStats with maplike support
  1916. var makeMapStats = function(stats) {
  1917. return new Map(Object.keys(stats).map(function(key) {
  1918. return [key, stats[key]];
  1919. }));
  1920. };
  1921.  
  1922. if (arguments.length >= 2) {
  1923. var successCallbackWrapper_ = function(response) {
  1924. args[1](makeMapStats(fixChromeStats_(response)));
  1925. };
  1926.  
  1927. return origGetStats.apply(this, [successCallbackWrapper_,
  1928. arguments[0]]);
  1929. }
  1930.  
  1931. // promise-support
  1932. return new Promise(function(resolve, reject) {
  1933. origGetStats.apply(self, [
  1934. function(response) {
  1935. resolve(makeMapStats(fixChromeStats_(response)));
  1936. }, reject]);
  1937. }).then(successCallback, errorCallback);
  1938. };
  1939.  
  1940. // add promise support -- natively available in Chrome 51
  1941. if (browserDetails.version < 51) {
  1942. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  1943. .forEach(function(method) {
  1944. var nativeMethod = window.RTCPeerConnection.prototype[method];
  1945. window.RTCPeerConnection.prototype[method] = function() {
  1946. var args = arguments;
  1947. var self = this;
  1948. var promise = new Promise(function(resolve, reject) {
  1949. nativeMethod.apply(self, [args[0], resolve, reject]);
  1950. });
  1951. if (args.length < 2) {
  1952. return promise;
  1953. }
  1954. return promise.then(function() {
  1955. args[1].apply(null, []);
  1956. },
  1957. function(err) {
  1958. if (args.length >= 3) {
  1959. args[2].apply(null, [err]);
  1960. }
  1961. });
  1962. };
  1963. });
  1964. }
  1965.  
  1966. // promise support for createOffer and createAnswer. Available (without
  1967. // bugs) since M52: crbug/619289
  1968. if (browserDetails.version < 52) {
  1969. ['createOffer', 'createAnswer'].forEach(function(method) {
  1970. var nativeMethod = window.RTCPeerConnection.prototype[method];
  1971. window.RTCPeerConnection.prototype[method] = function() {
  1972. var self = this;
  1973. if (arguments.length < 1 || (arguments.length === 1 &&
  1974. typeof arguments[0] === 'object')) {
  1975. var opts = arguments.length === 1 ? arguments[0] : undefined;
  1976. return new Promise(function(resolve, reject) {
  1977. nativeMethod.apply(self, [resolve, reject, opts]);
  1978. });
  1979. }
  1980. return nativeMethod.apply(this, arguments);
  1981. };
  1982. });
  1983. }
  1984.  
  1985. // shim implicit creation of RTCSessionDescription/RTCIceCandidate
  1986. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  1987. .forEach(function(method) {
  1988. var nativeMethod = window.RTCPeerConnection.prototype[method];
  1989. window.RTCPeerConnection.prototype[method] = function() {
  1990. arguments[0] = new ((method === 'addIceCandidate') ?
  1991. window.RTCIceCandidate :
  1992. window.RTCSessionDescription)(arguments[0]);
  1993. return nativeMethod.apply(this, arguments);
  1994. };
  1995. });
  1996.  
  1997. // support for addIceCandidate(null or undefined)
  1998. var nativeAddIceCandidate =
  1999. window.RTCPeerConnection.prototype.addIceCandidate;
  2000. window.RTCPeerConnection.prototype.addIceCandidate = function() {
  2001. if (!arguments[0]) {
  2002. if (arguments[1]) {
  2003. arguments[1].apply(null);
  2004. }
  2005. return Promise.resolve();
  2006. }
  2007. return nativeAddIceCandidate.apply(this, arguments);
  2008. };
  2009. }
  2010. };
  2011.  
  2012.  
  2013. // Expose public methods.
  2014. module.exports = {
  2015. shimMediaStream: chromeShim.shimMediaStream,
  2016. shimOnTrack: chromeShim.shimOnTrack,
  2017. shimAddTrack: chromeShim.shimAddTrack,
  2018. shimGetSendersWithDtmf: chromeShim.shimGetSendersWithDtmf,
  2019. shimSourceObject: chromeShim.shimSourceObject,
  2020. shimPeerConnection: chromeShim.shimPeerConnection,
  2021. shimGetUserMedia: __webpack_require__(13)
  2022. };
  2023.  
  2024.  
  2025. /***/ }),
  2026. /* 13 */
  2027. /***/ (function(module, exports, __webpack_require__) {
  2028.  
  2029. "use strict";
  2030. /*
  2031. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2032. *
  2033. * Use of this source code is governed by a BSD-style license
  2034. * that can be found in the LICENSE file in the root of the source
  2035. * tree.
  2036. */
  2037. /* eslint-env node */
  2038.  
  2039. var utils = __webpack_require__(0);
  2040. var logging = utils.log;
  2041.  
  2042. // Expose public methods.
  2043. module.exports = function(window) {
  2044. var browserDetails = utils.detectBrowser(window);
  2045. var navigator = window && window.navigator;
  2046.  
  2047. var constraintsToChrome_ = function(c) {
  2048. if (typeof c !== 'object' || c.mandatory || c.optional) {
  2049. return c;
  2050. }
  2051. var cc = {};
  2052. Object.keys(c).forEach(function(key) {
  2053. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  2054. return;
  2055. }
  2056. var r = (typeof c[key] === 'object') ? c[key] : {ideal: c[key]};
  2057. if (r.exact !== undefined && typeof r.exact === 'number') {
  2058. r.min = r.max = r.exact;
  2059. }
  2060. var oldname_ = function(prefix, name) {
  2061. if (prefix) {
  2062. return prefix + name.charAt(0).toUpperCase() + name.slice(1);
  2063. }
  2064. return (name === 'deviceId') ? 'sourceId' : name;
  2065. };
  2066. if (r.ideal !== undefined) {
  2067. cc.optional = cc.optional || [];
  2068. var oc = {};
  2069. if (typeof r.ideal === 'number') {
  2070. oc[oldname_('min', key)] = r.ideal;
  2071. cc.optional.push(oc);
  2072. oc = {};
  2073. oc[oldname_('max', key)] = r.ideal;
  2074. cc.optional.push(oc);
  2075. } else {
  2076. oc[oldname_('', key)] = r.ideal;
  2077. cc.optional.push(oc);
  2078. }
  2079. }
  2080. if (r.exact !== undefined && typeof r.exact !== 'number') {
  2081. cc.mandatory = cc.mandatory || {};
  2082. cc.mandatory[oldname_('', key)] = r.exact;
  2083. } else {
  2084. ['min', 'max'].forEach(function(mix) {
  2085. if (r[mix] !== undefined) {
  2086. cc.mandatory = cc.mandatory || {};
  2087. cc.mandatory[oldname_(mix, key)] = r[mix];
  2088. }
  2089. });
  2090. }
  2091. });
  2092. if (c.advanced) {
  2093. cc.optional = (cc.optional || []).concat(c.advanced);
  2094. }
  2095. return cc;
  2096. };
  2097.  
  2098. var shimConstraints_ = function(constraints, func) {
  2099. constraints = JSON.parse(JSON.stringify(constraints));
  2100. if (constraints && typeof constraints.audio === 'object') {
  2101. var remap = function(obj, a, b) {
  2102. if (a in obj && !(b in obj)) {
  2103. obj[b] = obj[a];
  2104. delete obj[a];
  2105. }
  2106. };
  2107. constraints = JSON.parse(JSON.stringify(constraints));
  2108. remap(constraints.audio, 'autoGainControl', 'googAutoGainControl');
  2109. remap(constraints.audio, 'noiseSuppression', 'googNoiseSuppression');
  2110. constraints.audio = constraintsToChrome_(constraints.audio);
  2111. }
  2112. if (constraints && typeof constraints.video === 'object') {
  2113. // Shim facingMode for mobile & surface pro.
  2114. var face = constraints.video.facingMode;
  2115. face = face && ((typeof face === 'object') ? face : {ideal: face});
  2116. var getSupportedFacingModeLies = browserDetails.version < 61;
  2117.  
  2118. if ((face && (face.exact === 'user' || face.exact === 'environment' ||
  2119. face.ideal === 'user' || face.ideal === 'environment')) &&
  2120. !(navigator.mediaDevices.getSupportedConstraints &&
  2121. navigator.mediaDevices.getSupportedConstraints().facingMode &&
  2122. !getSupportedFacingModeLies)) {
  2123. delete constraints.video.facingMode;
  2124. var matches;
  2125. if (face.exact === 'environment' || face.ideal === 'environment') {
  2126. matches = ['back', 'rear'];
  2127. } else if (face.exact === 'user' || face.ideal === 'user') {
  2128. matches = ['front'];
  2129. }
  2130. if (matches) {
  2131. // Look for matches in label, or use last cam for back (typical).
  2132. return navigator.mediaDevices.enumerateDevices()
  2133. .then(function(devices) {
  2134. devices = devices.filter(function(d) {
  2135. return d.kind === 'videoinput';
  2136. });
  2137. var dev = devices.find(function(d) {
  2138. return matches.some(function(match) {
  2139. return d.label.toLowerCase().indexOf(match) !== -1;
  2140. });
  2141. });
  2142. if (!dev && devices.length && matches.indexOf('back') !== -1) {
  2143. dev = devices[devices.length - 1]; // more likely the back cam
  2144. }
  2145. if (dev) {
  2146. constraints.video.deviceId = face.exact ? {exact: dev.deviceId} :
  2147. {ideal: dev.deviceId};
  2148. }
  2149. constraints.video = constraintsToChrome_(constraints.video);
  2150. logging('chrome: ' + JSON.stringify(constraints));
  2151. return func(constraints);
  2152. });
  2153. }
  2154. }
  2155. constraints.video = constraintsToChrome_(constraints.video);
  2156. }
  2157. logging('chrome: ' + JSON.stringify(constraints));
  2158. return func(constraints);
  2159. };
  2160.  
  2161. var shimError_ = function(e) {
  2162. return {
  2163. name: {
  2164. PermissionDeniedError: 'NotAllowedError',
  2165. InvalidStateError: 'NotReadableError',
  2166. DevicesNotFoundError: 'NotFoundError',
  2167. ConstraintNotSatisfiedError: 'OverconstrainedError',
  2168. TrackStartError: 'NotReadableError',
  2169. MediaDeviceFailedDueToShutdown: 'NotReadableError',
  2170. MediaDeviceKillSwitchOn: 'NotReadableError'
  2171. }[e.name] || e.name,
  2172. message: e.message,
  2173. constraint: e.constraintName,
  2174. toString: function() {
  2175. return this.name + (this.message && ': ') + this.message;
  2176. }
  2177. };
  2178. };
  2179.  
  2180. var getUserMedia_ = function(constraints, onSuccess, onError) {
  2181. shimConstraints_(constraints, function(c) {
  2182. navigator.webkitGetUserMedia(c, onSuccess, function(e) {
  2183. onError(shimError_(e));
  2184. });
  2185. });
  2186. };
  2187.  
  2188. navigator.getUserMedia = getUserMedia_;
  2189.  
  2190. // Returns the result of getUserMedia as a Promise.
  2191. var getUserMediaPromise_ = function(constraints) {
  2192. return new Promise(function(resolve, reject) {
  2193. navigator.getUserMedia(constraints, resolve, reject);
  2194. });
  2195. };
  2196.  
  2197. if (!navigator.mediaDevices) {
  2198. navigator.mediaDevices = {
  2199. getUserMedia: getUserMediaPromise_,
  2200. enumerateDevices: function() {
  2201. return new Promise(function(resolve) {
  2202. var kinds = {audio: 'audioinput', video: 'videoinput'};
  2203. return window.MediaStreamTrack.getSources(function(devices) {
  2204. resolve(devices.map(function(device) {
  2205. return {label: device.label,
  2206. kind: kinds[device.kind],
  2207. deviceId: device.id,
  2208. groupId: ''};
  2209. }));
  2210. });
  2211. });
  2212. },
  2213. getSupportedConstraints: function() {
  2214. return {
  2215. deviceId: true, echoCancellation: true, facingMode: true,
  2216. frameRate: true, height: true, width: true
  2217. };
  2218. }
  2219. };
  2220. }
  2221.  
  2222. // A shim for getUserMedia method on the mediaDevices object.
  2223. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  2224. if (!navigator.mediaDevices.getUserMedia) {
  2225. navigator.mediaDevices.getUserMedia = function(constraints) {
  2226. return getUserMediaPromise_(constraints);
  2227. };
  2228. } else {
  2229. // Even though Chrome 45 has navigator.mediaDevices and a getUserMedia
  2230. // function which returns a Promise, it does not accept spec-style
  2231. // constraints.
  2232. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  2233. bind(navigator.mediaDevices);
  2234. navigator.mediaDevices.getUserMedia = function(cs) {
  2235. return shimConstraints_(cs, function(c) {
  2236. return origGetUserMedia(c).then(function(stream) {
  2237. if (c.audio && !stream.getAudioTracks().length ||
  2238. c.video && !stream.getVideoTracks().length) {
  2239. stream.getTracks().forEach(function(track) {
  2240. track.stop();
  2241. });
  2242. throw new DOMException('', 'NotFoundError');
  2243. }
  2244. return stream;
  2245. }, function(e) {
  2246. return Promise.reject(shimError_(e));
  2247. });
  2248. });
  2249. };
  2250. }
  2251.  
  2252. // Dummy devicechange event methods.
  2253. // TODO(KaptenJansson) remove once implemented in Chrome stable.
  2254. if (typeof navigator.mediaDevices.addEventListener === 'undefined') {
  2255. navigator.mediaDevices.addEventListener = function() {
  2256. logging('Dummy mediaDevices.addEventListener called.');
  2257. };
  2258. }
  2259. if (typeof navigator.mediaDevices.removeEventListener === 'undefined') {
  2260. navigator.mediaDevices.removeEventListener = function() {
  2261. logging('Dummy mediaDevices.removeEventListener called.');
  2262. };
  2263. }
  2264. };
  2265.  
  2266.  
  2267. /***/ }),
  2268. /* 14 */
  2269. /***/ (function(module, exports, __webpack_require__) {
  2270.  
  2271. "use strict";
  2272. /*
  2273. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  2274. *
  2275. * Use of this source code is governed by a BSD-style license
  2276. * that can be found in the LICENSE file in the root of the source
  2277. * tree.
  2278. */
  2279. /* eslint-env node */
  2280.  
  2281.  
  2282. var utils = __webpack_require__(0);
  2283. var shimRTCPeerConnection = __webpack_require__(15);
  2284.  
  2285. module.exports = {
  2286. shimGetUserMedia: __webpack_require__(17),
  2287. shimPeerConnection: function(window) {
  2288. var browserDetails = utils.detectBrowser(window);
  2289.  
  2290. if (window.RTCIceGatherer) {
  2291. // ORTC defines an RTCIceCandidate object but no constructor.
  2292. // Not implemented in Edge.
  2293. if (!window.RTCIceCandidate) {
  2294. window.RTCIceCandidate = function(args) {
  2295. return args;
  2296. };
  2297. }
  2298. // ORTC does not have a session description object but
  2299. // other browsers (i.e. Chrome) that will support both PC and ORTC
  2300. // in the future might have this defined already.
  2301. if (!window.RTCSessionDescription) {
  2302. window.RTCSessionDescription = function(args) {
  2303. return args;
  2304. };
  2305. }
  2306. // this adds an additional event listener to MediaStrackTrack that signals
  2307. // when a tracks enabled property was changed. Workaround for a bug in
  2308. // addStream, see below. No longer required in 15025+
  2309. if (browserDetails.version < 15025) {
  2310. var origMSTEnabled = Object.getOwnPropertyDescriptor(
  2311. window.MediaStreamTrack.prototype, 'enabled');
  2312. Object.defineProperty(window.MediaStreamTrack.prototype, 'enabled', {
  2313. set: function(value) {
  2314. origMSTEnabled.set.call(this, value);
  2315. var ev = new Event('enabled');
  2316. ev.enabled = value;
  2317. this.dispatchEvent(ev);
  2318. }
  2319. });
  2320. }
  2321. }
  2322.  
  2323. // ORTC defines the DTMF sender a bit different.
  2324. // https://github.com/w3c/ortc/issues/714
  2325. if (window.RTCRtpSender && !('dtmf' in window.RTCRtpSender.prototype)) {
  2326. Object.defineProperty(window.RTCRtpSender.prototype, 'dtmf', {
  2327. get: function() {
  2328. if (this._dtmf === undefined) {
  2329. if (this.track.kind === 'audio') {
  2330. this._dtmf = new window.RTCDtmfSender(this);
  2331. } else if (this.track.kind === 'video') {
  2332. this._dtmf = null;
  2333. }
  2334. }
  2335. return this._dtmf;
  2336. }
  2337. });
  2338. }
  2339.  
  2340. window.RTCPeerConnection =
  2341. shimRTCPeerConnection(window, browserDetails.version);
  2342. },
  2343. shimReplaceTrack: function(window) {
  2344. // ORTC has replaceTrack -- https://github.com/w3c/ortc/issues/614
  2345. if (window.RTCRtpSender &&
  2346. !('replaceTrack' in window.RTCRtpSender.prototype)) {
  2347. window.RTCRtpSender.prototype.replaceTrack =
  2348. window.RTCRtpSender.prototype.setTrack;
  2349. }
  2350. }
  2351. };
  2352.  
  2353.  
  2354. /***/ }),
  2355. /* 15 */
  2356. /***/ (function(module, exports, __webpack_require__) {
  2357.  
  2358. "use strict";
  2359. /*
  2360. * Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
  2361. *
  2362. * Use of this source code is governed by a BSD-style license
  2363. * that can be found in the LICENSE file in the root of the source
  2364. * tree.
  2365. */
  2366. /* eslint-env node */
  2367.  
  2368.  
  2369. var SDPUtils = __webpack_require__(16);
  2370.  
  2371. // sort tracks such that they follow an a-v-a-v...
  2372. // pattern.
  2373. function sortTracks(tracks) {
  2374. var audioTracks = tracks.filter(function(track) {
  2375. return track.kind === 'audio';
  2376. });
  2377. var videoTracks = tracks.filter(function(track) {
  2378. return track.kind === 'video';
  2379. });
  2380. tracks = [];
  2381. while (audioTracks.length || videoTracks.length) {
  2382. if (audioTracks.length) {
  2383. tracks.push(audioTracks.shift());
  2384. }
  2385. if (videoTracks.length) {
  2386. tracks.push(videoTracks.shift());
  2387. }
  2388. }
  2389. return tracks;
  2390. }
  2391.  
  2392. // Edge does not like
  2393. // 1) stun:
  2394. // 2) turn: that does not have all of turn:host:port?transport=udp
  2395. // 3) turn: with ipv6 addresses
  2396. // 4) turn: occurring muliple times
  2397. function filterIceServers(iceServers, edgeVersion) {
  2398. var hasTurn = false;
  2399. iceServers = JSON.parse(JSON.stringify(iceServers));
  2400. return iceServers.filter(function(server) {
  2401. if (server && (server.urls || server.url)) {
  2402. var urls = server.urls || server.url;
  2403. if (server.url && !server.urls) {
  2404. console.warn('RTCIceServer.url is deprecated! Use urls instead.');
  2405. }
  2406. var isString = typeof urls === 'string';
  2407. if (isString) {
  2408. urls = [urls];
  2409. }
  2410. urls = urls.filter(function(url) {
  2411. var validTurn = url.indexOf('turn:') === 0 &&
  2412. url.indexOf('transport=udp') !== -1 &&
  2413. url.indexOf('turn:[') === -1 &&
  2414. !hasTurn;
  2415.  
  2416. if (validTurn) {
  2417. hasTurn = true;
  2418. return true;
  2419. }
  2420. return url.indexOf('stun:') === 0 && edgeVersion >= 14393;
  2421. });
  2422.  
  2423. delete server.url;
  2424. server.urls = isString ? urls[0] : urls;
  2425. return !!urls.length;
  2426. }
  2427. return false;
  2428. });
  2429. }
  2430.  
  2431. // Determines the intersection of local and remote capabilities.
  2432. function getCommonCapabilities(localCapabilities, remoteCapabilities) {
  2433. var commonCapabilities = {
  2434. codecs: [],
  2435. headerExtensions: [],
  2436. fecMechanisms: []
  2437. };
  2438.  
  2439. var findCodecByPayloadType = function(pt, codecs) {
  2440. pt = parseInt(pt, 10);
  2441. for (var i = 0; i < codecs.length; i++) {
  2442. if (codecs[i].payloadType === pt ||
  2443. codecs[i].preferredPayloadType === pt) {
  2444. return codecs[i];
  2445. }
  2446. }
  2447. };
  2448.  
  2449. var rtxCapabilityMatches = function(lRtx, rRtx, lCodecs, rCodecs) {
  2450. var lCodec = findCodecByPayloadType(lRtx.parameters.apt, lCodecs);
  2451. var rCodec = findCodecByPayloadType(rRtx.parameters.apt, rCodecs);
  2452. return lCodec && rCodec &&
  2453. lCodec.name.toLowerCase() === rCodec.name.toLowerCase();
  2454. };
  2455.  
  2456. localCapabilities.codecs.forEach(function(lCodec) {
  2457. for (var i = 0; i < remoteCapabilities.codecs.length; i++) {
  2458. var rCodec = remoteCapabilities.codecs[i];
  2459. if (lCodec.name.toLowerCase() === rCodec.name.toLowerCase() &&
  2460. lCodec.clockRate === rCodec.clockRate) {
  2461. if (lCodec.name.toLowerCase() === 'rtx' &&
  2462. lCodec.parameters && rCodec.parameters.apt) {
  2463. // for RTX we need to find the local rtx that has a apt
  2464. // which points to the same local codec as the remote one.
  2465. if (!rtxCapabilityMatches(lCodec, rCodec,
  2466. localCapabilities.codecs, remoteCapabilities.codecs)) {
  2467. continue;
  2468. }
  2469. }
  2470. rCodec = JSON.parse(JSON.stringify(rCodec)); // deepcopy
  2471. // number of channels is the highest common number of channels
  2472. rCodec.numChannels = Math.min(lCodec.numChannels,
  2473. rCodec.numChannels);
  2474. // push rCodec so we reply with offerer payload type
  2475. commonCapabilities.codecs.push(rCodec);
  2476.  
  2477. // determine common feedback mechanisms
  2478. rCodec.rtcpFeedback = rCodec.rtcpFeedback.filter(function(fb) {
  2479. for (var j = 0; j < lCodec.rtcpFeedback.length; j++) {
  2480. if (lCodec.rtcpFeedback[j].type === fb.type &&
  2481. lCodec.rtcpFeedback[j].parameter === fb.parameter) {
  2482. return true;
  2483. }
  2484. }
  2485. return false;
  2486. });
  2487. // FIXME: also need to determine .parameters
  2488. // see https://github.com/openpeer/ortc/issues/569
  2489. break;
  2490. }
  2491. }
  2492. });
  2493.  
  2494. localCapabilities.headerExtensions.forEach(function(lHeaderExtension) {
  2495. for (var i = 0; i < remoteCapabilities.headerExtensions.length;
  2496. i++) {
  2497. var rHeaderExtension = remoteCapabilities.headerExtensions[i];
  2498. if (lHeaderExtension.uri === rHeaderExtension.uri) {
  2499. commonCapabilities.headerExtensions.push(rHeaderExtension);
  2500. break;
  2501. }
  2502. }
  2503. });
  2504.  
  2505. // FIXME: fecMechanisms
  2506. return commonCapabilities;
  2507. }
  2508.  
  2509. // is action=setLocalDescription with type allowed in signalingState
  2510. function isActionAllowedInSignalingState(action, type, signalingState) {
  2511. return {
  2512. offer: {
  2513. setLocalDescription: ['stable', 'have-local-offer'],
  2514. setRemoteDescription: ['stable', 'have-remote-offer']
  2515. },
  2516. answer: {
  2517. setLocalDescription: ['have-remote-offer', 'have-local-pranswer'],
  2518. setRemoteDescription: ['have-local-offer', 'have-remote-pranswer']
  2519. }
  2520. }[type][action].indexOf(signalingState) !== -1;
  2521. }
  2522.  
  2523. module.exports = function(window, edgeVersion) {
  2524. var RTCPeerConnection = function(config) {
  2525. var self = this;
  2526.  
  2527. var _eventTarget = document.createDocumentFragment();
  2528. ['addEventListener', 'removeEventListener', 'dispatchEvent']
  2529. .forEach(function(method) {
  2530. self[method] = _eventTarget[method].bind(_eventTarget);
  2531. });
  2532.  
  2533. this.needNegotiation = false;
  2534.  
  2535. this.onicecandidate = null;
  2536. this.onaddstream = null;
  2537. this.ontrack = null;
  2538. this.onremovestream = null;
  2539. this.onsignalingstatechange = null;
  2540. this.oniceconnectionstatechange = null;
  2541. this.onicegatheringstatechange = null;
  2542. this.onnegotiationneeded = null;
  2543. this.ondatachannel = null;
  2544. this.canTrickleIceCandidates = null;
  2545.  
  2546. this.localStreams = [];
  2547. this.remoteStreams = [];
  2548. this.getLocalStreams = function() {
  2549. return self.localStreams;
  2550. };
  2551. this.getRemoteStreams = function() {
  2552. return self.remoteStreams;
  2553. };
  2554.  
  2555. this.localDescription = new window.RTCSessionDescription({
  2556. type: '',
  2557. sdp: ''
  2558. });
  2559. this.remoteDescription = new window.RTCSessionDescription({
  2560. type: '',
  2561. sdp: ''
  2562. });
  2563. this.signalingState = 'stable';
  2564. this.iceConnectionState = 'new';
  2565. this.iceGatheringState = 'new';
  2566.  
  2567. this.iceOptions = {
  2568. gatherPolicy: 'all',
  2569. iceServers: []
  2570. };
  2571. if (config && config.iceTransportPolicy) {
  2572. switch (config.iceTransportPolicy) {
  2573. case 'all':
  2574. case 'relay':
  2575. this.iceOptions.gatherPolicy = config.iceTransportPolicy;
  2576. break;
  2577. default:
  2578. // don't set iceTransportPolicy.
  2579. break;
  2580. }
  2581. }
  2582. this.usingBundle = config && config.bundlePolicy === 'max-bundle';
  2583.  
  2584. if (config && config.iceServers) {
  2585. this.iceOptions.iceServers = filterIceServers(config.iceServers,
  2586. edgeVersion);
  2587. }
  2588. this._config = config || {};
  2589.  
  2590. // per-track iceGathers, iceTransports, dtlsTransports, rtpSenders, ...
  2591. // everything that is needed to describe a SDP m-line.
  2592. this.transceivers = [];
  2593.  
  2594. // since the iceGatherer is currently created in createOffer but we
  2595. // must not emit candidates until after setLocalDescription we buffer
  2596. // them in this array.
  2597. this._localIceCandidatesBuffer = [];
  2598.  
  2599. this._sdpSessionId = SDPUtils.generateSessionId();
  2600. };
  2601.  
  2602. RTCPeerConnection.prototype._emitGatheringStateChange = function() {
  2603. var event = new Event('icegatheringstatechange');
  2604. this.dispatchEvent(event);
  2605. if (this.onicegatheringstatechange !== null) {
  2606. this.onicegatheringstatechange(event);
  2607. }
  2608. };
  2609.  
  2610. RTCPeerConnection.prototype._emitBufferedCandidates = function() {
  2611. var self = this;
  2612. var sections = SDPUtils.splitSections(self.localDescription.sdp);
  2613. // FIXME: need to apply ice candidates in a way which is async but
  2614. // in-order
  2615. this._localIceCandidatesBuffer.forEach(function(event) {
  2616. var end = !event.candidate || Object.keys(event.candidate).length === 0;
  2617. if (end) {
  2618. for (var j = 1; j < sections.length; j++) {
  2619. if (sections[j].indexOf('\r\na=end-of-candidates\r\n') === -1) {
  2620. sections[j] += 'a=end-of-candidates\r\n';
  2621. }
  2622. }
  2623. } else {
  2624. sections[event.candidate.sdpMLineIndex + 1] +=
  2625. 'a=' + event.candidate.candidate + '\r\n';
  2626. }
  2627. self.localDescription.sdp = sections.join('');
  2628. self.dispatchEvent(event);
  2629. if (self.onicecandidate !== null) {
  2630. self.onicecandidate(event);
  2631. }
  2632. if (!event.candidate && self.iceGatheringState !== 'complete') {
  2633. var complete = self.transceivers.every(function(transceiver) {
  2634. return transceiver.iceGatherer &&
  2635. transceiver.iceGatherer.state === 'completed';
  2636. });
  2637. if (complete && self.iceGatheringStateChange !== 'complete') {
  2638. self.iceGatheringState = 'complete';
  2639. self._emitGatheringStateChange();
  2640. }
  2641. }
  2642. });
  2643. this._localIceCandidatesBuffer = [];
  2644. };
  2645.  
  2646. RTCPeerConnection.prototype.getConfiguration = function() {
  2647. return this._config;
  2648. };
  2649.  
  2650. // internal helper to create a transceiver object.
  2651. // (whih is not yet the same as the WebRTC 1.0 transceiver)
  2652. RTCPeerConnection.prototype._createTransceiver = function(kind) {
  2653. var hasBundleTransport = this.transceivers.length > 0;
  2654. var transceiver = {
  2655. track: null,
  2656. iceGatherer: null,
  2657. iceTransport: null,
  2658. dtlsTransport: null,
  2659. localCapabilities: null,
  2660. remoteCapabilities: null,
  2661. rtpSender: null,
  2662. rtpReceiver: null,
  2663. kind: kind,
  2664. mid: null,
  2665. sendEncodingParameters: null,
  2666. recvEncodingParameters: null,
  2667. stream: null,
  2668. wantReceive: true
  2669. };
  2670. if (this.usingBundle && hasBundleTransport) {
  2671. transceiver.iceTransport = this.transceivers[0].iceTransport;
  2672. transceiver.dtlsTransport = this.transceivers[0].dtlsTransport;
  2673. } else {
  2674. var transports = this._createIceAndDtlsTransports();
  2675. transceiver.iceTransport = transports.iceTransport;
  2676. transceiver.dtlsTransport = transports.dtlsTransport;
  2677. }
  2678. this.transceivers.push(transceiver);
  2679. return transceiver;
  2680. };
  2681.  
  2682. RTCPeerConnection.prototype.addTrack = function(track, stream) {
  2683. var transceiver;
  2684. for (var i = 0; i < this.transceivers.length; i++) {
  2685. if (!this.transceivers[i].track &&
  2686. this.transceivers[i].kind === track.kind) {
  2687. transceiver = this.transceivers[i];
  2688. }
  2689. }
  2690. if (!transceiver) {
  2691. transceiver = this._createTransceiver(track.kind);
  2692. }
  2693.  
  2694. transceiver.track = track;
  2695. transceiver.stream = stream;
  2696. transceiver.rtpSender = new window.RTCRtpSender(track,
  2697. transceiver.dtlsTransport);
  2698.  
  2699. this._maybeFireNegotiationNeeded();
  2700. return transceiver.rtpSender;
  2701. };
  2702.  
  2703. RTCPeerConnection.prototype.addStream = function(stream) {
  2704. var self = this;
  2705. if (edgeVersion >= 15025) {
  2706. this.localStreams.push(stream);
  2707. stream.getTracks().forEach(function(track) {
  2708. self.addTrack(track, stream);
  2709. });
  2710. } else {
  2711. // Clone is necessary for local demos mostly, attaching directly
  2712. // to two different senders does not work (build 10547).
  2713. // Fixed in 15025 (or earlier)
  2714. var clonedStream = stream.clone();
  2715. stream.getTracks().forEach(function(track, idx) {
  2716. var clonedTrack = clonedStream.getTracks()[idx];
  2717. track.addEventListener('enabled', function(event) {
  2718. clonedTrack.enabled = event.enabled;
  2719. });
  2720. });
  2721. clonedStream.getTracks().forEach(function(track) {
  2722. self.addTrack(track, clonedStream);
  2723. });
  2724. this.localStreams.push(clonedStream);
  2725. }
  2726. this._maybeFireNegotiationNeeded();
  2727. };
  2728.  
  2729. RTCPeerConnection.prototype.removeStream = function(stream) {
  2730. var idx = this.localStreams.indexOf(stream);
  2731. if (idx > -1) {
  2732. this.localStreams.splice(idx, 1);
  2733. this._maybeFireNegotiationNeeded();
  2734. }
  2735. };
  2736.  
  2737. RTCPeerConnection.prototype.getSenders = function() {
  2738. return this.transceivers.filter(function(transceiver) {
  2739. return !!transceiver.rtpSender;
  2740. })
  2741. .map(function(transceiver) {
  2742. return transceiver.rtpSender;
  2743. });
  2744. };
  2745.  
  2746. RTCPeerConnection.prototype.getReceivers = function() {
  2747. return this.transceivers.filter(function(transceiver) {
  2748. return !!transceiver.rtpReceiver;
  2749. })
  2750. .map(function(transceiver) {
  2751. return transceiver.rtpReceiver;
  2752. });
  2753. };
  2754.  
  2755. // Create ICE gatherer and hook it up.
  2756. RTCPeerConnection.prototype._createIceGatherer = function(mid,
  2757. sdpMLineIndex) {
  2758. var self = this;
  2759. var iceGatherer = new window.RTCIceGatherer(self.iceOptions);
  2760. iceGatherer.onlocalcandidate = function(evt) {
  2761. var event = new Event('icecandidate');
  2762. event.candidate = {sdpMid: mid, sdpMLineIndex: sdpMLineIndex};
  2763.  
  2764. var cand = evt.candidate;
  2765. var end = !cand || Object.keys(cand).length === 0;
  2766. // Edge emits an empty object for RTCIceCandidateComplete‥
  2767. if (end) {
  2768. // polyfill since RTCIceGatherer.state is not implemented in
  2769. // Edge 10547 yet.
  2770. if (iceGatherer.state === undefined) {
  2771. iceGatherer.state = 'completed';
  2772. }
  2773. } else {
  2774. // RTCIceCandidate doesn't have a component, needs to be added
  2775. cand.component = 1;
  2776. event.candidate.candidate = SDPUtils.writeCandidate(cand);
  2777. }
  2778.  
  2779. // update local description.
  2780. var sections = SDPUtils.splitSections(self.localDescription.sdp);
  2781. if (!end) {
  2782. sections[event.candidate.sdpMLineIndex + 1] +=
  2783. 'a=' + event.candidate.candidate + '\r\n';
  2784. } else {
  2785. sections[event.candidate.sdpMLineIndex + 1] +=
  2786. 'a=end-of-candidates\r\n';
  2787. }
  2788. self.localDescription.sdp = sections.join('');
  2789. var transceivers = self._pendingOffer ? self._pendingOffer :
  2790. self.transceivers;
  2791. var complete = transceivers.every(function(transceiver) {
  2792. return transceiver.iceGatherer &&
  2793. transceiver.iceGatherer.state === 'completed';
  2794. });
  2795.  
  2796. // Emit candidate if localDescription is set.
  2797. // Also emits null candidate when all gatherers are complete.
  2798. switch (self.iceGatheringState) {
  2799. case 'new':
  2800. if (!end) {
  2801. self._localIceCandidatesBuffer.push(event);
  2802. }
  2803. if (end && complete) {
  2804. self._localIceCandidatesBuffer.push(
  2805. new Event('icecandidate'));
  2806. }
  2807. break;
  2808. case 'gathering':
  2809. self._emitBufferedCandidates();
  2810. if (!end) {
  2811. self.dispatchEvent(event);
  2812. if (self.onicecandidate !== null) {
  2813. self.onicecandidate(event);
  2814. }
  2815. }
  2816. if (complete) {
  2817. self.dispatchEvent(new Event('icecandidate'));
  2818. if (self.onicecandidate !== null) {
  2819. self.onicecandidate(new Event('icecandidate'));
  2820. }
  2821. self.iceGatheringState = 'complete';
  2822. self._emitGatheringStateChange();
  2823. }
  2824. break;
  2825. case 'complete':
  2826. // should not happen... currently!
  2827. break;
  2828. default: // no-op.
  2829. break;
  2830. }
  2831. };
  2832. return iceGatherer;
  2833. };
  2834.  
  2835. // Create ICE transport and DTLS transport.
  2836. RTCPeerConnection.prototype._createIceAndDtlsTransports = function() {
  2837. var self = this;
  2838. var iceTransport = new window.RTCIceTransport(null);
  2839. iceTransport.onicestatechange = function() {
  2840. self._updateConnectionState();
  2841. };
  2842.  
  2843. var dtlsTransport = new window.RTCDtlsTransport(iceTransport);
  2844. dtlsTransport.ondtlsstatechange = function() {
  2845. self._updateConnectionState();
  2846. };
  2847. dtlsTransport.onerror = function() {
  2848. // onerror does not set state to failed by itself.
  2849. Object.defineProperty(dtlsTransport, 'state',
  2850. {value: 'failed', writable: true});
  2851. self._updateConnectionState();
  2852. };
  2853.  
  2854. return {
  2855. iceTransport: iceTransport,
  2856. dtlsTransport: dtlsTransport
  2857. };
  2858. };
  2859.  
  2860. // Destroy ICE gatherer, ICE transport and DTLS transport.
  2861. // Without triggering the callbacks.
  2862. RTCPeerConnection.prototype._disposeIceAndDtlsTransports = function(
  2863. sdpMLineIndex) {
  2864. var iceGatherer = this.transceivers[sdpMLineIndex].iceGatherer;
  2865. if (iceGatherer) {
  2866. delete iceGatherer.onlocalcandidate;
  2867. delete this.transceivers[sdpMLineIndex].iceGatherer;
  2868. }
  2869. var iceTransport = this.transceivers[sdpMLineIndex].iceTransport;
  2870. if (iceTransport) {
  2871. delete iceTransport.onicestatechange;
  2872. delete this.transceivers[sdpMLineIndex].iceTransport;
  2873. }
  2874. var dtlsTransport = this.transceivers[sdpMLineIndex].dtlsTransport;
  2875. if (dtlsTransport) {
  2876. delete dtlsTransport.ondtlsstatechange;
  2877. delete dtlsTransport.onerror;
  2878. delete this.transceivers[sdpMLineIndex].dtlsTransport;
  2879. }
  2880. };
  2881.  
  2882. // Start the RTP Sender and Receiver for a transceiver.
  2883. RTCPeerConnection.prototype._transceive = function(transceiver,
  2884. send, recv) {
  2885. var params = getCommonCapabilities(transceiver.localCapabilities,
  2886. transceiver.remoteCapabilities);
  2887. if (send && transceiver.rtpSender) {
  2888. params.encodings = transceiver.sendEncodingParameters;
  2889. params.rtcp = {
  2890. cname: SDPUtils.localCName,
  2891. compound: transceiver.rtcpParameters.compound
  2892. };
  2893. if (transceiver.recvEncodingParameters.length) {
  2894. params.rtcp.ssrc = transceiver.recvEncodingParameters[0].ssrc;
  2895. }
  2896. transceiver.rtpSender.send(params);
  2897. }
  2898. if (recv && transceiver.rtpReceiver) {
  2899. // remove RTX field in Edge 14942
  2900. if (transceiver.kind === 'video'
  2901. && transceiver.recvEncodingParameters
  2902. && edgeVersion < 15019) {
  2903. transceiver.recvEncodingParameters.forEach(function(p) {
  2904. delete p.rtx;
  2905. });
  2906. }
  2907. params.encodings = transceiver.recvEncodingParameters;
  2908. params.rtcp = {
  2909. cname: transceiver.rtcpParameters.cname,
  2910. compound: transceiver.rtcpParameters.compound
  2911. };
  2912. if (transceiver.sendEncodingParameters.length) {
  2913. params.rtcp.ssrc = transceiver.sendEncodingParameters[0].ssrc;
  2914. }
  2915. transceiver.rtpReceiver.receive(params);
  2916. }
  2917. };
  2918.  
  2919. RTCPeerConnection.prototype.setLocalDescription = function(description) {
  2920. var self = this;
  2921.  
  2922. if (!isActionAllowedInSignalingState('setLocalDescription',
  2923. description.type, this.signalingState)) {
  2924. var e = new Error('Can not set local ' + description.type +
  2925. ' in state ' + this.signalingState);
  2926. e.name = 'InvalidStateError';
  2927. if (arguments.length > 2 && typeof arguments[2] === 'function') {
  2928. window.setTimeout(arguments[2], 0, e);
  2929. }
  2930. return Promise.reject(e);
  2931. }
  2932.  
  2933. var sections;
  2934. var sessionpart;
  2935. if (description.type === 'offer') {
  2936. // FIXME: What was the purpose of this empty if statement?
  2937. // if (!this._pendingOffer) {
  2938. // } else {
  2939. if (this._pendingOffer) {
  2940. // VERY limited support for SDP munging. Limited to:
  2941. // * changing the order of codecs
  2942. sections = SDPUtils.splitSections(description.sdp);
  2943. sessionpart = sections.shift();
  2944. sections.forEach(function(mediaSection, sdpMLineIndex) {
  2945. var caps = SDPUtils.parseRtpParameters(mediaSection);
  2946. self._pendingOffer[sdpMLineIndex].localCapabilities = caps;
  2947. });
  2948. this.transceivers = this._pendingOffer;
  2949. delete this._pendingOffer;
  2950. }
  2951. } else if (description.type === 'answer') {
  2952. sections = SDPUtils.splitSections(self.remoteDescription.sdp);
  2953. sessionpart = sections.shift();
  2954. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  2955. 'a=ice-lite').length > 0;
  2956. sections.forEach(function(mediaSection, sdpMLineIndex) {
  2957. var transceiver = self.transceivers[sdpMLineIndex];
  2958. var iceGatherer = transceiver.iceGatherer;
  2959. var iceTransport = transceiver.iceTransport;
  2960. var dtlsTransport = transceiver.dtlsTransport;
  2961. var localCapabilities = transceiver.localCapabilities;
  2962. var remoteCapabilities = transceiver.remoteCapabilities;
  2963.  
  2964. var rejected = SDPUtils.isRejected(mediaSection);
  2965.  
  2966. if (!rejected && !transceiver.isDatachannel) {
  2967. var remoteIceParameters = SDPUtils.getIceParameters(
  2968. mediaSection, sessionpart);
  2969. var remoteDtlsParameters = SDPUtils.getDtlsParameters(
  2970. mediaSection, sessionpart);
  2971. if (isIceLite) {
  2972. remoteDtlsParameters.role = 'server';
  2973. }
  2974.  
  2975. if (!self.usingBundle || sdpMLineIndex === 0) {
  2976. iceTransport.start(iceGatherer, remoteIceParameters,
  2977. isIceLite ? 'controlling' : 'controlled');
  2978. dtlsTransport.start(remoteDtlsParameters);
  2979. }
  2980.  
  2981. // Calculate intersection of capabilities.
  2982. var params = getCommonCapabilities(localCapabilities,
  2983. remoteCapabilities);
  2984.  
  2985. // Start the RTCRtpSender. The RTCRtpReceiver for this
  2986. // transceiver has already been started in setRemoteDescription.
  2987. self._transceive(transceiver,
  2988. params.codecs.length > 0,
  2989. false);
  2990. }
  2991. });
  2992. }
  2993.  
  2994. this.localDescription = {
  2995. type: description.type,
  2996. sdp: description.sdp
  2997. };
  2998. switch (description.type) {
  2999. case 'offer':
  3000. this._updateSignalingState('have-local-offer');
  3001. break;
  3002. case 'answer':
  3003. this._updateSignalingState('stable');
  3004. break;
  3005. default:
  3006. throw new TypeError('unsupported type "' + description.type +
  3007. '"');
  3008. }
  3009.  
  3010. // If a success callback was provided, emit ICE candidates after it
  3011. // has been executed. Otherwise, emit callback after the Promise is
  3012. // resolved.
  3013. var hasCallback = arguments.length > 1 &&
  3014. typeof arguments[1] === 'function';
  3015. if (hasCallback) {
  3016. var cb = arguments[1];
  3017. window.setTimeout(function() {
  3018. cb();
  3019. if (self.iceGatheringState === 'new') {
  3020. self.iceGatheringState = 'gathering';
  3021. self._emitGatheringStateChange();
  3022. }
  3023. self._emitBufferedCandidates();
  3024. }, 0);
  3025. }
  3026. var p = Promise.resolve();
  3027. p.then(function() {
  3028. if (!hasCallback) {
  3029. if (self.iceGatheringState === 'new') {
  3030. self.iceGatheringState = 'gathering';
  3031. self._emitGatheringStateChange();
  3032. }
  3033. // Usually candidates will be emitted earlier.
  3034. window.setTimeout(self._emitBufferedCandidates.bind(self), 500);
  3035. }
  3036. });
  3037. return p;
  3038. };
  3039.  
  3040. RTCPeerConnection.prototype.setRemoteDescription = function(description) {
  3041. var self = this;
  3042.  
  3043. if (!isActionAllowedInSignalingState('setRemoteDescription',
  3044. description.type, this.signalingState)) {
  3045. var e = new Error('Can not set remote ' + description.type +
  3046. ' in state ' + this.signalingState);
  3047. e.name = 'InvalidStateError';
  3048. if (arguments.length > 2 && typeof arguments[2] === 'function') {
  3049. window.setTimeout(arguments[2], 0, e);
  3050. }
  3051. return Promise.reject(e);
  3052. }
  3053.  
  3054. var streams = {};
  3055. var receiverList = [];
  3056. var sections = SDPUtils.splitSections(description.sdp);
  3057. var sessionpart = sections.shift();
  3058. var isIceLite = SDPUtils.matchPrefix(sessionpart,
  3059. 'a=ice-lite').length > 0;
  3060. var usingBundle = SDPUtils.matchPrefix(sessionpart,
  3061. 'a=group:BUNDLE ').length > 0;
  3062. this.usingBundle = usingBundle;
  3063. var iceOptions = SDPUtils.matchPrefix(sessionpart,
  3064. 'a=ice-options:')[0];
  3065. if (iceOptions) {
  3066. this.canTrickleIceCandidates = iceOptions.substr(14).split(' ')
  3067. .indexOf('trickle') >= 0;
  3068. } else {
  3069. this.canTrickleIceCandidates = false;
  3070. }
  3071.  
  3072. sections.forEach(function(mediaSection, sdpMLineIndex) {
  3073. var lines = SDPUtils.splitLines(mediaSection);
  3074. var kind = SDPUtils.getKind(mediaSection);
  3075. var rejected = SDPUtils.isRejected(mediaSection);
  3076. var protocol = lines[0].substr(2).split(' ')[2];
  3077.  
  3078. var direction = SDPUtils.getDirection(mediaSection, sessionpart);
  3079. var remoteMsid = SDPUtils.parseMsid(mediaSection);
  3080.  
  3081. var mid = SDPUtils.getMid(mediaSection) || SDPUtils.generateIdentifier();
  3082.  
  3083. // Reject datachannels which are not implemented yet.
  3084. if (kind === 'application' && protocol === 'DTLS/SCTP') {
  3085. self.transceivers[sdpMLineIndex] = {
  3086. mid: mid,
  3087. isDatachannel: true
  3088. };
  3089. return;
  3090. }
  3091.  
  3092. var transceiver;
  3093. var iceGatherer;
  3094. var iceTransport;
  3095. var dtlsTransport;
  3096. var rtpReceiver;
  3097. var sendEncodingParameters;
  3098. var recvEncodingParameters;
  3099. var localCapabilities;
  3100.  
  3101. var track;
  3102. // FIXME: ensure the mediaSection has rtcp-mux set.
  3103. var remoteCapabilities = SDPUtils.parseRtpParameters(mediaSection);
  3104. var remoteIceParameters;
  3105. var remoteDtlsParameters;
  3106. if (!rejected) {
  3107. remoteIceParameters = SDPUtils.getIceParameters(mediaSection,
  3108. sessionpart);
  3109. remoteDtlsParameters = SDPUtils.getDtlsParameters(mediaSection,
  3110. sessionpart);
  3111. remoteDtlsParameters.role = 'client';
  3112. }
  3113. recvEncodingParameters =
  3114. SDPUtils.parseRtpEncodingParameters(mediaSection);
  3115.  
  3116. var rtcpParameters = SDPUtils.parseRtcpParameters(mediaSection);
  3117.  
  3118. var isComplete = SDPUtils.matchPrefix(mediaSection,
  3119. 'a=end-of-candidates', sessionpart).length > 0;
  3120. var cands = SDPUtils.matchPrefix(mediaSection, 'a=candidate:')
  3121. .map(function(cand) {
  3122. return SDPUtils.parseCandidate(cand);
  3123. })
  3124. .filter(function(cand) {
  3125. return cand.component === '1' || cand.component === 1;
  3126. });
  3127.  
  3128. // Check if we can use BUNDLE and dispose transports.
  3129. if ((description.type === 'offer' || description.type === 'answer') &&
  3130. !rejected && usingBundle && sdpMLineIndex > 0 &&
  3131. self.transceivers[sdpMLineIndex]) {
  3132. self._disposeIceAndDtlsTransports(sdpMLineIndex);
  3133. self.transceivers[sdpMLineIndex].iceGatherer =
  3134. self.transceivers[0].iceGatherer;
  3135. self.transceivers[sdpMLineIndex].iceTransport =
  3136. self.transceivers[0].iceTransport;
  3137. self.transceivers[sdpMLineIndex].dtlsTransport =
  3138. self.transceivers[0].dtlsTransport;
  3139. if (self.transceivers[sdpMLineIndex].rtpSender) {
  3140. self.transceivers[sdpMLineIndex].rtpSender.setTransport(
  3141. self.transceivers[0].dtlsTransport);
  3142. }
  3143. if (self.transceivers[sdpMLineIndex].rtpReceiver) {
  3144. self.transceivers[sdpMLineIndex].rtpReceiver.setTransport(
  3145. self.transceivers[0].dtlsTransport);
  3146. }
  3147. }
  3148. if (description.type === 'offer' && !rejected) {
  3149. transceiver = self.transceivers[sdpMLineIndex] ||
  3150. self._createTransceiver(kind);
  3151. transceiver.mid = mid;
  3152.  
  3153. if (!transceiver.iceGatherer) {
  3154. transceiver.iceGatherer = usingBundle && sdpMLineIndex > 0 ?
  3155. self.transceivers[0].iceGatherer :
  3156. self._createIceGatherer(mid, sdpMLineIndex);
  3157. }
  3158.  
  3159. if (isComplete && cands.length &&
  3160. (!usingBundle || sdpMLineIndex === 0)) {
  3161. transceiver.iceTransport.setRemoteCandidates(cands);
  3162. }
  3163.  
  3164. localCapabilities = window.RTCRtpReceiver.getCapabilities(kind);
  3165.  
  3166. // filter RTX until additional stuff needed for RTX is implemented
  3167. // in adapter.js
  3168. if (edgeVersion < 15019) {
  3169. localCapabilities.codecs = localCapabilities.codecs.filter(
  3170. function(codec) {
  3171. return codec.name !== 'rtx';
  3172. });
  3173. }
  3174.  
  3175. sendEncodingParameters = [{
  3176. ssrc: (2 * sdpMLineIndex + 2) * 1001
  3177. }];
  3178.  
  3179. if (direction === 'sendrecv' || direction === 'sendonly') {
  3180. rtpReceiver = new window.RTCRtpReceiver(transceiver.dtlsTransport,
  3181. kind);
  3182.  
  3183. track = rtpReceiver.track;
  3184. // FIXME: does not work with Plan B.
  3185. if (remoteMsid) {
  3186. if (!streams[remoteMsid.stream]) {
  3187. streams[remoteMsid.stream] = new window.MediaStream();
  3188. Object.defineProperty(streams[remoteMsid.stream], 'id', {
  3189. get: function() {
  3190. return remoteMsid.stream;
  3191. }
  3192. });
  3193. }
  3194. Object.defineProperty(track, 'id', {
  3195. get: function() {
  3196. return remoteMsid.track;
  3197. }
  3198. });
  3199. streams[remoteMsid.stream].addTrack(track);
  3200. receiverList.push([track, rtpReceiver,
  3201. streams[remoteMsid.stream]]);
  3202. } else {
  3203. if (!streams.default) {
  3204. streams.default = new window.MediaStream();
  3205. }
  3206. streams.default.addTrack(track);
  3207. receiverList.push([track, rtpReceiver, streams.default]);
  3208. }
  3209. }
  3210.  
  3211. transceiver.localCapabilities = localCapabilities;
  3212. transceiver.remoteCapabilities = remoteCapabilities;
  3213. transceiver.rtpReceiver = rtpReceiver;
  3214. transceiver.rtcpParameters = rtcpParameters;
  3215. transceiver.sendEncodingParameters = sendEncodingParameters;
  3216. transceiver.recvEncodingParameters = recvEncodingParameters;
  3217.  
  3218. // Start the RTCRtpReceiver now. The RTPSender is started in
  3219. // setLocalDescription.
  3220. self._transceive(self.transceivers[sdpMLineIndex],
  3221. false,
  3222. direction === 'sendrecv' || direction === 'sendonly');
  3223. } else if (description.type === 'answer' && !rejected) {
  3224. transceiver = self.transceivers[sdpMLineIndex];
  3225. iceGatherer = transceiver.iceGatherer;
  3226. iceTransport = transceiver.iceTransport;
  3227. dtlsTransport = transceiver.dtlsTransport;
  3228. rtpReceiver = transceiver.rtpReceiver;
  3229. sendEncodingParameters = transceiver.sendEncodingParameters;
  3230. localCapabilities = transceiver.localCapabilities;
  3231.  
  3232. self.transceivers[sdpMLineIndex].recvEncodingParameters =
  3233. recvEncodingParameters;
  3234. self.transceivers[sdpMLineIndex].remoteCapabilities =
  3235. remoteCapabilities;
  3236. self.transceivers[sdpMLineIndex].rtcpParameters = rtcpParameters;
  3237.  
  3238. if (!usingBundle || sdpMLineIndex === 0) {
  3239. if ((isIceLite || isComplete) && cands.length) {
  3240. iceTransport.setRemoteCandidates(cands);
  3241. }
  3242. iceTransport.start(iceGatherer, remoteIceParameters,
  3243. 'controlling');
  3244. dtlsTransport.start(remoteDtlsParameters);
  3245. }
  3246.  
  3247. self._transceive(transceiver,
  3248. direction === 'sendrecv' || direction === 'recvonly',
  3249. direction === 'sendrecv' || direction === 'sendonly');
  3250.  
  3251. if (rtpReceiver &&
  3252. (direction === 'sendrecv' || direction === 'sendonly')) {
  3253. track = rtpReceiver.track;
  3254. if (remoteMsid) {
  3255. if (!streams[remoteMsid.stream]) {
  3256. streams[remoteMsid.stream] = new window.MediaStream();
  3257. }
  3258. streams[remoteMsid.stream].addTrack(track);
  3259. receiverList.push([track, rtpReceiver, streams[remoteMsid.stream]]);
  3260. } else {
  3261. if (!streams.default) {
  3262. streams.default = new window.MediaStream();
  3263. }
  3264. streams.default.addTrack(track);
  3265. receiverList.push([track, rtpReceiver, streams.default]);
  3266. }
  3267. } else {
  3268. // FIXME: actually the receiver should be created later.
  3269. delete transceiver.rtpReceiver;
  3270. }
  3271. }
  3272. });
  3273.  
  3274. this.remoteDescription = {
  3275. type: description.type,
  3276. sdp: description.sdp
  3277. };
  3278. switch (description.type) {
  3279. case 'offer':
  3280. this._updateSignalingState('have-remote-offer');
  3281. break;
  3282. case 'answer':
  3283. this._updateSignalingState('stable');
  3284. break;
  3285. default:
  3286. throw new TypeError('unsupported type "' + description.type +
  3287. '"');
  3288. }
  3289. Object.keys(streams).forEach(function(sid) {
  3290. var stream = streams[sid];
  3291. if (stream.getTracks().length) {
  3292. self.remoteStreams.push(stream);
  3293. var event = new Event('addstream');
  3294. event.stream = stream;
  3295. self.dispatchEvent(event);
  3296. if (self.onaddstream !== null) {
  3297. window.setTimeout(function() {
  3298. self.onaddstream(event);
  3299. }, 0);
  3300. }
  3301.  
  3302. receiverList.forEach(function(item) {
  3303. var track = item[0];
  3304. var receiver = item[1];
  3305. if (stream.id !== item[2].id) {
  3306. return;
  3307. }
  3308. var trackEvent = new Event('track');
  3309. trackEvent.track = track;
  3310. trackEvent.receiver = receiver;
  3311. trackEvent.streams = [stream];
  3312. self.dispatchEvent(trackEvent);
  3313. if (self.ontrack !== null) {
  3314. window.setTimeout(function() {
  3315. self.ontrack(trackEvent);
  3316. }, 0);
  3317. }
  3318. });
  3319. }
  3320. });
  3321.  
  3322. // check whether addIceCandidate({}) was called within four seconds after
  3323. // setRemoteDescription.
  3324. window.setTimeout(function() {
  3325. if (!(self && self.transceivers)) {
  3326. return;
  3327. }
  3328. self.transceivers.forEach(function(transceiver) {
  3329. if (transceiver.iceTransport &&
  3330. transceiver.iceTransport.state === 'new' &&
  3331. transceiver.iceTransport.getRemoteCandidates().length > 0) {
  3332. console.warn('Timeout for addRemoteCandidate. Consider sending ' +
  3333. 'an end-of-candidates notification');
  3334. transceiver.iceTransport.addRemoteCandidate({});
  3335. }
  3336. });
  3337. }, 4000);
  3338.  
  3339. if (arguments.length > 1 && typeof arguments[1] === 'function') {
  3340. window.setTimeout(arguments[1], 0);
  3341. }
  3342. return Promise.resolve();
  3343. };
  3344.  
  3345. RTCPeerConnection.prototype.close = function() {
  3346. this.transceivers.forEach(function(transceiver) {
  3347. /* not yet
  3348. if (transceiver.iceGatherer) {
  3349. transceiver.iceGatherer.close();
  3350. }
  3351. */
  3352. if (transceiver.iceTransport) {
  3353. transceiver.iceTransport.stop();
  3354. }
  3355. if (transceiver.dtlsTransport) {
  3356. transceiver.dtlsTransport.stop();
  3357. }
  3358. if (transceiver.rtpSender) {
  3359. transceiver.rtpSender.stop();
  3360. }
  3361. if (transceiver.rtpReceiver) {
  3362. transceiver.rtpReceiver.stop();
  3363. }
  3364. });
  3365. // FIXME: clean up tracks, local streams, remote streams, etc
  3366. this._updateSignalingState('closed');
  3367. };
  3368.  
  3369. // Update the signaling state.
  3370. RTCPeerConnection.prototype._updateSignalingState = function(newState) {
  3371. this.signalingState = newState;
  3372. var event = new Event('signalingstatechange');
  3373. this.dispatchEvent(event);
  3374. if (this.onsignalingstatechange !== null) {
  3375. this.onsignalingstatechange(event);
  3376. }
  3377. };
  3378.  
  3379. // Determine whether to fire the negotiationneeded event.
  3380. RTCPeerConnection.prototype._maybeFireNegotiationNeeded = function() {
  3381. var self = this;
  3382. if (this.signalingState !== 'stable' || this.needNegotiation === true) {
  3383. return;
  3384. }
  3385. this.needNegotiation = true;
  3386. window.setTimeout(function() {
  3387. if (self.needNegotiation === false) {
  3388. return;
  3389. }
  3390. self.needNegotiation = false;
  3391. var event = new Event('negotiationneeded');
  3392. self.dispatchEvent(event);
  3393. if (self.onnegotiationneeded !== null) {
  3394. self.onnegotiationneeded(event);
  3395. }
  3396. }, 0);
  3397. };
  3398.  
  3399. // Update the connection state.
  3400. RTCPeerConnection.prototype._updateConnectionState = function() {
  3401. var self = this;
  3402. var newState;
  3403. var states = {
  3404. 'new': 0,
  3405. closed: 0,
  3406. connecting: 0,
  3407. checking: 0,
  3408. connected: 0,
  3409. completed: 0,
  3410. disconnected: 0,
  3411. failed: 0
  3412. };
  3413. this.transceivers.forEach(function(transceiver) {
  3414. states[transceiver.iceTransport.state]++;
  3415. states[transceiver.dtlsTransport.state]++;
  3416. });
  3417. // ICETransport.completed and connected are the same for this purpose.
  3418. states.connected += states.completed;
  3419.  
  3420. newState = 'new';
  3421. if (states.failed > 0) {
  3422. newState = 'failed';
  3423. } else if (states.connecting > 0 || states.checking > 0) {
  3424. newState = 'connecting';
  3425. } else if (states.disconnected > 0) {
  3426. newState = 'disconnected';
  3427. } else if (states.new > 0) {
  3428. newState = 'new';
  3429. } else if (states.connected > 0 || states.completed > 0) {
  3430. newState = 'connected';
  3431. }
  3432.  
  3433. if (newState !== self.iceConnectionState) {
  3434. self.iceConnectionState = newState;
  3435. var event = new Event('iceconnectionstatechange');
  3436. this.dispatchEvent(event);
  3437. if (this.oniceconnectionstatechange !== null) {
  3438. this.oniceconnectionstatechange(event);
  3439. }
  3440. }
  3441. };
  3442.  
  3443. RTCPeerConnection.prototype.createOffer = function() {
  3444. var self = this;
  3445. if (this._pendingOffer) {
  3446. throw new Error('createOffer called while there is a pending offer.');
  3447. }
  3448. var offerOptions;
  3449. if (arguments.length === 1 && typeof arguments[0] !== 'function') {
  3450. offerOptions = arguments[0];
  3451. } else if (arguments.length === 3) {
  3452. offerOptions = arguments[2];
  3453. }
  3454.  
  3455. var numAudioTracks = this.transceivers.filter(function(t) {
  3456. return t.kind === 'audio';
  3457. }).length;
  3458. var numVideoTracks = this.transceivers.filter(function(t) {
  3459. return t.kind === 'video';
  3460. }).length;
  3461.  
  3462. // Determine number of audio and video tracks we need to send/recv.
  3463. if (offerOptions) {
  3464. // Reject Chrome legacy constraints.
  3465. if (offerOptions.mandatory || offerOptions.optional) {
  3466. throw new TypeError(
  3467. 'Legacy mandatory/optional constraints not supported.');
  3468. }
  3469. if (offerOptions.offerToReceiveAudio !== undefined) {
  3470. if (offerOptions.offerToReceiveAudio === true) {
  3471. numAudioTracks = 1;
  3472. } else if (offerOptions.offerToReceiveAudio === false) {
  3473. numAudioTracks = 0;
  3474. } else {
  3475. numAudioTracks = offerOptions.offerToReceiveAudio;
  3476. }
  3477. }
  3478. if (offerOptions.offerToReceiveVideo !== undefined) {
  3479. if (offerOptions.offerToReceiveVideo === true) {
  3480. numVideoTracks = 1;
  3481. } else if (offerOptions.offerToReceiveVideo === false) {
  3482. numVideoTracks = 0;
  3483. } else {
  3484. numVideoTracks = offerOptions.offerToReceiveVideo;
  3485. }
  3486. }
  3487. }
  3488.  
  3489. this.transceivers.forEach(function(transceiver) {
  3490. if (transceiver.kind === 'audio') {
  3491. numAudioTracks--;
  3492. if (numAudioTracks < 0) {
  3493. transceiver.wantReceive = false;
  3494. }
  3495. } else if (transceiver.kind === 'video') {
  3496. numVideoTracks--;
  3497. if (numVideoTracks < 0) {
  3498. transceiver.wantReceive = false;
  3499. }
  3500. }
  3501. });
  3502.  
  3503. // Create M-lines for recvonly streams.
  3504. while (numAudioTracks > 0 || numVideoTracks > 0) {
  3505. if (numAudioTracks > 0) {
  3506. this._createTransceiver('audio');
  3507. numAudioTracks--;
  3508. }
  3509. if (numVideoTracks > 0) {
  3510. this._createTransceiver('video');
  3511. numVideoTracks--;
  3512. }
  3513. }
  3514. // reorder tracks
  3515. var transceivers = sortTracks(this.transceivers);
  3516.  
  3517. var sdp = SDPUtils.writeSessionBoilerplate(this._sdpSessionId);
  3518. transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3519. // For each track, create an ice gatherer, ice transport,
  3520. // dtls transport, potentially rtpsender and rtpreceiver.
  3521. var track = transceiver.track;
  3522. var kind = transceiver.kind;
  3523. var mid = SDPUtils.generateIdentifier();
  3524. transceiver.mid = mid;
  3525.  
  3526. if (!transceiver.iceGatherer) {
  3527. transceiver.iceGatherer = self.usingBundle && sdpMLineIndex > 0 ?
  3528. transceivers[0].iceGatherer :
  3529. self._createIceGatherer(mid, sdpMLineIndex);
  3530. }
  3531.  
  3532. var localCapabilities = window.RTCRtpSender.getCapabilities(kind);
  3533. // filter RTX until additional stuff needed for RTX is implemented
  3534. // in adapter.js
  3535. if (edgeVersion < 15019) {
  3536. localCapabilities.codecs = localCapabilities.codecs.filter(
  3537. function(codec) {
  3538. return codec.name !== 'rtx';
  3539. });
  3540. }
  3541. localCapabilities.codecs.forEach(function(codec) {
  3542. // work around https://bugs.chromium.org/p/webrtc/issues/detail?id=6552
  3543. // by adding level-asymmetry-allowed=1
  3544. if (codec.name === 'H264' &&
  3545. codec.parameters['level-asymmetry-allowed'] === undefined) {
  3546. codec.parameters['level-asymmetry-allowed'] = '1';
  3547. }
  3548. });
  3549.  
  3550. // generate an ssrc now, to be used later in rtpSender.send
  3551. var sendEncodingParameters = [{
  3552. ssrc: (2 * sdpMLineIndex + 1) * 1001
  3553. }];
  3554. if (track) {
  3555. // add RTX
  3556. if (edgeVersion >= 15019 && kind === 'video') {
  3557. sendEncodingParameters[0].rtx = {
  3558. ssrc: (2 * sdpMLineIndex + 1) * 1001 + 1
  3559. };
  3560. }
  3561. }
  3562.  
  3563. if (transceiver.wantReceive) {
  3564. transceiver.rtpReceiver = new window.RTCRtpReceiver(
  3565. transceiver.dtlsTransport,
  3566. kind
  3567. );
  3568. }
  3569.  
  3570. transceiver.localCapabilities = localCapabilities;
  3571. transceiver.sendEncodingParameters = sendEncodingParameters;
  3572. });
  3573.  
  3574. // always offer BUNDLE and dispose on return if not supported.
  3575. if (this._config.bundlePolicy !== 'max-compat') {
  3576. sdp += 'a=group:BUNDLE ' + transceivers.map(function(t) {
  3577. return t.mid;
  3578. }).join(' ') + '\r\n';
  3579. }
  3580. sdp += 'a=ice-options:trickle\r\n';
  3581.  
  3582. transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3583. sdp += SDPUtils.writeMediaSection(transceiver,
  3584. transceiver.localCapabilities, 'offer', transceiver.stream);
  3585. sdp += 'a=rtcp-rsize\r\n';
  3586. });
  3587.  
  3588. this._pendingOffer = transceivers;
  3589. var desc = new window.RTCSessionDescription({
  3590. type: 'offer',
  3591. sdp: sdp
  3592. });
  3593. if (arguments.length && typeof arguments[0] === 'function') {
  3594. window.setTimeout(arguments[0], 0, desc);
  3595. }
  3596. return Promise.resolve(desc);
  3597. };
  3598.  
  3599. RTCPeerConnection.prototype.createAnswer = function() {
  3600. var sdp = SDPUtils.writeSessionBoilerplate(this._sdpSessionId);
  3601. if (this.usingBundle) {
  3602. sdp += 'a=group:BUNDLE ' + this.transceivers.map(function(t) {
  3603. return t.mid;
  3604. }).join(' ') + '\r\n';
  3605. }
  3606. this.transceivers.forEach(function(transceiver, sdpMLineIndex) {
  3607. if (transceiver.isDatachannel) {
  3608. sdp += 'm=application 0 DTLS/SCTP 5000\r\n' +
  3609. 'c=IN IP4 0.0.0.0\r\n' +
  3610. 'a=mid:' + transceiver.mid + '\r\n';
  3611. return;
  3612. }
  3613.  
  3614. // FIXME: look at direction.
  3615. if (transceiver.stream) {
  3616. var localTrack;
  3617. if (transceiver.kind === 'audio') {
  3618. localTrack = transceiver.stream.getAudioTracks()[0];
  3619. } else if (transceiver.kind === 'video') {
  3620. localTrack = transceiver.stream.getVideoTracks()[0];
  3621. }
  3622. if (localTrack) {
  3623. // add RTX
  3624. if (edgeVersion >= 15019 && transceiver.kind === 'video') {
  3625. transceiver.sendEncodingParameters[0].rtx = {
  3626. ssrc: (2 * sdpMLineIndex + 2) * 1001 + 1
  3627. };
  3628. }
  3629. }
  3630. }
  3631.  
  3632. // Calculate intersection of capabilities.
  3633. var commonCapabilities = getCommonCapabilities(
  3634. transceiver.localCapabilities,
  3635. transceiver.remoteCapabilities);
  3636.  
  3637. var hasRtx = commonCapabilities.codecs.filter(function(c) {
  3638. return c.name.toLowerCase() === 'rtx';
  3639. }).length;
  3640. if (!hasRtx && transceiver.sendEncodingParameters[0].rtx) {
  3641. delete transceiver.sendEncodingParameters[0].rtx;
  3642. }
  3643.  
  3644. sdp += SDPUtils.writeMediaSection(transceiver, commonCapabilities,
  3645. 'answer', transceiver.stream);
  3646. if (transceiver.rtcpParameters &&
  3647. transceiver.rtcpParameters.reducedSize) {
  3648. sdp += 'a=rtcp-rsize\r\n';
  3649. }
  3650. });
  3651.  
  3652. var desc = new window.RTCSessionDescription({
  3653. type: 'answer',
  3654. sdp: sdp
  3655. });
  3656. if (arguments.length && typeof arguments[0] === 'function') {
  3657. window.setTimeout(arguments[0], 0, desc);
  3658. }
  3659. return Promise.resolve(desc);
  3660. };
  3661.  
  3662. RTCPeerConnection.prototype.addIceCandidate = function(candidate) {
  3663. if (!candidate) {
  3664. for (var j = 0; j < this.transceivers.length; j++) {
  3665. this.transceivers[j].iceTransport.addRemoteCandidate({});
  3666. if (this.usingBundle) {
  3667. return Promise.resolve();
  3668. }
  3669. }
  3670. } else {
  3671. var mLineIndex = candidate.sdpMLineIndex;
  3672. if (candidate.sdpMid) {
  3673. for (var i = 0; i < this.transceivers.length; i++) {
  3674. if (this.transceivers[i].mid === candidate.sdpMid) {
  3675. mLineIndex = i;
  3676. break;
  3677. }
  3678. }
  3679. }
  3680. var transceiver = this.transceivers[mLineIndex];
  3681. if (transceiver) {
  3682. var cand = Object.keys(candidate.candidate).length > 0 ?
  3683. SDPUtils.parseCandidate(candidate.candidate) : {};
  3684. // Ignore Chrome's invalid candidates since Edge does not like them.
  3685. if (cand.protocol === 'tcp' && (cand.port === 0 || cand.port === 9)) {
  3686. return Promise.resolve();
  3687. }
  3688. // Ignore RTCP candidates, we assume RTCP-MUX.
  3689. if (cand.component &&
  3690. !(cand.component === '1' || cand.component === 1)) {
  3691. return Promise.resolve();
  3692. }
  3693. transceiver.iceTransport.addRemoteCandidate(cand);
  3694.  
  3695. // update the remoteDescription.
  3696. var sections = SDPUtils.splitSections(this.remoteDescription.sdp);
  3697. sections[mLineIndex + 1] += (cand.type ? candidate.candidate.trim()
  3698. : 'a=end-of-candidates') + '\r\n';
  3699. this.remoteDescription.sdp = sections.join('');
  3700. }
  3701. }
  3702. if (arguments.length > 1 && typeof arguments[1] === 'function') {
  3703. window.setTimeout(arguments[1], 0);
  3704. }
  3705. return Promise.resolve();
  3706. };
  3707.  
  3708. RTCPeerConnection.prototype.getStats = function() {
  3709. var promises = [];
  3710. this.transceivers.forEach(function(transceiver) {
  3711. ['rtpSender', 'rtpReceiver', 'iceGatherer', 'iceTransport',
  3712. 'dtlsTransport'].forEach(function(method) {
  3713. if (transceiver[method]) {
  3714. promises.push(transceiver[method].getStats());
  3715. }
  3716. });
  3717. });
  3718. var cb = arguments.length > 1 && typeof arguments[1] === 'function' &&
  3719. arguments[1];
  3720. var fixStatsType = function(stat) {
  3721. return {
  3722. inboundrtp: 'inbound-rtp',
  3723. outboundrtp: 'outbound-rtp',
  3724. candidatepair: 'candidate-pair',
  3725. localcandidate: 'local-candidate',
  3726. remotecandidate: 'remote-candidate'
  3727. }[stat.type] || stat.type;
  3728. };
  3729. return new Promise(function(resolve) {
  3730. // shim getStats with maplike support
  3731. var results = new Map();
  3732. Promise.all(promises).then(function(res) {
  3733. res.forEach(function(result) {
  3734. Object.keys(result).forEach(function(id) {
  3735. result[id].type = fixStatsType(result[id]);
  3736. results.set(id, result[id]);
  3737. });
  3738. });
  3739. if (cb) {
  3740. window.setTimeout(cb, 0, results);
  3741. }
  3742. resolve(results);
  3743. });
  3744. });
  3745. };
  3746. return RTCPeerConnection;
  3747. };
  3748.  
  3749.  
  3750. /***/ }),
  3751. /* 16 */
  3752. /***/ (function(module, exports, __webpack_require__) {
  3753.  
  3754. "use strict";
  3755. /* eslint-env node */
  3756.  
  3757.  
  3758. // SDP helpers.
  3759. var SDPUtils = {};
  3760.  
  3761. // Generate an alphanumeric identifier for cname or mids.
  3762. // TODO: use UUIDs instead? https://gist.github.com/jed/982883
  3763. SDPUtils.generateIdentifier = function() {
  3764. return Math.random().toString(36).substr(2, 10);
  3765. };
  3766.  
  3767. // The RTCP CNAME used by all peerconnections from the same JS.
  3768. SDPUtils.localCName = SDPUtils.generateIdentifier();
  3769.  
  3770. // Splits SDP into lines, dealing with both CRLF and LF.
  3771. SDPUtils.splitLines = function(blob) {
  3772. return blob.trim().split('\n').map(function(line) {
  3773. return line.trim();
  3774. });
  3775. };
  3776. // Splits SDP into sessionpart and mediasections. Ensures CRLF.
  3777. SDPUtils.splitSections = function(blob) {
  3778. var parts = blob.split('\nm=');
  3779. return parts.map(function(part, index) {
  3780. return (index > 0 ? 'm=' + part : part).trim() + '\r\n';
  3781. });
  3782. };
  3783.  
  3784. // Returns lines that start with a certain prefix.
  3785. SDPUtils.matchPrefix = function(blob, prefix) {
  3786. return SDPUtils.splitLines(blob).filter(function(line) {
  3787. return line.indexOf(prefix) === 0;
  3788. });
  3789. };
  3790.  
  3791. // Parses an ICE candidate line. Sample input:
  3792. // candidate:702786350 2 udp 41819902 8.8.8.8 60769 typ relay raddr 8.8.8.8
  3793. // rport 55996"
  3794. SDPUtils.parseCandidate = function(line) {
  3795. var parts;
  3796. // Parse both variants.
  3797. if (line.indexOf('a=candidate:') === 0) {
  3798. parts = line.substring(12).split(' ');
  3799. } else {
  3800. parts = line.substring(10).split(' ');
  3801. }
  3802.  
  3803. var candidate = {
  3804. foundation: parts[0],
  3805. component: parseInt(parts[1], 10),
  3806. protocol: parts[2].toLowerCase(),
  3807. priority: parseInt(parts[3], 10),
  3808. ip: parts[4],
  3809. port: parseInt(parts[5], 10),
  3810. // skip parts[6] == 'typ'
  3811. type: parts[7]
  3812. };
  3813.  
  3814. for (var i = 8; i < parts.length; i += 2) {
  3815. switch (parts[i]) {
  3816. case 'raddr':
  3817. candidate.relatedAddress = parts[i + 1];
  3818. break;
  3819. case 'rport':
  3820. candidate.relatedPort = parseInt(parts[i + 1], 10);
  3821. break;
  3822. case 'tcptype':
  3823. candidate.tcpType = parts[i + 1];
  3824. break;
  3825. default: // extension handling, in particular ufrag
  3826. candidate[parts[i]] = parts[i + 1];
  3827. break;
  3828. }
  3829. }
  3830. return candidate;
  3831. };
  3832.  
  3833. // Translates a candidate object into SDP candidate attribute.
  3834. SDPUtils.writeCandidate = function(candidate) {
  3835. var sdp = [];
  3836. sdp.push(candidate.foundation);
  3837. sdp.push(candidate.component);
  3838. sdp.push(candidate.protocol.toUpperCase());
  3839. sdp.push(candidate.priority);
  3840. sdp.push(candidate.ip);
  3841. sdp.push(candidate.port);
  3842.  
  3843. var type = candidate.type;
  3844. sdp.push('typ');
  3845. sdp.push(type);
  3846. if (type !== 'host' && candidate.relatedAddress &&
  3847. candidate.relatedPort) {
  3848. sdp.push('raddr');
  3849. sdp.push(candidate.relatedAddress); // was: relAddr
  3850. sdp.push('rport');
  3851. sdp.push(candidate.relatedPort); // was: relPort
  3852. }
  3853. if (candidate.tcpType && candidate.protocol.toLowerCase() === 'tcp') {
  3854. sdp.push('tcptype');
  3855. sdp.push(candidate.tcpType);
  3856. }
  3857. if (candidate.ufrag) {
  3858. sdp.push('ufrag');
  3859. sdp.push(candidate.ufrag);
  3860. }
  3861. return 'candidate:' + sdp.join(' ');
  3862. };
  3863.  
  3864. // Parses an ice-options line, returns an array of option tags.
  3865. // a=ice-options:foo bar
  3866. SDPUtils.parseIceOptions = function(line) {
  3867. return line.substr(14).split(' ');
  3868. }
  3869.  
  3870. // Parses an rtpmap line, returns RTCRtpCoddecParameters. Sample input:
  3871. // a=rtpmap:111 opus/48000/2
  3872. SDPUtils.parseRtpMap = function(line) {
  3873. var parts = line.substr(9).split(' ');
  3874. var parsed = {
  3875. payloadType: parseInt(parts.shift(), 10) // was: id
  3876. };
  3877.  
  3878. parts = parts[0].split('/');
  3879.  
  3880. parsed.name = parts[0];
  3881. parsed.clockRate = parseInt(parts[1], 10); // was: clockrate
  3882. // was: channels
  3883. parsed.numChannels = parts.length === 3 ? parseInt(parts[2], 10) : 1;
  3884. return parsed;
  3885. };
  3886.  
  3887. // Generate an a=rtpmap line from RTCRtpCodecCapability or
  3888. // RTCRtpCodecParameters.
  3889. SDPUtils.writeRtpMap = function(codec) {
  3890. var pt = codec.payloadType;
  3891. if (codec.preferredPayloadType !== undefined) {
  3892. pt = codec.preferredPayloadType;
  3893. }
  3894. return 'a=rtpmap:' + pt + ' ' + codec.name + '/' + codec.clockRate +
  3895. (codec.numChannels !== 1 ? '/' + codec.numChannels : '') + '\r\n';
  3896. };
  3897.  
  3898. // Parses an a=extmap line (headerextension from RFC 5285). Sample input:
  3899. // a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  3900. // a=extmap:2/sendonly urn:ietf:params:rtp-hdrext:toffset
  3901. SDPUtils.parseExtmap = function(line) {
  3902. var parts = line.substr(9).split(' ');
  3903. return {
  3904. id: parseInt(parts[0], 10),
  3905. direction: parts[0].indexOf('/') > 0 ? parts[0].split('/')[1] : 'sendrecv',
  3906. uri: parts[1]
  3907. };
  3908. };
  3909.  
  3910. // Generates a=extmap line from RTCRtpHeaderExtensionParameters or
  3911. // RTCRtpHeaderExtension.
  3912. SDPUtils.writeExtmap = function(headerExtension) {
  3913. return 'a=extmap:' + (headerExtension.id || headerExtension.preferredId) +
  3914. (headerExtension.direction && headerExtension.direction !== 'sendrecv'
  3915. ? '/' + headerExtension.direction
  3916. : '') +
  3917. ' ' + headerExtension.uri + '\r\n';
  3918. };
  3919.  
  3920. // Parses an ftmp line, returns dictionary. Sample input:
  3921. // a=fmtp:96 vbr=on;cng=on
  3922. // Also deals with vbr=on; cng=on
  3923. SDPUtils.parseFmtp = function(line) {
  3924. var parsed = {};
  3925. var kv;
  3926. var parts = line.substr(line.indexOf(' ') + 1).split(';');
  3927. for (var j = 0; j < parts.length; j++) {
  3928. kv = parts[j].trim().split('=');
  3929. parsed[kv[0].trim()] = kv[1];
  3930. }
  3931. return parsed;
  3932. };
  3933.  
  3934. // Generates an a=ftmp line from RTCRtpCodecCapability or RTCRtpCodecParameters.
  3935. SDPUtils.writeFmtp = function(codec) {
  3936. var line = '';
  3937. var pt = codec.payloadType;
  3938. if (codec.preferredPayloadType !== undefined) {
  3939. pt = codec.preferredPayloadType;
  3940. }
  3941. if (codec.parameters && Object.keys(codec.parameters).length) {
  3942. var params = [];
  3943. Object.keys(codec.parameters).forEach(function(param) {
  3944. params.push(param + '=' + codec.parameters[param]);
  3945. });
  3946. line += 'a=fmtp:' + pt + ' ' + params.join(';') + '\r\n';
  3947. }
  3948. return line;
  3949. };
  3950.  
  3951. // Parses an rtcp-fb line, returns RTCPRtcpFeedback object. Sample input:
  3952. // a=rtcp-fb:98 nack rpsi
  3953. SDPUtils.parseRtcpFb = function(line) {
  3954. var parts = line.substr(line.indexOf(' ') + 1).split(' ');
  3955. return {
  3956. type: parts.shift(),
  3957. parameter: parts.join(' ')
  3958. };
  3959. };
  3960. // Generate a=rtcp-fb lines from RTCRtpCodecCapability or RTCRtpCodecParameters.
  3961. SDPUtils.writeRtcpFb = function(codec) {
  3962. var lines = '';
  3963. var pt = codec.payloadType;
  3964. if (codec.preferredPayloadType !== undefined) {
  3965. pt = codec.preferredPayloadType;
  3966. }
  3967. if (codec.rtcpFeedback && codec.rtcpFeedback.length) {
  3968. // FIXME: special handling for trr-int?
  3969. codec.rtcpFeedback.forEach(function(fb) {
  3970. lines += 'a=rtcp-fb:' + pt + ' ' + fb.type +
  3971. (fb.parameter && fb.parameter.length ? ' ' + fb.parameter : '') +
  3972. '\r\n';
  3973. });
  3974. }
  3975. return lines;
  3976. };
  3977.  
  3978. // Parses an RFC 5576 ssrc media attribute. Sample input:
  3979. // a=ssrc:3735928559 cname:something
  3980. SDPUtils.parseSsrcMedia = function(line) {
  3981. var sp = line.indexOf(' ');
  3982. var parts = {
  3983. ssrc: parseInt(line.substr(7, sp - 7), 10)
  3984. };
  3985. var colon = line.indexOf(':', sp);
  3986. if (colon > -1) {
  3987. parts.attribute = line.substr(sp + 1, colon - sp - 1);
  3988. parts.value = line.substr(colon + 1);
  3989. } else {
  3990. parts.attribute = line.substr(sp + 1);
  3991. }
  3992. return parts;
  3993. };
  3994.  
  3995. // Extracts the MID (RFC 5888) from a media section.
  3996. // returns the MID or undefined if no mid line was found.
  3997. SDPUtils.getMid = function(mediaSection) {
  3998. var mid = SDPUtils.matchPrefix(mediaSection, 'a=mid:')[0];
  3999. if (mid) {
  4000. return mid.substr(6);
  4001. }
  4002. }
  4003.  
  4004. SDPUtils.parseFingerprint = function(line) {
  4005. var parts = line.substr(14).split(' ');
  4006. return {
  4007. algorithm: parts[0].toLowerCase(), // algorithm is case-sensitive in Edge.
  4008. value: parts[1]
  4009. };
  4010. };
  4011.  
  4012. // Extracts DTLS parameters from SDP media section or sessionpart.
  4013. // FIXME: for consistency with other functions this should only
  4014. // get the fingerprint line as input. See also getIceParameters.
  4015. SDPUtils.getDtlsParameters = function(mediaSection, sessionpart) {
  4016. var lines = SDPUtils.matchPrefix(mediaSection + sessionpart,
  4017. 'a=fingerprint:');
  4018. // Note: a=setup line is ignored since we use the 'auto' role.
  4019. // Note2: 'algorithm' is not case sensitive except in Edge.
  4020. return {
  4021. role: 'auto',
  4022. fingerprints: lines.map(SDPUtils.parseFingerprint)
  4023. };
  4024. };
  4025.  
  4026. // Serializes DTLS parameters to SDP.
  4027. SDPUtils.writeDtlsParameters = function(params, setupType) {
  4028. var sdp = 'a=setup:' + setupType + '\r\n';
  4029. params.fingerprints.forEach(function(fp) {
  4030. sdp += 'a=fingerprint:' + fp.algorithm + ' ' + fp.value + '\r\n';
  4031. });
  4032. return sdp;
  4033. };
  4034. // Parses ICE information from SDP media section or sessionpart.
  4035. // FIXME: for consistency with other functions this should only
  4036. // get the ice-ufrag and ice-pwd lines as input.
  4037. SDPUtils.getIceParameters = function(mediaSection, sessionpart) {
  4038. var lines = SDPUtils.splitLines(mediaSection);
  4039. // Search in session part, too.
  4040. lines = lines.concat(SDPUtils.splitLines(sessionpart));
  4041. var iceParameters = {
  4042. usernameFragment: lines.filter(function(line) {
  4043. return line.indexOf('a=ice-ufrag:') === 0;
  4044. })[0].substr(12),
  4045. password: lines.filter(function(line) {
  4046. return line.indexOf('a=ice-pwd:') === 0;
  4047. })[0].substr(10)
  4048. };
  4049. return iceParameters;
  4050. };
  4051.  
  4052. // Serializes ICE parameters to SDP.
  4053. SDPUtils.writeIceParameters = function(params) {
  4054. return 'a=ice-ufrag:' + params.usernameFragment + '\r\n' +
  4055. 'a=ice-pwd:' + params.password + '\r\n';
  4056. };
  4057.  
  4058. // Parses the SDP media section and returns RTCRtpParameters.
  4059. SDPUtils.parseRtpParameters = function(mediaSection) {
  4060. var description = {
  4061. codecs: [],
  4062. headerExtensions: [],
  4063. fecMechanisms: [],
  4064. rtcp: []
  4065. };
  4066. var lines = SDPUtils.splitLines(mediaSection);
  4067. var mline = lines[0].split(' ');
  4068. for (var i = 3; i < mline.length; i++) { // find all codecs from mline[3..]
  4069. var pt = mline[i];
  4070. var rtpmapline = SDPUtils.matchPrefix(
  4071. mediaSection, 'a=rtpmap:' + pt + ' ')[0];
  4072. if (rtpmapline) {
  4073. var codec = SDPUtils.parseRtpMap(rtpmapline);
  4074. var fmtps = SDPUtils.matchPrefix(
  4075. mediaSection, 'a=fmtp:' + pt + ' ');
  4076. // Only the first a=fmtp:<pt> is considered.
  4077. codec.parameters = fmtps.length ? SDPUtils.parseFmtp(fmtps[0]) : {};
  4078. codec.rtcpFeedback = SDPUtils.matchPrefix(
  4079. mediaSection, 'a=rtcp-fb:' + pt + ' ')
  4080. .map(SDPUtils.parseRtcpFb);
  4081. description.codecs.push(codec);
  4082. // parse FEC mechanisms from rtpmap lines.
  4083. switch (codec.name.toUpperCase()) {
  4084. case 'RED':
  4085. case 'ULPFEC':
  4086. description.fecMechanisms.push(codec.name.toUpperCase());
  4087. break;
  4088. default: // only RED and ULPFEC are recognized as FEC mechanisms.
  4089. break;
  4090. }
  4091. }
  4092. }
  4093. SDPUtils.matchPrefix(mediaSection, 'a=extmap:').forEach(function(line) {
  4094. description.headerExtensions.push(SDPUtils.parseExtmap(line));
  4095. });
  4096. // FIXME: parse rtcp.
  4097. return description;
  4098. };
  4099.  
  4100. // Generates parts of the SDP media section describing the capabilities /
  4101. // parameters.
  4102. SDPUtils.writeRtpDescription = function(kind, caps) {
  4103. var sdp = '';
  4104.  
  4105. // Build the mline.
  4106. sdp += 'm=' + kind + ' ';
  4107. sdp += caps.codecs.length > 0 ? '9' : '0'; // reject if no codecs.
  4108. sdp += ' UDP/TLS/RTP/SAVPF ';
  4109. sdp += caps.codecs.map(function(codec) {
  4110. if (codec.preferredPayloadType !== undefined) {
  4111. return codec.preferredPayloadType;
  4112. }
  4113. return codec.payloadType;
  4114. }).join(' ') + '\r\n';
  4115.  
  4116. sdp += 'c=IN IP4 0.0.0.0\r\n';
  4117. sdp += 'a=rtcp:9 IN IP4 0.0.0.0\r\n';
  4118.  
  4119. // Add a=rtpmap lines for each codec. Also fmtp and rtcp-fb.
  4120. caps.codecs.forEach(function(codec) {
  4121. sdp += SDPUtils.writeRtpMap(codec);
  4122. sdp += SDPUtils.writeFmtp(codec);
  4123. sdp += SDPUtils.writeRtcpFb(codec);
  4124. });
  4125. var maxptime = 0;
  4126. caps.codecs.forEach(function(codec) {
  4127. if (codec.maxptime > maxptime) {
  4128. maxptime = codec.maxptime;
  4129. }
  4130. });
  4131. if (maxptime > 0) {
  4132. sdp += 'a=maxptime:' + maxptime + '\r\n';
  4133. }
  4134. sdp += 'a=rtcp-mux\r\n';
  4135.  
  4136. caps.headerExtensions.forEach(function(extension) {
  4137. sdp += SDPUtils.writeExtmap(extension);
  4138. });
  4139. // FIXME: write fecMechanisms.
  4140. return sdp;
  4141. };
  4142.  
  4143. // Parses the SDP media section and returns an array of
  4144. // RTCRtpEncodingParameters.
  4145. SDPUtils.parseRtpEncodingParameters = function(mediaSection) {
  4146. var encodingParameters = [];
  4147. var description = SDPUtils.parseRtpParameters(mediaSection);
  4148. var hasRed = description.fecMechanisms.indexOf('RED') !== -1;
  4149. var hasUlpfec = description.fecMechanisms.indexOf('ULPFEC') !== -1;
  4150.  
  4151. // filter a=ssrc:... cname:, ignore PlanB-msid
  4152. var ssrcs = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  4153. .map(function(line) {
  4154. return SDPUtils.parseSsrcMedia(line);
  4155. })
  4156. .filter(function(parts) {
  4157. return parts.attribute === 'cname';
  4158. });
  4159. var primarySsrc = ssrcs.length > 0 && ssrcs[0].ssrc;
  4160. var secondarySsrc;
  4161.  
  4162. var flows = SDPUtils.matchPrefix(mediaSection, 'a=ssrc-group:FID')
  4163. .map(function(line) {
  4164. var parts = line.split(' ');
  4165. parts.shift();
  4166. return parts.map(function(part) {
  4167. return parseInt(part, 10);
  4168. });
  4169. });
  4170. if (flows.length > 0 && flows[0].length > 1 && flows[0][0] === primarySsrc) {
  4171. secondarySsrc = flows[0][1];
  4172. }
  4173.  
  4174. description.codecs.forEach(function(codec) {
  4175. if (codec.name.toUpperCase() === 'RTX' && codec.parameters.apt) {
  4176. var encParam = {
  4177. ssrc: primarySsrc,
  4178. codecPayloadType: parseInt(codec.parameters.apt, 10),
  4179. rtx: {
  4180. ssrc: secondarySsrc
  4181. }
  4182. };
  4183. encodingParameters.push(encParam);
  4184. if (hasRed) {
  4185. encParam = JSON.parse(JSON.stringify(encParam));
  4186. encParam.fec = {
  4187. ssrc: secondarySsrc,
  4188. mechanism: hasUlpfec ? 'red+ulpfec' : 'red'
  4189. };
  4190. encodingParameters.push(encParam);
  4191. }
  4192. }
  4193. });
  4194. if (encodingParameters.length === 0 && primarySsrc) {
  4195. encodingParameters.push({
  4196. ssrc: primarySsrc
  4197. });
  4198. }
  4199.  
  4200. // we support both b=AS and b=TIAS but interpret AS as TIAS.
  4201. var bandwidth = SDPUtils.matchPrefix(mediaSection, 'b=');
  4202. if (bandwidth.length) {
  4203. if (bandwidth[0].indexOf('b=TIAS:') === 0) {
  4204. bandwidth = parseInt(bandwidth[0].substr(7), 10);
  4205. } else if (bandwidth[0].indexOf('b=AS:') === 0) {
  4206. // use formula from JSEP to convert b=AS to TIAS value.
  4207. bandwidth = parseInt(bandwidth[0].substr(5), 10) * 1000 * 0.95
  4208. - (50 * 40 * 8);
  4209. } else {
  4210. bandwidth = undefined;
  4211. }
  4212. encodingParameters.forEach(function(params) {
  4213. params.maxBitrate = bandwidth;
  4214. });
  4215. }
  4216. return encodingParameters;
  4217. };
  4218.  
  4219. // parses http://draft.ortc.org/#rtcrtcpparameters*
  4220. SDPUtils.parseRtcpParameters = function(mediaSection) {
  4221. var rtcpParameters = {};
  4222.  
  4223. var cname;
  4224. // Gets the first SSRC. Note that with RTX there might be multiple
  4225. // SSRCs.
  4226. var remoteSsrc = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  4227. .map(function(line) {
  4228. return SDPUtils.parseSsrcMedia(line);
  4229. })
  4230. .filter(function(obj) {
  4231. return obj.attribute === 'cname';
  4232. })[0];
  4233. if (remoteSsrc) {
  4234. rtcpParameters.cname = remoteSsrc.value;
  4235. rtcpParameters.ssrc = remoteSsrc.ssrc;
  4236. }
  4237.  
  4238. // Edge uses the compound attribute instead of reducedSize
  4239. // compound is !reducedSize
  4240. var rsize = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-rsize');
  4241. rtcpParameters.reducedSize = rsize.length > 0;
  4242. rtcpParameters.compound = rsize.length === 0;
  4243.  
  4244. // parses the rtcp-mux attrіbute.
  4245. // Note that Edge does not support unmuxed RTCP.
  4246. var mux = SDPUtils.matchPrefix(mediaSection, 'a=rtcp-mux');
  4247. rtcpParameters.mux = mux.length > 0;
  4248.  
  4249. return rtcpParameters;
  4250. };
  4251.  
  4252. // parses either a=msid: or a=ssrc:... msid lines and returns
  4253. // the id of the MediaStream and MediaStreamTrack.
  4254. SDPUtils.parseMsid = function(mediaSection) {
  4255. var parts;
  4256. var spec = SDPUtils.matchPrefix(mediaSection, 'a=msid:');
  4257. if (spec.length === 1) {
  4258. parts = spec[0].substr(7).split(' ');
  4259. return {stream: parts[0], track: parts[1]};
  4260. }
  4261. var planB = SDPUtils.matchPrefix(mediaSection, 'a=ssrc:')
  4262. .map(function(line) {
  4263. return SDPUtils.parseSsrcMedia(line);
  4264. })
  4265. .filter(function(parts) {
  4266. return parts.attribute === 'msid';
  4267. });
  4268. if (planB.length > 0) {
  4269. parts = planB[0].value.split(' ');
  4270. return {stream: parts[0], track: parts[1]};
  4271. }
  4272. };
  4273.  
  4274. // Generate a session ID for SDP.
  4275. // https://tools.ietf.org/html/draft-ietf-rtcweb-jsep-20#section-5.2.1
  4276. // recommends using a cryptographically random +ve 64-bit value
  4277. // but right now this should be acceptable and within the right range
  4278. SDPUtils.generateSessionId = function() {
  4279. return Math.random().toString().substr(2, 21);
  4280. };
  4281.  
  4282. // Write boilder plate for start of SDP
  4283. // sessId argument is optional - if not supplied it will
  4284. // be generated randomly
  4285. // sessVersion is optional and defaults to 2
  4286. SDPUtils.writeSessionBoilerplate = function(sessId, sessVer) {
  4287. var sessionId;
  4288. var version = sessVer !== undefined ? sessVer : 2;
  4289. if (sessId) {
  4290. sessionId = sessId;
  4291. } else {
  4292. sessionId = SDPUtils.generateSessionId();
  4293. }
  4294. // FIXME: sess-id should be an NTP timestamp.
  4295. return 'v=0\r\n' +
  4296. 'o=thisisadapterortc ' + sessionId + ' ' + version + ' IN IP4 127.0.0.1\r\n' +
  4297. 's=-\r\n' +
  4298. 't=0 0\r\n';
  4299. };
  4300.  
  4301. SDPUtils.writeMediaSection = function(transceiver, caps, type, stream) {
  4302. var sdp = SDPUtils.writeRtpDescription(transceiver.kind, caps);
  4303.  
  4304. // Map ICE parameters (ufrag, pwd) to SDP.
  4305. sdp += SDPUtils.writeIceParameters(
  4306. transceiver.iceGatherer.getLocalParameters());
  4307.  
  4308. // Map DTLS parameters to SDP.
  4309. sdp += SDPUtils.writeDtlsParameters(
  4310. transceiver.dtlsTransport.getLocalParameters(),
  4311. type === 'offer' ? 'actpass' : 'active');
  4312.  
  4313. sdp += 'a=mid:' + transceiver.mid + '\r\n';
  4314.  
  4315. if (transceiver.direction) {
  4316. sdp += 'a=' + transceiver.direction + '\r\n';
  4317. } else if (transceiver.rtpSender && transceiver.rtpReceiver) {
  4318. sdp += 'a=sendrecv\r\n';
  4319. } else if (transceiver.rtpSender) {
  4320. sdp += 'a=sendonly\r\n';
  4321. } else if (transceiver.rtpReceiver) {
  4322. sdp += 'a=recvonly\r\n';
  4323. } else {
  4324. sdp += 'a=inactive\r\n';
  4325. }
  4326.  
  4327. if (transceiver.rtpSender) {
  4328. // spec.
  4329. var msid = 'msid:' + stream.id + ' ' +
  4330. transceiver.rtpSender.track.id + '\r\n';
  4331. sdp += 'a=' + msid;
  4332.  
  4333. // for Chrome.
  4334. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  4335. ' ' + msid;
  4336. if (transceiver.sendEncodingParameters[0].rtx) {
  4337. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  4338. ' ' + msid;
  4339. sdp += 'a=ssrc-group:FID ' +
  4340. transceiver.sendEncodingParameters[0].ssrc + ' ' +
  4341. transceiver.sendEncodingParameters[0].rtx.ssrc +
  4342. '\r\n';
  4343. }
  4344. }
  4345. // FIXME: this should be written by writeRtpDescription.
  4346. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].ssrc +
  4347. ' cname:' + SDPUtils.localCName + '\r\n';
  4348. if (transceiver.rtpSender && transceiver.sendEncodingParameters[0].rtx) {
  4349. sdp += 'a=ssrc:' + transceiver.sendEncodingParameters[0].rtx.ssrc +
  4350. ' cname:' + SDPUtils.localCName + '\r\n';
  4351. }
  4352. return sdp;
  4353. };
  4354.  
  4355. // Gets the direction from the mediaSection or the sessionpart.
  4356. SDPUtils.getDirection = function(mediaSection, sessionpart) {
  4357. // Look for sendrecv, sendonly, recvonly, inactive, default to sendrecv.
  4358. var lines = SDPUtils.splitLines(mediaSection);
  4359. for (var i = 0; i < lines.length; i++) {
  4360. switch (lines[i]) {
  4361. case 'a=sendrecv':
  4362. case 'a=sendonly':
  4363. case 'a=recvonly':
  4364. case 'a=inactive':
  4365. return lines[i].substr(2);
  4366. default:
  4367. // FIXME: What should happen here?
  4368. }
  4369. }
  4370. if (sessionpart) {
  4371. return SDPUtils.getDirection(sessionpart);
  4372. }
  4373. return 'sendrecv';
  4374. };
  4375.  
  4376. SDPUtils.getKind = function(mediaSection) {
  4377. var lines = SDPUtils.splitLines(mediaSection);
  4378. var mline = lines[0].split(' ');
  4379. return mline[0].substr(2);
  4380. };
  4381.  
  4382. SDPUtils.isRejected = function(mediaSection) {
  4383. return mediaSection.split(' ', 2)[1] === '0';
  4384. };
  4385.  
  4386. // Expose public methods.
  4387. module.exports = SDPUtils;
  4388.  
  4389.  
  4390. /***/ }),
  4391. /* 17 */
  4392. /***/ (function(module, exports, __webpack_require__) {
  4393.  
  4394. "use strict";
  4395. /*
  4396. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4397. *
  4398. * Use of this source code is governed by a BSD-style license
  4399. * that can be found in the LICENSE file in the root of the source
  4400. * tree.
  4401. */
  4402. /* eslint-env node */
  4403.  
  4404.  
  4405. // Expose public methods.
  4406. module.exports = function(window) {
  4407. var navigator = window && window.navigator;
  4408.  
  4409. var shimError_ = function(e) {
  4410. return {
  4411. name: {PermissionDeniedError: 'NotAllowedError'}[e.name] || e.name,
  4412. message: e.message,
  4413. constraint: e.constraint,
  4414. toString: function() {
  4415. return this.name;
  4416. }
  4417. };
  4418. };
  4419.  
  4420. // getUserMedia error shim.
  4421. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  4422. bind(navigator.mediaDevices);
  4423. navigator.mediaDevices.getUserMedia = function(c) {
  4424. return origGetUserMedia(c).catch(function(e) {
  4425. return Promise.reject(shimError_(e));
  4426. });
  4427. };
  4428. };
  4429.  
  4430.  
  4431. /***/ }),
  4432. /* 18 */
  4433. /***/ (function(module, exports, __webpack_require__) {
  4434.  
  4435. "use strict";
  4436. /*
  4437. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4438. *
  4439. * Use of this source code is governed by a BSD-style license
  4440. * that can be found in the LICENSE file in the root of the source
  4441. * tree.
  4442. */
  4443. /* eslint-env node */
  4444.  
  4445.  
  4446. var utils = __webpack_require__(0);
  4447.  
  4448. var firefoxShim = {
  4449. shimOnTrack: function(window) {
  4450. if (typeof window === 'object' && window.RTCPeerConnection && !('ontrack' in
  4451. window.RTCPeerConnection.prototype)) {
  4452. Object.defineProperty(window.RTCPeerConnection.prototype, 'ontrack', {
  4453. get: function() {
  4454. return this._ontrack;
  4455. },
  4456. set: function(f) {
  4457. if (this._ontrack) {
  4458. this.removeEventListener('track', this._ontrack);
  4459. this.removeEventListener('addstream', this._ontrackpoly);
  4460. }
  4461. this.addEventListener('track', this._ontrack = f);
  4462. this.addEventListener('addstream', this._ontrackpoly = function(e) {
  4463. e.stream.getTracks().forEach(function(track) {
  4464. var event = new Event('track');
  4465. event.track = track;
  4466. event.receiver = {track: track};
  4467. event.streams = [e.stream];
  4468. this.dispatchEvent(event);
  4469. }.bind(this));
  4470. }.bind(this));
  4471. }
  4472. });
  4473. }
  4474. },
  4475.  
  4476. shimSourceObject: function(window) {
  4477. // Firefox has supported mozSrcObject since FF22, unprefixed in 42.
  4478. if (typeof window === 'object') {
  4479. if (window.HTMLMediaElement &&
  4480. !('srcObject' in window.HTMLMediaElement.prototype)) {
  4481. // Shim the srcObject property, once, when HTMLMediaElement is found.
  4482. Object.defineProperty(window.HTMLMediaElement.prototype, 'srcObject', {
  4483. get: function() {
  4484. return this.mozSrcObject;
  4485. },
  4486. set: function(stream) {
  4487. this.mozSrcObject = stream;
  4488. }
  4489. });
  4490. }
  4491. }
  4492. },
  4493.  
  4494. shimPeerConnection: function(window) {
  4495. var browserDetails = utils.detectBrowser(window);
  4496.  
  4497. if (typeof window !== 'object' || !(window.RTCPeerConnection ||
  4498. window.mozRTCPeerConnection)) {
  4499. return; // probably media.peerconnection.enabled=false in about:config
  4500. }
  4501. // The RTCPeerConnection object.
  4502. if (!window.RTCPeerConnection) {
  4503. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  4504. if (browserDetails.version < 38) {
  4505. // .urls is not supported in FF < 38.
  4506. // create RTCIceServers with a single url.
  4507. if (pcConfig && pcConfig.iceServers) {
  4508. var newIceServers = [];
  4509. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  4510. var server = pcConfig.iceServers[i];
  4511. if (server.hasOwnProperty('urls')) {
  4512. for (var j = 0; j < server.urls.length; j++) {
  4513. var newServer = {
  4514. url: server.urls[j]
  4515. };
  4516. if (server.urls[j].indexOf('turn') === 0) {
  4517. newServer.username = server.username;
  4518. newServer.credential = server.credential;
  4519. }
  4520. newIceServers.push(newServer);
  4521. }
  4522. } else {
  4523. newIceServers.push(pcConfig.iceServers[i]);
  4524. }
  4525. }
  4526. pcConfig.iceServers = newIceServers;
  4527. }
  4528. }
  4529. return new window.mozRTCPeerConnection(pcConfig, pcConstraints);
  4530. };
  4531. window.RTCPeerConnection.prototype =
  4532. window.mozRTCPeerConnection.prototype;
  4533.  
  4534. // wrap static methods. Currently just generateCertificate.
  4535. if (window.mozRTCPeerConnection.generateCertificate) {
  4536. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  4537. get: function() {
  4538. return window.mozRTCPeerConnection.generateCertificate;
  4539. }
  4540. });
  4541. }
  4542.  
  4543. window.RTCSessionDescription = window.mozRTCSessionDescription;
  4544. window.RTCIceCandidate = window.mozRTCIceCandidate;
  4545. }
  4546.  
  4547. // shim away need for obsolete RTCIceCandidate/RTCSessionDescription.
  4548. ['setLocalDescription', 'setRemoteDescription', 'addIceCandidate']
  4549. .forEach(function(method) {
  4550. var nativeMethod = window.RTCPeerConnection.prototype[method];
  4551. window.RTCPeerConnection.prototype[method] = function() {
  4552. arguments[0] = new ((method === 'addIceCandidate') ?
  4553. window.RTCIceCandidate :
  4554. window.RTCSessionDescription)(arguments[0]);
  4555. return nativeMethod.apply(this, arguments);
  4556. };
  4557. });
  4558.  
  4559. // support for addIceCandidate(null or undefined)
  4560. var nativeAddIceCandidate =
  4561. window.RTCPeerConnection.prototype.addIceCandidate;
  4562. window.RTCPeerConnection.prototype.addIceCandidate = function() {
  4563. if (!arguments[0]) {
  4564. if (arguments[1]) {
  4565. arguments[1].apply(null);
  4566. }
  4567. return Promise.resolve();
  4568. }
  4569. return nativeAddIceCandidate.apply(this, arguments);
  4570. };
  4571.  
  4572. // shim getStats with maplike support
  4573. var makeMapStats = function(stats) {
  4574. var map = new Map();
  4575. Object.keys(stats).forEach(function(key) {
  4576. map.set(key, stats[key]);
  4577. map[key] = stats[key];
  4578. });
  4579. return map;
  4580. };
  4581.  
  4582. var modernStatsTypes = {
  4583. inboundrtp: 'inbound-rtp',
  4584. outboundrtp: 'outbound-rtp',
  4585. candidatepair: 'candidate-pair',
  4586. localcandidate: 'local-candidate',
  4587. remotecandidate: 'remote-candidate'
  4588. };
  4589.  
  4590. var nativeGetStats = window.RTCPeerConnection.prototype.getStats;
  4591. window.RTCPeerConnection.prototype.getStats = function(
  4592. selector,
  4593. onSucc,
  4594. onErr
  4595. ) {
  4596. return nativeGetStats.apply(this, [selector || null])
  4597. .then(function(stats) {
  4598. if (browserDetails.version < 48) {
  4599. stats = makeMapStats(stats);
  4600. }
  4601. if (browserDetails.version < 53 && !onSucc) {
  4602. // Shim only promise getStats with spec-hyphens in type names
  4603. // Leave callback version alone; misc old uses of forEach before Map
  4604. try {
  4605. stats.forEach(function(stat) {
  4606. stat.type = modernStatsTypes[stat.type] || stat.type;
  4607. });
  4608. } catch (e) {
  4609. if (e.name !== 'TypeError') {
  4610. throw e;
  4611. }
  4612. // Avoid TypeError: "type" is read-only, in old versions. 34-43ish
  4613. stats.forEach(function(stat, i) {
  4614. stats.set(i, Object.assign({}, stat, {
  4615. type: modernStatsTypes[stat.type] || stat.type
  4616. }));
  4617. });
  4618. }
  4619. }
  4620. return stats;
  4621. })
  4622. .then(onSucc, onErr);
  4623. };
  4624. }
  4625. };
  4626.  
  4627. // Expose public methods.
  4628. module.exports = {
  4629. shimOnTrack: firefoxShim.shimOnTrack,
  4630. shimSourceObject: firefoxShim.shimSourceObject,
  4631. shimPeerConnection: firefoxShim.shimPeerConnection,
  4632. shimGetUserMedia: __webpack_require__(19)
  4633. };
  4634.  
  4635.  
  4636. /***/ }),
  4637. /* 19 */
  4638. /***/ (function(module, exports, __webpack_require__) {
  4639.  
  4640. "use strict";
  4641. /*
  4642. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4643. *
  4644. * Use of this source code is governed by a BSD-style license
  4645. * that can be found in the LICENSE file in the root of the source
  4646. * tree.
  4647. */
  4648. /* eslint-env node */
  4649.  
  4650.  
  4651. var utils = __webpack_require__(0);
  4652. var logging = utils.log;
  4653.  
  4654. // Expose public methods.
  4655. module.exports = function(window) {
  4656. var browserDetails = utils.detectBrowser(window);
  4657. var navigator = window && window.navigator;
  4658. var MediaStreamTrack = window && window.MediaStreamTrack;
  4659.  
  4660. var shimError_ = function(e) {
  4661. return {
  4662. name: {
  4663. InternalError: 'NotReadableError',
  4664. NotSupportedError: 'TypeError',
  4665. PermissionDeniedError: 'NotAllowedError',
  4666. SecurityError: 'NotAllowedError'
  4667. }[e.name] || e.name,
  4668. message: {
  4669. 'The operation is insecure.': 'The request is not allowed by the ' +
  4670. 'user agent or the platform in the current context.'
  4671. }[e.message] || e.message,
  4672. constraint: e.constraint,
  4673. toString: function() {
  4674. return this.name + (this.message && ': ') + this.message;
  4675. }
  4676. };
  4677. };
  4678.  
  4679. // getUserMedia constraints shim.
  4680. var getUserMedia_ = function(constraints, onSuccess, onError) {
  4681. var constraintsToFF37_ = function(c) {
  4682. if (typeof c !== 'object' || c.require) {
  4683. return c;
  4684. }
  4685. var require = [];
  4686. Object.keys(c).forEach(function(key) {
  4687. if (key === 'require' || key === 'advanced' || key === 'mediaSource') {
  4688. return;
  4689. }
  4690. var r = c[key] = (typeof c[key] === 'object') ?
  4691. c[key] : {ideal: c[key]};
  4692. if (r.min !== undefined ||
  4693. r.max !== undefined || r.exact !== undefined) {
  4694. require.push(key);
  4695. }
  4696. if (r.exact !== undefined) {
  4697. if (typeof r.exact === 'number') {
  4698. r. min = r.max = r.exact;
  4699. } else {
  4700. c[key] = r.exact;
  4701. }
  4702. delete r.exact;
  4703. }
  4704. if (r.ideal !== undefined) {
  4705. c.advanced = c.advanced || [];
  4706. var oc = {};
  4707. if (typeof r.ideal === 'number') {
  4708. oc[key] = {min: r.ideal, max: r.ideal};
  4709. } else {
  4710. oc[key] = r.ideal;
  4711. }
  4712. c.advanced.push(oc);
  4713. delete r.ideal;
  4714. if (!Object.keys(r).length) {
  4715. delete c[key];
  4716. }
  4717. }
  4718. });
  4719. if (require.length) {
  4720. c.require = require;
  4721. }
  4722. return c;
  4723. };
  4724. constraints = JSON.parse(JSON.stringify(constraints));
  4725. if (browserDetails.version < 38) {
  4726. logging('spec: ' + JSON.stringify(constraints));
  4727. if (constraints.audio) {
  4728. constraints.audio = constraintsToFF37_(constraints.audio);
  4729. }
  4730. if (constraints.video) {
  4731. constraints.video = constraintsToFF37_(constraints.video);
  4732. }
  4733. logging('ff37: ' + JSON.stringify(constraints));
  4734. }
  4735. return navigator.mozGetUserMedia(constraints, onSuccess, function(e) {
  4736. onError(shimError_(e));
  4737. });
  4738. };
  4739.  
  4740. // Returns the result of getUserMedia as a Promise.
  4741. var getUserMediaPromise_ = function(constraints) {
  4742. return new Promise(function(resolve, reject) {
  4743. getUserMedia_(constraints, resolve, reject);
  4744. });
  4745. };
  4746.  
  4747. // Shim for mediaDevices on older versions.
  4748. if (!navigator.mediaDevices) {
  4749. navigator.mediaDevices = {getUserMedia: getUserMediaPromise_,
  4750. addEventListener: function() { },
  4751. removeEventListener: function() { }
  4752. };
  4753. }
  4754. navigator.mediaDevices.enumerateDevices =
  4755. navigator.mediaDevices.enumerateDevices || function() {
  4756. return new Promise(function(resolve) {
  4757. var infos = [
  4758. {kind: 'audioinput', deviceId: 'default', label: '', groupId: ''},
  4759. {kind: 'videoinput', deviceId: 'default', label: '', groupId: ''}
  4760. ];
  4761. resolve(infos);
  4762. });
  4763. };
  4764.  
  4765. if (browserDetails.version < 41) {
  4766. // Work around http://bugzil.la/1169665
  4767. var orgEnumerateDevices =
  4768. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices);
  4769. navigator.mediaDevices.enumerateDevices = function() {
  4770. return orgEnumerateDevices().then(undefined, function(e) {
  4771. if (e.name === 'NotFoundError') {
  4772. return [];
  4773. }
  4774. throw e;
  4775. });
  4776. };
  4777. }
  4778. if (browserDetails.version < 49) {
  4779. var origGetUserMedia = navigator.mediaDevices.getUserMedia.
  4780. bind(navigator.mediaDevices);
  4781. navigator.mediaDevices.getUserMedia = function(c) {
  4782. return origGetUserMedia(c).then(function(stream) {
  4783. // Work around https://bugzil.la/802326
  4784. if (c.audio && !stream.getAudioTracks().length ||
  4785. c.video && !stream.getVideoTracks().length) {
  4786. stream.getTracks().forEach(function(track) {
  4787. track.stop();
  4788. });
  4789. throw new DOMException('The object can not be found here.',
  4790. 'NotFoundError');
  4791. }
  4792. return stream;
  4793. }, function(e) {
  4794. return Promise.reject(shimError_(e));
  4795. });
  4796. };
  4797. }
  4798. if (!(browserDetails.version > 55 &&
  4799. 'autoGainControl' in navigator.mediaDevices.getSupportedConstraints())) {
  4800. var remap = function(obj, a, b) {
  4801. if (a in obj && !(b in obj)) {
  4802. obj[b] = obj[a];
  4803. delete obj[a];
  4804. }
  4805. };
  4806.  
  4807. var nativeGetUserMedia = navigator.mediaDevices.getUserMedia.
  4808. bind(navigator.mediaDevices);
  4809. navigator.mediaDevices.getUserMedia = function(c) {
  4810. if (typeof c === 'object' && typeof c.audio === 'object') {
  4811. c = JSON.parse(JSON.stringify(c));
  4812. remap(c.audio, 'autoGainControl', 'mozAutoGainControl');
  4813. remap(c.audio, 'noiseSuppression', 'mozNoiseSuppression');
  4814. }
  4815. return nativeGetUserMedia(c);
  4816. };
  4817.  
  4818. if (MediaStreamTrack && MediaStreamTrack.prototype.getSettings) {
  4819. var nativeGetSettings = MediaStreamTrack.prototype.getSettings;
  4820. MediaStreamTrack.prototype.getSettings = function() {
  4821. var obj = nativeGetSettings.apply(this, arguments);
  4822. remap(obj, 'mozAutoGainControl', 'autoGainControl');
  4823. remap(obj, 'mozNoiseSuppression', 'noiseSuppression');
  4824. return obj;
  4825. };
  4826. }
  4827.  
  4828. if (MediaStreamTrack && MediaStreamTrack.prototype.applyConstraints) {
  4829. var nativeApplyConstraints = MediaStreamTrack.prototype.applyConstraints;
  4830. MediaStreamTrack.prototype.applyConstraints = function(c) {
  4831. if (this.kind === 'audio' && typeof c === 'object') {
  4832. c = JSON.parse(JSON.stringify(c));
  4833. remap(c, 'autoGainControl', 'mozAutoGainControl');
  4834. remap(c, 'noiseSuppression', 'mozNoiseSuppression');
  4835. }
  4836. return nativeApplyConstraints.apply(this, [c]);
  4837. };
  4838. }
  4839. }
  4840. navigator.getUserMedia = function(constraints, onSuccess, onError) {
  4841. if (browserDetails.version < 44) {
  4842. return getUserMedia_(constraints, onSuccess, onError);
  4843. }
  4844. // Replace Firefox 44+'s deprecation warning with unprefixed version.
  4845. console.warn('navigator.getUserMedia has been replaced by ' +
  4846. 'navigator.mediaDevices.getUserMedia');
  4847. navigator.mediaDevices.getUserMedia(constraints).then(onSuccess, onError);
  4848. };
  4849. };
  4850.  
  4851.  
  4852. /***/ }),
  4853. /* 20 */
  4854. /***/ (function(module, exports, __webpack_require__) {
  4855.  
  4856. "use strict";
  4857. /*
  4858. * Copyright (c) 2016 The WebRTC project authors. All Rights Reserved.
  4859. *
  4860. * Use of this source code is governed by a BSD-style license
  4861. * that can be found in the LICENSE file in the root of the source
  4862. * tree.
  4863. */
  4864.  
  4865. var utils = __webpack_require__(0);
  4866.  
  4867. var safariShim = {
  4868. // TODO: DrAlex, should be here, double check against LayoutTests
  4869.  
  4870. // TODO: once the back-end for the mac port is done, add.
  4871. // TODO: check for webkitGTK+
  4872. // shimPeerConnection: function() { },
  4873.  
  4874. shimLocalStreamsAPI: function(window) {
  4875. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4876. return;
  4877. }
  4878. if (!('getLocalStreams' in window.RTCPeerConnection.prototype)) {
  4879. window.RTCPeerConnection.prototype.getLocalStreams = function() {
  4880. if (!this._localStreams) {
  4881. this._localStreams = [];
  4882. }
  4883. return this._localStreams;
  4884. };
  4885. }
  4886. if (!('getStreamById' in window.RTCPeerConnection.prototype)) {
  4887. window.RTCPeerConnection.prototype.getStreamById = function(id) {
  4888. var result = null;
  4889. if (this._localStreams) {
  4890. this._localStreams.forEach(function(stream) {
  4891. if (stream.id === id) {
  4892. result = stream;
  4893. }
  4894. });
  4895. }
  4896. if (this._remoteStreams) {
  4897. this._remoteStreams.forEach(function(stream) {
  4898. if (stream.id === id) {
  4899. result = stream;
  4900. }
  4901. });
  4902. }
  4903. return result;
  4904. };
  4905. }
  4906. if (!('addStream' in window.RTCPeerConnection.prototype)) {
  4907. var _addTrack = window.RTCPeerConnection.prototype.addTrack;
  4908. window.RTCPeerConnection.prototype.addStream = function(stream) {
  4909. if (!this._localStreams) {
  4910. this._localStreams = [];
  4911. }
  4912. if (this._localStreams.indexOf(stream) === -1) {
  4913. this._localStreams.push(stream);
  4914. }
  4915. var self = this;
  4916. stream.getTracks().forEach(function(track) {
  4917. _addTrack.call(self, track, stream);
  4918. });
  4919. };
  4920.  
  4921. window.RTCPeerConnection.prototype.addTrack = function(track, stream) {
  4922. if (stream) {
  4923. if (!this._localStreams) {
  4924. this._localStreams = [stream];
  4925. } else if (this._localStreams.indexOf(stream) === -1) {
  4926. this._localStreams.push(stream);
  4927. }
  4928. }
  4929. _addTrack.call(this, track, stream);
  4930. };
  4931. }
  4932. if (!('removeStream' in window.RTCPeerConnection.prototype)) {
  4933. window.RTCPeerConnection.prototype.removeStream = function(stream) {
  4934. if (!this._localStreams) {
  4935. this._localStreams = [];
  4936. }
  4937. var index = this._localStreams.indexOf(stream);
  4938. if (index === -1) {
  4939. return;
  4940. }
  4941. this._localStreams.splice(index, 1);
  4942. var self = this;
  4943. var tracks = stream.getTracks();
  4944. this.getSenders().forEach(function(sender) {
  4945. if (tracks.indexOf(sender.track) !== -1) {
  4946. self.removeTrack(sender);
  4947. }
  4948. });
  4949. };
  4950. }
  4951. },
  4952. shimRemoteStreamsAPI: function(window) {
  4953. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4954. return;
  4955. }
  4956. if (!('getRemoteStreams' in window.RTCPeerConnection.prototype)) {
  4957. window.RTCPeerConnection.prototype.getRemoteStreams = function() {
  4958. return this._remoteStreams ? this._remoteStreams : [];
  4959. };
  4960. }
  4961. if (!('onaddstream' in window.RTCPeerConnection.prototype)) {
  4962. Object.defineProperty(window.RTCPeerConnection.prototype, 'onaddstream', {
  4963. get: function() {
  4964. return this._onaddstream;
  4965. },
  4966. set: function(f) {
  4967. if (this._onaddstream) {
  4968. this.removeEventListener('addstream', this._onaddstream);
  4969. this.removeEventListener('track', this._onaddstreampoly);
  4970. }
  4971. this.addEventListener('addstream', this._onaddstream = f);
  4972. this.addEventListener('track', this._onaddstreampoly = function(e) {
  4973. var stream = e.streams[0];
  4974. if (!this._remoteStreams) {
  4975. this._remoteStreams = [];
  4976. }
  4977. if (this._remoteStreams.indexOf(stream) >= 0) {
  4978. return;
  4979. }
  4980. this._remoteStreams.push(stream);
  4981. var event = new Event('addstream');
  4982. event.stream = e.streams[0];
  4983. this.dispatchEvent(event);
  4984. }.bind(this));
  4985. }
  4986. });
  4987. }
  4988. },
  4989. shimCallbacksAPI: function(window) {
  4990. if (typeof window !== 'object' || !window.RTCPeerConnection) {
  4991. return;
  4992. }
  4993. var prototype = window.RTCPeerConnection.prototype;
  4994. var createOffer = prototype.createOffer;
  4995. var createAnswer = prototype.createAnswer;
  4996. var setLocalDescription = prototype.setLocalDescription;
  4997. var setRemoteDescription = prototype.setRemoteDescription;
  4998. var addIceCandidate = prototype.addIceCandidate;
  4999.  
  5000. prototype.createOffer = function(successCallback, failureCallback) {
  5001. var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  5002. var promise = createOffer.apply(this, [options]);
  5003. if (!failureCallback) {
  5004. return promise;
  5005. }
  5006. promise.then(successCallback, failureCallback);
  5007. return Promise.resolve();
  5008. };
  5009.  
  5010. prototype.createAnswer = function(successCallback, failureCallback) {
  5011. var options = (arguments.length >= 2) ? arguments[2] : arguments[0];
  5012. var promise = createAnswer.apply(this, [options]);
  5013. if (!failureCallback) {
  5014. return promise;
  5015. }
  5016. promise.then(successCallback, failureCallback);
  5017. return Promise.resolve();
  5018. };
  5019.  
  5020. var withCallback = function(description, successCallback, failureCallback) {
  5021. var promise = setLocalDescription.apply(this, [description]);
  5022. if (!failureCallback) {
  5023. return promise;
  5024. }
  5025. promise.then(successCallback, failureCallback);
  5026. return Promise.resolve();
  5027. };
  5028. prototype.setLocalDescription = withCallback;
  5029.  
  5030. withCallback = function(description, successCallback, failureCallback) {
  5031. var promise = setRemoteDescription.apply(this, [description]);
  5032. if (!failureCallback) {
  5033. return promise;
  5034. }
  5035. promise.then(successCallback, failureCallback);
  5036. return Promise.resolve();
  5037. };
  5038. prototype.setRemoteDescription = withCallback;
  5039.  
  5040. withCallback = function(candidate, successCallback, failureCallback) {
  5041. var promise = addIceCandidate.apply(this, [candidate]);
  5042. if (!failureCallback) {
  5043. return promise;
  5044. }
  5045. promise.then(successCallback, failureCallback);
  5046. return Promise.resolve();
  5047. };
  5048. prototype.addIceCandidate = withCallback;
  5049. },
  5050. shimGetUserMedia: function(window) {
  5051. var navigator = window && window.navigator;
  5052.  
  5053. if (!navigator.getUserMedia) {
  5054. if (navigator.webkitGetUserMedia) {
  5055. navigator.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  5056. } else if (navigator.mediaDevices &&
  5057. navigator.mediaDevices.getUserMedia) {
  5058. navigator.getUserMedia = function(constraints, cb, errcb) {
  5059. navigator.mediaDevices.getUserMedia(constraints)
  5060. .then(cb, errcb);
  5061. }.bind(navigator);
  5062. }
  5063. }
  5064. },
  5065. shimRTCIceServerUrls: function(window) {
  5066. // migrate from non-spec RTCIceServer.url to RTCIceServer.urls
  5067. var OrigPeerConnection = window.RTCPeerConnection;
  5068. window.RTCPeerConnection = function(pcConfig, pcConstraints) {
  5069. if (pcConfig && pcConfig.iceServers) {
  5070. var newIceServers = [];
  5071. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  5072. var server = pcConfig.iceServers[i];
  5073. if (!server.hasOwnProperty('urls') &&
  5074. server.hasOwnProperty('url')) {
  5075. utils.deprecated('RTCIceServer.url', 'RTCIceServer.urls');
  5076. server = JSON.parse(JSON.stringify(server));
  5077. server.urls = server.url;
  5078. delete server.url;
  5079. newIceServers.push(server);
  5080. } else {
  5081. newIceServers.push(pcConfig.iceServers[i]);
  5082. }
  5083. }
  5084. pcConfig.iceServers = newIceServers;
  5085. }
  5086. return new OrigPeerConnection(pcConfig, pcConstraints);
  5087. };
  5088. window.RTCPeerConnection.prototype = OrigPeerConnection.prototype;
  5089. // wrap static methods. Currently just generateCertificate.
  5090. Object.defineProperty(window.RTCPeerConnection, 'generateCertificate', {
  5091. get: function() {
  5092. return OrigPeerConnection.generateCertificate;
  5093. }
  5094. });
  5095. }
  5096. };
  5097.  
  5098. // Expose public methods.
  5099. module.exports = {
  5100. shimCallbacksAPI: safariShim.shimCallbacksAPI,
  5101. shimLocalStreamsAPI: safariShim.shimLocalStreamsAPI,
  5102. shimRemoteStreamsAPI: safariShim.shimRemoteStreamsAPI,
  5103. shimGetUserMedia: safariShim.shimGetUserMedia,
  5104. shimRTCIceServerUrls: safariShim.shimRTCIceServerUrls
  5105. // TODO
  5106. // shimPeerConnection: safariShim.shimPeerConnection
  5107. };
  5108.  
  5109.  
  5110. /***/ }),
  5111. /* 21 */
  5112. /***/ (function(module, exports, __webpack_require__) {
  5113.  
  5114. var require;var require;(function(f){if(true){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.default = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
  5115. "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var _require=_dereq_("./spec/reference-implementation/lib/readable-stream"),ReadableStream=_require.ReadableStream,_require2=_dereq_("./spec/reference-implementation/lib/writable-stream"),WritableStream=_require2.WritableStream,ByteLengthQueuingStrategy=_dereq_("./spec/reference-implementation/lib/byte-length-queuing-strategy"),CountQueuingStrategy=_dereq_("./spec/reference-implementation/lib/count-queuing-strategy"),TransformStream=_dereq_("./spec/reference-implementation/lib/transform-stream").TransformStream;exports.ByteLengthQueuingStrategy=ByteLengthQueuingStrategy,exports.CountQueuingStrategy=CountQueuingStrategy,exports.TransformStream=TransformStream,exports.ReadableStream=ReadableStream,exports.WritableStream=WritableStream;var interfaces={ReadableStream:ReadableStream,WritableStream:WritableStream,ByteLengthQueuingStrategy:ByteLengthQueuingStrategy,CountQueuingStrategy:CountQueuingStrategy,TransformStream:TransformStream};exports.default=interfaces,"undefined"!=typeof window&&Object.assign(window,interfaces);
  5116.  
  5117. },{"./spec/reference-implementation/lib/byte-length-queuing-strategy":3,"./spec/reference-implementation/lib/count-queuing-strategy":4,"./spec/reference-implementation/lib/readable-stream":7,"./spec/reference-implementation/lib/transform-stream":8,"./spec/reference-implementation/lib/writable-stream":9}],2:[function(_dereq_,module,exports){
  5118.  
  5119. },{}],3:[function(_dereq_,module,exports){
  5120. "use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function e(e,r){for(var t=0;t<r.length;t++){var a=r[t];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(r,t,a){return t&&e(r.prototype,t),a&&e(r,a),r}}(),_require=_dereq_("./helpers.js"),createDataProperty=_require.createDataProperty;module.exports=function(){function e(r){var t=r.highWaterMark;_classCallCheck(this,e),createDataProperty(this,"highWaterMark",t)}return _createClass(e,[{key:"size",value:function(e){return e.byteLength}}]),e}();
  5121.  
  5122. },{"./helpers.js":5}],4:[function(_dereq_,module,exports){
  5123. "use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}var _createClass=function(){function e(e,r){for(var t=0;t<r.length;t++){var a=r[t];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(r,t,a){return t&&e(r.prototype,t),a&&e(r,a),r}}(),_require=_dereq_("./helpers.js"),createDataProperty=_require.createDataProperty;module.exports=function(){function e(r){var t=r.highWaterMark;_classCallCheck(this,e),createDataProperty(this,"highWaterMark",t)}return _createClass(e,[{key:"size",value:function(){return 1}}]),e}();
  5124.  
  5125. },{"./helpers.js":5}],5:[function(_dereq_,module,exports){
  5126. "use strict";function _toConsumableArray(e){if(Array.isArray(e)){for(var r=0,t=Array(e.length);r<e.length;r++)t[r]=e[r];return t}return Array.from(e)}function IsPropertyKey(e){return"string"==typeof e||"symbol"===("undefined"==typeof e?"undefined":_typeof(e))}function Call(e,r,t){if("function"!=typeof e)throw new TypeError("Argument is not a function");return Function.prototype.apply.call(e,r,t)}var _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};exports.typeIsObject=function(e){return"object"===("undefined"==typeof e?"undefined":_typeof(e))&&null!==e||"function"==typeof e},exports.createDataProperty=function(e,r,t){Object.defineProperty(e,r,{value:t,writable:!0,enumerable:!0,configurable:!0})},exports.createArrayFromList=function(e){return e.slice()},exports.ArrayBufferCopy=function(e,r,t,o,n){new Uint8Array(e).set(new Uint8Array(t,o,n),r)},exports.CreateIterResultObject=function(e,r){var t={};return Object.defineProperty(t,"value",{value:e,enumerable:!0,writable:!0,configurable:!0}),Object.defineProperty(t,"done",{value:r,enumerable:!0,writable:!0,configurable:!0}),t},exports.IsFiniteNonNegativeNumber=function(e){return!Number.isNaN(e)&&(e!==1/0&&!(e<0))},exports.InvokeOrNoop=function(e,r,t){var o=e[r];if(void 0!==o)return Call(o,e,t)},exports.PromiseInvokeOrNoop=function(e,r,t){try{return Promise.resolve(exports.InvokeOrNoop(e,r,t))}catch(e){return Promise.reject(e)}},exports.PromiseInvokeOrPerformFallback=function(e,r,t,o,n){var i=void 0;try{i=e[r]}catch(e){return Promise.reject(e)}if(void 0===i)return o.apply(void 0,_toConsumableArray(n));try{return Promise.resolve(Call(i,e,t))}catch(e){return Promise.reject(e)}},exports.PromiseInvokeOrFallbackOrNoop=function(e,r,t,o,n){return exports.PromiseInvokeOrPerformFallback(e,r,t,exports.PromiseInvokeOrNoop,[e,o,n])},exports.SameRealmTransfer=function(e){return e},exports.ValidateAndNormalizeHighWaterMark=function(e){if(e=Number(e),Number.isNaN(e)||e<0)throw new RangeError("highWaterMark property of a queuing strategy must be non-negative and non-NaN");return e},exports.ValidateAndNormalizeQueuingStrategy=function(e,r){if(void 0!==e&&"function"!=typeof e)throw new TypeError("size property of a queuing strategy must be a function");return r=exports.ValidateAndNormalizeHighWaterMark(r),{size:e,highWaterMark:r}};
  5127.  
  5128. },{}],6:[function(_dereq_,module,exports){
  5129. "use strict";var _require=_dereq_("./helpers.js"),IsFiniteNonNegativeNumber=_require.IsFiniteNonNegativeNumber;exports.DequeueValue=function(e){var t=e.shift();return e._totalSize-=t.size,t.value},exports.EnqueueValueWithSize=function(e,t,i){if(i=Number(i),!IsFiniteNonNegativeNumber(i))throw new RangeError("Size must be a finite, non-NaN, non-negative number.");e.push({value:t,size:i}),void 0===e._totalSize&&(e._totalSize=0),e._totalSize+=i},exports.GetTotalQueueSize=function(e){return void 0===e._totalSize&&(e._totalSize=0),e._totalSize},exports.PeekQueueValue=function(e){var t=e[0];return t.value};
  5130.  
  5131. },{"./helpers.js":5}],7:[function(_dereq_,module,exports){
  5132. "use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function AcquireReadableStreamBYOBReader(e){return new ReadableStreamBYOBReader(e)}function AcquireReadableStreamDefaultReader(e){return new ReadableStreamDefaultReader(e)}function IsReadableStream(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readableStreamController")}function IsReadableStreamDisturbed(e){return e._disturbed}function IsReadableStreamLocked(e){return void 0!==e._reader}function ReadableStreamTee(e,r){var t=AcquireReadableStreamDefaultReader(e),a={closedOrErrored:!1,canceled1:!1,canceled2:!1,reason1:void 0,reason2:void 0};a.promise=new Promise(function(e){a._resolve=e});var l=create_ReadableStreamTeePullFunction();l._reader=t,l._teeState=a,l._cloneForBranch2=r;var o=create_ReadableStreamTeeBranch1CancelFunction();o._stream=e,o._teeState=a;var n=create_ReadableStreamTeeBranch2CancelFunction();n._stream=e,n._teeState=a;var i=Object.create(Object.prototype);createDataProperty(i,"pull",l),createDataProperty(i,"cancel",o);var d=new ReadableStream(i),s=Object.create(Object.prototype);createDataProperty(s,"pull",l),createDataProperty(s,"cancel",n);var u=new ReadableStream(s);return l._branch1=d._readableStreamController,l._branch2=u._readableStreamController,t._closedPromise.catch(function(e){a.closedOrErrored!==!0&&(ReadableStreamDefaultControllerError(l._branch1,e),ReadableStreamDefaultControllerError(l._branch2,e),a.closedOrErrored=!0)}),[d,u]}function create_ReadableStreamTeePullFunction(){function e(){var r=e._reader,t=e._branch1,a=e._branch2,l=e._teeState;return ReadableStreamDefaultReaderRead(r).then(function(e){var r=e.value,o=e.done;if(o===!0&&l.closedOrErrored===!1&&(l.canceled1===!1&&ReadableStreamDefaultControllerClose(t),l.canceled2===!1&&ReadableStreamDefaultControllerClose(a),l.closedOrErrored=!0),l.closedOrErrored!==!0){var n=r,i=r;l.canceled1===!1&&ReadableStreamDefaultControllerEnqueue(t,n),l.canceled2===!1&&ReadableStreamDefaultControllerEnqueue(a,i)}})}return e}function create_ReadableStreamTeeBranch1CancelFunction(){function e(r){var t=e._stream,a=e._teeState;if(a.canceled1=!0,a.reason1=r,a.canceled2===!0){var l=createArrayFromList([a.reason1,a.reason2]),o=ReadableStreamCancel(t,l);a._resolve(o)}return a.promise}return e}function create_ReadableStreamTeeBranch2CancelFunction(){function e(r){var t=e._stream,a=e._teeState;if(a.canceled2=!0,a.reason2=r,a.canceled1===!0){var l=createArrayFromList([a.reason1,a.reason2]),o=ReadableStreamCancel(t,l);a._resolve(o)}return a.promise}return e}function ReadableStreamAddReadIntoRequest(e){var r=new Promise(function(r,t){var a={_resolve:r,_reject:t};e._reader._readIntoRequests.push(a)});return r}function ReadableStreamAddReadRequest(e){var r=new Promise(function(r,t){var a={_resolve:r,_reject:t};e._reader._readRequests.push(a)});return r}function ReadableStreamCancel(e,r){if(e._disturbed=!0,"closed"===e._state)return Promise.resolve(void 0);if("errored"===e._state)return Promise.reject(e._storedError);ReadableStreamClose(e);var t=e._readableStreamController[InternalCancel](r);return t.then(function(){})}function ReadableStreamClose(e){e._state="closed";var r=e._reader;if(void 0!==r){if(IsReadableStreamDefaultReader(r)===!0){var t=!0,a=!1,l=void 0;try{for(var o,n=r._readRequests[Symbol.iterator]();!(t=(o=n.next()).done);t=!0){var i=o.value._resolve;i(CreateIterResultObject(void 0,!0))}}catch(e){a=!0,l=e}finally{try{!t&&n.return&&n.return()}finally{if(a)throw l}}r._readRequests=[]}defaultReaderClosedPromiseResolve(r)}}function ReadableStreamError(e,r){e._state="errored",e._storedError=r;var t=e._reader;if(void 0!==t){if(IsReadableStreamDefaultReader(t)===!0){var a=!0,l=!1,o=void 0;try{for(var n,i=t._readRequests[Symbol.iterator]();!(a=(n=i.next()).done);a=!0){var d=n.value;d._reject(r)}}catch(e){l=!0,o=e}finally{try{!a&&i.return&&i.return()}finally{if(l)throw o}}t._readRequests=[]}else{var s=!0,u=!1,c=void 0;try{for(var b,R=t._readIntoRequests[Symbol.iterator]();!(s=(b=R.next()).done);s=!0){var m=b.value;m._reject(r)}}catch(e){u=!0,c=e}finally{try{!s&&R.return&&R.return()}finally{if(u)throw c}}t._readIntoRequests=[]}defaultReaderClosedPromiseReject(t,r),t._closedPromise.catch(function(){})}}function ReadableStreamFulfillReadIntoRequest(e,r,t){var a=e._reader,l=a._readIntoRequests.shift();l._resolve(CreateIterResultObject(r,t))}function ReadableStreamFulfillReadRequest(e,r,t){var a=e._reader,l=a._readRequests.shift();l._resolve(CreateIterResultObject(r,t))}function ReadableStreamGetNumReadIntoRequests(e){return e._reader._readIntoRequests.length}function ReadableStreamGetNumReadRequests(e){return e._reader._readRequests.length}function ReadableStreamHasBYOBReader(e){var r=e._reader;return void 0!==r&&IsReadableStreamBYOBReader(r)!==!1}function ReadableStreamHasDefaultReader(e){var r=e._reader;return void 0!==r&&IsReadableStreamDefaultReader(r)!==!1}function IsReadableStreamBYOBReader(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readIntoRequests")}function IsReadableStreamDefaultReader(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_readRequests")}function ReadableStreamReaderGenericInitialize(e,r){e._ownerReadableStream=r,r._reader=e,"readable"===r._state?defaultReaderClosedPromiseInitialize(e):"closed"===r._state?defaultReaderClosedPromiseInitializeAsResolved(e):(defaultReaderClosedPromiseInitializeAsRejected(e,r._storedError),e._closedPromise.catch(function(){}))}function ReadableStreamReaderGenericCancel(e,r){var t=e._ownerReadableStream;return ReadableStreamCancel(t,r)}function ReadableStreamReaderGenericRelease(e){"readable"===e._ownerReadableStream._state?defaultReaderClosedPromiseReject(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")):defaultReaderClosedPromiseResetToRejected(e,new TypeError("Reader was released and can no longer be used to monitor the stream's closedness")),e._closedPromise.catch(function(){}),e._ownerReadableStream._reader=void 0,e._ownerReadableStream=void 0}function ReadableStreamBYOBReaderRead(e,r){var t=e._ownerReadableStream;return t._disturbed=!0,"errored"===t._state?Promise.reject(t._storedError):ReadableByteStreamControllerPullInto(t._readableStreamController,r)}function ReadableStreamDefaultReaderRead(e){var r=e._ownerReadableStream;return r._disturbed=!0,"closed"===r._state?Promise.resolve(CreateIterResultObject(void 0,!0)):"errored"===r._state?Promise.reject(r._storedError):r._readableStreamController[InternalPull]()}function IsReadableStreamDefaultController(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_underlyingSource")}function ReadableStreamDefaultControllerCallPullIfNeeded(e){var r=ReadableStreamDefaultControllerShouldCallPull(e);if(r!==!1){if(e._pulling===!0)return void(e._pullAgain=!0);e._pulling=!0;var t=PromiseInvokeOrNoop(e._underlyingSource,"pull",[e]);t.then(function(){if(e._pulling=!1,e._pullAgain===!0)return e._pullAgain=!1,ReadableStreamDefaultControllerCallPullIfNeeded(e)},function(r){ReadableStreamDefaultControllerErrorIfNeeded(e,r)}).catch(rethrowAssertionErrorRejection)}}function ReadableStreamDefaultControllerShouldCallPull(e){var r=e._controlledReadableStream;if("closed"===r._state||"errored"===r._state)return!1;if(e._closeRequested===!0)return!1;if(e._started===!1)return!1;if(IsReadableStreamLocked(r)===!0&&ReadableStreamGetNumReadRequests(r)>0)return!0;var t=ReadableStreamDefaultControllerGetDesiredSize(e);return t>0}function ReadableStreamDefaultControllerClose(e){var r=e._controlledReadableStream;e._closeRequested=!0,0===e._queue.length&&ReadableStreamClose(r)}function ReadableStreamDefaultControllerEnqueue(e,r){var t=e._controlledReadableStream;if(IsReadableStreamLocked(t)===!0&&ReadableStreamGetNumReadRequests(t)>0)ReadableStreamFulfillReadRequest(t,r,!1);else{var a=1;if(void 0!==e._strategySize)try{a=e._strategySize(r)}catch(r){throw ReadableStreamDefaultControllerErrorIfNeeded(e,r),r}try{EnqueueValueWithSize(e._queue,r,a)}catch(r){throw ReadableStreamDefaultControllerErrorIfNeeded(e,r),r}}ReadableStreamDefaultControllerCallPullIfNeeded(e)}function ReadableStreamDefaultControllerError(e,r){var t=e._controlledReadableStream;e._queue=[],ReadableStreamError(t,r)}function ReadableStreamDefaultControllerErrorIfNeeded(e,r){"readable"===e._controlledReadableStream._state&&ReadableStreamDefaultControllerError(e,r)}function ReadableStreamDefaultControllerGetDesiredSize(e){var r=GetTotalQueueSize(e._queue);return e._strategyHWM-r}function IsReadableByteStreamController(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_underlyingByteSource")}function IsReadableStreamBYOBRequest(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_associatedReadableByteStreamController")}function ReadableByteStreamControllerCallPullIfNeeded(e){var r=ReadableByteStreamControllerShouldCallPull(e);if(r!==!1){if(e._pulling===!0)return void(e._pullAgain=!0);e._pulling=!0;var t=PromiseInvokeOrNoop(e._underlyingByteSource,"pull",[e]);t.then(function(){e._pulling=!1,e._pullAgain===!0&&(e._pullAgain=!1,ReadableByteStreamControllerCallPullIfNeeded(e))},function(r){"readable"===e._controlledReadableStream._state&&ReadableByteStreamControllerError(e,r)}).catch(rethrowAssertionErrorRejection)}}function ReadableByteStreamControllerClearPendingPullIntos(e){ReadableByteStreamControllerInvalidateBYOBRequest(e),e._pendingPullIntos=[]}function ReadableByteStreamControllerCommitPullIntoDescriptor(e,r){var t=!1;"closed"===e._state&&(t=!0);var a=ReadableByteStreamControllerConvertPullIntoDescriptor(r);"default"===r.readerType?ReadableStreamFulfillReadRequest(e,a,t):ReadableStreamFulfillReadIntoRequest(e,a,t)}function ReadableByteStreamControllerConvertPullIntoDescriptor(e){var r=e.bytesFilled,t=e.elementSize;return new e.ctor(e.buffer,e.byteOffset,r/t)}function ReadableByteStreamControllerEnqueueChunkToQueue(e,r,t,a){e._queue.push({buffer:r,byteOffset:t,byteLength:a}),e._totalQueuedBytes+=a}function ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(e,r){var t=r.elementSize,a=r.bytesFilled-r.bytesFilled%t,l=Math.min(e._totalQueuedBytes,r.byteLength-r.bytesFilled),o=r.bytesFilled+l,n=o-o%t,i=l,d=!1;n>a&&(i=n-r.bytesFilled,d=!0);for(var s=e._queue;i>0;){var u=s[0],c=Math.min(i,u.byteLength),b=r.byteOffset+r.bytesFilled;ArrayBufferCopy(r.buffer,b,u.buffer,u.byteOffset,c),u.byteLength===c?s.shift():(u.byteOffset+=c,u.byteLength-=c),e._totalQueuedBytes-=c,ReadableByteStreamControllerFillHeadPullIntoDescriptor(e,c,r),i-=c}return d}function ReadableByteStreamControllerFillHeadPullIntoDescriptor(e,r,t){ReadableByteStreamControllerInvalidateBYOBRequest(e),t.bytesFilled+=r}function ReadableByteStreamControllerHandleQueueDrain(e){0===e._totalQueuedBytes&&e._closeRequested===!0?ReadableStreamClose(e._controlledReadableStream):ReadableByteStreamControllerCallPullIfNeeded(e)}function ReadableByteStreamControllerInvalidateBYOBRequest(e){void 0!==e._byobRequest&&(e._byobRequest._associatedReadableByteStreamController=void 0,e._byobRequest._view=void 0,e._byobRequest=void 0)}function ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(e){for(;e._pendingPullIntos.length>0;){if(0===e._totalQueuedBytes)return;var r=e._pendingPullIntos[0];ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(e,r)===!0&&(ReadableByteStreamControllerShiftPendingPullInto(e),ReadableByteStreamControllerCommitPullIntoDescriptor(e._controlledReadableStream,r))}}function ReadableByteStreamControllerPullInto(e,r){var t=e._controlledReadableStream,a=1;r.constructor!==DataView&&(a=r.constructor.BYTES_PER_ELEMENT);var l=r.constructor,o={buffer:r.buffer,byteOffset:r.byteOffset,byteLength:r.byteLength,bytesFilled:0,elementSize:a,ctor:l,readerType:"byob"};if(e._pendingPullIntos.length>0)return o.buffer=SameRealmTransfer(o.buffer),e._pendingPullIntos.push(o),ReadableStreamAddReadIntoRequest(t);if("closed"===t._state){var n=new r.constructor(r.buffer,r.byteOffset,0);return Promise.resolve(CreateIterResultObject(n,!0))}if(e._totalQueuedBytes>0){if(ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(e,o)===!0){var i=ReadableByteStreamControllerConvertPullIntoDescriptor(o);return ReadableByteStreamControllerHandleQueueDrain(e),Promise.resolve(CreateIterResultObject(i,!1))}if(e._closeRequested===!0){var d=new TypeError("Insufficient bytes to fill elements in the given buffer");return ReadableByteStreamControllerError(e,d),Promise.reject(d)}}o.buffer=SameRealmTransfer(o.buffer),e._pendingPullIntos.push(o);var s=ReadableStreamAddReadIntoRequest(t);return ReadableByteStreamControllerCallPullIfNeeded(e),s}function ReadableByteStreamControllerRespondInClosedState(e,r){r.buffer=SameRealmTransfer(r.buffer);for(var t=e._controlledReadableStream;ReadableStreamGetNumReadIntoRequests(t)>0;){var a=ReadableByteStreamControllerShiftPendingPullInto(e);ReadableByteStreamControllerCommitPullIntoDescriptor(t,a)}}function ReadableByteStreamControllerRespondInReadableState(e,r,t){if(t.bytesFilled+r>t.byteLength)throw new RangeError("bytesWritten out of range");if(ReadableByteStreamControllerFillHeadPullIntoDescriptor(e,r,t),!(t.bytesFilled<t.elementSize)){ReadableByteStreamControllerShiftPendingPullInto(e);var a=t.bytesFilled%t.elementSize;if(a>0){var l=t.byteOffset+t.bytesFilled,o=t.buffer.slice(l-a,l);ReadableByteStreamControllerEnqueueChunkToQueue(e,o,0,o.byteLength)}t.buffer=SameRealmTransfer(t.buffer),t.bytesFilled-=a,ReadableByteStreamControllerCommitPullIntoDescriptor(e._controlledReadableStream,t),ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(e)}}function ReadableByteStreamControllerRespondInternal(e,r){var t=e._pendingPullIntos[0],a=e._controlledReadableStream;if("closed"===a._state){if(0!==r)throw new TypeError("bytesWritten must be 0 when calling respond() on a closed stream");ReadableByteStreamControllerRespondInClosedState(e,t)}else ReadableByteStreamControllerRespondInReadableState(e,r,t)}function ReadableByteStreamControllerShiftPendingPullInto(e){var r=e._pendingPullIntos.shift();return ReadableByteStreamControllerInvalidateBYOBRequest(e),r}function ReadableByteStreamControllerShouldCallPull(e){var r=e._controlledReadableStream;return"readable"===r._state&&(e._closeRequested!==!0&&(e._started!==!1&&(!!(ReadableStreamHasDefaultReader(r)&&ReadableStreamGetNumReadRequests(r)>0)||(!!(ReadableStreamHasBYOBReader(r)&&ReadableStreamGetNumReadIntoRequests(r)>0)||ReadableByteStreamControllerGetDesiredSize(e)>0))))}function ReadableByteStreamControllerClose(e){var r=e._controlledReadableStream;if(e._totalQueuedBytes>0)return void(e._closeRequested=!0);if(e._pendingPullIntos.length>0){var t=e._pendingPullIntos[0];if(t.bytesFilled>0){var a=new TypeError("Insufficient bytes to fill elements in the given buffer");throw ReadableByteStreamControllerError(e,a),a}}ReadableStreamClose(r)}function ReadableByteStreamControllerEnqueue(e,r){var t=e._controlledReadableStream,a=r.buffer,l=r.byteOffset,o=r.byteLength,n=SameRealmTransfer(a);if(ReadableStreamHasDefaultReader(t)===!0)if(0===ReadableStreamGetNumReadRequests(t))ReadableByteStreamControllerEnqueueChunkToQueue(e,n,l,o);else{var i=new Uint8Array(n,l,o);ReadableStreamFulfillReadRequest(t,i,!1)}else ReadableStreamHasBYOBReader(t)===!0?(ReadableByteStreamControllerEnqueueChunkToQueue(e,n,l,o),ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(e)):ReadableByteStreamControllerEnqueueChunkToQueue(e,n,l,o)}function ReadableByteStreamControllerError(e,r){var t=e._controlledReadableStream;ReadableByteStreamControllerClearPendingPullIntos(e),e._queue=[],ReadableStreamError(t,r)}function ReadableByteStreamControllerGetDesiredSize(e){return e._strategyHWM-e._totalQueuedBytes}function ReadableByteStreamControllerRespond(e,r){if(r=Number(r),IsFiniteNonNegativeNumber(r)===!1)throw new RangeError("bytesWritten must be a finite");ReadableByteStreamControllerRespondInternal(e,r)}function ReadableByteStreamControllerRespondWithNewView(e,r){var t=e._pendingPullIntos[0];if(t.byteOffset+t.bytesFilled!==r.byteOffset)throw new RangeError("The region specified by view does not match byobRequest");if(t.byteLength!==r.byteLength)throw new RangeError("The buffer of view has different capacity than byobRequest");t.buffer=r.buffer,ReadableByteStreamControllerRespondInternal(e,r.byteLength)}function streamBrandCheckException(e){return new TypeError("ReadableStream.prototype."+e+" can only be used on a ReadableStream")}function readerLockException(e){return new TypeError("Cannot "+e+" a stream using a released reader")}function defaultReaderBrandCheckException(e){return new TypeError("ReadableStreamDefaultReader.prototype."+e+" can only be used on a ReadableStreamDefaultReader")}function defaultReaderClosedPromiseInitialize(e){e._closedPromise=new Promise(function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t})}function defaultReaderClosedPromiseInitializeAsRejected(e,r){e._closedPromise=Promise.reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function defaultReaderClosedPromiseInitializeAsResolved(e){e._closedPromise=Promise.resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function defaultReaderClosedPromiseReject(e,r){e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function defaultReaderClosedPromiseResetToRejected(e,r){e._closedPromise=Promise.reject(r)}function defaultReaderClosedPromiseResolve(e){e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function byobReaderBrandCheckException(e){return new TypeError("ReadableStreamBYOBReader.prototype."+e+" can only be used on a ReadableStreamBYOBReader")}function defaultControllerBrandCheckException(e){return new TypeError("ReadableStreamDefaultController.prototype."+e+" can only be used on a ReadableStreamDefaultController")}function byobRequestBrandCheckException(e){return new TypeError("ReadableStreamBYOBRequest.prototype."+e+" can only be used on a ReadableStreamBYOBRequest")}function byteStreamControllerBrandCheckException(e){return new TypeError("ReadableByteStreamController.prototype."+e+" can only be used on a ReadableByteStreamController")}var _createClass=function(){function e(e,r){for(var t=0;t<r.length;t++){var a=r[t];a.enumerable=a.enumerable||!1,a.configurable=!0,"value"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(r,t,a){return t&&e(r.prototype,t),a&&e(r,a),r}}(),_require=_dereq_("./helpers.js"),ArrayBufferCopy=_require.ArrayBufferCopy,CreateIterResultObject=_require.CreateIterResultObject,IsFiniteNonNegativeNumber=_require.IsFiniteNonNegativeNumber,InvokeOrNoop=_require.InvokeOrNoop,PromiseInvokeOrNoop=_require.PromiseInvokeOrNoop,SameRealmTransfer=_require.SameRealmTransfer,ValidateAndNormalizeQueuingStrategy=_require.ValidateAndNormalizeQueuingStrategy,ValidateAndNormalizeHighWaterMark=_require.ValidateAndNormalizeHighWaterMark,_require2=_dereq_("./helpers.js"),createArrayFromList=_require2.createArrayFromList,createDataProperty=_require2.createDataProperty,typeIsObject=_require2.typeIsObject,_require3=_dereq_("./utils.js"),rethrowAssertionErrorRejection=_require3.rethrowAssertionErrorRejection,_require4=_dereq_("./queue-with-sizes.js"),DequeueValue=_require4.DequeueValue,EnqueueValueWithSize=_require4.EnqueueValueWithSize,GetTotalQueueSize=_require4.GetTotalQueueSize,_require5=_dereq_("./writable-stream.js"),AcquireWritableStreamDefaultWriter=_require5.AcquireWritableStreamDefaultWriter,IsWritableStream=_require5.IsWritableStream,IsWritableStreamLocked=_require5.IsWritableStreamLocked,WritableStreamAbort=_require5.WritableStreamAbort,WritableStreamDefaultWriterCloseWithErrorPropagation=_require5.WritableStreamDefaultWriterCloseWithErrorPropagation,WritableStreamDefaultWriterRelease=_require5.WritableStreamDefaultWriterRelease,WritableStreamDefaultWriterWrite=_require5.WritableStreamDefaultWriterWrite,InternalCancel=Symbol("[[Cancel]]"),InternalPull=Symbol("[[Pull]]"),ReadableStream=function(){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=t.size,l=t.highWaterMark;_classCallCheck(this,e),this._state="readable",this._reader=void 0,this._storedError=void 0,this._disturbed=!1,this._readableStreamController=void 0;var o=r.type,n=String(o);if("bytes"===n)void 0===l&&(l=0),this._readableStreamController=new ReadableByteStreamController(this,r,l);else{if(void 0!==o)throw new RangeError("Invalid type is specified");void 0===l&&(l=1),this._readableStreamController=new ReadableStreamDefaultController(this,r,a,l)}}return _createClass(e,[{key:"cancel",value:function(e){return IsReadableStream(this)===!1?Promise.reject(streamBrandCheckException("cancel")):IsReadableStreamLocked(this)===!0?Promise.reject(new TypeError("Cannot cancel a stream that already has a reader")):ReadableStreamCancel(this,e)}},{key:"getReader",value:function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=e.mode;if(IsReadableStream(this)===!1)throw streamBrandCheckException("getReader");if("byob"===r){if(IsReadableByteStreamController(this._readableStreamController)===!1)throw new TypeError("Cannot get a ReadableStreamBYOBReader for a stream not constructed with a byte source");return AcquireReadableStreamBYOBReader(this)}if(void 0===r)return AcquireReadableStreamDefaultReader(this);throw new RangeError("Invalid mode is specified")}},{key:"pipeThrough",value:function(e,r){var t=e.writable,a=e.readable;return this.pipeTo(t,r),a}},{key:"pipeTo",value:function(e){var r=this,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=t.preventClose,l=t.preventAbort,o=t.preventCancel;if(IsReadableStream(this)===!1)return Promise.reject(streamBrandCheckException("pipeTo"));if(IsWritableStream(e)===!1)return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo's first argument must be a WritableStream"));if(a=Boolean(a),l=Boolean(l),o=Boolean(o),IsReadableStreamLocked(this)===!0)return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked ReadableStream"));if(IsWritableStreamLocked(e)===!0)return Promise.reject(new TypeError("ReadableStream.prototype.pipeTo cannot be used on a locked WritableStream"));var n=AcquireReadableStreamDefaultReader(this),i=AcquireWritableStreamDefaultWriter(e),d=!1,s=Promise.resolve();return new Promise(function(t,u){function c(){return s=Promise.resolve(),d===!0?Promise.resolve():i._readyPromise.then(function(){return ReadableStreamDefaultReaderRead(n).then(function(e){var r=e.value,t=e.done;if(t!==!0)return s=WritableStreamDefaultWriterWrite(i,r)})}).then(c)}function b(e,r,t){"errored"===e._state?t(e._storedError):r.catch(t).catch(rethrowAssertionErrorRejection)}function R(e,r,t){"closed"===e._state?t():r.then(t).catch(rethrowAssertionErrorRejection)}function m(){return s.catch(function(){})}function f(e,r,t){d!==!0&&(d=!0,m().then(function(){return e().then(function(){return S(r,t)},function(e){return S(!0,e)})}).catch(rethrowAssertionErrorRejection))}function h(e,r){d!==!0&&(d=!0,m().then(function(){S(e,r)}).catch(rethrowAssertionErrorRejection))}function S(e,r){WritableStreamDefaultWriterRelease(i),ReadableStreamReaderGenericRelease(n),e?u(r):t(void 0)}b(r,n._closedPromise,function(r){l===!1?f(function(){return WritableStreamAbort(e,r)},!0,r):h(!0,r)}),b(e,i._closedPromise,function(e){o===!1?f(function(){return ReadableStreamCancel(r,e)},!0,e):h(!0,e)}),R(r,n._closedPromise,function(){a===!1?f(function(){return WritableStreamDefaultWriterCloseWithErrorPropagation(i)}):h()}),"closing"!==e._state&&"closed"!==e._state||!function(){var e=new TypeError("the destination writable stream closed before all data could be piped to it");o===!1?f(function(){return ReadableStreamCancel(r,e)},!0,e):h(!0,e)}(),c().catch(function(e){s=Promise.resolve(),rethrowAssertionErrorRejection(e)})})}},{key:"tee",value:function(){if(IsReadableStream(this)===!1)throw streamBrandCheckException("tee");var e=ReadableStreamTee(this,!1);return createArrayFromList(e)}},{key:"locked",get:function(){if(IsReadableStream(this)===!1)throw streamBrandCheckException("locked");return IsReadableStreamLocked(this)}}]),e}();module.exports={ReadableStream:ReadableStream,IsReadableStreamDisturbed:IsReadableStreamDisturbed,ReadableStreamDefaultControllerClose:ReadableStreamDefaultControllerClose,ReadableStreamDefaultControllerEnqueue:ReadableStreamDefaultControllerEnqueue,ReadableStreamDefaultControllerError:ReadableStreamDefaultControllerError,ReadableStreamDefaultControllerGetDesiredSize:ReadableStreamDefaultControllerGetDesiredSize};var ReadableStreamDefaultReader=function(){function e(r){if(_classCallCheck(this,e),IsReadableStream(r)===!1)throw new TypeError("ReadableStreamDefaultReader can only be constructed with a ReadableStream instance");if(IsReadableStreamLocked(r)===!0)throw new TypeError("This stream has already been locked for exclusive reading by another reader");ReadableStreamReaderGenericInitialize(this,r),this._readRequests=[]}return _createClass(e,[{key:"cancel",value:function(e){return IsReadableStreamDefaultReader(this)===!1?Promise.reject(defaultReaderBrandCheckException("cancel")):void 0===this._ownerReadableStream?Promise.reject(readerLockException("cancel")):ReadableStreamReaderGenericCancel(this,e)}},{key:"read",value:function(){return IsReadableStreamDefaultReader(this)===!1?Promise.reject(defaultReaderBrandCheckException("read")):void 0===this._ownerReadableStream?Promise.reject(readerLockException("read from")):ReadableStreamDefaultReaderRead(this)}},{key:"releaseLock",value:function(){if(IsReadableStreamDefaultReader(this)===!1)throw defaultReaderBrandCheckException("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");ReadableStreamReaderGenericRelease(this)}}},{key:"closed",get:function(){return IsReadableStreamDefaultReader(this)===!1?Promise.reject(defaultReaderBrandCheckException("closed")):this._closedPromise}}]),e}(),ReadableStreamBYOBReader=function(){function e(r){if(_classCallCheck(this,e),!IsReadableStream(r))throw new TypeError("ReadableStreamBYOBReader can only be constructed with a ReadableStream instance given a byte source");if(IsReadableStreamLocked(r))throw new TypeError("This stream has already been locked for exclusive reading by another reader");ReadableStreamReaderGenericInitialize(this,r),this._readIntoRequests=[]}return _createClass(e,[{key:"cancel",value:function(e){return IsReadableStreamBYOBReader(this)?void 0===this._ownerReadableStream?Promise.reject(readerLockException("cancel")):ReadableStreamReaderGenericCancel(this,e):Promise.reject(byobReaderBrandCheckException("cancel"))}},{key:"read",value:function(e){return IsReadableStreamBYOBReader(this)?void 0===this._ownerReadableStream?Promise.reject(readerLockException("read from")):ArrayBuffer.isView(e)?0===e.byteLength?Promise.reject(new TypeError("view must have non-zero byteLength")):ReadableStreamBYOBReaderRead(this,e):Promise.reject(new TypeError("view must be an array buffer view")):Promise.reject(byobReaderBrandCheckException("read"))}},{key:"releaseLock",value:function(){if(!IsReadableStreamBYOBReader(this))throw byobReaderBrandCheckException("releaseLock");if(void 0!==this._ownerReadableStream){if(this._readIntoRequests.length>0)throw new TypeError("Tried to release a reader lock when that reader has pending read() calls un-settled");ReadableStreamReaderGenericRelease(this)}}},{key:"closed",get:function(){return IsReadableStreamBYOBReader(this)?this._closedPromise:Promise.reject(byobReaderBrandCheckException("closed"))}}]),e}(),ReadableStreamDefaultController=function(){function e(r,t,a,l){if(_classCallCheck(this,e),IsReadableStream(r)===!1)throw new TypeError("ReadableStreamDefaultController can only be constructed with a ReadableStream instance");if(void 0!==r._readableStreamController)throw new TypeError("ReadableStreamDefaultController instances can only be created by the ReadableStream constructor");this._controlledReadableStream=r,this._underlyingSource=t,this._queue=[],this._started=!1,this._closeRequested=!1,this._pullAgain=!1,this._pulling=!1;var o=ValidateAndNormalizeQueuingStrategy(a,l);this._strategySize=o.size,this._strategyHWM=o.highWaterMark;var n=this,i=InvokeOrNoop(t,"start",[this]);Promise.resolve(i).then(function(){n._started=!0,ReadableStreamDefaultControllerCallPullIfNeeded(n)},function(e){ReadableStreamDefaultControllerErrorIfNeeded(n,e)}).catch(rethrowAssertionErrorRejection)}return _createClass(e,[{key:"close",value:function(){if(IsReadableStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("close");if(this._closeRequested===!0)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");ReadableStreamDefaultControllerClose(this)}},{key:"enqueue",value:function(e){if(IsReadableStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("enqueue");if(this._closeRequested===!0)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");return ReadableStreamDefaultControllerEnqueue(this,e)}},{key:"error",value:function(e){if(IsReadableStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");ReadableStreamDefaultControllerError(this,e)}},{key:InternalCancel,value:function(e){return this._queue=[],PromiseInvokeOrNoop(this._underlyingSource,"cancel",[e])}},{key:InternalPull,value:function(){var e=this._controlledReadableStream;if(this._queue.length>0){var r=DequeueValue(this._queue);return this._closeRequested===!0&&0===this._queue.length?ReadableStreamClose(e):ReadableStreamDefaultControllerCallPullIfNeeded(this),Promise.resolve(CreateIterResultObject(r,!1))}var t=ReadableStreamAddReadRequest(e);return ReadableStreamDefaultControllerCallPullIfNeeded(this),t}},{key:"desiredSize",get:function(){if(IsReadableStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("desiredSize");return ReadableStreamDefaultControllerGetDesiredSize(this)}}]),e}(),ReadableStreamBYOBRequest=function(){function e(r,t){_classCallCheck(this,e),this._associatedReadableByteStreamController=r,this._view=t}return _createClass(e,[{key:"respond",value:function(e){if(IsReadableStreamBYOBRequest(this)===!1)throw byobRequestBrandCheckException("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");ReadableByteStreamControllerRespond(this._associatedReadableByteStreamController,e)}},{key:"respondWithNewView",value:function(e){if(IsReadableStreamBYOBRequest(this)===!1)throw byobRequestBrandCheckException("respond");if(void 0===this._associatedReadableByteStreamController)throw new TypeError("This BYOB request has been invalidated");if(!ArrayBuffer.isView(e))throw new TypeError("You can only respond with array buffer views");ReadableByteStreamControllerRespondWithNewView(this._associatedReadableByteStreamController,e)}},{key:"view",get:function(){return this._view}}]),e}(),ReadableByteStreamController=function(){function e(r,t,a){if(_classCallCheck(this,e),IsReadableStream(r)===!1)throw new TypeError("ReadableByteStreamController can only be constructed with a ReadableStream instance given a byte source");if(void 0!==r._readableStreamController)throw new TypeError("ReadableByteStreamController instances can only be created by the ReadableStream constructor given a byte source");
  5133. this._controlledReadableStream=r,this._underlyingByteSource=t,this._pullAgain=!1,this._pulling=!1,ReadableByteStreamControllerClearPendingPullIntos(this),this._queue=[],this._totalQueuedBytes=0,this._closeRequested=!1,this._started=!1,this._strategyHWM=ValidateAndNormalizeHighWaterMark(a);var l=t.autoAllocateChunkSize;if(void 0!==l&&(Number.isInteger(l)===!1||l<=0))throw new RangeError("autoAllocateChunkSize must be a positive integer");this._autoAllocateChunkSize=l,this._pendingPullIntos=[];var o=this,n=InvokeOrNoop(t,"start",[this]);Promise.resolve(n).then(function(){o._started=!0,ReadableByteStreamControllerCallPullIfNeeded(o)},function(e){"readable"===r._state&&ReadableByteStreamControllerError(o,e)}).catch(rethrowAssertionErrorRejection)}return _createClass(e,[{key:"close",value:function(){if(IsReadableByteStreamController(this)===!1)throw byteStreamControllerBrandCheckException("close");if(this._closeRequested===!0)throw new TypeError("The stream has already been closed; do not close it again!");var e=this._controlledReadableStream._state;if("readable"!==e)throw new TypeError("The stream (in "+e+" state) is not in the readable state and cannot be closed");ReadableByteStreamControllerClose(this)}},{key:"enqueue",value:function(e){if(IsReadableByteStreamController(this)===!1)throw byteStreamControllerBrandCheckException("enqueue");if(this._closeRequested===!0)throw new TypeError("stream is closed or draining");var r=this._controlledReadableStream._state;if("readable"!==r)throw new TypeError("The stream (in "+r+" state) is not in the readable state and cannot be enqueued to");if(!ArrayBuffer.isView(e))throw new TypeError("You can only enqueue array buffer views when using a ReadableByteStreamController");ReadableByteStreamControllerEnqueue(this,e)}},{key:"error",value:function(e){if(IsReadableByteStreamController(this)===!1)throw byteStreamControllerBrandCheckException("error");var r=this._controlledReadableStream;if("readable"!==r._state)throw new TypeError("The stream is "+r._state+" and so cannot be errored");ReadableByteStreamControllerError(this,e)}},{key:InternalCancel,value:function(e){if(this._pendingPullIntos.length>0){var r=this._pendingPullIntos[0];r.bytesFilled=0}return this._queue=[],this._totalQueuedBytes=0,PromiseInvokeOrNoop(this._underlyingByteSource,"cancel",[e])}},{key:InternalPull,value:function(){var e=this._controlledReadableStream;if(0===ReadableStreamGetNumReadRequests(e)){if(this._totalQueuedBytes>0){var r=this._queue.shift();this._totalQueuedBytes-=r.byteLength,ReadableByteStreamControllerHandleQueueDrain(this);var t=void 0;try{t=new Uint8Array(r.buffer,r.byteOffset,r.byteLength)}catch(e){return Promise.reject(e)}return Promise.resolve(CreateIterResultObject(t,!1))}var a=this._autoAllocateChunkSize;if(void 0!==a){var l=void 0;try{l=new ArrayBuffer(a)}catch(e){return Promise.reject(e)}var o={buffer:l,byteOffset:0,byteLength:a,bytesFilled:0,elementSize:1,ctor:Uint8Array,readerType:"default"};this._pendingPullIntos.push(o)}}var n=ReadableStreamAddReadRequest(e);return ReadableByteStreamControllerCallPullIfNeeded(this),n}},{key:"byobRequest",get:function(){if(IsReadableByteStreamController(this)===!1)throw byteStreamControllerBrandCheckException("byobRequest");if(void 0===this._byobRequest&&this._pendingPullIntos.length>0){var e=this._pendingPullIntos[0],r=new Uint8Array(e.buffer,e.byteOffset+e.bytesFilled,e.byteLength-e.bytesFilled);this._byobRequest=new ReadableStreamBYOBRequest(this,r)}return this._byobRequest}},{key:"desiredSize",get:function(){if(IsReadableByteStreamController(this)===!1)throw byteStreamControllerBrandCheckException("desiredSize");return ReadableByteStreamControllerGetDesiredSize(this)}}]),e}();
  5134.  
  5135. },{"./helpers.js":5,"./queue-with-sizes.js":6,"./utils.js":2,"./writable-stream.js":9}],8:[function(_dereq_,module,exports){
  5136. "use strict";function _classCallCheck(r,e){if(!(r instanceof e))throw new TypeError("Cannot call a class as a function")}function TransformStreamCloseReadable(r){if(r._errored===!0)throw new TypeError("TransformStream is already errored");if(r._readableClosed===!0)throw new TypeError("Readable side is already closed");TransformStreamCloseReadableInternal(r)}function TransformStreamEnqueueToReadable(r,e){if(r._errored===!0)throw new TypeError("TransformStream is already errored");if(r._readableClosed===!0)throw new TypeError("Readable side is already closed");var a=r._readableController;try{ReadableStreamDefaultControllerEnqueue(a,e)}catch(e){throw r._readableClosed=!0,TransformStreamErrorIfNeeded(r,e),r._storedError}var t=ReadableStreamDefaultControllerGetDesiredSize(a),o=t<=0;o===!0&&r._backpressure===!1&&TransformStreamSetBackpressure(r,!0)}function TransformStreamError(r,e){if(r._errored===!0)throw new TypeError("TransformStream is already errored");TransformStreamErrorInternal(r,e)}function TransformStreamCloseReadableInternal(r){try{ReadableStreamDefaultControllerClose(r._readableController)}catch(r){}r._readableClosed=!0}function TransformStreamErrorIfNeeded(r,e){r._errored===!1&&TransformStreamErrorInternal(r,e)}function TransformStreamErrorInternal(r,e){r._errored=!0,r._storedError=e,r._writableDone===!1&&WritableStreamDefaultControllerError(r._writableController,e),r._readableClosed===!1&&ReadableStreamDefaultControllerError(r._readableController,e)}function TransformStreamReadableReadyPromise(r){return r._backpressure===!1?Promise.resolve():r._backpressureChangePromise}function TransformStreamSetBackpressure(r,e){void 0!==r._backpressureChangePromise&&r._backpressureChangePromise_resolve(e),r._backpressureChangePromise=new Promise(function(e){r._backpressureChangePromise_resolve=e}),r._backpressureChangePromise.then(function(r){}),r._backpressure=e}function TransformStreamDefaultTransform(r,e){var a=e._controlledTransformStream;return TransformStreamEnqueueToReadable(a,r),Promise.resolve()}function TransformStreamTransform(r,e){r._transforming=!0;var a=r._transformer,t=r._transformStreamController,o=PromiseInvokeOrPerformFallback(a,"transform",[e,t],TransformStreamDefaultTransform,[e,t]);return o.then(function(){return r._transforming=!1,TransformStreamReadableReadyPromise(r)},function(e){return TransformStreamErrorIfNeeded(r,e),Promise.reject(e)})}function IsTransformStreamDefaultController(r){return!!typeIsObject(r)&&!!Object.prototype.hasOwnProperty.call(r,"_controlledTransformStream")}function IsTransformStream(r){return!!typeIsObject(r)&&!!Object.prototype.hasOwnProperty.call(r,"_transformStreamController")}function defaultControllerBrandCheckException(r){return new TypeError("TransformStreamDefaultController.prototype."+r+" can only be used on a TransformStreamDefaultController")}function streamBrandCheckException(r){return new TypeError("TransformStream.prototype."+r+" can only be used on a TransformStream")}var _createClass=function(){function r(r,e){for(var a=0;a<e.length;a++){var t=e[a];t.enumerable=t.enumerable||!1,t.configurable=!0,"value"in t&&(t.writable=!0),Object.defineProperty(r,t.key,t)}}return function(e,a,t){return a&&r(e.prototype,a),t&&r(e,t),e}}(),_require=_dereq_("./helpers.js"),InvokeOrNoop=_require.InvokeOrNoop,PromiseInvokeOrPerformFallback=_require.PromiseInvokeOrPerformFallback,PromiseInvokeOrNoop=_require.PromiseInvokeOrNoop,typeIsObject=_require.typeIsObject,_require2=_dereq_("./readable-stream.js"),ReadableStream=_require2.ReadableStream,ReadableStreamDefaultControllerClose=_require2.ReadableStreamDefaultControllerClose,ReadableStreamDefaultControllerEnqueue=_require2.ReadableStreamDefaultControllerEnqueue,ReadableStreamDefaultControllerError=_require2.ReadableStreamDefaultControllerError,ReadableStreamDefaultControllerGetDesiredSize=_require2.ReadableStreamDefaultControllerGetDesiredSize,_require3=_dereq_("./writable-stream.js"),WritableStream=_require3.WritableStream,WritableStreamDefaultControllerError=_require3.WritableStreamDefaultControllerError,TransformStreamSink=function(){function r(e,a){_classCallCheck(this,r),this._transformStream=e,this._startPromise=a}return _createClass(r,[{key:"start",value:function(r){var e=this._transformStream;return e._writableController=r,this._startPromise.then(function(){return TransformStreamReadableReadyPromise(e)})}},{key:"write",value:function(r){var e=this._transformStream;return TransformStreamTransform(e,r)}},{key:"abort",value:function(){var r=this._transformStream;r._writableDone=!0,TransformStreamErrorInternal(r,new TypeError("Writable side aborted"))}},{key:"close",value:function(){var r=this._transformStream;r._writableDone=!0;var e=PromiseInvokeOrNoop(r._transformer,"flush",[r._transformStreamController]);return e.then(function(){return r._errored===!0?Promise.reject(r._storedError):(r._readableClosed===!1&&TransformStreamCloseReadableInternal(r),Promise.resolve())}).catch(function(e){return TransformStreamErrorIfNeeded(r,e),Promise.reject(r._storedError)})}}]),r}(),TransformStreamSource=function(){function r(e,a){_classCallCheck(this,r),this._transformStream=e,this._startPromise=a}return _createClass(r,[{key:"start",value:function(r){var e=this._transformStream;return e._readableController=r,this._startPromise.then(function(){return e._backpressure===!0?Promise.resolve():e._backpressureChangePromise})}},{key:"pull",value:function(){var r=this._transformStream;return TransformStreamSetBackpressure(r,!1),r._backpressureChangePromise}},{key:"cancel",value:function(){var r=this._transformStream;r._readableClosed=!0,TransformStreamErrorInternal(r,new TypeError("Readable side canceled"))}}]),r}(),TransformStreamDefaultController=function(){function r(e){if(_classCallCheck(this,r),IsTransformStream(e)===!1)throw new TypeError("TransformStreamDefaultController can only be constructed with a TransformStream instance");if(void 0!==e._transformStreamController)throw new TypeError("TransformStreamDefaultController instances can only be created by the TransformStream constructor");this._controlledTransformStream=e}return _createClass(r,[{key:"enqueue",value:function(r){if(IsTransformStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("enqueue");TransformStreamEnqueueToReadable(this._controlledTransformStream,r)}},{key:"close",value:function(){if(IsTransformStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("close");TransformStreamCloseReadable(this._controlledTransformStream)}},{key:"error",value:function(r){if(IsTransformStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("error");TransformStreamError(this._controlledTransformStream,r)}},{key:"desiredSize",get:function(){if(IsTransformStreamDefaultController(this)===!1)throw defaultControllerBrandCheckException("desiredSize");var r=this._controlledTransformStream,e=r._readableController;return ReadableStreamDefaultControllerGetDesiredSize(e)}}]),r}(),TransformStream=function(){function r(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};_classCallCheck(this,r),this._transformer=e;var a=e.readableStrategy,t=e.writableStrategy;this._transforming=!1,this._errored=!1,this._storedError=void 0,this._writableController=void 0,this._readableController=void 0,this._transformStreamController=void 0,this._writableDone=!1,this._readableClosed=!1,this._backpressure=void 0,this._backpressureChangePromise=void 0,this._backpressureChangePromise_resolve=void 0,this._transformStreamController=new TransformStreamDefaultController(this);var o=void 0,n=new Promise(function(r){o=r}),s=new TransformStreamSource(this,n);this._readable=new ReadableStream(s,a);var l=new TransformStreamSink(this,n);this._writable=new WritableStream(l,t);var i=ReadableStreamDefaultControllerGetDesiredSize(this._readableController);TransformStreamSetBackpressure(this,i<=0);var m=this,f=InvokeOrNoop(e,"start",[m._transformStreamController]);o(f),n.catch(function(r){m._errored===!1&&(m._errored=!0,m._storedError=r)})}return _createClass(r,[{key:"readable",get:function(){if(IsTransformStream(this)===!1)throw streamBrandCheckException("readable");return this._readable}},{key:"writable",get:function(){if(IsTransformStream(this)===!1)throw streamBrandCheckException("writable");return this._writable}}]),r}();module.exports={TransformStream:TransformStream};
  5137.  
  5138. },{"./helpers.js":5,"./readable-stream.js":7,"./writable-stream.js":9}],9:[function(_dereq_,module,exports){
  5139. "use strict";function _classCallCheck(e,r){if(!(e instanceof r))throw new TypeError("Cannot call a class as a function")}function AcquireWritableStreamDefaultWriter(e){return new WritableStreamDefaultWriter(e)}function IsWritableStream(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_writableStreamController")}function IsWritableStreamLocked(e){return void 0!==e._writer}function WritableStreamAbort(e,r){var t=e._state;if("closed"===t)return Promise.resolve(void 0);if("errored"===t)return Promise.reject(e._storedError);var i=new TypeError("Aborted");WritableStreamError(e,i);var o=e._writableStreamController;if(o._writing===!0||o._inClose===!0){var a=new Promise(function(r,t){var i={_resolve:r,_reject:t};e._pendingAbortRequest=i});return o._writing===!0?a.then(function(){return WritableStreamDefaultControllerAbort(e._writableStreamController,r)}):a}return WritableStreamDefaultControllerAbort(e._writableStreamController,r)}function WritableStreamAddWriteRequest(e){var r=new Promise(function(r,t){var i={_resolve:r,_reject:t};e._writeRequests.push(i)});return r}function WritableStreamError(e,r){var t=e._state;e._state="errored",e._storedError=r;var i=e._writableStreamController;(void 0===i||i._writing===!1&&i._inClose===!1)&&WritableStreamRejectPromisesInReactionToError(e);var o=e._writer;void 0!==o&&("writable"===t&&WritableStreamDefaultControllerGetBackpressure(e._writableStreamController)===!0?defaultWriterReadyPromiseReject(o,r):defaultWriterReadyPromiseResetToRejected(o,r),o._readyPromise.catch(function(){}))}function WritableStreamFinishClose(e){"closing"===e._state?(defaultWriterClosedPromiseResolve(e._writer),e._state="closed"):(defaultWriterClosedPromiseReject(e._writer,e._storedError),e._writer._closedPromise.catch(function(){})),void 0!==e._pendingAbortRequest&&(e._pendingAbortRequest._resolve(),e._pendingAbortRequest=void 0)}function WritableStreamRejectPromisesInReactionToError(e){var r=e._storedError,t=!0,i=!1,o=void 0;try{for(var a,l=e._writeRequests[Symbol.iterator]();!(t=(a=l.next()).done);t=!0){var n=a.value;n._reject(r)}}catch(e){i=!0,o=e}finally{try{!t&&l.return&&l.return()}finally{if(i)throw o}}e._writeRequests=[],void 0!==e._pendingCloseRequest&&(e._pendingCloseRequest._reject(r),e._pendingCloseRequest=void 0);var s=e._writer;void 0!==s&&(defaultWriterClosedPromiseReject(s,r),s._closedPromise.catch(function(){}))}function WritableStreamUpdateBackpressure(e,r){var t=e._writer;void 0!==t&&(r===!0?defaultWriterReadyPromiseReset(t):defaultWriterReadyPromiseResolve(t))}function IsWritableStreamDefaultWriter(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_ownerWritableStream")}function WritableStreamDefaultWriterAbort(e,r){var t=e._ownerWritableStream;return WritableStreamAbort(t,r)}function WritableStreamDefaultWriterClose(e){var r=e._ownerWritableStream,t=r._state;if("closed"===t||"errored"===t)return Promise.reject(new TypeError("The stream (in "+t+" state) is not in the writable state and cannot be closed"));var i=new Promise(function(e,t){var i={_resolve:e,_reject:t};r._pendingCloseRequest=i});return WritableStreamDefaultControllerGetBackpressure(r._writableStreamController)===!0&&defaultWriterReadyPromiseResolve(e),r._state="closing",WritableStreamDefaultControllerClose(r._writableStreamController),i}function WritableStreamDefaultWriterCloseWithErrorPropagation(e){var r=e._ownerWritableStream,t=r._state;return"closing"===t||"closed"===t?Promise.resolve():"errored"===t?Promise.reject(r._storedError):WritableStreamDefaultWriterClose(e)}function WritableStreamDefaultWriterGetDesiredSize(e){var r=e._ownerWritableStream,t=r._state;return"errored"===t?null:"closed"===t?0:WritableStreamDefaultControllerGetDesiredSize(r._writableStreamController)}function WritableStreamDefaultWriterRelease(e){var r=e._ownerWritableStream,t=new TypeError("Writer was released and can no longer be used to monitor the stream's closedness"),i=r._state;"writable"===i||"closing"===i||void 0!==r._pendingAbortRequest?defaultWriterClosedPromiseReject(e,t):defaultWriterClosedPromiseResetToRejected(e,t),e._closedPromise.catch(function(){}),"writable"===i&&WritableStreamDefaultControllerGetBackpressure(r._writableStreamController)===!0?defaultWriterReadyPromiseReject(e,t):defaultWriterReadyPromiseResetToRejected(e,t),e._readyPromise.catch(function(){}),r._writer=void 0,e._ownerWritableStream=void 0}function WritableStreamDefaultWriterWrite(e,r){var t=e._ownerWritableStream,i=t._state;if("closed"===i||"errored"===i)return Promise.reject(new TypeError("The stream (in "+i+" state) is not in the writable state and cannot be written to"));var o=WritableStreamAddWriteRequest(t);return WritableStreamDefaultControllerWrite(t._writableStreamController,r),o}function WritableStreamDefaultControllerAbort(e,r){e._queue=[];var t=PromiseInvokeOrFallbackOrNoop(e._underlyingSink,"abort",[r],"close",[e]);return t.then(function(){})}function WritableStreamDefaultControllerClose(e){EnqueueValueWithSize(e._queue,"close",0),WritableStreamDefaultControllerAdvanceQueueIfNeeded(e)}function WritableStreamDefaultControllerGetDesiredSize(e){var r=GetTotalQueueSize(e._queue);return e._strategyHWM-r}function WritableStreamDefaultControllerWrite(e,r){var t=e._controlledWritableStream,i=1;if(void 0!==e._strategySize)try{i=e._strategySize(r)}catch(r){return void WritableStreamDefaultControllerErrorIfNeeded(e,r)}var o={chunk:r},a=WritableStreamDefaultControllerGetBackpressure(e);try{EnqueueValueWithSize(e._queue,o,i)}catch(r){return void WritableStreamDefaultControllerErrorIfNeeded(e,r)}if("writable"===t._state){var l=WritableStreamDefaultControllerGetBackpressure(e);a!==l&&WritableStreamUpdateBackpressure(t,l)}WritableStreamDefaultControllerAdvanceQueueIfNeeded(e)}function IsWritableStreamDefaultController(e){return!!typeIsObject(e)&&!!Object.prototype.hasOwnProperty.call(e,"_underlyingSink")}function WritableStreamDefaultControllerAdvanceQueueIfNeeded(e){if("closed"!==e._controlledWritableStream._state&&"errored"!==e._controlledWritableStream._state&&e._started!==!1&&e._writing!==!0&&0!==e._queue.length){var r=PeekQueueValue(e._queue);"close"===r?WritableStreamDefaultControllerProcessClose(e):WritableStreamDefaultControllerProcessWrite(e,r.chunk)}}function WritableStreamDefaultControllerErrorIfNeeded(e,r){"writable"!==e._controlledWritableStream._state&&"closing"!==e._controlledWritableStream._state||WritableStreamDefaultControllerError(e,r)}function WritableStreamDefaultControllerProcessClose(e){var r=e._controlledWritableStream;DequeueValue(e._queue),e._inClose=!0;var t=PromiseInvokeOrNoop(e._underlyingSink,"close",[e]);t.then(function(){e._inClose=!1,"closing"!==r._state&&"errored"!==r._state||(r._pendingCloseRequest._resolve(void 0),r._pendingCloseRequest=void 0,WritableStreamFinishClose(r))},function(t){e._inClose=!1,r._pendingCloseRequest._reject(t),r._pendingCloseRequest=void 0,void 0!==r._pendingAbortRequest&&(r._pendingAbortRequest._reject(t),r._pendingAbortRequest=void 0),WritableStreamDefaultControllerErrorIfNeeded(e,t)}).catch(rethrowAssertionErrorRejection)}function WritableStreamDefaultControllerProcessWrite(e,r){e._writing=!0;var t=e._controlledWritableStream;t._pendingWriteRequest=t._writeRequests.shift();var i=PromiseInvokeOrNoop(e._underlyingSink,"write",[r,e]);i.then(function(){var r=t._state;if(e._writing=!1,t._pendingWriteRequest._resolve(void 0),t._pendingWriteRequest=void 0,"errored"===r)return WritableStreamRejectPromisesInReactionToError(t),void(void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._resolve(),t._pendingAbortRequest=void 0));var i=WritableStreamDefaultControllerGetBackpressure(e);if(DequeueValue(e._queue),"closing"!==r){var o=WritableStreamDefaultControllerGetBackpressure(e);i!==o&&WritableStreamUpdateBackpressure(e._controlledWritableStream,o)}WritableStreamDefaultControllerAdvanceQueueIfNeeded(e)},function(r){e._writing=!1,t._pendingWriteRequest._reject(r),t._pendingWriteRequest=void 0,"errored"===t._state&&(t._storedError=r,WritableStreamRejectPromisesInReactionToError(t)),void 0!==t._pendingAbortRequest&&(t._pendingAbortRequest._reject(r),t._pendingAbortRequest=void 0),WritableStreamDefaultControllerErrorIfNeeded(e,r)}).catch(rethrowAssertionErrorRejection)}function WritableStreamDefaultControllerGetBackpressure(e){var r=WritableStreamDefaultControllerGetDesiredSize(e);return r<=0}function WritableStreamDefaultControllerError(e,r){var t=e._controlledWritableStream;WritableStreamError(t,r),e._queue=[]}function streamBrandCheckException(e){return new TypeError("WritableStream.prototype."+e+" can only be used on a WritableStream")}function defaultWriterBrandCheckException(e){return new TypeError("WritableStreamDefaultWriter.prototype."+e+" can only be used on a WritableStreamDefaultWriter")}function defaultWriterLockException(e){return new TypeError("Cannot "+e+" a stream using a released writer")}function defaultWriterClosedPromiseInitialize(e){e._closedPromise=new Promise(function(r,t){e._closedPromise_resolve=r,e._closedPromise_reject=t})}function defaultWriterClosedPromiseInitializeAsRejected(e,r){e._closedPromise=Promise.reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function defaultWriterClosedPromiseInitializeAsResolved(e){e._closedPromise=Promise.resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function defaultWriterClosedPromiseReject(e,r){e._closedPromise_reject(r),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function defaultWriterClosedPromiseResetToRejected(e,r){e._closedPromise=Promise.reject(r)}function defaultWriterClosedPromiseResolve(e){e._closedPromise_resolve(void 0),e._closedPromise_resolve=void 0,e._closedPromise_reject=void 0}function defaultWriterReadyPromiseInitialize(e){e._readyPromise=new Promise(function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})}function defaultWriterReadyPromiseInitializeAsResolved(e){e._readyPromise=Promise.resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0}function defaultWriterReadyPromiseReject(e,r){e._readyPromise_reject(r),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0}function defaultWriterReadyPromiseReset(e){e._readyPromise=new Promise(function(r,t){e._readyPromise_resolve=r,e._readyPromise_reject=t})}function defaultWriterReadyPromiseResetToRejected(e,r){e._readyPromise=Promise.reject(r)}function defaultWriterReadyPromiseResolve(e){e._readyPromise_resolve(void 0),e._readyPromise_resolve=void 0,e._readyPromise_reject=void 0}var _createClass=function(){function e(e,r){for(var t=0;t<r.length;t++){var i=r[t];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,i.key,i)}}return function(r,t,i){return t&&e(r.prototype,t),i&&e(r,i),r}}(),_require=_dereq_("./helpers.js"),InvokeOrNoop=_require.InvokeOrNoop,PromiseInvokeOrNoop=_require.PromiseInvokeOrNoop,PromiseInvokeOrFallbackOrNoop=_require.PromiseInvokeOrFallbackOrNoop,ValidateAndNormalizeQueuingStrategy=_require.ValidateAndNormalizeQueuingStrategy,typeIsObject=_require.typeIsObject,_require2=_dereq_("./utils.js"),rethrowAssertionErrorRejection=_require2.rethrowAssertionErrorRejection,_require3=_dereq_("./queue-with-sizes.js"),DequeueValue=_require3.DequeueValue,EnqueueValueWithSize=_require3.EnqueueValueWithSize,GetTotalQueueSize=_require3.GetTotalQueueSize,PeekQueueValue=_require3.PeekQueueValue,WritableStream=function(){function e(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=t.size,o=t.highWaterMark,a=void 0===o?1:o;_classCallCheck(this,e),this._state="writable",this._storedError=void 0,this._writer=void 0,this._writableStreamController=void 0,this._writeRequests=[],this._pendingWriteRequest=void 0,this._pendingCloseRequest=void 0,this._pendingAbortRequest=void 0;var l=r.type;if(void 0!==l)throw new RangeError("Invalid type is specified");this._writableStreamController=new WritableStreamDefaultController(this,r,i,a)}return _createClass(e,[{key:"abort",value:function(e){return IsWritableStream(this)===!1?Promise.reject(streamBrandCheckException("abort")):IsWritableStreamLocked(this)===!0?Promise.reject(new TypeError("Cannot abort a stream that already has a writer")):WritableStreamAbort(this,e)}},{key:"getWriter",value:function(){if(IsWritableStream(this)===!1)throw streamBrandCheckException("getWriter");return AcquireWritableStreamDefaultWriter(this)}},{key:"locked",get:function(){if(IsWritableStream(this)===!1)throw streamBrandCheckException("locked");return IsWritableStreamLocked(this)}}]),e}();module.exports={AcquireWritableStreamDefaultWriter:AcquireWritableStreamDefaultWriter,IsWritableStream:IsWritableStream,IsWritableStreamLocked:IsWritableStreamLocked,WritableStream:WritableStream,WritableStreamAbort:WritableStreamAbort,WritableStreamDefaultControllerError:WritableStreamDefaultControllerError,WritableStreamDefaultWriterCloseWithErrorPropagation:WritableStreamDefaultWriterCloseWithErrorPropagation,WritableStreamDefaultWriterRelease:WritableStreamDefaultWriterRelease,WritableStreamDefaultWriterWrite:WritableStreamDefaultWriterWrite};var WritableStreamDefaultWriter=function(){function e(r){if(_classCallCheck(this,e),IsWritableStream(r)===!1)throw new TypeError("WritableStreamDefaultWriter can only be constructed with a WritableStream instance");if(IsWritableStreamLocked(r)===!0)throw new TypeError("This stream has already been locked for exclusive writing by another writer");this._ownerWritableStream=r,r._writer=this;var t=r._state;"writable"===t||"closing"===t?defaultWriterClosedPromiseInitialize(this):"closed"===t?defaultWriterClosedPromiseInitializeAsResolved(this):(defaultWriterClosedPromiseInitializeAsRejected(this,r._storedError),this._closedPromise.catch(function(){})),"writable"===t&&WritableStreamDefaultControllerGetBackpressure(r._writableStreamController)===!0?defaultWriterReadyPromiseInitialize(this):defaultWriterReadyPromiseInitializeAsResolved(this,void 0)}return _createClass(e,[{key:"abort",value:function(e){return IsWritableStreamDefaultWriter(this)===!1?Promise.reject(defaultWriterBrandCheckException("abort")):void 0===this._ownerWritableStream?Promise.reject(defaultWriterLockException("abort")):WritableStreamDefaultWriterAbort(this,e)}},{key:"close",value:function(){if(IsWritableStreamDefaultWriter(this)===!1)return Promise.reject(defaultWriterBrandCheckException("close"));var e=this._ownerWritableStream;return void 0===e?Promise.reject(defaultWriterLockException("close")):"closing"===e._state?Promise.reject(new TypeError("cannot close an already-closing stream")):WritableStreamDefaultWriterClose(this)}},{key:"releaseLock",value:function(){if(IsWritableStreamDefaultWriter(this)===!1)throw defaultWriterBrandCheckException("releaseLock");var e=this._ownerWritableStream;void 0!==e&&WritableStreamDefaultWriterRelease(this)}},{key:"write",value:function(e){if(IsWritableStreamDefaultWriter(this)===!1)return Promise.reject(defaultWriterBrandCheckException("write"));var r=this._ownerWritableStream;return void 0===r?Promise.reject(defaultWriterLockException("write to")):"closing"===r._state?Promise.reject(new TypeError("Cannot write to an already-closed stream")):WritableStreamDefaultWriterWrite(this,e)}},{key:"closed",get:function(){return IsWritableStreamDefaultWriter(this)===!1?Promise.reject(defaultWriterBrandCheckException("closed")):this._closedPromise}},{key:"desiredSize",get:function(){if(IsWritableStreamDefaultWriter(this)===!1)throw defaultWriterBrandCheckException("desiredSize");if(void 0===this._ownerWritableStream)throw defaultWriterLockException("desiredSize");return WritableStreamDefaultWriterGetDesiredSize(this)}},{key:"ready",get:function(){return IsWritableStreamDefaultWriter(this)===!1?Promise.reject(defaultWriterBrandCheckException("ready")):this._readyPromise}}]),e}(),WritableStreamDefaultController=function(){function e(r,t,i,o){if(_classCallCheck(this,e),IsWritableStream(r)===!1)throw new TypeError("WritableStreamDefaultController can only be constructed with a WritableStream instance");if(void 0!==r._writableStreamController)throw new TypeError("WritableStreamDefaultController instances can only be created by the WritableStream constructor");this._controlledWritableStream=r,this._underlyingSink=t,this._queue=[],this._started=!1,this._writing=!1,this._inClose=!1;var a=ValidateAndNormalizeQueuingStrategy(i,o);this._strategySize=a.size,this._strategyHWM=a.highWaterMark;var l=WritableStreamDefaultControllerGetBackpressure(this);l===!0&&WritableStreamUpdateBackpressure(r,l);var n=this,s=InvokeOrNoop(t,"start",[this]);Promise.resolve(s).then(function(){n._started=!0,WritableStreamDefaultControllerAdvanceQueueIfNeeded(n)},function(e){WritableStreamDefaultControllerErrorIfNeeded(n,e)}).catch(rethrowAssertionErrorRejection)}return _createClass(e,[{key:"error",value:function(e){if(IsWritableStreamDefaultController(this)===!1)throw new TypeError("WritableStreamDefaultController.prototype.error can only be used on a WritableStreamDefaultController");var r=this._controlledWritableStream._state;if("closed"===r||"errored"===r)throw new TypeError("The stream is "+r+" and so cannot be errored");WritableStreamDefaultControllerError(this,e)}}]),e}();
  5140.  
  5141. },{"./helpers.js":5,"./queue-with-sizes.js":6,"./utils.js":2}]},{},[1])(1)
  5142. });
  5143. //# sourceMappingURL=polyfill.min.js.map
  5144.  
  5145.  
  5146. /***/ }),
  5147. /* 22 */
  5148. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  5149.  
  5150. "use strict";
  5151. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  5152.  
  5153. // CONCATENATED MODULE: ../node_modules/fetch-readablestream/src/fetch.js
  5154. // thin wrapper around `fetch()` to ensure we only expose the properties provided by
  5155. // the XHR polyfil; / fetch-readablestream Response API.
  5156. function fetchRequest(url, options) {
  5157. return fetch(url, options)
  5158. .then(r => {
  5159. return {
  5160. body: r.body,
  5161. headers: r.headers,
  5162. ok: r.ok,
  5163. status: r.status,
  5164. statusText: r.statusText,
  5165. url: r.url
  5166. };
  5167. });
  5168. }
  5169.  
  5170. // CONCATENATED MODULE: ../node_modules/fetch-readablestream/src/polyfill/Headers.js
  5171. // Headers is a partial polyfill for the HTML5 Headers class.
  5172. class Headers_Headers {
  5173. constructor(h = {}) {
  5174. this.h = {};
  5175. if (h instanceof Headers_Headers) {
  5176. h.forEach((value, key) => this.append(key, value));
  5177. }
  5178. Object.getOwnPropertyNames(h)
  5179. .forEach(key => this.append(key, h[key]));
  5180. }
  5181. append(key, value) {
  5182. key = key.toLowerCase();
  5183. if (!Array.isArray(this.h[key])) {
  5184. this.h[key] = [];
  5185. }
  5186. this.h[key].push(value);
  5187. }
  5188. set(key, value) {
  5189. this.h[key.toLowerCase()] = [ value ];
  5190. }
  5191. has(key) {
  5192. return Array.isArray(this.h[key.toLowerCase()]);
  5193. }
  5194. get(key) {
  5195. key = key.toLowerCase();
  5196. if (Array.isArray(this.h[key])) {
  5197. return this.h[key][0];
  5198. }
  5199. }
  5200. getAll(key) {
  5201. return this.h[key.toLowerCase()].concat();
  5202. }
  5203. entries() {
  5204. const items = [];
  5205. this.forEach((value, key) => { items.push([key, value]) });
  5206. return makeIterator(items);
  5207. }
  5208.  
  5209. // forEach is not part of the official spec.
  5210. forEach(callback, thisArg) {
  5211. Object.getOwnPropertyNames(this.h)
  5212. .forEach(key => {
  5213. this.h[key].forEach(value => callback.call(thisArg, value, key, this));
  5214. }, this);
  5215. }
  5216. }
  5217.  
  5218. function makeIterator(items) {
  5219. return {
  5220. next() {
  5221. const value = items.shift();
  5222. return {
  5223. done: value === undefined,
  5224. value: value
  5225. }
  5226. },
  5227. [Symbol.iterator]() {
  5228. return this;
  5229. }
  5230. };
  5231. }
  5232. // CONCATENATED MODULE: ../node_modules/fetch-readablestream/src/xhr.js
  5233. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_original__ = __webpack_require__(23);
  5234. /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_original___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_original__);
  5235.  
  5236.  
  5237.  
  5238. function makeXhrTransport({ responseType, responseParserFactory }) {
  5239. return function xhrTransport(url, options) {
  5240. const xhr = new XMLHttpRequest();
  5241. const responseParser = responseParserFactory();
  5242.  
  5243. let responseStreamController;
  5244. let cancelled = false;
  5245.  
  5246. const responseStream = new ReadableStream({
  5247. start(c) {
  5248. responseStreamController = c
  5249. },
  5250. cancel() {
  5251. cancelled = true;
  5252. xhr.abort()
  5253. }
  5254. });
  5255.  
  5256. const { method = 'GET' } = options;
  5257.  
  5258. xhr.open(method, url);
  5259. xhr.responseType = responseType;
  5260. xhr.withCredentials = (options.credentials === 'include' || (options.credentials === 'same-origin' && __WEBPACK_IMPORTED_MODULE_1_original___default.a.same(url, location.origin)));
  5261. if (options.headers) {
  5262. for (const pair of options.headers.entries()) {
  5263. xhr.setRequestHeader(pair[0], pair[1]);
  5264. }
  5265. }
  5266.  
  5267. return new Promise((resolve, reject) => {
  5268. if (options.body && (method === 'GET' || method === 'HEAD')) {
  5269. reject(new TypeError("Failed to execute 'fetchStream' on 'Window': Request with GET/HEAD method cannot have body"))
  5270. }
  5271.  
  5272. xhr.onreadystatechange = function () {
  5273. if (xhr.readyState === xhr.HEADERS_RECEIVED) {
  5274. return resolve({
  5275. body: responseStream,
  5276. headers: parseResposneHeaders(xhr.getAllResponseHeaders()),
  5277. ok: xhr.status >= 200 && xhr.status < 300,
  5278. status: xhr.status,
  5279. statusText: xhr.statusText,
  5280. url: makeResponseUrl(xhr.responseURL, url)
  5281. });
  5282. }
  5283. };
  5284.  
  5285. xhr.onerror = function () {
  5286. return reject(new TypeError('Network request failed'));
  5287. };
  5288.  
  5289. xhr.ontimeout = function() {
  5290. reject(new TypeError('Network request failed'))
  5291. };
  5292.  
  5293. xhr.onprogress = function () {
  5294. if (!cancelled) {
  5295. const bytes = responseParser(xhr.response);
  5296. responseStreamController.enqueue(bytes);
  5297. }
  5298. };
  5299.  
  5300. xhr.onload = function () {
  5301. responseStreamController.close();
  5302. };
  5303.  
  5304. xhr.send(options.body);
  5305. });
  5306. }
  5307. }
  5308.  
  5309. function makeHeaders() {
  5310. // Prefer the native method if provided by the browser.
  5311. if (typeof Headers !== 'undefined') {
  5312. return new Headers();
  5313. }
  5314. return new Headers_Headers();
  5315. }
  5316.  
  5317. function makeResponseUrl(responseUrl, requestUrl) {
  5318. if (!responseUrl) {
  5319. // best guess; note this will not correctly handle redirects.
  5320. if (requestUrl.substring(0, 4) !== "http") {
  5321. return location.origin + requestUrl;
  5322. }
  5323. return requestUrl;
  5324. }
  5325. return responseUrl;
  5326. }
  5327.  
  5328. function parseResposneHeaders(str) {
  5329. const hdrs = makeHeaders();
  5330. if (str) {
  5331. const pairs = str.split('\u000d\u000a');
  5332. for (let i = 0; i < pairs.length; i++) {
  5333. const p = pairs[i];
  5334. const index = p.indexOf('\u003a\u0020');
  5335. if (index > 0) {
  5336. const key = p.substring(0, index);
  5337. const value = p.substring(index + 2);
  5338. hdrs.append(key, value);
  5339. }
  5340. }
  5341. }
  5342. return hdrs;
  5343. }
  5344. // CONCATENATED MODULE: ../node_modules/fetch-readablestream/src/defaultTransportFactory.js
  5345.  
  5346.  
  5347.  
  5348. // selected is used to cache the detected transport.
  5349. let selected = null;
  5350.  
  5351. // defaultTransportFactory selects the most appropriate transport based on the
  5352. // capabilities of the current environment.
  5353. function defaultTransportFactory() {
  5354. if (!selected) {
  5355. selected = detectTransport();
  5356. }
  5357. return selected;
  5358. }
  5359.  
  5360. function detectTransport() {
  5361. if (typeof Response !== 'undefined' && Response.prototype.hasOwnProperty("body")) {
  5362. // fetch with ReadableStream support.
  5363. return fetchRequest;
  5364. }
  5365.  
  5366. const mozChunked = 'moz-chunked-arraybuffer';
  5367. if (supportsXhrResponseType(mozChunked)) {
  5368. // Firefox, ArrayBuffer support.
  5369. return makeXhrTransport({
  5370. responseType: mozChunked,
  5371. responseParserFactory: function () {
  5372. return response => new Uint8Array(response);
  5373. }
  5374. });
  5375. }
  5376.  
  5377. // Bog-standard, expensive, text concatenation with byte encoding :(
  5378. return makeXhrTransport({
  5379. responseType: 'text',
  5380. responseParserFactory: function () {
  5381. const encoder = new TextEncoder();
  5382. let offset = 0;
  5383. return function (response) {
  5384. const chunk = response.substr(offset);
  5385. offset = response.length;
  5386. return encoder.encode(chunk, { stream: true });
  5387. }
  5388. }
  5389. });
  5390. }
  5391.  
  5392. function supportsXhrResponseType(type) {
  5393. try {
  5394. const tmpXhr = new XMLHttpRequest();
  5395. tmpXhr.responseType = type;
  5396. return tmpXhr.responseType === type;
  5397. } catch (e) { /* IE throws on setting responseType to an unsupported value */ }
  5398. return false;
  5399. }
  5400.  
  5401. // CONCATENATED MODULE: ../node_modules/fetch-readablestream/src/index.js
  5402. /* harmony export (immutable) */ __webpack_exports__["default"] = fetchStream;
  5403.  
  5404.  
  5405. function fetchStream(url, options = {}) {
  5406. let transport = options.transport;
  5407. if (!transport) {
  5408. transport = fetchStream.transportFactory();
  5409. }
  5410.  
  5411. return transport(url, options);
  5412. }
  5413.  
  5414. // override this function to delegate to an alternative transport function selection
  5415. // strategy; useful when testing.
  5416. fetchStream.transportFactory = defaultTransportFactory;
  5417.  
  5418. /***/ }),
  5419. /* 23 */
  5420. /***/ (function(module, exports, __webpack_require__) {
  5421.  
  5422. "use strict";
  5423.  
  5424.  
  5425. var parse = __webpack_require__(6);
  5426.  
  5427. /**
  5428. * Transform an URL to a valid origin value.
  5429. *
  5430. * @param {String|Object} url URL to transform to it's origin.
  5431. * @returns {String} The origin.
  5432. * @api public
  5433. */
  5434. function origin(url) {
  5435. if ('string' === typeof url) url = parse(url);
  5436.  
  5437. //
  5438. // 6.2. ASCII Serialization of an Origin
  5439. // http://tools.ietf.org/html/rfc6454#section-6.2
  5440. //
  5441. if (!url.protocol || !url.hostname) return 'null';
  5442.  
  5443. //
  5444. // 4. Origin of a URI
  5445. // http://tools.ietf.org/html/rfc6454#section-4
  5446. //
  5447. // States that url.scheme, host should be converted to lower case. This also
  5448. // makes it easier to match origins as everything is just lower case.
  5449. //
  5450. return (url.protocol +'//'+ url.host).toLowerCase();
  5451. }
  5452.  
  5453. /**
  5454. * Check if the origins are the same.
  5455. *
  5456. * @param {String} a URL or origin of a.
  5457. * @param {String} b URL or origin of b.
  5458. * @returns {Boolean}
  5459. * @api public
  5460. */
  5461. origin.same = function same(a, b) {
  5462. return origin(a) === origin(b);
  5463. };
  5464.  
  5465. //
  5466. // Expose the origin
  5467. //
  5468. module.exports = origin;
  5469.  
  5470.  
  5471. /***/ }),
  5472. /* 24 */
  5473. /***/ (function(module, exports, __webpack_require__) {
  5474.  
  5475. "use strict";
  5476.  
  5477.  
  5478. /**
  5479. * Check if we're required to add a port number.
  5480. *
  5481. * @see https://url.spec.whatwg.org/#default-port
  5482. * @param {Number|String} port Port number we need to check
  5483. * @param {String} protocol Protocol we need to check against.
  5484. * @returns {Boolean} Is it a default port for the given protocol
  5485. * @api private
  5486. */
  5487. module.exports = function required(port, protocol) {
  5488. protocol = protocol.split(':')[0];
  5489. port = +port;
  5490.  
  5491. if (!port) return false;
  5492.  
  5493. switch (protocol) {
  5494. case 'http':
  5495. case 'ws':
  5496. return port !== 80;
  5497.  
  5498. case 'https':
  5499. case 'wss':
  5500. return port !== 443;
  5501.  
  5502. case 'ftp':
  5503. return port !== 21;
  5504.  
  5505. case 'gopher':
  5506. return port !== 70;
  5507.  
  5508. case 'file':
  5509. return false;
  5510. }
  5511.  
  5512. return port !== 0;
  5513. };
  5514.  
  5515.  
  5516. /***/ }),
  5517. /* 25 */
  5518. /***/ (function(module, exports, __webpack_require__) {
  5519.  
  5520. "use strict";
  5521. /* WEBPACK VAR INJECTION */(function(global) {
  5522.  
  5523. /**
  5524. * These properties should not be copied or inherited from. This is only needed
  5525. * for all non blob URL's as the a blob URL does not include a hash, only the
  5526. * origin.
  5527. *
  5528. * @type {Object}
  5529. * @private
  5530. */
  5531. var ignore = { hash: 1, query: 1 }
  5532. , URL;
  5533.  
  5534. /**
  5535. * The location object differs when your code is loaded through a normal page,
  5536. * Worker or through a worker using a blob. And with the blobble begins the
  5537. * trouble as the location object will contain the URL of the blob, not the
  5538. * location of the page where our code is loaded in. The actual origin is
  5539. * encoded in the `pathname` so we can thankfully generate a good "default"
  5540. * location from it so we can generate proper relative URL's again.
  5541. *
  5542. * @param {Object} loc Optional default location object.
  5543. * @returns {Object} lolcation object.
  5544. * @api public
  5545. */
  5546. module.exports = function lolcation(loc) {
  5547. loc = loc || global.location || {};
  5548. URL = URL || __webpack_require__(6);
  5549.  
  5550. var finaldestination = {}
  5551. , type = typeof loc
  5552. , key;
  5553.  
  5554. if ('blob:' === loc.protocol) {
  5555. finaldestination = new URL(unescape(loc.pathname), {});
  5556. } else if ('string' === type) {
  5557. finaldestination = new URL(loc, {});
  5558. for (key in ignore) delete finaldestination[key];
  5559. } else if ('object' === type) for (key in loc) {
  5560. if (key in ignore) continue;
  5561. finaldestination[key] = loc[key];
  5562. }
  5563.  
  5564. return finaldestination;
  5565. };
  5566.  
  5567. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  5568.  
  5569. /***/ }),
  5570. /* 26 */
  5571. /***/ (function(module, exports, __webpack_require__) {
  5572.  
  5573. "use strict";
  5574.  
  5575.  
  5576. var has = Object.prototype.hasOwnProperty;
  5577.  
  5578. /**
  5579. * Simple query string parser.
  5580. *
  5581. * @param {String} query The query string that needs to be parsed.
  5582. * @returns {Object}
  5583. * @api public
  5584. */
  5585. function querystring(query) {
  5586. var parser = /([^=?&]+)=?([^&]*)/g
  5587. , result = {}
  5588. , part;
  5589.  
  5590. //
  5591. // Little nifty parsing hack, leverage the fact that RegExp.exec increments
  5592. // the lastIndex property so we can continue executing this loop until we've
  5593. // parsed all results.
  5594. //
  5595. for (;
  5596. part = parser.exec(query);
  5597. result[decodeURIComponent(part[1])] = decodeURIComponent(part[2])
  5598. );
  5599.  
  5600. return result;
  5601. }
  5602.  
  5603. /**
  5604. * Transform a query string to an object.
  5605. *
  5606. * @param {Object} obj Object that should be transformed.
  5607. * @param {String} prefix Optional prefix.
  5608. * @returns {String}
  5609. * @api public
  5610. */
  5611. function querystringify(obj, prefix) {
  5612. prefix = prefix || '';
  5613.  
  5614. var pairs = [];
  5615.  
  5616. //
  5617. // Optionally prefix with a '?' if needed
  5618. //
  5619. if ('string' !== typeof prefix) prefix = '?';
  5620.  
  5621. for (var key in obj) {
  5622. if (has.call(obj, key)) {
  5623. pairs.push(encodeURIComponent(key) +'='+ encodeURIComponent(obj[key]));
  5624. }
  5625. }
  5626.  
  5627. return pairs.length ? prefix + pairs.join('&') : '';
  5628. }
  5629.  
  5630. //
  5631. // Expose the module.
  5632. //
  5633. exports.stringify = querystringify;
  5634. exports.parse = querystring;
  5635.  
  5636.  
  5637. /***/ }),
  5638. /* 27 */
  5639. /***/ (function(module, exports, __webpack_require__) {
  5640.  
  5641. "use strict";
  5642.  
  5643.  
  5644. Object.defineProperty(exports, "__esModule", {
  5645. value: true
  5646. });
  5647.  
  5648. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5649.  
  5650. var _detector = __webpack_require__(2);
  5651.  
  5652. var _detector2 = _interopRequireDefault(_detector);
  5653.  
  5654. var _cookies = __webpack_require__(5);
  5655.  
  5656. var _cookies2 = _interopRequireDefault(_cookies);
  5657.  
  5658. var _hooker = __webpack_require__(4);
  5659.  
  5660. var _hooker2 = _interopRequireDefault(_hooker);
  5661.  
  5662. var _faker = __webpack_require__(7);
  5663.  
  5664. var _faker2 = _interopRequireDefault(_faker);
  5665.  
  5666. var _logger = __webpack_require__(1);
  5667.  
  5668. var _logger2 = _interopRequireDefault(_logger);
  5669.  
  5670. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  5671.  
  5672. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  5673.  
  5674. var Mocker = function () {
  5675. function Mocker() {
  5676. _classCallCheck(this, Mocker);
  5677. }
  5678.  
  5679. _createClass(Mocker, null, [{
  5680. key: 'mock',
  5681. value: function mock() {
  5682. this.mockForBestDefintion();
  5683. this.mockAd();
  5684. this.mockVip();
  5685. this.mockLogo();
  5686. this.mockCheckPlugin();
  5687. }
  5688. }, {
  5689. key: 'mockToUseVms',
  5690. value: function mockToUseVms() {
  5691. _faker2.default.fakeChrome();
  5692. }
  5693. }, {
  5694. key: 'mockToUseM3u8',
  5695. value: function mockToUseM3u8() {
  5696. _faker2.default.fakeMacPlatform();
  5697. _faker2.default.fakeSafari();
  5698. }
  5699. }, {
  5700. key: 'mockForBestDefintion',
  5701. value: function mockForBestDefintion() {
  5702. // fall-back
  5703. if (_detector2.default.isSupportVms()) {
  5704. if (!_detector2.default.isChrome()) this.mockToUseVms(); // vms, 1080p or higher
  5705. } else if (_detector2.default.isSupportM3u8()) {
  5706. this.mockToUseM3u8(); // tmts m3u8
  5707. } else {
  5708. // by default, tmts mp4 ...
  5709. }
  5710. }
  5711. }, {
  5712. key: '_isAdReq',
  5713. value: function _isAdReq(url) {
  5714. var AD_URL = 'http://t7z.cupid.iqiyi.com/show2';
  5715. return url.indexOf(AD_URL) === 0;
  5716. }
  5717. }, {
  5718. key: 'mockAd',
  5719. value: function mockAd() {
  5720. var _this = this;
  5721.  
  5722. _hooker2.default.hookJqueryAjax(function (url, options) {
  5723. if (_this._isAdReq(url)) {
  5724. var res = _faker2.default.fakeAdRes();
  5725. (options.complete || options.success)({ responseJSON: res }, 'success');
  5726. _logger2.default.log('mocked ad request ' + url);
  5727. return true;
  5728. }
  5729. });
  5730. }
  5731. }, {
  5732. key: '_isCheckVipReq',
  5733. value: function _isCheckVipReq(url) {
  5734. var CHECK_VIP_URL = 'https://cmonitor.iqiyi.com/apis/user/check_vip.action';
  5735. return url === CHECK_VIP_URL;
  5736. }
  5737. }, {
  5738. key: '_isLogin',
  5739. value: function _isLogin() {
  5740. return !!_cookies2.default.get('P00001');
  5741. }
  5742. }, {
  5743. key: 'mockVip',
  5744. value: function mockVip() {
  5745. var _this2 = this;
  5746.  
  5747. if (!this._isLogin()) _faker2.default.fakePassportCookie();
  5748.  
  5749. _hooker2.default.hookHttpJsonp(function (options) {
  5750. var url = options.url;
  5751.  
  5752. if (_this2._isCheckVipReq(url)) {
  5753. var res = _faker2.default.fakeVipRes(options.params.authcookie);
  5754. options.success(res);
  5755. _logger2.default.log('mocked check vip request ' + url);
  5756. return true;
  5757. }
  5758. });
  5759. }
  5760. }, {
  5761. key: 'mockLogo',
  5762. value: function mockLogo() {
  5763. _hooker2.default.hookLogo(function (exports) {
  5764. return exports.prototype.showLogo = function () {};
  5765. });
  5766. }
  5767. }, {
  5768. key: 'mockCheckPlugin',
  5769. value: function mockCheckPlugin() {
  5770. _hooker2.default.hookSkinBase(function (exports) {
  5771. exports.prototype._checkPlugin = function () {};
  5772. });
  5773. }
  5774. }]);
  5775.  
  5776. return Mocker;
  5777. }();
  5778.  
  5779. exports.default = Mocker;
  5780.  
  5781. /***/ }),
  5782. /* 28 */
  5783. /***/ (function(module, exports, __webpack_require__) {
  5784.  
  5785. var __WEBPACK_AMD_DEFINE_RESULT__;/*
  5786. * JavaScript MD5
  5787. * https://github.com/blueimp/JavaScript-MD5
  5788. *
  5789. * Copyright 2011, Sebastian Tschan
  5790. * https://blueimp.net
  5791. *
  5792. * Licensed under the MIT license:
  5793. * https://opensource.org/licenses/MIT
  5794. *
  5795. * Based on
  5796. * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
  5797. * Digest Algorithm, as defined in RFC 1321.
  5798. * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
  5799. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
  5800. * Distributed under the BSD License
  5801. * See http://pajhome.org.uk/crypt/md5 for more info.
  5802. */
  5803.  
  5804. /* global define */
  5805.  
  5806. ;(function ($) {
  5807. 'use strict'
  5808.  
  5809. /*
  5810. * Add integers, wrapping at 2^32. This uses 16-bit operations internally
  5811. * to work around bugs in some JS interpreters.
  5812. */
  5813. function safeAdd (x, y) {
  5814. var lsw = (x & 0xFFFF) + (y & 0xFFFF)
  5815. var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
  5816. return (msw << 16) | (lsw & 0xFFFF)
  5817. }
  5818.  
  5819. /*
  5820. * Bitwise rotate a 32-bit number to the left.
  5821. */
  5822. function bitRotateLeft (num, cnt) {
  5823. return (num << cnt) | (num >>> (32 - cnt))
  5824. }
  5825.  
  5826. /*
  5827. * These functions implement the four basic operations the algorithm uses.
  5828. */
  5829. function md5cmn (q, a, b, x, s, t) {
  5830. return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b)
  5831. }
  5832. function md5ff (a, b, c, d, x, s, t) {
  5833. return md5cmn((b & c) | ((~b) & d), a, b, x, s, t)
  5834. }
  5835. function md5gg (a, b, c, d, x, s, t) {
  5836. return md5cmn((b & d) | (c & (~d)), a, b, x, s, t)
  5837. }
  5838. function md5hh (a, b, c, d, x, s, t) {
  5839. return md5cmn(b ^ c ^ d, a, b, x, s, t)
  5840. }
  5841. function md5ii (a, b, c, d, x, s, t) {
  5842. return md5cmn(c ^ (b | (~d)), a, b, x, s, t)
  5843. }
  5844.  
  5845. /*
  5846. * Calculate the MD5 of an array of little-endian words, and a bit length.
  5847. */
  5848. function binlMD5 (x, len) {
  5849. /* append padding */
  5850. x[len >> 5] |= 0x80 << (len % 32)
  5851. x[(((len + 64) >>> 9) << 4) + 14] = len
  5852.  
  5853. var i
  5854. var olda
  5855. var oldb
  5856. var oldc
  5857. var oldd
  5858. var a = 1732584193
  5859. var b = -271733879
  5860. var c = -1732584194
  5861. var d = 271733878
  5862.  
  5863. for (i = 0; i < x.length; i += 16) {
  5864. olda = a
  5865. oldb = b
  5866. oldc = c
  5867. oldd = d
  5868.  
  5869. a = md5ff(a, b, c, d, x[i], 7, -680876936)
  5870. d = md5ff(d, a, b, c, x[i + 1], 12, -389564586)
  5871. c = md5ff(c, d, a, b, x[i + 2], 17, 606105819)
  5872. b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330)
  5873. a = md5ff(a, b, c, d, x[i + 4], 7, -176418897)
  5874. d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426)
  5875. c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341)
  5876. b = md5ff(b, c, d, a, x[i + 7], 22, -45705983)
  5877. a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416)
  5878. d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417)
  5879. c = md5ff(c, d, a, b, x[i + 10], 17, -42063)
  5880. b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162)
  5881. a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682)
  5882. d = md5ff(d, a, b, c, x[i + 13], 12, -40341101)
  5883. c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290)
  5884. b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329)
  5885.  
  5886. a = md5gg(a, b, c, d, x[i + 1], 5, -165796510)
  5887. d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632)
  5888. c = md5gg(c, d, a, b, x[i + 11], 14, 643717713)
  5889. b = md5gg(b, c, d, a, x[i], 20, -373897302)
  5890. a = md5gg(a, b, c, d, x[i + 5], 5, -701558691)
  5891. d = md5gg(d, a, b, c, x[i + 10], 9, 38016083)
  5892. c = md5gg(c, d, a, b, x[i + 15], 14, -660478335)
  5893. b = md5gg(b, c, d, a, x[i + 4], 20, -405537848)
  5894. a = md5gg(a, b, c, d, x[i + 9], 5, 568446438)
  5895. d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690)
  5896. c = md5gg(c, d, a, b, x[i + 3], 14, -187363961)
  5897. b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501)
  5898. a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467)
  5899. d = md5gg(d, a, b, c, x[i + 2], 9, -51403784)
  5900. c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473)
  5901. b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734)
  5902.  
  5903. a = md5hh(a, b, c, d, x[i + 5], 4, -378558)
  5904. d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463)
  5905. c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562)
  5906. b = md5hh(b, c, d, a, x[i + 14], 23, -35309556)
  5907. a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060)
  5908. d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353)
  5909. c = md5hh(c, d, a, b, x[i + 7], 16, -155497632)
  5910. b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640)
  5911. a = md5hh(a, b, c, d, x[i + 13], 4, 681279174)
  5912. d = md5hh(d, a, b, c, x[i], 11, -358537222)
  5913. c = md5hh(c, d, a, b, x[i + 3], 16, -722521979)
  5914. b = md5hh(b, c, d, a, x[i + 6], 23, 76029189)
  5915. a = md5hh(a, b, c, d, x[i + 9], 4, -640364487)
  5916. d = md5hh(d, a, b, c, x[i + 12], 11, -421815835)
  5917. c = md5hh(c, d, a, b, x[i + 15], 16, 530742520)
  5918. b = md5hh(b, c, d, a, x[i + 2], 23, -995338651)
  5919.  
  5920. a = md5ii(a, b, c, d, x[i], 6, -198630844)
  5921. d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415)
  5922. c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905)
  5923. b = md5ii(b, c, d, a, x[i + 5], 21, -57434055)
  5924. a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571)
  5925. d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606)
  5926. c = md5ii(c, d, a, b, x[i + 10], 15, -1051523)
  5927. b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799)
  5928. a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359)
  5929. d = md5ii(d, a, b, c, x[i + 15], 10, -30611744)
  5930. c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380)
  5931. b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649)
  5932. a = md5ii(a, b, c, d, x[i + 4], 6, -145523070)
  5933. d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379)
  5934. c = md5ii(c, d, a, b, x[i + 2], 15, 718787259)
  5935. b = md5ii(b, c, d, a, x[i + 9], 21, -343485551)
  5936.  
  5937. a = safeAdd(a, olda)
  5938. b = safeAdd(b, oldb)
  5939. c = safeAdd(c, oldc)
  5940. d = safeAdd(d, oldd)
  5941. }
  5942. return [a, b, c, d]
  5943. }
  5944.  
  5945. /*
  5946. * Convert an array of little-endian words to a string
  5947. */
  5948. function binl2rstr (input) {
  5949. var i
  5950. var output = ''
  5951. var length32 = input.length * 32
  5952. for (i = 0; i < length32; i += 8) {
  5953. output += String.fromCharCode((input[i >> 5] >>> (i % 32)) & 0xFF)
  5954. }
  5955. return output
  5956. }
  5957.  
  5958. /*
  5959. * Convert a raw string to an array of little-endian words
  5960. * Characters >255 have their high-byte silently ignored.
  5961. */
  5962. function rstr2binl (input) {
  5963. var i
  5964. var output = []
  5965. output[(input.length >> 2) - 1] = undefined
  5966. for (i = 0; i < output.length; i += 1) {
  5967. output[i] = 0
  5968. }
  5969. var length8 = input.length * 8
  5970. for (i = 0; i < length8; i += 8) {
  5971. output[i >> 5] |= (input.charCodeAt(i / 8) & 0xFF) << (i % 32)
  5972. }
  5973. return output
  5974. }
  5975.  
  5976. /*
  5977. * Calculate the MD5 of a raw string
  5978. */
  5979. function rstrMD5 (s) {
  5980. return binl2rstr(binlMD5(rstr2binl(s), s.length * 8))
  5981. }
  5982.  
  5983. /*
  5984. * Calculate the HMAC-MD5, of a key and some data (raw strings)
  5985. */
  5986. function rstrHMACMD5 (key, data) {
  5987. var i
  5988. var bkey = rstr2binl(key)
  5989. var ipad = []
  5990. var opad = []
  5991. var hash
  5992. ipad[15] = opad[15] = undefined
  5993. if (bkey.length > 16) {
  5994. bkey = binlMD5(bkey, key.length * 8)
  5995. }
  5996. for (i = 0; i < 16; i += 1) {
  5997. ipad[i] = bkey[i] ^ 0x36363636
  5998. opad[i] = bkey[i] ^ 0x5C5C5C5C
  5999. }
  6000. hash = binlMD5(ipad.concat(rstr2binl(data)), 512 + data.length * 8)
  6001. return binl2rstr(binlMD5(opad.concat(hash), 512 + 128))
  6002. }
  6003.  
  6004. /*
  6005. * Convert a raw string to a hex string
  6006. */
  6007. function rstr2hex (input) {
  6008. var hexTab = '0123456789abcdef'
  6009. var output = ''
  6010. var x
  6011. var i
  6012. for (i = 0; i < input.length; i += 1) {
  6013. x = input.charCodeAt(i)
  6014. output += hexTab.charAt((x >>> 4) & 0x0F) +
  6015. hexTab.charAt(x & 0x0F)
  6016. }
  6017. return output
  6018. }
  6019.  
  6020. /*
  6021. * Encode a string as utf-8
  6022. */
  6023. function str2rstrUTF8 (input) {
  6024. return unescape(encodeURIComponent(input))
  6025. }
  6026.  
  6027. /*
  6028. * Take string arguments and return either raw or hex encoded strings
  6029. */
  6030. function rawMD5 (s) {
  6031. return rstrMD5(str2rstrUTF8(s))
  6032. }
  6033. function hexMD5 (s) {
  6034. return rstr2hex(rawMD5(s))
  6035. }
  6036. function rawHMACMD5 (k, d) {
  6037. return rstrHMACMD5(str2rstrUTF8(k), str2rstrUTF8(d))
  6038. }
  6039. function hexHMACMD5 (k, d) {
  6040. return rstr2hex(rawHMACMD5(k, d))
  6041. }
  6042.  
  6043. function md5 (string, key, raw) {
  6044. if (!key) {
  6045. if (!raw) {
  6046. return hexMD5(string)
  6047. }
  6048. return rawMD5(string)
  6049. }
  6050. if (!raw) {
  6051. return hexHMACMD5(key, string)
  6052. }
  6053. return rawHMACMD5(key, string)
  6054. }
  6055.  
  6056. if (true) {
  6057. !(__WEBPACK_AMD_DEFINE_RESULT__ = function () {
  6058. return md5
  6059. }.call(exports, __webpack_require__, exports, module),
  6060. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__))
  6061. } else if (typeof module === 'object' && module.exports) {
  6062. module.exports = md5
  6063. } else {
  6064. $.md5 = md5
  6065. }
  6066. }(this))
  6067.  
  6068.  
  6069. /***/ }),
  6070. /* 29 */
  6071. /***/ (function(module, exports, __webpack_require__) {
  6072.  
  6073. "use strict";
  6074.  
  6075.  
  6076. Object.defineProperty(exports, "__esModule", {
  6077. value: true
  6078. });
  6079.  
  6080. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  6081.  
  6082. var _logger = __webpack_require__(1);
  6083.  
  6084. var _logger2 = _interopRequireDefault(_logger);
  6085.  
  6086. var _detector = __webpack_require__(2);
  6087.  
  6088. var _detector2 = _interopRequireDefault(_detector);
  6089.  
  6090. var _hooker = __webpack_require__(4);
  6091.  
  6092. var _hooker2 = _interopRequireDefault(_hooker);
  6093.  
  6094. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6095.  
  6096. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  6097.  
  6098. var Patcher = function () {
  6099. function Patcher() {
  6100. _classCallCheck(this, Patcher);
  6101. }
  6102.  
  6103. _createClass(Patcher, null, [{
  6104. key: '_patchWebFullScreen',
  6105. value: function _patchWebFullScreen() {
  6106. _hooker2.default.hookWebFullScreenInit(function (that, wrapper, btn) {
  6107. btn.on('toggle', that.toggle.bind(that));
  6108. });
  6109. }
  6110. }, {
  6111. key: '_patchInitFullScreen',
  6112. value: function _patchInitFullScreen() {
  6113. this._patchWebFullScreen();
  6114.  
  6115. _hooker2.default.hookInitFullScreen(function (that) {
  6116. that.core.on('togglefullscreen', function () {
  6117. that._fullscreenBtn.fire('click', { data: null });
  6118. });
  6119.  
  6120. that.core.on('togglewebfullscreen', function () {
  6121. that._webfullscreenBtn.fire('toggle', { data: null });
  6122. });
  6123. });
  6124. }
  6125. }, {
  6126. key: '_patchPluginControls',
  6127. value: function _patchPluginControls() {
  6128. _hooker2.default.hookPluginControlsInit(function (that) {
  6129. that.core.on('showtip', function (event) {
  6130. that.setcontroltip.apply(that, [{ str: event.data, x: that._process.offset().left, y: 3, cut: true, timeout: true }]);
  6131. if (that.$plugin.hasClass('process_hidden')) {
  6132. that._controltips.css('top', '-25px');
  6133. } else if (that.$plugin.hasClass('bottom-hide')) {
  6134. that._controltips.css('top', '-38px');
  6135. }
  6136. });
  6137. });
  6138. }
  6139. }, {
  6140. key: '_obtainFlvInfo',
  6141. value: function _obtainFlvInfo() {
  6142. var _this = this;
  6143.  
  6144. _hooker2.default.hookParseData(function (that) {
  6145. return _this._flvInfo = that.flvInfo;
  6146. });
  6147. }
  6148. }, {
  6149. key: '_patchCore',
  6150. value: function _patchCore() {
  6151. var self = this;
  6152.  
  6153. this._patchPluginControls();
  6154. this._patchInitFullScreen();
  6155. this._obtainFlvInfo();
  6156.  
  6157. _hooker2.default.hookCore(function (exports) {
  6158. exports.prototype._showTip = function (msg) {
  6159. this.fire({ type: 'showtip', data: msg });
  6160. };
  6161.  
  6162. exports.prototype.getFPS = function () {
  6163. if (self._flvInfo) {
  6164. return self._flvInfo.videoConfigTag.sps.frame_rate.fps;
  6165. } else {
  6166. return 25; // f4v极速以上,动画23.976、电影24、电视剧25。
  6167. }
  6168. };
  6169.  
  6170. exports.prototype.prevFrame = function () {
  6171. var video = this.video();
  6172. var seekTime = Math.max(0, Math.min(this.getDuration(), video.currentTime - 1 / this.getFPS()));
  6173. video.currentTime = seekTime;
  6174. this._showTip('上一帧');
  6175. };
  6176.  
  6177. exports.prototype.nextFrame = function () {
  6178. var video = this.video();
  6179. var seekTime = Math.max(0, Math.min(this.getDuration(), video.currentTime + 1 / this.getFPS()));
  6180. video.currentTime = seekTime;
  6181. this._showTip('下一帧');
  6182. };
  6183.  
  6184. exports.prototype.seek = function () {
  6185. var _engine;
  6186.  
  6187. var video = this.video();
  6188. var playbackRate = video.playbackRate;
  6189. (_engine = this._engine).seek.apply(_engine, arguments);
  6190. video.playbackRate = playbackRate;
  6191. };
  6192.  
  6193. exports.prototype.stepSeek = function (stepTime) {
  6194. var seekTime = Math.max(0, Math.min(this.getDuration(), this.getCurrenttime() + stepTime));
  6195. var msg = void 0;
  6196.  
  6197. if (Math.abs(stepTime) < 60) {
  6198. msg = stepTime > 0 ? '\u6B65\u8FDB\uFF1A' + stepTime + '\u79D2' : '\u6B65\u9000\uFF1A' + Math.abs(stepTime) + '\u79D2';
  6199. } else {
  6200. msg = stepTime > 0 ? '\u6B65\u8FDB\uFF1A' + stepTime / 60 + '\u5206\u949F' : '\u6B65\u9000\uFF1A' + Math.abs(stepTime) / 60 + '\u5206\u949F';
  6201. }
  6202. this._showTip(msg);
  6203.  
  6204. this.seek(seekTime, true);
  6205. };
  6206.  
  6207. exports.prototype.rangeSeek = function (range) {
  6208. var duration = this.getDuration();
  6209. var seekTime = Math.max(0, Math.min(duration, duration * range));
  6210. this.seek(seekTime, true);
  6211. this._showTip('定位:' + (range * 100).toFixed(0) + '%');
  6212. };
  6213.  
  6214. exports.prototype.toggleMute = function () {
  6215. if (this.getMuted()) {
  6216. this.setMuted(false);
  6217. this._showTip('取消静音');
  6218. } else {
  6219. this.setMuted(true);
  6220. this._showTip('静音');
  6221. }
  6222. };
  6223.  
  6224. exports.prototype.adjustVolume = function (value) {
  6225. var volume = this.getVolume() + value;
  6226. volume = Math.max(0, Math.min(1, volume.toFixed(2)));
  6227. this.setVolume(volume);
  6228. this.fire({ type: 'keyvolumechange' });
  6229. };
  6230.  
  6231. exports.prototype.adjustPlaybackRate = function (value) {
  6232. var video = this.video();
  6233. var playbackRate = Math.max(0.2, Math.min(5, video.playbackRate + value));
  6234. video.playbackRate = playbackRate;
  6235. this._showTip('\u64AD\u653E\u901F\u7387\uFF1A' + playbackRate.toFixed(1).replace(/\.0+$/, ''));
  6236. };
  6237.  
  6238. exports.prototype.resetPlaybackRate = function () {
  6239. var video = this.video();
  6240. video.playbackRate = 1;
  6241. this._showTip('恢复播放速率');
  6242. };
  6243.  
  6244. exports.prototype.hasPrevVideo = function () {
  6245. return this._getVideoIndexInList(this._movieinfo.tvid) > 0 || this._getVideoIndexInList(this._movieinfo.oldTvid) > 0;
  6246. };
  6247.  
  6248. exports.prototype.playNext = function () {
  6249. if (this.hasNextVideo()) {
  6250. this._showTip('播放下一集');
  6251. this.switchNextVideo();
  6252. } else {
  6253. this._showTip('没有下一集哦');
  6254. }
  6255. };
  6256.  
  6257. exports.prototype.playPrev = function () {
  6258. if (this.hasPrevVideo()) {
  6259. this._showTip('播放上一集');
  6260. this.switchPreVideo();
  6261. } else {
  6262. this._showTip('没有上一集哦');
  6263. }
  6264. };
  6265. });
  6266. }
  6267. }, {
  6268. key: '_patchKeyShortcuts',
  6269. value: function _patchKeyShortcuts() {
  6270. _hooker2.default.hookPluginHotKeys(function (exports) {
  6271. exports.prototype.init = function () {
  6272. document.addEventListener('keydown', this._keydown.bind(this));
  6273. };
  6274.  
  6275. exports.prototype._isValidTarget = function (target) {
  6276. return target.nodeName === 'BODY' || target.nodeName == 'VIDEO' || target.classList.contains('pw-video'); // 全局
  6277. // return target.nodeName === 'VIDEO' || target.classList.contains('pw-video'); // 非全局
  6278. };
  6279.  
  6280. exports.prototype._keydown = function (event) {
  6281. if (!this._isValidTarget(event.target)) return;
  6282.  
  6283. switch (event.keyCode) {
  6284. case 32:
  6285. // Spacebar
  6286. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6287. if (this.core.isPaused()) {
  6288. this.core.play(true);
  6289. this.core._showTip('播放');
  6290. } else {
  6291. this.core.pause(true);
  6292. this.core._showTip('暂停');
  6293. }
  6294. } else {
  6295. return;
  6296. }
  6297. break;
  6298. case 39: // → Arrow Right
  6299. case 37:
  6300. {
  6301. // ← Arrow Left
  6302. var stepTime = void 0;
  6303. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6304. stepTime = 39 === event.keyCode ? 5 : -5;
  6305. } else if (event.ctrlKey && !event.shiftKey && !event.altKey) {
  6306. stepTime = 39 === event.keyCode ? 30 : -30;
  6307. } else if (!event.ctrlKey && event.shiftKey && !event.altKey) {
  6308. stepTime = 39 === event.keyCode ? 60 : -60;
  6309. } else if (event.ctrlKey && !event.shiftKey && event.altKey) {
  6310. stepTime = 39 === event.keyCode ? 3e2 : -3e2; // 5分钟
  6311. } else {
  6312. return;
  6313. }
  6314.  
  6315. this.core.stepSeek(stepTime);
  6316. break;
  6317. }
  6318. case 38: // ↑ Arrow Up
  6319. case 40:
  6320. // ↓ Arrow Down
  6321. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6322. this.core.adjustVolume(38 === event.keyCode ? 0.05 : -0.05);
  6323. } else {
  6324. return;
  6325. }
  6326. break;
  6327. case 77:
  6328. // M
  6329. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6330. this.core.toggleMute();
  6331. } else {
  6332. return;
  6333. }
  6334. break;
  6335. case 13:
  6336. // Enter
  6337. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6338. this.core.fire({ type: 'togglefullscreen' });
  6339. } else if (event.ctrlKey && !event.shiftKey && !event.altKey) {
  6340. this.core.fire({ type: 'togglewebfullscreen' });
  6341. } else {
  6342. return;
  6343. }
  6344. break;
  6345. case 67: // C
  6346. case 88:
  6347. // X
  6348. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6349. this.core.adjustPlaybackRate(67 === event.keyCode ? 0.1 : -0.1);
  6350. } else {
  6351. return;
  6352. }
  6353. break;
  6354. case 90:
  6355. // Z
  6356. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6357. this.core.resetPlaybackRate();
  6358. } else {
  6359. return;
  6360. }
  6361. break;
  6362. case 68: // D
  6363. case 70:
  6364. // F
  6365. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6366. this.core.pause(true);
  6367. if (event.keyCode === 68) {
  6368. this.core.prevFrame();
  6369. } else {
  6370. this.core.nextFrame();
  6371. }
  6372. } else {
  6373. return;
  6374. }
  6375. break;
  6376. case 80: // P
  6377. case 78:
  6378. // N
  6379. if (!event.ctrlKey && event.shiftKey && !event.altKey) {
  6380. if (event.keyCode === 78) {
  6381. this.core.playNext();
  6382. } else {
  6383. this.core.playPrev();
  6384. }
  6385. } else {
  6386. return;
  6387. }
  6388. break;
  6389. default:
  6390. if (event.keyCode >= 48 && event.keyCode <= 57) {
  6391. // 0 ~ 9
  6392. if (!event.ctrlKey && !event.shiftKey && !event.altKey) {
  6393. this.core.rangeSeek((event.keyCode - 48) * 0.1);
  6394. } else {
  6395. return;
  6396. }
  6397. } else {
  6398. return;
  6399. }
  6400. }
  6401.  
  6402. event.preventDefault();
  6403. event.stopPropagation();
  6404. };
  6405.  
  6406. _logger2.default.log('添加键盘快捷键');
  6407. });
  6408. }
  6409. }, {
  6410. key: '_patchMouseShortcuts',
  6411. value: function _patchMouseShortcuts() {
  6412. _hooker2.default.hookPluginControlsInit(function (that) {
  6413. document.addEventListener('wheel', function (event) {
  6414. if (!_detector2.default.isFullScreen()) return;
  6415.  
  6416. var delta = event.wheelDelta || event.detail || event.deltaY && -event.deltaY;
  6417. that.core.adjustVolume(delta > 0 ? 0.05 : -0.05);
  6418. });
  6419.  
  6420. _logger2.default.log('添加鼠标快捷键');
  6421. });
  6422. }
  6423. }, {
  6424. key: 'patchShortcuts',
  6425. value: function patchShortcuts() {
  6426. this._patchCore();
  6427.  
  6428. this._patchKeyShortcuts();
  6429. this._patchMouseShortcuts();
  6430. }
  6431. }]);
  6432.  
  6433. return Patcher;
  6434. }();
  6435.  
  6436. exports.default = Patcher;
  6437.  
  6438. /***/ }),
  6439. /* 30 */
  6440. /***/ (function(module, exports, __webpack_require__) {
  6441.  
  6442. "use strict";
  6443.  
  6444.  
  6445. Object.defineProperty(exports, "__esModule", {
  6446. value: true
  6447. });
  6448. exports.adaptIframe = exports.replaceFlash = undefined;
  6449.  
  6450. var _regenerator = __webpack_require__(31);
  6451.  
  6452. var _regenerator2 = _interopRequireDefault(_regenerator);
  6453.  
  6454. var embedSrc = function () {
  6455. var _ref = _asyncToGenerator(_regenerator2.default.mark(function _callee(targetNode, _ref2) {
  6456. var tvid = _ref2.tvid,
  6457. vid = _ref2.vid;
  6458. var url;
  6459. return _regenerator2.default.wrap(function _callee$(_context) {
  6460. while (1) {
  6461. switch (_context.prev = _context.next) {
  6462. case 0:
  6463. targetNode.innerHTML = '<div class="' + GM_info.script.name + ' info">\u6B63\u5728\u83B7\u53D6\u89C6\u9891\u6E90...</div>';
  6464.  
  6465. _context.prev = 1;
  6466. _context.next = 4;
  6467. return (0, _utils.getVideoUrl)(tvid, vid);
  6468.  
  6469. case 4:
  6470. url = _context.sent;
  6471.  
  6472. _logger2.default.log('source url: %s', url);
  6473. targetNode.innerHTML = '<iframe id="innerFrame" src="' + url + '" frameborder="0" allowfullscreen="true" width="100%" height="100%"></iframe>';
  6474. _context.next = 12;
  6475. break;
  6476.  
  6477. case 9:
  6478. _context.prev = 9;
  6479. _context.t0 = _context['catch'](1);
  6480.  
  6481. targetNode.innerHTML = '<div class="' + GM_info.script.name + ' error"><p>\u83B7\u53D6\u89C6\u9891\u6E90\u51FA\u9519\uFF01</p><p>' + _context.t0.message + '</p></div>';
  6482.  
  6483. case 12:
  6484. case 'end':
  6485. return _context.stop();
  6486. }
  6487. }
  6488. }, _callee, this, [[1, 9]]);
  6489. }));
  6490.  
  6491. return function embedSrc(_x, _x2) {
  6492. return _ref.apply(this, arguments);
  6493. };
  6494. }();
  6495.  
  6496. var _logger = __webpack_require__(1);
  6497.  
  6498. var _logger2 = _interopRequireDefault(_logger);
  6499.  
  6500. var _hooker = __webpack_require__(4);
  6501.  
  6502. var _hooker2 = _interopRequireDefault(_hooker);
  6503.  
  6504. var _faker = __webpack_require__(7);
  6505.  
  6506. var _faker2 = _interopRequireDefault(_faker);
  6507.  
  6508. var _detector = __webpack_require__(2);
  6509.  
  6510. var _detector2 = _interopRequireDefault(_detector);
  6511.  
  6512. var _utils = __webpack_require__(34);
  6513.  
  6514. function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
  6515.  
  6516. function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
  6517.  
  6518. function replaceFlash() {
  6519. if (!_detector2.default.hasFlashPlugin()) _faker2.default.fakeFlashPlugin();
  6520.  
  6521. var observer = new MutationObserver(function (records, self) {
  6522. var _iteratorNormalCompletion = true;
  6523. var _didIteratorError = false;
  6524. var _iteratorError = undefined;
  6525.  
  6526. try {
  6527. for (var _iterator = records[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  6528. var record = _step.value;
  6529.  
  6530. if (record.type !== 'childList' || !record.addedNodes) continue;
  6531.  
  6532. var _iteratorNormalCompletion2 = true;
  6533. var _didIteratorError2 = false;
  6534. var _iteratorError2 = undefined;
  6535.  
  6536. try {
  6537. for (var _iterator2 = record.addedNodes[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  6538. var node = _step2.value;
  6539.  
  6540. if (node.nodeName !== 'OBJECT' && node.nodeName !== 'EMBED') continue;
  6541. _logger2.default.log('finded node', node);
  6542.  
  6543. var text = node.outerHTML;
  6544. var vid = (0, _utils.findVid)(text);
  6545. var tvid = (0, _utils.findTvid)(text);
  6546.  
  6547. if (tvid && vid) {
  6548. _logger2.default.log('finded tvid: %s, vid: %s', tvid, vid);
  6549. embedSrc(node.parentNode, { tvid: tvid, vid: vid });
  6550. self.disconnect();
  6551. _logger2.default.log('stoped observation');
  6552. }
  6553. }
  6554. } catch (err) {
  6555. _didIteratorError2 = true;
  6556. _iteratorError2 = err;
  6557. } finally {
  6558. try {
  6559. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  6560. _iterator2.return();
  6561. }
  6562. } finally {
  6563. if (_didIteratorError2) {
  6564. throw _iteratorError2;
  6565. }
  6566. }
  6567. }
  6568. }
  6569. } catch (err) {
  6570. _didIteratorError = true;
  6571. _iteratorError = err;
  6572. } finally {
  6573. try {
  6574. if (!_iteratorNormalCompletion && _iterator.return) {
  6575. _iterator.return();
  6576. }
  6577. } finally {
  6578. if (_didIteratorError) {
  6579. throw _iteratorError;
  6580. }
  6581. }
  6582. }
  6583. });
  6584.  
  6585. observer.observe(document.body || document.documentElement, { subtree: true, childList: true });
  6586. _logger2.default.log('started observation');
  6587. }
  6588.  
  6589. function adaptIframe() {
  6590. var style = '\n body[class|="qypage"] {\n overflow: hidden !important;\n background: #000 !important;\n visibility: hidden;\n }\n\n .mod-func {\n display: none !important;\n }\n\n .' + GM_info.script.name + '.info {\n width: 20em;\n height: 5em;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n margin: auto;\n text-align: center;\n line-height: 5em;\n font-size: 1em;\n color: #ccc;\n }\n\n .' + GM_info.script.name + '.error {\n height: 3em;\n position: absolute;\n top: 0;\n bottom: 0;\n left: 0;\n right: 0;\n margin: auto;\n text-align: center;\n font-size: 1em;\n color: #c00;\n }\n ';
  6591.  
  6592. GM_addStyle(style);
  6593.  
  6594. _hooker2.default.hookWebFullScreen(function (exports) {
  6595. var init = exports.__proto__.init;
  6596. exports.__proto__.init = function (wrapper, btn) {
  6597. init.apply(this, [wrapper, btn]);
  6598. this.enter();
  6599.  
  6600. btn[0].style.display = 'none';
  6601. document.body.style.visibility = 'visible';
  6602. };
  6603.  
  6604. exports.__proto__.exit = function () {};
  6605. });
  6606.  
  6607. _hooker2.default.hookCore(function (exports) {
  6608. exports.prototype.hasNextVideo = function () {
  6609. return null;
  6610. };
  6611. });
  6612. }
  6613.  
  6614. exports.replaceFlash = replaceFlash;
  6615. exports.adaptIframe = adaptIframe;
  6616.  
  6617. /***/ }),
  6618. /* 31 */
  6619. /***/ (function(module, exports, __webpack_require__) {
  6620.  
  6621. module.exports = __webpack_require__(32);
  6622.  
  6623.  
  6624. /***/ }),
  6625. /* 32 */
  6626. /***/ (function(module, exports, __webpack_require__) {
  6627.  
  6628. /* WEBPACK VAR INJECTION */(function(global) {// This method of obtaining a reference to the global object needs to be
  6629. // kept identical to the way it is obtained in runtime.js
  6630. var g =
  6631. typeof global === "object" ? global :
  6632. typeof window === "object" ? window :
  6633. typeof self === "object" ? self : this;
  6634.  
  6635. // Use `getOwnPropertyNames` because not all browsers support calling
  6636. // `hasOwnProperty` on the global `self` object in a worker. See #183.
  6637. var hadRuntime = g.regeneratorRuntime &&
  6638. Object.getOwnPropertyNames(g).indexOf("regeneratorRuntime") >= 0;
  6639.  
  6640. // Save the old regeneratorRuntime in case it needs to be restored later.
  6641. var oldRuntime = hadRuntime && g.regeneratorRuntime;
  6642.  
  6643. // Force reevalutation of runtime.js.
  6644. g.regeneratorRuntime = undefined;
  6645.  
  6646. module.exports = __webpack_require__(33);
  6647.  
  6648. if (hadRuntime) {
  6649. // Restore the original runtime.
  6650. g.regeneratorRuntime = oldRuntime;
  6651. } else {
  6652. // Remove the global property added by runtime.js.
  6653. try {
  6654. delete g.regeneratorRuntime;
  6655. } catch(e) {
  6656. g.regeneratorRuntime = undefined;
  6657. }
  6658. }
  6659.  
  6660. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  6661.  
  6662. /***/ }),
  6663. /* 33 */
  6664. /***/ (function(module, exports, __webpack_require__) {
  6665.  
  6666. /* WEBPACK VAR INJECTION */(function(global) {/**
  6667. * Copyright (c) 2014, Facebook, Inc.
  6668. * All rights reserved.
  6669. *
  6670. * This source code is licensed under the BSD-style license found in the
  6671. * https://raw.github.com/facebook/regenerator/master/LICENSE file. An
  6672. * additional grant of patent rights can be found in the PATENTS file in
  6673. * the same directory.
  6674. */
  6675.  
  6676. !(function(global) {
  6677. "use strict";
  6678.  
  6679. var Op = Object.prototype;
  6680. var hasOwn = Op.hasOwnProperty;
  6681. var undefined; // More compressible than void 0.
  6682. var $Symbol = typeof Symbol === "function" ? Symbol : {};
  6683. var iteratorSymbol = $Symbol.iterator || "@@iterator";
  6684. var asyncIteratorSymbol = $Symbol.asyncIterator || "@@asyncIterator";
  6685. var toStringTagSymbol = $Symbol.toStringTag || "@@toStringTag";
  6686.  
  6687. var inModule = typeof module === "object";
  6688. var runtime = global.regeneratorRuntime;
  6689. if (runtime) {
  6690. if (inModule) {
  6691. // If regeneratorRuntime is defined globally and we're in a module,
  6692. // make the exports object identical to regeneratorRuntime.
  6693. module.exports = runtime;
  6694. }
  6695. // Don't bother evaluating the rest of this file if the runtime was
  6696. // already defined globally.
  6697. return;
  6698. }
  6699.  
  6700. // Define the runtime globally (as expected by generated code) as either
  6701. // module.exports (if we're in a module) or a new, empty object.
  6702. runtime = global.regeneratorRuntime = inModule ? module.exports : {};
  6703.  
  6704. function wrap(innerFn, outerFn, self, tryLocsList) {
  6705. // If outerFn provided and outerFn.prototype is a Generator, then outerFn.prototype instanceof Generator.
  6706. var protoGenerator = outerFn && outerFn.prototype instanceof Generator ? outerFn : Generator;
  6707. var generator = Object.create(protoGenerator.prototype);
  6708. var context = new Context(tryLocsList || []);
  6709.  
  6710. // The ._invoke method unifies the implementations of the .next,
  6711. // .throw, and .return methods.
  6712. generator._invoke = makeInvokeMethod(innerFn, self, context);
  6713.  
  6714. return generator;
  6715. }
  6716. runtime.wrap = wrap;
  6717.  
  6718. // Try/catch helper to minimize deoptimizations. Returns a completion
  6719. // record like context.tryEntries[i].completion. This interface could
  6720. // have been (and was previously) designed to take a closure to be
  6721. // invoked without arguments, but in all the cases we care about we
  6722. // already have an existing method we want to call, so there's no need
  6723. // to create a new function object. We can even get away with assuming
  6724. // the method takes exactly one argument, since that happens to be true
  6725. // in every case, so we don't have to touch the arguments object. The
  6726. // only additional allocation required is the completion record, which
  6727. // has a stable shape and so hopefully should be cheap to allocate.
  6728. function tryCatch(fn, obj, arg) {
  6729. try {
  6730. return { type: "normal", arg: fn.call(obj, arg) };
  6731. } catch (err) {
  6732. return { type: "throw", arg: err };
  6733. }
  6734. }
  6735.  
  6736. var GenStateSuspendedStart = "suspendedStart";
  6737. var GenStateSuspendedYield = "suspendedYield";
  6738. var GenStateExecuting = "executing";
  6739. var GenStateCompleted = "completed";
  6740.  
  6741. // Returning this object from the innerFn has the same effect as
  6742. // breaking out of the dispatch switch statement.
  6743. var ContinueSentinel = {};
  6744.  
  6745. // Dummy constructor functions that we use as the .constructor and
  6746. // .constructor.prototype properties for functions that return Generator
  6747. // objects. For full spec compliance, you may wish to configure your
  6748. // minifier not to mangle the names of these two functions.
  6749. function Generator() {}
  6750. function GeneratorFunction() {}
  6751. function GeneratorFunctionPrototype() {}
  6752.  
  6753. // This is a polyfill for %IteratorPrototype% for environments that
  6754. // don't natively support it.
  6755. var IteratorPrototype = {};
  6756. IteratorPrototype[iteratorSymbol] = function () {
  6757. return this;
  6758. };
  6759.  
  6760. var getProto = Object.getPrototypeOf;
  6761. var NativeIteratorPrototype = getProto && getProto(getProto(values([])));
  6762. if (NativeIteratorPrototype &&
  6763. NativeIteratorPrototype !== Op &&
  6764. hasOwn.call(NativeIteratorPrototype, iteratorSymbol)) {
  6765. // This environment has a native %IteratorPrototype%; use it instead
  6766. // of the polyfill.
  6767. IteratorPrototype = NativeIteratorPrototype;
  6768. }
  6769.  
  6770. var Gp = GeneratorFunctionPrototype.prototype =
  6771. Generator.prototype = Object.create(IteratorPrototype);
  6772. GeneratorFunction.prototype = Gp.constructor = GeneratorFunctionPrototype;
  6773. GeneratorFunctionPrototype.constructor = GeneratorFunction;
  6774. GeneratorFunctionPrototype[toStringTagSymbol] =
  6775. GeneratorFunction.displayName = "GeneratorFunction";
  6776.  
  6777. // Helper for defining the .next, .throw, and .return methods of the
  6778. // Iterator interface in terms of a single ._invoke method.
  6779. function defineIteratorMethods(prototype) {
  6780. ["next", "throw", "return"].forEach(function(method) {
  6781. prototype[method] = function(arg) {
  6782. return this._invoke(method, arg);
  6783. };
  6784. });
  6785. }
  6786.  
  6787. runtime.isGeneratorFunction = function(genFun) {
  6788. var ctor = typeof genFun === "function" && genFun.constructor;
  6789. return ctor
  6790. ? ctor === GeneratorFunction ||
  6791. // For the native GeneratorFunction constructor, the best we can
  6792. // do is to check its .name property.
  6793. (ctor.displayName || ctor.name) === "GeneratorFunction"
  6794. : false;
  6795. };
  6796.  
  6797. runtime.mark = function(genFun) {
  6798. if (Object.setPrototypeOf) {
  6799. Object.setPrototypeOf(genFun, GeneratorFunctionPrototype);
  6800. } else {
  6801. genFun.__proto__ = GeneratorFunctionPrototype;
  6802. if (!(toStringTagSymbol in genFun)) {
  6803. genFun[toStringTagSymbol] = "GeneratorFunction";
  6804. }
  6805. }
  6806. genFun.prototype = Object.create(Gp);
  6807. return genFun;
  6808. };
  6809.  
  6810. // Within the body of any async function, `await x` is transformed to
  6811. // `yield regeneratorRuntime.awrap(x)`, so that the runtime can test
  6812. // `hasOwn.call(value, "__await")` to determine if the yielded value is
  6813. // meant to be awaited.
  6814. runtime.awrap = function(arg) {
  6815. return { __await: arg };
  6816. };
  6817.  
  6818. function AsyncIterator(generator) {
  6819. function invoke(method, arg, resolve, reject) {
  6820. var record = tryCatch(generator[method], generator, arg);
  6821. if (record.type === "throw") {
  6822. reject(record.arg);
  6823. } else {
  6824. var result = record.arg;
  6825. var value = result.value;
  6826. if (value &&
  6827. typeof value === "object" &&
  6828. hasOwn.call(value, "__await")) {
  6829. return Promise.resolve(value.__await).then(function(value) {
  6830. invoke("next", value, resolve, reject);
  6831. }, function(err) {
  6832. invoke("throw", err, resolve, reject);
  6833. });
  6834. }
  6835.  
  6836. return Promise.resolve(value).then(function(unwrapped) {
  6837. // When a yielded Promise is resolved, its final value becomes
  6838. // the .value of the Promise<{value,done}> result for the
  6839. // current iteration. If the Promise is rejected, however, the
  6840. // result for this iteration will be rejected with the same
  6841. // reason. Note that rejections of yielded Promises are not
  6842. // thrown back into the generator function, as is the case
  6843. // when an awaited Promise is rejected. This difference in
  6844. // behavior between yield and await is important, because it
  6845. // allows the consumer to decide what to do with the yielded
  6846. // rejection (swallow it and continue, manually .throw it back
  6847. // into the generator, abandon iteration, whatever). With
  6848. // await, by contrast, there is no opportunity to examine the
  6849. // rejection reason outside the generator function, so the
  6850. // only option is to throw it from the await expression, and
  6851. // let the generator function handle the exception.
  6852. result.value = unwrapped;
  6853. resolve(result);
  6854. }, reject);
  6855. }
  6856. }
  6857.  
  6858. if (typeof global.process === "object" && global.process.domain) {
  6859. invoke = global.process.domain.bind(invoke);
  6860. }
  6861.  
  6862. var previousPromise;
  6863.  
  6864. function enqueue(method, arg) {
  6865. function callInvokeWithMethodAndArg() {
  6866. return new Promise(function(resolve, reject) {
  6867. invoke(method, arg, resolve, reject);
  6868. });
  6869. }
  6870.  
  6871. return previousPromise =
  6872. // If enqueue has been called before, then we want to wait until
  6873. // all previous Promises have been resolved before calling invoke,
  6874. // so that results are always delivered in the correct order. If
  6875. // enqueue has not been called before, then it is important to
  6876. // call invoke immediately, without waiting on a callback to fire,
  6877. // so that the async generator function has the opportunity to do
  6878. // any necessary setup in a predictable way. This predictability
  6879. // is why the Promise constructor synchronously invokes its
  6880. // executor callback, and why async functions synchronously
  6881. // execute code before the first await. Since we implement simple
  6882. // async functions in terms of async generators, it is especially
  6883. // important to get this right, even though it requires care.
  6884. previousPromise ? previousPromise.then(
  6885. callInvokeWithMethodAndArg,
  6886. // Avoid propagating failures to Promises returned by later
  6887. // invocations of the iterator.
  6888. callInvokeWithMethodAndArg
  6889. ) : callInvokeWithMethodAndArg();
  6890. }
  6891.  
  6892. // Define the unified helper method that is used to implement .next,
  6893. // .throw, and .return (see defineIteratorMethods).
  6894. this._invoke = enqueue;
  6895. }
  6896.  
  6897. defineIteratorMethods(AsyncIterator.prototype);
  6898. AsyncIterator.prototype[asyncIteratorSymbol] = function () {
  6899. return this;
  6900. };
  6901. runtime.AsyncIterator = AsyncIterator;
  6902.  
  6903. // Note that simple async functions are implemented on top of
  6904. // AsyncIterator objects; they just return a Promise for the value of
  6905. // the final result produced by the iterator.
  6906. runtime.async = function(innerFn, outerFn, self, tryLocsList) {
  6907. var iter = new AsyncIterator(
  6908. wrap(innerFn, outerFn, self, tryLocsList)
  6909. );
  6910.  
  6911. return runtime.isGeneratorFunction(outerFn)
  6912. ? iter // If outerFn is a generator, return the full iterator.
  6913. : iter.next().then(function(result) {
  6914. return result.done ? result.value : iter.next();
  6915. });
  6916. };
  6917.  
  6918. function makeInvokeMethod(innerFn, self, context) {
  6919. var state = GenStateSuspendedStart;
  6920.  
  6921. return function invoke(method, arg) {
  6922. if (state === GenStateExecuting) {
  6923. throw new Error("Generator is already running");
  6924. }
  6925.  
  6926. if (state === GenStateCompleted) {
  6927. if (method === "throw") {
  6928. throw arg;
  6929. }
  6930.  
  6931. // Be forgiving, per 25.3.3.3.3 of the spec:
  6932. // https://people.mozilla.org/~jorendorff/es6-draft.html#sec-generatorresume
  6933. return doneResult();
  6934. }
  6935.  
  6936. context.method = method;
  6937. context.arg = arg;
  6938.  
  6939. while (true) {
  6940. var delegate = context.delegate;
  6941. if (delegate) {
  6942. var delegateResult = maybeInvokeDelegate(delegate, context);
  6943. if (delegateResult) {
  6944. if (delegateResult === ContinueSentinel) continue;
  6945. return delegateResult;
  6946. }
  6947. }
  6948.  
  6949. if (context.method === "next") {
  6950. // Setting context._sent for legacy support of Babel's
  6951. // function.sent implementation.
  6952. context.sent = context._sent = context.arg;
  6953.  
  6954. } else if (context.method === "throw") {
  6955. if (state === GenStateSuspendedStart) {
  6956. state = GenStateCompleted;
  6957. throw context.arg;
  6958. }
  6959.  
  6960. context.dispatchException(context.arg);
  6961.  
  6962. } else if (context.method === "return") {
  6963. context.abrupt("return", context.arg);
  6964. }
  6965.  
  6966. state = GenStateExecuting;
  6967.  
  6968. var record = tryCatch(innerFn, self, context);
  6969. if (record.type === "normal") {
  6970. // If an exception is thrown from innerFn, we leave state ===
  6971. // GenStateExecuting and loop back for another invocation.
  6972. state = context.done
  6973. ? GenStateCompleted
  6974. : GenStateSuspendedYield;
  6975.  
  6976. if (record.arg === ContinueSentinel) {
  6977. continue;
  6978. }
  6979.  
  6980. return {
  6981. value: record.arg,
  6982. done: context.done
  6983. };
  6984.  
  6985. } else if (record.type === "throw") {
  6986. state = GenStateCompleted;
  6987. // Dispatch the exception by looping back around to the
  6988. // context.dispatchException(context.arg) call above.
  6989. context.method = "throw";
  6990. context.arg = record.arg;
  6991. }
  6992. }
  6993. };
  6994. }
  6995.  
  6996. // Call delegate.iterator[context.method](context.arg) and handle the
  6997. // result, either by returning a { value, done } result from the
  6998. // delegate iterator, or by modifying context.method and context.arg,
  6999. // setting context.delegate to null, and returning the ContinueSentinel.
  7000. function maybeInvokeDelegate(delegate, context) {
  7001. var method = delegate.iterator[context.method];
  7002. if (method === undefined) {
  7003. // A .throw or .return when the delegate iterator has no .throw
  7004. // method always terminates the yield* loop.
  7005. context.delegate = null;
  7006.  
  7007. if (context.method === "throw") {
  7008. if (delegate.iterator.return) {
  7009. // If the delegate iterator has a return method, give it a
  7010. // chance to clean up.
  7011. context.method = "return";
  7012. context.arg = undefined;
  7013. maybeInvokeDelegate(delegate, context);
  7014.  
  7015. if (context.method === "throw") {
  7016. // If maybeInvokeDelegate(context) changed context.method from
  7017. // "return" to "throw", let that override the TypeError below.
  7018. return ContinueSentinel;
  7019. }
  7020. }
  7021.  
  7022. context.method = "throw";
  7023. context.arg = new TypeError(
  7024. "The iterator does not provide a 'throw' method");
  7025. }
  7026.  
  7027. return ContinueSentinel;
  7028. }
  7029.  
  7030. var record = tryCatch(method, delegate.iterator, context.arg);
  7031.  
  7032. if (record.type === "throw") {
  7033. context.method = "throw";
  7034. context.arg = record.arg;
  7035. context.delegate = null;
  7036. return ContinueSentinel;
  7037. }
  7038.  
  7039. var info = record.arg;
  7040.  
  7041. if (! info) {
  7042. context.method = "throw";
  7043. context.arg = new TypeError("iterator result is not an object");
  7044. context.delegate = null;
  7045. return ContinueSentinel;
  7046. }
  7047.  
  7048. if (info.done) {
  7049. // Assign the result of the finished delegate to the temporary
  7050. // variable specified by delegate.resultName (see delegateYield).
  7051. context[delegate.resultName] = info.value;
  7052.  
  7053. // Resume execution at the desired location (see delegateYield).
  7054. context.next = delegate.nextLoc;
  7055.  
  7056. // If context.method was "throw" but the delegate handled the
  7057. // exception, let the outer generator proceed normally. If
  7058. // context.method was "next", forget context.arg since it has been
  7059. // "consumed" by the delegate iterator. If context.method was
  7060. // "return", allow the original .return call to continue in the
  7061. // outer generator.
  7062. if (context.method !== "return") {
  7063. context.method = "next";
  7064. context.arg = undefined;
  7065. }
  7066.  
  7067. } else {
  7068. // Re-yield the result returned by the delegate method.
  7069. return info;
  7070. }
  7071.  
  7072. // The delegate iterator is finished, so forget it and continue with
  7073. // the outer generator.
  7074. context.delegate = null;
  7075. return ContinueSentinel;
  7076. }
  7077.  
  7078. // Define Generator.prototype.{next,throw,return} in terms of the
  7079. // unified ._invoke helper method.
  7080. defineIteratorMethods(Gp);
  7081.  
  7082. Gp[toStringTagSymbol] = "Generator";
  7083.  
  7084. // A Generator should always return itself as the iterator object when the
  7085. // @@iterator function is called on it. Some browsers' implementations of the
  7086. // iterator prototype chain incorrectly implement this, causing the Generator
  7087. // object to not be returned from this call. This ensures that doesn't happen.
  7088. // See https://github.com/facebook/regenerator/issues/274 for more details.
  7089. Gp[iteratorSymbol] = function() {
  7090. return this;
  7091. };
  7092.  
  7093. Gp.toString = function() {
  7094. return "[object Generator]";
  7095. };
  7096.  
  7097. function pushTryEntry(locs) {
  7098. var entry = { tryLoc: locs[0] };
  7099.  
  7100. if (1 in locs) {
  7101. entry.catchLoc = locs[1];
  7102. }
  7103.  
  7104. if (2 in locs) {
  7105. entry.finallyLoc = locs[2];
  7106. entry.afterLoc = locs[3];
  7107. }
  7108.  
  7109. this.tryEntries.push(entry);
  7110. }
  7111.  
  7112. function resetTryEntry(entry) {
  7113. var record = entry.completion || {};
  7114. record.type = "normal";
  7115. delete record.arg;
  7116. entry.completion = record;
  7117. }
  7118.  
  7119. function Context(tryLocsList) {
  7120. // The root entry object (effectively a try statement without a catch
  7121. // or a finally block) gives us a place to store values thrown from
  7122. // locations where there is no enclosing try statement.
  7123. this.tryEntries = [{ tryLoc: "root" }];
  7124. tryLocsList.forEach(pushTryEntry, this);
  7125. this.reset(true);
  7126. }
  7127.  
  7128. runtime.keys = function(object) {
  7129. var keys = [];
  7130. for (var key in object) {
  7131. keys.push(key);
  7132. }
  7133. keys.reverse();
  7134.  
  7135. // Rather than returning an object with a next method, we keep
  7136. // things simple and return the next function itself.
  7137. return function next() {
  7138. while (keys.length) {
  7139. var key = keys.pop();
  7140. if (key in object) {
  7141. next.value = key;
  7142. next.done = false;
  7143. return next;
  7144. }
  7145. }
  7146.  
  7147. // To avoid creating an additional object, we just hang the .value
  7148. // and .done properties off the next function object itself. This
  7149. // also ensures that the minifier will not anonymize the function.
  7150. next.done = true;
  7151. return next;
  7152. };
  7153. };
  7154.  
  7155. function values(iterable) {
  7156. if (iterable) {
  7157. var iteratorMethod = iterable[iteratorSymbol];
  7158. if (iteratorMethod) {
  7159. return iteratorMethod.call(iterable);
  7160. }
  7161.  
  7162. if (typeof iterable.next === "function") {
  7163. return iterable;
  7164. }
  7165.  
  7166. if (!isNaN(iterable.length)) {
  7167. var i = -1, next = function next() {
  7168. while (++i < iterable.length) {
  7169. if (hasOwn.call(iterable, i)) {
  7170. next.value = iterable[i];
  7171. next.done = false;
  7172. return next;
  7173. }
  7174. }
  7175.  
  7176. next.value = undefined;
  7177. next.done = true;
  7178.  
  7179. return next;
  7180. };
  7181.  
  7182. return next.next = next;
  7183. }
  7184. }
  7185.  
  7186. // Return an iterator with no values.
  7187. return { next: doneResult };
  7188. }
  7189. runtime.values = values;
  7190.  
  7191. function doneResult() {
  7192. return { value: undefined, done: true };
  7193. }
  7194.  
  7195. Context.prototype = {
  7196. constructor: Context,
  7197.  
  7198. reset: function(skipTempReset) {
  7199. this.prev = 0;
  7200. this.next = 0;
  7201. // Resetting context._sent for legacy support of Babel's
  7202. // function.sent implementation.
  7203. this.sent = this._sent = undefined;
  7204. this.done = false;
  7205. this.delegate = null;
  7206.  
  7207. this.method = "next";
  7208. this.arg = undefined;
  7209.  
  7210. this.tryEntries.forEach(resetTryEntry);
  7211.  
  7212. if (!skipTempReset) {
  7213. for (var name in this) {
  7214. // Not sure about the optimal order of these conditions:
  7215. if (name.charAt(0) === "t" &&
  7216. hasOwn.call(this, name) &&
  7217. !isNaN(+name.slice(1))) {
  7218. this[name] = undefined;
  7219. }
  7220. }
  7221. }
  7222. },
  7223.  
  7224. stop: function() {
  7225. this.done = true;
  7226.  
  7227. var rootEntry = this.tryEntries[0];
  7228. var rootRecord = rootEntry.completion;
  7229. if (rootRecord.type === "throw") {
  7230. throw rootRecord.arg;
  7231. }
  7232.  
  7233. return this.rval;
  7234. },
  7235.  
  7236. dispatchException: function(exception) {
  7237. if (this.done) {
  7238. throw exception;
  7239. }
  7240.  
  7241. var context = this;
  7242. function handle(loc, caught) {
  7243. record.type = "throw";
  7244. record.arg = exception;
  7245. context.next = loc;
  7246.  
  7247. if (caught) {
  7248. // If the dispatched exception was caught by a catch block,
  7249. // then let that catch block handle the exception normally.
  7250. context.method = "next";
  7251. context.arg = undefined;
  7252. }
  7253.  
  7254. return !! caught;
  7255. }
  7256.  
  7257. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  7258. var entry = this.tryEntries[i];
  7259. var record = entry.completion;
  7260.  
  7261. if (entry.tryLoc === "root") {
  7262. // Exception thrown outside of any try block that could handle
  7263. // it, so set the completion value of the entire function to
  7264. // throw the exception.
  7265. return handle("end");
  7266. }
  7267.  
  7268. if (entry.tryLoc <= this.prev) {
  7269. var hasCatch = hasOwn.call(entry, "catchLoc");
  7270. var hasFinally = hasOwn.call(entry, "finallyLoc");
  7271.  
  7272. if (hasCatch && hasFinally) {
  7273. if (this.prev < entry.catchLoc) {
  7274. return handle(entry.catchLoc, true);
  7275. } else if (this.prev < entry.finallyLoc) {
  7276. return handle(entry.finallyLoc);
  7277. }
  7278.  
  7279. } else if (hasCatch) {
  7280. if (this.prev < entry.catchLoc) {
  7281. return handle(entry.catchLoc, true);
  7282. }
  7283.  
  7284. } else if (hasFinally) {
  7285. if (this.prev < entry.finallyLoc) {
  7286. return handle(entry.finallyLoc);
  7287. }
  7288.  
  7289. } else {
  7290. throw new Error("try statement without catch or finally");
  7291. }
  7292. }
  7293. }
  7294. },
  7295.  
  7296. abrupt: function(type, arg) {
  7297. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  7298. var entry = this.tryEntries[i];
  7299. if (entry.tryLoc <= this.prev &&
  7300. hasOwn.call(entry, "finallyLoc") &&
  7301. this.prev < entry.finallyLoc) {
  7302. var finallyEntry = entry;
  7303. break;
  7304. }
  7305. }
  7306.  
  7307. if (finallyEntry &&
  7308. (type === "break" ||
  7309. type === "continue") &&
  7310. finallyEntry.tryLoc <= arg &&
  7311. arg <= finallyEntry.finallyLoc) {
  7312. // Ignore the finally entry if control is not jumping to a
  7313. // location outside the try/catch block.
  7314. finallyEntry = null;
  7315. }
  7316.  
  7317. var record = finallyEntry ? finallyEntry.completion : {};
  7318. record.type = type;
  7319. record.arg = arg;
  7320.  
  7321. if (finallyEntry) {
  7322. this.method = "next";
  7323. this.next = finallyEntry.finallyLoc;
  7324. return ContinueSentinel;
  7325. }
  7326.  
  7327. return this.complete(record);
  7328. },
  7329.  
  7330. complete: function(record, afterLoc) {
  7331. if (record.type === "throw") {
  7332. throw record.arg;
  7333. }
  7334.  
  7335. if (record.type === "break" ||
  7336. record.type === "continue") {
  7337. this.next = record.arg;
  7338. } else if (record.type === "return") {
  7339. this.rval = this.arg = record.arg;
  7340. this.method = "return";
  7341. this.next = "end";
  7342. } else if (record.type === "normal" && afterLoc) {
  7343. this.next = afterLoc;
  7344. }
  7345.  
  7346. return ContinueSentinel;
  7347. },
  7348.  
  7349. finish: function(finallyLoc) {
  7350. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  7351. var entry = this.tryEntries[i];
  7352. if (entry.finallyLoc === finallyLoc) {
  7353. this.complete(entry.completion, entry.afterLoc);
  7354. resetTryEntry(entry);
  7355. return ContinueSentinel;
  7356. }
  7357. }
  7358. },
  7359.  
  7360. "catch": function(tryLoc) {
  7361. for (var i = this.tryEntries.length - 1; i >= 0; --i) {
  7362. var entry = this.tryEntries[i];
  7363. if (entry.tryLoc === tryLoc) {
  7364. var record = entry.completion;
  7365. if (record.type === "throw") {
  7366. var thrown = record.arg;
  7367. resetTryEntry(entry);
  7368. }
  7369. return thrown;
  7370. }
  7371. }
  7372.  
  7373. // The context.catch method must only be called with a location
  7374. // argument that corresponds to a known catch block.
  7375. throw new Error("illegal catch attempt");
  7376. },
  7377.  
  7378. delegateYield: function(iterable, resultName, nextLoc) {
  7379. this.delegate = {
  7380. iterator: values(iterable),
  7381. resultName: resultName,
  7382. nextLoc: nextLoc
  7383. };
  7384.  
  7385. if (this.method === "next") {
  7386. // Deliberately forget the last sent value so that we don't
  7387. // accidentally pass it on to the delegate.
  7388. this.arg = undefined;
  7389. }
  7390.  
  7391. return ContinueSentinel;
  7392. }
  7393. };
  7394. })(
  7395. // Among the various tricks for obtaining a reference to the global
  7396. // object, this seems to be the most reliable technique that does not
  7397. // use indirect eval (which violates Content Security Policy).
  7398. typeof global === "object" ? global :
  7399. typeof window === "object" ? window :
  7400. typeof self === "object" ? self : this
  7401. );
  7402.  
  7403. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
  7404.  
  7405. /***/ }),
  7406. /* 34 */
  7407. /***/ (function(module, exports, __webpack_require__) {
  7408.  
  7409. "use strict";
  7410.  
  7411.  
  7412. Object.defineProperty(exports, "__esModule", {
  7413. value: true
  7414. });
  7415.  
  7416. function getVideoUrl(tvid, vid) {
  7417. return new Promise(function (resolve, reject) {
  7418. GM_xmlhttpRequest({
  7419. url: 'http://cache.video.qiyi.com/jp/vi/' + tvid + '/' + vid + '/?callback=callback',
  7420. method: 'GET',
  7421. timeout: 8e3,
  7422. onload: function onload(details) {
  7423. try {
  7424. var json = JSON.parse(/callback\s*\(\s*(\{.*\})\s*\)/.exec(details.responseText)[1]);
  7425. resolve(json.vu);
  7426. } catch (err) {
  7427. reject(err);
  7428. }
  7429. },
  7430. onerror: reject,
  7431. onabort: reject,
  7432. ontimeout: reject
  7433. });
  7434. });
  7435. }
  7436.  
  7437. function findVid(text) {
  7438. var result = /vid=([\da-z]+)/i.exec(text);
  7439. return result ? result[1] : null;
  7440. }
  7441.  
  7442. function findTvid(text) {
  7443. var result = /tvid=(\d+)/i.exec(text);
  7444. return result ? result[1] : null;
  7445. }
  7446.  
  7447. exports.getVideoUrl = getVideoUrl;
  7448. exports.findVid = findVid;
  7449. exports.findTvid = findTvid;
  7450.  
  7451. /***/ })
  7452. /******/ ]);

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址