园林绿化
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

6024 lines
260 KiB

  1. /*!
  2. * kml与geojson互转工具类
  3. * 版本信息v1.2.0, hash值: d5ca7f27b3bc2d3b0b2d
  4. * 编译日期2022-02-20 11:53:55
  5. * 版权所有Copyright by 木遥 https://github.com/muyao1987/kml-geojson
  6. *
  7. */
  8. (function webpackUniversalModuleDefinition(root, factory) {
  9. if(typeof exports === 'object' && typeof module === 'object')
  10. module.exports = factory();
  11. else if(typeof define === 'function' && define.amd)
  12. define("kgUtil", [], factory);
  13. else if(typeof exports === 'object')
  14. exports["kgUtil"] = factory();
  15. else
  16. root["kgUtil"] = factory();
  17. })(window, function() {
  18. return /******/ (function(modules) { // webpackBootstrap
  19. /******/ // The module cache
  20. /******/ var installedModules = {};
  21. /******/
  22. /******/ // The require function
  23. /******/ function __webpack_require__(moduleId) {
  24. /******/
  25. /******/ // Check if module is in cache
  26. /******/ if(installedModules[moduleId]) {
  27. /******/ return installedModules[moduleId].exports;
  28. /******/ }
  29. /******/ // Create a new module (and put it into the cache)
  30. /******/ var module = installedModules[moduleId] = {
  31. /******/ i: moduleId,
  32. /******/ l: false,
  33. /******/ exports: {}
  34. /******/ };
  35. /******/
  36. /******/ // Execute the module function
  37. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  38. /******/
  39. /******/ // Flag the module as loaded
  40. /******/ module.l = true;
  41. /******/
  42. /******/ // Return the exports of the module
  43. /******/ return module.exports;
  44. /******/ }
  45. /******/
  46. /******/
  47. /******/ // expose the modules object (__webpack_modules__)
  48. /******/ __webpack_require__.m = modules;
  49. /******/
  50. /******/ // expose the module cache
  51. /******/ __webpack_require__.c = installedModules;
  52. /******/
  53. /******/ // define getter function for harmony exports
  54. /******/ __webpack_require__.d = function(exports, name, getter) {
  55. /******/ if(!__webpack_require__.o(exports, name)) {
  56. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  57. /******/ }
  58. /******/ };
  59. /******/
  60. /******/ // define __esModule on exports
  61. /******/ __webpack_require__.r = function(exports) {
  62. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  63. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  64. /******/ }
  65. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  66. /******/ };
  67. /******/
  68. /******/ // create a fake namespace object
  69. /******/ // mode & 1: value is a module id, require it
  70. /******/ // mode & 2: merge all properties of value into the ns
  71. /******/ // mode & 4: return value when already ns object
  72. /******/ // mode & 8|1: behave like require
  73. /******/ __webpack_require__.t = function(value, mode) {
  74. /******/ if(mode & 1) value = __webpack_require__(value);
  75. /******/ if(mode & 8) return value;
  76. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  77. /******/ var ns = Object.create(null);
  78. /******/ __webpack_require__.r(ns);
  79. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  80. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  81. /******/ return ns;
  82. /******/ };
  83. /******/
  84. /******/ // getDefaultExport function for compatibility with non-harmony modules
  85. /******/ __webpack_require__.n = function(module) {
  86. /******/ var getter = module && module.__esModule ?
  87. /******/ function getDefault() { return module['default']; } :
  88. /******/ function getModuleExports() { return module; };
  89. /******/ __webpack_require__.d(getter, 'a', getter);
  90. /******/ return getter;
  91. /******/ };
  92. /******/
  93. /******/ // Object.prototype.hasOwnProperty.call
  94. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  95. /******/
  96. /******/ // __webpack_public_path__
  97. /******/ __webpack_require__.p = "";
  98. /******/
  99. /******/
  100. /******/ // Load entry module and return exports
  101. /******/ return __webpack_require__(__webpack_require__.s = 16);
  102. /******/ })
  103. /************************************************************************/
  104. /******/ ([
  105. /* 0 */
  106. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  107. "use strict";
  108. /* WEBPACK VAR INJECTION */(function(process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return kmlToGeoJSON; });
  109. /* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(2);
  110. /* harmony import */ var _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(_babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0__);
  111. // kml => geojson
  112. var removeSpace = /\s*/g,
  113. trimSpace = /^\s*|\s*$/g,
  114. splitSpace = /\s+/; // generate a short, numeric hash of a string
  115. function okhash(x) {
  116. if (!x || !x.length) return 0;
  117. for (var i = 0, h = 0; i < x.length; i++) {
  118. h = (h << 5) - h + x.charCodeAt(i) | 0;
  119. }
  120. return h;
  121. } // all Y children of X
  122. function get(x, y) {
  123. return x.getElementsByTagName(y);
  124. }
  125. function attr(x, y) {
  126. return x.getAttribute(y);
  127. }
  128. function attrf(x, y) {
  129. return parseFloat(attr(x, y));
  130. } // one Y child of X, if any, otherwise null
  131. function get1(x, y) {
  132. var n = get(x, y);
  133. return n.length ? n[0] : null;
  134. } // https://developer.mozilla.org/en-US/docs/Web/API/Node.normalize
  135. function norm(el) {
  136. if (el.normalize) {
  137. el.normalize();
  138. }
  139. return el;
  140. } // cast array x into numbers
  141. function numarray(x) {
  142. for (var j = 0, o = []; j < x.length; j++) {
  143. o[j] = parseFloat(x[j]);
  144. }
  145. return o;
  146. } // get the content of a text node, if any
  147. function nodeVal(x) {
  148. if (x) {
  149. norm(x);
  150. }
  151. return x && x.textContent || '';
  152. } // get the contents of multiple text nodes, if present
  153. // function getMulti(x, ys) {
  154. // var o = {},
  155. // n,
  156. // k
  157. // for (k = 0; k < ys.length; k++) {
  158. // n = get1(x, ys[k])
  159. // if (n) o[ys[k]] = nodeVal(n)
  160. // }
  161. // return o
  162. // }
  163. // add properties of Y to X, overwriting if present in both
  164. // function extend(x, y) {
  165. // for (var k in y) x[k] = y[k]
  166. // }
  167. // get one coordinate from a coordinate array, if any
  168. function coord1(v) {
  169. return numarray(v.replace(removeSpace, '').split(','));
  170. } // get all coordinates from a coordinate array as [[],[]]
  171. function coord(v) {
  172. var coords = v.replace(trimSpace, '').split(splitSpace),
  173. o = [];
  174. for (var i = 0; i < coords.length; i++) {
  175. o.push(coord1(coords[i]));
  176. }
  177. return o;
  178. } // function coordPair(x) {
  179. // var ll = [attrf(x, 'lon'), attrf(x, 'lat')],
  180. // ele = get1(x, 'ele'),
  181. // // handle namespaced attribute in browser
  182. // heartRate = get1(x, 'gpxtpx:hr') || get1(x, 'hr'),
  183. // time = get1(x, 'time'),
  184. // e
  185. // if (ele) {
  186. // e = parseFloat(nodeVal(ele))
  187. // if (!isNaN(e)) {
  188. // ll.push(e)
  189. // }
  190. // }
  191. // return {
  192. // coordinates: ll,
  193. // time: time ? nodeVal(time) : null,
  194. // heartRate: heartRate ? parseFloat(nodeVal(heartRate)) : null,
  195. // }
  196. // }
  197. // create a new feature collection parent object
  198. function fc() {
  199. return {
  200. type: 'FeatureCollection',
  201. features: []
  202. };
  203. }
  204. var serializer;
  205. if (typeof XMLSerializer !== 'undefined') {
  206. /* istanbul ignore next */
  207. serializer = new XMLSerializer(); // only require xmldom in a node environment
  208. } else if ((typeof exports === "undefined" ? "undefined" : _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(exports)) === 'object' && (typeof process === "undefined" ? "undefined" : _babel_runtime_helpers_typeof__WEBPACK_IMPORTED_MODULE_0___default()(process)) === 'object' && !process.browser) {
  209. serializer = new (__webpack_require__(13).XMLSerializer)();
  210. }
  211. function xml2str(str) {
  212. // IE9 will create a new XMLSerializer but it'll crash immediately.
  213. // This line is ignored because we don't run coverage tests in IE9
  214. /* istanbul ignore next */
  215. if (str.xml !== undefined) return str.xml;
  216. return serializer.serializeToString(str);
  217. }
  218. function kmlToGeoJSON(doc) {
  219. var gj = fc(),
  220. // styleindex keeps track of hashed styles in order to match features
  221. styleIndex = {},
  222. styleByHash = {},
  223. // stylemapindex keeps track of style maps to expose in properties
  224. styleMapIndex = {},
  225. // atomic geospatial types supported by KML - MultiGeometry is
  226. // handled separately
  227. geotypes = ['Polygon', 'LineString', 'Point', 'Track', 'gx:Track'],
  228. // all root placemarks in the file
  229. placemarks = get(doc, 'Placemark'),
  230. styles = get(doc, 'Style'),
  231. styleMaps = get(doc, 'StyleMap');
  232. for (var k = 0; k < styles.length; k++) {
  233. var hash = okhash(xml2str(styles[k])).toString(16);
  234. styleIndex['#' + attr(styles[k], 'id')] = hash;
  235. styleByHash[hash] = styles[k];
  236. }
  237. for (var l = 0; l < styleMaps.length; l++) {
  238. styleIndex['#' + attr(styleMaps[l], 'id')] = okhash(xml2str(styleMaps[l])).toString(16);
  239. var pairs = get(styleMaps[l], 'Pair');
  240. var pairsMap = {};
  241. for (var m = 0; m < pairs.length; m++) {
  242. pairsMap[nodeVal(get1(pairs[m], 'key'))] = nodeVal(get1(pairs[m], 'styleUrl'));
  243. }
  244. styleMapIndex['#' + attr(styleMaps[l], 'id')] = pairsMap;
  245. }
  246. for (var j = 0; j < placemarks.length; j++) {
  247. gj.features = gj.features.concat(getPlacemark(placemarks[j]));
  248. }
  249. function kmlColor(v) {
  250. var color, opacity;
  251. v = v || '';
  252. if (v.substr(0, 1) === '#') {
  253. v = v.substr(1);
  254. }
  255. if (v.length === 6 || v.length === 3) {
  256. color = v;
  257. }
  258. if (v.length === 8) {
  259. opacity = parseInt(v.substr(0, 2), 16) / 255;
  260. color = '#' + v.substr(6, 2) + v.substr(4, 2) + v.substr(2, 2);
  261. }
  262. return [color, isNaN(opacity) ? undefined : opacity];
  263. }
  264. function gxCoord(v) {
  265. return numarray(v.split(' '));
  266. }
  267. function gxCoords(root) {
  268. var elems = get(root, 'coord', 'gx'),
  269. coords = [],
  270. times = [];
  271. if (elems.length === 0) elems = get(root, 'gx:coord');
  272. for (var i = 0; i < elems.length; i++) {
  273. coords.push(gxCoord(nodeVal(elems[i])));
  274. }
  275. var timeElems = get(root, 'when');
  276. for (var j = 0; j < timeElems.length; j++) {
  277. times.push(nodeVal(timeElems[j]));
  278. }
  279. return {
  280. coords: coords,
  281. times: times
  282. };
  283. }
  284. function getGeometry(root) {
  285. var geomNode,
  286. geomNodes,
  287. i,
  288. j,
  289. k,
  290. geoms = [],
  291. coordTimes = [];
  292. if (get1(root, 'MultiGeometry')) {
  293. return getGeometry(get1(root, 'MultiGeometry'));
  294. }
  295. if (get1(root, 'MultiTrack')) {
  296. return getGeometry(get1(root, 'MultiTrack'));
  297. }
  298. if (get1(root, 'gx:MultiTrack')) {
  299. return getGeometry(get1(root, 'gx:MultiTrack'));
  300. }
  301. for (i = 0; i < geotypes.length; i++) {
  302. geomNodes = get(root, geotypes[i]);
  303. if (geomNodes) {
  304. for (j = 0; j < geomNodes.length; j++) {
  305. geomNode = geomNodes[j];
  306. if (geotypes[i] === 'Point') {
  307. geoms.push({
  308. type: 'Point',
  309. coordinates: coord1(nodeVal(get1(geomNode, 'coordinates')))
  310. });
  311. } else if (geotypes[i] === 'LineString') {
  312. geoms.push({
  313. type: 'LineString',
  314. coordinates: coord(nodeVal(get1(geomNode, 'coordinates')))
  315. });
  316. } else if (geotypes[i] === 'Polygon') {
  317. var rings = get(geomNode, 'LinearRing'),
  318. coords = [];
  319. for (k = 0; k < rings.length; k++) {
  320. coords.push(coord(nodeVal(get1(rings[k], 'coordinates'))));
  321. }
  322. geoms.push({
  323. type: 'Polygon',
  324. coordinates: coords
  325. });
  326. } else if (geotypes[i] === 'Track' || geotypes[i] === 'gx:Track') {
  327. var track = gxCoords(geomNode);
  328. geoms.push({
  329. type: 'LineString',
  330. coordinates: track.coords
  331. });
  332. if (track.times.length) coordTimes.push(track.times);
  333. }
  334. }
  335. }
  336. }
  337. return {
  338. geoms: geoms,
  339. coordTimes: coordTimes
  340. };
  341. }
  342. function getPlacemark(root) {
  343. var geomsAndTimes = getGeometry(root),
  344. i,
  345. properties = {},
  346. name = nodeVal(get1(root, 'name')),
  347. styleUrl = nodeVal(get1(root, 'styleUrl')),
  348. description = nodeVal(get1(root, 'description')),
  349. timeSpan = get1(root, 'TimeSpan'),
  350. timeStamp = get1(root, 'TimeStamp'),
  351. extendedData = get1(root, 'ExtendedData'),
  352. lineStyle = get1(root, 'LineStyle'),
  353. polyStyle = get1(root, 'PolyStyle'),
  354. visibility = get1(root, 'visibility');
  355. if (!geomsAndTimes.geoms.length) return [];
  356. if (name) properties.name = name;
  357. if (styleUrl) {
  358. if (styleUrl[0] !== '#') {
  359. styleUrl = '#' + styleUrl;
  360. }
  361. properties.styleUrl = styleUrl;
  362. if (styleIndex[styleUrl]) {
  363. properties.styleHash = styleIndex[styleUrl];
  364. }
  365. if (styleMapIndex[styleUrl]) {
  366. properties.styleMapHash = styleMapIndex[styleUrl];
  367. properties.styleHash = styleIndex[styleMapIndex[styleUrl].normal];
  368. } // Try to populate the lineStyle or polyStyle since we got the style hash
  369. var style = styleByHash[properties.styleHash];
  370. if (style) {
  371. if (!lineStyle) lineStyle = get1(style, 'LineStyle');
  372. if (!polyStyle) polyStyle = get1(style, 'PolyStyle');
  373. }
  374. }
  375. if (description) properties.description = description;
  376. if (timeSpan) {
  377. var begin = nodeVal(get1(timeSpan, 'begin'));
  378. var end = nodeVal(get1(timeSpan, 'end'));
  379. properties.timespan = {
  380. begin: begin,
  381. end: end
  382. };
  383. }
  384. if (timeStamp) {
  385. properties.timestamp = nodeVal(get1(timeStamp, 'when'));
  386. }
  387. if (lineStyle) {
  388. var linestyles = kmlColor(nodeVal(get1(lineStyle, 'color'))),
  389. color = linestyles[0],
  390. opacity = linestyles[1],
  391. width = parseFloat(nodeVal(get1(lineStyle, 'width')));
  392. if (color) properties.stroke = color;
  393. if (!isNaN(opacity)) properties['stroke-opacity'] = opacity;
  394. if (!isNaN(width)) properties['stroke-width'] = width;
  395. }
  396. if (polyStyle) {
  397. var polystyles = kmlColor(nodeVal(get1(polyStyle, 'color'))),
  398. pcolor = polystyles[0],
  399. popacity = polystyles[1],
  400. fill = nodeVal(get1(polyStyle, 'fill')),
  401. outline = nodeVal(get1(polyStyle, 'outline'));
  402. if (pcolor) properties.fill = pcolor;
  403. if (!isNaN(popacity)) properties['fill-opacity'] = popacity;
  404. if (fill) properties['fill-opacity'] = fill === '1' ? properties['fill-opacity'] || 1 : 0;
  405. if (outline) properties['stroke-opacity'] = outline === '1' ? properties['stroke-opacity'] || 1 : 0;
  406. }
  407. if (extendedData) {
  408. var datas = get(extendedData, 'Data'),
  409. simpleDatas = get(extendedData, 'SimpleData');
  410. for (i = 0; i < datas.length; i++) {
  411. var _name = datas[i].getAttribute('name');
  412. var val = nodeVal(get1(datas[i], 'value'));
  413. try {
  414. val = JSON.parse(val);
  415. } catch (e) {}
  416. properties[_name] = val;
  417. }
  418. for (i = 0; i < simpleDatas.length; i++) {
  419. var _name2 = simpleDatas[i].getAttribute('name');
  420. var _val = nodeVal(simpleDatas[i]);
  421. try {
  422. _val = JSON.parse(_val);
  423. } catch (e) {}
  424. properties[_name2] = _val;
  425. }
  426. }
  427. if (visibility) {
  428. properties.visibility = nodeVal(visibility);
  429. }
  430. if (geomsAndTimes.coordTimes.length) {
  431. properties.coordTimes = geomsAndTimes.coordTimes.length === 1 ? geomsAndTimes.coordTimes[0] : geomsAndTimes.coordTimes;
  432. }
  433. var feature = {
  434. type: 'Feature',
  435. geometry: geomsAndTimes.geoms.length === 1 ? geomsAndTimes.geoms[0] : {
  436. type: 'GeometryCollection',
  437. geometries: geomsAndTimes.geoms
  438. },
  439. properties: properties
  440. };
  441. if (attr(root, 'id')) feature.id = attr(root, 'id');
  442. return [feature];
  443. }
  444. return gj;
  445. }
  446. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(3)))
  447. /***/ }),
  448. /* 1 */
  449. /***/ (function(module, exports) {
  450. var g;
  451. // This works in non-strict mode
  452. g = (function() {
  453. return this;
  454. })();
  455. try {
  456. // This works if eval is allowed (see CSP)
  457. g = g || new Function("return this")();
  458. } catch (e) {
  459. // This works if the window reference is available
  460. if (typeof window === "object") g = window;
  461. }
  462. // g can still be undefined, but nothing to do about it...
  463. // We return undefined, instead of nothing here, so it's
  464. // easier to handle this case. if(!global) { ...}
  465. module.exports = g;
  466. /***/ }),
  467. /* 2 */
  468. /***/ (function(module, exports) {
  469. function _typeof(obj) {
  470. "@babel/helpers - typeof";
  471. return (module.exports = _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) {
  472. return typeof obj;
  473. } : function (obj) {
  474. return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
  475. }, module.exports.__esModule = true, module.exports["default"] = module.exports), _typeof(obj);
  476. }
  477. module.exports = _typeof, module.exports.__esModule = true, module.exports["default"] = module.exports;
  478. /***/ }),
  479. /* 3 */
  480. /***/ (function(module, exports) {
  481. // shim for using process in browser
  482. var process = module.exports = {};
  483. // cached from whatever global is present so that test runners that stub it
  484. // don't break things. But we need to wrap it in a try catch in case it is
  485. // wrapped in strict mode code which doesn't define any globals. It's inside a
  486. // function because try/catches deoptimize in certain engines.
  487. var cachedSetTimeout;
  488. var cachedClearTimeout;
  489. function defaultSetTimout() {
  490. throw new Error('setTimeout has not been defined');
  491. }
  492. function defaultClearTimeout () {
  493. throw new Error('clearTimeout has not been defined');
  494. }
  495. (function () {
  496. try {
  497. if (typeof setTimeout === 'function') {
  498. cachedSetTimeout = setTimeout;
  499. } else {
  500. cachedSetTimeout = defaultSetTimout;
  501. }
  502. } catch (e) {
  503. cachedSetTimeout = defaultSetTimout;
  504. }
  505. try {
  506. if (typeof clearTimeout === 'function') {
  507. cachedClearTimeout = clearTimeout;
  508. } else {
  509. cachedClearTimeout = defaultClearTimeout;
  510. }
  511. } catch (e) {
  512. cachedClearTimeout = defaultClearTimeout;
  513. }
  514. } ())
  515. function runTimeout(fun) {
  516. if (cachedSetTimeout === setTimeout) {
  517. //normal enviroments in sane situations
  518. return setTimeout(fun, 0);
  519. }
  520. // if setTimeout wasn't available but was latter defined
  521. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  522. cachedSetTimeout = setTimeout;
  523. return setTimeout(fun, 0);
  524. }
  525. try {
  526. // when when somebody has screwed with setTimeout but no I.E. maddness
  527. return cachedSetTimeout(fun, 0);
  528. } catch(e){
  529. try {
  530. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  531. return cachedSetTimeout.call(null, fun, 0);
  532. } catch(e){
  533. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  534. return cachedSetTimeout.call(this, fun, 0);
  535. }
  536. }
  537. }
  538. function runClearTimeout(marker) {
  539. if (cachedClearTimeout === clearTimeout) {
  540. //normal enviroments in sane situations
  541. return clearTimeout(marker);
  542. }
  543. // if clearTimeout wasn't available but was latter defined
  544. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  545. cachedClearTimeout = clearTimeout;
  546. return clearTimeout(marker);
  547. }
  548. try {
  549. // when when somebody has screwed with setTimeout but no I.E. maddness
  550. return cachedClearTimeout(marker);
  551. } catch (e){
  552. try {
  553. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  554. return cachedClearTimeout.call(null, marker);
  555. } catch (e){
  556. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  557. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  558. return cachedClearTimeout.call(this, marker);
  559. }
  560. }
  561. }
  562. var queue = [];
  563. var draining = false;
  564. var currentQueue;
  565. var queueIndex = -1;
  566. function cleanUpNextTick() {
  567. if (!draining || !currentQueue) {
  568. return;
  569. }
  570. draining = false;
  571. if (currentQueue.length) {
  572. queue = currentQueue.concat(queue);
  573. } else {
  574. queueIndex = -1;
  575. }
  576. if (queue.length) {
  577. drainQueue();
  578. }
  579. }
  580. function drainQueue() {
  581. if (draining) {
  582. return;
  583. }
  584. var timeout = runTimeout(cleanUpNextTick);
  585. draining = true;
  586. var len = queue.length;
  587. while(len) {
  588. currentQueue = queue;
  589. queue = [];
  590. while (++queueIndex < len) {
  591. if (currentQueue) {
  592. currentQueue[queueIndex].run();
  593. }
  594. }
  595. queueIndex = -1;
  596. len = queue.length;
  597. }
  598. currentQueue = null;
  599. draining = false;
  600. runClearTimeout(timeout);
  601. }
  602. process.nextTick = function (fun) {
  603. var args = new Array(arguments.length - 1);
  604. if (arguments.length > 1) {
  605. for (var i = 1; i < arguments.length; i++) {
  606. args[i - 1] = arguments[i];
  607. }
  608. }
  609. queue.push(new Item(fun, args));
  610. if (queue.length === 1 && !draining) {
  611. runTimeout(drainQueue);
  612. }
  613. };
  614. // v8 likes predictible objects
  615. function Item(fun, array) {
  616. this.fun = fun;
  617. this.array = array;
  618. }
  619. Item.prototype.run = function () {
  620. this.fun.apply(null, this.array);
  621. };
  622. process.title = 'browser';
  623. process.browser = true;
  624. process.env = {};
  625. process.argv = [];
  626. process.version = ''; // empty string to avoid regexp issues
  627. process.versions = {};
  628. function noop() {}
  629. process.on = noop;
  630. process.addListener = noop;
  631. process.once = noop;
  632. process.off = noop;
  633. process.removeListener = noop;
  634. process.removeAllListeners = noop;
  635. process.emit = noop;
  636. process.prependListener = noop;
  637. process.prependOnceListener = noop;
  638. process.listeners = function (name) { return [] }
  639. process.binding = function (name) {
  640. throw new Error('process.binding is not supported');
  641. };
  642. process.cwd = function () { return '/' };
  643. process.chdir = function (dir) {
  644. throw new Error('process.chdir is not supported');
  645. };
  646. process.umask = function() { return 0; };
  647. /***/ }),
  648. /* 4 */
  649. /***/ (function(module, exports) {
  650. function copy(src,dest){
  651. for(var p in src){
  652. dest[p] = src[p];
  653. }
  654. }
  655. /**
  656. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  657. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  658. */
  659. function _extends(Class,Super){
  660. var pt = Class.prototype;
  661. if(!(pt instanceof Super)){
  662. function t(){};
  663. t.prototype = Super.prototype;
  664. t = new t();
  665. copy(pt,t);
  666. Class.prototype = pt = t;
  667. }
  668. if(pt.constructor != Class){
  669. if(typeof Class != 'function'){
  670. console.error("unknow Class:"+Class)
  671. }
  672. pt.constructor = Class
  673. }
  674. }
  675. var htmlns = 'http://www.w3.org/1999/xhtml' ;
  676. // Node Types
  677. var NodeType = {}
  678. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  679. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  680. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  681. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  682. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  683. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  684. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  685. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  686. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  687. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  688. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  689. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  690. // ExceptionCode
  691. var ExceptionCode = {}
  692. var ExceptionMessage = {};
  693. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  694. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  695. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  696. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  697. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  698. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  699. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  700. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  701. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  702. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  703. //level2
  704. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  705. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  706. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  707. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  708. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  709. /**
  710. * DOM Level 2
  711. * Object DOMException
  712. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  713. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  714. */
  715. function DOMException(code, message) {
  716. if(message instanceof Error){
  717. var error = message;
  718. }else{
  719. error = this;
  720. Error.call(this, ExceptionMessage[code]);
  721. this.message = ExceptionMessage[code];
  722. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  723. }
  724. error.code = code;
  725. if(message) this.message = this.message + ": " + message;
  726. return error;
  727. };
  728. DOMException.prototype = Error.prototype;
  729. copy(ExceptionCode,DOMException)
  730. /**
  731. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  732. * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
  733. * The items in the NodeList are accessible via an integral index, starting from 0.
  734. */
  735. function NodeList() {
  736. };
  737. NodeList.prototype = {
  738. /**
  739. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  740. * @standard level1
  741. */
  742. length:0,
  743. /**
  744. * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
  745. * @standard level1
  746. * @param index unsigned long
  747. * Index into the collection.
  748. * @return Node
  749. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  750. */
  751. item: function(index) {
  752. return this[index] || null;
  753. },
  754. toString:function(isHTML,nodeFilter){
  755. for(var buf = [], i = 0;i<this.length;i++){
  756. serializeToString(this[i],buf,isHTML,nodeFilter);
  757. }
  758. return buf.join('');
  759. }
  760. };
  761. function LiveNodeList(node,refresh){
  762. this._node = node;
  763. this._refresh = refresh
  764. _updateLiveList(this);
  765. }
  766. function _updateLiveList(list){
  767. var inc = list._node._inc || list._node.ownerDocument._inc;
  768. if(list._inc != inc){
  769. var ls = list._refresh(list._node);
  770. //console.log(ls.length)
  771. __set__(list,'length',ls.length);
  772. copy(ls,list);
  773. list._inc = inc;
  774. }
  775. }
  776. LiveNodeList.prototype.item = function(i){
  777. _updateLiveList(this);
  778. return this[i];
  779. }
  780. _extends(LiveNodeList,NodeList);
  781. /**
  782. *
  783. * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index, but this is simply to allow convenient enumeration of the contents of a NamedNodeMap, and does not imply that the DOM specifies an order to these Nodes.
  784. * NamedNodeMap objects in the DOM are live.
  785. * used for attributes or DocumentType entities
  786. */
  787. function NamedNodeMap() {
  788. };
  789. function _findNodeIndex(list,node){
  790. var i = list.length;
  791. while(i--){
  792. if(list[i] === node){return i}
  793. }
  794. }
  795. function _addNamedNode(el,list,newAttr,oldAttr){
  796. if(oldAttr){
  797. list[_findNodeIndex(list,oldAttr)] = newAttr;
  798. }else{
  799. list[list.length++] = newAttr;
  800. }
  801. if(el){
  802. newAttr.ownerElement = el;
  803. var doc = el.ownerDocument;
  804. if(doc){
  805. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  806. _onAddAttribute(doc,el,newAttr);
  807. }
  808. }
  809. }
  810. function _removeNamedNode(el,list,attr){
  811. //console.log('remove attr:'+attr)
  812. var i = _findNodeIndex(list,attr);
  813. if(i>=0){
  814. var lastIndex = list.length-1
  815. while(i<lastIndex){
  816. list[i] = list[++i]
  817. }
  818. list.length = lastIndex;
  819. if(el){
  820. var doc = el.ownerDocument;
  821. if(doc){
  822. _onRemoveAttribute(doc,el,attr);
  823. attr.ownerElement = null;
  824. }
  825. }
  826. }else{
  827. throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
  828. }
  829. }
  830. NamedNodeMap.prototype = {
  831. length:0,
  832. item:NodeList.prototype.item,
  833. getNamedItem: function(key) {
  834. // if(key.indexOf(':')>0 || key == 'xmlns'){
  835. // return null;
  836. // }
  837. //console.log()
  838. var i = this.length;
  839. while(i--){
  840. var attr = this[i];
  841. //console.log(attr.nodeName,key)
  842. if(attr.nodeName == key){
  843. return attr;
  844. }
  845. }
  846. },
  847. setNamedItem: function(attr) {
  848. var el = attr.ownerElement;
  849. if(el && el!=this._ownerElement){
  850. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  851. }
  852. var oldAttr = this.getNamedItem(attr.nodeName);
  853. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  854. return oldAttr;
  855. },
  856. /* returns Node */
  857. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  858. var el = attr.ownerElement, oldAttr;
  859. if(el && el!=this._ownerElement){
  860. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  861. }
  862. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  863. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  864. return oldAttr;
  865. },
  866. /* returns Node */
  867. removeNamedItem: function(key) {
  868. var attr = this.getNamedItem(key);
  869. _removeNamedNode(this._ownerElement,this,attr);
  870. return attr;
  871. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  872. //for level2
  873. removeNamedItemNS:function(namespaceURI,localName){
  874. var attr = this.getNamedItemNS(namespaceURI,localName);
  875. _removeNamedNode(this._ownerElement,this,attr);
  876. return attr;
  877. },
  878. getNamedItemNS: function(namespaceURI, localName) {
  879. var i = this.length;
  880. while(i--){
  881. var node = this[i];
  882. if(node.localName == localName && node.namespaceURI == namespaceURI){
  883. return node;
  884. }
  885. }
  886. return null;
  887. }
  888. };
  889. /**
  890. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  891. */
  892. function DOMImplementation(/* Object */ features) {
  893. this._features = {};
  894. if (features) {
  895. for (var feature in features) {
  896. this._features = features[feature];
  897. }
  898. }
  899. };
  900. DOMImplementation.prototype = {
  901. hasFeature: function(/* string */ feature, /* string */ version) {
  902. var versions = this._features[feature.toLowerCase()];
  903. if (versions && (!version || version in versions)) {
  904. return true;
  905. } else {
  906. return false;
  907. }
  908. },
  909. // Introduced in DOM Level 2:
  910. createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  911. var doc = new Document();
  912. doc.implementation = this;
  913. doc.childNodes = new NodeList();
  914. doc.doctype = doctype;
  915. if(doctype){
  916. doc.appendChild(doctype);
  917. }
  918. if(qualifiedName){
  919. var root = doc.createElementNS(namespaceURI,qualifiedName);
  920. doc.appendChild(root);
  921. }
  922. return doc;
  923. },
  924. // Introduced in DOM Level 2:
  925. createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  926. var node = new DocumentType();
  927. node.name = qualifiedName;
  928. node.nodeName = qualifiedName;
  929. node.publicId = publicId;
  930. node.systemId = systemId;
  931. // Introduced in DOM Level 2:
  932. //readonly attribute DOMString internalSubset;
  933. //TODO:..
  934. // readonly attribute NamedNodeMap entities;
  935. // readonly attribute NamedNodeMap notations;
  936. return node;
  937. }
  938. };
  939. /**
  940. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  941. */
  942. function Node() {
  943. };
  944. Node.prototype = {
  945. firstChild : null,
  946. lastChild : null,
  947. previousSibling : null,
  948. nextSibling : null,
  949. attributes : null,
  950. parentNode : null,
  951. childNodes : null,
  952. ownerDocument : null,
  953. nodeValue : null,
  954. namespaceURI : null,
  955. prefix : null,
  956. localName : null,
  957. // Modified in DOM Level 2:
  958. insertBefore:function(newChild, refChild){//raises
  959. return _insertBefore(this,newChild,refChild);
  960. },
  961. replaceChild:function(newChild, oldChild){//raises
  962. this.insertBefore(newChild,oldChild);
  963. if(oldChild){
  964. this.removeChild(oldChild);
  965. }
  966. },
  967. removeChild:function(oldChild){
  968. return _removeChild(this,oldChild);
  969. },
  970. appendChild:function(newChild){
  971. return this.insertBefore(newChild,null);
  972. },
  973. hasChildNodes:function(){
  974. return this.firstChild != null;
  975. },
  976. cloneNode:function(deep){
  977. return cloneNode(this.ownerDocument||this,this,deep);
  978. },
  979. // Modified in DOM Level 2:
  980. normalize:function(){
  981. var child = this.firstChild;
  982. while(child){
  983. var next = child.nextSibling;
  984. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  985. this.removeChild(next);
  986. child.appendData(next.data);
  987. }else{
  988. child.normalize();
  989. child = next;
  990. }
  991. }
  992. },
  993. // Introduced in DOM Level 2:
  994. isSupported:function(feature, version){
  995. return this.ownerDocument.implementation.hasFeature(feature,version);
  996. },
  997. // Introduced in DOM Level 2:
  998. hasAttributes:function(){
  999. return this.attributes.length>0;
  1000. },
  1001. lookupPrefix:function(namespaceURI){
  1002. var el = this;
  1003. while(el){
  1004. var map = el._nsMap;
  1005. //console.dir(map)
  1006. if(map){
  1007. for(var n in map){
  1008. if(map[n] == namespaceURI){
  1009. return n;
  1010. }
  1011. }
  1012. }
  1013. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  1014. }
  1015. return null;
  1016. },
  1017. // Introduced in DOM Level 3:
  1018. lookupNamespaceURI:function(prefix){
  1019. var el = this;
  1020. while(el){
  1021. var map = el._nsMap;
  1022. //console.dir(map)
  1023. if(map){
  1024. if(prefix in map){
  1025. return map[prefix] ;
  1026. }
  1027. }
  1028. el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
  1029. }
  1030. return null;
  1031. },
  1032. // Introduced in DOM Level 3:
  1033. isDefaultNamespace:function(namespaceURI){
  1034. var prefix = this.lookupPrefix(namespaceURI);
  1035. return prefix == null;
  1036. }
  1037. };
  1038. function _xmlEncoder(c){
  1039. return c == '<' && '&lt;' ||
  1040. c == '>' && '&gt;' ||
  1041. c == '&' && '&amp;' ||
  1042. c == '"' && '&quot;' ||
  1043. '&#'+c.charCodeAt()+';'
  1044. }
  1045. copy(NodeType,Node);
  1046. copy(NodeType,Node.prototype);
  1047. /**
  1048. * @param callback return true for continue,false for break
  1049. * @return boolean true: break visit;
  1050. */
  1051. function _visitNode(node,callback){
  1052. if(callback(node)){
  1053. return true;
  1054. }
  1055. if(node = node.firstChild){
  1056. do{
  1057. if(_visitNode(node,callback)){return true}
  1058. }while(node=node.nextSibling)
  1059. }
  1060. }
  1061. function Document(){
  1062. }
  1063. function _onAddAttribute(doc,el,newAttr){
  1064. doc && doc._inc++;
  1065. var ns = newAttr.namespaceURI ;
  1066. if(ns == 'http://www.w3.org/2000/xmlns/'){
  1067. //update namespace
  1068. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  1069. }
  1070. }
  1071. function _onRemoveAttribute(doc,el,newAttr,remove){
  1072. doc && doc._inc++;
  1073. var ns = newAttr.namespaceURI ;
  1074. if(ns == 'http://www.w3.org/2000/xmlns/'){
  1075. //update namespace
  1076. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  1077. }
  1078. }
  1079. function _onUpdateChild(doc,el,newChild){
  1080. if(doc && doc._inc){
  1081. doc._inc++;
  1082. //update childNodes
  1083. var cs = el.childNodes;
  1084. if(newChild){
  1085. cs[cs.length++] = newChild;
  1086. }else{
  1087. //console.log(1)
  1088. var child = el.firstChild;
  1089. var i = 0;
  1090. while(child){
  1091. cs[i++] = child;
  1092. child =child.nextSibling;
  1093. }
  1094. cs.length = i;
  1095. }
  1096. }
  1097. }
  1098. /**
  1099. * attributes;
  1100. * children;
  1101. *
  1102. * writeable properties:
  1103. * nodeValue,Attr:value,CharacterData:data
  1104. * prefix
  1105. */
  1106. function _removeChild(parentNode,child){
  1107. var previous = child.previousSibling;
  1108. var next = child.nextSibling;
  1109. if(previous){
  1110. previous.nextSibling = next;
  1111. }else{
  1112. parentNode.firstChild = next
  1113. }
  1114. if(next){
  1115. next.previousSibling = previous;
  1116. }else{
  1117. parentNode.lastChild = previous;
  1118. }
  1119. _onUpdateChild(parentNode.ownerDocument,parentNode);
  1120. return child;
  1121. }
  1122. /**
  1123. * preformance key(refChild == null)
  1124. */
  1125. function _insertBefore(parentNode,newChild,nextChild){
  1126. var cp = newChild.parentNode;
  1127. if(cp){
  1128. cp.removeChild(newChild);//remove and update
  1129. }
  1130. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  1131. var newFirst = newChild.firstChild;
  1132. if (newFirst == null) {
  1133. return newChild;
  1134. }
  1135. var newLast = newChild.lastChild;
  1136. }else{
  1137. newFirst = newLast = newChild;
  1138. }
  1139. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  1140. newFirst.previousSibling = pre;
  1141. newLast.nextSibling = nextChild;
  1142. if(pre){
  1143. pre.nextSibling = newFirst;
  1144. }else{
  1145. parentNode.firstChild = newFirst;
  1146. }
  1147. if(nextChild == null){
  1148. parentNode.lastChild = newLast;
  1149. }else{
  1150. nextChild.previousSibling = newLast;
  1151. }
  1152. do{
  1153. newFirst.parentNode = parentNode;
  1154. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  1155. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  1156. //console.log(parentNode.lastChild.nextSibling == null)
  1157. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  1158. newChild.firstChild = newChild.lastChild = null;
  1159. }
  1160. return newChild;
  1161. }
  1162. function _appendSingleChild(parentNode,newChild){
  1163. var cp = newChild.parentNode;
  1164. if(cp){
  1165. var pre = parentNode.lastChild;
  1166. cp.removeChild(newChild);//remove and update
  1167. var pre = parentNode.lastChild;
  1168. }
  1169. var pre = parentNode.lastChild;
  1170. newChild.parentNode = parentNode;
  1171. newChild.previousSibling = pre;
  1172. newChild.nextSibling = null;
  1173. if(pre){
  1174. pre.nextSibling = newChild;
  1175. }else{
  1176. parentNode.firstChild = newChild;
  1177. }
  1178. parentNode.lastChild = newChild;
  1179. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  1180. return newChild;
  1181. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  1182. }
  1183. Document.prototype = {
  1184. //implementation : null,
  1185. nodeName : '#document',
  1186. nodeType : DOCUMENT_NODE,
  1187. doctype : null,
  1188. documentElement : null,
  1189. _inc : 1,
  1190. insertBefore : function(newChild, refChild){//raises
  1191. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  1192. var child = newChild.firstChild;
  1193. while(child){
  1194. var next = child.nextSibling;
  1195. this.insertBefore(child,refChild);
  1196. child = next;
  1197. }
  1198. return newChild;
  1199. }
  1200. if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
  1201. this.documentElement = newChild;
  1202. }
  1203. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  1204. },
  1205. removeChild : function(oldChild){
  1206. if(this.documentElement == oldChild){
  1207. this.documentElement = null;
  1208. }
  1209. return _removeChild(this,oldChild);
  1210. },
  1211. // Introduced in DOM Level 2:
  1212. importNode : function(importedNode,deep){
  1213. return importNode(this,importedNode,deep);
  1214. },
  1215. // Introduced in DOM Level 2:
  1216. getElementById : function(id){
  1217. var rtv = null;
  1218. _visitNode(this.documentElement,function(node){
  1219. if(node.nodeType == ELEMENT_NODE){
  1220. if(node.getAttribute('id') == id){
  1221. rtv = node;
  1222. return true;
  1223. }
  1224. }
  1225. })
  1226. return rtv;
  1227. },
  1228. getElementsByClassName: function(className) {
  1229. var pattern = new RegExp("(^|\\s)" + className + "(\\s|$)");
  1230. return new LiveNodeList(this, function(base) {
  1231. var ls = [];
  1232. _visitNode(base.documentElement, function(node) {
  1233. if(node !== base && node.nodeType == ELEMENT_NODE) {
  1234. if(pattern.test(node.getAttribute('class'))) {
  1235. ls.push(node);
  1236. }
  1237. }
  1238. });
  1239. return ls;
  1240. });
  1241. },
  1242. //document factory method:
  1243. createElement : function(tagName){
  1244. var node = new Element();
  1245. node.ownerDocument = this;
  1246. node.nodeName = tagName;
  1247. node.tagName = tagName;
  1248. node.childNodes = new NodeList();
  1249. var attrs = node.attributes = new NamedNodeMap();
  1250. attrs._ownerElement = node;
  1251. return node;
  1252. },
  1253. createDocumentFragment : function(){
  1254. var node = new DocumentFragment();
  1255. node.ownerDocument = this;
  1256. node.childNodes = new NodeList();
  1257. return node;
  1258. },
  1259. createTextNode : function(data){
  1260. var node = new Text();
  1261. node.ownerDocument = this;
  1262. node.appendData(data)
  1263. return node;
  1264. },
  1265. createComment : function(data){
  1266. var node = new Comment();
  1267. node.ownerDocument = this;
  1268. node.appendData(data)
  1269. return node;
  1270. },
  1271. createCDATASection : function(data){
  1272. var node = new CDATASection();
  1273. node.ownerDocument = this;
  1274. node.appendData(data)
  1275. return node;
  1276. },
  1277. createProcessingInstruction : function(target,data){
  1278. var node = new ProcessingInstruction();
  1279. node.ownerDocument = this;
  1280. node.tagName = node.target = target;
  1281. node.nodeValue= node.data = data;
  1282. return node;
  1283. },
  1284. createAttribute : function(name){
  1285. var node = new Attr();
  1286. node.ownerDocument = this;
  1287. node.name = name;
  1288. node.nodeName = name;
  1289. node.localName = name;
  1290. node.specified = true;
  1291. return node;
  1292. },
  1293. createEntityReference : function(name){
  1294. var node = new EntityReference();
  1295. node.ownerDocument = this;
  1296. node.nodeName = name;
  1297. return node;
  1298. },
  1299. // Introduced in DOM Level 2:
  1300. createElementNS : function(namespaceURI,qualifiedName){
  1301. var node = new Element();
  1302. var pl = qualifiedName.split(':');
  1303. var attrs = node.attributes = new NamedNodeMap();
  1304. node.childNodes = new NodeList();
  1305. node.ownerDocument = this;
  1306. node.nodeName = qualifiedName;
  1307. node.tagName = qualifiedName;
  1308. node.namespaceURI = namespaceURI;
  1309. if(pl.length == 2){
  1310. node.prefix = pl[0];
  1311. node.localName = pl[1];
  1312. }else{
  1313. //el.prefix = null;
  1314. node.localName = qualifiedName;
  1315. }
  1316. attrs._ownerElement = node;
  1317. return node;
  1318. },
  1319. // Introduced in DOM Level 2:
  1320. createAttributeNS : function(namespaceURI,qualifiedName){
  1321. var node = new Attr();
  1322. var pl = qualifiedName.split(':');
  1323. node.ownerDocument = this;
  1324. node.nodeName = qualifiedName;
  1325. node.name = qualifiedName;
  1326. node.namespaceURI = namespaceURI;
  1327. node.specified = true;
  1328. if(pl.length == 2){
  1329. node.prefix = pl[0];
  1330. node.localName = pl[1];
  1331. }else{
  1332. //el.prefix = null;
  1333. node.localName = qualifiedName;
  1334. }
  1335. return node;
  1336. }
  1337. };
  1338. _extends(Document,Node);
  1339. function Element() {
  1340. this._nsMap = {};
  1341. };
  1342. Element.prototype = {
  1343. nodeType : ELEMENT_NODE,
  1344. hasAttribute : function(name){
  1345. return this.getAttributeNode(name)!=null;
  1346. },
  1347. getAttribute : function(name){
  1348. var attr = this.getAttributeNode(name);
  1349. return attr && attr.value || '';
  1350. },
  1351. getAttributeNode : function(name){
  1352. return this.attributes.getNamedItem(name);
  1353. },
  1354. setAttribute : function(name, value){
  1355. var attr = this.ownerDocument.createAttribute(name);
  1356. attr.value = attr.nodeValue = "" + value;
  1357. this.setAttributeNode(attr)
  1358. },
  1359. removeAttribute : function(name){
  1360. var attr = this.getAttributeNode(name)
  1361. attr && this.removeAttributeNode(attr);
  1362. },
  1363. //four real opeartion method
  1364. appendChild:function(newChild){
  1365. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  1366. return this.insertBefore(newChild,null);
  1367. }else{
  1368. return _appendSingleChild(this,newChild);
  1369. }
  1370. },
  1371. setAttributeNode : function(newAttr){
  1372. return this.attributes.setNamedItem(newAttr);
  1373. },
  1374. setAttributeNodeNS : function(newAttr){
  1375. return this.attributes.setNamedItemNS(newAttr);
  1376. },
  1377. removeAttributeNode : function(oldAttr){
  1378. //console.log(this == oldAttr.ownerElement)
  1379. return this.attributes.removeNamedItem(oldAttr.nodeName);
  1380. },
  1381. //get real attribute name,and remove it by removeAttributeNode
  1382. removeAttributeNS : function(namespaceURI, localName){
  1383. var old = this.getAttributeNodeNS(namespaceURI, localName);
  1384. old && this.removeAttributeNode(old);
  1385. },
  1386. hasAttributeNS : function(namespaceURI, localName){
  1387. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  1388. },
  1389. getAttributeNS : function(namespaceURI, localName){
  1390. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  1391. return attr && attr.value || '';
  1392. },
  1393. setAttributeNS : function(namespaceURI, qualifiedName, value){
  1394. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  1395. attr.value = attr.nodeValue = "" + value;
  1396. this.setAttributeNode(attr)
  1397. },
  1398. getAttributeNodeNS : function(namespaceURI, localName){
  1399. return this.attributes.getNamedItemNS(namespaceURI, localName);
  1400. },
  1401. getElementsByTagName : function(tagName){
  1402. return new LiveNodeList(this,function(base){
  1403. var ls = [];
  1404. _visitNode(base,function(node){
  1405. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  1406. ls.push(node);
  1407. }
  1408. });
  1409. return ls;
  1410. });
  1411. },
  1412. getElementsByTagNameNS : function(namespaceURI, localName){
  1413. return new LiveNodeList(this,function(base){
  1414. var ls = [];
  1415. _visitNode(base,function(node){
  1416. if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
  1417. ls.push(node);
  1418. }
  1419. });
  1420. return ls;
  1421. });
  1422. }
  1423. };
  1424. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  1425. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  1426. _extends(Element,Node);
  1427. function Attr() {
  1428. };
  1429. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  1430. _extends(Attr,Node);
  1431. function CharacterData() {
  1432. };
  1433. CharacterData.prototype = {
  1434. data : '',
  1435. substringData : function(offset, count) {
  1436. return this.data.substring(offset, offset+count);
  1437. },
  1438. appendData: function(text) {
  1439. text = this.data+text;
  1440. this.nodeValue = this.data = text;
  1441. this.length = text.length;
  1442. },
  1443. insertData: function(offset,text) {
  1444. this.replaceData(offset,0,text);
  1445. },
  1446. appendChild:function(newChild){
  1447. throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
  1448. },
  1449. deleteData: function(offset, count) {
  1450. this.replaceData(offset,count,"");
  1451. },
  1452. replaceData: function(offset, count, text) {
  1453. var start = this.data.substring(0,offset);
  1454. var end = this.data.substring(offset+count);
  1455. text = start + text + end;
  1456. this.nodeValue = this.data = text;
  1457. this.length = text.length;
  1458. }
  1459. }
  1460. _extends(CharacterData,Node);
  1461. function Text() {
  1462. };
  1463. Text.prototype = {
  1464. nodeName : "#text",
  1465. nodeType : TEXT_NODE,
  1466. splitText : function(offset) {
  1467. var text = this.data;
  1468. var newText = text.substring(offset);
  1469. text = text.substring(0, offset);
  1470. this.data = this.nodeValue = text;
  1471. this.length = text.length;
  1472. var newNode = this.ownerDocument.createTextNode(newText);
  1473. if(this.parentNode){
  1474. this.parentNode.insertBefore(newNode, this.nextSibling);
  1475. }
  1476. return newNode;
  1477. }
  1478. }
  1479. _extends(Text,CharacterData);
  1480. function Comment() {
  1481. };
  1482. Comment.prototype = {
  1483. nodeName : "#comment",
  1484. nodeType : COMMENT_NODE
  1485. }
  1486. _extends(Comment,CharacterData);
  1487. function CDATASection() {
  1488. };
  1489. CDATASection.prototype = {
  1490. nodeName : "#cdata-section",
  1491. nodeType : CDATA_SECTION_NODE
  1492. }
  1493. _extends(CDATASection,CharacterData);
  1494. function DocumentType() {
  1495. };
  1496. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  1497. _extends(DocumentType,Node);
  1498. function Notation() {
  1499. };
  1500. Notation.prototype.nodeType = NOTATION_NODE;
  1501. _extends(Notation,Node);
  1502. function Entity() {
  1503. };
  1504. Entity.prototype.nodeType = ENTITY_NODE;
  1505. _extends(Entity,Node);
  1506. function EntityReference() {
  1507. };
  1508. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  1509. _extends(EntityReference,Node);
  1510. function DocumentFragment() {
  1511. };
  1512. DocumentFragment.prototype.nodeName = "#document-fragment";
  1513. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  1514. _extends(DocumentFragment,Node);
  1515. function ProcessingInstruction() {
  1516. }
  1517. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  1518. _extends(ProcessingInstruction,Node);
  1519. function XMLSerializer(){}
  1520. XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
  1521. return nodeSerializeToString.call(node,isHtml,nodeFilter);
  1522. }
  1523. Node.prototype.toString = nodeSerializeToString;
  1524. function nodeSerializeToString(isHtml,nodeFilter){
  1525. var buf = [];
  1526. var refNode = this.nodeType == 9 && this.documentElement || this;
  1527. var prefix = refNode.prefix;
  1528. var uri = refNode.namespaceURI;
  1529. if(uri && prefix == null){
  1530. //console.log(prefix)
  1531. var prefix = refNode.lookupPrefix(uri);
  1532. if(prefix == null){
  1533. //isHTML = true;
  1534. var visibleNamespaces=[
  1535. {namespace:uri,prefix:null}
  1536. //{namespace:uri,prefix:''}
  1537. ]
  1538. }
  1539. }
  1540. serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
  1541. //console.log('###',this.nodeType,uri,prefix,buf.join(''))
  1542. return buf.join('');
  1543. }
  1544. function needNamespaceDefine(node,isHTML, visibleNamespaces) {
  1545. var prefix = node.prefix||'';
  1546. var uri = node.namespaceURI;
  1547. if (!prefix && !uri){
  1548. return false;
  1549. }
  1550. if (prefix === "xml" && uri === "http://www.w3.org/XML/1998/namespace"
  1551. || uri == 'http://www.w3.org/2000/xmlns/'){
  1552. return false;
  1553. }
  1554. var i = visibleNamespaces.length
  1555. //console.log('@@@@',node.tagName,prefix,uri,visibleNamespaces)
  1556. while (i--) {
  1557. var ns = visibleNamespaces[i];
  1558. // get namespace prefix
  1559. //console.log(node.nodeType,node.tagName,ns.prefix,prefix)
  1560. if (ns.prefix == prefix){
  1561. return ns.namespace != uri;
  1562. }
  1563. }
  1564. //console.log(isHTML,uri,prefix=='')
  1565. //if(isHTML && prefix ==null && uri == 'http://www.w3.org/1999/xhtml'){
  1566. // return false;
  1567. //}
  1568. //node.flag = '11111'
  1569. //console.error(3,true,node.flag,node.prefix,node.namespaceURI)
  1570. return true;
  1571. }
  1572. function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
  1573. if(nodeFilter){
  1574. node = nodeFilter(node);
  1575. if(node){
  1576. if(typeof node == 'string'){
  1577. buf.push(node);
  1578. return;
  1579. }
  1580. }else{
  1581. return;
  1582. }
  1583. //buf.sort.apply(attrs, attributeSorter);
  1584. }
  1585. switch(node.nodeType){
  1586. case ELEMENT_NODE:
  1587. if (!visibleNamespaces) visibleNamespaces = [];
  1588. var startVisibleNamespaces = visibleNamespaces.length;
  1589. var attrs = node.attributes;
  1590. var len = attrs.length;
  1591. var child = node.firstChild;
  1592. var nodeName = node.tagName;
  1593. isHTML = (htmlns === node.namespaceURI) ||isHTML
  1594. buf.push('<',nodeName);
  1595. for(var i=0;i<len;i++){
  1596. // add namespaces for attributes
  1597. var attr = attrs.item(i);
  1598. if (attr.prefix == 'xmlns') {
  1599. visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
  1600. }else if(attr.nodeName == 'xmlns'){
  1601. visibleNamespaces.push({ prefix: '', namespace: attr.value });
  1602. }
  1603. }
  1604. for(var i=0;i<len;i++){
  1605. var attr = attrs.item(i);
  1606. if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
  1607. var prefix = attr.prefix||'';
  1608. var uri = attr.namespaceURI;
  1609. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1610. buf.push(ns, '="' , uri , '"');
  1611. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1612. }
  1613. serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
  1614. }
  1615. // add namespace for current node
  1616. if (needNamespaceDefine(node,isHTML, visibleNamespaces)) {
  1617. var prefix = node.prefix||'';
  1618. var uri = node.namespaceURI;
  1619. if (uri) {
  1620. // Avoid empty namespace value like xmlns:ds=""
  1621. // Empty namespace URL will we produce an invalid XML document
  1622. var ns = prefix ? ' xmlns:' + prefix : " xmlns";
  1623. buf.push(ns, '="' , uri , '"');
  1624. visibleNamespaces.push({ prefix: prefix, namespace:uri });
  1625. }
  1626. }
  1627. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  1628. buf.push('>');
  1629. //if is cdata child node
  1630. if(isHTML && /^script$/i.test(nodeName)){
  1631. while(child){
  1632. if(child.data){
  1633. buf.push(child.data);
  1634. }else{
  1635. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1636. }
  1637. child = child.nextSibling;
  1638. }
  1639. }else
  1640. {
  1641. while(child){
  1642. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1643. child = child.nextSibling;
  1644. }
  1645. }
  1646. buf.push('</',nodeName,'>');
  1647. }else{
  1648. buf.push('/>');
  1649. }
  1650. // remove added visible namespaces
  1651. //visibleNamespaces.length = startVisibleNamespaces;
  1652. return;
  1653. case DOCUMENT_NODE:
  1654. case DOCUMENT_FRAGMENT_NODE:
  1655. var child = node.firstChild;
  1656. while(child){
  1657. serializeToString(child,buf,isHTML,nodeFilter,visibleNamespaces);
  1658. child = child.nextSibling;
  1659. }
  1660. return;
  1661. case ATTRIBUTE_NODE:
  1662. /**
  1663. * Well-formedness constraint: No < in Attribute Values
  1664. * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
  1665. * @see https://www.w3.org/TR/xml/#CleanAttrVals
  1666. * @see https://www.w3.org/TR/xml/#NT-AttValue
  1667. */
  1668. return buf.push(' ', node.name, '="', node.value.replace(/[<&"]/g,_xmlEncoder), '"');
  1669. case TEXT_NODE:
  1670. /**
  1671. * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
  1672. * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
  1673. * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
  1674. * `&amp;` and `&lt;` respectively.
  1675. * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
  1676. * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
  1677. * when that string is not marking the end of a CDATA section.
  1678. *
  1679. * In the content of elements, character data is any string of characters
  1680. * which does not contain the start-delimiter of any markup
  1681. * and does not include the CDATA-section-close delimiter, `]]>`.
  1682. *
  1683. * @see https://www.w3.org/TR/xml/#NT-CharData
  1684. */
  1685. return buf.push(node.data
  1686. .replace(/[<&]/g,_xmlEncoder)
  1687. .replace(/]]>/g, ']]&gt;')
  1688. );
  1689. case CDATA_SECTION_NODE:
  1690. return buf.push( '<![CDATA[',node.data,']]>');
  1691. case COMMENT_NODE:
  1692. return buf.push( "<!--",node.data,"-->");
  1693. case DOCUMENT_TYPE_NODE:
  1694. var pubid = node.publicId;
  1695. var sysid = node.systemId;
  1696. buf.push('<!DOCTYPE ',node.name);
  1697. if(pubid){
  1698. buf.push(' PUBLIC ', pubid);
  1699. if (sysid && sysid!='.') {
  1700. buf.push(' ', sysid);
  1701. }
  1702. buf.push('>');
  1703. }else if(sysid && sysid!='.'){
  1704. buf.push(' SYSTEM ', sysid, '>');
  1705. }else{
  1706. var sub = node.internalSubset;
  1707. if(sub){
  1708. buf.push(" [",sub,"]");
  1709. }
  1710. buf.push(">");
  1711. }
  1712. return;
  1713. case PROCESSING_INSTRUCTION_NODE:
  1714. return buf.push( "<?",node.target," ",node.data,"?>");
  1715. case ENTITY_REFERENCE_NODE:
  1716. return buf.push( '&',node.nodeName,';');
  1717. //case ENTITY_NODE:
  1718. //case NOTATION_NODE:
  1719. default:
  1720. buf.push('??',node.nodeName);
  1721. }
  1722. }
  1723. function importNode(doc,node,deep){
  1724. var node2;
  1725. switch (node.nodeType) {
  1726. case ELEMENT_NODE:
  1727. node2 = node.cloneNode(false);
  1728. node2.ownerDocument = doc;
  1729. //var attrs = node2.attributes;
  1730. //var len = attrs.length;
  1731. //for(var i=0;i<len;i++){
  1732. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  1733. //}
  1734. case DOCUMENT_FRAGMENT_NODE:
  1735. break;
  1736. case ATTRIBUTE_NODE:
  1737. deep = true;
  1738. break;
  1739. //case ENTITY_REFERENCE_NODE:
  1740. //case PROCESSING_INSTRUCTION_NODE:
  1741. ////case TEXT_NODE:
  1742. //case CDATA_SECTION_NODE:
  1743. //case COMMENT_NODE:
  1744. // deep = false;
  1745. // break;
  1746. //case DOCUMENT_NODE:
  1747. //case DOCUMENT_TYPE_NODE:
  1748. //cannot be imported.
  1749. //case ENTITY_NODE:
  1750. //case NOTATION_NODE:
  1751. //can not hit in level3
  1752. //default:throw e;
  1753. }
  1754. if(!node2){
  1755. node2 = node.cloneNode(false);//false
  1756. }
  1757. node2.ownerDocument = doc;
  1758. node2.parentNode = null;
  1759. if(deep){
  1760. var child = node.firstChild;
  1761. while(child){
  1762. node2.appendChild(importNode(doc,child,deep));
  1763. child = child.nextSibling;
  1764. }
  1765. }
  1766. return node2;
  1767. }
  1768. //
  1769. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  1770. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  1771. function cloneNode(doc,node,deep){
  1772. var node2 = new node.constructor();
  1773. for(var n in node){
  1774. var v = node[n];
  1775. if(typeof v != 'object' ){
  1776. if(v != node2[n]){
  1777. node2[n] = v;
  1778. }
  1779. }
  1780. }
  1781. if(node.childNodes){
  1782. node2.childNodes = new NodeList();
  1783. }
  1784. node2.ownerDocument = doc;
  1785. switch (node2.nodeType) {
  1786. case ELEMENT_NODE:
  1787. var attrs = node.attributes;
  1788. var attrs2 = node2.attributes = new NamedNodeMap();
  1789. var len = attrs.length
  1790. attrs2._ownerElement = node2;
  1791. for(var i=0;i<len;i++){
  1792. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  1793. }
  1794. break;;
  1795. case ATTRIBUTE_NODE:
  1796. deep = true;
  1797. }
  1798. if(deep){
  1799. var child = node.firstChild;
  1800. while(child){
  1801. node2.appendChild(cloneNode(doc,child,deep));
  1802. child = child.nextSibling;
  1803. }
  1804. }
  1805. return node2;
  1806. }
  1807. function __set__(object,key,value){
  1808. object[key] = value
  1809. }
  1810. //do dynamic
  1811. try{
  1812. if(Object.defineProperty){
  1813. Object.defineProperty(LiveNodeList.prototype,'length',{
  1814. get:function(){
  1815. _updateLiveList(this);
  1816. return this.$$length;
  1817. }
  1818. });
  1819. Object.defineProperty(Node.prototype,'textContent',{
  1820. get:function(){
  1821. return getTextContent(this);
  1822. },
  1823. set:function(data){
  1824. switch(this.nodeType){
  1825. case ELEMENT_NODE:
  1826. case DOCUMENT_FRAGMENT_NODE:
  1827. while(this.firstChild){
  1828. this.removeChild(this.firstChild);
  1829. }
  1830. if(data || String(data)){
  1831. this.appendChild(this.ownerDocument.createTextNode(data));
  1832. }
  1833. break;
  1834. default:
  1835. //TODO:
  1836. this.data = data;
  1837. this.value = data;
  1838. this.nodeValue = data;
  1839. }
  1840. }
  1841. })
  1842. function getTextContent(node){
  1843. switch(node.nodeType){
  1844. case ELEMENT_NODE:
  1845. case DOCUMENT_FRAGMENT_NODE:
  1846. var buf = [];
  1847. node = node.firstChild;
  1848. while(node){
  1849. if(node.nodeType!==7 && node.nodeType !==8){
  1850. buf.push(getTextContent(node));
  1851. }
  1852. node = node.nextSibling;
  1853. }
  1854. return buf.join('');
  1855. default:
  1856. return node.nodeValue;
  1857. }
  1858. }
  1859. __set__ = function(object,key,value){
  1860. //console.log(value)
  1861. object['$$'+key] = value
  1862. }
  1863. }
  1864. }catch(e){//ie8
  1865. }
  1866. //if(typeof require == 'function'){
  1867. exports.Node = Node;
  1868. exports.DOMException = DOMException;
  1869. exports.DOMImplementation = DOMImplementation;
  1870. exports.XMLSerializer = XMLSerializer;
  1871. //}
  1872. /***/ }),
  1873. /* 5 */
  1874. /***/ (function(module, exports, __webpack_require__) {
  1875. /* WEBPACK VAR INJECTION */(function(Buffer, global, setImmediate) {var require;var require;/*!
  1876. JSZip v3.7.1 - A JavaScript class for generating and reading zip files
  1877. <http://stuartk.com/jszip>
  1878. (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
  1879. Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown.
  1880. JSZip uses the library pako released under the MIT license :
  1881. https://github.com/nodeca/pako/blob/master/LICENSE
  1882. */
  1883. !function(t){if(true)module.exports=t();else {}}(function(){return function s(a,o,h){function u(r,t){if(!o[r]){if(!a[r]){var e="function"==typeof require&&require;if(!t&&__webpack_require__(12))return require(r,!0);if(l)return l(r,!0);var i=new Error("Cannot find module '"+r+"'");throw i.code="MODULE_NOT_FOUND",i}var n=o[r]={exports:{}};a[r][0].call(n.exports,function(t){var e=a[r][1][t];return u(e||t)},n,n.exports,s,a,o,h)}return o[r].exports}for(var l="function"==typeof require&&require,t=0;t<h.length;t++)u(h[t]);return u}({1:[function(t,e,r){"use strict";var c=t("./utils"),d=t("./support"),p="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.encode=function(t){for(var e,r,i,n,s,a,o,h=[],u=0,l=t.length,f=l,d="string"!==c.getTypeOf(t);u<t.length;)f=l-u,i=d?(e=t[u++],r=u<l?t[u++]:0,u<l?t[u++]:0):(e=t.charCodeAt(u++),r=u<l?t.charCodeAt(u++):0,u<l?t.charCodeAt(u++):0),n=e>>2,s=(3&e)<<4|r>>4,a=1<f?(15&r)<<2|i>>6:64,o=2<f?63&i:64,h.push(p.charAt(n)+p.charAt(s)+p.charAt(a)+p.charAt(o));return h.join("")},r.decode=function(t){var e,r,i,n,s,a,o=0,h=0,u="data:";if(t.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var l,f=3*(t=t.replace(/[^A-Za-z0-9\+\/\=]/g,"")).length/4;if(t.charAt(t.length-1)===p.charAt(64)&&f--,t.charAt(t.length-2)===p.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(l=d.uint8array?new Uint8Array(0|f):new Array(0|f);o<t.length;)e=p.indexOf(t.charAt(o++))<<2|(n=p.indexOf(t.charAt(o++)))>>4,r=(15&n)<<4|(s=p.indexOf(t.charAt(o++)))>>2,i=(3&s)<<6|(a=p.indexOf(t.charAt(o++))),l[h++]=e,64!==s&&(l[h++]=r),64!==a&&(l[h++]=i);return l}},{"./support":30,"./utils":32}],2:[function(t,e,r){"use strict";var i=t("./external"),n=t("./stream/DataWorker"),s=t("./stream/Crc32Probe"),a=t("./stream/DataLengthProbe");function o(t,e,r,i,n){this.compressedSize=t,this.uncompressedSize=e,this.crc32=r,this.compression=i,this.compressedContent=n}o.prototype={getContentWorker:function(){var t=new n(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),e=this;return t.on("end",function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),t},getCompressedWorker:function(){return new n(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(t,e,r){return t.pipe(new s).pipe(new a("uncompressedSize")).pipe(e.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression",e)},e.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,r){"use strict";var i=t("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(t){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},r.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,r){"use strict";var i=t("./utils");var o=function(){for(var t,e=[],r=0;r<256;r++){t=r;for(var i=0;i<8;i++)t=1&t?3988292384^t>>>1:t>>>1;e[r]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==i.getTypeOf(t)?function(t,e,r,i){var n=o,s=i+r;t^=-1;for(var a=i;a<s;a++)t=t>>>8^n[255&(t^e[a])];return-1^t}(0|e,t,t.length,0):function(t,e,r,i){var n=o,s=i+r;t^=-1;for(var a=i;a<s;a++)t=t>>>8^n[255&(t^e.charCodeAt(a))];return-1^t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,r){"use strict";r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(t,e,r){"use strict";var i=null;i="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:i}},{lie:37}],7:[function(t,e,r){"use strict";var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array
  1884. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(6).Buffer, __webpack_require__(1), __webpack_require__(10).setImmediate))
  1885. /***/ }),
  1886. /* 6 */
  1887. /***/ (function(module, exports, __webpack_require__) {
  1888. "use strict";
  1889. /* WEBPACK VAR INJECTION */(function(global) {/*!
  1890. * The buffer module from node.js, for the browser.
  1891. *
  1892. * @author Feross Aboukhadijeh <http://feross.org>
  1893. * @license MIT
  1894. */
  1895. /* eslint-disable no-proto */
  1896. var base64 = __webpack_require__(7)
  1897. var ieee754 = __webpack_require__(8)
  1898. var isArray = __webpack_require__(9)
  1899. exports.Buffer = Buffer
  1900. exports.SlowBuffer = SlowBuffer
  1901. exports.INSPECT_MAX_BYTES = 50
  1902. /**
  1903. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  1904. * === true Use Uint8Array implementation (fastest)
  1905. * === false Use Object implementation (most compatible, even IE6)
  1906. *
  1907. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  1908. * Opera 11.6+, iOS 4.2+.
  1909. *
  1910. * Due to various browser bugs, sometimes the Object implementation will be used even
  1911. * when the browser supports typed arrays.
  1912. *
  1913. * Note:
  1914. *
  1915. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  1916. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  1917. *
  1918. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  1919. *
  1920. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  1921. * incorrect length in some situations.
  1922. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  1923. * get the Object implementation, which is slower but behaves correctly.
  1924. */
  1925. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  1926. ? global.TYPED_ARRAY_SUPPORT
  1927. : typedArraySupport()
  1928. /*
  1929. * Export kMaxLength after typed array support is determined.
  1930. */
  1931. exports.kMaxLength = kMaxLength()
  1932. function typedArraySupport () {
  1933. try {
  1934. var arr = new Uint8Array(1)
  1935. arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
  1936. return arr.foo() === 42 && // typed array instances can be augmented
  1937. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  1938. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  1939. } catch (e) {
  1940. return false
  1941. }
  1942. }
  1943. function kMaxLength () {
  1944. return Buffer.TYPED_ARRAY_SUPPORT
  1945. ? 0x7fffffff
  1946. : 0x3fffffff
  1947. }
  1948. function createBuffer (that, length) {
  1949. if (kMaxLength() < length) {
  1950. throw new RangeError('Invalid typed array length')
  1951. }
  1952. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1953. // Return an augmented `Uint8Array` instance, for best performance
  1954. that = new Uint8Array(length)
  1955. that.__proto__ = Buffer.prototype
  1956. } else {
  1957. // Fallback: Return an object instance of the Buffer class
  1958. if (that === null) {
  1959. that = new Buffer(length)
  1960. }
  1961. that.length = length
  1962. }
  1963. return that
  1964. }
  1965. /**
  1966. * The Buffer constructor returns instances of `Uint8Array` that have their
  1967. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  1968. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  1969. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  1970. * returns a single octet.
  1971. *
  1972. * The `Uint8Array` prototype remains unmodified.
  1973. */
  1974. function Buffer (arg, encodingOrOffset, length) {
  1975. if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
  1976. return new Buffer(arg, encodingOrOffset, length)
  1977. }
  1978. // Common case.
  1979. if (typeof arg === 'number') {
  1980. if (typeof encodingOrOffset === 'string') {
  1981. throw new Error(
  1982. 'If encoding is specified then the first argument must be a string'
  1983. )
  1984. }
  1985. return allocUnsafe(this, arg)
  1986. }
  1987. return from(this, arg, encodingOrOffset, length)
  1988. }
  1989. Buffer.poolSize = 8192 // not used by this implementation
  1990. // TODO: Legacy, not needed anymore. Remove in next major version.
  1991. Buffer._augment = function (arr) {
  1992. arr.__proto__ = Buffer.prototype
  1993. return arr
  1994. }
  1995. function from (that, value, encodingOrOffset, length) {
  1996. if (typeof value === 'number') {
  1997. throw new TypeError('"value" argument must not be a number')
  1998. }
  1999. if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
  2000. return fromArrayBuffer(that, value, encodingOrOffset, length)
  2001. }
  2002. if (typeof value === 'string') {
  2003. return fromString(that, value, encodingOrOffset)
  2004. }
  2005. return fromObject(that, value)
  2006. }
  2007. /**
  2008. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2009. * if value is a number.
  2010. * Buffer.from(str[, encoding])
  2011. * Buffer.from(array)
  2012. * Buffer.from(buffer)
  2013. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2014. **/
  2015. Buffer.from = function (value, encodingOrOffset, length) {
  2016. return from(null, value, encodingOrOffset, length)
  2017. }
  2018. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2019. Buffer.prototype.__proto__ = Uint8Array.prototype
  2020. Buffer.__proto__ = Uint8Array
  2021. if (typeof Symbol !== 'undefined' && Symbol.species &&
  2022. Buffer[Symbol.species] === Buffer) {
  2023. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2024. Object.defineProperty(Buffer, Symbol.species, {
  2025. value: null,
  2026. configurable: true
  2027. })
  2028. }
  2029. }
  2030. function assertSize (size) {
  2031. if (typeof size !== 'number') {
  2032. throw new TypeError('"size" argument must be a number')
  2033. } else if (size < 0) {
  2034. throw new RangeError('"size" argument must not be negative')
  2035. }
  2036. }
  2037. function alloc (that, size, fill, encoding) {
  2038. assertSize(size)
  2039. if (size <= 0) {
  2040. return createBuffer(that, size)
  2041. }
  2042. if (fill !== undefined) {
  2043. // Only pay attention to encoding if it's a string. This
  2044. // prevents accidentally sending in a number that would
  2045. // be interpretted as a start offset.
  2046. return typeof encoding === 'string'
  2047. ? createBuffer(that, size).fill(fill, encoding)
  2048. : createBuffer(that, size).fill(fill)
  2049. }
  2050. return createBuffer(that, size)
  2051. }
  2052. /**
  2053. * Creates a new filled Buffer instance.
  2054. * alloc(size[, fill[, encoding]])
  2055. **/
  2056. Buffer.alloc = function (size, fill, encoding) {
  2057. return alloc(null, size, fill, encoding)
  2058. }
  2059. function allocUnsafe (that, size) {
  2060. assertSize(size)
  2061. that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
  2062. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  2063. for (var i = 0; i < size; ++i) {
  2064. that[i] = 0
  2065. }
  2066. }
  2067. return that
  2068. }
  2069. /**
  2070. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2071. * */
  2072. Buffer.allocUnsafe = function (size) {
  2073. return allocUnsafe(null, size)
  2074. }
  2075. /**
  2076. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2077. */
  2078. Buffer.allocUnsafeSlow = function (size) {
  2079. return allocUnsafe(null, size)
  2080. }
  2081. function fromString (that, string, encoding) {
  2082. if (typeof encoding !== 'string' || encoding === '') {
  2083. encoding = 'utf8'
  2084. }
  2085. if (!Buffer.isEncoding(encoding)) {
  2086. throw new TypeError('"encoding" must be a valid string encoding')
  2087. }
  2088. var length = byteLength(string, encoding) | 0
  2089. that = createBuffer(that, length)
  2090. var actual = that.write(string, encoding)
  2091. if (actual !== length) {
  2092. // Writing a hex string, for example, that contains invalid characters will
  2093. // cause everything after the first invalid character to be ignored. (e.g.
  2094. // 'abxxcd' will be treated as 'ab')
  2095. that = that.slice(0, actual)
  2096. }
  2097. return that
  2098. }
  2099. function fromArrayLike (that, array) {
  2100. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2101. that = createBuffer(that, length)
  2102. for (var i = 0; i < length; i += 1) {
  2103. that[i] = array[i] & 255
  2104. }
  2105. return that
  2106. }
  2107. function fromArrayBuffer (that, array, byteOffset, length) {
  2108. array.byteLength // this throws if `array` is not a valid ArrayBuffer
  2109. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2110. throw new RangeError('\'offset\' is out of bounds')
  2111. }
  2112. if (array.byteLength < byteOffset + (length || 0)) {
  2113. throw new RangeError('\'length\' is out of bounds')
  2114. }
  2115. if (byteOffset === undefined && length === undefined) {
  2116. array = new Uint8Array(array)
  2117. } else if (length === undefined) {
  2118. array = new Uint8Array(array, byteOffset)
  2119. } else {
  2120. array = new Uint8Array(array, byteOffset, length)
  2121. }
  2122. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2123. // Return an augmented `Uint8Array` instance, for best performance
  2124. that = array
  2125. that.__proto__ = Buffer.prototype
  2126. } else {
  2127. // Fallback: Return an object instance of the Buffer class
  2128. that = fromArrayLike(that, array)
  2129. }
  2130. return that
  2131. }
  2132. function fromObject (that, obj) {
  2133. if (Buffer.isBuffer(obj)) {
  2134. var len = checked(obj.length) | 0
  2135. that = createBuffer(that, len)
  2136. if (that.length === 0) {
  2137. return that
  2138. }
  2139. obj.copy(that, 0, 0, len)
  2140. return that
  2141. }
  2142. if (obj) {
  2143. if ((typeof ArrayBuffer !== 'undefined' &&
  2144. obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
  2145. if (typeof obj.length !== 'number' || isnan(obj.length)) {
  2146. return createBuffer(that, 0)
  2147. }
  2148. return fromArrayLike(that, obj)
  2149. }
  2150. if (obj.type === 'Buffer' && isArray(obj.data)) {
  2151. return fromArrayLike(that, obj.data)
  2152. }
  2153. }
  2154. throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
  2155. }
  2156. function checked (length) {
  2157. // Note: cannot use `length < kMaxLength()` here because that fails when
  2158. // length is NaN (which is otherwise coerced to zero.)
  2159. if (length >= kMaxLength()) {
  2160. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2161. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  2162. }
  2163. return length | 0
  2164. }
  2165. function SlowBuffer (length) {
  2166. if (+length != length) { // eslint-disable-line eqeqeq
  2167. length = 0
  2168. }
  2169. return Buffer.alloc(+length)
  2170. }
  2171. Buffer.isBuffer = function isBuffer (b) {
  2172. return !!(b != null && b._isBuffer)
  2173. }
  2174. Buffer.compare = function compare (a, b) {
  2175. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2176. throw new TypeError('Arguments must be Buffers')
  2177. }
  2178. if (a === b) return 0
  2179. var x = a.length
  2180. var y = b.length
  2181. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2182. if (a[i] !== b[i]) {
  2183. x = a[i]
  2184. y = b[i]
  2185. break
  2186. }
  2187. }
  2188. if (x < y) return -1
  2189. if (y < x) return 1
  2190. return 0
  2191. }
  2192. Buffer.isEncoding = function isEncoding (encoding) {
  2193. switch (String(encoding).toLowerCase()) {
  2194. case 'hex':
  2195. case 'utf8':
  2196. case 'utf-8':
  2197. case 'ascii':
  2198. case 'latin1':
  2199. case 'binary':
  2200. case 'base64':
  2201. case 'ucs2':
  2202. case 'ucs-2':
  2203. case 'utf16le':
  2204. case 'utf-16le':
  2205. return true
  2206. default:
  2207. return false
  2208. }
  2209. }
  2210. Buffer.concat = function concat (list, length) {
  2211. if (!isArray(list)) {
  2212. throw new TypeError('"list" argument must be an Array of Buffers')
  2213. }
  2214. if (list.length === 0) {
  2215. return Buffer.alloc(0)
  2216. }
  2217. var i
  2218. if (length === undefined) {
  2219. length = 0
  2220. for (i = 0; i < list.length; ++i) {
  2221. length += list[i].length
  2222. }
  2223. }
  2224. var buffer = Buffer.allocUnsafe(length)
  2225. var pos = 0
  2226. for (i = 0; i < list.length; ++i) {
  2227. var buf = list[i]
  2228. if (!Buffer.isBuffer(buf)) {
  2229. throw new TypeError('"list" argument must be an Array of Buffers')
  2230. }
  2231. buf.copy(buffer, pos)
  2232. pos += buf.length
  2233. }
  2234. return buffer
  2235. }
  2236. function byteLength (string, encoding) {
  2237. if (Buffer.isBuffer(string)) {
  2238. return string.length
  2239. }
  2240. if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
  2241. (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
  2242. return string.byteLength
  2243. }
  2244. if (typeof string !== 'string') {
  2245. string = '' + string
  2246. }
  2247. var len = string.length
  2248. if (len === 0) return 0
  2249. // Use a for loop to avoid recursion
  2250. var loweredCase = false
  2251. for (;;) {
  2252. switch (encoding) {
  2253. case 'ascii':
  2254. case 'latin1':
  2255. case 'binary':
  2256. return len
  2257. case 'utf8':
  2258. case 'utf-8':
  2259. case undefined:
  2260. return utf8ToBytes(string).length
  2261. case 'ucs2':
  2262. case 'ucs-2':
  2263. case 'utf16le':
  2264. case 'utf-16le':
  2265. return len * 2
  2266. case 'hex':
  2267. return len >>> 1
  2268. case 'base64':
  2269. return base64ToBytes(string).length
  2270. default:
  2271. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  2272. encoding = ('' + encoding).toLowerCase()
  2273. loweredCase = true
  2274. }
  2275. }
  2276. }
  2277. Buffer.byteLength = byteLength
  2278. function slowToString (encoding, start, end) {
  2279. var loweredCase = false
  2280. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2281. // property of a typed array.
  2282. // This behaves neither like String nor Uint8Array in that we set start/end
  2283. // to their upper/lower bounds if the value passed is out of range.
  2284. // undefined is handled specially as per ECMA-262 6th Edition,
  2285. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2286. if (start === undefined || start < 0) {
  2287. start = 0
  2288. }
  2289. // Return early if start > this.length. Done here to prevent potential uint32
  2290. // coercion fail below.
  2291. if (start > this.length) {
  2292. return ''
  2293. }
  2294. if (end === undefined || end > this.length) {
  2295. end = this.length
  2296. }
  2297. if (end <= 0) {
  2298. return ''
  2299. }
  2300. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2301. end >>>= 0
  2302. start >>>= 0
  2303. if (end <= start) {
  2304. return ''
  2305. }
  2306. if (!encoding) encoding = 'utf8'
  2307. while (true) {
  2308. switch (encoding) {
  2309. case 'hex':
  2310. return hexSlice(this, start, end)
  2311. case 'utf8':
  2312. case 'utf-8':
  2313. return utf8Slice(this, start, end)
  2314. case 'ascii':
  2315. return asciiSlice(this, start, end)
  2316. case 'latin1':
  2317. case 'binary':
  2318. return latin1Slice(this, start, end)
  2319. case 'base64':
  2320. return base64Slice(this, start, end)
  2321. case 'ucs2':
  2322. case 'ucs-2':
  2323. case 'utf16le':
  2324. case 'utf-16le':
  2325. return utf16leSlice(this, start, end)
  2326. default:
  2327. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2328. encoding = (encoding + '').toLowerCase()
  2329. loweredCase = true
  2330. }
  2331. }
  2332. }
  2333. // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
  2334. // Buffer instances.
  2335. Buffer.prototype._isBuffer = true
  2336. function swap (b, n, m) {
  2337. var i = b[n]
  2338. b[n] = b[m]
  2339. b[m] = i
  2340. }
  2341. Buffer.prototype.swap16 = function swap16 () {
  2342. var len = this.length
  2343. if (len % 2 !== 0) {
  2344. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2345. }
  2346. for (var i = 0; i < len; i += 2) {
  2347. swap(this, i, i + 1)
  2348. }
  2349. return this
  2350. }
  2351. Buffer.prototype.swap32 = function swap32 () {
  2352. var len = this.length
  2353. if (len % 4 !== 0) {
  2354. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2355. }
  2356. for (var i = 0; i < len; i += 4) {
  2357. swap(this, i, i + 3)
  2358. swap(this, i + 1, i + 2)
  2359. }
  2360. return this
  2361. }
  2362. Buffer.prototype.swap64 = function swap64 () {
  2363. var len = this.length
  2364. if (len % 8 !== 0) {
  2365. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2366. }
  2367. for (var i = 0; i < len; i += 8) {
  2368. swap(this, i, i + 7)
  2369. swap(this, i + 1, i + 6)
  2370. swap(this, i + 2, i + 5)
  2371. swap(this, i + 3, i + 4)
  2372. }
  2373. return this
  2374. }
  2375. Buffer.prototype.toString = function toString () {
  2376. var length = this.length | 0
  2377. if (length === 0) return ''
  2378. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2379. return slowToString.apply(this, arguments)
  2380. }
  2381. Buffer.prototype.equals = function equals (b) {
  2382. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2383. if (this === b) return true
  2384. return Buffer.compare(this, b) === 0
  2385. }
  2386. Buffer.prototype.inspect = function inspect () {
  2387. var str = ''
  2388. var max = exports.INSPECT_MAX_BYTES
  2389. if (this.length > 0) {
  2390. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  2391. if (this.length > max) str += ' ... '
  2392. }
  2393. return '<Buffer ' + str + '>'
  2394. }
  2395. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2396. if (!Buffer.isBuffer(target)) {
  2397. throw new TypeError('Argument must be a Buffer')
  2398. }
  2399. if (start === undefined) {
  2400. start = 0
  2401. }
  2402. if (end === undefined) {
  2403. end = target ? target.length : 0
  2404. }
  2405. if (thisStart === undefined) {
  2406. thisStart = 0
  2407. }
  2408. if (thisEnd === undefined) {
  2409. thisEnd = this.length
  2410. }
  2411. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2412. throw new RangeError('out of range index')
  2413. }
  2414. if (thisStart >= thisEnd && start >= end) {
  2415. return 0
  2416. }
  2417. if (thisStart >= thisEnd) {
  2418. return -1
  2419. }
  2420. if (start >= end) {
  2421. return 1
  2422. }
  2423. start >>>= 0
  2424. end >>>= 0
  2425. thisStart >>>= 0
  2426. thisEnd >>>= 0
  2427. if (this === target) return 0
  2428. var x = thisEnd - thisStart
  2429. var y = end - start
  2430. var len = Math.min(x, y)
  2431. var thisCopy = this.slice(thisStart, thisEnd)
  2432. var targetCopy = target.slice(start, end)
  2433. for (var i = 0; i < len; ++i) {
  2434. if (thisCopy[i] !== targetCopy[i]) {
  2435. x = thisCopy[i]
  2436. y = targetCopy[i]
  2437. break
  2438. }
  2439. }
  2440. if (x < y) return -1
  2441. if (y < x) return 1
  2442. return 0
  2443. }
  2444. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  2445. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  2446. //
  2447. // Arguments:
  2448. // - buffer - a Buffer to search
  2449. // - val - a string, Buffer, or number
  2450. // - byteOffset - an index into `buffer`; will be clamped to an int32
  2451. // - encoding - an optional encoding, relevant is val is a string
  2452. // - dir - true for indexOf, false for lastIndexOf
  2453. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  2454. // Empty buffer means no match
  2455. if (buffer.length === 0) return -1
  2456. // Normalize byteOffset
  2457. if (typeof byteOffset === 'string') {
  2458. encoding = byteOffset
  2459. byteOffset = 0
  2460. } else if (byteOffset > 0x7fffffff) {
  2461. byteOffset = 0x7fffffff
  2462. } else if (byteOffset < -0x80000000) {
  2463. byteOffset = -0x80000000
  2464. }
  2465. byteOffset = +byteOffset // Coerce to Number.
  2466. if (isNaN(byteOffset)) {
  2467. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  2468. byteOffset = dir ? 0 : (buffer.length - 1)
  2469. }
  2470. // Normalize byteOffset: negative offsets start from the end of the buffer
  2471. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  2472. if (byteOffset >= buffer.length) {
  2473. if (dir) return -1
  2474. else byteOffset = buffer.length - 1
  2475. } else if (byteOffset < 0) {
  2476. if (dir) byteOffset = 0
  2477. else return -1
  2478. }
  2479. // Normalize val
  2480. if (typeof val === 'string') {
  2481. val = Buffer.from(val, encoding)
  2482. }
  2483. // Finally, search either indexOf (if dir is true) or lastIndexOf
  2484. if (Buffer.isBuffer(val)) {
  2485. // Special case: looking for empty string/buffer always fails
  2486. if (val.length === 0) {
  2487. return -1
  2488. }
  2489. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  2490. } else if (typeof val === 'number') {
  2491. val = val & 0xFF // Search for a byte value [0-255]
  2492. if (Buffer.TYPED_ARRAY_SUPPORT &&
  2493. typeof Uint8Array.prototype.indexOf === 'function') {
  2494. if (dir) {
  2495. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  2496. } else {
  2497. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  2498. }
  2499. }
  2500. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  2501. }
  2502. throw new TypeError('val must be string, number or Buffer')
  2503. }
  2504. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  2505. var indexSize = 1
  2506. var arrLength = arr.length
  2507. var valLength = val.length
  2508. if (encoding !== undefined) {
  2509. encoding = String(encoding).toLowerCase()
  2510. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  2511. encoding === 'utf16le' || encoding === 'utf-16le') {
  2512. if (arr.length < 2 || val.length < 2) {
  2513. return -1
  2514. }
  2515. indexSize = 2
  2516. arrLength /= 2
  2517. valLength /= 2
  2518. byteOffset /= 2
  2519. }
  2520. }
  2521. function read (buf, i) {
  2522. if (indexSize === 1) {
  2523. return buf[i]
  2524. } else {
  2525. return buf.readUInt16BE(i * indexSize)
  2526. }
  2527. }
  2528. var i
  2529. if (dir) {
  2530. var foundIndex = -1
  2531. for (i = byteOffset; i < arrLength; i++) {
  2532. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  2533. if (foundIndex === -1) foundIndex = i
  2534. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  2535. } else {
  2536. if (foundIndex !== -1) i -= i - foundIndex
  2537. foundIndex = -1
  2538. }
  2539. }
  2540. } else {
  2541. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  2542. for (i = byteOffset; i >= 0; i--) {
  2543. var found = true
  2544. for (var j = 0; j < valLength; j++) {
  2545. if (read(arr, i + j) !== read(val, j)) {
  2546. found = false
  2547. break
  2548. }
  2549. }
  2550. if (found) return i
  2551. }
  2552. }
  2553. return -1
  2554. }
  2555. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  2556. return this.indexOf(val, byteOffset, encoding) !== -1
  2557. }
  2558. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  2559. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  2560. }
  2561. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  2562. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  2563. }
  2564. function hexWrite (buf, string, offset, length) {
  2565. offset = Number(offset) || 0
  2566. var remaining = buf.length - offset
  2567. if (!length) {
  2568. length = remaining
  2569. } else {
  2570. length = Number(length)
  2571. if (length > remaining) {
  2572. length = remaining
  2573. }
  2574. }
  2575. // must be an even number of digits
  2576. var strLen = string.length
  2577. if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
  2578. if (length > strLen / 2) {
  2579. length = strLen / 2
  2580. }
  2581. for (var i = 0; i < length; ++i) {
  2582. var parsed = parseInt(string.substr(i * 2, 2), 16)
  2583. if (isNaN(parsed)) return i
  2584. buf[offset + i] = parsed
  2585. }
  2586. return i
  2587. }
  2588. function utf8Write (buf, string, offset, length) {
  2589. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  2590. }
  2591. function asciiWrite (buf, string, offset, length) {
  2592. return blitBuffer(asciiToBytes(string), buf, offset, length)
  2593. }
  2594. function latin1Write (buf, string, offset, length) {
  2595. return asciiWrite(buf, string, offset, length)
  2596. }
  2597. function base64Write (buf, string, offset, length) {
  2598. return blitBuffer(base64ToBytes(string), buf, offset, length)
  2599. }
  2600. function ucs2Write (buf, string, offset, length) {
  2601. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  2602. }
  2603. Buffer.prototype.write = function write (string, offset, length, encoding) {
  2604. // Buffer#write(string)
  2605. if (offset === undefined) {
  2606. encoding = 'utf8'
  2607. length = this.length
  2608. offset = 0
  2609. // Buffer#write(string, encoding)
  2610. } else if (length === undefined && typeof offset === 'string') {
  2611. encoding = offset
  2612. length = this.length
  2613. offset = 0
  2614. // Buffer#write(string, offset[, length][, encoding])
  2615. } else if (isFinite(offset)) {
  2616. offset = offset | 0
  2617. if (isFinite(length)) {
  2618. length = length | 0
  2619. if (encoding === undefined) encoding = 'utf8'
  2620. } else {
  2621. encoding = length
  2622. length = undefined
  2623. }
  2624. // legacy write(string, encoding, offset, length) - remove in v0.13
  2625. } else {
  2626. throw new Error(
  2627. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  2628. )
  2629. }
  2630. var remaining = this.length - offset
  2631. if (length === undefined || length > remaining) length = remaining
  2632. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  2633. throw new RangeError('Attempt to write outside buffer bounds')
  2634. }
  2635. if (!encoding) encoding = 'utf8'
  2636. var loweredCase = false
  2637. for (;;) {
  2638. switch (encoding) {
  2639. case 'hex':
  2640. return hexWrite(this, string, offset, length)
  2641. case 'utf8':
  2642. case 'utf-8':
  2643. return utf8Write(this, string, offset, length)
  2644. case 'ascii':
  2645. return asciiWrite(this, string, offset, length)
  2646. case 'latin1':
  2647. case 'binary':
  2648. return latin1Write(this, string, offset, length)
  2649. case 'base64':
  2650. // Warning: maxLength not taken into account in base64Write
  2651. return base64Write(this, string, offset, length)
  2652. case 'ucs2':
  2653. case 'ucs-2':
  2654. case 'utf16le':
  2655. case 'utf-16le':
  2656. return ucs2Write(this, string, offset, length)
  2657. default:
  2658. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2659. encoding = ('' + encoding).toLowerCase()
  2660. loweredCase = true
  2661. }
  2662. }
  2663. }
  2664. Buffer.prototype.toJSON = function toJSON () {
  2665. return {
  2666. type: 'Buffer',
  2667. data: Array.prototype.slice.call(this._arr || this, 0)
  2668. }
  2669. }
  2670. function base64Slice (buf, start, end) {
  2671. if (start === 0 && end === buf.length) {
  2672. return base64.fromByteArray(buf)
  2673. } else {
  2674. return base64.fromByteArray(buf.slice(start, end))
  2675. }
  2676. }
  2677. function utf8Slice (buf, start, end) {
  2678. end = Math.min(buf.length, end)
  2679. var res = []
  2680. var i = start
  2681. while (i < end) {
  2682. var firstByte = buf[i]
  2683. var codePoint = null
  2684. var bytesPerSequence = (firstByte > 0xEF) ? 4
  2685. : (firstByte > 0xDF) ? 3
  2686. : (firstByte > 0xBF) ? 2
  2687. : 1
  2688. if (i + bytesPerSequence <= end) {
  2689. var secondByte, thirdByte, fourthByte, tempCodePoint
  2690. switch (bytesPerSequence) {
  2691. case 1:
  2692. if (firstByte < 0x80) {
  2693. codePoint = firstByte
  2694. }
  2695. break
  2696. case 2:
  2697. secondByte = buf[i + 1]
  2698. if ((secondByte & 0xC0) === 0x80) {
  2699. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  2700. if (tempCodePoint > 0x7F) {
  2701. codePoint = tempCodePoint
  2702. }
  2703. }
  2704. break
  2705. case 3:
  2706. secondByte = buf[i + 1]
  2707. thirdByte = buf[i + 2]
  2708. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  2709. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  2710. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  2711. codePoint = tempCodePoint
  2712. }
  2713. }
  2714. break
  2715. case 4:
  2716. secondByte = buf[i + 1]
  2717. thirdByte = buf[i + 2]
  2718. fourthByte = buf[i + 3]
  2719. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  2720. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  2721. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  2722. codePoint = tempCodePoint
  2723. }
  2724. }
  2725. }
  2726. }
  2727. if (codePoint === null) {
  2728. // we did not generate a valid codePoint so insert a
  2729. // replacement char (U+FFFD) and advance only 1 byte
  2730. codePoint = 0xFFFD
  2731. bytesPerSequence = 1
  2732. } else if (codePoint > 0xFFFF) {
  2733. // encode to utf16 (surrogate pair dance)
  2734. codePoint -= 0x10000
  2735. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  2736. codePoint = 0xDC00 | codePoint & 0x3FF
  2737. }
  2738. res.push(codePoint)
  2739. i += bytesPerSequence
  2740. }
  2741. return decodeCodePointsArray(res)
  2742. }
  2743. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  2744. // the lowest limit is Chrome, with 0x10000 args.
  2745. // We go 1 magnitude less, for safety
  2746. var MAX_ARGUMENTS_LENGTH = 0x1000
  2747. function decodeCodePointsArray (codePoints) {
  2748. var len = codePoints.length
  2749. if (len <= MAX_ARGUMENTS_LENGTH) {
  2750. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  2751. }
  2752. // Decode in chunks to avoid "call stack size exceeded".
  2753. var res = ''
  2754. var i = 0
  2755. while (i < len) {
  2756. res += String.fromCharCode.apply(
  2757. String,
  2758. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  2759. )
  2760. }
  2761. return res
  2762. }
  2763. function asciiSlice (buf, start, end) {
  2764. var ret = ''
  2765. end = Math.min(buf.length, end)
  2766. for (var i = start; i < end; ++i) {
  2767. ret += String.fromCharCode(buf[i] & 0x7F)
  2768. }
  2769. return ret
  2770. }
  2771. function latin1Slice (buf, start, end) {
  2772. var ret = ''
  2773. end = Math.min(buf.length, end)
  2774. for (var i = start; i < end; ++i) {
  2775. ret += String.fromCharCode(buf[i])
  2776. }
  2777. return ret
  2778. }
  2779. function hexSlice (buf, start, end) {
  2780. var len = buf.length
  2781. if (!start || start < 0) start = 0
  2782. if (!end || end < 0 || end > len) end = len
  2783. var out = ''
  2784. for (var i = start; i < end; ++i) {
  2785. out += toHex(buf[i])
  2786. }
  2787. return out
  2788. }
  2789. function utf16leSlice (buf, start, end) {
  2790. var bytes = buf.slice(start, end)
  2791. var res = ''
  2792. for (var i = 0; i < bytes.length; i += 2) {
  2793. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  2794. }
  2795. return res
  2796. }
  2797. Buffer.prototype.slice = function slice (start, end) {
  2798. var len = this.length
  2799. start = ~~start
  2800. end = end === undefined ? len : ~~end
  2801. if (start < 0) {
  2802. start += len
  2803. if (start < 0) start = 0
  2804. } else if (start > len) {
  2805. start = len
  2806. }
  2807. if (end < 0) {
  2808. end += len
  2809. if (end < 0) end = 0
  2810. } else if (end > len) {
  2811. end = len
  2812. }
  2813. if (end < start) end = start
  2814. var newBuf
  2815. if (Buffer.TYPED_ARRAY_SUPPORT) {
  2816. newBuf = this.subarray(start, end)
  2817. newBuf.__proto__ = Buffer.prototype
  2818. } else {
  2819. var sliceLen = end - start
  2820. newBuf = new Buffer(sliceLen, undefined)
  2821. for (var i = 0; i < sliceLen; ++i) {
  2822. newBuf[i] = this[i + start]
  2823. }
  2824. }
  2825. return newBuf
  2826. }
  2827. /*
  2828. * Need to make sure that buffer isn't trying to write out of bounds.
  2829. */
  2830. function checkOffset (offset, ext, length) {
  2831. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  2832. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  2833. }
  2834. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  2835. offset = offset | 0
  2836. byteLength = byteLength | 0
  2837. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2838. var val = this[offset]
  2839. var mul = 1
  2840. var i = 0
  2841. while (++i < byteLength && (mul *= 0x100)) {
  2842. val += this[offset + i] * mul
  2843. }
  2844. return val
  2845. }
  2846. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  2847. offset = offset | 0
  2848. byteLength = byteLength | 0
  2849. if (!noAssert) {
  2850. checkOffset(offset, byteLength, this.length)
  2851. }
  2852. var val = this[offset + --byteLength]
  2853. var mul = 1
  2854. while (byteLength > 0 && (mul *= 0x100)) {
  2855. val += this[offset + --byteLength] * mul
  2856. }
  2857. return val
  2858. }
  2859. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  2860. if (!noAssert) checkOffset(offset, 1, this.length)
  2861. return this[offset]
  2862. }
  2863. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  2864. if (!noAssert) checkOffset(offset, 2, this.length)
  2865. return this[offset] | (this[offset + 1] << 8)
  2866. }
  2867. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  2868. if (!noAssert) checkOffset(offset, 2, this.length)
  2869. return (this[offset] << 8) | this[offset + 1]
  2870. }
  2871. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  2872. if (!noAssert) checkOffset(offset, 4, this.length)
  2873. return ((this[offset]) |
  2874. (this[offset + 1] << 8) |
  2875. (this[offset + 2] << 16)) +
  2876. (this[offset + 3] * 0x1000000)
  2877. }
  2878. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  2879. if (!noAssert) checkOffset(offset, 4, this.length)
  2880. return (this[offset] * 0x1000000) +
  2881. ((this[offset + 1] << 16) |
  2882. (this[offset + 2] << 8) |
  2883. this[offset + 3])
  2884. }
  2885. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  2886. offset = offset | 0
  2887. byteLength = byteLength | 0
  2888. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2889. var val = this[offset]
  2890. var mul = 1
  2891. var i = 0
  2892. while (++i < byteLength && (mul *= 0x100)) {
  2893. val += this[offset + i] * mul
  2894. }
  2895. mul *= 0x80
  2896. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  2897. return val
  2898. }
  2899. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  2900. offset = offset | 0
  2901. byteLength = byteLength | 0
  2902. if (!noAssert) checkOffset(offset, byteLength, this.length)
  2903. var i = byteLength
  2904. var mul = 1
  2905. var val = this[offset + --i]
  2906. while (i > 0 && (mul *= 0x100)) {
  2907. val += this[offset + --i] * mul
  2908. }
  2909. mul *= 0x80
  2910. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  2911. return val
  2912. }
  2913. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  2914. if (!noAssert) checkOffset(offset, 1, this.length)
  2915. if (!(this[offset] & 0x80)) return (this[offset])
  2916. return ((0xff - this[offset] + 1) * -1)
  2917. }
  2918. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  2919. if (!noAssert) checkOffset(offset, 2, this.length)
  2920. var val = this[offset] | (this[offset + 1] << 8)
  2921. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2922. }
  2923. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  2924. if (!noAssert) checkOffset(offset, 2, this.length)
  2925. var val = this[offset + 1] | (this[offset] << 8)
  2926. return (val & 0x8000) ? val | 0xFFFF0000 : val
  2927. }
  2928. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  2929. if (!noAssert) checkOffset(offset, 4, this.length)
  2930. return (this[offset]) |
  2931. (this[offset + 1] << 8) |
  2932. (this[offset + 2] << 16) |
  2933. (this[offset + 3] << 24)
  2934. }
  2935. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  2936. if (!noAssert) checkOffset(offset, 4, this.length)
  2937. return (this[offset] << 24) |
  2938. (this[offset + 1] << 16) |
  2939. (this[offset + 2] << 8) |
  2940. (this[offset + 3])
  2941. }
  2942. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  2943. if (!noAssert) checkOffset(offset, 4, this.length)
  2944. return ieee754.read(this, offset, true, 23, 4)
  2945. }
  2946. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  2947. if (!noAssert) checkOffset(offset, 4, this.length)
  2948. return ieee754.read(this, offset, false, 23, 4)
  2949. }
  2950. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  2951. if (!noAssert) checkOffset(offset, 8, this.length)
  2952. return ieee754.read(this, offset, true, 52, 8)
  2953. }
  2954. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  2955. if (!noAssert) checkOffset(offset, 8, this.length)
  2956. return ieee754.read(this, offset, false, 52, 8)
  2957. }
  2958. function checkInt (buf, value, offset, ext, max, min) {
  2959. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  2960. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  2961. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  2962. }
  2963. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  2964. value = +value
  2965. offset = offset | 0
  2966. byteLength = byteLength | 0
  2967. if (!noAssert) {
  2968. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  2969. checkInt(this, value, offset, byteLength, maxBytes, 0)
  2970. }
  2971. var mul = 1
  2972. var i = 0
  2973. this[offset] = value & 0xFF
  2974. while (++i < byteLength && (mul *= 0x100)) {
  2975. this[offset + i] = (value / mul) & 0xFF
  2976. }
  2977. return offset + byteLength
  2978. }
  2979. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  2980. value = +value
  2981. offset = offset | 0
  2982. byteLength = byteLength | 0
  2983. if (!noAssert) {
  2984. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  2985. checkInt(this, value, offset, byteLength, maxBytes, 0)
  2986. }
  2987. var i = byteLength - 1
  2988. var mul = 1
  2989. this[offset + i] = value & 0xFF
  2990. while (--i >= 0 && (mul *= 0x100)) {
  2991. this[offset + i] = (value / mul) & 0xFF
  2992. }
  2993. return offset + byteLength
  2994. }
  2995. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  2996. value = +value
  2997. offset = offset | 0
  2998. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  2999. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  3000. this[offset] = (value & 0xff)
  3001. return offset + 1
  3002. }
  3003. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  3004. if (value < 0) value = 0xffff + value + 1
  3005. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
  3006. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  3007. (littleEndian ? i : 1 - i) * 8
  3008. }
  3009. }
  3010. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3011. value = +value
  3012. offset = offset | 0
  3013. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3014. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3015. this[offset] = (value & 0xff)
  3016. this[offset + 1] = (value >>> 8)
  3017. } else {
  3018. objectWriteUInt16(this, value, offset, true)
  3019. }
  3020. return offset + 2
  3021. }
  3022. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3023. value = +value
  3024. offset = offset | 0
  3025. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3026. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3027. this[offset] = (value >>> 8)
  3028. this[offset + 1] = (value & 0xff)
  3029. } else {
  3030. objectWriteUInt16(this, value, offset, false)
  3031. }
  3032. return offset + 2
  3033. }
  3034. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  3035. if (value < 0) value = 0xffffffff + value + 1
  3036. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
  3037. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  3038. }
  3039. }
  3040. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3041. value = +value
  3042. offset = offset | 0
  3043. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3044. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3045. this[offset + 3] = (value >>> 24)
  3046. this[offset + 2] = (value >>> 16)
  3047. this[offset + 1] = (value >>> 8)
  3048. this[offset] = (value & 0xff)
  3049. } else {
  3050. objectWriteUInt32(this, value, offset, true)
  3051. }
  3052. return offset + 4
  3053. }
  3054. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3055. value = +value
  3056. offset = offset | 0
  3057. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3058. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3059. this[offset] = (value >>> 24)
  3060. this[offset + 1] = (value >>> 16)
  3061. this[offset + 2] = (value >>> 8)
  3062. this[offset + 3] = (value & 0xff)
  3063. } else {
  3064. objectWriteUInt32(this, value, offset, false)
  3065. }
  3066. return offset + 4
  3067. }
  3068. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3069. value = +value
  3070. offset = offset | 0
  3071. if (!noAssert) {
  3072. var limit = Math.pow(2, 8 * byteLength - 1)
  3073. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3074. }
  3075. var i = 0
  3076. var mul = 1
  3077. var sub = 0
  3078. this[offset] = value & 0xFF
  3079. while (++i < byteLength && (mul *= 0x100)) {
  3080. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3081. sub = 1
  3082. }
  3083. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3084. }
  3085. return offset + byteLength
  3086. }
  3087. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3088. value = +value
  3089. offset = offset | 0
  3090. if (!noAssert) {
  3091. var limit = Math.pow(2, 8 * byteLength - 1)
  3092. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3093. }
  3094. var i = byteLength - 1
  3095. var mul = 1
  3096. var sub = 0
  3097. this[offset + i] = value & 0xFF
  3098. while (--i >= 0 && (mul *= 0x100)) {
  3099. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3100. sub = 1
  3101. }
  3102. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3103. }
  3104. return offset + byteLength
  3105. }
  3106. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3107. value = +value
  3108. offset = offset | 0
  3109. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3110. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  3111. if (value < 0) value = 0xff + value + 1
  3112. this[offset] = (value & 0xff)
  3113. return offset + 1
  3114. }
  3115. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3116. value = +value
  3117. offset = offset | 0
  3118. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3119. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3120. this[offset] = (value & 0xff)
  3121. this[offset + 1] = (value >>> 8)
  3122. } else {
  3123. objectWriteUInt16(this, value, offset, true)
  3124. }
  3125. return offset + 2
  3126. }
  3127. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3128. value = +value
  3129. offset = offset | 0
  3130. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3131. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3132. this[offset] = (value >>> 8)
  3133. this[offset + 1] = (value & 0xff)
  3134. } else {
  3135. objectWriteUInt16(this, value, offset, false)
  3136. }
  3137. return offset + 2
  3138. }
  3139. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3140. value = +value
  3141. offset = offset | 0
  3142. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3143. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3144. this[offset] = (value & 0xff)
  3145. this[offset + 1] = (value >>> 8)
  3146. this[offset + 2] = (value >>> 16)
  3147. this[offset + 3] = (value >>> 24)
  3148. } else {
  3149. objectWriteUInt32(this, value, offset, true)
  3150. }
  3151. return offset + 4
  3152. }
  3153. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3154. value = +value
  3155. offset = offset | 0
  3156. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3157. if (value < 0) value = 0xffffffff + value + 1
  3158. if (Buffer.TYPED_ARRAY_SUPPORT) {
  3159. this[offset] = (value >>> 24)
  3160. this[offset + 1] = (value >>> 16)
  3161. this[offset + 2] = (value >>> 8)
  3162. this[offset + 3] = (value & 0xff)
  3163. } else {
  3164. objectWriteUInt32(this, value, offset, false)
  3165. }
  3166. return offset + 4
  3167. }
  3168. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3169. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3170. if (offset < 0) throw new RangeError('Index out of range')
  3171. }
  3172. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3173. if (!noAssert) {
  3174. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3175. }
  3176. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3177. return offset + 4
  3178. }
  3179. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3180. return writeFloat(this, value, offset, true, noAssert)
  3181. }
  3182. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3183. return writeFloat(this, value, offset, false, noAssert)
  3184. }
  3185. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3186. if (!noAssert) {
  3187. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3188. }
  3189. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3190. return offset + 8
  3191. }
  3192. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3193. return writeDouble(this, value, offset, true, noAssert)
  3194. }
  3195. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3196. return writeDouble(this, value, offset, false, noAssert)
  3197. }
  3198. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3199. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3200. if (!start) start = 0
  3201. if (!end && end !== 0) end = this.length
  3202. if (targetStart >= target.length) targetStart = target.length
  3203. if (!targetStart) targetStart = 0
  3204. if (end > 0 && end < start) end = start
  3205. // Copy 0 bytes; we're done
  3206. if (end === start) return 0
  3207. if (target.length === 0 || this.length === 0) return 0
  3208. // Fatal error conditions
  3209. if (targetStart < 0) {
  3210. throw new RangeError('targetStart out of bounds')
  3211. }
  3212. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  3213. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3214. // Are we oob?
  3215. if (end > this.length) end = this.length
  3216. if (target.length - targetStart < end - start) {
  3217. end = target.length - targetStart + start
  3218. }
  3219. var len = end - start
  3220. var i
  3221. if (this === target && start < targetStart && targetStart < end) {
  3222. // descending copy from end
  3223. for (i = len - 1; i >= 0; --i) {
  3224. target[i + targetStart] = this[i + start]
  3225. }
  3226. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  3227. // ascending copy from start
  3228. for (i = 0; i < len; ++i) {
  3229. target[i + targetStart] = this[i + start]
  3230. }
  3231. } else {
  3232. Uint8Array.prototype.set.call(
  3233. target,
  3234. this.subarray(start, start + len),
  3235. targetStart
  3236. )
  3237. }
  3238. return len
  3239. }
  3240. // Usage:
  3241. // buffer.fill(number[, offset[, end]])
  3242. // buffer.fill(buffer[, offset[, end]])
  3243. // buffer.fill(string[, offset[, end]][, encoding])
  3244. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3245. // Handle string cases:
  3246. if (typeof val === 'string') {
  3247. if (typeof start === 'string') {
  3248. encoding = start
  3249. start = 0
  3250. end = this.length
  3251. } else if (typeof end === 'string') {
  3252. encoding = end
  3253. end = this.length
  3254. }
  3255. if (val.length === 1) {
  3256. var code = val.charCodeAt(0)
  3257. if (code < 256) {
  3258. val = code
  3259. }
  3260. }
  3261. if (encoding !== undefined && typeof encoding !== 'string') {
  3262. throw new TypeError('encoding must be a string')
  3263. }
  3264. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3265. throw new TypeError('Unknown encoding: ' + encoding)
  3266. }
  3267. } else if (typeof val === 'number') {
  3268. val = val & 255
  3269. }
  3270. // Invalid ranges are not set to a default, so can range check early.
  3271. if (start < 0 || this.length < start || this.length < end) {
  3272. throw new RangeError('Out of range index')
  3273. }
  3274. if (end <= start) {
  3275. return this
  3276. }
  3277. start = start >>> 0
  3278. end = end === undefined ? this.length : end >>> 0
  3279. if (!val) val = 0
  3280. var i
  3281. if (typeof val === 'number') {
  3282. for (i = start; i < end; ++i) {
  3283. this[i] = val
  3284. }
  3285. } else {
  3286. var bytes = Buffer.isBuffer(val)
  3287. ? val
  3288. : utf8ToBytes(new Buffer(val, encoding).toString())
  3289. var len = bytes.length
  3290. for (i = 0; i < end - start; ++i) {
  3291. this[i + start] = bytes[i % len]
  3292. }
  3293. }
  3294. return this
  3295. }
  3296. // HELPER FUNCTIONS
  3297. // ================
  3298. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  3299. function base64clean (str) {
  3300. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3301. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  3302. // Node converts strings with length < 2 to ''
  3303. if (str.length < 2) return ''
  3304. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3305. while (str.length % 4 !== 0) {
  3306. str = str + '='
  3307. }
  3308. return str
  3309. }
  3310. function stringtrim (str) {
  3311. if (str.trim) return str.trim()
  3312. return str.replace(/^\s+|\s+$/g, '')
  3313. }
  3314. function toHex (n) {
  3315. if (n < 16) return '0' + n.toString(16)
  3316. return n.toString(16)
  3317. }
  3318. function utf8ToBytes (string, units) {
  3319. units = units || Infinity
  3320. var codePoint
  3321. var length = string.length
  3322. var leadSurrogate = null
  3323. var bytes = []
  3324. for (var i = 0; i < length; ++i) {
  3325. codePoint = string.charCodeAt(i)
  3326. // is surrogate component
  3327. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3328. // last char was a lead
  3329. if (!leadSurrogate) {
  3330. // no lead yet
  3331. if (codePoint > 0xDBFF) {
  3332. // unexpected trail
  3333. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3334. continue
  3335. } else if (i + 1 === length) {
  3336. // unpaired lead
  3337. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3338. continue
  3339. }
  3340. // valid lead
  3341. leadSurrogate = codePoint
  3342. continue
  3343. }
  3344. // 2 leads in a row
  3345. if (codePoint < 0xDC00) {
  3346. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3347. leadSurrogate = codePoint
  3348. continue
  3349. }
  3350. // valid surrogate pair
  3351. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3352. } else if (leadSurrogate) {
  3353. // valid bmp char, but last char was a lead
  3354. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3355. }
  3356. leadSurrogate = null
  3357. // encode utf8
  3358. if (codePoint < 0x80) {
  3359. if ((units -= 1) < 0) break
  3360. bytes.push(codePoint)
  3361. } else if (codePoint < 0x800) {
  3362. if ((units -= 2) < 0) break
  3363. bytes.push(
  3364. codePoint >> 0x6 | 0xC0,
  3365. codePoint & 0x3F | 0x80
  3366. )
  3367. } else if (codePoint < 0x10000) {
  3368. if ((units -= 3) < 0) break
  3369. bytes.push(
  3370. codePoint >> 0xC | 0xE0,
  3371. codePoint >> 0x6 & 0x3F | 0x80,
  3372. codePoint & 0x3F | 0x80
  3373. )
  3374. } else if (codePoint < 0x110000) {
  3375. if ((units -= 4) < 0) break
  3376. bytes.push(
  3377. codePoint >> 0x12 | 0xF0,
  3378. codePoint >> 0xC & 0x3F | 0x80,
  3379. codePoint >> 0x6 & 0x3F | 0x80,
  3380. codePoint & 0x3F | 0x80
  3381. )
  3382. } else {
  3383. throw new Error('Invalid code point')
  3384. }
  3385. }
  3386. return bytes
  3387. }
  3388. function asciiToBytes (str) {
  3389. var byteArray = []
  3390. for (var i = 0; i < str.length; ++i) {
  3391. // Node's code seems to be doing this and not & 0x7F..
  3392. byteArray.push(str.charCodeAt(i) & 0xFF)
  3393. }
  3394. return byteArray
  3395. }
  3396. function utf16leToBytes (str, units) {
  3397. var c, hi, lo
  3398. var byteArray = []
  3399. for (var i = 0; i < str.length; ++i) {
  3400. if ((units -= 2) < 0) break
  3401. c = str.charCodeAt(i)
  3402. hi = c >> 8
  3403. lo = c % 256
  3404. byteArray.push(lo)
  3405. byteArray.push(hi)
  3406. }
  3407. return byteArray
  3408. }
  3409. function base64ToBytes (str) {
  3410. return base64.toByteArray(base64clean(str))
  3411. }
  3412. function blitBuffer (src, dst, offset, length) {
  3413. for (var i = 0; i < length; ++i) {
  3414. if ((i + offset >= dst.length) || (i >= src.length)) break
  3415. dst[i + offset] = src[i]
  3416. }
  3417. return i
  3418. }
  3419. function isnan (val) {
  3420. return val !== val // eslint-disable-line no-self-compare
  3421. }
  3422. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1)))
  3423. /***/ }),
  3424. /* 7 */
  3425. /***/ (function(module, exports, __webpack_require__) {
  3426. "use strict";
  3427. exports.byteLength = byteLength
  3428. exports.toByteArray = toByteArray
  3429. exports.fromByteArray = fromByteArray
  3430. var lookup = []
  3431. var revLookup = []
  3432. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  3433. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  3434. for (var i = 0, len = code.length; i < len; ++i) {
  3435. lookup[i] = code[i]
  3436. revLookup[code.charCodeAt(i)] = i
  3437. }
  3438. // Support decoding URL-safe base64 strings, as Node.js does.
  3439. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  3440. revLookup['-'.charCodeAt(0)] = 62
  3441. revLookup['_'.charCodeAt(0)] = 63
  3442. function getLens (b64) {
  3443. var len = b64.length
  3444. if (len % 4 > 0) {
  3445. throw new Error('Invalid string. Length must be a multiple of 4')
  3446. }
  3447. // Trim off extra bytes after placeholder bytes are found
  3448. // See: https://github.com/beatgammit/base64-js/issues/42
  3449. var validLen = b64.indexOf('=')
  3450. if (validLen === -1) validLen = len
  3451. var placeHoldersLen = validLen === len
  3452. ? 0
  3453. : 4 - (validLen % 4)
  3454. return [validLen, placeHoldersLen]
  3455. }
  3456. // base64 is 4/3 + up to two characters of the original data
  3457. function byteLength (b64) {
  3458. var lens = getLens(b64)
  3459. var validLen = lens[0]
  3460. var placeHoldersLen = lens[1]
  3461. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  3462. }
  3463. function _byteLength (b64, validLen, placeHoldersLen) {
  3464. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  3465. }
  3466. function toByteArray (b64) {
  3467. var tmp
  3468. var lens = getLens(b64)
  3469. var validLen = lens[0]
  3470. var placeHoldersLen = lens[1]
  3471. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  3472. var curByte = 0
  3473. // if there are placeholders, only get up to the last complete 4 chars
  3474. var len = placeHoldersLen > 0
  3475. ? validLen - 4
  3476. : validLen
  3477. var i
  3478. for (i = 0; i < len; i += 4) {
  3479. tmp =
  3480. (revLookup[b64.charCodeAt(i)] << 18) |
  3481. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  3482. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  3483. revLookup[b64.charCodeAt(i + 3)]
  3484. arr[curByte++] = (tmp >> 16) & 0xFF
  3485. arr[curByte++] = (tmp >> 8) & 0xFF
  3486. arr[curByte++] = tmp & 0xFF
  3487. }
  3488. if (placeHoldersLen === 2) {
  3489. tmp =
  3490. (revLookup[b64.charCodeAt(i)] << 2) |
  3491. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  3492. arr[curByte++] = tmp & 0xFF
  3493. }
  3494. if (placeHoldersLen === 1) {
  3495. tmp =
  3496. (revLookup[b64.charCodeAt(i)] << 10) |
  3497. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  3498. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  3499. arr[curByte++] = (tmp >> 8) & 0xFF
  3500. arr[curByte++] = tmp & 0xFF
  3501. }
  3502. return arr
  3503. }
  3504. function tripletToBase64 (num) {
  3505. return lookup[num >> 18 & 0x3F] +
  3506. lookup[num >> 12 & 0x3F] +
  3507. lookup[num >> 6 & 0x3F] +
  3508. lookup[num & 0x3F]
  3509. }
  3510. function encodeChunk (uint8, start, end) {
  3511. var tmp
  3512. var output = []
  3513. for (var i = start; i < end; i += 3) {
  3514. tmp =
  3515. ((uint8[i] << 16) & 0xFF0000) +
  3516. ((uint8[i + 1] << 8) & 0xFF00) +
  3517. (uint8[i + 2] & 0xFF)
  3518. output.push(tripletToBase64(tmp))
  3519. }
  3520. return output.join('')
  3521. }
  3522. function fromByteArray (uint8) {
  3523. var tmp
  3524. var len = uint8.length
  3525. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  3526. var parts = []
  3527. var maxChunkLength = 16383 // must be multiple of 3
  3528. // go through the array every three bytes, we'll deal with trailing stuff later
  3529. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  3530. parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
  3531. }
  3532. // pad the end with zeros, but make sure to not forget the extra bytes
  3533. if (extraBytes === 1) {
  3534. tmp = uint8[len - 1]
  3535. parts.push(
  3536. lookup[tmp >> 2] +
  3537. lookup[(tmp << 4) & 0x3F] +
  3538. '=='
  3539. )
  3540. } else if (extraBytes === 2) {
  3541. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  3542. parts.push(
  3543. lookup[tmp >> 10] +
  3544. lookup[(tmp >> 4) & 0x3F] +
  3545. lookup[(tmp << 2) & 0x3F] +
  3546. '='
  3547. )
  3548. }
  3549. return parts.join('')
  3550. }
  3551. /***/ }),
  3552. /* 8 */
  3553. /***/ (function(module, exports) {
  3554. /*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
  3555. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  3556. var e, m
  3557. var eLen = (nBytes * 8) - mLen - 1
  3558. var eMax = (1 << eLen) - 1
  3559. var eBias = eMax >> 1
  3560. var nBits = -7
  3561. var i = isLE ? (nBytes - 1) : 0
  3562. var d = isLE ? -1 : 1
  3563. var s = buffer[offset + i]
  3564. i += d
  3565. e = s & ((1 << (-nBits)) - 1)
  3566. s >>= (-nBits)
  3567. nBits += eLen
  3568. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  3569. m = e & ((1 << (-nBits)) - 1)
  3570. e >>= (-nBits)
  3571. nBits += mLen
  3572. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  3573. if (e === 0) {
  3574. e = 1 - eBias
  3575. } else if (e === eMax) {
  3576. return m ? NaN : ((s ? -1 : 1) * Infinity)
  3577. } else {
  3578. m = m + Math.pow(2, mLen)
  3579. e = e - eBias
  3580. }
  3581. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  3582. }
  3583. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  3584. var e, m, c
  3585. var eLen = (nBytes * 8) - mLen - 1
  3586. var eMax = (1 << eLen) - 1
  3587. var eBias = eMax >> 1
  3588. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  3589. var i = isLE ? 0 : (nBytes - 1)
  3590. var d = isLE ? 1 : -1
  3591. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  3592. value = Math.abs(value)
  3593. if (isNaN(value) || value === Infinity) {
  3594. m = isNaN(value) ? 1 : 0
  3595. e = eMax
  3596. } else {
  3597. e = Math.floor(Math.log(value) / Math.LN2)
  3598. if (value * (c = Math.pow(2, -e)) < 1) {
  3599. e--
  3600. c *= 2
  3601. }
  3602. if (e + eBias >= 1) {
  3603. value += rt / c
  3604. } else {
  3605. value += rt * Math.pow(2, 1 - eBias)
  3606. }
  3607. if (value * c >= 2) {
  3608. e++
  3609. c /= 2
  3610. }
  3611. if (e + eBias >= eMax) {
  3612. m = 0
  3613. e = eMax
  3614. } else if (e + eBias >= 1) {
  3615. m = ((value * c) - 1) * Math.pow(2, mLen)
  3616. e = e + eBias
  3617. } else {
  3618. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  3619. e = 0
  3620. }
  3621. }
  3622. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  3623. e = (e << mLen) | m
  3624. eLen += mLen
  3625. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  3626. buffer[offset + i - d] |= s * 128
  3627. }
  3628. /***/ }),
  3629. /* 9 */
  3630. /***/ (function(module, exports) {
  3631. var toString = {}.toString;
  3632. module.exports = Array.isArray || function (arr) {
  3633. return toString.call(arr) == '[object Array]';
  3634. };
  3635. /***/ }),
  3636. /* 10 */
  3637. /***/ (function(module, exports, __webpack_require__) {
  3638. /* WEBPACK VAR INJECTION */(function(global) {var scope = (typeof global !== "undefined" && global) ||
  3639. (typeof self !== "undefined" && self) ||
  3640. window;
  3641. var apply = Function.prototype.apply;
  3642. // DOM APIs, for completeness
  3643. exports.setTimeout = function() {
  3644. return new Timeout(apply.call(setTimeout, scope, arguments), clearTimeout);
  3645. };
  3646. exports.setInterval = function() {
  3647. return new Timeout(apply.call(setInterval, scope, arguments), clearInterval);
  3648. };
  3649. exports.clearTimeout =
  3650. exports.clearInterval = function(timeout) {
  3651. if (timeout) {
  3652. timeout.close();
  3653. }
  3654. };
  3655. function Timeout(id, clearFn) {
  3656. this._id = id;
  3657. this._clearFn = clearFn;
  3658. }
  3659. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  3660. Timeout.prototype.close = function() {
  3661. this._clearFn.call(scope, this._id);
  3662. };
  3663. // Does not start the time, just sets up the members needed.
  3664. exports.enroll = function(item, msecs) {
  3665. clearTimeout(item._idleTimeoutId);
  3666. item._idleTimeout = msecs;
  3667. };
  3668. exports.unenroll = function(item) {
  3669. clearTimeout(item._idleTimeoutId);
  3670. item._idleTimeout = -1;
  3671. };
  3672. exports._unrefActive = exports.active = function(item) {
  3673. clearTimeout(item._idleTimeoutId);
  3674. var msecs = item._idleTimeout;
  3675. if (msecs >= 0) {
  3676. item._idleTimeoutId = setTimeout(function onTimeout() {
  3677. if (item._onTimeout)
  3678. item._onTimeout();
  3679. }, msecs);
  3680. }
  3681. };
  3682. // setimmediate attaches itself to the global object
  3683. __webpack_require__(11);
  3684. // On some exotic environments, it's not clear which object `setimmediate` was
  3685. // able to install onto. Search each possibility in the same order as the
  3686. // `setimmediate` library.
  3687. exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
  3688. (typeof global !== "undefined" && global.setImmediate) ||
  3689. (this && this.setImmediate);
  3690. exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
  3691. (typeof global !== "undefined" && global.clearImmediate) ||
  3692. (this && this.clearImmediate);
  3693. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1)))
  3694. /***/ }),
  3695. /* 11 */
  3696. /***/ (function(module, exports, __webpack_require__) {
  3697. /* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) {
  3698. "use strict";
  3699. if (global.setImmediate) {
  3700. return;
  3701. }
  3702. var nextHandle = 1; // Spec says greater than zero
  3703. var tasksByHandle = {};
  3704. var currentlyRunningATask = false;
  3705. var doc = global.document;
  3706. var registerImmediate;
  3707. function setImmediate(callback) {
  3708. // Callback can either be a function or a string
  3709. if (typeof callback !== "function") {
  3710. callback = new Function("" + callback);
  3711. }
  3712. // Copy function arguments
  3713. var args = new Array(arguments.length - 1);
  3714. for (var i = 0; i < args.length; i++) {
  3715. args[i] = arguments[i + 1];
  3716. }
  3717. // Store and register the task
  3718. var task = { callback: callback, args: args };
  3719. tasksByHandle[nextHandle] = task;
  3720. registerImmediate(nextHandle);
  3721. return nextHandle++;
  3722. }
  3723. function clearImmediate(handle) {
  3724. delete tasksByHandle[handle];
  3725. }
  3726. function run(task) {
  3727. var callback = task.callback;
  3728. var args = task.args;
  3729. switch (args.length) {
  3730. case 0:
  3731. callback();
  3732. break;
  3733. case 1:
  3734. callback(args[0]);
  3735. break;
  3736. case 2:
  3737. callback(args[0], args[1]);
  3738. break;
  3739. case 3:
  3740. callback(args[0], args[1], args[2]);
  3741. break;
  3742. default:
  3743. callback.apply(undefined, args);
  3744. break;
  3745. }
  3746. }
  3747. function runIfPresent(handle) {
  3748. // From the spec: "Wait until any invocations of this algorithm started before this one have completed."
  3749. // So if we're currently running a task, we'll need to delay this invocation.
  3750. if (currentlyRunningATask) {
  3751. // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a
  3752. // "too much recursion" error.
  3753. setTimeout(runIfPresent, 0, handle);
  3754. } else {
  3755. var task = tasksByHandle[handle];
  3756. if (task) {
  3757. currentlyRunningATask = true;
  3758. try {
  3759. run(task);
  3760. } finally {
  3761. clearImmediate(handle);
  3762. currentlyRunningATask = false;
  3763. }
  3764. }
  3765. }
  3766. }
  3767. function installNextTickImplementation() {
  3768. registerImmediate = function(handle) {
  3769. process.nextTick(function () { runIfPresent(handle); });
  3770. };
  3771. }
  3772. function canUsePostMessage() {
  3773. // The test against `importScripts` prevents this implementation from being installed inside a web worker,
  3774. // where `global.postMessage` means something completely different and can't be used for this purpose.
  3775. if (global.postMessage && !global.importScripts) {
  3776. var postMessageIsAsynchronous = true;
  3777. var oldOnMessage = global.onmessage;
  3778. global.onmessage = function() {
  3779. postMessageIsAsynchronous = false;
  3780. };
  3781. global.postMessage("", "*");
  3782. global.onmessage = oldOnMessage;
  3783. return postMessageIsAsynchronous;
  3784. }
  3785. }
  3786. function installPostMessageImplementation() {
  3787. // Installs an event handler on `global` for the `message` event: see
  3788. // * https://developer.mozilla.org/en/DOM/window.postMessage
  3789. // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages
  3790. var messagePrefix = "setImmediate$" + Math.random() + "$";
  3791. var onGlobalMessage = function(event) {
  3792. if (event.source === global &&
  3793. typeof event.data === "string" &&
  3794. event.data.indexOf(messagePrefix) === 0) {
  3795. runIfPresent(+event.data.slice(messagePrefix.length));
  3796. }
  3797. };
  3798. if (global.addEventListener) {
  3799. global.addEventListener("message", onGlobalMessage, false);
  3800. } else {
  3801. global.attachEvent("onmessage", onGlobalMessage);
  3802. }
  3803. registerImmediate = function(handle) {
  3804. global.postMessage(messagePrefix + handle, "*");
  3805. };
  3806. }
  3807. function installMessageChannelImplementation() {
  3808. var channel = new MessageChannel();
  3809. channel.port1.onmessage = function(event) {
  3810. var handle = event.data;
  3811. runIfPresent(handle);
  3812. };
  3813. registerImmediate = function(handle) {
  3814. channel.port2.postMessage(handle);
  3815. };
  3816. }
  3817. function installReadyStateChangeImplementation() {
  3818. var html = doc.documentElement;
  3819. registerImmediate = function(handle) {
  3820. // Create a <script> element; its readystatechange event will be fired asynchronously once it is inserted
  3821. // into the document. Do so, thus queuing up the task. Remember to clean up once it's been called.
  3822. var script = doc.createElement("script");
  3823. script.onreadystatechange = function () {
  3824. runIfPresent(handle);
  3825. script.onreadystatechange = null;
  3826. html.removeChild(script);
  3827. script = null;
  3828. };
  3829. html.appendChild(script);
  3830. };
  3831. }
  3832. function installSetTimeoutImplementation() {
  3833. registerImmediate = function(handle) {
  3834. setTimeout(runIfPresent, 0, handle);
  3835. };
  3836. }
  3837. // If supported, we should attach to the prototype of global, since that is where setTimeout et al. live.
  3838. var attachTo = Object.getPrototypeOf && Object.getPrototypeOf(global);
  3839. attachTo = attachTo && attachTo.setTimeout ? attachTo : global;
  3840. // Don't get fooled by e.g. browserify environments.
  3841. if ({}.toString.call(global.process) === "[object process]") {
  3842. // For Node.js before 0.9
  3843. installNextTickImplementation();
  3844. } else if (canUsePostMessage()) {
  3845. // For non-IE10 modern browsers
  3846. installPostMessageImplementation();
  3847. } else if (global.MessageChannel) {
  3848. // For web workers, where supported
  3849. installMessageChannelImplementation();
  3850. } else if (doc && "onreadystatechange" in doc.createElement("script")) {
  3851. // For IE 6–8
  3852. installReadyStateChangeImplementation();
  3853. } else {
  3854. // For older browsers
  3855. installSetTimeoutImplementation();
  3856. }
  3857. attachTo.setImmediate = setImmediate;
  3858. attachTo.clearImmediate = clearImmediate;
  3859. }(typeof self === "undefined" ? typeof global === "undefined" ? this : global : self));
  3860. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(1), __webpack_require__(3)))
  3861. /***/ }),
  3862. /* 12 */
  3863. /***/ (function(module, exports) {
  3864. function webpackEmptyContext(req) {
  3865. var e = new Error("Cannot find module '" + req + "'");
  3866. e.code = 'MODULE_NOT_FOUND';
  3867. throw e;
  3868. }
  3869. webpackEmptyContext.keys = function() { return []; };
  3870. webpackEmptyContext.resolve = webpackEmptyContext;
  3871. module.exports = webpackEmptyContext;
  3872. webpackEmptyContext.id = 12;
  3873. /***/ }),
  3874. /* 13 */
  3875. /***/ (function(module, exports, __webpack_require__) {
  3876. function DOMParser(options){
  3877. this.options = options ||{locator:{}};
  3878. }
  3879. DOMParser.prototype.parseFromString = function(source,mimeType){
  3880. var options = this.options;
  3881. var sax = new XMLReader();
  3882. var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
  3883. var errorHandler = options.errorHandler;
  3884. var locator = options.locator;
  3885. var defaultNSMap = options.xmlns||{};
  3886. var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
  3887. var entityMap = isHTML?htmlEntity.entityMap:{'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"};
  3888. if(locator){
  3889. domBuilder.setDocumentLocator(locator)
  3890. }
  3891. sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
  3892. sax.domBuilder = options.domBuilder || domBuilder;
  3893. if(isHTML){
  3894. defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
  3895. }
  3896. defaultNSMap.xml = defaultNSMap.xml || 'http://www.w3.org/XML/1998/namespace';
  3897. if(source && typeof source === 'string'){
  3898. sax.parse(source,defaultNSMap,entityMap);
  3899. }else{
  3900. sax.errorHandler.error("invalid doc source");
  3901. }
  3902. return domBuilder.doc;
  3903. }
  3904. function buildErrorHandler(errorImpl,domBuilder,locator){
  3905. if(!errorImpl){
  3906. if(domBuilder instanceof DOMHandler){
  3907. return domBuilder;
  3908. }
  3909. errorImpl = domBuilder ;
  3910. }
  3911. var errorHandler = {}
  3912. var isCallback = errorImpl instanceof Function;
  3913. locator = locator||{}
  3914. function build(key){
  3915. var fn = errorImpl[key];
  3916. if(!fn && isCallback){
  3917. fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
  3918. }
  3919. errorHandler[key] = fn && function(msg){
  3920. fn('[xmldom '+key+']\t'+msg+_locator(locator));
  3921. }||function(){};
  3922. }
  3923. build('warning');
  3924. build('error');
  3925. build('fatalError');
  3926. return errorHandler;
  3927. }
  3928. //console.log('#\n\n\n\n\n\n\n####')
  3929. /**
  3930. * +ContentHandler+ErrorHandler
  3931. * +LexicalHandler+EntityResolver2
  3932. * -DeclHandler-DTDHandler
  3933. *
  3934. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  3935. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  3936. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  3937. */
  3938. function DOMHandler() {
  3939. this.cdata = false;
  3940. }
  3941. function position(locator,node){
  3942. node.lineNumber = locator.lineNumber;
  3943. node.columnNumber = locator.columnNumber;
  3944. }
  3945. /**
  3946. * @see org.xml.sax.ContentHandler#startDocument
  3947. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  3948. */
  3949. DOMHandler.prototype = {
  3950. startDocument : function() {
  3951. this.doc = new DOMImplementation().createDocument(null, null, null);
  3952. if (this.locator) {
  3953. this.doc.documentURI = this.locator.systemId;
  3954. }
  3955. },
  3956. startElement:function(namespaceURI, localName, qName, attrs) {
  3957. var doc = this.doc;
  3958. var el = doc.createElementNS(namespaceURI, qName||localName);
  3959. var len = attrs.length;
  3960. appendElement(this, el);
  3961. this.currentElement = el;
  3962. this.locator && position(this.locator,el)
  3963. for (var i = 0 ; i < len; i++) {
  3964. var namespaceURI = attrs.getURI(i);
  3965. var value = attrs.getValue(i);
  3966. var qName = attrs.getQName(i);
  3967. var attr = doc.createAttributeNS(namespaceURI, qName);
  3968. this.locator &&position(attrs.getLocator(i),attr);
  3969. attr.value = attr.nodeValue = value;
  3970. el.setAttributeNode(attr)
  3971. }
  3972. },
  3973. endElement:function(namespaceURI, localName, qName) {
  3974. var current = this.currentElement
  3975. var tagName = current.tagName;
  3976. this.currentElement = current.parentNode;
  3977. },
  3978. startPrefixMapping:function(prefix, uri) {
  3979. },
  3980. endPrefixMapping:function(prefix) {
  3981. },
  3982. processingInstruction:function(target, data) {
  3983. var ins = this.doc.createProcessingInstruction(target, data);
  3984. this.locator && position(this.locator,ins)
  3985. appendElement(this, ins);
  3986. },
  3987. ignorableWhitespace:function(ch, start, length) {
  3988. },
  3989. characters:function(chars, start, length) {
  3990. chars = _toString.apply(this,arguments)
  3991. //console.log(chars)
  3992. if(chars){
  3993. if (this.cdata) {
  3994. var charNode = this.doc.createCDATASection(chars);
  3995. } else {
  3996. var charNode = this.doc.createTextNode(chars);
  3997. }
  3998. if(this.currentElement){
  3999. this.currentElement.appendChild(charNode);
  4000. }else if(/^\s*$/.test(chars)){
  4001. this.doc.appendChild(charNode);
  4002. //process xml
  4003. }
  4004. this.locator && position(this.locator,charNode)
  4005. }
  4006. },
  4007. skippedEntity:function(name) {
  4008. },
  4009. endDocument:function() {
  4010. this.doc.normalize();
  4011. },
  4012. setDocumentLocator:function (locator) {
  4013. if(this.locator = locator){// && !('lineNumber' in locator)){
  4014. locator.lineNumber = 0;
  4015. }
  4016. },
  4017. //LexicalHandler
  4018. comment:function(chars, start, length) {
  4019. chars = _toString.apply(this,arguments)
  4020. var comm = this.doc.createComment(chars);
  4021. this.locator && position(this.locator,comm)
  4022. appendElement(this, comm);
  4023. },
  4024. startCDATA:function() {
  4025. //used in characters() methods
  4026. this.cdata = true;
  4027. },
  4028. endCDATA:function() {
  4029. this.cdata = false;
  4030. },
  4031. startDTD:function(name, publicId, systemId) {
  4032. var impl = this.doc.implementation;
  4033. if (impl && impl.createDocumentType) {
  4034. var dt = impl.createDocumentType(name, publicId, systemId);
  4035. this.locator && position(this.locator,dt)
  4036. appendElement(this, dt);
  4037. }
  4038. },
  4039. /**
  4040. * @see org.xml.sax.ErrorHandler
  4041. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  4042. */
  4043. warning:function(error) {
  4044. console.warn('[xmldom warning]\t'+error,_locator(this.locator));
  4045. },
  4046. error:function(error) {
  4047. console.error('[xmldom error]\t'+error,_locator(this.locator));
  4048. },
  4049. fatalError:function(error) {
  4050. throw new ParseError(error, this.locator);
  4051. }
  4052. }
  4053. function _locator(l){
  4054. if(l){
  4055. return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
  4056. }
  4057. }
  4058. function _toString(chars,start,length){
  4059. if(typeof chars == 'string'){
  4060. return chars.substr(start,length)
  4061. }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  4062. if(chars.length >= start+length || start){
  4063. return new java.lang.String(chars,start,length)+'';
  4064. }
  4065. return chars;
  4066. }
  4067. }
  4068. /*
  4069. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  4070. * used method of org.xml.sax.ext.LexicalHandler:
  4071. * #comment(chars, start, length)
  4072. * #startCDATA()
  4073. * #endCDATA()
  4074. * #startDTD(name, publicId, systemId)
  4075. *
  4076. *
  4077. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  4078. * #endDTD()
  4079. * #startEntity(name)
  4080. * #endEntity(name)
  4081. *
  4082. *
  4083. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  4084. * IGNORED method of org.xml.sax.ext.DeclHandler
  4085. * #attributeDecl(eName, aName, type, mode, value)
  4086. * #elementDecl(name, model)
  4087. * #externalEntityDecl(name, publicId, systemId)
  4088. * #internalEntityDecl(name, value)
  4089. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  4090. * IGNORED method of org.xml.sax.EntityResolver2
  4091. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  4092. * #resolveEntity(publicId, systemId)
  4093. * #getExternalSubset(name, baseURI)
  4094. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  4095. * IGNORED method of org.xml.sax.DTDHandler
  4096. * #notationDecl(name, publicId, systemId) {};
  4097. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  4098. */
  4099. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
  4100. DOMHandler.prototype[key] = function(){return null}
  4101. })
  4102. /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
  4103. function appendElement (hander,node) {
  4104. if (!hander.currentElement) {
  4105. hander.doc.appendChild(node);
  4106. } else {
  4107. hander.currentElement.appendChild(node);
  4108. }
  4109. }//appendChild and setAttributeNS are preformance key
  4110. //if(typeof require == 'function'){
  4111. var htmlEntity = __webpack_require__(14);
  4112. var sax = __webpack_require__(15);
  4113. var XMLReader = sax.XMLReader;
  4114. var ParseError = sax.ParseError;
  4115. var DOMImplementation = exports.DOMImplementation = __webpack_require__(4).DOMImplementation;
  4116. exports.XMLSerializer = __webpack_require__(4).XMLSerializer ;
  4117. exports.DOMParser = DOMParser;
  4118. exports.__DOMHandler = DOMHandler;
  4119. //}
  4120. /***/ }),
  4121. /* 14 */
  4122. /***/ (function(module, exports) {
  4123. exports.entityMap = {
  4124. lt: '<',
  4125. gt: '>',
  4126. amp: '&',
  4127. quot: '"',
  4128. apos: "'",
  4129. Agrave: "À",
  4130. Aacute: "Á",
  4131. Acirc: "Â",
  4132. Atilde: "Ã",
  4133. Auml: "Ä",
  4134. Aring: "Å",
  4135. AElig: "Æ",
  4136. Ccedil: "Ç",
  4137. Egrave: "È",
  4138. Eacute: "É",
  4139. Ecirc: "Ê",
  4140. Euml: "Ë",
  4141. Igrave: "Ì",
  4142. Iacute: "Í",
  4143. Icirc: "Î",
  4144. Iuml: "Ï",
  4145. ETH: "Ð",
  4146. Ntilde: "Ñ",
  4147. Ograve: "Ò",
  4148. Oacute: "Ó",
  4149. Ocirc: "Ô",
  4150. Otilde: "Õ",
  4151. Ouml: "Ö",
  4152. Oslash: "Ø",
  4153. Ugrave: "Ù",
  4154. Uacute: "Ú",
  4155. Ucirc: "Û",
  4156. Uuml: "Ü",
  4157. Yacute: "Ý",
  4158. THORN: "Þ",
  4159. szlig: "ß",
  4160. agrave: "à",
  4161. aacute: "á",
  4162. acirc: "â",
  4163. atilde: "ã",
  4164. auml: "ä",
  4165. aring: "å",
  4166. aelig: "æ",
  4167. ccedil: "ç",
  4168. egrave: "è",
  4169. eacute: "é",
  4170. ecirc: "ê",
  4171. euml: "ë",
  4172. igrave: "ì",
  4173. iacute: "í",
  4174. icirc: "î",
  4175. iuml: "ï",
  4176. eth: "ð",
  4177. ntilde: "ñ",
  4178. ograve: "ò",
  4179. oacute: "ó",
  4180. ocirc: "ô",
  4181. otilde: "õ",
  4182. ouml: "ö",
  4183. oslash: "ø",
  4184. ugrave: "ù",
  4185. uacute: "ú",
  4186. ucirc: "û",
  4187. uuml: "ü",
  4188. yacute: "ý",
  4189. thorn: "þ",
  4190. yuml: "ÿ",
  4191. nbsp: "\u00a0",
  4192. iexcl: "¡",
  4193. cent: "¢",
  4194. pound: "£",
  4195. curren: "¤",
  4196. yen: "¥",
  4197. brvbar: "¦",
  4198. sect: "§",
  4199. uml: "¨",
  4200. copy: "©",
  4201. ordf: "ª",
  4202. laquo: "«",
  4203. not: "¬",
  4204. shy: "­­",
  4205. reg: "®",
  4206. macr: "¯",
  4207. deg: "°",
  4208. plusmn: "±",
  4209. sup2: "²",
  4210. sup3: "³",
  4211. acute: "´",
  4212. micro: "µ",
  4213. para: "¶",
  4214. middot: "·",
  4215. cedil: "¸",
  4216. sup1: "¹",
  4217. ordm: "º",
  4218. raquo: "»",
  4219. frac14: "¼",
  4220. frac12: "½",
  4221. frac34: "¾",
  4222. iquest: "¿",
  4223. times: "×",
  4224. divide: "÷",
  4225. forall: "∀",
  4226. part: "∂",
  4227. exist: "∃",
  4228. empty: "∅",
  4229. nabla: "∇",
  4230. isin: "∈",
  4231. notin: "∉",
  4232. ni: "∋",
  4233. prod: "∏",
  4234. sum: "∑",
  4235. minus: "−",
  4236. lowast: "∗",
  4237. radic: "√",
  4238. prop: "∝",
  4239. infin: "∞",
  4240. ang: "∠",
  4241. and: "∧",
  4242. or: "∨",
  4243. cap: "∩",
  4244. cup: "∪",
  4245. 'int': "∫",
  4246. there4: "∴",
  4247. sim: "∼",
  4248. cong: "≅",
  4249. asymp: "≈",
  4250. ne: "≠",
  4251. equiv: "≡",
  4252. le: "≤",
  4253. ge: "≥",
  4254. sub: "⊂",
  4255. sup: "⊃",
  4256. nsub: "⊄",
  4257. sube: "⊆",
  4258. supe: "⊇",
  4259. oplus: "⊕",
  4260. otimes: "⊗",
  4261. perp: "⊥",
  4262. sdot: "⋅",
  4263. Alpha: "Α",
  4264. Beta: "Β",
  4265. Gamma: "Γ",
  4266. Delta: "Δ",
  4267. Epsilon: "Ε",
  4268. Zeta: "Ζ",
  4269. Eta: "Η",
  4270. Theta: "Θ",
  4271. Iota: "Ι",
  4272. Kappa: "Κ",
  4273. Lambda: "Λ",
  4274. Mu: "Μ",
  4275. Nu: "Ν",
  4276. Xi: "Ξ",
  4277. Omicron: "Ο",
  4278. Pi: "Π",
  4279. Rho: "Ρ",
  4280. Sigma: "Σ",
  4281. Tau: "Τ",
  4282. Upsilon: "Υ",
  4283. Phi: "Φ",
  4284. Chi: "Χ",
  4285. Psi: "Ψ",
  4286. Omega: "Ω",
  4287. alpha: "α",
  4288. beta: "β",
  4289. gamma: "γ",
  4290. delta: "δ",
  4291. epsilon: "ε",
  4292. zeta: "ζ",
  4293. eta: "η",
  4294. theta: "θ",
  4295. iota: "ι",
  4296. kappa: "κ",
  4297. lambda: "λ",
  4298. mu: "μ",
  4299. nu: "ν",
  4300. xi: "ξ",
  4301. omicron: "ο",
  4302. pi: "π",
  4303. rho: "ρ",
  4304. sigmaf: "ς",
  4305. sigma: "σ",
  4306. tau: "τ",
  4307. upsilon: "υ",
  4308. phi: "φ",
  4309. chi: "χ",
  4310. psi: "ψ",
  4311. omega: "ω",
  4312. thetasym: "ϑ",
  4313. upsih: "ϒ",
  4314. piv: "ϖ",
  4315. OElig: "Œ",
  4316. oelig: "œ",
  4317. Scaron: "Š",
  4318. scaron: "š",
  4319. Yuml: "Ÿ",
  4320. fnof: "ƒ",
  4321. circ: "ˆ",
  4322. tilde: "˜",
  4323. ensp: " ",
  4324. emsp: " ",
  4325. thinsp: " ",
  4326. zwnj: "‌",
  4327. zwj: "‍",
  4328. lrm: "‎",
  4329. rlm: "‏",
  4330. ndash: "–",
  4331. mdash: "—",
  4332. lsquo: "‘",
  4333. rsquo: "’",
  4334. sbquo: "‚",
  4335. ldquo: "“",
  4336. rdquo: "”",
  4337. bdquo: "„",
  4338. dagger: "†",
  4339. Dagger: "‡",
  4340. bull: "•",
  4341. hellip: "…",
  4342. permil: "‰",
  4343. prime: "′",
  4344. Prime: "″",
  4345. lsaquo: "‹",
  4346. rsaquo: "›",
  4347. oline: "‾",
  4348. euro: "€",
  4349. trade: "™",
  4350. larr: "←",
  4351. uarr: "↑",
  4352. rarr: "→",
  4353. darr: "↓",
  4354. harr: "↔",
  4355. crarr: "↵",
  4356. lceil: "⌈",
  4357. rceil: "⌉",
  4358. lfloor: "⌊",
  4359. rfloor: "⌋",
  4360. loz: "◊",
  4361. spades: "♠",
  4362. clubs: "♣",
  4363. hearts: "♥",
  4364. diams: "♦"
  4365. };
  4366. /***/ }),
  4367. /* 15 */
  4368. /***/ (function(module, exports) {
  4369. //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
  4370. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  4371. //[5] Name ::= NameStartChar (NameChar)*
  4372. var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF
  4373. var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
  4374. var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
  4375. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  4376. //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
  4377. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  4378. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  4379. var S_TAG = 0;//tag name offerring
  4380. var S_ATTR = 1;//attr name offerring
  4381. var S_ATTR_SPACE=2;//attr name end and space offer
  4382. var S_EQ = 3;//=space?
  4383. var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
  4384. var S_ATTR_END = 5;//attr value end and no space(quot end)
  4385. var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
  4386. var S_TAG_CLOSE = 7;//closed el<el />
  4387. /**
  4388. * Creates an error that will not be caught by XMLReader aka the SAX parser.
  4389. *
  4390. * @param {string} message
  4391. * @param {any?} locator Optional, can provide details about the location in the source
  4392. * @constructor
  4393. */
  4394. function ParseError(message, locator) {
  4395. this.message = message
  4396. this.locator = locator
  4397. if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError);
  4398. }
  4399. ParseError.prototype = new Error();
  4400. ParseError.prototype.name = ParseError.name
  4401. function XMLReader(){
  4402. }
  4403. XMLReader.prototype = {
  4404. parse:function(source,defaultNSMap,entityMap){
  4405. var domBuilder = this.domBuilder;
  4406. domBuilder.startDocument();
  4407. _copy(defaultNSMap ,defaultNSMap = {})
  4408. parse(source,defaultNSMap,entityMap,
  4409. domBuilder,this.errorHandler);
  4410. domBuilder.endDocument();
  4411. }
  4412. }
  4413. function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
  4414. function fixedFromCharCode(code) {
  4415. // String.prototype.fromCharCode does not supports
  4416. // > 2 bytes unicode chars directly
  4417. if (code > 0xffff) {
  4418. code -= 0x10000;
  4419. var surrogate1 = 0xd800 + (code >> 10)
  4420. , surrogate2 = 0xdc00 + (code & 0x3ff);
  4421. return String.fromCharCode(surrogate1, surrogate2);
  4422. } else {
  4423. return String.fromCharCode(code);
  4424. }
  4425. }
  4426. function entityReplacer(a){
  4427. var k = a.slice(1,-1);
  4428. if(k in entityMap){
  4429. return entityMap[k];
  4430. }else if(k.charAt(0) === '#'){
  4431. return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
  4432. }else{
  4433. errorHandler.error('entity not found:'+a);
  4434. return a;
  4435. }
  4436. }
  4437. function appendText(end){//has some bugs
  4438. if(end>start){
  4439. var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
  4440. locator&&position(start);
  4441. domBuilder.characters(xt,0,end-start);
  4442. start = end
  4443. }
  4444. }
  4445. function position(p,m){
  4446. while(p>=lineEnd && (m = linePattern.exec(source))){
  4447. lineStart = m.index;
  4448. lineEnd = lineStart + m[0].length;
  4449. locator.lineNumber++;
  4450. //console.log('line++:',locator,startPos,endPos)
  4451. }
  4452. locator.columnNumber = p-lineStart+1;
  4453. }
  4454. var lineStart = 0;
  4455. var lineEnd = 0;
  4456. var linePattern = /.*(?:\r\n?|\n)|.*$/g
  4457. var locator = domBuilder.locator;
  4458. var parseStack = [{currentNSMap:defaultNSMapCopy}]
  4459. var closeMap = {};
  4460. var start = 0;
  4461. while(true){
  4462. try{
  4463. var tagStart = source.indexOf('<',start);
  4464. if(tagStart<0){
  4465. if(!source.substr(start).match(/^\s*$/)){
  4466. var doc = domBuilder.doc;
  4467. var text = doc.createTextNode(source.substr(start));
  4468. doc.appendChild(text);
  4469. domBuilder.currentElement = text;
  4470. }
  4471. return;
  4472. }
  4473. if(tagStart>start){
  4474. appendText(tagStart);
  4475. }
  4476. switch(source.charAt(tagStart+1)){
  4477. case '/':
  4478. var end = source.indexOf('>',tagStart+3);
  4479. var tagName = source.substring(tagStart+2,end);
  4480. var config = parseStack.pop();
  4481. if(end<0){
  4482. tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
  4483. errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
  4484. end = tagStart+1+tagName.length;
  4485. }else if(tagName.match(/\s</)){
  4486. tagName = tagName.replace(/[\s<].*/,'');
  4487. errorHandler.error("end tag name: "+tagName+' maybe not complete');
  4488. end = tagStart+1+tagName.length;
  4489. }
  4490. var localNSMap = config.localNSMap;
  4491. var endMatch = config.tagName == tagName;
  4492. var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase()
  4493. if(endIgnoreCaseMach){
  4494. domBuilder.endElement(config.uri,config.localName,tagName);
  4495. if(localNSMap){
  4496. for(var prefix in localNSMap){
  4497. domBuilder.endPrefixMapping(prefix) ;
  4498. }
  4499. }
  4500. if(!endMatch){
  4501. errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
  4502. }
  4503. }else{
  4504. parseStack.push(config)
  4505. }
  4506. end++;
  4507. break;
  4508. // end elment
  4509. case '?':// <?...?>
  4510. locator&&position(tagStart);
  4511. end = parseInstruction(source,tagStart,domBuilder);
  4512. break;
  4513. case '!':// <!doctype,<![CDATA,<!--
  4514. locator&&position(tagStart);
  4515. end = parseDCC(source,tagStart,domBuilder,errorHandler);
  4516. break;
  4517. default:
  4518. locator&&position(tagStart);
  4519. var el = new ElementAttributes();
  4520. var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  4521. //elStartEnd
  4522. var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
  4523. var len = el.length;
  4524. if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
  4525. el.closed = true;
  4526. if(!entityMap.nbsp){
  4527. errorHandler.warning('unclosed xml attribute');
  4528. }
  4529. }
  4530. if(locator && len){
  4531. var locator2 = copyLocator(locator,{});
  4532. //try{//attribute position fixed
  4533. for(var i = 0;i<len;i++){
  4534. var a = el[i];
  4535. position(a.offset);
  4536. a.locator = copyLocator(locator,{});
  4537. }
  4538. domBuilder.locator = locator2
  4539. if(appendElement(el,domBuilder,currentNSMap)){
  4540. parseStack.push(el)
  4541. }
  4542. domBuilder.locator = locator;
  4543. }else{
  4544. if(appendElement(el,domBuilder,currentNSMap)){
  4545. parseStack.push(el)
  4546. }
  4547. }
  4548. if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
  4549. end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
  4550. }else{
  4551. end++;
  4552. }
  4553. }
  4554. }catch(e){
  4555. if (e instanceof ParseError) {
  4556. throw e;
  4557. }
  4558. errorHandler.error('element parse error: '+e)
  4559. end = -1;
  4560. }
  4561. if(end>start){
  4562. start = end;
  4563. }else{
  4564. //TODO: 这里有可能sax回退,有位置错误风险
  4565. appendText(Math.max(tagStart,start)+1);
  4566. }
  4567. }
  4568. }
  4569. function copyLocator(f,t){
  4570. t.lineNumber = f.lineNumber;
  4571. t.columnNumber = f.columnNumber;
  4572. return t;
  4573. }
  4574. /**
  4575. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  4576. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  4577. */
  4578. function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
  4579. /**
  4580. * @param {string} qname
  4581. * @param {string} value
  4582. * @param {number} startIndex
  4583. */
  4584. function addAttribute(qname, value, startIndex) {
  4585. if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined')
  4586. el.addValue(qname, value, startIndex)
  4587. }
  4588. var attrName;
  4589. var value;
  4590. var p = ++start;
  4591. var s = S_TAG;//status
  4592. while(true){
  4593. var c = source.charAt(p);
  4594. switch(c){
  4595. case '=':
  4596. if(s === S_ATTR){//attrName
  4597. attrName = source.slice(start,p);
  4598. s = S_EQ;
  4599. }else if(s === S_ATTR_SPACE){
  4600. s = S_EQ;
  4601. }else{
  4602. //fatalError: equal must after attrName or space after attrName
  4603. throw new Error('attribute equal must after attrName'); // No known test case
  4604. }
  4605. break;
  4606. case '\'':
  4607. case '"':
  4608. if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
  4609. ){//equal
  4610. if(s === S_ATTR){
  4611. errorHandler.warning('attribute value must after "="')
  4612. attrName = source.slice(start,p)
  4613. }
  4614. start = p+1;
  4615. p = source.indexOf(c,start)
  4616. if(p>0){
  4617. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  4618. addAttribute(attrName, value, start-1);
  4619. s = S_ATTR_END;
  4620. }else{
  4621. //fatalError: no end quot match
  4622. throw new Error('attribute value no end \''+c+'\' match');
  4623. }
  4624. }else if(s == S_ATTR_NOQUOT_VALUE){
  4625. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  4626. //console.log(attrName,value,start,p)
  4627. addAttribute(attrName, value, start);
  4628. //console.dir(el)
  4629. errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
  4630. start = p+1;
  4631. s = S_ATTR_END
  4632. }else{
  4633. //fatalError: no equal before
  4634. throw new Error('attribute value must after "="'); // No known test case
  4635. }
  4636. break;
  4637. case '/':
  4638. switch(s){
  4639. case S_TAG:
  4640. el.setTagName(source.slice(start,p));
  4641. case S_ATTR_END:
  4642. case S_TAG_SPACE:
  4643. case S_TAG_CLOSE:
  4644. s =S_TAG_CLOSE;
  4645. el.closed = true;
  4646. case S_ATTR_NOQUOT_VALUE:
  4647. case S_ATTR:
  4648. case S_ATTR_SPACE:
  4649. break;
  4650. //case S_EQ:
  4651. default:
  4652. throw new Error("attribute invalid close char('/')") // No known test case
  4653. }
  4654. break;
  4655. case ''://end document
  4656. errorHandler.error('unexpected end of input');
  4657. if(s == S_TAG){
  4658. el.setTagName(source.slice(start,p));
  4659. }
  4660. return p;
  4661. case '>':
  4662. switch(s){
  4663. case S_TAG:
  4664. el.setTagName(source.slice(start,p));
  4665. case S_ATTR_END:
  4666. case S_TAG_SPACE:
  4667. case S_TAG_CLOSE:
  4668. break;//normal
  4669. case S_ATTR_NOQUOT_VALUE://Compatible state
  4670. case S_ATTR:
  4671. value = source.slice(start,p);
  4672. if(value.slice(-1) === '/'){
  4673. el.closed = true;
  4674. value = value.slice(0,-1)
  4675. }
  4676. case S_ATTR_SPACE:
  4677. if(s === S_ATTR_SPACE){
  4678. value = attrName;
  4679. }
  4680. if(s == S_ATTR_NOQUOT_VALUE){
  4681. errorHandler.warning('attribute "'+value+'" missed quot(")!');
  4682. addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start)
  4683. }else{
  4684. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !value.match(/^(?:disabled|checked|selected)$/i)){
  4685. errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
  4686. }
  4687. addAttribute(value, value, start)
  4688. }
  4689. break;
  4690. case S_EQ:
  4691. throw new Error('attribute value missed!!');
  4692. }
  4693. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  4694. return p;
  4695. /*xml space '\x20' | #x9 | #xD | #xA; */
  4696. case '\u0080':
  4697. c = ' ';
  4698. default:
  4699. if(c<= ' '){//space
  4700. switch(s){
  4701. case S_TAG:
  4702. el.setTagName(source.slice(start,p));//tagName
  4703. s = S_TAG_SPACE;
  4704. break;
  4705. case S_ATTR:
  4706. attrName = source.slice(start,p)
  4707. s = S_ATTR_SPACE;
  4708. break;
  4709. case S_ATTR_NOQUOT_VALUE:
  4710. var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  4711. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  4712. addAttribute(attrName, value, start)
  4713. case S_ATTR_END:
  4714. s = S_TAG_SPACE;
  4715. break;
  4716. //case S_TAG_SPACE:
  4717. //case S_EQ:
  4718. //case S_ATTR_SPACE:
  4719. // void();break;
  4720. //case S_TAG_CLOSE:
  4721. //ignore warning
  4722. }
  4723. }else{//not space
  4724. //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
  4725. //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
  4726. switch(s){
  4727. //case S_TAG:void();break;
  4728. //case S_ATTR:void();break;
  4729. //case S_ATTR_NOQUOT_VALUE:void();break;
  4730. case S_ATTR_SPACE:
  4731. var tagName = el.tagName;
  4732. if(currentNSMap[''] !== 'http://www.w3.org/1999/xhtml' || !attrName.match(/^(?:disabled|checked|selected)$/i)){
  4733. errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!')
  4734. }
  4735. addAttribute(attrName, attrName, start);
  4736. start = p;
  4737. s = S_ATTR;
  4738. break;
  4739. case S_ATTR_END:
  4740. errorHandler.warning('attribute space is required"'+attrName+'"!!')
  4741. case S_TAG_SPACE:
  4742. s = S_ATTR;
  4743. start = p;
  4744. break;
  4745. case S_EQ:
  4746. s = S_ATTR_NOQUOT_VALUE;
  4747. start = p;
  4748. break;
  4749. case S_TAG_CLOSE:
  4750. throw new Error("elements closed character '/' and '>' must be connected to");
  4751. }
  4752. }
  4753. }//end outer switch
  4754. //console.log('p++',p)
  4755. p++;
  4756. }
  4757. }
  4758. /**
  4759. * @return true if has new namespace define
  4760. */
  4761. function appendElement(el,domBuilder,currentNSMap){
  4762. var tagName = el.tagName;
  4763. var localNSMap = null;
  4764. //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  4765. var i = el.length;
  4766. while(i--){
  4767. var a = el[i];
  4768. var qName = a.qName;
  4769. var value = a.value;
  4770. var nsp = qName.indexOf(':');
  4771. if(nsp>0){
  4772. var prefix = a.prefix = qName.slice(0,nsp);
  4773. var localName = qName.slice(nsp+1);
  4774. var nsPrefix = prefix === 'xmlns' && localName
  4775. }else{
  4776. localName = qName;
  4777. prefix = null
  4778. nsPrefix = qName === 'xmlns' && ''
  4779. }
  4780. //can not set prefix,because prefix !== ''
  4781. a.localName = localName ;
  4782. //prefix == null for no ns prefix attribute
  4783. if(nsPrefix !== false){//hack!!
  4784. if(localNSMap == null){
  4785. localNSMap = {}
  4786. //console.log(currentNSMap,0)
  4787. _copy(currentNSMap,currentNSMap={})
  4788. //console.log(currentNSMap,1)
  4789. }
  4790. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  4791. a.uri = 'http://www.w3.org/2000/xmlns/'
  4792. domBuilder.startPrefixMapping(nsPrefix, value)
  4793. }
  4794. }
  4795. var i = el.length;
  4796. while(i--){
  4797. a = el[i];
  4798. var prefix = a.prefix;
  4799. if(prefix){//no prefix attribute has no namespace
  4800. if(prefix === 'xml'){
  4801. a.uri = 'http://www.w3.org/XML/1998/namespace';
  4802. }if(prefix !== 'xmlns'){
  4803. a.uri = currentNSMap[prefix || '']
  4804. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  4805. }
  4806. }
  4807. }
  4808. var nsp = tagName.indexOf(':');
  4809. if(nsp>0){
  4810. prefix = el.prefix = tagName.slice(0,nsp);
  4811. localName = el.localName = tagName.slice(nsp+1);
  4812. }else{
  4813. prefix = null;//important!!
  4814. localName = el.localName = tagName;
  4815. }
  4816. //no prefix element has default namespace
  4817. var ns = el.uri = currentNSMap[prefix || ''];
  4818. domBuilder.startElement(ns,localName,tagName,el);
  4819. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  4820. //localNSMap = null
  4821. if(el.closed){
  4822. domBuilder.endElement(ns,localName,tagName);
  4823. if(localNSMap){
  4824. for(prefix in localNSMap){
  4825. domBuilder.endPrefixMapping(prefix)
  4826. }
  4827. }
  4828. }else{
  4829. el.currentNSMap = currentNSMap;
  4830. el.localNSMap = localNSMap;
  4831. //parseStack.push(el);
  4832. return true;
  4833. }
  4834. }
  4835. function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
  4836. if(/^(?:script|textarea)$/i.test(tagName)){
  4837. var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
  4838. var text = source.substring(elStartEnd+1,elEndStart);
  4839. if(/[&<]/.test(text)){
  4840. if(/^script$/i.test(tagName)){
  4841. //if(!/\]\]>/.test(text)){
  4842. //lexHandler.startCDATA();
  4843. domBuilder.characters(text,0,text.length);
  4844. //lexHandler.endCDATA();
  4845. return elEndStart;
  4846. //}
  4847. }//}else{//text area
  4848. text = text.replace(/&#?\w+;/g,entityReplacer);
  4849. domBuilder.characters(text,0,text.length);
  4850. return elEndStart;
  4851. //}
  4852. }
  4853. }
  4854. return elStartEnd+1;
  4855. }
  4856. function fixSelfClosed(source,elStartEnd,tagName,closeMap){
  4857. //if(tagName in closeMap){
  4858. var pos = closeMap[tagName];
  4859. if(pos == null){
  4860. //console.log(tagName)
  4861. pos = source.lastIndexOf('</'+tagName+'>')
  4862. if(pos<elStartEnd){//忘记闭合
  4863. pos = source.lastIndexOf('</'+tagName)
  4864. }
  4865. closeMap[tagName] =pos
  4866. }
  4867. return pos<elStartEnd;
  4868. //}
  4869. }
  4870. function _copy(source,target){
  4871. for(var n in source){target[n] = source[n]}
  4872. }
  4873. function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
  4874. var next= source.charAt(start+2)
  4875. switch(next){
  4876. case '-':
  4877. if(source.charAt(start + 3) === '-'){
  4878. var end = source.indexOf('-->',start+4);
  4879. //append comment source.substring(4,end)//<!--
  4880. if(end>start){
  4881. domBuilder.comment(source,start+4,end-start-4);
  4882. return end+3;
  4883. }else{
  4884. errorHandler.error("Unclosed comment");
  4885. return -1;
  4886. }
  4887. }else{
  4888. //error
  4889. return -1;
  4890. }
  4891. default:
  4892. if(source.substr(start+3,6) == 'CDATA['){
  4893. var end = source.indexOf(']]>',start+9);
  4894. domBuilder.startCDATA();
  4895. domBuilder.characters(source,start+9,end-start-9);
  4896. domBuilder.endCDATA()
  4897. return end+3;
  4898. }
  4899. //<!DOCTYPE
  4900. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  4901. var matchs = split(source,start);
  4902. var len = matchs.length;
  4903. if(len>1 && /!doctype/i.test(matchs[0][0])){
  4904. var name = matchs[1][0];
  4905. var pubid = false;
  4906. var sysid = false;
  4907. if(len>3){
  4908. if(/^public$/i.test(matchs[2][0])){
  4909. pubid = matchs[3][0];
  4910. sysid = len>4 && matchs[4][0];
  4911. }else if(/^system$/i.test(matchs[2][0])){
  4912. sysid = matchs[3][0];
  4913. }
  4914. }
  4915. var lastMatch = matchs[len-1]
  4916. domBuilder.startDTD(name, pubid, sysid);
  4917. domBuilder.endDTD();
  4918. return lastMatch.index+lastMatch[0].length
  4919. }
  4920. }
  4921. return -1;
  4922. }
  4923. function parseInstruction(source,start,domBuilder){
  4924. var end = source.indexOf('?>',start);
  4925. if(end){
  4926. var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  4927. if(match){
  4928. var len = match[0].length;
  4929. domBuilder.processingInstruction(match[1], match[2]) ;
  4930. return end+2;
  4931. }else{//error
  4932. return -1;
  4933. }
  4934. }
  4935. return -1;
  4936. }
  4937. function ElementAttributes(){
  4938. this.attributeNames = {}
  4939. }
  4940. ElementAttributes.prototype = {
  4941. setTagName:function(tagName){
  4942. if(!tagNamePattern.test(tagName)){
  4943. throw new Error('invalid tagName:'+tagName)
  4944. }
  4945. this.tagName = tagName
  4946. },
  4947. addValue:function(qName, value, offset) {
  4948. if(!tagNamePattern.test(qName)){
  4949. throw new Error('invalid attribute:'+qName)
  4950. }
  4951. this.attributeNames[qName] = this.length;
  4952. this[this.length++] = {qName:qName,value:value,offset:offset}
  4953. },
  4954. length:0,
  4955. getLocalName:function(i){return this[i].localName},
  4956. getLocator:function(i){return this[i].locator},
  4957. getQName:function(i){return this[i].qName},
  4958. getURI:function(i){return this[i].uri},
  4959. getValue:function(i){return this[i].value}
  4960. // ,getIndex:function(uri, localName)){
  4961. // if(localName){
  4962. //
  4963. // }else{
  4964. // var qName = uri
  4965. // }
  4966. // },
  4967. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  4968. // getType:function(uri,localName){}
  4969. // getType:function(i){},
  4970. }
  4971. function split(source,start){
  4972. var match;
  4973. var buf = [];
  4974. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  4975. reg.lastIndex = start;
  4976. reg.exec(source);//skip <
  4977. while(match = reg.exec(source)){
  4978. buf.push(match);
  4979. if(match[1])return buf;
  4980. }
  4981. }
  4982. exports.XMLReader = XMLReader;
  4983. exports.ParseError = ParseError;
  4984. /***/ }),
  4985. /* 16 */
  4986. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  4987. "use strict";
  4988. // ESM COMPAT FLAG
  4989. __webpack_require__.r(__webpack_exports__);
  4990. // EXPORTS
  4991. __webpack_require__.d(__webpack_exports__, "toKml", function() { return /* binding */ toKml; });
  4992. __webpack_require__.d(__webpack_exports__, "toGeoJSON", function() { return /* binding */ toGeoJSON; });
  4993. // EXTERNAL MODULE: ./node_modules/JSZip/dist/jszip.min.js
  4994. var jszip_min = __webpack_require__(5);
  4995. // EXTERNAL MODULE: ./src/conver/kmlToGeoJSON.js
  4996. var kmlToGeoJSON = __webpack_require__(0);
  4997. // CONCATENATED MODULE: ./src/conver/geoJSONToKml.js
  4998. //geojson => kml
  4999. function geoJSONToKml(geojson, options) {
  5000. options = options || {
  5001. documentName: undefined,
  5002. documentDescription: undefined,
  5003. name: 'name',
  5004. description: 'description',
  5005. simplestyle: false,
  5006. timestamp: 'timestamp'
  5007. };
  5008. return '<?xml version="1.0" encoding="UTF-8"?>' + tag('kml', tag('Document', documentName(options) + documentDescription(options) + root(geojson, options)), [['xmlns', 'http://www.opengis.net/kml/2.2']]);
  5009. }
  5010. function feature(options, styleHashesArray) {
  5011. return function (attr) {
  5012. if (!attr.properties || !geometry.valid(attr.geometry)) return '';
  5013. var geometryString = geometry.any(attr.geometry);
  5014. if (!geometryString) return '';
  5015. var styleDefinition = '',
  5016. styleReference = '';
  5017. if (options.simplestyle) {
  5018. var styleHash = hashStyle(attr.properties);
  5019. if (styleHash) {
  5020. if (geometry.isPoint(attr.geometry) && hasMarkerStyle(attr.properties)) {
  5021. if (styleHashesArray.indexOf(styleHash) === -1) {
  5022. styleDefinition = markerStyle(attr.properties, styleHash);
  5023. styleHashesArray.push(styleHash);
  5024. }
  5025. styleReference = tag('styleUrl', '#' + styleHash);
  5026. } else if ((geometry.isPolygon(attr.geometry) || geometry.isLine(attr.geometry)) && hasPolygonAndLineStyle(attr.properties)) {
  5027. if (styleHashesArray.indexOf(styleHash) === -1) {
  5028. styleDefinition = polygonAndLineStyle(attr.properties, styleHash);
  5029. styleHashesArray.push(styleHash);
  5030. }
  5031. styleReference = tag('styleUrl', '#' + styleHash);
  5032. } // Note that style of GeometryCollection / MultiGeometry is not supported
  5033. }
  5034. }
  5035. return styleDefinition + tag('Placemark', geoJSONToKml_name(attr.properties, options) + description(attr.properties, options) + extendeddata(attr.properties) + timestamp(attr.properties, options) + geometryString + styleReference);
  5036. };
  5037. }
  5038. function root(attr, options) {
  5039. if (!attr.type) return '';
  5040. var styleHashesArray = [];
  5041. switch (attr.type) {
  5042. case 'FeatureCollection':
  5043. if (!attr.features) return '';
  5044. return attr.features.map(feature(options, styleHashesArray)).join('');
  5045. case 'Feature':
  5046. return feature(options, styleHashesArray)(attr);
  5047. default:
  5048. return feature(options, styleHashesArray)({
  5049. type: 'Feature',
  5050. geometry: attr,
  5051. properties: {}
  5052. });
  5053. }
  5054. }
  5055. function documentName(options) {
  5056. return options.documentName !== undefined ? tag('name', options.documentName) : '';
  5057. }
  5058. function documentDescription(options) {
  5059. return options.documentDescription !== undefined ? tag('description', options.documentDescription) : '';
  5060. }
  5061. function geoJSONToKml_name(attr, options) {
  5062. return attr[options.name] ? tag('name', encode(attr[options.name])) : '';
  5063. }
  5064. function description(attr, options) {
  5065. return attr[options.description] ? tag('description', encode(attr[options.description])) : '';
  5066. }
  5067. function timestamp(attr, options) {
  5068. return attr[options.timestamp] ? tag('TimeStamp', tag('when', encode(attr[options.timestamp]))) : '';
  5069. } // ## Geometry Types
  5070. //
  5071. // https://developers.google.com/kml/documentation/kmlreference#geometry
  5072. var geometry = {
  5073. Point: function Point(attr) {
  5074. return tag('Point', tag('coordinates', attr.coordinates.join(',')));
  5075. },
  5076. LineString: function LineString(attr) {
  5077. return tag('LineString', tag('coordinates', linearring(attr.coordinates)));
  5078. },
  5079. Polygon: function Polygon(attr) {
  5080. if (!attr.coordinates.length) return '';
  5081. var outer = attr.coordinates[0],
  5082. inner = attr.coordinates.slice(1),
  5083. outerRing = tag('outerBoundaryIs', tag('LinearRing', tag('coordinates', linearring(outer)))),
  5084. innerRings = inner.map(function (i) {
  5085. return tag('innerBoundaryIs', tag('LinearRing', tag('coordinates', linearring(i))));
  5086. }).join('');
  5087. return tag('Polygon', outerRing + innerRings);
  5088. },
  5089. MultiPoint: function MultiPoint(attr) {
  5090. if (!attr.coordinates.length) return '';
  5091. return tag('MultiGeometry', attr.coordinates.map(function (c) {
  5092. return geometry.Point({
  5093. coordinates: c
  5094. });
  5095. }).join(''));
  5096. },
  5097. MultiPolygon: function MultiPolygon(attr) {
  5098. if (!attr.coordinates.length) return '';
  5099. return tag('MultiGeometry', attr.coordinates.map(function (c) {
  5100. return geometry.Polygon({
  5101. coordinates: c
  5102. });
  5103. }).join(''));
  5104. },
  5105. MultiLineString: function MultiLineString(attr) {
  5106. if (!attr.coordinates.length) return '';
  5107. return tag('MultiGeometry', attr.coordinates.map(function (c) {
  5108. return geometry.LineString({
  5109. coordinates: c
  5110. });
  5111. }).join(''));
  5112. },
  5113. GeometryCollection: function GeometryCollection(attr) {
  5114. return tag('MultiGeometry', attr.geometries.map(geometry.any).join(''));
  5115. },
  5116. valid: function valid(attr) {
  5117. return attr && attr.type && (attr.coordinates || attr.type === 'GeometryCollection' && attr.geometries && attr.geometries.every(geometry.valid));
  5118. },
  5119. any: function any(attr) {
  5120. if (geometry[attr.type]) {
  5121. return geometry[attr.type](attr);
  5122. } else {
  5123. return '';
  5124. }
  5125. },
  5126. isPoint: function isPoint(attr) {
  5127. return attr.type === 'Point' || attr.type === 'MultiPoint';
  5128. },
  5129. isPolygon: function isPolygon(attr) {
  5130. return attr.type === 'Polygon' || attr.type === 'MultiPolygon';
  5131. },
  5132. isLine: function isLine(attr) {
  5133. return attr.type === 'LineString' || attr.type === 'MultiLineString';
  5134. }
  5135. };
  5136. function linearring(attr) {
  5137. return attr.map(function (cds) {
  5138. return cds.join(',');
  5139. }).join(' ');
  5140. } // ## Data
  5141. function extendeddata(attr) {
  5142. var arr = [];
  5143. for (var i in attr) {
  5144. var val = attr[i];
  5145. if (isObject(val)) {
  5146. arr.push("<Data name =\"".concat(i, "\"><value>").concat(JSON.stringify(val), "</value></Data>"));
  5147. } else {
  5148. arr.push("<Data name =\"".concat(i, "\"><value>").concat(val, "</value></Data>"));
  5149. }
  5150. }
  5151. return tag('ExtendedData', arr.join(''));
  5152. }
  5153. function data(attr) {
  5154. return tag('Data', tag('value', encode(attr[1])), [['name', encode(attr[0])]]);
  5155. } // ## Marker style
  5156. function hasMarkerStyle(attr) {
  5157. return !!(attr['marker-size'] || attr['marker-symbol'] || attr['marker-color']);
  5158. }
  5159. function markerStyle(attr, styleHash) {
  5160. return tag('Style', tag('IconStyle', tag('Icon', tag('href', iconUrl(attr)))) + iconSize(attr), [['id', styleHash]]);
  5161. }
  5162. function iconUrl(attr) {
  5163. return attr['marker-symbol']; // var size = attr['marker-size'] || 'medium',
  5164. // symbol = attr['marker-symbol'] ? '-' + attr['marker-symbol'] : '',
  5165. // color = (attr['marker-color'] || '7e7e7e').replace('#', '')
  5166. // return 'https://api.tiles.mapbox.com/v3/marker/' + 'pin-' + size.charAt(0) + symbol + '+' + color + '.png'
  5167. }
  5168. function iconSize(attr) {
  5169. return tag('hotSpot', '', [['xunits', 'fraction'], ['yunits', 'fraction'], ['x', 0.5], ['y', 0.5]]);
  5170. } // ## Polygon and Line style
  5171. function hasPolygonAndLineStyle(attr) {
  5172. for (var key in attr) {
  5173. if ({
  5174. stroke: true,
  5175. 'stroke-opacity': true,
  5176. 'stroke-width': true,
  5177. fill: true,
  5178. 'fill-opacity': true
  5179. }[key]) return true;
  5180. }
  5181. }
  5182. function polygonAndLineStyle(attr, styleHash) {
  5183. var lineStyle = tag('LineStyle', [tag('color', hexToKmlColor(attr['stroke'], attr['stroke-opacity']) || 'ff555555') + tag('width', attr['stroke-width'] === undefined ? 2 : attr['stroke-width'])]);
  5184. var polyStyle = '';
  5185. if (attr['fill'] || attr['fill-opacity']) {
  5186. polyStyle = tag('PolyStyle', [tag('color', hexToKmlColor(attr['fill'], attr['fill-opacity']) || '88555555')]);
  5187. }
  5188. return tag('Style', lineStyle + polyStyle, [['id', styleHash]]);
  5189. } // ## Style helpers
  5190. function hashStyle(attr) {
  5191. var hash = '';
  5192. if (attr['marker-symbol']) hash = hash + 'ms' + attr['marker-symbol'];
  5193. if (attr['marker-color']) hash = hash + 'mc' + attr['marker-color'].replace('#', '');
  5194. if (attr['marker-size']) hash = hash + 'ms' + attr['marker-size'];
  5195. if (attr['stroke']) hash = hash + 's' + attr['stroke'].replace('#', '');
  5196. if (attr['stroke-width']) hash = hash + 'sw' + attr['stroke-width'].toString().replace('.', '');
  5197. if (attr['stroke-opacity']) hash = hash + 'mo' + attr['stroke-opacity'].toString().replace('.', '');
  5198. if (attr['fill']) hash = hash + 'f' + attr['fill'].replace('#', '');
  5199. if (attr['fill-opacity']) hash = hash + 'fo' + attr['fill-opacity'].toString().replace('.', '');
  5200. return hash;
  5201. }
  5202. function hexToKmlColor(hexColor, opacity) {
  5203. if (typeof hexColor !== 'string') return '';
  5204. hexColor = hexColor.replace('#', '').toLowerCase();
  5205. if (hexColor.length === 3) {
  5206. hexColor = hexColor[0] + hexColor[0] + hexColor[1] + hexColor[1] + hexColor[2] + hexColor[2];
  5207. } else if (hexColor.length !== 6) {
  5208. return '';
  5209. }
  5210. var r = hexColor[0] + hexColor[1];
  5211. var g = hexColor[2] + hexColor[3];
  5212. var b = hexColor[4] + hexColor[5];
  5213. var o = 'ff';
  5214. if (typeof opacity === 'number' && opacity >= 0.0 && opacity <= 1.0) {
  5215. o = (opacity * 255).toString(16);
  5216. if (o.indexOf('.') > -1) o = o.substr(0, o.indexOf('.'));
  5217. if (o.length < 2) o = '0' + o;
  5218. }
  5219. return o + b + g + r;
  5220. }
  5221. /**
  5222. * 判断对象是否为Object类型
  5223. * @param {*} obj 对象
  5224. * @returns {Boolean} 是否为Object类型
  5225. */
  5226. function isObject(obj) {
  5227. return Object.prototype.toString.call(obj) === '[object Object]';
  5228. }
  5229. /**
  5230. * @param {string} attr a string of attribute
  5231. * @returns {string}
  5232. */
  5233. function encode(attr) {
  5234. if (!attr) return '';
  5235. return attr.toString().replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  5236. }
  5237. /**
  5238. * @param {array} attr an array of attributes
  5239. * @returns {string}
  5240. */
  5241. function attr(attributes) {
  5242. if (!Object.keys(attributes).length) return '';
  5243. return ' ' + Object.keys(attributes).map(function (key) {
  5244. return key + '="' + geoJSONToKml_escape(attributes[key]) + '"';
  5245. }).join(' ');
  5246. }
  5247. var escape_map = {
  5248. '>': '&gt;',
  5249. '<': '&lt;',
  5250. "'": '&apos;',
  5251. '"': '&quot;',
  5252. '&': '&amp;'
  5253. };
  5254. function geoJSONToKml_escape(string, ignore) {
  5255. var pattern;
  5256. if (string === null || string === undefined) return;
  5257. ignore = (ignore || '').replace(/[^&"<>\']/g, '');
  5258. pattern = '([&"<>\'])'.replace(new RegExp('[' + ignore + ']', 'g'), '');
  5259. return string.replace(new RegExp(pattern, 'g'), function (str, item) {
  5260. return escape_map[item];
  5261. });
  5262. }
  5263. /**
  5264. * @param {string} el element name
  5265. * @param {string} contents innerXML
  5266. * @param {array} attributes array of pairs
  5267. * @returns {string}
  5268. */
  5269. function tag(el, attributes, contents) {
  5270. if (Array.isArray(attributes) || typeof attributes === 'string') {
  5271. contents = attributes;
  5272. attributes = {};
  5273. }
  5274. if (Array.isArray(contents)) contents = '\n' + contents.map(function (content) {
  5275. return ' ' + content;
  5276. }).join('\n') + '\n';
  5277. return '<' + el + attr(attributes) + '>' + contents + '</' + el + '>';
  5278. }
  5279. // CONCATENATED MODULE: ./src/index.js
  5280. //geojson转kml
  5281. function toKml(geojson, options) {
  5282. if (geojson.features) {
  5283. geojson.features.forEach(function (feature) {
  5284. if (!feature.properties) return;
  5285. var style = feature.properties.style;
  5286. if (style) {
  5287. if (style.image) {
  5288. feature.properties['marker-symbol'] = style.image;
  5289. if (style.outlineColor) feature.properties['marker-color'] = style.outlineColor;
  5290. return;
  5291. }
  5292. if (style.color) {
  5293. feature.properties['fill'] = style.color;
  5294. if (style.opacity) feature.properties['fill-opacity'] = style.opacity;
  5295. }
  5296. if (style.outlineColor) {
  5297. var _style$outlineWidth, _ref, _style$outlineOpacity;
  5298. feature.properties['stroke'] = style.outlineColor;
  5299. feature.properties['stroke-width'] = (_style$outlineWidth = style.outlineWidth) !== null && _style$outlineWidth !== void 0 ? _style$outlineWidth : 1;
  5300. feature.properties['stroke-opacity'] = (_ref = (_style$outlineOpacity = style.outlineOpacity) !== null && _style$outlineOpacity !== void 0 ? _style$outlineOpacity : style.opacity) !== null && _ref !== void 0 ? _ref : 1.0;
  5301. }
  5302. if (style.html) {
  5303. style.html = HTMLEncode(style.html);
  5304. }
  5305. }
  5306. });
  5307. }
  5308. return geoJSONToKml(geojson, options);
  5309. }
  5310. var getDom = function getDom(xml) {
  5311. return new DOMParser().parseFromString(xml, 'text/xml');
  5312. };
  5313. var getExtension = function getExtension(fileName) {
  5314. return fileName.split('.').pop();
  5315. };
  5316. var src_getKmlDom = function getKmlDom(kmzFile) {
  5317. var zip = new jszip_min();
  5318. return zip.loadAsync(kmzFile).then(function (zip) {
  5319. var kmlDom = null;
  5320. zip.forEach(function (relPath, file) {
  5321. if (getExtension(relPath) === 'kml' && kmlDom === null) {
  5322. kmlDom = file.async('string').then(getDom);
  5323. }
  5324. });
  5325. return kmlDom || Promise.reject('No kml file found');
  5326. });
  5327. }; //kml转geojson
  5328. function toGeoJSON(doc) {
  5329. if (!doc) return Promise.reject('参数不能为空');
  5330. if (isString(doc)) {
  5331. var extension = getExtension(doc);
  5332. if (extension === 'kml' && window.Cesium) {
  5333. return Cesium.Resource.fetchXML(doc).then(function (kmlDom) {
  5334. return Object(kmlToGeoJSON["a" /* kmlToGeoJSON */])(kmlDom);
  5335. });
  5336. } else if (extension === 'kmz' && window.Cesium) {
  5337. return Cesium.Resource.fetchBlob(doc).then(function (xml) {
  5338. return src_getKmlDom(xml);
  5339. }).then(function (kmlDom) {
  5340. return Object(kmlToGeoJSON["a" /* kmlToGeoJSON */])(kmlDom);
  5341. });
  5342. } else {
  5343. //直接传kml字符串文档
  5344. var geojson = Object(kmlToGeoJSON["a" /* kmlToGeoJSON */])(getDom(doc));
  5345. return Promise.resolve(geojson);
  5346. }
  5347. } else if (doc.getRootNode) {
  5348. //直接传docmect文档
  5349. var _geojson = Object(kmlToGeoJSON["a" /* kmlToGeoJSON */])(doc);
  5350. return Promise.resolve(_geojson);
  5351. } else {
  5352. //直接传blob
  5353. return src_getKmlDom(doc).then(function (kmlDom) {
  5354. return Object(kmlToGeoJSON["a" /* kmlToGeoJSON */])(kmlDom);
  5355. });
  5356. }
  5357. }
  5358. function isString(str) {
  5359. return typeof str == 'string' && str.constructor == String;
  5360. }
  5361. function HTMLEncode(html) {
  5362. var temp = document.createElement("div");
  5363. temp.textContent != null ? temp.textContent = html : temp.innerText = html;
  5364. var output = temp.innerHTML;
  5365. return output;
  5366. }
  5367. /***/ })
  5368. /******/ ]);
  5369. });