plist-parse.js 110 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.plist = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. (function (Buffer){
  3. /**
  4. * Module dependencies.
  5. */
  6. var deprecate = require('util-deprecate');
  7. var DOMParser = require('xmldom').DOMParser;
  8. /**
  9. * Module exports.
  10. */
  11. exports.parse = parse;
  12. exports.parseString = deprecate(parseString, '`parseString()` is deprecated. ' +
  13. 'It\'s not actually async. Use `parse()` instead.');
  14. exports.parseStringSync = deprecate(parseStringSync, '`parseStringSync()` is ' +
  15. 'deprecated. Use `parse()` instead.');
  16. /**
  17. * We ignore raw text (usually whitespace), <!-- xml comments -->,
  18. * and raw CDATA nodes.
  19. *
  20. * @param {Element} node
  21. * @returns {Boolean}
  22. * @api private
  23. */
  24. function shouldIgnoreNode (node) {
  25. return node.nodeType === 3 // text
  26. || node.nodeType === 8 // comment
  27. || node.nodeType === 4; // cdata
  28. }
  29. /**
  30. * Parses a Plist XML string. Returns an Object.
  31. *
  32. * @param {String} xml - the XML String to decode
  33. * @returns {Mixed} the decoded value from the Plist XML
  34. * @api public
  35. */
  36. function parse (xml) {
  37. var doc = new DOMParser().parseFromString(xml);
  38. if (doc.documentElement.nodeName !== 'plist') {
  39. throw new Error('malformed document. First element should be <plist>');
  40. }
  41. var plist = parsePlistXML(doc.documentElement);
  42. // the root <plist> node gets interpreted as an Array,
  43. // so pull out the inner data first
  44. if (plist.length == 1) plist = plist[0];
  45. return plist;
  46. }
  47. /**
  48. * Parses a Plist XML string. Returns an Object. Takes a `callback` function.
  49. *
  50. * @param {String} xml - the XML String to decode
  51. * @param {Function} callback - callback function
  52. * @returns {Mixed} the decoded value from the Plist XML
  53. * @api public
  54. * @deprecated not actually async. use parse() instead
  55. */
  56. function parseString (xml, callback) {
  57. var doc, error, plist;
  58. try {
  59. doc = new DOMParser().parseFromString(xml);
  60. plist = parsePlistXML(doc.documentElement);
  61. } catch(e) {
  62. error = e;
  63. }
  64. callback(error, plist);
  65. }
  66. /**
  67. * Parses a Plist XML string. Returns an Object.
  68. *
  69. * @param {String} xml - the XML String to decode
  70. * @param {Function} callback - callback function
  71. * @returns {Mixed} the decoded value from the Plist XML
  72. * @api public
  73. * @deprecated use parse() instead
  74. */
  75. function parseStringSync (xml) {
  76. var doc = new DOMParser().parseFromString(xml);
  77. var plist;
  78. if (doc.documentElement.nodeName !== 'plist') {
  79. throw new Error('malformed document. First element should be <plist>');
  80. }
  81. plist = parsePlistXML(doc.documentElement);
  82. // if the plist is an array with 1 element, pull it out of the array
  83. if (plist.length == 1) {
  84. plist = plist[0];
  85. }
  86. return plist;
  87. }
  88. /**
  89. * Convert an XML based plist document into a JSON representation.
  90. *
  91. * @param {Object} xml_node - current XML node in the plist
  92. * @returns {Mixed} built up JSON object
  93. * @api private
  94. */
  95. function parsePlistXML (node) {
  96. var i, new_obj, key, val, new_arr, res, d;
  97. if (!node)
  98. return null;
  99. if (node.nodeName === 'plist') {
  100. new_arr = [];
  101. for (i=0; i < node.childNodes.length; i++) {
  102. // ignore comment nodes (text)
  103. if (!shouldIgnoreNode(node.childNodes[i])) {
  104. new_arr.push( parsePlistXML(node.childNodes[i]));
  105. }
  106. }
  107. return new_arr;
  108. } else if (node.nodeName === 'dict') {
  109. new_obj = {};
  110. key = null;
  111. for (i=0; i < node.childNodes.length; i++) {
  112. // ignore comment nodes (text)
  113. if (!shouldIgnoreNode(node.childNodes[i])) {
  114. if (key === null) {
  115. key = parsePlistXML(node.childNodes[i]);
  116. } else {
  117. new_obj[key] = parsePlistXML(node.childNodes[i]);
  118. key = null;
  119. }
  120. }
  121. }
  122. return new_obj;
  123. } else if (node.nodeName === 'array') {
  124. new_arr = [];
  125. for (i=0; i < node.childNodes.length; i++) {
  126. // ignore comment nodes (text)
  127. if (!shouldIgnoreNode(node.childNodes[i])) {
  128. res = parsePlistXML(node.childNodes[i]);
  129. if (null != res) new_arr.push(res);
  130. }
  131. }
  132. return new_arr;
  133. } else if (node.nodeName === '#text') {
  134. // TODO: what should we do with text types? (CDATA sections)
  135. } else if (node.nodeName === 'key') {
  136. return node.childNodes[0].nodeValue;
  137. } else if (node.nodeName === 'string') {
  138. res = '';
  139. for (d=0; d < node.childNodes.length; d++) {
  140. res += node.childNodes[d].nodeValue;
  141. }
  142. return res;
  143. } else if (node.nodeName === 'integer') {
  144. // parse as base 10 integer
  145. return parseInt(node.childNodes[0].nodeValue, 10);
  146. } else if (node.nodeName === 'real') {
  147. res = '';
  148. for (d=0; d < node.childNodes.length; d++) {
  149. if (node.childNodes[d].nodeType === 3) {
  150. res += node.childNodes[d].nodeValue;
  151. }
  152. }
  153. return parseFloat(res);
  154. } else if (node.nodeName === 'data') {
  155. res = '';
  156. for (d=0; d < node.childNodes.length; d++) {
  157. if (node.childNodes[d].nodeType === 3) {
  158. res += node.childNodes[d].nodeValue.replace(/\s+/g, '');
  159. }
  160. }
  161. // decode base64 data to a Buffer instance
  162. return new Buffer(res, 'base64');
  163. } else if (node.nodeName === 'date') {
  164. return new Date(node.childNodes[0].nodeValue);
  165. } else if (node.nodeName === 'true') {
  166. return true;
  167. } else if (node.nodeName === 'false') {
  168. return false;
  169. }
  170. }
  171. }).call(this,require("buffer").Buffer)
  172. },{"buffer":3,"util-deprecate":6,"xmldom":7}],2:[function(require,module,exports){
  173. var lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  174. ;(function (exports) {
  175. 'use strict';
  176. var Arr = (typeof Uint8Array !== 'undefined')
  177. ? Uint8Array
  178. : Array
  179. var PLUS = '+'.charCodeAt(0)
  180. var SLASH = '/'.charCodeAt(0)
  181. var NUMBER = '0'.charCodeAt(0)
  182. var LOWER = 'a'.charCodeAt(0)
  183. var UPPER = 'A'.charCodeAt(0)
  184. var PLUS_URL_SAFE = '-'.charCodeAt(0)
  185. var SLASH_URL_SAFE = '_'.charCodeAt(0)
  186. function decode (elt) {
  187. var code = elt.charCodeAt(0)
  188. if (code === PLUS ||
  189. code === PLUS_URL_SAFE)
  190. return 62 // '+'
  191. if (code === SLASH ||
  192. code === SLASH_URL_SAFE)
  193. return 63 // '/'
  194. if (code < NUMBER)
  195. return -1 //no match
  196. if (code < NUMBER + 10)
  197. return code - NUMBER + 26 + 26
  198. if (code < UPPER + 26)
  199. return code - UPPER
  200. if (code < LOWER + 26)
  201. return code - LOWER + 26
  202. }
  203. function b64ToByteArray (b64) {
  204. var i, j, l, tmp, placeHolders, arr
  205. if (b64.length % 4 > 0) {
  206. throw new Error('Invalid string. Length must be a multiple of 4')
  207. }
  208. // the number of equal signs (place holders)
  209. // if there are two placeholders, than the two characters before it
  210. // represent one byte
  211. // if there is only one, then the three characters before it represent 2 bytes
  212. // this is just a cheap hack to not do indexOf twice
  213. var len = b64.length
  214. placeHolders = '=' === b64.charAt(len - 2) ? 2 : '=' === b64.charAt(len - 1) ? 1 : 0
  215. // base64 is 4/3 + up to two characters of the original data
  216. arr = new Arr(b64.length * 3 / 4 - placeHolders)
  217. // if there are placeholders, only get up to the last complete 4 chars
  218. l = placeHolders > 0 ? b64.length - 4 : b64.length
  219. var L = 0
  220. function push (v) {
  221. arr[L++] = v
  222. }
  223. for (i = 0, j = 0; i < l; i += 4, j += 3) {
  224. tmp = (decode(b64.charAt(i)) << 18) | (decode(b64.charAt(i + 1)) << 12) | (decode(b64.charAt(i + 2)) << 6) | decode(b64.charAt(i + 3))
  225. push((tmp & 0xFF0000) >> 16)
  226. push((tmp & 0xFF00) >> 8)
  227. push(tmp & 0xFF)
  228. }
  229. if (placeHolders === 2) {
  230. tmp = (decode(b64.charAt(i)) << 2) | (decode(b64.charAt(i + 1)) >> 4)
  231. push(tmp & 0xFF)
  232. } else if (placeHolders === 1) {
  233. tmp = (decode(b64.charAt(i)) << 10) | (decode(b64.charAt(i + 1)) << 4) | (decode(b64.charAt(i + 2)) >> 2)
  234. push((tmp >> 8) & 0xFF)
  235. push(tmp & 0xFF)
  236. }
  237. return arr
  238. }
  239. function uint8ToBase64 (uint8) {
  240. var i,
  241. extraBytes = uint8.length % 3, // if we have 1 byte left, pad 2 bytes
  242. output = "",
  243. temp, length
  244. function encode (num) {
  245. return lookup.charAt(num)
  246. }
  247. function tripletToBase64 (num) {
  248. return encode(num >> 18 & 0x3F) + encode(num >> 12 & 0x3F) + encode(num >> 6 & 0x3F) + encode(num & 0x3F)
  249. }
  250. // go through the array every three bytes, we'll deal with trailing stuff later
  251. for (i = 0, length = uint8.length - extraBytes; i < length; i += 3) {
  252. temp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
  253. output += tripletToBase64(temp)
  254. }
  255. // pad the end with zeros, but make sure to not forget the extra bytes
  256. switch (extraBytes) {
  257. case 1:
  258. temp = uint8[uint8.length - 1]
  259. output += encode(temp >> 2)
  260. output += encode((temp << 4) & 0x3F)
  261. output += '=='
  262. break
  263. case 2:
  264. temp = (uint8[uint8.length - 2] << 8) + (uint8[uint8.length - 1])
  265. output += encode(temp >> 10)
  266. output += encode((temp >> 4) & 0x3F)
  267. output += encode((temp << 2) & 0x3F)
  268. output += '='
  269. break
  270. }
  271. return output
  272. }
  273. exports.toByteArray = b64ToByteArray
  274. exports.fromByteArray = uint8ToBase64
  275. }(typeof exports === 'undefined' ? (this.base64js = {}) : exports))
  276. },{}],3:[function(require,module,exports){
  277. (function (global){
  278. /*!
  279. * The buffer module from node.js, for the browser.
  280. *
  281. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  282. * @license MIT
  283. */
  284. /* eslint-disable no-proto */
  285. var base64 = require('base64-js')
  286. var ieee754 = require('ieee754')
  287. var isArray = require('is-array')
  288. exports.Buffer = Buffer
  289. exports.SlowBuffer = SlowBuffer
  290. exports.INSPECT_MAX_BYTES = 50
  291. Buffer.poolSize = 8192 // not used by this implementation
  292. var rootParent = {}
  293. /**
  294. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  295. * === true Use Uint8Array implementation (fastest)
  296. * === false Use Object implementation (most compatible, even IE6)
  297. *
  298. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  299. * Opera 11.6+, iOS 4.2+.
  300. *
  301. * Due to various browser bugs, sometimes the Object implementation will be used even
  302. * when the browser supports typed arrays.
  303. *
  304. * Note:
  305. *
  306. * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
  307. * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
  308. *
  309. * - Safari 5-7 lacks support for changing the `Object.prototype.constructor` property
  310. * on objects.
  311. *
  312. * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
  313. *
  314. * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
  315. * incorrect length in some situations.
  316. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
  317. * get the Object implementation, which is slower but behaves correctly.
  318. */
  319. Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  320. ? global.TYPED_ARRAY_SUPPORT
  321. : typedArraySupport()
  322. function typedArraySupport () {
  323. function Bar () {}
  324. try {
  325. var arr = new Uint8Array(1)
  326. arr.foo = function () { return 42 }
  327. arr.constructor = Bar
  328. return arr.foo() === 42 && // typed array instances can be augmented
  329. arr.constructor === Bar && // constructor can be set
  330. typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
  331. arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
  332. } catch (e) {
  333. return false
  334. }
  335. }
  336. function kMaxLength () {
  337. return Buffer.TYPED_ARRAY_SUPPORT
  338. ? 0x7fffffff
  339. : 0x3fffffff
  340. }
  341. /**
  342. * Class: Buffer
  343. * =============
  344. *
  345. * The Buffer constructor returns instances of `Uint8Array` that are augmented
  346. * with function properties for all the node `Buffer` API functions. We use
  347. * `Uint8Array` so that square bracket notation works as expected -- it returns
  348. * a single octet.
  349. *
  350. * By augmenting the instances, we can avoid modifying the `Uint8Array`
  351. * prototype.
  352. */
  353. function Buffer (arg) {
  354. if (!(this instanceof Buffer)) {
  355. // Avoid going through an ArgumentsAdaptorTrampoline in the common case.
  356. if (arguments.length > 1) return new Buffer(arg, arguments[1])
  357. return new Buffer(arg)
  358. }
  359. this.length = 0
  360. this.parent = undefined
  361. // Common case.
  362. if (typeof arg === 'number') {
  363. return fromNumber(this, arg)
  364. }
  365. // Slightly less common case.
  366. if (typeof arg === 'string') {
  367. return fromString(this, arg, arguments.length > 1 ? arguments[1] : 'utf8')
  368. }
  369. // Unusual.
  370. return fromObject(this, arg)
  371. }
  372. function fromNumber (that, length) {
  373. that = allocate(that, length < 0 ? 0 : checked(length) | 0)
  374. if (!Buffer.TYPED_ARRAY_SUPPORT) {
  375. for (var i = 0; i < length; i++) {
  376. that[i] = 0
  377. }
  378. }
  379. return that
  380. }
  381. function fromString (that, string, encoding) {
  382. if (typeof encoding !== 'string' || encoding === '') encoding = 'utf8'
  383. // Assumption: byteLength() return value is always < kMaxLength.
  384. var length = byteLength(string, encoding) | 0
  385. that = allocate(that, length)
  386. that.write(string, encoding)
  387. return that
  388. }
  389. function fromObject (that, object) {
  390. if (Buffer.isBuffer(object)) return fromBuffer(that, object)
  391. if (isArray(object)) return fromArray(that, object)
  392. if (object == null) {
  393. throw new TypeError('must start with number, buffer, array or string')
  394. }
  395. if (typeof ArrayBuffer !== 'undefined') {
  396. if (object.buffer instanceof ArrayBuffer) {
  397. return fromTypedArray(that, object)
  398. }
  399. if (object instanceof ArrayBuffer) {
  400. return fromArrayBuffer(that, object)
  401. }
  402. }
  403. if (object.length) return fromArrayLike(that, object)
  404. return fromJsonObject(that, object)
  405. }
  406. function fromBuffer (that, buffer) {
  407. var length = checked(buffer.length) | 0
  408. that = allocate(that, length)
  409. buffer.copy(that, 0, 0, length)
  410. return that
  411. }
  412. function fromArray (that, array) {
  413. var length = checked(array.length) | 0
  414. that = allocate(that, length)
  415. for (var i = 0; i < length; i += 1) {
  416. that[i] = array[i] & 255
  417. }
  418. return that
  419. }
  420. // Duplicate of fromArray() to keep fromArray() monomorphic.
  421. function fromTypedArray (that, array) {
  422. var length = checked(array.length) | 0
  423. that = allocate(that, length)
  424. // Truncating the elements is probably not what people expect from typed
  425. // arrays with BYTES_PER_ELEMENT > 1 but it's compatible with the behavior
  426. // of the old Buffer constructor.
  427. for (var i = 0; i < length; i += 1) {
  428. that[i] = array[i] & 255
  429. }
  430. return that
  431. }
  432. function fromArrayBuffer (that, array) {
  433. if (Buffer.TYPED_ARRAY_SUPPORT) {
  434. // Return an augmented `Uint8Array` instance, for best performance
  435. array.byteLength
  436. that = Buffer._augment(new Uint8Array(array))
  437. } else {
  438. // Fallback: Return an object instance of the Buffer class
  439. that = fromTypedArray(that, new Uint8Array(array))
  440. }
  441. return that
  442. }
  443. function fromArrayLike (that, array) {
  444. var length = checked(array.length) | 0
  445. that = allocate(that, length)
  446. for (var i = 0; i < length; i += 1) {
  447. that[i] = array[i] & 255
  448. }
  449. return that
  450. }
  451. // Deserialize { type: 'Buffer', data: [1,2,3,...] } into a Buffer object.
  452. // Returns a zero-length buffer for inputs that don't conform to the spec.
  453. function fromJsonObject (that, object) {
  454. var array
  455. var length = 0
  456. if (object.type === 'Buffer' && isArray(object.data)) {
  457. array = object.data
  458. length = checked(array.length) | 0
  459. }
  460. that = allocate(that, length)
  461. for (var i = 0; i < length; i += 1) {
  462. that[i] = array[i] & 255
  463. }
  464. return that
  465. }
  466. if (Buffer.TYPED_ARRAY_SUPPORT) {
  467. Buffer.prototype.__proto__ = Uint8Array.prototype
  468. Buffer.__proto__ = Uint8Array
  469. }
  470. function allocate (that, length) {
  471. if (Buffer.TYPED_ARRAY_SUPPORT) {
  472. // Return an augmented `Uint8Array` instance, for best performance
  473. that = Buffer._augment(new Uint8Array(length))
  474. that.__proto__ = Buffer.prototype
  475. } else {
  476. // Fallback: Return an object instance of the Buffer class
  477. that.length = length
  478. that._isBuffer = true
  479. }
  480. var fromPool = length !== 0 && length <= Buffer.poolSize >>> 1
  481. if (fromPool) that.parent = rootParent
  482. return that
  483. }
  484. function checked (length) {
  485. // Note: cannot use `length < kMaxLength` here because that fails when
  486. // length is NaN (which is otherwise coerced to zero.)
  487. if (length >= kMaxLength()) {
  488. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  489. 'size: 0x' + kMaxLength().toString(16) + ' bytes')
  490. }
  491. return length | 0
  492. }
  493. function SlowBuffer (subject, encoding) {
  494. if (!(this instanceof SlowBuffer)) return new SlowBuffer(subject, encoding)
  495. var buf = new Buffer(subject, encoding)
  496. delete buf.parent
  497. return buf
  498. }
  499. Buffer.isBuffer = function isBuffer (b) {
  500. return !!(b != null && b._isBuffer)
  501. }
  502. Buffer.compare = function compare (a, b) {
  503. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  504. throw new TypeError('Arguments must be Buffers')
  505. }
  506. if (a === b) return 0
  507. var x = a.length
  508. var y = b.length
  509. var i = 0
  510. var len = Math.min(x, y)
  511. while (i < len) {
  512. if (a[i] !== b[i]) break
  513. ++i
  514. }
  515. if (i !== len) {
  516. x = a[i]
  517. y = b[i]
  518. }
  519. if (x < y) return -1
  520. if (y < x) return 1
  521. return 0
  522. }
  523. Buffer.isEncoding = function isEncoding (encoding) {
  524. switch (String(encoding).toLowerCase()) {
  525. case 'hex':
  526. case 'utf8':
  527. case 'utf-8':
  528. case 'ascii':
  529. case 'binary':
  530. case 'base64':
  531. case 'raw':
  532. case 'ucs2':
  533. case 'ucs-2':
  534. case 'utf16le':
  535. case 'utf-16le':
  536. return true
  537. default:
  538. return false
  539. }
  540. }
  541. Buffer.concat = function concat (list, length) {
  542. if (!isArray(list)) throw new TypeError('list argument must be an Array of Buffers.')
  543. if (list.length === 0) {
  544. return new Buffer(0)
  545. }
  546. var i
  547. if (length === undefined) {
  548. length = 0
  549. for (i = 0; i < list.length; i++) {
  550. length += list[i].length
  551. }
  552. }
  553. var buf = new Buffer(length)
  554. var pos = 0
  555. for (i = 0; i < list.length; i++) {
  556. var item = list[i]
  557. item.copy(buf, pos)
  558. pos += item.length
  559. }
  560. return buf
  561. }
  562. function byteLength (string, encoding) {
  563. if (typeof string !== 'string') string = '' + string
  564. var len = string.length
  565. if (len === 0) return 0
  566. // Use a for loop to avoid recursion
  567. var loweredCase = false
  568. for (;;) {
  569. switch (encoding) {
  570. case 'ascii':
  571. case 'binary':
  572. // Deprecated
  573. case 'raw':
  574. case 'raws':
  575. return len
  576. case 'utf8':
  577. case 'utf-8':
  578. return utf8ToBytes(string).length
  579. case 'ucs2':
  580. case 'ucs-2':
  581. case 'utf16le':
  582. case 'utf-16le':
  583. return len * 2
  584. case 'hex':
  585. return len >>> 1
  586. case 'base64':
  587. return base64ToBytes(string).length
  588. default:
  589. if (loweredCase) return utf8ToBytes(string).length // assume utf8
  590. encoding = ('' + encoding).toLowerCase()
  591. loweredCase = true
  592. }
  593. }
  594. }
  595. Buffer.byteLength = byteLength
  596. // pre-set for values that may exist in the future
  597. Buffer.prototype.length = undefined
  598. Buffer.prototype.parent = undefined
  599. function slowToString (encoding, start, end) {
  600. var loweredCase = false
  601. start = start | 0
  602. end = end === undefined || end === Infinity ? this.length : end | 0
  603. if (!encoding) encoding = 'utf8'
  604. if (start < 0) start = 0
  605. if (end > this.length) end = this.length
  606. if (end <= start) return ''
  607. while (true) {
  608. switch (encoding) {
  609. case 'hex':
  610. return hexSlice(this, start, end)
  611. case 'utf8':
  612. case 'utf-8':
  613. return utf8Slice(this, start, end)
  614. case 'ascii':
  615. return asciiSlice(this, start, end)
  616. case 'binary':
  617. return binarySlice(this, start, end)
  618. case 'base64':
  619. return base64Slice(this, start, end)
  620. case 'ucs2':
  621. case 'ucs-2':
  622. case 'utf16le':
  623. case 'utf-16le':
  624. return utf16leSlice(this, start, end)
  625. default:
  626. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  627. encoding = (encoding + '').toLowerCase()
  628. loweredCase = true
  629. }
  630. }
  631. }
  632. Buffer.prototype.toString = function toString () {
  633. var length = this.length | 0
  634. if (length === 0) return ''
  635. if (arguments.length === 0) return utf8Slice(this, 0, length)
  636. return slowToString.apply(this, arguments)
  637. }
  638. Buffer.prototype.equals = function equals (b) {
  639. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  640. if (this === b) return true
  641. return Buffer.compare(this, b) === 0
  642. }
  643. Buffer.prototype.inspect = function inspect () {
  644. var str = ''
  645. var max = exports.INSPECT_MAX_BYTES
  646. if (this.length > 0) {
  647. str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
  648. if (this.length > max) str += ' ... '
  649. }
  650. return '<Buffer ' + str + '>'
  651. }
  652. Buffer.prototype.compare = function compare (b) {
  653. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  654. if (this === b) return 0
  655. return Buffer.compare(this, b)
  656. }
  657. Buffer.prototype.indexOf = function indexOf (val, byteOffset) {
  658. if (byteOffset > 0x7fffffff) byteOffset = 0x7fffffff
  659. else if (byteOffset < -0x80000000) byteOffset = -0x80000000
  660. byteOffset >>= 0
  661. if (this.length === 0) return -1
  662. if (byteOffset >= this.length) return -1
  663. // Negative offsets start from the end of the buffer
  664. if (byteOffset < 0) byteOffset = Math.max(this.length + byteOffset, 0)
  665. if (typeof val === 'string') {
  666. if (val.length === 0) return -1 // special case: looking for empty string always fails
  667. return String.prototype.indexOf.call(this, val, byteOffset)
  668. }
  669. if (Buffer.isBuffer(val)) {
  670. return arrayIndexOf(this, val, byteOffset)
  671. }
  672. if (typeof val === 'number') {
  673. if (Buffer.TYPED_ARRAY_SUPPORT && Uint8Array.prototype.indexOf === 'function') {
  674. return Uint8Array.prototype.indexOf.call(this, val, byteOffset)
  675. }
  676. return arrayIndexOf(this, [ val ], byteOffset)
  677. }
  678. function arrayIndexOf (arr, val, byteOffset) {
  679. var foundIndex = -1
  680. for (var i = 0; byteOffset + i < arr.length; i++) {
  681. if (arr[byteOffset + i] === val[foundIndex === -1 ? 0 : i - foundIndex]) {
  682. if (foundIndex === -1) foundIndex = i
  683. if (i - foundIndex + 1 === val.length) return byteOffset + foundIndex
  684. } else {
  685. foundIndex = -1
  686. }
  687. }
  688. return -1
  689. }
  690. throw new TypeError('val must be string, number or Buffer')
  691. }
  692. // `get` is deprecated
  693. Buffer.prototype.get = function get (offset) {
  694. console.log('.get() is deprecated. Access using array indexes instead.')
  695. return this.readUInt8(offset)
  696. }
  697. // `set` is deprecated
  698. Buffer.prototype.set = function set (v, offset) {
  699. console.log('.set() is deprecated. Access using array indexes instead.')
  700. return this.writeUInt8(v, offset)
  701. }
  702. function hexWrite (buf, string, offset, length) {
  703. offset = Number(offset) || 0
  704. var remaining = buf.length - offset
  705. if (!length) {
  706. length = remaining
  707. } else {
  708. length = Number(length)
  709. if (length > remaining) {
  710. length = remaining
  711. }
  712. }
  713. // must be an even number of digits
  714. var strLen = string.length
  715. if (strLen % 2 !== 0) throw new Error('Invalid hex string')
  716. if (length > strLen / 2) {
  717. length = strLen / 2
  718. }
  719. for (var i = 0; i < length; i++) {
  720. var parsed = parseInt(string.substr(i * 2, 2), 16)
  721. if (isNaN(parsed)) throw new Error('Invalid hex string')
  722. buf[offset + i] = parsed
  723. }
  724. return i
  725. }
  726. function utf8Write (buf, string, offset, length) {
  727. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  728. }
  729. function asciiWrite (buf, string, offset, length) {
  730. return blitBuffer(asciiToBytes(string), buf, offset, length)
  731. }
  732. function binaryWrite (buf, string, offset, length) {
  733. return asciiWrite(buf, string, offset, length)
  734. }
  735. function base64Write (buf, string, offset, length) {
  736. return blitBuffer(base64ToBytes(string), buf, offset, length)
  737. }
  738. function ucs2Write (buf, string, offset, length) {
  739. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  740. }
  741. Buffer.prototype.write = function write (string, offset, length, encoding) {
  742. // Buffer#write(string)
  743. if (offset === undefined) {
  744. encoding = 'utf8'
  745. length = this.length
  746. offset = 0
  747. // Buffer#write(string, encoding)
  748. } else if (length === undefined && typeof offset === 'string') {
  749. encoding = offset
  750. length = this.length
  751. offset = 0
  752. // Buffer#write(string, offset[, length][, encoding])
  753. } else if (isFinite(offset)) {
  754. offset = offset | 0
  755. if (isFinite(length)) {
  756. length = length | 0
  757. if (encoding === undefined) encoding = 'utf8'
  758. } else {
  759. encoding = length
  760. length = undefined
  761. }
  762. // legacy write(string, encoding, offset, length) - remove in v0.13
  763. } else {
  764. var swap = encoding
  765. encoding = offset
  766. offset = length | 0
  767. length = swap
  768. }
  769. var remaining = this.length - offset
  770. if (length === undefined || length > remaining) length = remaining
  771. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  772. throw new RangeError('attempt to write outside buffer bounds')
  773. }
  774. if (!encoding) encoding = 'utf8'
  775. var loweredCase = false
  776. for (;;) {
  777. switch (encoding) {
  778. case 'hex':
  779. return hexWrite(this, string, offset, length)
  780. case 'utf8':
  781. case 'utf-8':
  782. return utf8Write(this, string, offset, length)
  783. case 'ascii':
  784. return asciiWrite(this, string, offset, length)
  785. case 'binary':
  786. return binaryWrite(this, string, offset, length)
  787. case 'base64':
  788. // Warning: maxLength not taken into account in base64Write
  789. return base64Write(this, string, offset, length)
  790. case 'ucs2':
  791. case 'ucs-2':
  792. case 'utf16le':
  793. case 'utf-16le':
  794. return ucs2Write(this, string, offset, length)
  795. default:
  796. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  797. encoding = ('' + encoding).toLowerCase()
  798. loweredCase = true
  799. }
  800. }
  801. }
  802. Buffer.prototype.toJSON = function toJSON () {
  803. return {
  804. type: 'Buffer',
  805. data: Array.prototype.slice.call(this._arr || this, 0)
  806. }
  807. }
  808. function base64Slice (buf, start, end) {
  809. if (start === 0 && end === buf.length) {
  810. return base64.fromByteArray(buf)
  811. } else {
  812. return base64.fromByteArray(buf.slice(start, end))
  813. }
  814. }
  815. function utf8Slice (buf, start, end) {
  816. end = Math.min(buf.length, end)
  817. var res = []
  818. var i = start
  819. while (i < end) {
  820. var firstByte = buf[i]
  821. var codePoint = null
  822. var bytesPerSequence = (firstByte > 0xEF) ? 4
  823. : (firstByte > 0xDF) ? 3
  824. : (firstByte > 0xBF) ? 2
  825. : 1
  826. if (i + bytesPerSequence <= end) {
  827. var secondByte, thirdByte, fourthByte, tempCodePoint
  828. switch (bytesPerSequence) {
  829. case 1:
  830. if (firstByte < 0x80) {
  831. codePoint = firstByte
  832. }
  833. break
  834. case 2:
  835. secondByte = buf[i + 1]
  836. if ((secondByte & 0xC0) === 0x80) {
  837. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  838. if (tempCodePoint > 0x7F) {
  839. codePoint = tempCodePoint
  840. }
  841. }
  842. break
  843. case 3:
  844. secondByte = buf[i + 1]
  845. thirdByte = buf[i + 2]
  846. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  847. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  848. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  849. codePoint = tempCodePoint
  850. }
  851. }
  852. break
  853. case 4:
  854. secondByte = buf[i + 1]
  855. thirdByte = buf[i + 2]
  856. fourthByte = buf[i + 3]
  857. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  858. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  859. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  860. codePoint = tempCodePoint
  861. }
  862. }
  863. }
  864. }
  865. if (codePoint === null) {
  866. // we did not generate a valid codePoint so insert a
  867. // replacement char (U+FFFD) and advance only 1 byte
  868. codePoint = 0xFFFD
  869. bytesPerSequence = 1
  870. } else if (codePoint > 0xFFFF) {
  871. // encode to utf16 (surrogate pair dance)
  872. codePoint -= 0x10000
  873. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  874. codePoint = 0xDC00 | codePoint & 0x3FF
  875. }
  876. res.push(codePoint)
  877. i += bytesPerSequence
  878. }
  879. return decodeCodePointsArray(res)
  880. }
  881. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  882. // the lowest limit is Chrome, with 0x10000 args.
  883. // We go 1 magnitude less, for safety
  884. var MAX_ARGUMENTS_LENGTH = 0x1000
  885. function decodeCodePointsArray (codePoints) {
  886. var len = codePoints.length
  887. if (len <= MAX_ARGUMENTS_LENGTH) {
  888. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  889. }
  890. // Decode in chunks to avoid "call stack size exceeded".
  891. var res = ''
  892. var i = 0
  893. while (i < len) {
  894. res += String.fromCharCode.apply(
  895. String,
  896. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  897. )
  898. }
  899. return res
  900. }
  901. function asciiSlice (buf, start, end) {
  902. var ret = ''
  903. end = Math.min(buf.length, end)
  904. for (var i = start; i < end; i++) {
  905. ret += String.fromCharCode(buf[i] & 0x7F)
  906. }
  907. return ret
  908. }
  909. function binarySlice (buf, start, end) {
  910. var ret = ''
  911. end = Math.min(buf.length, end)
  912. for (var i = start; i < end; i++) {
  913. ret += String.fromCharCode(buf[i])
  914. }
  915. return ret
  916. }
  917. function hexSlice (buf, start, end) {
  918. var len = buf.length
  919. if (!start || start < 0) start = 0
  920. if (!end || end < 0 || end > len) end = len
  921. var out = ''
  922. for (var i = start; i < end; i++) {
  923. out += toHex(buf[i])
  924. }
  925. return out
  926. }
  927. function utf16leSlice (buf, start, end) {
  928. var bytes = buf.slice(start, end)
  929. var res = ''
  930. for (var i = 0; i < bytes.length; i += 2) {
  931. res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
  932. }
  933. return res
  934. }
  935. Buffer.prototype.slice = function slice (start, end) {
  936. var len = this.length
  937. start = ~~start
  938. end = end === undefined ? len : ~~end
  939. if (start < 0) {
  940. start += len
  941. if (start < 0) start = 0
  942. } else if (start > len) {
  943. start = len
  944. }
  945. if (end < 0) {
  946. end += len
  947. if (end < 0) end = 0
  948. } else if (end > len) {
  949. end = len
  950. }
  951. if (end < start) end = start
  952. var newBuf
  953. if (Buffer.TYPED_ARRAY_SUPPORT) {
  954. newBuf = Buffer._augment(this.subarray(start, end))
  955. } else {
  956. var sliceLen = end - start
  957. newBuf = new Buffer(sliceLen, undefined)
  958. for (var i = 0; i < sliceLen; i++) {
  959. newBuf[i] = this[i + start]
  960. }
  961. }
  962. if (newBuf.length) newBuf.parent = this.parent || this
  963. return newBuf
  964. }
  965. /*
  966. * Need to make sure that buffer isn't trying to write out of bounds.
  967. */
  968. function checkOffset (offset, ext, length) {
  969. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  970. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  971. }
  972. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  973. offset = offset | 0
  974. byteLength = byteLength | 0
  975. if (!noAssert) checkOffset(offset, byteLength, this.length)
  976. var val = this[offset]
  977. var mul = 1
  978. var i = 0
  979. while (++i < byteLength && (mul *= 0x100)) {
  980. val += this[offset + i] * mul
  981. }
  982. return val
  983. }
  984. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  985. offset = offset | 0
  986. byteLength = byteLength | 0
  987. if (!noAssert) {
  988. checkOffset(offset, byteLength, this.length)
  989. }
  990. var val = this[offset + --byteLength]
  991. var mul = 1
  992. while (byteLength > 0 && (mul *= 0x100)) {
  993. val += this[offset + --byteLength] * mul
  994. }
  995. return val
  996. }
  997. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  998. if (!noAssert) checkOffset(offset, 1, this.length)
  999. return this[offset]
  1000. }
  1001. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  1002. if (!noAssert) checkOffset(offset, 2, this.length)
  1003. return this[offset] | (this[offset + 1] << 8)
  1004. }
  1005. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  1006. if (!noAssert) checkOffset(offset, 2, this.length)
  1007. return (this[offset] << 8) | this[offset + 1]
  1008. }
  1009. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  1010. if (!noAssert) checkOffset(offset, 4, this.length)
  1011. return ((this[offset]) |
  1012. (this[offset + 1] << 8) |
  1013. (this[offset + 2] << 16)) +
  1014. (this[offset + 3] * 0x1000000)
  1015. }
  1016. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  1017. if (!noAssert) checkOffset(offset, 4, this.length)
  1018. return (this[offset] * 0x1000000) +
  1019. ((this[offset + 1] << 16) |
  1020. (this[offset + 2] << 8) |
  1021. this[offset + 3])
  1022. }
  1023. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  1024. offset = offset | 0
  1025. byteLength = byteLength | 0
  1026. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1027. var val = this[offset]
  1028. var mul = 1
  1029. var i = 0
  1030. while (++i < byteLength && (mul *= 0x100)) {
  1031. val += this[offset + i] * mul
  1032. }
  1033. mul *= 0x80
  1034. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1035. return val
  1036. }
  1037. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  1038. offset = offset | 0
  1039. byteLength = byteLength | 0
  1040. if (!noAssert) checkOffset(offset, byteLength, this.length)
  1041. var i = byteLength
  1042. var mul = 1
  1043. var val = this[offset + --i]
  1044. while (i > 0 && (mul *= 0x100)) {
  1045. val += this[offset + --i] * mul
  1046. }
  1047. mul *= 0x80
  1048. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  1049. return val
  1050. }
  1051. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  1052. if (!noAssert) checkOffset(offset, 1, this.length)
  1053. if (!(this[offset] & 0x80)) return (this[offset])
  1054. return ((0xff - this[offset] + 1) * -1)
  1055. }
  1056. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  1057. if (!noAssert) checkOffset(offset, 2, this.length)
  1058. var val = this[offset] | (this[offset + 1] << 8)
  1059. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1060. }
  1061. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  1062. if (!noAssert) checkOffset(offset, 2, this.length)
  1063. var val = this[offset + 1] | (this[offset] << 8)
  1064. return (val & 0x8000) ? val | 0xFFFF0000 : val
  1065. }
  1066. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  1067. if (!noAssert) checkOffset(offset, 4, this.length)
  1068. return (this[offset]) |
  1069. (this[offset + 1] << 8) |
  1070. (this[offset + 2] << 16) |
  1071. (this[offset + 3] << 24)
  1072. }
  1073. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  1074. if (!noAssert) checkOffset(offset, 4, this.length)
  1075. return (this[offset] << 24) |
  1076. (this[offset + 1] << 16) |
  1077. (this[offset + 2] << 8) |
  1078. (this[offset + 3])
  1079. }
  1080. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  1081. if (!noAssert) checkOffset(offset, 4, this.length)
  1082. return ieee754.read(this, offset, true, 23, 4)
  1083. }
  1084. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  1085. if (!noAssert) checkOffset(offset, 4, this.length)
  1086. return ieee754.read(this, offset, false, 23, 4)
  1087. }
  1088. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  1089. if (!noAssert) checkOffset(offset, 8, this.length)
  1090. return ieee754.read(this, offset, true, 52, 8)
  1091. }
  1092. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  1093. if (!noAssert) checkOffset(offset, 8, this.length)
  1094. return ieee754.read(this, offset, false, 52, 8)
  1095. }
  1096. function checkInt (buf, value, offset, ext, max, min) {
  1097. if (!Buffer.isBuffer(buf)) throw new TypeError('buffer must be a Buffer instance')
  1098. if (value > max || value < min) throw new RangeError('value is out of bounds')
  1099. if (offset + ext > buf.length) throw new RangeError('index out of range')
  1100. }
  1101. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  1102. value = +value
  1103. offset = offset | 0
  1104. byteLength = byteLength | 0
  1105. if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  1106. var mul = 1
  1107. var i = 0
  1108. this[offset] = value & 0xFF
  1109. while (++i < byteLength && (mul *= 0x100)) {
  1110. this[offset + i] = (value / mul) & 0xFF
  1111. }
  1112. return offset + byteLength
  1113. }
  1114. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  1115. value = +value
  1116. offset = offset | 0
  1117. byteLength = byteLength | 0
  1118. if (!noAssert) checkInt(this, value, offset, byteLength, Math.pow(2, 8 * byteLength), 0)
  1119. var i = byteLength - 1
  1120. var mul = 1
  1121. this[offset + i] = value & 0xFF
  1122. while (--i >= 0 && (mul *= 0x100)) {
  1123. this[offset + i] = (value / mul) & 0xFF
  1124. }
  1125. return offset + byteLength
  1126. }
  1127. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  1128. value = +value
  1129. offset = offset | 0
  1130. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  1131. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1132. this[offset] = (value & 0xff)
  1133. return offset + 1
  1134. }
  1135. function objectWriteUInt16 (buf, value, offset, littleEndian) {
  1136. if (value < 0) value = 0xffff + value + 1
  1137. for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; i++) {
  1138. buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
  1139. (littleEndian ? i : 1 - i) * 8
  1140. }
  1141. }
  1142. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  1143. value = +value
  1144. offset = offset | 0
  1145. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1146. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1147. this[offset] = (value & 0xff)
  1148. this[offset + 1] = (value >>> 8)
  1149. } else {
  1150. objectWriteUInt16(this, value, offset, true)
  1151. }
  1152. return offset + 2
  1153. }
  1154. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  1155. value = +value
  1156. offset = offset | 0
  1157. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  1158. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1159. this[offset] = (value >>> 8)
  1160. this[offset + 1] = (value & 0xff)
  1161. } else {
  1162. objectWriteUInt16(this, value, offset, false)
  1163. }
  1164. return offset + 2
  1165. }
  1166. function objectWriteUInt32 (buf, value, offset, littleEndian) {
  1167. if (value < 0) value = 0xffffffff + value + 1
  1168. for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; i++) {
  1169. buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
  1170. }
  1171. }
  1172. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  1173. value = +value
  1174. offset = offset | 0
  1175. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1176. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1177. this[offset + 3] = (value >>> 24)
  1178. this[offset + 2] = (value >>> 16)
  1179. this[offset + 1] = (value >>> 8)
  1180. this[offset] = (value & 0xff)
  1181. } else {
  1182. objectWriteUInt32(this, value, offset, true)
  1183. }
  1184. return offset + 4
  1185. }
  1186. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  1187. value = +value
  1188. offset = offset | 0
  1189. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  1190. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1191. this[offset] = (value >>> 24)
  1192. this[offset + 1] = (value >>> 16)
  1193. this[offset + 2] = (value >>> 8)
  1194. this[offset + 3] = (value & 0xff)
  1195. } else {
  1196. objectWriteUInt32(this, value, offset, false)
  1197. }
  1198. return offset + 4
  1199. }
  1200. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  1201. value = +value
  1202. offset = offset | 0
  1203. if (!noAssert) {
  1204. var limit = Math.pow(2, 8 * byteLength - 1)
  1205. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1206. }
  1207. var i = 0
  1208. var mul = 1
  1209. var sub = value < 0 ? 1 : 0
  1210. this[offset] = value & 0xFF
  1211. while (++i < byteLength && (mul *= 0x100)) {
  1212. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1213. }
  1214. return offset + byteLength
  1215. }
  1216. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  1217. value = +value
  1218. offset = offset | 0
  1219. if (!noAssert) {
  1220. var limit = Math.pow(2, 8 * byteLength - 1)
  1221. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  1222. }
  1223. var i = byteLength - 1
  1224. var mul = 1
  1225. var sub = value < 0 ? 1 : 0
  1226. this[offset + i] = value & 0xFF
  1227. while (--i >= 0 && (mul *= 0x100)) {
  1228. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  1229. }
  1230. return offset + byteLength
  1231. }
  1232. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  1233. value = +value
  1234. offset = offset | 0
  1235. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  1236. if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
  1237. if (value < 0) value = 0xff + value + 1
  1238. this[offset] = (value & 0xff)
  1239. return offset + 1
  1240. }
  1241. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  1242. value = +value
  1243. offset = offset | 0
  1244. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1245. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1246. this[offset] = (value & 0xff)
  1247. this[offset + 1] = (value >>> 8)
  1248. } else {
  1249. objectWriteUInt16(this, value, offset, true)
  1250. }
  1251. return offset + 2
  1252. }
  1253. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  1254. value = +value
  1255. offset = offset | 0
  1256. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  1257. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1258. this[offset] = (value >>> 8)
  1259. this[offset + 1] = (value & 0xff)
  1260. } else {
  1261. objectWriteUInt16(this, value, offset, false)
  1262. }
  1263. return offset + 2
  1264. }
  1265. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  1266. value = +value
  1267. offset = offset | 0
  1268. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1269. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1270. this[offset] = (value & 0xff)
  1271. this[offset + 1] = (value >>> 8)
  1272. this[offset + 2] = (value >>> 16)
  1273. this[offset + 3] = (value >>> 24)
  1274. } else {
  1275. objectWriteUInt32(this, value, offset, true)
  1276. }
  1277. return offset + 4
  1278. }
  1279. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  1280. value = +value
  1281. offset = offset | 0
  1282. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  1283. if (value < 0) value = 0xffffffff + value + 1
  1284. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1285. this[offset] = (value >>> 24)
  1286. this[offset + 1] = (value >>> 16)
  1287. this[offset + 2] = (value >>> 8)
  1288. this[offset + 3] = (value & 0xff)
  1289. } else {
  1290. objectWriteUInt32(this, value, offset, false)
  1291. }
  1292. return offset + 4
  1293. }
  1294. function checkIEEE754 (buf, value, offset, ext, max, min) {
  1295. if (value > max || value < min) throw new RangeError('value is out of bounds')
  1296. if (offset + ext > buf.length) throw new RangeError('index out of range')
  1297. if (offset < 0) throw new RangeError('index out of range')
  1298. }
  1299. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  1300. if (!noAssert) {
  1301. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  1302. }
  1303. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  1304. return offset + 4
  1305. }
  1306. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  1307. return writeFloat(this, value, offset, true, noAssert)
  1308. }
  1309. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  1310. return writeFloat(this, value, offset, false, noAssert)
  1311. }
  1312. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  1313. if (!noAssert) {
  1314. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  1315. }
  1316. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  1317. return offset + 8
  1318. }
  1319. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  1320. return writeDouble(this, value, offset, true, noAssert)
  1321. }
  1322. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  1323. return writeDouble(this, value, offset, false, noAssert)
  1324. }
  1325. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  1326. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  1327. if (!start) start = 0
  1328. if (!end && end !== 0) end = this.length
  1329. if (targetStart >= target.length) targetStart = target.length
  1330. if (!targetStart) targetStart = 0
  1331. if (end > 0 && end < start) end = start
  1332. // Copy 0 bytes; we're done
  1333. if (end === start) return 0
  1334. if (target.length === 0 || this.length === 0) return 0
  1335. // Fatal error conditions
  1336. if (targetStart < 0) {
  1337. throw new RangeError('targetStart out of bounds')
  1338. }
  1339. if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
  1340. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  1341. // Are we oob?
  1342. if (end > this.length) end = this.length
  1343. if (target.length - targetStart < end - start) {
  1344. end = target.length - targetStart + start
  1345. }
  1346. var len = end - start
  1347. var i
  1348. if (this === target && start < targetStart && targetStart < end) {
  1349. // descending copy from end
  1350. for (i = len - 1; i >= 0; i--) {
  1351. target[i + targetStart] = this[i + start]
  1352. }
  1353. } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
  1354. // ascending copy from start
  1355. for (i = 0; i < len; i++) {
  1356. target[i + targetStart] = this[i + start]
  1357. }
  1358. } else {
  1359. target._set(this.subarray(start, start + len), targetStart)
  1360. }
  1361. return len
  1362. }
  1363. // fill(value, start=0, end=buffer.length)
  1364. Buffer.prototype.fill = function fill (value, start, end) {
  1365. if (!value) value = 0
  1366. if (!start) start = 0
  1367. if (!end) end = this.length
  1368. if (end < start) throw new RangeError('end < start')
  1369. // Fill 0 bytes; we're done
  1370. if (end === start) return
  1371. if (this.length === 0) return
  1372. if (start < 0 || start >= this.length) throw new RangeError('start out of bounds')
  1373. if (end < 0 || end > this.length) throw new RangeError('end out of bounds')
  1374. var i
  1375. if (typeof value === 'number') {
  1376. for (i = start; i < end; i++) {
  1377. this[i] = value
  1378. }
  1379. } else {
  1380. var bytes = utf8ToBytes(value.toString())
  1381. var len = bytes.length
  1382. for (i = start; i < end; i++) {
  1383. this[i] = bytes[i % len]
  1384. }
  1385. }
  1386. return this
  1387. }
  1388. /**
  1389. * Creates a new `ArrayBuffer` with the *copied* memory of the buffer instance.
  1390. * Added in Node 0.12. Only available in browsers that support ArrayBuffer.
  1391. */
  1392. Buffer.prototype.toArrayBuffer = function toArrayBuffer () {
  1393. if (typeof Uint8Array !== 'undefined') {
  1394. if (Buffer.TYPED_ARRAY_SUPPORT) {
  1395. return (new Buffer(this)).buffer
  1396. } else {
  1397. var buf = new Uint8Array(this.length)
  1398. for (var i = 0, len = buf.length; i < len; i += 1) {
  1399. buf[i] = this[i]
  1400. }
  1401. return buf.buffer
  1402. }
  1403. } else {
  1404. throw new TypeError('Buffer.toArrayBuffer not supported in this browser')
  1405. }
  1406. }
  1407. // HELPER FUNCTIONS
  1408. // ================
  1409. var BP = Buffer.prototype
  1410. /**
  1411. * Augment a Uint8Array *instance* (not the Uint8Array class!) with Buffer methods
  1412. */
  1413. Buffer._augment = function _augment (arr) {
  1414. arr.constructor = Buffer
  1415. arr._isBuffer = true
  1416. // save reference to original Uint8Array set method before overwriting
  1417. arr._set = arr.set
  1418. // deprecated
  1419. arr.get = BP.get
  1420. arr.set = BP.set
  1421. arr.write = BP.write
  1422. arr.toString = BP.toString
  1423. arr.toLocaleString = BP.toString
  1424. arr.toJSON = BP.toJSON
  1425. arr.equals = BP.equals
  1426. arr.compare = BP.compare
  1427. arr.indexOf = BP.indexOf
  1428. arr.copy = BP.copy
  1429. arr.slice = BP.slice
  1430. arr.readUIntLE = BP.readUIntLE
  1431. arr.readUIntBE = BP.readUIntBE
  1432. arr.readUInt8 = BP.readUInt8
  1433. arr.readUInt16LE = BP.readUInt16LE
  1434. arr.readUInt16BE = BP.readUInt16BE
  1435. arr.readUInt32LE = BP.readUInt32LE
  1436. arr.readUInt32BE = BP.readUInt32BE
  1437. arr.readIntLE = BP.readIntLE
  1438. arr.readIntBE = BP.readIntBE
  1439. arr.readInt8 = BP.readInt8
  1440. arr.readInt16LE = BP.readInt16LE
  1441. arr.readInt16BE = BP.readInt16BE
  1442. arr.readInt32LE = BP.readInt32LE
  1443. arr.readInt32BE = BP.readInt32BE
  1444. arr.readFloatLE = BP.readFloatLE
  1445. arr.readFloatBE = BP.readFloatBE
  1446. arr.readDoubleLE = BP.readDoubleLE
  1447. arr.readDoubleBE = BP.readDoubleBE
  1448. arr.writeUInt8 = BP.writeUInt8
  1449. arr.writeUIntLE = BP.writeUIntLE
  1450. arr.writeUIntBE = BP.writeUIntBE
  1451. arr.writeUInt16LE = BP.writeUInt16LE
  1452. arr.writeUInt16BE = BP.writeUInt16BE
  1453. arr.writeUInt32LE = BP.writeUInt32LE
  1454. arr.writeUInt32BE = BP.writeUInt32BE
  1455. arr.writeIntLE = BP.writeIntLE
  1456. arr.writeIntBE = BP.writeIntBE
  1457. arr.writeInt8 = BP.writeInt8
  1458. arr.writeInt16LE = BP.writeInt16LE
  1459. arr.writeInt16BE = BP.writeInt16BE
  1460. arr.writeInt32LE = BP.writeInt32LE
  1461. arr.writeInt32BE = BP.writeInt32BE
  1462. arr.writeFloatLE = BP.writeFloatLE
  1463. arr.writeFloatBE = BP.writeFloatBE
  1464. arr.writeDoubleLE = BP.writeDoubleLE
  1465. arr.writeDoubleBE = BP.writeDoubleBE
  1466. arr.fill = BP.fill
  1467. arr.inspect = BP.inspect
  1468. arr.toArrayBuffer = BP.toArrayBuffer
  1469. return arr
  1470. }
  1471. var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
  1472. function base64clean (str) {
  1473. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  1474. str = stringtrim(str).replace(INVALID_BASE64_RE, '')
  1475. // Node converts strings with length < 2 to ''
  1476. if (str.length < 2) return ''
  1477. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  1478. while (str.length % 4 !== 0) {
  1479. str = str + '='
  1480. }
  1481. return str
  1482. }
  1483. function stringtrim (str) {
  1484. if (str.trim) return str.trim()
  1485. return str.replace(/^\s+|\s+$/g, '')
  1486. }
  1487. function toHex (n) {
  1488. if (n < 16) return '0' + n.toString(16)
  1489. return n.toString(16)
  1490. }
  1491. function utf8ToBytes (string, units) {
  1492. units = units || Infinity
  1493. var codePoint
  1494. var length = string.length
  1495. var leadSurrogate = null
  1496. var bytes = []
  1497. for (var i = 0; i < length; i++) {
  1498. codePoint = string.charCodeAt(i)
  1499. // is surrogate component
  1500. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  1501. // last char was a lead
  1502. if (!leadSurrogate) {
  1503. // no lead yet
  1504. if (codePoint > 0xDBFF) {
  1505. // unexpected trail
  1506. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1507. continue
  1508. } else if (i + 1 === length) {
  1509. // unpaired lead
  1510. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1511. continue
  1512. }
  1513. // valid lead
  1514. leadSurrogate = codePoint
  1515. continue
  1516. }
  1517. // 2 leads in a row
  1518. if (codePoint < 0xDC00) {
  1519. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1520. leadSurrogate = codePoint
  1521. continue
  1522. }
  1523. // valid surrogate pair
  1524. codePoint = leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00 | 0x10000
  1525. } else if (leadSurrogate) {
  1526. // valid bmp char, but last char was a lead
  1527. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  1528. }
  1529. leadSurrogate = null
  1530. // encode utf8
  1531. if (codePoint < 0x80) {
  1532. if ((units -= 1) < 0) break
  1533. bytes.push(codePoint)
  1534. } else if (codePoint < 0x800) {
  1535. if ((units -= 2) < 0) break
  1536. bytes.push(
  1537. codePoint >> 0x6 | 0xC0,
  1538. codePoint & 0x3F | 0x80
  1539. )
  1540. } else if (codePoint < 0x10000) {
  1541. if ((units -= 3) < 0) break
  1542. bytes.push(
  1543. codePoint >> 0xC | 0xE0,
  1544. codePoint >> 0x6 & 0x3F | 0x80,
  1545. codePoint & 0x3F | 0x80
  1546. )
  1547. } else if (codePoint < 0x110000) {
  1548. if ((units -= 4) < 0) break
  1549. bytes.push(
  1550. codePoint >> 0x12 | 0xF0,
  1551. codePoint >> 0xC & 0x3F | 0x80,
  1552. codePoint >> 0x6 & 0x3F | 0x80,
  1553. codePoint & 0x3F | 0x80
  1554. )
  1555. } else {
  1556. throw new Error('Invalid code point')
  1557. }
  1558. }
  1559. return bytes
  1560. }
  1561. function asciiToBytes (str) {
  1562. var byteArray = []
  1563. for (var i = 0; i < str.length; i++) {
  1564. // Node's code seems to be doing this and not & 0x7F..
  1565. byteArray.push(str.charCodeAt(i) & 0xFF)
  1566. }
  1567. return byteArray
  1568. }
  1569. function utf16leToBytes (str, units) {
  1570. var c, hi, lo
  1571. var byteArray = []
  1572. for (var i = 0; i < str.length; i++) {
  1573. if ((units -= 2) < 0) break
  1574. c = str.charCodeAt(i)
  1575. hi = c >> 8
  1576. lo = c % 256
  1577. byteArray.push(lo)
  1578. byteArray.push(hi)
  1579. }
  1580. return byteArray
  1581. }
  1582. function base64ToBytes (str) {
  1583. return base64.toByteArray(base64clean(str))
  1584. }
  1585. function blitBuffer (src, dst, offset, length) {
  1586. for (var i = 0; i < length; i++) {
  1587. if ((i + offset >= dst.length) || (i >= src.length)) break
  1588. dst[i + offset] = src[i]
  1589. }
  1590. return i
  1591. }
  1592. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1593. },{"base64-js":2,"ieee754":4,"is-array":5}],4:[function(require,module,exports){
  1594. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  1595. var e, m
  1596. var eLen = nBytes * 8 - mLen - 1
  1597. var eMax = (1 << eLen) - 1
  1598. var eBias = eMax >> 1
  1599. var nBits = -7
  1600. var i = isLE ? (nBytes - 1) : 0
  1601. var d = isLE ? -1 : 1
  1602. var s = buffer[offset + i]
  1603. i += d
  1604. e = s & ((1 << (-nBits)) - 1)
  1605. s >>= (-nBits)
  1606. nBits += eLen
  1607. for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  1608. m = e & ((1 << (-nBits)) - 1)
  1609. e >>= (-nBits)
  1610. nBits += mLen
  1611. for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
  1612. if (e === 0) {
  1613. e = 1 - eBias
  1614. } else if (e === eMax) {
  1615. return m ? NaN : ((s ? -1 : 1) * Infinity)
  1616. } else {
  1617. m = m + Math.pow(2, mLen)
  1618. e = e - eBias
  1619. }
  1620. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  1621. }
  1622. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  1623. var e, m, c
  1624. var eLen = nBytes * 8 - mLen - 1
  1625. var eMax = (1 << eLen) - 1
  1626. var eBias = eMax >> 1
  1627. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  1628. var i = isLE ? 0 : (nBytes - 1)
  1629. var d = isLE ? 1 : -1
  1630. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  1631. value = Math.abs(value)
  1632. if (isNaN(value) || value === Infinity) {
  1633. m = isNaN(value) ? 1 : 0
  1634. e = eMax
  1635. } else {
  1636. e = Math.floor(Math.log(value) / Math.LN2)
  1637. if (value * (c = Math.pow(2, -e)) < 1) {
  1638. e--
  1639. c *= 2
  1640. }
  1641. if (e + eBias >= 1) {
  1642. value += rt / c
  1643. } else {
  1644. value += rt * Math.pow(2, 1 - eBias)
  1645. }
  1646. if (value * c >= 2) {
  1647. e++
  1648. c /= 2
  1649. }
  1650. if (e + eBias >= eMax) {
  1651. m = 0
  1652. e = eMax
  1653. } else if (e + eBias >= 1) {
  1654. m = (value * c - 1) * Math.pow(2, mLen)
  1655. e = e + eBias
  1656. } else {
  1657. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  1658. e = 0
  1659. }
  1660. }
  1661. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  1662. e = (e << mLen) | m
  1663. eLen += mLen
  1664. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  1665. buffer[offset + i - d] |= s * 128
  1666. }
  1667. },{}],5:[function(require,module,exports){
  1668. /**
  1669. * isArray
  1670. */
  1671. var isArray = Array.isArray;
  1672. /**
  1673. * toString
  1674. */
  1675. var str = Object.prototype.toString;
  1676. /**
  1677. * Whether or not the given `val`
  1678. * is an array.
  1679. *
  1680. * example:
  1681. *
  1682. * isArray([]);
  1683. * // > true
  1684. * isArray(arguments);
  1685. * // > false
  1686. * isArray('');
  1687. * // > false
  1688. *
  1689. * @param {mixed} val
  1690. * @return {bool}
  1691. */
  1692. module.exports = isArray || function (val) {
  1693. return !! val && '[object Array]' == str.call(val);
  1694. };
  1695. },{}],6:[function(require,module,exports){
  1696. (function (global){
  1697. /**
  1698. * Module exports.
  1699. */
  1700. module.exports = deprecate;
  1701. /**
  1702. * Mark that a method should not be used.
  1703. * Returns a modified function which warns once by default.
  1704. *
  1705. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  1706. *
  1707. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  1708. * will throw an Error when invoked.
  1709. *
  1710. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  1711. * will invoke `console.trace()` instead of `console.error()`.
  1712. *
  1713. * @param {Function} fn - the function to deprecate
  1714. * @param {String} msg - the string to print to the console when `fn` is invoked
  1715. * @returns {Function} a new "deprecated" version of `fn`
  1716. * @api public
  1717. */
  1718. function deprecate (fn, msg) {
  1719. if (config('noDeprecation')) {
  1720. return fn;
  1721. }
  1722. var warned = false;
  1723. function deprecated() {
  1724. if (!warned) {
  1725. if (config('throwDeprecation')) {
  1726. throw new Error(msg);
  1727. } else if (config('traceDeprecation')) {
  1728. console.trace(msg);
  1729. } else {
  1730. console.warn(msg);
  1731. }
  1732. warned = true;
  1733. }
  1734. return fn.apply(this, arguments);
  1735. }
  1736. return deprecated;
  1737. }
  1738. /**
  1739. * Checks `localStorage` for boolean values for the given `name`.
  1740. *
  1741. * @param {String} name
  1742. * @returns {Boolean}
  1743. * @api private
  1744. */
  1745. function config (name) {
  1746. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  1747. try {
  1748. if (!global.localStorage) return false;
  1749. } catch (_) {
  1750. return false;
  1751. }
  1752. var val = global.localStorage[name];
  1753. if (null == val) return false;
  1754. return String(val).toLowerCase() === 'true';
  1755. }
  1756. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  1757. },{}],7:[function(require,module,exports){
  1758. function DOMParser(options){
  1759. this.options = options ||{locator:{}};
  1760. }
  1761. DOMParser.prototype.parseFromString = function(source,mimeType){
  1762. var options = this.options;
  1763. var sax = new XMLReader();
  1764. var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
  1765. var errorHandler = options.errorHandler;
  1766. var locator = options.locator;
  1767. var defaultNSMap = options.xmlns||{};
  1768. var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"}
  1769. if(locator){
  1770. domBuilder.setDocumentLocator(locator)
  1771. }
  1772. sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
  1773. sax.domBuilder = options.domBuilder || domBuilder;
  1774. if(/\/x?html?$/.test(mimeType)){
  1775. entityMap.nbsp = '\xa0';
  1776. entityMap.copy = '\xa9';
  1777. defaultNSMap['']= 'http://www.w3.org/1999/xhtml';
  1778. }
  1779. if(source){
  1780. sax.parse(source,defaultNSMap,entityMap);
  1781. }else{
  1782. sax.errorHandler.error("invalid document source");
  1783. }
  1784. return domBuilder.document;
  1785. }
  1786. function buildErrorHandler(errorImpl,domBuilder,locator){
  1787. if(!errorImpl){
  1788. if(domBuilder instanceof DOMHandler){
  1789. return domBuilder;
  1790. }
  1791. errorImpl = domBuilder ;
  1792. }
  1793. var errorHandler = {}
  1794. var isCallback = errorImpl instanceof Function;
  1795. locator = locator||{}
  1796. function build(key){
  1797. var fn = errorImpl[key];
  1798. if(!fn){
  1799. if(isCallback){
  1800. fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl;
  1801. }else{
  1802. var i=arguments.length;
  1803. while(--i){
  1804. if(fn = errorImpl[arguments[i]]){
  1805. break;
  1806. }
  1807. }
  1808. }
  1809. }
  1810. errorHandler[key] = fn && function(msg){
  1811. fn(msg+_locator(locator));
  1812. }||function(){};
  1813. }
  1814. build('warning','warn');
  1815. build('error','warn','warning');
  1816. build('fatalError','warn','warning','error');
  1817. return errorHandler;
  1818. }
  1819. /**
  1820. * +ContentHandler+ErrorHandler
  1821. * +LexicalHandler+EntityResolver2
  1822. * -DeclHandler-DTDHandler
  1823. *
  1824. * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
  1825. * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
  1826. * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
  1827. */
  1828. function DOMHandler() {
  1829. this.cdata = false;
  1830. }
  1831. function position(locator,node){
  1832. node.lineNumber = locator.lineNumber;
  1833. node.columnNumber = locator.columnNumber;
  1834. }
  1835. /**
  1836. * @see org.xml.sax.ContentHandler#startDocument
  1837. * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
  1838. */
  1839. DOMHandler.prototype = {
  1840. startDocument : function() {
  1841. this.document = new DOMImplementation().createDocument(null, null, null);
  1842. if (this.locator) {
  1843. this.document.documentURI = this.locator.systemId;
  1844. }
  1845. },
  1846. startElement:function(namespaceURI, localName, qName, attrs) {
  1847. var doc = this.document;
  1848. var el = doc.createElementNS(namespaceURI, qName||localName);
  1849. var len = attrs.length;
  1850. appendElement(this, el);
  1851. this.currentElement = el;
  1852. this.locator && position(this.locator,el)
  1853. for (var i = 0 ; i < len; i++) {
  1854. var namespaceURI = attrs.getURI(i);
  1855. var value = attrs.getValue(i);
  1856. var qName = attrs.getQName(i);
  1857. var attr = doc.createAttributeNS(namespaceURI, qName);
  1858. if( attr.getOffset){
  1859. position(attr.getOffset(1),attr)
  1860. }
  1861. attr.value = attr.nodeValue = value;
  1862. el.setAttributeNode(attr)
  1863. }
  1864. },
  1865. endElement:function(namespaceURI, localName, qName) {
  1866. var current = this.currentElement
  1867. var tagName = current.tagName;
  1868. this.currentElement = current.parentNode;
  1869. },
  1870. startPrefixMapping:function(prefix, uri) {
  1871. },
  1872. endPrefixMapping:function(prefix) {
  1873. },
  1874. processingInstruction:function(target, data) {
  1875. var ins = this.document.createProcessingInstruction(target, data);
  1876. this.locator && position(this.locator,ins)
  1877. appendElement(this, ins);
  1878. },
  1879. ignorableWhitespace:function(ch, start, length) {
  1880. },
  1881. characters:function(chars, start, length) {
  1882. chars = _toString.apply(this,arguments)
  1883. //console.log(chars)
  1884. if(this.currentElement && chars){
  1885. if (this.cdata) {
  1886. var charNode = this.document.createCDATASection(chars);
  1887. this.currentElement.appendChild(charNode);
  1888. } else {
  1889. var charNode = this.document.createTextNode(chars);
  1890. this.currentElement.appendChild(charNode);
  1891. }
  1892. this.locator && position(this.locator,charNode)
  1893. }
  1894. },
  1895. skippedEntity:function(name) {
  1896. },
  1897. endDocument:function() {
  1898. this.document.normalize();
  1899. },
  1900. setDocumentLocator:function (locator) {
  1901. if(this.locator = locator){// && !('lineNumber' in locator)){
  1902. locator.lineNumber = 0;
  1903. }
  1904. },
  1905. //LexicalHandler
  1906. comment:function(chars, start, length) {
  1907. chars = _toString.apply(this,arguments)
  1908. var comm = this.document.createComment(chars);
  1909. this.locator && position(this.locator,comm)
  1910. appendElement(this, comm);
  1911. },
  1912. startCDATA:function() {
  1913. //used in characters() methods
  1914. this.cdata = true;
  1915. },
  1916. endCDATA:function() {
  1917. this.cdata = false;
  1918. },
  1919. startDTD:function(name, publicId, systemId) {
  1920. var impl = this.document.implementation;
  1921. if (impl && impl.createDocumentType) {
  1922. var dt = impl.createDocumentType(name, publicId, systemId);
  1923. this.locator && position(this.locator,dt)
  1924. appendElement(this, dt);
  1925. }
  1926. },
  1927. /**
  1928. * @see org.xml.sax.ErrorHandler
  1929. * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
  1930. */
  1931. warning:function(error) {
  1932. console.warn(error,_locator(this.locator));
  1933. },
  1934. error:function(error) {
  1935. console.error(error,_locator(this.locator));
  1936. },
  1937. fatalError:function(error) {
  1938. console.error(error,_locator(this.locator));
  1939. throw error;
  1940. }
  1941. }
  1942. function _locator(l){
  1943. if(l){
  1944. return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
  1945. }
  1946. }
  1947. function _toString(chars,start,length){
  1948. if(typeof chars == 'string'){
  1949. return chars.substr(start,length)
  1950. }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
  1951. if(chars.length >= start+length || start){
  1952. return new java.lang.String(chars,start,length)+'';
  1953. }
  1954. return chars;
  1955. }
  1956. }
  1957. /*
  1958. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
  1959. * used method of org.xml.sax.ext.LexicalHandler:
  1960. * #comment(chars, start, length)
  1961. * #startCDATA()
  1962. * #endCDATA()
  1963. * #startDTD(name, publicId, systemId)
  1964. *
  1965. *
  1966. * IGNORED method of org.xml.sax.ext.LexicalHandler:
  1967. * #endDTD()
  1968. * #startEntity(name)
  1969. * #endEntity(name)
  1970. *
  1971. *
  1972. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
  1973. * IGNORED method of org.xml.sax.ext.DeclHandler
  1974. * #attributeDecl(eName, aName, type, mode, value)
  1975. * #elementDecl(name, model)
  1976. * #externalEntityDecl(name, publicId, systemId)
  1977. * #internalEntityDecl(name, value)
  1978. * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
  1979. * IGNORED method of org.xml.sax.EntityResolver2
  1980. * #resolveEntity(String name,String publicId,String baseURI,String systemId)
  1981. * #resolveEntity(publicId, systemId)
  1982. * #getExternalSubset(name, baseURI)
  1983. * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
  1984. * IGNORED method of org.xml.sax.DTDHandler
  1985. * #notationDecl(name, publicId, systemId) {};
  1986. * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
  1987. */
  1988. "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
  1989. DOMHandler.prototype[key] = function(){return null}
  1990. })
  1991. /* 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 */
  1992. function appendElement (hander,node) {
  1993. if (!hander.currentElement) {
  1994. hander.document.appendChild(node);
  1995. } else {
  1996. hander.currentElement.appendChild(node);
  1997. }
  1998. }//appendChild and setAttributeNS are preformance key
  1999. if(typeof require == 'function'){
  2000. var XMLReader = require('./sax').XMLReader;
  2001. var DOMImplementation = exports.DOMImplementation = require('./dom').DOMImplementation;
  2002. exports.XMLSerializer = require('./dom').XMLSerializer ;
  2003. exports.DOMParser = DOMParser;
  2004. }
  2005. },{"./dom":8,"./sax":9}],8:[function(require,module,exports){
  2006. /*
  2007. * DOM Level 2
  2008. * Object DOMException
  2009. * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
  2010. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
  2011. */
  2012. function copy(src,dest){
  2013. for(var p in src){
  2014. dest[p] = src[p];
  2015. }
  2016. }
  2017. /**
  2018. ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
  2019. ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
  2020. */
  2021. function _extends(Class,Super){
  2022. var pt = Class.prototype;
  2023. if(Object.create){
  2024. var ppt = Object.create(Super.prototype)
  2025. pt.__proto__ = ppt;
  2026. }
  2027. if(!(pt instanceof Super)){
  2028. function t(){};
  2029. t.prototype = Super.prototype;
  2030. t = new t();
  2031. copy(pt,t);
  2032. Class.prototype = pt = t;
  2033. }
  2034. if(pt.constructor != Class){
  2035. if(typeof Class != 'function'){
  2036. console.error("unknow Class:"+Class)
  2037. }
  2038. pt.constructor = Class
  2039. }
  2040. }
  2041. var htmlns = 'http://www.w3.org/1999/xhtml' ;
  2042. // Node Types
  2043. var NodeType = {}
  2044. var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
  2045. var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
  2046. var TEXT_NODE = NodeType.TEXT_NODE = 3;
  2047. var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
  2048. var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
  2049. var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
  2050. var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
  2051. var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
  2052. var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
  2053. var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
  2054. var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
  2055. var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
  2056. // ExceptionCode
  2057. var ExceptionCode = {}
  2058. var ExceptionMessage = {};
  2059. var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
  2060. var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
  2061. var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
  2062. var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
  2063. var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
  2064. var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
  2065. var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
  2066. var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
  2067. var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
  2068. var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
  2069. //level2
  2070. var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
  2071. var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
  2072. var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
  2073. var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
  2074. var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
  2075. function DOMException(code, message) {
  2076. if(message instanceof Error){
  2077. var error = message;
  2078. }else{
  2079. error = this;
  2080. Error.call(this, ExceptionMessage[code]);
  2081. this.message = ExceptionMessage[code];
  2082. if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
  2083. }
  2084. error.code = code;
  2085. if(message) this.message = this.message + ": " + message;
  2086. return error;
  2087. };
  2088. DOMException.prototype = Error.prototype;
  2089. copy(ExceptionCode,DOMException)
  2090. /**
  2091. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
  2092. * 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.
  2093. * The items in the NodeList are accessible via an integral index, starting from 0.
  2094. */
  2095. function NodeList() {
  2096. };
  2097. NodeList.prototype = {
  2098. /**
  2099. * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
  2100. * @standard level1
  2101. */
  2102. length:0,
  2103. /**
  2104. * 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.
  2105. * @standard level1
  2106. * @param index unsigned long
  2107. * Index into the collection.
  2108. * @return Node
  2109. * The node at the indexth position in the NodeList, or null if that is not a valid index.
  2110. */
  2111. item: function(index) {
  2112. return this[index] || null;
  2113. }
  2114. };
  2115. function LiveNodeList(node,refresh){
  2116. this._node = node;
  2117. this._refresh = refresh
  2118. _updateLiveList(this);
  2119. }
  2120. function _updateLiveList(list){
  2121. var inc = list._node._inc || list._node.ownerDocument._inc;
  2122. if(list._inc != inc){
  2123. var ls = list._refresh(list._node);
  2124. //console.log(ls.length)
  2125. __set__(list,'length',ls.length);
  2126. copy(ls,list);
  2127. list._inc = inc;
  2128. }
  2129. }
  2130. LiveNodeList.prototype.item = function(i){
  2131. _updateLiveList(this);
  2132. return this[i];
  2133. }
  2134. _extends(LiveNodeList,NodeList);
  2135. /**
  2136. *
  2137. * 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.
  2138. * NamedNodeMap objects in the DOM are live.
  2139. * used for attributes or DocumentType entities
  2140. */
  2141. function NamedNodeMap() {
  2142. };
  2143. function _findNodeIndex(list,node){
  2144. var i = list.length;
  2145. while(i--){
  2146. if(list[i] === node){return i}
  2147. }
  2148. }
  2149. function _addNamedNode(el,list,newAttr,oldAttr){
  2150. if(oldAttr){
  2151. list[_findNodeIndex(list,oldAttr)] = newAttr;
  2152. }else{
  2153. list[list.length++] = newAttr;
  2154. }
  2155. if(el){
  2156. newAttr.ownerElement = el;
  2157. var doc = el.ownerDocument;
  2158. if(doc){
  2159. oldAttr && _onRemoveAttribute(doc,el,oldAttr);
  2160. _onAddAttribute(doc,el,newAttr);
  2161. }
  2162. }
  2163. }
  2164. function _removeNamedNode(el,list,attr){
  2165. var i = _findNodeIndex(list,attr);
  2166. if(i>=0){
  2167. var lastIndex = list.length-1
  2168. while(i<lastIndex){
  2169. list[i] = list[++i]
  2170. }
  2171. list.length = lastIndex;
  2172. if(el){
  2173. var doc = el.ownerDocument;
  2174. if(doc){
  2175. _onRemoveAttribute(doc,el,attr);
  2176. attr.ownerElement = null;
  2177. }
  2178. }
  2179. }else{
  2180. throw DOMException(NOT_FOUND_ERR,new Error())
  2181. }
  2182. }
  2183. NamedNodeMap.prototype = {
  2184. length:0,
  2185. item:NodeList.prototype.item,
  2186. getNamedItem: function(key) {
  2187. // if(key.indexOf(':')>0 || key == 'xmlns'){
  2188. // return null;
  2189. // }
  2190. var i = this.length;
  2191. while(i--){
  2192. var attr = this[i];
  2193. if(attr.nodeName == key){
  2194. return attr;
  2195. }
  2196. }
  2197. },
  2198. setNamedItem: function(attr) {
  2199. var el = attr.ownerElement;
  2200. if(el && el!=this._ownerElement){
  2201. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  2202. }
  2203. var oldAttr = this.getNamedItem(attr.nodeName);
  2204. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  2205. return oldAttr;
  2206. },
  2207. /* returns Node */
  2208. setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
  2209. var el = attr.ownerElement, oldAttr;
  2210. if(el && el!=this._ownerElement){
  2211. throw new DOMException(INUSE_ATTRIBUTE_ERR);
  2212. }
  2213. oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
  2214. _addNamedNode(this._ownerElement,this,attr,oldAttr);
  2215. return oldAttr;
  2216. },
  2217. /* returns Node */
  2218. removeNamedItem: function(key) {
  2219. var attr = this.getNamedItem(key);
  2220. _removeNamedNode(this._ownerElement,this,attr);
  2221. return attr;
  2222. },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
  2223. //for level2
  2224. removeNamedItemNS:function(namespaceURI,localName){
  2225. var attr = this.getNamedItemNS(namespaceURI,localName);
  2226. _removeNamedNode(this._ownerElement,this,attr);
  2227. return attr;
  2228. },
  2229. getNamedItemNS: function(namespaceURI, localName) {
  2230. var i = this.length;
  2231. while(i--){
  2232. var node = this[i];
  2233. if(node.localName == localName && node.namespaceURI == namespaceURI){
  2234. return node;
  2235. }
  2236. }
  2237. return null;
  2238. }
  2239. };
  2240. /**
  2241. * @see http://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490
  2242. */
  2243. function DOMImplementation(/* Object */ features) {
  2244. this._features = {};
  2245. if (features) {
  2246. for (var feature in features) {
  2247. this._features = features[feature];
  2248. }
  2249. }
  2250. };
  2251. DOMImplementation.prototype = {
  2252. hasFeature: function(/* string */ feature, /* string */ version) {
  2253. var versions = this._features[feature.toLowerCase()];
  2254. if (versions && (!version || version in versions)) {
  2255. return true;
  2256. } else {
  2257. return false;
  2258. }
  2259. },
  2260. // Introduced in DOM Level 2:
  2261. createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR
  2262. var doc = new Document();
  2263. doc.doctype = doctype;
  2264. if(doctype){
  2265. doc.appendChild(doctype);
  2266. }
  2267. doc.implementation = this;
  2268. doc.childNodes = new NodeList();
  2269. if(qualifiedName){
  2270. var root = doc.createElementNS(namespaceURI,qualifiedName);
  2271. doc.appendChild(root);
  2272. }
  2273. return doc;
  2274. },
  2275. // Introduced in DOM Level 2:
  2276. createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR
  2277. var node = new DocumentType();
  2278. node.name = qualifiedName;
  2279. node.nodeName = qualifiedName;
  2280. node.publicId = publicId;
  2281. node.systemId = systemId;
  2282. // Introduced in DOM Level 2:
  2283. //readonly attribute DOMString internalSubset;
  2284. //TODO:..
  2285. // readonly attribute NamedNodeMap entities;
  2286. // readonly attribute NamedNodeMap notations;
  2287. return node;
  2288. }
  2289. };
  2290. /**
  2291. * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
  2292. */
  2293. function Node() {
  2294. };
  2295. Node.prototype = {
  2296. firstChild : null,
  2297. lastChild : null,
  2298. previousSibling : null,
  2299. nextSibling : null,
  2300. attributes : null,
  2301. parentNode : null,
  2302. childNodes : null,
  2303. ownerDocument : null,
  2304. nodeValue : null,
  2305. namespaceURI : null,
  2306. prefix : null,
  2307. localName : null,
  2308. // Modified in DOM Level 2:
  2309. insertBefore:function(newChild, refChild){//raises
  2310. return _insertBefore(this,newChild,refChild);
  2311. },
  2312. replaceChild:function(newChild, oldChild){//raises
  2313. this.insertBefore(newChild,oldChild);
  2314. if(oldChild){
  2315. this.removeChild(oldChild);
  2316. }
  2317. },
  2318. removeChild:function(oldChild){
  2319. return _removeChild(this,oldChild);
  2320. },
  2321. appendChild:function(newChild){
  2322. return this.insertBefore(newChild,null);
  2323. },
  2324. hasChildNodes:function(){
  2325. return this.firstChild != null;
  2326. },
  2327. cloneNode:function(deep){
  2328. return cloneNode(this.ownerDocument||this,this,deep);
  2329. },
  2330. // Modified in DOM Level 2:
  2331. normalize:function(){
  2332. var child = this.firstChild;
  2333. while(child){
  2334. var next = child.nextSibling;
  2335. if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
  2336. this.removeChild(next);
  2337. child.appendData(next.data);
  2338. }else{
  2339. child.normalize();
  2340. child = next;
  2341. }
  2342. }
  2343. },
  2344. // Introduced in DOM Level 2:
  2345. isSupported:function(feature, version){
  2346. return this.ownerDocument.implementation.hasFeature(feature,version);
  2347. },
  2348. // Introduced in DOM Level 2:
  2349. hasAttributes:function(){
  2350. return this.attributes.length>0;
  2351. },
  2352. lookupPrefix:function(namespaceURI){
  2353. var el = this;
  2354. while(el){
  2355. var map = el._nsMap;
  2356. //console.dir(map)
  2357. if(map){
  2358. for(var n in map){
  2359. if(map[n] == namespaceURI){
  2360. return n;
  2361. }
  2362. }
  2363. }
  2364. el = el.nodeType == 2?el.ownerDocument : el.parentNode;
  2365. }
  2366. return null;
  2367. },
  2368. // Introduced in DOM Level 3:
  2369. lookupNamespaceURI:function(prefix){
  2370. var el = this;
  2371. while(el){
  2372. var map = el._nsMap;
  2373. //console.dir(map)
  2374. if(map){
  2375. if(prefix in map){
  2376. return map[prefix] ;
  2377. }
  2378. }
  2379. el = el.nodeType == 2?el.ownerDocument : el.parentNode;
  2380. }
  2381. return null;
  2382. },
  2383. // Introduced in DOM Level 3:
  2384. isDefaultNamespace:function(namespaceURI){
  2385. var prefix = this.lookupPrefix(namespaceURI);
  2386. return prefix == null;
  2387. }
  2388. };
  2389. function _xmlEncoder(c){
  2390. return c == '<' && '&lt;' ||
  2391. c == '>' && '&gt;' ||
  2392. c == '&' && '&amp;' ||
  2393. c == '"' && '&quot;' ||
  2394. '&#'+c.charCodeAt()+';'
  2395. }
  2396. copy(NodeType,Node);
  2397. copy(NodeType,Node.prototype);
  2398. /**
  2399. * @param callback return true for continue,false for break
  2400. * @return boolean true: break visit;
  2401. */
  2402. function _visitNode(node,callback){
  2403. if(callback(node)){
  2404. return true;
  2405. }
  2406. if(node = node.firstChild){
  2407. do{
  2408. if(_visitNode(node,callback)){return true}
  2409. }while(node=node.nextSibling)
  2410. }
  2411. }
  2412. function Document(){
  2413. }
  2414. function _onAddAttribute(doc,el,newAttr){
  2415. doc && doc._inc++;
  2416. var ns = newAttr.namespaceURI ;
  2417. if(ns == 'http://www.w3.org/2000/xmlns/'){
  2418. //update namespace
  2419. el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value
  2420. }
  2421. }
  2422. function _onRemoveAttribute(doc,el,newAttr,remove){
  2423. doc && doc._inc++;
  2424. var ns = newAttr.namespaceURI ;
  2425. if(ns == 'http://www.w3.org/2000/xmlns/'){
  2426. //update namespace
  2427. delete el._nsMap[newAttr.prefix?newAttr.localName:'']
  2428. }
  2429. }
  2430. function _onUpdateChild(doc,el,newChild){
  2431. if(doc && doc._inc){
  2432. doc._inc++;
  2433. //update childNodes
  2434. var cs = el.childNodes;
  2435. if(newChild){
  2436. cs[cs.length++] = newChild;
  2437. }else{
  2438. //console.log(1)
  2439. var child = el.firstChild;
  2440. var i = 0;
  2441. while(child){
  2442. cs[i++] = child;
  2443. child =child.nextSibling;
  2444. }
  2445. cs.length = i;
  2446. }
  2447. }
  2448. }
  2449. /**
  2450. * attributes;
  2451. * children;
  2452. *
  2453. * writeable properties:
  2454. * nodeValue,Attr:value,CharacterData:data
  2455. * prefix
  2456. */
  2457. function _removeChild(parentNode,child){
  2458. var previous = child.previousSibling;
  2459. var next = child.nextSibling;
  2460. if(previous){
  2461. previous.nextSibling = next;
  2462. }else{
  2463. parentNode.firstChild = next
  2464. }
  2465. if(next){
  2466. next.previousSibling = previous;
  2467. }else{
  2468. parentNode.lastChild = previous;
  2469. }
  2470. _onUpdateChild(parentNode.ownerDocument,parentNode);
  2471. return child;
  2472. }
  2473. /**
  2474. * preformance key(refChild == null)
  2475. */
  2476. function _insertBefore(parentNode,newChild,nextChild){
  2477. var cp = newChild.parentNode;
  2478. if(cp){
  2479. cp.removeChild(newChild);//remove and update
  2480. }
  2481. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  2482. var newFirst = newChild.firstChild;
  2483. if (newFirst == null) {
  2484. return newChild;
  2485. }
  2486. var newLast = newChild.lastChild;
  2487. }else{
  2488. newFirst = newLast = newChild;
  2489. }
  2490. var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
  2491. newFirst.previousSibling = pre;
  2492. newLast.nextSibling = nextChild;
  2493. if(pre){
  2494. pre.nextSibling = newFirst;
  2495. }else{
  2496. parentNode.firstChild = newFirst;
  2497. }
  2498. if(nextChild == null){
  2499. parentNode.lastChild = newLast;
  2500. }else{
  2501. nextChild.previousSibling = newLast;
  2502. }
  2503. do{
  2504. newFirst.parentNode = parentNode;
  2505. }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
  2506. _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
  2507. //console.log(parentNode.lastChild.nextSibling == null)
  2508. if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
  2509. newChild.firstChild = newChild.lastChild = null;
  2510. }
  2511. return newChild;
  2512. }
  2513. function _appendSingleChild(parentNode,newChild){
  2514. var cp = newChild.parentNode;
  2515. if(cp){
  2516. var pre = parentNode.lastChild;
  2517. cp.removeChild(newChild);//remove and update
  2518. var pre = parentNode.lastChild;
  2519. }
  2520. var pre = parentNode.lastChild;
  2521. newChild.parentNode = parentNode;
  2522. newChild.previousSibling = pre;
  2523. newChild.nextSibling = null;
  2524. if(pre){
  2525. pre.nextSibling = newChild;
  2526. }else{
  2527. parentNode.firstChild = newChild;
  2528. }
  2529. parentNode.lastChild = newChild;
  2530. _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
  2531. return newChild;
  2532. //console.log("__aa",parentNode.lastChild.nextSibling == null)
  2533. }
  2534. Document.prototype = {
  2535. //implementation : null,
  2536. nodeName : '#document',
  2537. nodeType : DOCUMENT_NODE,
  2538. doctype : null,
  2539. documentElement : null,
  2540. _inc : 1,
  2541. insertBefore : function(newChild, refChild){//raises
  2542. if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
  2543. var child = newChild.firstChild;
  2544. while(child){
  2545. var next = child.nextSibling;
  2546. this.insertBefore(child,refChild);
  2547. child = next;
  2548. }
  2549. return newChild;
  2550. }
  2551. if(this.documentElement == null && newChild.nodeType == 1){
  2552. this.documentElement = newChild;
  2553. }
  2554. return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
  2555. },
  2556. removeChild : function(oldChild){
  2557. if(this.documentElement == oldChild){
  2558. this.documentElement = null;
  2559. }
  2560. return _removeChild(this,oldChild);
  2561. },
  2562. // Introduced in DOM Level 2:
  2563. importNode : function(importedNode,deep){
  2564. return importNode(this,importedNode,deep);
  2565. },
  2566. // Introduced in DOM Level 2:
  2567. getElementById : function(id){
  2568. var rtv = null;
  2569. _visitNode(this.documentElement,function(node){
  2570. if(node.nodeType == 1){
  2571. if(node.getAttribute('id') == id){
  2572. rtv = node;
  2573. return true;
  2574. }
  2575. }
  2576. })
  2577. return rtv;
  2578. },
  2579. //document factory method:
  2580. createElement : function(tagName){
  2581. var node = new Element();
  2582. node.ownerDocument = this;
  2583. node.nodeName = tagName;
  2584. node.tagName = tagName;
  2585. node.childNodes = new NodeList();
  2586. var attrs = node.attributes = new NamedNodeMap();
  2587. attrs._ownerElement = node;
  2588. return node;
  2589. },
  2590. createDocumentFragment : function(){
  2591. var node = new DocumentFragment();
  2592. node.ownerDocument = this;
  2593. node.childNodes = new NodeList();
  2594. return node;
  2595. },
  2596. createTextNode : function(data){
  2597. var node = new Text();
  2598. node.ownerDocument = this;
  2599. node.appendData(data)
  2600. return node;
  2601. },
  2602. createComment : function(data){
  2603. var node = new Comment();
  2604. node.ownerDocument = this;
  2605. node.appendData(data)
  2606. return node;
  2607. },
  2608. createCDATASection : function(data){
  2609. var node = new CDATASection();
  2610. node.ownerDocument = this;
  2611. node.appendData(data)
  2612. return node;
  2613. },
  2614. createProcessingInstruction : function(target,data){
  2615. var node = new ProcessingInstruction();
  2616. node.ownerDocument = this;
  2617. node.tagName = node.target = target;
  2618. node.nodeValue= node.data = data;
  2619. return node;
  2620. },
  2621. createAttribute : function(name){
  2622. var node = new Attr();
  2623. node.ownerDocument = this;
  2624. node.name = name;
  2625. node.nodeName = name;
  2626. node.localName = name;
  2627. node.specified = true;
  2628. return node;
  2629. },
  2630. createEntityReference : function(name){
  2631. var node = new EntityReference();
  2632. node.ownerDocument = this;
  2633. node.nodeName = name;
  2634. return node;
  2635. },
  2636. // Introduced in DOM Level 2:
  2637. createElementNS : function(namespaceURI,qualifiedName){
  2638. var node = new Element();
  2639. var pl = qualifiedName.split(':');
  2640. var attrs = node.attributes = new NamedNodeMap();
  2641. node.childNodes = new NodeList();
  2642. node.ownerDocument = this;
  2643. node.nodeName = qualifiedName;
  2644. node.tagName = qualifiedName;
  2645. node.namespaceURI = namespaceURI;
  2646. if(pl.length == 2){
  2647. node.prefix = pl[0];
  2648. node.localName = pl[1];
  2649. }else{
  2650. //el.prefix = null;
  2651. node.localName = qualifiedName;
  2652. }
  2653. attrs._ownerElement = node;
  2654. return node;
  2655. },
  2656. // Introduced in DOM Level 2:
  2657. createAttributeNS : function(namespaceURI,qualifiedName){
  2658. var node = new Attr();
  2659. var pl = qualifiedName.split(':');
  2660. node.ownerDocument = this;
  2661. node.nodeName = qualifiedName;
  2662. node.name = qualifiedName;
  2663. node.namespaceURI = namespaceURI;
  2664. node.specified = true;
  2665. if(pl.length == 2){
  2666. node.prefix = pl[0];
  2667. node.localName = pl[1];
  2668. }else{
  2669. //el.prefix = null;
  2670. node.localName = qualifiedName;
  2671. }
  2672. return node;
  2673. }
  2674. };
  2675. _extends(Document,Node);
  2676. function Element() {
  2677. this._nsMap = {};
  2678. };
  2679. Element.prototype = {
  2680. nodeType : ELEMENT_NODE,
  2681. hasAttribute : function(name){
  2682. return this.getAttributeNode(name)!=null;
  2683. },
  2684. getAttribute : function(name){
  2685. var attr = this.getAttributeNode(name);
  2686. return attr && attr.value || '';
  2687. },
  2688. getAttributeNode : function(name){
  2689. return this.attributes.getNamedItem(name);
  2690. },
  2691. setAttribute : function(name, value){
  2692. var attr = this.ownerDocument.createAttribute(name);
  2693. attr.value = attr.nodeValue = "" + value;
  2694. this.setAttributeNode(attr)
  2695. },
  2696. removeAttribute : function(name){
  2697. var attr = this.getAttributeNode(name)
  2698. attr && this.removeAttributeNode(attr);
  2699. },
  2700. //four real opeartion method
  2701. appendChild:function(newChild){
  2702. if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
  2703. return this.insertBefore(newChild,null);
  2704. }else{
  2705. return _appendSingleChild(this,newChild);
  2706. }
  2707. },
  2708. setAttributeNode : function(newAttr){
  2709. return this.attributes.setNamedItem(newAttr);
  2710. },
  2711. setAttributeNodeNS : function(newAttr){
  2712. return this.attributes.setNamedItemNS(newAttr);
  2713. },
  2714. removeAttributeNode : function(oldAttr){
  2715. return this.attributes.removeNamedItem(oldAttr.nodeName);
  2716. },
  2717. //get real attribute name,and remove it by removeAttributeNode
  2718. removeAttributeNS : function(namespaceURI, localName){
  2719. var old = this.getAttributeNodeNS(namespaceURI, localName);
  2720. old && this.removeAttributeNode(old);
  2721. },
  2722. hasAttributeNS : function(namespaceURI, localName){
  2723. return this.getAttributeNodeNS(namespaceURI, localName)!=null;
  2724. },
  2725. getAttributeNS : function(namespaceURI, localName){
  2726. var attr = this.getAttributeNodeNS(namespaceURI, localName);
  2727. return attr && attr.value || '';
  2728. },
  2729. setAttributeNS : function(namespaceURI, qualifiedName, value){
  2730. var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
  2731. attr.value = attr.nodeValue = value;
  2732. this.setAttributeNode(attr)
  2733. },
  2734. getAttributeNodeNS : function(namespaceURI, localName){
  2735. return this.attributes.getNamedItemNS(namespaceURI, localName);
  2736. },
  2737. getElementsByTagName : function(tagName){
  2738. return new LiveNodeList(this,function(base){
  2739. var ls = [];
  2740. _visitNode(base,function(node){
  2741. if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
  2742. ls.push(node);
  2743. }
  2744. });
  2745. return ls;
  2746. });
  2747. },
  2748. getElementsByTagNameNS : function(namespaceURI, localName){
  2749. return new LiveNodeList(this,function(base){
  2750. var ls = [];
  2751. _visitNode(base,function(node){
  2752. if(node !== base && node.nodeType === ELEMENT_NODE && node.namespaceURI === namespaceURI && (localName === '*' || node.localName == localName)){
  2753. ls.push(node);
  2754. }
  2755. });
  2756. return ls;
  2757. });
  2758. }
  2759. };
  2760. Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
  2761. Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
  2762. _extends(Element,Node);
  2763. function Attr() {
  2764. };
  2765. Attr.prototype.nodeType = ATTRIBUTE_NODE;
  2766. _extends(Attr,Node);
  2767. function CharacterData() {
  2768. };
  2769. CharacterData.prototype = {
  2770. data : '',
  2771. substringData : function(offset, count) {
  2772. return this.data.substring(offset, offset+count);
  2773. },
  2774. appendData: function(text) {
  2775. text = this.data+text;
  2776. this.nodeValue = this.data = text;
  2777. this.length = text.length;
  2778. },
  2779. insertData: function(offset,text) {
  2780. this.replaceData(offset,0,text);
  2781. },
  2782. appendChild:function(newChild){
  2783. //if(!(newChild instanceof CharacterData)){
  2784. throw new Error(ExceptionMessage[3])
  2785. //}
  2786. return Node.prototype.appendChild.apply(this,arguments)
  2787. },
  2788. deleteData: function(offset, count) {
  2789. this.replaceData(offset,count,"");
  2790. },
  2791. replaceData: function(offset, count, text) {
  2792. var start = this.data.substring(0,offset);
  2793. var end = this.data.substring(offset+count);
  2794. text = start + text + end;
  2795. this.nodeValue = this.data = text;
  2796. this.length = text.length;
  2797. }
  2798. }
  2799. _extends(CharacterData,Node);
  2800. function Text() {
  2801. };
  2802. Text.prototype = {
  2803. nodeName : "#text",
  2804. nodeType : TEXT_NODE,
  2805. splitText : function(offset) {
  2806. var text = this.data;
  2807. var newText = text.substring(offset);
  2808. text = text.substring(0, offset);
  2809. this.data = this.nodeValue = text;
  2810. this.length = text.length;
  2811. var newNode = this.ownerDocument.createTextNode(newText);
  2812. if(this.parentNode){
  2813. this.parentNode.insertBefore(newNode, this.nextSibling);
  2814. }
  2815. return newNode;
  2816. }
  2817. }
  2818. _extends(Text,CharacterData);
  2819. function Comment() {
  2820. };
  2821. Comment.prototype = {
  2822. nodeName : "#comment",
  2823. nodeType : COMMENT_NODE
  2824. }
  2825. _extends(Comment,CharacterData);
  2826. function CDATASection() {
  2827. };
  2828. CDATASection.prototype = {
  2829. nodeName : "#cdata-section",
  2830. nodeType : CDATA_SECTION_NODE
  2831. }
  2832. _extends(CDATASection,CharacterData);
  2833. function DocumentType() {
  2834. };
  2835. DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
  2836. _extends(DocumentType,Node);
  2837. function Notation() {
  2838. };
  2839. Notation.prototype.nodeType = NOTATION_NODE;
  2840. _extends(Notation,Node);
  2841. function Entity() {
  2842. };
  2843. Entity.prototype.nodeType = ENTITY_NODE;
  2844. _extends(Entity,Node);
  2845. function EntityReference() {
  2846. };
  2847. EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
  2848. _extends(EntityReference,Node);
  2849. function DocumentFragment() {
  2850. };
  2851. DocumentFragment.prototype.nodeName = "#document-fragment";
  2852. DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
  2853. _extends(DocumentFragment,Node);
  2854. function ProcessingInstruction() {
  2855. }
  2856. ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
  2857. _extends(ProcessingInstruction,Node);
  2858. function XMLSerializer(){}
  2859. XMLSerializer.prototype.serializeToString = function(node){
  2860. var buf = [];
  2861. serializeToString(node,buf);
  2862. return buf.join('');
  2863. }
  2864. Node.prototype.toString =function(){
  2865. return XMLSerializer.prototype.serializeToString(this);
  2866. }
  2867. function serializeToString(node,buf){
  2868. switch(node.nodeType){
  2869. case ELEMENT_NODE:
  2870. var attrs = node.attributes;
  2871. var len = attrs.length;
  2872. var child = node.firstChild;
  2873. var nodeName = node.tagName;
  2874. var isHTML = htmlns === node.namespaceURI
  2875. buf.push('<',nodeName);
  2876. for(var i=0;i<len;i++){
  2877. serializeToString(attrs.item(i),buf,isHTML);
  2878. }
  2879. if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
  2880. buf.push('>');
  2881. //if is cdata child node
  2882. if(isHTML && /^script$/i.test(nodeName)){
  2883. if(child){
  2884. buf.push(child.data);
  2885. }
  2886. }else{
  2887. while(child){
  2888. serializeToString(child,buf);
  2889. child = child.nextSibling;
  2890. }
  2891. }
  2892. buf.push('</',nodeName,'>');
  2893. }else{
  2894. buf.push('/>');
  2895. }
  2896. return;
  2897. case DOCUMENT_NODE:
  2898. case DOCUMENT_FRAGMENT_NODE:
  2899. var child = node.firstChild;
  2900. while(child){
  2901. serializeToString(child,buf);
  2902. child = child.nextSibling;
  2903. }
  2904. return;
  2905. case ATTRIBUTE_NODE:
  2906. return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"');
  2907. case TEXT_NODE:
  2908. return buf.push(node.data.replace(/[<&]/g,_xmlEncoder));
  2909. case CDATA_SECTION_NODE:
  2910. return buf.push( '<![CDATA[',node.data,']]>');
  2911. case COMMENT_NODE:
  2912. return buf.push( "<!--",node.data,"-->");
  2913. case DOCUMENT_TYPE_NODE:
  2914. var pubid = node.publicId;
  2915. var sysid = node.systemId;
  2916. buf.push('<!DOCTYPE ',node.name);
  2917. if(pubid){
  2918. buf.push(' PUBLIC "',pubid);
  2919. if (sysid && sysid!='.') {
  2920. buf.push( '" "',sysid);
  2921. }
  2922. buf.push('">');
  2923. }else if(sysid && sysid!='.'){
  2924. buf.push(' SYSTEM "',sysid,'">');
  2925. }else{
  2926. var sub = node.internalSubset;
  2927. if(sub){
  2928. buf.push(" [",sub,"]");
  2929. }
  2930. buf.push(">");
  2931. }
  2932. return;
  2933. case PROCESSING_INSTRUCTION_NODE:
  2934. return buf.push( "<?",node.target," ",node.data,"?>");
  2935. case ENTITY_REFERENCE_NODE:
  2936. return buf.push( '&',node.nodeName,';');
  2937. //case ENTITY_NODE:
  2938. //case NOTATION_NODE:
  2939. default:
  2940. buf.push('??',node.nodeName);
  2941. }
  2942. }
  2943. function importNode(doc,node,deep){
  2944. var node2;
  2945. switch (node.nodeType) {
  2946. case ELEMENT_NODE:
  2947. node2 = node.cloneNode(false);
  2948. node2.ownerDocument = doc;
  2949. //var attrs = node2.attributes;
  2950. //var len = attrs.length;
  2951. //for(var i=0;i<len;i++){
  2952. //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
  2953. //}
  2954. case DOCUMENT_FRAGMENT_NODE:
  2955. break;
  2956. case ATTRIBUTE_NODE:
  2957. deep = true;
  2958. break;
  2959. //case ENTITY_REFERENCE_NODE:
  2960. //case PROCESSING_INSTRUCTION_NODE:
  2961. ////case TEXT_NODE:
  2962. //case CDATA_SECTION_NODE:
  2963. //case COMMENT_NODE:
  2964. // deep = false;
  2965. // break;
  2966. //case DOCUMENT_NODE:
  2967. //case DOCUMENT_TYPE_NODE:
  2968. //cannot be imported.
  2969. //case ENTITY_NODE:
  2970. //case NOTATION_NODE:
  2971. //can not hit in level3
  2972. //default:throw e;
  2973. }
  2974. if(!node2){
  2975. node2 = node.cloneNode(false);//false
  2976. }
  2977. node2.ownerDocument = doc;
  2978. node2.parentNode = null;
  2979. if(deep){
  2980. var child = node.firstChild;
  2981. while(child){
  2982. node2.appendChild(importNode(doc,child,deep));
  2983. child = child.nextSibling;
  2984. }
  2985. }
  2986. return node2;
  2987. }
  2988. //
  2989. //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
  2990. // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
  2991. function cloneNode(doc,node,deep){
  2992. var node2 = new node.constructor();
  2993. for(var n in node){
  2994. var v = node[n];
  2995. if(typeof v != 'object' ){
  2996. if(v != node2[n]){
  2997. node2[n] = v;
  2998. }
  2999. }
  3000. }
  3001. if(node.childNodes){
  3002. node2.childNodes = new NodeList();
  3003. }
  3004. node2.ownerDocument = doc;
  3005. switch (node2.nodeType) {
  3006. case ELEMENT_NODE:
  3007. var attrs = node.attributes;
  3008. var attrs2 = node2.attributes = new NamedNodeMap();
  3009. var len = attrs.length
  3010. attrs2._ownerElement = node2;
  3011. for(var i=0;i<len;i++){
  3012. node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
  3013. }
  3014. break;;
  3015. case ATTRIBUTE_NODE:
  3016. deep = true;
  3017. }
  3018. if(deep){
  3019. var child = node.firstChild;
  3020. while(child){
  3021. node2.appendChild(cloneNode(doc,child,deep));
  3022. child = child.nextSibling;
  3023. }
  3024. }
  3025. return node2;
  3026. }
  3027. function __set__(object,key,value){
  3028. object[key] = value
  3029. }
  3030. //do dynamic
  3031. try{
  3032. if(Object.defineProperty){
  3033. Object.defineProperty(LiveNodeList.prototype,'length',{
  3034. get:function(){
  3035. _updateLiveList(this);
  3036. return this.$$length;
  3037. }
  3038. });
  3039. Object.defineProperty(Node.prototype,'textContent',{
  3040. get:function(){
  3041. return getTextContent(this);
  3042. },
  3043. set:function(data){
  3044. switch(this.nodeType){
  3045. case 1:
  3046. case 11:
  3047. while(this.firstChild){
  3048. this.removeChild(this.firstChild);
  3049. }
  3050. if(data || String(data)){
  3051. this.appendChild(this.ownerDocument.createTextNode(data));
  3052. }
  3053. break;
  3054. default:
  3055. //TODO:
  3056. this.data = data;
  3057. this.value = value;
  3058. this.nodeValue = data;
  3059. }
  3060. }
  3061. })
  3062. function getTextContent(node){
  3063. switch(node.nodeType){
  3064. case 1:
  3065. case 11:
  3066. var buf = [];
  3067. node = node.firstChild;
  3068. while(node){
  3069. if(node.nodeType!==7 && node.nodeType !==8){
  3070. buf.push(getTextContent(node));
  3071. }
  3072. node = node.nextSibling;
  3073. }
  3074. return buf.join('');
  3075. default:
  3076. return node.nodeValue;
  3077. }
  3078. }
  3079. __set__ = function(object,key,value){
  3080. //console.log(value)
  3081. object['$$'+key] = value
  3082. }
  3083. }
  3084. }catch(e){//ie8
  3085. }
  3086. if(typeof require == 'function'){
  3087. exports.DOMImplementation = DOMImplementation;
  3088. exports.XMLSerializer = XMLSerializer;
  3089. }
  3090. },{}],9:[function(require,module,exports){
  3091. //[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]
  3092. //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
  3093. //[5] Name ::= NameStartChar (NameChar)*
  3094. 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
  3095. var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\u00B7\u0300-\u036F\\ux203F-\u2040]");
  3096. var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
  3097. //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
  3098. //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(',')
  3099. //S_TAG, S_ATTR, S_EQ, S_V
  3100. //S_ATTR_S, S_E, S_S, S_C
  3101. var S_TAG = 0;//tag name offerring
  3102. var S_ATTR = 1;//attr name offerring
  3103. var S_ATTR_S=2;//attr name end and space offer
  3104. var S_EQ = 3;//=space?
  3105. var S_V = 4;//attr value(no quot value only)
  3106. var S_E = 5;//attr value end and no space(quot end)
  3107. var S_S = 6;//(attr value end || tag end ) && (space offer)
  3108. var S_C = 7;//closed el<el />
  3109. function XMLReader(){
  3110. }
  3111. XMLReader.prototype = {
  3112. parse:function(source,defaultNSMap,entityMap){
  3113. var domBuilder = this.domBuilder;
  3114. domBuilder.startDocument();
  3115. _copy(defaultNSMap ,defaultNSMap = {})
  3116. parse(source,defaultNSMap,entityMap,
  3117. domBuilder,this.errorHandler);
  3118. domBuilder.endDocument();
  3119. }
  3120. }
  3121. function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
  3122. function fixedFromCharCode(code) {
  3123. // String.prototype.fromCharCode does not supports
  3124. // > 2 bytes unicode chars directly
  3125. if (code > 0xffff) {
  3126. code -= 0x10000;
  3127. var surrogate1 = 0xd800 + (code >> 10)
  3128. , surrogate2 = 0xdc00 + (code & 0x3ff);
  3129. return String.fromCharCode(surrogate1, surrogate2);
  3130. } else {
  3131. return String.fromCharCode(code);
  3132. }
  3133. }
  3134. function entityReplacer(a){
  3135. var k = a.slice(1,-1);
  3136. if(k in entityMap){
  3137. return entityMap[k];
  3138. }else if(k.charAt(0) === '#'){
  3139. return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
  3140. }else{
  3141. errorHandler.error('entity not found:'+a);
  3142. return a;
  3143. }
  3144. }
  3145. function appendText(end){//has some bugs
  3146. var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
  3147. locator&&position(start);
  3148. domBuilder.characters(xt,0,end-start);
  3149. start = end
  3150. }
  3151. function position(start,m){
  3152. while(start>=endPos && (m = linePattern.exec(source))){
  3153. startPos = m.index;
  3154. endPos = startPos + m[0].length;
  3155. locator.lineNumber++;
  3156. //console.log('line++:',locator,startPos,endPos)
  3157. }
  3158. locator.columnNumber = start-startPos+1;
  3159. }
  3160. var startPos = 0;
  3161. var endPos = 0;
  3162. var linePattern = /.+(?:\r\n?|\n)|.*$/g
  3163. var locator = domBuilder.locator;
  3164. var parseStack = [{currentNSMap:defaultNSMapCopy}]
  3165. var closeMap = {};
  3166. var start = 0;
  3167. while(true){
  3168. var i = source.indexOf('<',start);
  3169. if(i<0){
  3170. if(!source.substr(start).match(/^\s*$/)){
  3171. var doc = domBuilder.document;
  3172. var text = doc.createTextNode(source.substr(start));
  3173. doc.appendChild(text);
  3174. domBuilder.currentElement = text;
  3175. }
  3176. return;
  3177. }
  3178. if(i>start){
  3179. appendText(i);
  3180. }
  3181. switch(source.charAt(i+1)){
  3182. case '/':
  3183. var end = source.indexOf('>',i+3);
  3184. var tagName = source.substring(i+2,end);
  3185. var config = parseStack.pop();
  3186. var localNSMap = config.localNSMap;
  3187. if(config.tagName != tagName){
  3188. errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName );
  3189. }
  3190. domBuilder.endElement(config.uri,config.localName,tagName);
  3191. if(localNSMap){
  3192. for(var prefix in localNSMap){
  3193. domBuilder.endPrefixMapping(prefix) ;
  3194. }
  3195. }
  3196. end++;
  3197. break;
  3198. // end elment
  3199. case '?':// <?...?>
  3200. locator&&position(i);
  3201. end = parseInstruction(source,i,domBuilder);
  3202. break;
  3203. case '!':// <!doctype,<![CDATA,<!--
  3204. locator&&position(i);
  3205. end = parseDCC(source,i,domBuilder,errorHandler);
  3206. break;
  3207. default:
  3208. try{
  3209. locator&&position(i);
  3210. var el = new ElementAttributes();
  3211. //elStartEnd
  3212. var end = parseElementStartPart(source,i,el,entityReplacer,errorHandler);
  3213. var len = el.length;
  3214. //position fixed
  3215. if(len && locator){
  3216. var backup = copyLocator(locator,{});
  3217. for(var i = 0;i<len;i++){
  3218. var a = el[i];
  3219. position(a.offset);
  3220. a.offset = copyLocator(locator,{});
  3221. }
  3222. copyLocator(backup,locator);
  3223. }
  3224. if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
  3225. el.closed = true;
  3226. if(!entityMap.nbsp){
  3227. errorHandler.warning('unclosed xml attribute');
  3228. }
  3229. }
  3230. appendElement(el,domBuilder,parseStack);
  3231. if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){
  3232. end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder)
  3233. }else{
  3234. end++;
  3235. }
  3236. }catch(e){
  3237. errorHandler.error('element parse error: '+e);
  3238. end = -1;
  3239. }
  3240. }
  3241. if(end<0){
  3242. //TODO: 这里有可能sax回退,有位置错误风险
  3243. appendText(i+1);
  3244. }else{
  3245. start = end;
  3246. }
  3247. }
  3248. }
  3249. function copyLocator(f,t){
  3250. t.lineNumber = f.lineNumber;
  3251. t.columnNumber = f.columnNumber;
  3252. return t;
  3253. }
  3254. /**
  3255. * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
  3256. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  3257. */
  3258. function parseElementStartPart(source,start,el,entityReplacer,errorHandler){
  3259. var attrName;
  3260. var value;
  3261. var p = ++start;
  3262. var s = S_TAG;//status
  3263. while(true){
  3264. var c = source.charAt(p);
  3265. switch(c){
  3266. case '=':
  3267. if(s === S_ATTR){//attrName
  3268. attrName = source.slice(start,p);
  3269. s = S_EQ;
  3270. }else if(s === S_ATTR_S){
  3271. s = S_EQ;
  3272. }else{
  3273. //fatalError: equal must after attrName or space after attrName
  3274. throw new Error('attribute equal must after attrName');
  3275. }
  3276. break;
  3277. case '\'':
  3278. case '"':
  3279. if(s === S_EQ){//equal
  3280. start = p+1;
  3281. p = source.indexOf(c,start)
  3282. if(p>0){
  3283. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  3284. el.add(attrName,value,start-1);
  3285. s = S_E;
  3286. }else{
  3287. //fatalError: no end quot match
  3288. throw new Error('attribute value no end \''+c+'\' match');
  3289. }
  3290. }else if(s == S_V){
  3291. value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  3292. //console.log(attrName,value,start,p)
  3293. el.add(attrName,value,start);
  3294. //console.dir(el)
  3295. errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
  3296. start = p+1;
  3297. s = S_E
  3298. }else{
  3299. //fatalError: no equal before
  3300. throw new Error('attribute value must after "="');
  3301. }
  3302. break;
  3303. case '/':
  3304. switch(s){
  3305. case S_TAG:
  3306. el.setTagName(source.slice(start,p));
  3307. case S_E:
  3308. case S_S:
  3309. case S_C:
  3310. s = S_C;
  3311. el.closed = true;
  3312. case S_V:
  3313. case S_ATTR:
  3314. case S_ATTR_S:
  3315. break;
  3316. //case S_EQ:
  3317. default:
  3318. throw new Error("attribute invalid close char('/')")
  3319. }
  3320. break;
  3321. case ''://end document
  3322. //throw new Error('unexpected end of input')
  3323. errorHandler.error('unexpected end of input');
  3324. case '>':
  3325. switch(s){
  3326. case S_TAG:
  3327. el.setTagName(source.slice(start,p));
  3328. case S_E:
  3329. case S_S:
  3330. case S_C:
  3331. break;//normal
  3332. case S_V://Compatible state
  3333. case S_ATTR:
  3334. value = source.slice(start,p);
  3335. if(value.slice(-1) === '/'){
  3336. el.closed = true;
  3337. value = value.slice(0,-1)
  3338. }
  3339. case S_ATTR_S:
  3340. if(s === S_ATTR_S){
  3341. value = attrName;
  3342. }
  3343. if(s == S_V){
  3344. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  3345. el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start)
  3346. }else{
  3347. errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!')
  3348. el.add(value,value,start)
  3349. }
  3350. break;
  3351. case S_EQ:
  3352. throw new Error('attribute value missed!!');
  3353. }
  3354. // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
  3355. return p;
  3356. /*xml space '\x20' | #x9 | #xD | #xA; */
  3357. case '\u0080':
  3358. c = ' ';
  3359. default:
  3360. if(c<= ' '){//space
  3361. switch(s){
  3362. case S_TAG:
  3363. el.setTagName(source.slice(start,p));//tagName
  3364. s = S_S;
  3365. break;
  3366. case S_ATTR:
  3367. attrName = source.slice(start,p)
  3368. s = S_ATTR_S;
  3369. break;
  3370. case S_V:
  3371. var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
  3372. errorHandler.warning('attribute "'+value+'" missed quot(")!!');
  3373. el.add(attrName,value,start)
  3374. case S_E:
  3375. s = S_S;
  3376. break;
  3377. //case S_S:
  3378. //case S_EQ:
  3379. //case S_ATTR_S:
  3380. // void();break;
  3381. //case S_C:
  3382. //ignore warning
  3383. }
  3384. }else{//not space
  3385. //S_TAG, S_ATTR, S_EQ, S_V
  3386. //S_ATTR_S, S_E, S_S, S_C
  3387. switch(s){
  3388. //case S_TAG:void();break;
  3389. //case S_ATTR:void();break;
  3390. //case S_V:void();break;
  3391. case S_ATTR_S:
  3392. errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead!!')
  3393. el.add(attrName,attrName,start);
  3394. start = p;
  3395. s = S_ATTR;
  3396. break;
  3397. case S_E:
  3398. errorHandler.warning('attribute space is required"'+attrName+'"!!')
  3399. case S_S:
  3400. s = S_ATTR;
  3401. start = p;
  3402. break;
  3403. case S_EQ:
  3404. s = S_V;
  3405. start = p;
  3406. break;
  3407. case S_C:
  3408. throw new Error("elements closed character '/' and '>' must be connected to");
  3409. }
  3410. }
  3411. }
  3412. p++;
  3413. }
  3414. }
  3415. /**
  3416. * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
  3417. */
  3418. function appendElement(el,domBuilder,parseStack){
  3419. var tagName = el.tagName;
  3420. var localNSMap = null;
  3421. var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
  3422. var i = el.length;
  3423. while(i--){
  3424. var a = el[i];
  3425. var qName = a.qName;
  3426. var value = a.value;
  3427. var nsp = qName.indexOf(':');
  3428. if(nsp>0){
  3429. var prefix = a.prefix = qName.slice(0,nsp);
  3430. var localName = qName.slice(nsp+1);
  3431. var nsPrefix = prefix === 'xmlns' && localName
  3432. }else{
  3433. localName = qName;
  3434. prefix = null
  3435. nsPrefix = qName === 'xmlns' && ''
  3436. }
  3437. //can not set prefix,because prefix !== ''
  3438. a.localName = localName ;
  3439. //prefix == null for no ns prefix attribute
  3440. if(nsPrefix !== false){//hack!!
  3441. if(localNSMap == null){
  3442. localNSMap = {}
  3443. //console.log(currentNSMap,0)
  3444. _copy(currentNSMap,currentNSMap={})
  3445. //console.log(currentNSMap,1)
  3446. }
  3447. currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
  3448. a.uri = 'http://www.w3.org/2000/xmlns/'
  3449. domBuilder.startPrefixMapping(nsPrefix, value)
  3450. }
  3451. }
  3452. var i = el.length;
  3453. while(i--){
  3454. a = el[i];
  3455. var prefix = a.prefix;
  3456. if(prefix){//no prefix attribute has no namespace
  3457. if(prefix === 'xml'){
  3458. a.uri = 'http://www.w3.org/XML/1998/namespace';
  3459. }if(prefix !== 'xmlns'){
  3460. a.uri = currentNSMap[prefix]
  3461. //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
  3462. }
  3463. }
  3464. }
  3465. var nsp = tagName.indexOf(':');
  3466. if(nsp>0){
  3467. prefix = el.prefix = tagName.slice(0,nsp);
  3468. localName = el.localName = tagName.slice(nsp+1);
  3469. }else{
  3470. prefix = null;//important!!
  3471. localName = el.localName = tagName;
  3472. }
  3473. //no prefix element has default namespace
  3474. var ns = el.uri = currentNSMap[prefix || ''];
  3475. domBuilder.startElement(ns,localName,tagName,el);
  3476. //endPrefixMapping and startPrefixMapping have not any help for dom builder
  3477. //localNSMap = null
  3478. if(el.closed){
  3479. domBuilder.endElement(ns,localName,tagName);
  3480. if(localNSMap){
  3481. for(prefix in localNSMap){
  3482. domBuilder.endPrefixMapping(prefix)
  3483. }
  3484. }
  3485. }else{
  3486. el.currentNSMap = currentNSMap;
  3487. el.localNSMap = localNSMap;
  3488. parseStack.push(el);
  3489. }
  3490. }
  3491. function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
  3492. if(/^(?:script|textarea)$/i.test(tagName)){
  3493. var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
  3494. var text = source.substring(elStartEnd+1,elEndStart);
  3495. if(/[&<]/.test(text)){
  3496. if(/^script$/i.test(tagName)){
  3497. //if(!/\]\]>/.test(text)){
  3498. //lexHandler.startCDATA();
  3499. domBuilder.characters(text,0,text.length);
  3500. //lexHandler.endCDATA();
  3501. return elEndStart;
  3502. //}
  3503. }//}else{//text area
  3504. text = text.replace(/&#?\w+;/g,entityReplacer);
  3505. domBuilder.characters(text,0,text.length);
  3506. return elEndStart;
  3507. //}
  3508. }
  3509. }
  3510. return elStartEnd+1;
  3511. }
  3512. function fixSelfClosed(source,elStartEnd,tagName,closeMap){
  3513. //if(tagName in closeMap){
  3514. var pos = closeMap[tagName];
  3515. if(pos == null){
  3516. //console.log(tagName)
  3517. pos = closeMap[tagName] = source.lastIndexOf('</'+tagName+'>')
  3518. }
  3519. return pos<elStartEnd;
  3520. //}
  3521. }
  3522. function _copy(source,target){
  3523. for(var n in source){target[n] = source[n]}
  3524. }
  3525. function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
  3526. var next= source.charAt(start+2)
  3527. switch(next){
  3528. case '-':
  3529. if(source.charAt(start + 3) === '-'){
  3530. var end = source.indexOf('-->',start+4);
  3531. //append comment source.substring(4,end)//<!--
  3532. if(end>start){
  3533. domBuilder.comment(source,start+4,end-start-4);
  3534. return end+3;
  3535. }else{
  3536. errorHandler.error("Unclosed comment");
  3537. return -1;
  3538. }
  3539. }else{
  3540. //error
  3541. return -1;
  3542. }
  3543. default:
  3544. if(source.substr(start+3,6) == 'CDATA['){
  3545. var end = source.indexOf(']]>',start+9);
  3546. domBuilder.startCDATA();
  3547. domBuilder.characters(source,start+9,end-start-9);
  3548. domBuilder.endCDATA()
  3549. return end+3;
  3550. }
  3551. //<!DOCTYPE
  3552. //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
  3553. var matchs = split(source,start);
  3554. var len = matchs.length;
  3555. if(len>1 && /!doctype/i.test(matchs[0][0])){
  3556. var name = matchs[1][0];
  3557. var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0]
  3558. var sysid = len>4 && matchs[4][0];
  3559. var lastMatch = matchs[len-1]
  3560. domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'),
  3561. sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2'));
  3562. domBuilder.endDTD();
  3563. return lastMatch.index+lastMatch[0].length
  3564. }
  3565. }
  3566. return -1;
  3567. }
  3568. function parseInstruction(source,start,domBuilder){
  3569. var end = source.indexOf('?>',start);
  3570. if(end){
  3571. var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
  3572. if(match){
  3573. var len = match[0].length;
  3574. domBuilder.processingInstruction(match[1], match[2]) ;
  3575. return end+2;
  3576. }else{//error
  3577. return -1;
  3578. }
  3579. }
  3580. return -1;
  3581. }
  3582. /**
  3583. * @param source
  3584. */
  3585. function ElementAttributes(source){
  3586. }
  3587. ElementAttributes.prototype = {
  3588. setTagName:function(tagName){
  3589. if(!tagNamePattern.test(tagName)){
  3590. throw new Error('invalid tagName:'+tagName)
  3591. }
  3592. this.tagName = tagName
  3593. },
  3594. add:function(qName,value,offset){
  3595. if(!tagNamePattern.test(qName)){
  3596. throw new Error('invalid attribute:'+qName)
  3597. }
  3598. this[this.length++] = {qName:qName,value:value,offset:offset}
  3599. },
  3600. length:0,
  3601. getLocalName:function(i){return this[i].localName},
  3602. getOffset:function(i){return this[i].offset},
  3603. getQName:function(i){return this[i].qName},
  3604. getURI:function(i){return this[i].uri},
  3605. getValue:function(i){return this[i].value}
  3606. // ,getIndex:function(uri, localName)){
  3607. // if(localName){
  3608. //
  3609. // }else{
  3610. // var qName = uri
  3611. // }
  3612. // },
  3613. // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
  3614. // getType:function(uri,localName){}
  3615. // getType:function(i){},
  3616. }
  3617. function _set_proto_(thiz,parent){
  3618. thiz.__proto__ = parent;
  3619. return thiz;
  3620. }
  3621. if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){
  3622. _set_proto_ = function(thiz,parent){
  3623. function p(){};
  3624. p.prototype = parent;
  3625. p = new p();
  3626. for(parent in thiz){
  3627. p[parent] = thiz[parent];
  3628. }
  3629. return p;
  3630. }
  3631. }
  3632. function split(source,start){
  3633. var match;
  3634. var buf = [];
  3635. var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
  3636. reg.lastIndex = start;
  3637. reg.exec(source);//skip <
  3638. while(match = reg.exec(source)){
  3639. buf.push(match);
  3640. if(match[1])return buf;
  3641. }
  3642. }
  3643. if(typeof require == 'function'){
  3644. exports.XMLReader = XMLReader;
  3645. }
  3646. },{}]},{},[1])(1)
  3647. });