buildModuleUrl-e7952659.js 172 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592
  1. /**
  2. * Cesium - https://github.com/CesiumGS/cesium
  3. *
  4. * Copyright 2011-2020 Cesium Contributors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * Columbus View (Pat. Pend.)
  19. *
  20. * Portions licensed separately.
  21. * See https://github.com/CesiumGS/cesium/blob/master/LICENSE.md for full licensing details.
  22. */
  23. define(['exports', './when-8d13db60', './Check-70bec281', './RuntimeError-ba10bc3e'], function (exports, when, Check, RuntimeError) { 'use strict';
  24. /**
  25. * @license
  26. *
  27. * Grauw URI utilities
  28. *
  29. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  30. *
  31. * @author Laurens Holst (http://www.grauw.nl/)
  32. *
  33. * Copyright 2012 Laurens Holst
  34. *
  35. * Licensed under the Apache License, Version 2.0 (the "License");
  36. * you may not use this file except in compliance with the License.
  37. * You may obtain a copy of the License at
  38. *
  39. * http://www.apache.org/licenses/LICENSE-2.0
  40. *
  41. * Unless required by applicable law or agreed to in writing, software
  42. * distributed under the License is distributed on an "AS IS" BASIS,
  43. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  44. * See the License for the specific language governing permissions and
  45. * limitations under the License.
  46. *
  47. */
  48. /**
  49. * Constructs a URI object.
  50. * @constructor
  51. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  52. * @param {string|URI} uri A string or URI object to create the object from.
  53. */
  54. function URI(uri) {
  55. if (uri instanceof URI) { // copy constructor
  56. this.scheme = uri.scheme;
  57. this.authority = uri.authority;
  58. this.path = uri.path;
  59. this.query = uri.query;
  60. this.fragment = uri.fragment;
  61. } else if (uri) { // uri is URI string or cast to string
  62. var c = parseRegex.exec(uri);
  63. this.scheme = c[1];
  64. this.authority = c[2];
  65. this.path = c[3];
  66. this.query = c[4];
  67. this.fragment = c[5];
  68. }
  69. }
  70. // Initial values on the prototype
  71. URI.prototype.scheme = null;
  72. URI.prototype.authority = null;
  73. URI.prototype.path = '';
  74. URI.prototype.query = null;
  75. URI.prototype.fragment = null;
  76. // Regular expression from RFC 3986 appendix B
  77. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  78. /**
  79. * Returns the scheme part of the URI.
  80. * In "http://example.com:80/a/b?x#y" this is "http".
  81. */
  82. URI.prototype.getScheme = function() {
  83. return this.scheme;
  84. };
  85. /**
  86. * Returns the authority part of the URI.
  87. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  88. */
  89. URI.prototype.getAuthority = function() {
  90. return this.authority;
  91. };
  92. /**
  93. * Returns the path part of the URI.
  94. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  95. * In "mailto:mike@example.com" this is "mike@example.com".
  96. */
  97. URI.prototype.getPath = function() {
  98. return this.path;
  99. };
  100. /**
  101. * Returns the query part of the URI.
  102. * In "http://example.com:80/a/b?x#y" this is "x".
  103. */
  104. URI.prototype.getQuery = function() {
  105. return this.query;
  106. };
  107. /**
  108. * Returns the fragment part of the URI.
  109. * In "http://example.com:80/a/b?x#y" this is "y".
  110. */
  111. URI.prototype.getFragment = function() {
  112. return this.fragment;
  113. };
  114. /**
  115. * Tests whether the URI is an absolute URI.
  116. * See RFC 3986 section 4.3.
  117. */
  118. URI.prototype.isAbsolute = function() {
  119. return !!this.scheme && !this.fragment;
  120. };
  121. ///**
  122. //* Extensive validation of the URI against the ABNF in RFC 3986
  123. //*/
  124. //URI.prototype.validate
  125. /**
  126. * Tests whether the URI is a same-document reference.
  127. * See RFC 3986 section 4.4.
  128. *
  129. * To perform more thorough comparison, you can normalise the URI objects.
  130. */
  131. URI.prototype.isSameDocumentAs = function(uri) {
  132. return uri.scheme == this.scheme &&
  133. uri.authority == this.authority &&
  134. uri.path == this.path &&
  135. uri.query == this.query;
  136. };
  137. /**
  138. * Simple String Comparison of two URIs.
  139. * See RFC 3986 section 6.2.1.
  140. *
  141. * To perform more thorough comparison, you can normalise the URI objects.
  142. */
  143. URI.prototype.equals = function(uri) {
  144. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  145. };
  146. /**
  147. * Normalizes the URI using syntax-based normalization.
  148. * This includes case normalization, percent-encoding normalization and path segment normalization.
  149. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  150. * (Although that would not be a valid URI in the first place. See validate().)
  151. * See RFC 3986 section 6.2.2.
  152. */
  153. URI.prototype.normalize = function() {
  154. this.removeDotSegments();
  155. if (this.scheme)
  156. this.scheme = this.scheme.toLowerCase();
  157. if (this.authority)
  158. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  159. replace(caseRegex, replaceCase);
  160. if (this.path)
  161. this.path = this.path.replace(caseRegex, replaceCase);
  162. if (this.query)
  163. this.query = this.query.replace(caseRegex, replaceCase);
  164. if (this.fragment)
  165. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  166. };
  167. var caseRegex = /%[0-9a-z]{2}/gi;
  168. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  169. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  170. function replaceCase(str) {
  171. var dec = unescape(str);
  172. return percentRegex.test(dec) ? dec : str.toUpperCase();
  173. }
  174. function replaceAuthority(str, p1, p2, p3) {
  175. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  176. }
  177. /**
  178. * Resolve a relative URI (this) against a base URI.
  179. * The base URI must be an absolute URI.
  180. * See RFC 3986 section 5.2
  181. */
  182. URI.prototype.resolve = function(baseURI) {
  183. var uri = new URI();
  184. if (this.scheme) {
  185. uri.scheme = this.scheme;
  186. uri.authority = this.authority;
  187. uri.path = this.path;
  188. uri.query = this.query;
  189. } else {
  190. uri.scheme = baseURI.scheme;
  191. if (this.authority) {
  192. uri.authority = this.authority;
  193. uri.path = this.path;
  194. uri.query = this.query;
  195. } else {
  196. uri.authority = baseURI.authority;
  197. if (this.path == '') {
  198. uri.path = baseURI.path;
  199. uri.query = this.query || baseURI.query;
  200. } else {
  201. if (this.path.charAt(0) == '/') {
  202. uri.path = this.path;
  203. uri.removeDotSegments();
  204. } else {
  205. if (baseURI.authority && baseURI.path == '') {
  206. uri.path = '/' + this.path;
  207. } else {
  208. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  209. }
  210. uri.removeDotSegments();
  211. }
  212. uri.query = this.query;
  213. }
  214. }
  215. }
  216. uri.fragment = this.fragment;
  217. return uri;
  218. };
  219. /**
  220. * Remove dot segments from path.
  221. * See RFC 3986 section 5.2.4
  222. * @private
  223. */
  224. URI.prototype.removeDotSegments = function() {
  225. var input = this.path.split('/'),
  226. output = [],
  227. segment,
  228. absPath = input[0] == '';
  229. if (absPath)
  230. input.shift();
  231. var sFirst = input[0] == '' ? input.shift() : null;
  232. while (input.length) {
  233. segment = input.shift();
  234. if (segment == '..') {
  235. output.pop();
  236. } else if (segment != '.') {
  237. output.push(segment);
  238. }
  239. }
  240. if (segment == '.' || segment == '..')
  241. output.push('');
  242. if (absPath)
  243. output.unshift('');
  244. this.path = output.join('/');
  245. };
  246. // We don't like this function because it builds up a cache that is never cleared.
  247. // /**
  248. // * Resolves a relative URI against an absolute base URI.
  249. // * Convenience method.
  250. // * @param {String} uri the relative URI to resolve
  251. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  252. // */
  253. // URI.resolve = function(sURI, sBaseURI) {
  254. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  255. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  256. // return uri.resolve(baseURI).toString();
  257. // };
  258. // var cache = {};
  259. /**
  260. * Serialises the URI to a string.
  261. */
  262. URI.prototype.toString = function() {
  263. var result = '';
  264. if (this.scheme)
  265. result += this.scheme + ':';
  266. if (this.authority)
  267. result += '//' + this.authority;
  268. result += this.path;
  269. if (this.query)
  270. result += '?' + this.query;
  271. if (this.fragment)
  272. result += '#' + this.fragment;
  273. return result;
  274. };
  275. /**
  276. * @private
  277. */
  278. function appendForwardSlash(url) {
  279. if (url.length === 0 || url[url.length - 1] !== '/') {
  280. url = url + '/';
  281. }
  282. return url;
  283. }
  284. /**
  285. * Clones an object, returning a new object containing the same properties.
  286. *
  287. * @exports clone
  288. *
  289. * @param {Object} object The object to clone.
  290. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  291. * @returns {Object} The cloned object.
  292. */
  293. function clone(object, deep) {
  294. if (object === null || typeof object !== 'object') {
  295. return object;
  296. }
  297. deep = when.defaultValue(deep, false);
  298. var result = new object.constructor();
  299. for ( var propertyName in object) {
  300. if (object.hasOwnProperty(propertyName)) {
  301. var value = object[propertyName];
  302. if (deep) {
  303. value = clone(value, deep);
  304. }
  305. result[propertyName] = value;
  306. }
  307. }
  308. return result;
  309. }
  310. /**
  311. * Merges two objects, copying their properties onto a new combined object. When two objects have the same
  312. * property, the value of the property on the first object is used. If either object is undefined,
  313. * it will be treated as an empty object.
  314. *
  315. * @example
  316. * var object1 = {
  317. * propOne : 1,
  318. * propTwo : {
  319. * value1 : 10
  320. * }
  321. * }
  322. * var object2 = {
  323. * propTwo : 2
  324. * }
  325. * var final = Cesium.combine(object1, object2);
  326. *
  327. * // final === {
  328. * // propOne : 1,
  329. * // propTwo : {
  330. * // value1 : 10
  331. * // }
  332. * // }
  333. *
  334. * @param {Object} [object1] The first object to merge.
  335. * @param {Object} [object2] The second object to merge.
  336. * @param {Boolean} [deep=false] Perform a recursive merge.
  337. * @returns {Object} The combined object containing all properties from both objects.
  338. *
  339. * @exports combine
  340. */
  341. function combine(object1, object2, deep) {
  342. deep = when.defaultValue(deep, false);
  343. var result = {};
  344. var object1Defined = when.defined(object1);
  345. var object2Defined = when.defined(object2);
  346. var property;
  347. var object1Value;
  348. var object2Value;
  349. if (object1Defined) {
  350. for (property in object1) {
  351. if (object1.hasOwnProperty(property)) {
  352. object1Value = object1[property];
  353. if (object2Defined && deep && typeof object1Value === 'object' && object2.hasOwnProperty(property)) {
  354. object2Value = object2[property];
  355. if (typeof object2Value === 'object') {
  356. result[property] = combine(object1Value, object2Value, deep);
  357. } else {
  358. result[property] = object1Value;
  359. }
  360. } else {
  361. result[property] = object1Value;
  362. }
  363. }
  364. }
  365. }
  366. if (object2Defined) {
  367. for (property in object2) {
  368. if (object2.hasOwnProperty(property) && !result.hasOwnProperty(property)) {
  369. object2Value = object2[property];
  370. result[property] = object2Value;
  371. }
  372. }
  373. }
  374. return result;
  375. }
  376. /**
  377. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  378. * @exports getAbsoluteUri
  379. *
  380. * @param {String} relative The relative Uri.
  381. * @param {String} [base] The base Uri.
  382. * @returns {String} The absolute Uri of the given relative Uri.
  383. *
  384. * @example
  385. * //absolute Uri will be "https://test.com/awesome.png";
  386. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  387. */
  388. function getAbsoluteUri(relative, base) {
  389. var documentObject;
  390. if (typeof document !== 'undefined') {
  391. documentObject = document;
  392. }
  393. return getAbsoluteUri._implementation(relative, base, documentObject);
  394. }
  395. getAbsoluteUri._implementation = function(relative, base, documentObject) {
  396. //>>includeStart('debug', pragmas.debug);
  397. if (!when.defined(relative)) {
  398. throw new Check.DeveloperError('relative uri is required.');
  399. }
  400. //>>includeEnd('debug');
  401. if (!when.defined(base)) {
  402. if (typeof documentObject === 'undefined') {
  403. return relative;
  404. }
  405. base = when.defaultValue(documentObject.baseURI, documentObject.location.href);
  406. }
  407. var baseUri = new URI(base);
  408. var relativeUri = new URI(relative);
  409. return relativeUri.resolve(baseUri).toString();
  410. };
  411. /**
  412. * Given a URI, returns the base path of the URI.
  413. * @exports getBaseUri
  414. *
  415. * @param {String} uri The Uri.
  416. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  417. * @returns {String} The base path of the Uri.
  418. *
  419. * @example
  420. * // basePath will be "/Gallery/";
  421. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false');
  422. *
  423. * // basePath will be "/Gallery/?value=true&example=false";
  424. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false', true);
  425. */
  426. function getBaseUri(uri, includeQuery) {
  427. //>>includeStart('debug', pragmas.debug);
  428. if (!when.defined(uri)) {
  429. throw new Check.DeveloperError('uri is required.');
  430. }
  431. //>>includeEnd('debug');
  432. var basePath = '';
  433. var i = uri.lastIndexOf('/');
  434. if (i !== -1) {
  435. basePath = uri.substring(0, i + 1);
  436. }
  437. if (!includeQuery) {
  438. return basePath;
  439. }
  440. uri = new URI(uri);
  441. if (when.defined(uri.query)) {
  442. basePath += '?' + uri.query;
  443. }
  444. if (when.defined(uri.fragment)){
  445. basePath += '#' + uri.fragment;
  446. }
  447. return basePath;
  448. }
  449. /**
  450. * Given a URI, returns the extension of the URI.
  451. * @exports getExtensionFromUri
  452. *
  453. * @param {String} uri The Uri.
  454. * @returns {String} The extension of the Uri.
  455. *
  456. * @example
  457. * //extension will be "czml";
  458. * var extension = Cesium.getExtensionFromUri('/Gallery/simple.czml?value=true&example=false');
  459. */
  460. function getExtensionFromUri(uri) {
  461. //>>includeStart('debug', pragmas.debug);
  462. if (!when.defined(uri)) {
  463. throw new Check.DeveloperError('uri is required.');
  464. }
  465. //>>includeEnd('debug');
  466. var uriObject = new URI(uri);
  467. uriObject.normalize();
  468. var path = uriObject.path;
  469. var index = path.lastIndexOf('/');
  470. if (index !== -1) {
  471. path = path.substr(index + 1);
  472. }
  473. index = path.lastIndexOf('.');
  474. if (index === -1) {
  475. path = '';
  476. } else {
  477. path = path.substr(index + 1);
  478. }
  479. return path;
  480. }
  481. var blobUriRegex = /^blob:/i;
  482. /**
  483. * Determines if the specified uri is a blob uri.
  484. *
  485. * @exports isBlobUri
  486. *
  487. * @param {String} uri The uri to test.
  488. * @returns {Boolean} true when the uri is a blob uri; otherwise, false.
  489. *
  490. * @private
  491. */
  492. function isBlobUri(uri) {
  493. //>>includeStart('debug', pragmas.debug);
  494. Check.Check.typeOf.string('uri', uri);
  495. //>>includeEnd('debug');
  496. return blobUriRegex.test(uri);
  497. }
  498. var a;
  499. /**
  500. * Given a URL, determine whether that URL is considered cross-origin to the current page.
  501. *
  502. * @private
  503. */
  504. function isCrossOriginUrl(url) {
  505. if (!when.defined(a)) {
  506. a = document.createElement('a');
  507. }
  508. // copy window location into the anchor to get consistent results
  509. // when the port is default for the protocol (e.g. 80 for HTTP)
  510. a.href = window.location.href;
  511. // host includes both hostname and port if the port is not standard
  512. var host = a.host;
  513. var protocol = a.protocol;
  514. a.href = url;
  515. // IE only absolutizes href on get, not set
  516. a.href = a.href; // eslint-disable-line no-self-assign
  517. return protocol !== a.protocol || host !== a.host;
  518. }
  519. var dataUriRegex = /^data:/i;
  520. /**
  521. * Determines if the specified uri is a data uri.
  522. *
  523. * @exports isDataUri
  524. *
  525. * @param {String} uri The uri to test.
  526. * @returns {Boolean} true when the uri is a data uri; otherwise, false.
  527. *
  528. * @private
  529. */
  530. function isDataUri(uri) {
  531. //>>includeStart('debug', pragmas.debug);
  532. Check.Check.typeOf.string('uri', uri);
  533. //>>includeEnd('debug');
  534. return dataUriRegex.test(uri);
  535. }
  536. /**
  537. * @private
  538. */
  539. function loadAndExecuteScript(url) {
  540. var deferred = when.when.defer();
  541. var script = document.createElement('script');
  542. script.async = true;
  543. script.src = url;
  544. var head = document.getElementsByTagName('head')[0];
  545. script.onload = function() {
  546. script.onload = undefined;
  547. head.removeChild(script);
  548. deferred.resolve();
  549. };
  550. script.onerror = function(e) {
  551. deferred.reject(e);
  552. };
  553. head.appendChild(script);
  554. return deferred.promise;
  555. }
  556. /**
  557. * Converts an object representing a set of name/value pairs into a query string,
  558. * with names and values encoded properly for use in a URL. Values that are arrays
  559. * will produce multiple values with the same name.
  560. * @exports objectToQuery
  561. *
  562. * @param {Object} obj The object containing data to encode.
  563. * @returns {String} An encoded query string.
  564. *
  565. *
  566. * @example
  567. * var str = Cesium.objectToQuery({
  568. * key1 : 'some value',
  569. * key2 : 'a/b',
  570. * key3 : ['x', 'y']
  571. * });
  572. *
  573. * @see queryToObject
  574. * // str will be:
  575. * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
  576. */
  577. function objectToQuery(obj, donotEncodeSpecialCharacters) {
  578. //>>includeStart('debug', pragmas.debug);
  579. if (!when.defined(obj)) {
  580. throw new Check.DeveloperError('obj is required.');
  581. }
  582. //>>includeEnd('debug');
  583. var result = '';
  584. for ( var propName in obj) {
  585. if (obj.hasOwnProperty(propName)) {
  586. var value = obj[propName];
  587. var part = encodeURIComponent(propName) + '=';
  588. if (Array.isArray(value)) {
  589. for (var i = 0, len = value.length; i < len; ++i) {
  590. if (donotEncodeSpecialCharacters === true) {
  591. result += part + encodeURI(value[i]) + '&';
  592. } else {
  593. result += part + encodeURIComponent(value[i]) + '&';
  594. }
  595. }
  596. } else {
  597. if (donotEncodeSpecialCharacters === true) {
  598. result += part + encodeURI(value) + '&';
  599. } else {
  600. result += part + encodeURIComponent(value) + '&';
  601. }
  602. }
  603. }
  604. }
  605. // trim last &
  606. result = result.slice(0, -1);
  607. // This function used to replace %20 with + which is more compact and readable.
  608. // However, some servers didn't properly handle + as a space.
  609. // https://github.com/CesiumGS/cesium/issues/2192
  610. return result;
  611. }
  612. /**
  613. * Parses a query string into an object, where the keys and values of the object are the
  614. * name/value pairs from the query string, decoded. If a name appears multiple times,
  615. * the value in the object will be an array of values.
  616. * @exports queryToObject
  617. *
  618. * @param {String} queryString The query string.
  619. * @returns {Object} An object containing the parameters parsed from the query string.
  620. *
  621. *
  622. * @example
  623. * var obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
  624. * // obj will be:
  625. * // {
  626. * // key1 : 'some value',
  627. * // key2 : 'a/b',
  628. * // key3 : ['x', 'y']
  629. * // }
  630. *
  631. * @see objectToQuery
  632. */
  633. function queryToObject(queryString) {
  634. //>>includeStart('debug', pragmas.debug);
  635. if (!when.defined(queryString)) {
  636. throw new Check.DeveloperError('queryString is required.');
  637. }
  638. //>>includeEnd('debug');
  639. var result = {};
  640. if (queryString === '') {
  641. return result;
  642. }
  643. var parts = queryString.replace(/\+/g, '%20').split(/[&;]/);
  644. for (var i = 0, len = parts.length; i < len; ++i) {
  645. var subparts = parts[i].split('=');
  646. if (subparts.length > 2) {
  647. var index = parts[i].indexOf("=");
  648. var key = parts[i].substring(0, index);
  649. var strvalue = parts[i].substring(index + 1, parts[i].length);
  650. subparts = [key, strvalue];
  651. }
  652. var name = decodeURIComponent(subparts[0]);
  653. var value = subparts[1];
  654. if (when.defined(value)) {
  655. value = decodeURIComponent(value);
  656. } else {
  657. value = '';
  658. }
  659. var resultValue = result[name];
  660. if (typeof resultValue === 'string') {
  661. // expand the single value to an array
  662. result[name] = [resultValue, value];
  663. } else if (Array.isArray(resultValue)) {
  664. resultValue.push(value);
  665. } else {
  666. result[name] = value;
  667. }
  668. }
  669. return result;
  670. }
  671. /**
  672. * State of the request.
  673. *
  674. * @exports RequestState
  675. */
  676. var RequestState = {
  677. /**
  678. * Initial unissued state.
  679. *
  680. * @type Number
  681. * @constant
  682. */
  683. UNISSUED : 0,
  684. /**
  685. * Issued but not yet active. Will become active when open slots are available.
  686. *
  687. * @type Number
  688. * @constant
  689. */
  690. ISSUED : 1,
  691. /**
  692. * Actual http request has been sent.
  693. *
  694. * @type Number
  695. * @constant
  696. */
  697. ACTIVE : 2,
  698. /**
  699. * Request completed successfully.
  700. *
  701. * @type Number
  702. * @constant
  703. */
  704. RECEIVED : 3,
  705. /**
  706. * Request was cancelled, either explicitly or automatically because of low priority.
  707. *
  708. * @type Number
  709. * @constant
  710. */
  711. CANCELLED : 4,
  712. /**
  713. * Request failed.
  714. *
  715. * @type Number
  716. * @constant
  717. */
  718. FAILED : 5
  719. };
  720. var RequestState$1 = Object.freeze(RequestState);
  721. /**
  722. * An enum identifying the type of request. Used for finer grained logging and priority sorting.
  723. *
  724. * @exports RequestType
  725. */
  726. var RequestType = {
  727. /**
  728. * Terrain request.
  729. *
  730. * @type Number
  731. * @constant
  732. */
  733. TERRAIN : 0,
  734. /**
  735. * Imagery request.
  736. *
  737. * @type Number
  738. * @constant
  739. */
  740. IMAGERY : 1,
  741. /**
  742. * 3D Tiles request.
  743. *
  744. * @type Number
  745. * @constant
  746. */
  747. TILES3D : 2,
  748. /**
  749. * Other request.
  750. *
  751. * @type Number
  752. * @constant
  753. */
  754. OTHER : 3,
  755. PACK : 4,
  756. BLOCK : 5,
  757. BLOCKPACK : 6
  758. };
  759. var RequestType$1 = Object.freeze(RequestType);
  760. /**
  761. * Stores information for making a request. In general this does not need to be constructed directly.
  762. *
  763. * @alias Request
  764. * @constructor
  765. * @namespace
  766. * @exports Request
  767. * @param {Object} [options] An object with the following properties:
  768. * @param {String} [options.url] The url to request.
  769. * @param {Request~RequestCallback} [options.requestFunction] The function that makes the actual data request.
  770. * @param {Request~CancelCallback} [options.cancelFunction] The function that is called when the request is cancelled.
  771. * @param {Request~PriorityCallback} [options.priorityFunction] The function that is called to update the request's priority, which occurs once per frame.
  772. * @param {Number} [options.priority=0.0] The initial priority of the request.
  773. * @param {Boolean} [options.throttle=false] Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the request will be throttled and sent based on priority.
  774. * @param {Boolean} [options.throttleByServer=false] Whether to throttle the request by server.
  775. * @param {RequestType} [options.type=RequestType.OTHER] The type of request.
  776. */
  777. function Request(options) {
  778. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  779. var throttleByServer = when.defaultValue(options.throttleByServer, false);
  780. var throttle = when.defaultValue(options.throttle, false);
  781. /**
  782. * The URL to request.
  783. *
  784. * @type {String}
  785. */
  786. this.url = options.url;
  787. /**
  788. * The function that makes the actual data request.
  789. *
  790. * @type {Request~RequestCallback}
  791. */
  792. this.requestFunction = options.requestFunction;
  793. /**
  794. * The function that is called when the request is cancelled.
  795. *
  796. * @type {Request~CancelCallback}
  797. */
  798. this.cancelFunction = options.cancelFunction;
  799. /**
  800. * The function that is called to update the request's priority, which occurs once per frame.
  801. *
  802. * @type {Request~PriorityCallback}
  803. */
  804. this.priorityFunction = options.priorityFunction;
  805. /**
  806. * Priority is a unit-less value where lower values represent higher priority.
  807. * For world-based objects, this is usually the distance from the camera.
  808. * A request that does not have a priority function defaults to a priority of 0.
  809. *
  810. * If priorityFunction is defined, this value is updated every frame with the result of that call.
  811. *
  812. * @type {Number}
  813. * @default 0.0
  814. */
  815. this.priority = when.defaultValue(options.priority, 0.0);
  816. /**
  817. * Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the
  818. * request will be throttled and sent based on priority.
  819. *
  820. * @type {Boolean}
  821. * @readonly
  822. *
  823. * @default false
  824. */
  825. this.throttle = throttle;
  826. /**
  827. * Whether to throttle the request by server. Browsers typically support about 6-8 parallel connections
  828. * for HTTP/1 servers, and an unlimited amount of connections for HTTP/2 servers. Setting this value
  829. * to <code>true</code> is preferable for requests going through HTTP/1 servers.
  830. *
  831. * @type {Boolean}
  832. * @readonly
  833. *
  834. * @default false
  835. */
  836. this.throttleByServer = throttleByServer;
  837. /**
  838. * Type of request.
  839. *
  840. * @type {RequestType}
  841. * @readonly
  842. *
  843. * @default RequestType.OTHER
  844. */
  845. this.type = when.defaultValue(options.type, RequestType$1.OTHER);
  846. /**
  847. * A key used to identify the server that a request is going to. It is derived from the url's authority and scheme.
  848. *
  849. * @type {String}
  850. *
  851. * @private
  852. */
  853. this.serverKey = undefined;
  854. /**
  855. * The current state of the request.
  856. *
  857. * @type {RequestState}
  858. * @readonly
  859. */
  860. this.state = RequestState$1.UNISSUED;
  861. /**
  862. * The requests's deferred promise.
  863. *
  864. * @type {Object}
  865. *
  866. * @private
  867. */
  868. this.deferred = undefined;
  869. /**
  870. * Whether the request was explicitly cancelled.
  871. *
  872. * @type {Boolean}
  873. *
  874. * @private
  875. */
  876. this.cancelled = false;
  877. }
  878. /**
  879. * Mark the request as cancelled.
  880. *
  881. * @private
  882. */
  883. Request.prototype.cancel = function() {
  884. this.cancelled = true;
  885. };
  886. /**
  887. * Duplicates a Request instance.
  888. *
  889. * @param {Request} [result] The object onto which to store the result.
  890. *
  891. * @returns {Request} The modified result parameter or a new Resource instance if one was not provided.
  892. */
  893. Request.prototype.clone = function(result) {
  894. if (!when.defined(result)) {
  895. return new Request(this);
  896. }
  897. result.url = this.url;
  898. result.requestFunction = this.requestFunction;
  899. result.cancelFunction = this.cancelFunction;
  900. result.priorityFunction = this.priorityFunction;
  901. result.priority = this.priority;
  902. result.throttle = this.throttle;
  903. result.throttleByServer = this.throttleByServer;
  904. result.type = this.type;
  905. result.serverKey = this.serverKey;
  906. // These get defaulted because the cloned request hasn't been issued
  907. result.state = this.RequestState.UNISSUED;
  908. result.deferred = undefined;
  909. result.cancelled = false;
  910. return result;
  911. };
  912. /**
  913. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  914. * a dictionary.
  915. *
  916. * @exports parseResponseHeaders
  917. *
  918. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  919. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  920. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  921. * is that header's value.
  922. *
  923. * @private
  924. */
  925. function parseResponseHeaders(headerString) {
  926. var headers = {};
  927. if (!headerString) {
  928. return headers;
  929. }
  930. var headerPairs = headerString.split('\u000d\u000a');
  931. for (var i = 0; i < headerPairs.length; ++i) {
  932. var headerPair = headerPairs[i];
  933. // Can't use split() here because it does the wrong thing
  934. // if the header value has the string ": " in it.
  935. var index = headerPair.indexOf('\u003a\u0020');
  936. if (index > 0) {
  937. var key = headerPair.substring(0, index);
  938. var val = headerPair.substring(index + 2);
  939. headers[key] = val;
  940. }
  941. }
  942. return headers;
  943. }
  944. /**
  945. * An event that is raised when a request encounters an error.
  946. *
  947. * @constructor
  948. * @alias RequestErrorEvent
  949. *
  950. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  951. * @param {Object} [response] The response included along with the error.
  952. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  953. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  954. */
  955. function RequestErrorEvent(statusCode, response, responseHeaders) {
  956. /**
  957. * The HTTP error status code, such as 404. If the error does not have a particular
  958. * HTTP code, this property will be undefined.
  959. *
  960. * @type {Number}
  961. */
  962. this.statusCode = statusCode;
  963. /**
  964. * The response included along with the error. If the error does not include a response,
  965. * this property will be undefined.
  966. *
  967. * @type {Object}
  968. */
  969. this.response = response;
  970. /**
  971. * The headers included in the response, represented as an object literal of key/value pairs.
  972. * If the error does not include any headers, this property will be undefined.
  973. *
  974. * @type {Object}
  975. */
  976. this.responseHeaders = responseHeaders;
  977. if (typeof this.responseHeaders === 'string') {
  978. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  979. }
  980. }
  981. /**
  982. * Creates a string representing this RequestErrorEvent.
  983. * @memberof RequestErrorEvent
  984. *
  985. * @returns {String} A string representing the provided RequestErrorEvent.
  986. */
  987. RequestErrorEvent.prototype.toString = function() {
  988. var str = 'Request has failed.';
  989. if (when.defined(this.statusCode)) {
  990. str += ' Status Code: ' + this.statusCode;
  991. }
  992. return str;
  993. };
  994. /**
  995. * A generic utility class for managing subscribers for a particular event.
  996. * This class is usually instantiated inside of a container class and
  997. * exposed as a property for others to subscribe to.
  998. *
  999. * @alias Event
  1000. * @constructor
  1001. * @example
  1002. * MyObject.prototype.myListener = function(arg1, arg2) {
  1003. * this.myArg1Copy = arg1;
  1004. * this.myArg2Copy = arg2;
  1005. * }
  1006. *
  1007. * var myObjectInstance = new MyObject();
  1008. * var evt = new Cesium.Event();
  1009. * evt.addEventListener(MyObject.prototype.myListener, myObjectInstance);
  1010. * evt.raiseEvent('1', '2');
  1011. * evt.removeEventListener(MyObject.prototype.myListener);
  1012. */
  1013. function Event() {
  1014. this._listeners = [];
  1015. this._scopes = [];
  1016. this._toRemove = [];
  1017. this._insideRaiseEvent = false;
  1018. }
  1019. Object.defineProperties(Event.prototype, {
  1020. /**
  1021. * The number of listeners currently subscribed to the event.
  1022. * @memberof Event.prototype
  1023. * @type {Number}
  1024. * @readonly
  1025. */
  1026. numberOfListeners : {
  1027. get : function() {
  1028. return this._listeners.length - this._toRemove.length;
  1029. }
  1030. }
  1031. });
  1032. /**
  1033. * Registers a callback function to be executed whenever the event is raised.
  1034. * An optional scope can be provided to serve as the <code>this</code> pointer
  1035. * in which the function will execute.
  1036. *
  1037. * @param {Function} listener The function to be executed when the event is raised.
  1038. * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
  1039. * pointer in which the listener function will execute.
  1040. * @returns {Event~RemoveCallback} A function that will remove this event listener when invoked.
  1041. *
  1042. * @see Event#raiseEvent
  1043. * @see Event#removeEventListener
  1044. */
  1045. Event.prototype.addEventListener = function(listener, scope) {
  1046. //>>includeStart('debug', pragmas.debug);
  1047. Check.Check.typeOf.func('listener', listener);
  1048. //>>includeEnd('debug');
  1049. this._listeners.push(listener);
  1050. this._scopes.push(scope);
  1051. var event = this;
  1052. return function() {
  1053. event.removeEventListener(listener, scope);
  1054. };
  1055. };
  1056. /**
  1057. * Unregisters a previously registered callback.
  1058. *
  1059. * @param {Function} listener The function to be unregistered.
  1060. * @param {Object} [scope] The scope that was originally passed to addEventListener.
  1061. * @returns {Boolean} <code>true</code> if the listener was removed; <code>false</code> if the listener and scope are not registered with the event.
  1062. *
  1063. * @see Event#addEventListener
  1064. * @see Event#raiseEvent
  1065. */
  1066. Event.prototype.removeEventListener = function(listener, scope) {
  1067. //>>includeStart('debug', pragmas.debug);
  1068. Check.Check.typeOf.func('listener', listener);
  1069. //>>includeEnd('debug');
  1070. var listeners = this._listeners;
  1071. var scopes = this._scopes;
  1072. var index = -1;
  1073. for (var i = 0; i < listeners.length; i++) {
  1074. if (listeners[i] === listener && scopes[i] === scope) {
  1075. index = i;
  1076. break;
  1077. }
  1078. }
  1079. if (index !== -1) {
  1080. if (this._insideRaiseEvent) {
  1081. //In order to allow removing an event subscription from within
  1082. //a callback, we don't actually remove the items here. Instead
  1083. //remember the index they are at and undefined their value.
  1084. this._toRemove.push(index);
  1085. listeners[index] = undefined;
  1086. scopes[index] = undefined;
  1087. } else {
  1088. listeners.splice(index, 1);
  1089. scopes.splice(index, 1);
  1090. }
  1091. return true;
  1092. }
  1093. return false;
  1094. };
  1095. function compareNumber(a,b) {
  1096. return b - a;
  1097. }
  1098. /**
  1099. * Raises the event by calling each registered listener with all supplied arguments.
  1100. *
  1101. * @param {*} arguments This method takes any number of parameters and passes them through to the listener functions.
  1102. *
  1103. * @see Event#addEventListener
  1104. * @see Event#removeEventListener
  1105. */
  1106. Event.prototype.raiseEvent = function() {
  1107. this._insideRaiseEvent = true;
  1108. var i;
  1109. var listeners = this._listeners;
  1110. var scopes = this._scopes;
  1111. var length = listeners.length;
  1112. for (i = 0; i < length; i++) {
  1113. var listener = listeners[i];
  1114. if (when.defined(listener)) {
  1115. listeners[i].apply(scopes[i], arguments);
  1116. }
  1117. }
  1118. //Actually remove items removed in removeEventListener.
  1119. var toRemove = this._toRemove;
  1120. length = toRemove.length;
  1121. if (length > 0) {
  1122. toRemove.sort(compareNumber);
  1123. for (i = 0; i < length; i++) {
  1124. var index = toRemove[i];
  1125. listeners.splice(index, 1);
  1126. scopes.splice(index, 1);
  1127. }
  1128. toRemove.length = 0;
  1129. }
  1130. this._insideRaiseEvent = false;
  1131. };
  1132. /**
  1133. * Array implementation of a heap.
  1134. *
  1135. * @alias Heap
  1136. * @constructor
  1137. * @private
  1138. *
  1139. * @param {Object} options Object with the following properties:
  1140. * @param {Heap~ComparatorCallback} options.comparator The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
  1141. */
  1142. function Heap(options) {
  1143. //>>includeStart('debug', pragmas.debug);
  1144. Check.Check.typeOf.object('options', options);
  1145. Check.Check.defined('options.comparator', options.comparator);
  1146. //>>includeEnd('debug');
  1147. this._comparator = options.comparator;
  1148. this._array = [];
  1149. this._length = 0;
  1150. this._maximumLength = undefined;
  1151. }
  1152. Object.defineProperties(Heap.prototype, {
  1153. /**
  1154. * Gets the length of the heap.
  1155. *
  1156. * @memberof Heap.prototype
  1157. *
  1158. * @type {Number}
  1159. * @readonly
  1160. */
  1161. length : {
  1162. get : function() {
  1163. return this._length;
  1164. }
  1165. },
  1166. /**
  1167. * Gets the internal array.
  1168. *
  1169. * @memberof Heap.prototype
  1170. *
  1171. * @type {Array}
  1172. * @readonly
  1173. */
  1174. internalArray : {
  1175. get : function() {
  1176. return this._array;
  1177. }
  1178. },
  1179. /**
  1180. * Gets and sets the maximum length of the heap.
  1181. *
  1182. * @memberof Heap.prototype
  1183. *
  1184. * @type {Number}
  1185. */
  1186. maximumLength : {
  1187. get : function() {
  1188. return this._maximumLength;
  1189. },
  1190. set : function(value) {
  1191. this._maximumLength = value;
  1192. if (this._length > value && value > 0) {
  1193. this._length = value;
  1194. this._array.length = value;
  1195. }
  1196. }
  1197. },
  1198. /**
  1199. * The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
  1200. *
  1201. * @memberof Heap.prototype
  1202. *
  1203. * @type {Heap~ComparatorCallback}
  1204. */
  1205. comparator : {
  1206. get : function() {
  1207. return this._comparator;
  1208. }
  1209. }
  1210. });
  1211. function swap(array, a, b) {
  1212. var temp = array[a];
  1213. array[a] = array[b];
  1214. array[b] = temp;
  1215. }
  1216. /**
  1217. * Resizes the internal array of the heap.
  1218. *
  1219. * @param {Number} [length] The length to resize internal array to. Defaults to the current length of the heap.
  1220. */
  1221. Heap.prototype.reserve = function(length) {
  1222. length = when.defaultValue(length, this._length);
  1223. this._array.length = length;
  1224. };
  1225. /**
  1226. * Update the heap so that index and all descendants satisfy the heap property.
  1227. *
  1228. * @param {Number} [index=0] The starting index to heapify from.
  1229. */
  1230. Heap.prototype.heapify = function(index) {
  1231. index = when.defaultValue(index, 0);
  1232. var length = this._length;
  1233. var comparator = this._comparator;
  1234. var array = this._array;
  1235. var candidate = -1;
  1236. var inserting = true;
  1237. while (inserting) {
  1238. var right = 2 * (index + 1);
  1239. var left = right - 1;
  1240. if (left < length && comparator(array[left], array[index]) < 0) {
  1241. candidate = left;
  1242. } else {
  1243. candidate = index;
  1244. }
  1245. if (right < length && comparator(array[right], array[candidate]) < 0) {
  1246. candidate = right;
  1247. }
  1248. if (candidate !== index) {
  1249. swap(array, candidate, index);
  1250. index = candidate;
  1251. } else {
  1252. inserting = false;
  1253. }
  1254. }
  1255. };
  1256. /**
  1257. * Resort the heap.
  1258. */
  1259. Heap.prototype.resort = function() {
  1260. var length = this._length;
  1261. for (var i = Math.ceil(length / 2); i >= 0; --i) {
  1262. this.heapify(i);
  1263. }
  1264. };
  1265. /**
  1266. * Insert an element into the heap. If the length would grow greater than maximumLength
  1267. * of the heap, extra elements are removed.
  1268. *
  1269. * @param {*} element The element to insert
  1270. *
  1271. * @return {*} The element that was removed from the heap if the heap is at full capacity.
  1272. */
  1273. Heap.prototype.insert = function(element) {
  1274. //>>includeStart('debug', pragmas.debug);
  1275. Check.Check.defined('element', element);
  1276. //>>includeEnd('debug');
  1277. var array = this._array;
  1278. var comparator = this._comparator;
  1279. var maximumLength = this._maximumLength;
  1280. var index = this._length++;
  1281. if (index < array.length) {
  1282. array[index] = element;
  1283. } else {
  1284. array.push(element);
  1285. }
  1286. while (index !== 0) {
  1287. var parent = Math.floor((index - 1) / 2);
  1288. if (comparator(array[index], array[parent]) < 0) {
  1289. swap(array, index, parent);
  1290. index = parent;
  1291. } else {
  1292. break;
  1293. }
  1294. }
  1295. var removedElement;
  1296. if (when.defined(maximumLength) && (this._length > maximumLength)) {
  1297. removedElement = array[maximumLength];
  1298. array.pop();
  1299. this._length = maximumLength;
  1300. }
  1301. return removedElement;
  1302. };
  1303. /**
  1304. * Remove the element specified by index from the heap and return it.
  1305. *
  1306. * @param {Number} [index=0] The index to remove.
  1307. * @returns {*} The specified element of the heap.
  1308. */
  1309. Heap.prototype.pop = function(index) {
  1310. index = when.defaultValue(index, 0);
  1311. if (this._length === 0) {
  1312. return undefined;
  1313. }
  1314. //>>includeStart('debug', pragmas.debug);
  1315. Check.Check.typeOf.number.lessThan('index', index, this._length);
  1316. //>>includeEnd('debug');
  1317. var array = this._array;
  1318. var root = array[index];
  1319. swap(array, index, --this._length);
  1320. array[this._length] = undefined;
  1321. this.heapify(index);
  1322. return root;
  1323. };
  1324. /**
  1325. * Gets a timestamp that can be used in measuring the time between events. Timestamps
  1326. * are expressed in milliseconds, but it is not specified what the milliseconds are
  1327. * measured from. This function uses performance.now() if it is available, or Date.now()
  1328. * otherwise.
  1329. *
  1330. * @exports getTimestamp
  1331. *
  1332. * @returns {Number} The timestamp in milliseconds since some unspecified reference time.
  1333. */
  1334. var getTimestamp;
  1335. if (typeof performance !== 'undefined' && typeof performance.now === 'function' && isFinite(performance.now())) {
  1336. getTimestamp = function() {
  1337. return performance.now();
  1338. };
  1339. } else {
  1340. getTimestamp = function() {
  1341. return Date.now();
  1342. };
  1343. }
  1344. var getTimestamp$1 = getTimestamp;
  1345. function sortRequests(a, b) {
  1346. return a.priority - b.priority;
  1347. }
  1348. var statistics = {
  1349. numberOfAttemptedRequests : 0,
  1350. numberOfActiveRequests : 0,
  1351. numberOfCancelledRequests : 0,
  1352. numberOfCancelledActiveRequests : 0,
  1353. numberOfFailedRequests : 0,
  1354. numberOfActiveRequestsEver : 0,
  1355. lastNumberOfActiveRequests : 0,
  1356. totalRequestTime : 0
  1357. };
  1358. var priorityHeapLength = 20;
  1359. var requestHeap = new Heap({
  1360. comparator : sortRequests
  1361. });
  1362. requestHeap.maximumLength = priorityHeapLength;
  1363. requestHeap.reserve(priorityHeapLength);
  1364. var activeRequests = [];
  1365. var numberOfActiveRequestsByServer = {};
  1366. var pageUri = typeof document !== 'undefined' ? new URI(document.location.href) : new URI();
  1367. var requestCompletedEvent = new Event();
  1368. /**
  1369. * Tracks the number of active requests and prioritizes incoming requests.
  1370. *
  1371. * @exports RequestScheduler
  1372. *
  1373. * @private
  1374. */
  1375. function RequestScheduler() {
  1376. }
  1377. RequestScheduler.statisticRequestTime = -1;
  1378. /**
  1379. * The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
  1380. * @type {Number}
  1381. * @default 50
  1382. */
  1383. RequestScheduler.maximumRequests = 50;
  1384. /**
  1385. * The maximum number of simultaneous active requests per server. Un-throttled requests or servers specifically
  1386. * listed in requestsByServer do not observe this limit.
  1387. * @type {Number}
  1388. * @default 6
  1389. */
  1390. RequestScheduler.maximumRequestsPerServer = 6;
  1391. RequestScheduler.perPacketCount = 20;//批量下载,每帧每个包的最大请求数限制,默认是20,不超过120
  1392. /**
  1393. * A per serverKey list of overrides to use for throttling instead of maximumRequestsPerServer
  1394. */
  1395. RequestScheduler.requestsByServer = {
  1396. 'api.cesium.com:443': 18,
  1397. 'assets.cesium.com:443': 18
  1398. };
  1399. /**
  1400. * Specifies if the request scheduler should throttle incoming requests, or let the browser queue requests under its control.
  1401. * @type {Boolean}
  1402. * @default true
  1403. */
  1404. RequestScheduler.throttleRequests = true;
  1405. /**
  1406. * When true, log statistics to the console every frame
  1407. * @type {Boolean}
  1408. * @default false
  1409. */
  1410. RequestScheduler.debugShowStatistics = false;
  1411. /**
  1412. * An event that's raised when a request is completed. Event handlers are passed
  1413. * the error object if the request fails.
  1414. *
  1415. * @type {Event}
  1416. * @default Event()
  1417. */
  1418. RequestScheduler.requestCompletedEvent = requestCompletedEvent;
  1419. Object.defineProperties(RequestScheduler, {
  1420. /**
  1421. * Returns the statistics used by the request scheduler.
  1422. *
  1423. * @memberof RequestScheduler
  1424. *
  1425. * @type Object
  1426. * @readonly
  1427. */
  1428. statistics : {
  1429. get : function() {
  1430. return statistics;
  1431. }
  1432. },
  1433. /**
  1434. * The maximum size of the priority heap. This limits the number of requests that are sorted by priority. Only applies to requests that are not yet active.
  1435. *
  1436. * @memberof RequestScheduler
  1437. *
  1438. * @type {Number}
  1439. * @default 20
  1440. */
  1441. priorityHeapLength : {
  1442. get : function() {
  1443. return priorityHeapLength;
  1444. },
  1445. set : function(value) {
  1446. // If the new length shrinks the heap, need to cancel some of the requests.
  1447. // Since this value is not intended to be tweaked regularly it is fine to just cancel the high priority requests.
  1448. if (value < priorityHeapLength) {
  1449. while (requestHeap.length > value) {
  1450. var request = requestHeap.pop();
  1451. cancelRequest(request);
  1452. }
  1453. }
  1454. priorityHeapLength = value;
  1455. requestHeap.maximumLength = value;
  1456. requestHeap.reserve(value);
  1457. }
  1458. }
  1459. });
  1460. function updatePriority(request) {
  1461. if (when.defined(request.priorityFunction)) {
  1462. request.priority = request.priorityFunction();
  1463. }
  1464. }
  1465. function serverHasOpenSlots(serverKey) {
  1466. var maxRequests = when.defaultValue(RequestScheduler.requestsByServer[serverKey], RequestScheduler.maximumRequestsPerServer);
  1467. return numberOfActiveRequestsByServer[serverKey] < maxRequests;
  1468. }
  1469. RequestScheduler.packRequestGroup = {};//每帧的所有需要打包的请求 : (serverIP + provider name), value :[request, request,...]
  1470. RequestScheduler.packRequestPromise = {};//每帧打包请求的promise (serverIP + provider name) : defer
  1471. RequestScheduler.packRequestQuadKey = {};//请求包的四叉树编码 (serverIP + provider name) : (quadkey;quadkey;...)
  1472. RequestScheduler.quadKeyIndex = {};//记录当前四叉树编码数组的索引
  1473. RequestScheduler.packRequestHeap = {};//每个图层对应一个二叉堆(serverIp + provider name) : heap
  1474. RequestScheduler.blockDefer = {};
  1475. RequestScheduler.blockRequest = {};
  1476. function getRequestKey(request) {
  1477. if(when.defined(request.packKey)){
  1478. return request.packKey;
  1479. }
  1480. request.packKey = request.serverKey + '_' + request.providerName;
  1481. return request.packKey;
  1482. }
  1483. function getRequestBlockKey(request){
  1484. if(when.defined(request.blockKey)){
  1485. return request.blockKey;
  1486. }
  1487. request.blockKey = request.serverKey + '_' + request.providerName + '_' + request.quadKey + request.url.substring(request.url.indexOf("dataVersion"));
  1488. return request.blockKey;
  1489. }
  1490. function preparePackRequest (request) {
  1491. var packKey = getRequestKey(request);
  1492. if(!when.defined(RequestScheduler.packRequestGroup[packKey])) {
  1493. RequestScheduler.packRequestGroup[packKey] = [];
  1494. }
  1495. if(!when.defined(RequestScheduler.packRequestQuadKey[packKey])) {
  1496. RequestScheduler.packRequestQuadKey[packKey] = '';
  1497. }
  1498. if(!when.defined(RequestScheduler.packRequestPromise[packKey])) {
  1499. RequestScheduler.packRequestPromise[packKey] = when.when.defer();
  1500. }
  1501. if(!when.defined(RequestScheduler.quadKeyIndex[packKey])) {
  1502. RequestScheduler.quadKeyIndex[packKey] = 0;
  1503. }
  1504. request.quadKeyIndex = RequestScheduler.quadKeyIndex[packKey]++;
  1505. request.deferred = RequestScheduler.packRequestPromise[packKey];
  1506. request.state = RequestState$1.ISSUED;
  1507. RequestScheduler.packRequestGroup[packKey].push(request);
  1508. return request.deferred.promise;
  1509. }
  1510. function prepareBlockRequest(request) {
  1511. var key = getRequestBlockKey(request);
  1512. var deferred = RequestScheduler.blockDefer[key];
  1513. if(!when.defined(deferred)) {
  1514. deferred = RequestScheduler.blockDefer[key] = when.when.defer();
  1515. RequestScheduler.blockRequest[key] = request;
  1516. }
  1517. request.deferred = deferred;
  1518. request.state = RequestState$1.ISSUED;
  1519. return request.deferred.promise;
  1520. }
  1521. function clearRequestPackets() {
  1522. RequestScheduler.packRequestGroup = {};
  1523. RequestScheduler.packRequestPromise = {};
  1524. RequestScheduler.packRequestQuadKey = {};
  1525. RequestScheduler.quadKeyIndex = {};
  1526. }
  1527. function clearBlockRequest() {
  1528. RequestScheduler.blockRequest = {};
  1529. }
  1530. function cancelAllRequests(requests) {
  1531. for(var i = 0,j = requests.length;i < j;i++) {
  1532. var request = requests[i];
  1533. request.state = RequestState$1.CANCELLED;
  1534. }
  1535. }
  1536. function combineQuadkey(reqGroup) {
  1537. var quadkeys = [];
  1538. var keyMap = {};
  1539. for(var i = 0,j = reqGroup.length;i < j;i++){
  1540. var request = reqGroup[i];
  1541. if(request.cancelled){
  1542. continue ;
  1543. }
  1544. var quadKey = request.quadKey;
  1545. if(keyMap[quadKey]){
  1546. continue;
  1547. }
  1548. keyMap[quadKey] = true;
  1549. quadkeys.push(quadKey);
  1550. }
  1551. return quadkeys;
  1552. }
  1553. function startPackingRequest() {
  1554. var packRequestGroup = RequestScheduler.packRequestGroup;
  1555. for(var key in packRequestGroup) {
  1556. if(packRequestGroup.hasOwnProperty(key)) {
  1557. var reqGroup = packRequestGroup[key];
  1558. if(reqGroup.length < 1) {
  1559. continue ;
  1560. }
  1561. var packRequest = reqGroup[0].clone();
  1562. var isTileMap = packRequest.url.indexOf("rest/maps") !== -1;
  1563. packRequest.serverKey = reqGroup[0].serverKey;
  1564. packRequest.state = reqGroup[0].state;
  1565. var oldUrl = packRequest.url;
  1566. var quadKeys = combineQuadkey(reqGroup);
  1567. if(quadKeys.length < 1){
  1568. continue ;
  1569. }
  1570. if (isTileMap) {
  1571. RequestScheduler.packRequestQuadKey[key] = quadKeys.join(',');
  1572. } else {
  1573. RequestScheduler.packRequestQuadKey[key] = quadKeys.join(';');
  1574. }
  1575. var quadKey = RequestScheduler.packRequestQuadKey[key];
  1576. if (packRequest.throttleByServer && !serverHasOpenSlots(packRequest.serverKey)) {
  1577. cancelAllRequests(reqGroup);
  1578. RequestScheduler.packRequestPromise[key].reject();
  1579. continue;
  1580. }
  1581. packRequest.deferred = RequestScheduler.packRequestPromise[key];
  1582. var uri = new URI(oldUrl);
  1583. if (isTileMap) {
  1584. uri.query = when.defined(uri.query) ? uri.query + '&tiles=' + quadKey : 'tiles=' + quadKey;
  1585. } else {
  1586. uri.query = when.defined(uri.query) ? uri.query + '&extratiles=' + quadKey : 'extratiles=' + quadKey;
  1587. }
  1588. packRequest.url = uri.toString();
  1589. startRequest(packRequest, packRequest.url);
  1590. }
  1591. }
  1592. clearRequestPackets();
  1593. }
  1594. function updateBlockRequest() {
  1595. var blockRequest = RequestScheduler.blockRequest;
  1596. for(var key in blockRequest) {
  1597. if(blockRequest.hasOwnProperty(key)) {
  1598. var request = blockRequest[key];
  1599. startRequest(request);
  1600. }
  1601. }
  1602. clearBlockRequest();
  1603. }
  1604. function issueRequest(request) {
  1605. if (request.state === RequestState$1.UNISSUED) {
  1606. request.state = RequestState$1.ISSUED;
  1607. if(request.type === RequestType$1.PACK || request.type === RequestType$1.BLOCKPACK){
  1608. var packKey = getRequestKey(request);
  1609. if(!when.defined(RequestScheduler.packRequestPromise[packKey])) {
  1610. RequestScheduler.packRequestPromise[packKey] = when.when.defer();
  1611. }
  1612. request.deferred = RequestScheduler.packRequestPromise[packKey];
  1613. }
  1614. else{
  1615. request.deferred = when.when.defer();
  1616. }
  1617. }
  1618. return request.deferred.promise;
  1619. }
  1620. function getRequestReceivedFunction(request) {
  1621. return function(results) {
  1622. if (request.state === RequestState$1.CANCELLED) {
  1623. // If the data request comes back but the request is cancelled, ignore it.
  1624. return;
  1625. }
  1626. --statistics.numberOfActiveRequests;
  1627. --numberOfActiveRequestsByServer[request.serverKey];
  1628. requestCompletedEvent.raiseEvent();
  1629. request.state = RequestState$1.RECEIVED;
  1630. request.deferred.resolve(results);
  1631. request.endTime = getTimestamp$1();
  1632. if(RequestScheduler.statisticRequestTime > 0 || request.type !== RequestType$1.OTHER) {
  1633. statistics.totalRequestTime += request.endTime - request.startTime;
  1634. }
  1635. if(request.type === RequestType$1.BLOCK || request.type === RequestType$1.BLOCKPACK){
  1636. var key = getRequestBlockKey(request);
  1637. if(when.defined(RequestScheduler.blockDefer[key])){
  1638. RequestScheduler.blockDefer[key] = undefined;
  1639. delete RequestScheduler.blockDefer[key];
  1640. }
  1641. }
  1642. };
  1643. }
  1644. function getRequestFailedFunction(request) {
  1645. return function(error) {
  1646. if (request.state === RequestState$1.CANCELLED) {
  1647. // If the data request comes back but the request is cancelled, ignore it.
  1648. return;
  1649. }
  1650. ++statistics.numberOfFailedRequests;
  1651. --statistics.numberOfActiveRequests;
  1652. --numberOfActiveRequestsByServer[request.serverKey];
  1653. requestCompletedEvent.raiseEvent(error);
  1654. request.state = RequestState$1.FAILED;
  1655. request.deferred.reject(error);
  1656. };
  1657. }
  1658. function startRequest(request, url) {
  1659. var promise = issueRequest(request);
  1660. request.state = RequestState$1.ACTIVE;
  1661. activeRequests.push(request);
  1662. ++statistics.numberOfActiveRequests;
  1663. ++statistics.numberOfActiveRequestsEver;
  1664. ++numberOfActiveRequestsByServer[request.serverKey];
  1665. request.startTime = getTimestamp$1();
  1666. request.requestFunction(url).then(getRequestReceivedFunction(request)).otherwise(getRequestFailedFunction(request));
  1667. return promise;
  1668. }
  1669. function cancelRequest(request) {
  1670. var active = request.state === RequestState$1.ACTIVE;
  1671. request.state = RequestState$1.CANCELLED;
  1672. ++statistics.numberOfCancelledRequests;
  1673. request.deferred.reject();
  1674. if (active) {
  1675. --statistics.numberOfActiveRequests;
  1676. --numberOfActiveRequestsByServer[request.serverKey];
  1677. ++statistics.numberOfCancelledActiveRequests;
  1678. }
  1679. if (when.defined(request.cancelFunction)) {
  1680. request.cancelFunction();
  1681. }
  1682. }
  1683. function updatePackRequestHeap() {
  1684. for(var key in RequestScheduler.packRequestHeap) {
  1685. if(RequestScheduler.packRequestHeap.hasOwnProperty(key)) {
  1686. var heap = RequestScheduler.packRequestHeap[key];
  1687. var issuedRequests = heap.internalArray;
  1688. var issuedLength = heap.length;
  1689. for (var i = 0; i < issuedLength; ++i) {
  1690. updatePriority(issuedRequests[i]);
  1691. }
  1692. heap.resort();
  1693. }
  1694. }
  1695. }
  1696. function packingRequest() {
  1697. for(var key in RequestScheduler.packRequestHeap) {
  1698. if(RequestScheduler.packRequestHeap.hasOwnProperty(key)) {
  1699. var heap = RequestScheduler.packRequestHeap[key];
  1700. while(heap.length > 0) {
  1701. var request = heap.pop();
  1702. if (request.cancelled) {
  1703. cancelRequest(request);
  1704. continue;
  1705. }
  1706. preparePackRequest(request);
  1707. }
  1708. }
  1709. }
  1710. startPackingRequest();
  1711. }
  1712. /**
  1713. * Sort requests by priority and start requests.
  1714. */
  1715. RequestScheduler.update = function() {
  1716. var i;
  1717. var request;
  1718. // Loop over all active requests. Cancelled, failed, or received requests are removed from the array to make room for new requests.
  1719. var removeCount = 0;
  1720. var activeLength = activeRequests.length;
  1721. for (i = 0; i < activeLength; ++i) {
  1722. request = activeRequests[i];
  1723. if (request.cancelled) {
  1724. // Request was explicitly cancelled
  1725. cancelRequest(request);
  1726. }
  1727. if (request.state !== RequestState$1.ACTIVE) {
  1728. // Request is no longer active, remove from array
  1729. ++removeCount;
  1730. continue;
  1731. }
  1732. if (removeCount > 0) {
  1733. // Shift back to fill in vacated slots from completed requests
  1734. activeRequests[i - removeCount] = request;
  1735. }
  1736. }
  1737. activeRequests.length -= removeCount;
  1738. // Update priority of issued requests and resort the heap
  1739. var issuedRequests = requestHeap.internalArray;
  1740. var issuedLength = requestHeap.length;
  1741. for (i = 0; i < issuedLength; ++i) {
  1742. updatePriority(issuedRequests[i]);
  1743. }
  1744. requestHeap.resort();
  1745. updatePackRequestHeap();
  1746. updateBlockRequest();
  1747. packingRequest();
  1748. // Get the number of open slots and fill with the highest priority requests.
  1749. // Un-throttled requests are automatically added to activeRequests, so activeRequests.length may exceed maximumRequests
  1750. var openSlots = Math.max(RequestScheduler.maximumRequests - activeRequests.length, 0);
  1751. var filledSlots = 0;
  1752. while (filledSlots < openSlots && requestHeap.length > 0) {
  1753. // Loop until all open slots are filled or the heap becomes empty
  1754. request = requestHeap.pop();
  1755. if (request.cancelled) {
  1756. // Request was explicitly cancelled
  1757. cancelRequest(request);
  1758. continue;
  1759. }
  1760. if (request.throttleByServer && !serverHasOpenSlots(request.serverKey)) {
  1761. // Open slots are available, but the request is throttled by its server. Cancel and try again later.
  1762. cancelRequest(request);
  1763. continue;
  1764. }
  1765. startRequest(request);
  1766. ++filledSlots;
  1767. }
  1768. updateStatistics();
  1769. };
  1770. /**
  1771. * Get the server key from a given url.
  1772. *
  1773. * @param {String} url The url.
  1774. * @returns {String} The server key.
  1775. */
  1776. RequestScheduler.getServerKey = function(url) {
  1777. //>>includeStart('debug', pragmas.debug);
  1778. Check.Check.typeOf.string('url', url);
  1779. //>>includeEnd('debug');
  1780. var uri = new URI(url).resolve(pageUri);
  1781. uri.normalize();
  1782. var serverKey = uri.authority;
  1783. if (!/:/.test(serverKey)) {
  1784. // If the authority does not contain a port number, add port 443 for https or port 80 for http
  1785. serverKey = serverKey + ':' + (uri.scheme === 'https' ? '443' : '80');
  1786. }
  1787. var length = numberOfActiveRequestsByServer[serverKey];
  1788. if (!when.defined(length)) {
  1789. numberOfActiveRequestsByServer[serverKey] = 0;
  1790. }
  1791. return serverKey;
  1792. };
  1793. function getPackRequestHeap(request) {
  1794. var packKey = getRequestKey(request);
  1795. var heap = RequestScheduler.packRequestHeap[packKey];
  1796. if(!when.defined(heap)) {
  1797. heap = RequestScheduler.packRequestHeap[packKey] = new Heap({
  1798. comparator : sortRequests
  1799. });
  1800. heap.maximumLength = RequestScheduler.perPacketCount;
  1801. heap.reserve(priorityHeapLength);
  1802. }
  1803. return heap;
  1804. }
  1805. /**
  1806. * Issue a request. If request.throttle is false, the request is sent immediately. Otherwise the request will be
  1807. * queued and sorted by priority before being sent.
  1808. *
  1809. * @param {Request} request The request object.
  1810. *
  1811. * @returns {Promise|undefined} A Promise for the requested data, or undefined if this request does not have high enough priority to be issued.
  1812. */
  1813. RequestScheduler.request = function(request) {
  1814. //>>includeStart('debug', pragmas.debug);
  1815. Check.Check.typeOf.object('request', request);
  1816. Check.Check.typeOf.string('request.url', request.url);
  1817. Check.Check.typeOf.func('request.requestFunction', request.requestFunction);
  1818. //>>includeEnd('debug');
  1819. if (isDataUri(request.url) || isBlobUri(request.url)) {
  1820. requestCompletedEvent.raiseEvent();
  1821. request.state = RequestState$1.RECEIVED;
  1822. return request.requestFunction();
  1823. }
  1824. ++statistics.numberOfAttemptedRequests;
  1825. if (!when.defined(request.serverKey)) {
  1826. request.serverKey = RequestScheduler.getServerKey(request.url);
  1827. }
  1828. if(request.type === RequestType$1.BLOCK) {
  1829. return prepareBlockRequest(request);
  1830. }
  1831. if (request.throttleByServer && !serverHasOpenSlots(request.serverKey)) {
  1832. // Server is saturated. Try again later.
  1833. return undefined;
  1834. }
  1835. if (!RequestScheduler.throttleRequests || !request.throttle) {
  1836. return startRequest(request);
  1837. }
  1838. if (activeRequests.length >= RequestScheduler.maximumRequests) {
  1839. // Active requests are saturated. Try again later.
  1840. return undefined;
  1841. }
  1842. // Insert into the priority heap and see if a request was bumped off. If this request is the lowest
  1843. // priority it will be returned.
  1844. updatePriority(request);
  1845. var removedRequest;
  1846. if(request.type === RequestType$1.PACK || request.type === RequestType$1.BLOCKPACK) {
  1847. var packRequestHeap = getPackRequestHeap(request);
  1848. var inset = true;
  1849. if(request.type === RequestType$1.BLOCKPACK){
  1850. for(var i=0; i<packRequestHeap.length; i++){
  1851. if(packRequestHeap._array[i].quadKey === request.quadKey){
  1852. request.blockRequest = packRequestHeap._array[i];
  1853. inset = false;
  1854. break;
  1855. }
  1856. }
  1857. }
  1858. if(inset){
  1859. removedRequest = packRequestHeap.insert(request);
  1860. }
  1861. }
  1862. else{
  1863. removedRequest = requestHeap.insert(request);
  1864. }
  1865. if (when.defined(removedRequest)) {
  1866. if (removedRequest === request) {
  1867. // Request does not have high enough priority to be issued
  1868. return undefined;
  1869. }
  1870. // A previously issued request has been bumped off the priority heap, so cancel it
  1871. cancelRequest(removedRequest);
  1872. }
  1873. return issueRequest(request);
  1874. };
  1875. function updateStatistics() {
  1876. if (!RequestScheduler.debugShowStatistics) {
  1877. return;
  1878. }
  1879. if (statistics.numberOfActiveRequests === 0 && statistics.lastNumberOfActiveRequests > 0) {
  1880. if (statistics.numberOfAttemptedRequests > 0) {
  1881. console.log('Number of attempted requests: ' + statistics.numberOfAttemptedRequests);
  1882. statistics.numberOfAttemptedRequests = 0;
  1883. }
  1884. if (statistics.numberOfCancelledRequests > 0) {
  1885. console.log('Number of cancelled requests: ' + statistics.numberOfCancelledRequests);
  1886. statistics.numberOfCancelledRequests = 0;
  1887. }
  1888. if (statistics.numberOfCancelledActiveRequests > 0) {
  1889. console.log('Number of cancelled active requests: ' + statistics.numberOfCancelledActiveRequests);
  1890. statistics.numberOfCancelledActiveRequests = 0;
  1891. }
  1892. if (statistics.numberOfFailedRequests > 0) {
  1893. console.log('Number of failed requests: ' + statistics.numberOfFailedRequests);
  1894. statistics.numberOfFailedRequests = 0;
  1895. }
  1896. }
  1897. statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
  1898. }
  1899. /**
  1900. * For testing only. Clears any requests that may not have completed from previous tests.
  1901. *
  1902. * @private
  1903. */
  1904. RequestScheduler.clearForSpecs = function() {
  1905. while (requestHeap.length > 0) {
  1906. var request = requestHeap.pop();
  1907. cancelRequest(request);
  1908. }
  1909. var length = activeRequests.length;
  1910. for (var i = 0; i < length; ++i) {
  1911. cancelRequest(activeRequests[i]);
  1912. }
  1913. activeRequests.length = 0;
  1914. numberOfActiveRequestsByServer = {};
  1915. // Clear stats
  1916. statistics.numberOfAttemptedRequests = 0;
  1917. statistics.numberOfActiveRequests = 0;
  1918. statistics.numberOfCancelledRequests = 0;
  1919. statistics.numberOfCancelledActiveRequests = 0;
  1920. statistics.numberOfFailedRequests = 0;
  1921. statistics.numberOfActiveRequestsEver = 0;
  1922. statistics.lastNumberOfActiveRequests = 0;
  1923. statistics.totalRequestTime = 0;
  1924. };
  1925. /**
  1926. * For testing only.
  1927. *
  1928. * @private
  1929. */
  1930. RequestScheduler.numberOfActiveRequestsByServer = function(serverKey) {
  1931. return numberOfActiveRequestsByServer[serverKey];
  1932. };
  1933. /**
  1934. * For testing only.
  1935. *
  1936. * @private
  1937. */
  1938. RequestScheduler.requestHeap = requestHeap;
  1939. /**
  1940. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  1941. * any requests to these servers.
  1942. *
  1943. * @exports TrustedServers
  1944. *
  1945. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  1946. */
  1947. var TrustedServers = {};
  1948. var _servers = {};
  1949. /**
  1950. * Adds a trusted server to the registry
  1951. *
  1952. * @param {String} host The host to be added.
  1953. * @param {Number} port The port used to access the host.
  1954. *
  1955. * @example
  1956. * // Add a trusted server
  1957. * TrustedServers.add('my.server.com', 80);
  1958. */
  1959. TrustedServers.add = function(host, port) {
  1960. //>>includeStart('debug', pragmas.debug);
  1961. if (!when.defined(host)) {
  1962. throw new Check.DeveloperError('host is required.');
  1963. }
  1964. if (!when.defined(port) || port <= 0) {
  1965. throw new Check.DeveloperError('port is required to be greater than 0.');
  1966. }
  1967. //>>includeEnd('debug');
  1968. var authority = host.toLowerCase() + ':' + port;
  1969. if (!when.defined(_servers[authority])) {
  1970. _servers[authority] = true;
  1971. }
  1972. };
  1973. /**
  1974. * Removes a trusted server from the registry
  1975. *
  1976. * @param {String} host The host to be removed.
  1977. * @param {Number} port The port used to access the host.
  1978. *
  1979. * @example
  1980. * // Remove a trusted server
  1981. * TrustedServers.remove('my.server.com', 80);
  1982. */
  1983. TrustedServers.remove = function(host, port) {
  1984. //>>includeStart('debug', pragmas.debug);
  1985. if (!when.defined(host)) {
  1986. throw new Check.DeveloperError('host is required.');
  1987. }
  1988. if (!when.defined(port) || port <= 0) {
  1989. throw new Check.DeveloperError('port is required to be greater than 0.');
  1990. }
  1991. //>>includeEnd('debug');
  1992. var authority = host.toLowerCase() + ':' + port;
  1993. if (when.defined(_servers[authority])) {
  1994. delete _servers[authority];
  1995. }
  1996. };
  1997. function getAuthority(url) {
  1998. var uri = new URI(url);
  1999. uri.normalize();
  2000. // Removes username:password@ so we just have host[:port]
  2001. var authority = uri.getAuthority();
  2002. if (!when.defined(authority)) {
  2003. return undefined; // Relative URL
  2004. }
  2005. if (authority.indexOf('@') !== -1) {
  2006. var parts = authority.split('@');
  2007. authority = parts[1];
  2008. }
  2009. // If the port is missing add one based on the scheme
  2010. if (authority.indexOf(':') === -1) {
  2011. var scheme = uri.getScheme();
  2012. if (!when.defined(scheme)) {
  2013. scheme = window.location.protocol;
  2014. scheme = scheme.substring(0, scheme.length-1);
  2015. }
  2016. if (scheme === 'http') {
  2017. authority += ':80';
  2018. } else if (scheme === 'https') {
  2019. authority += ':443';
  2020. } else {
  2021. return undefined;
  2022. }
  2023. }
  2024. return authority;
  2025. }
  2026. /**
  2027. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  2028. *
  2029. * @param {String} url The url to be tested against the trusted list
  2030. *
  2031. * @returns {boolean} Returns true if url is trusted, false otherwise.
  2032. *
  2033. * @example
  2034. * // Add server
  2035. * TrustedServers.add('my.server.com', 81);
  2036. *
  2037. * // Check if server is trusted
  2038. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  2039. * // my.server.com:81 is trusted
  2040. * }
  2041. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  2042. * // my.server.com isn't trusted
  2043. * }
  2044. */
  2045. TrustedServers.contains = function(url) {
  2046. //>>includeStart('debug', pragmas.debug);
  2047. if (!when.defined(url)) {
  2048. throw new Check.DeveloperError('url is required.');
  2049. }
  2050. //>>includeEnd('debug');
  2051. var authority = getAuthority(url);
  2052. if (when.defined(authority) && when.defined(_servers[authority])) {
  2053. return true;
  2054. }
  2055. return false;
  2056. };
  2057. /**
  2058. * Clears the registry
  2059. *
  2060. * @example
  2061. * // Remove a trusted server
  2062. * TrustedServers.clear();
  2063. */
  2064. TrustedServers.clear = function() {
  2065. _servers = {};
  2066. };
  2067. var warnings = {};
  2068. /**
  2069. * Logs a one time message to the console. Use this function instead of
  2070. * <code>console.log</code> directly since this does not log duplicate messages
  2071. * unless it is called from multiple workers.
  2072. *
  2073. * @exports oneTimeWarning
  2074. *
  2075. * @param {String} identifier The unique identifier for this warning.
  2076. * @param {String} [message=identifier] The message to log to the console.
  2077. *
  2078. * @example
  2079. * for(var i=0;i<foo.length;++i) {
  2080. * if (!defined(foo[i].bar)) {
  2081. * // Something that can be recovered from but may happen a lot
  2082. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  2083. * foo[i].bar = 0;
  2084. * // ...
  2085. * }
  2086. * }
  2087. *
  2088. * @private
  2089. */
  2090. function oneTimeWarning(identifier, message) {
  2091. //>>includeStart('debug', pragmas.debug);
  2092. if (!when.defined(identifier)) {
  2093. throw new Check.DeveloperError('identifier is required.');
  2094. }
  2095. //>>includeEnd('debug');
  2096. if (!when.defined(warnings[identifier])) {
  2097. warnings[identifier] = true;
  2098. console.warn(when.defaultValue(message, identifier));
  2099. }
  2100. }
  2101. oneTimeWarning.geometryOutlines = 'Entity geometry outlines are unsupported on terrain. Outlines will be disabled. To enable outlines, disable geometry terrain clamping by explicitly setting height to 0.';
  2102. oneTimeWarning.geometryZIndex = 'Entity geometry with zIndex are unsupported when height or extrudedHeight are defined. zIndex will be ignored';
  2103. oneTimeWarning.geometryHeightReference = 'Entity corridor, ellipse, polygon or rectangle with heightReference must also have a defined height. heightReference will be ignored';
  2104. oneTimeWarning.geometryExtrudedHeightReference = 'Entity corridor, ellipse, polygon or rectangle with extrudedHeightReference must also have a defined extrudedHeight. extrudedHeightReference will be ignored';
  2105. /**
  2106. * Logs a deprecation message to the console. Use this function instead of
  2107. * <code>console.log</code> directly since this does not log duplicate messages
  2108. * unless it is called from multiple workers.
  2109. *
  2110. * @exports deprecationWarning
  2111. *
  2112. * @param {String} identifier The unique identifier for this deprecated API.
  2113. * @param {String} message The message to log to the console.
  2114. *
  2115. * @example
  2116. * // Deprecated function or class
  2117. * function Foo() {
  2118. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  2119. * // ...
  2120. * }
  2121. *
  2122. * // Deprecated function
  2123. * Bar.prototype.func = function() {
  2124. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  2125. * // ...
  2126. * };
  2127. *
  2128. * // Deprecated property
  2129. * Object.defineProperties(Bar.prototype, {
  2130. * prop : {
  2131. * get : function() {
  2132. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  2133. * // ...
  2134. * },
  2135. * set : function(value) {
  2136. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  2137. * // ...
  2138. * }
  2139. * }
  2140. * });
  2141. *
  2142. * @private
  2143. */
  2144. function deprecationWarning(identifier, message) {
  2145. //>>includeStart('debug', pragmas.debug);
  2146. if (!when.defined(identifier) || !when.defined(message)) {
  2147. throw new Check.DeveloperError('identifier and message are required.');
  2148. }
  2149. //>>includeEnd('debug');
  2150. oneTimeWarning(identifier, message);
  2151. }
  2152. var xhrBlobSupported = (function() {
  2153. try {
  2154. var xhr = new XMLHttpRequest();
  2155. xhr.open('GET', '#', true);
  2156. xhr.responseType = 'blob';
  2157. return xhr.responseType === 'blob';
  2158. } catch (e) {
  2159. return false;
  2160. }
  2161. })();
  2162. /**
  2163. * Parses a query string and returns the object equivalent.
  2164. *
  2165. * @param {Uri} uri The Uri with a query object.
  2166. * @param {Resource} resource The Resource that will be assigned queryParameters.
  2167. * @param {Boolean} merge If true, we'll merge with the resource's existing queryParameters. Otherwise they will be replaced.
  2168. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in uri will take precedence.
  2169. *
  2170. * @private
  2171. */
  2172. function parseQuery(uri, resource, merge, preserveQueryParameters) {
  2173. var queryString = uri.query;
  2174. if (!when.defined(queryString) || (queryString.length === 0)) {
  2175. return {};
  2176. }
  2177. var query;
  2178. // Special case we run into where the querystring is just a string, not key/value pairs
  2179. if (queryString.indexOf('=') === -1) {
  2180. var result = {};
  2181. result[queryString] = undefined;
  2182. query = result;
  2183. } else {
  2184. query = queryToObject(queryString);
  2185. }
  2186. if (merge) {
  2187. resource._queryParameters = combineQueryParameters(query, resource._queryParameters, preserveQueryParameters);
  2188. } else {
  2189. resource._queryParameters = query;
  2190. }
  2191. uri.query = undefined;
  2192. }
  2193. /**
  2194. * Converts a query object into a string.
  2195. *
  2196. * @param {Uri} uri The Uri object that will have the query object set.
  2197. * @param {Resource} resource The resource that has queryParameters
  2198. *
  2199. * @private
  2200. */
  2201. function stringifyQuery(uri, resource) {
  2202. var queryObject = resource._queryParameters;
  2203. var keys = Object.keys(queryObject);
  2204. // We have 1 key with an undefined value, so this is just a string, not key/value pairs
  2205. if (keys.length === 1 && !when.defined(queryObject[keys[0]])) {
  2206. uri.query = keys[0];
  2207. } else {
  2208. uri.query = objectToQuery(queryObject);
  2209. }
  2210. }
  2211. /**
  2212. * Clones a value if it is defined, otherwise returns the default value
  2213. *
  2214. * @param {*} [val] The value to clone.
  2215. * @param {*} [defaultVal] The default value.
  2216. *
  2217. * @returns {*} A clone of val or the defaultVal.
  2218. *
  2219. * @private
  2220. */
  2221. function defaultClone(val, defaultVal) {
  2222. if (!when.defined(val)) {
  2223. return defaultVal;
  2224. }
  2225. return when.defined(val.clone) ? val.clone() : clone(val);
  2226. }
  2227. /**
  2228. * Checks to make sure the Resource isn't already being requested.
  2229. *
  2230. * @param {Request} request The request to check.
  2231. *
  2232. * @private
  2233. */
  2234. function checkAndResetRequest(request) {
  2235. if (request.state === RequestState$1.ISSUED || request.state === RequestState$1.ACTIVE) {
  2236. throw new RuntimeError.RuntimeError('The Resource is already being fetched.');
  2237. }
  2238. request.state = RequestState$1.UNISSUED;
  2239. request.deferred = undefined;
  2240. }
  2241. /**
  2242. * This combines a map of query parameters.
  2243. *
  2244. * @param {Object} q1 The first map of query parameters. Values in this map will take precedence if preserveQueryParameters is false.
  2245. * @param {Object} q2 The second map of query parameters.
  2246. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in q1 will take precedence.
  2247. *
  2248. * @returns {Object} The combined map of query parameters.
  2249. *
  2250. * @example
  2251. * var q1 = {
  2252. * a: 1,
  2253. * b: 2
  2254. * };
  2255. * var q2 = {
  2256. * a: 3,
  2257. * c: 4
  2258. * };
  2259. * var q3 = {
  2260. * b: [5, 6],
  2261. * d: 7
  2262. * }
  2263. *
  2264. * // Returns
  2265. * // {
  2266. * // a: [1, 3],
  2267. * // b: 2,
  2268. * // c: 4
  2269. * // };
  2270. * combineQueryParameters(q1, q2, true);
  2271. *
  2272. * // Returns
  2273. * // {
  2274. * // a: 1,
  2275. * // b: 2,
  2276. * // c: 4
  2277. * // };
  2278. * combineQueryParameters(q1, q2, false);
  2279. *
  2280. * // Returns
  2281. * // {
  2282. * // a: 1,
  2283. * // b: [2, 5, 6],
  2284. * // d: 7
  2285. * // };
  2286. * combineQueryParameters(q1, q3, true);
  2287. *
  2288. * // Returns
  2289. * // {
  2290. * // a: 1,
  2291. * // b: 2,
  2292. * // d: 7
  2293. * // };
  2294. * combineQueryParameters(q1, q3, false);
  2295. *
  2296. * @private
  2297. */
  2298. function combineQueryParameters(q1, q2, preserveQueryParameters) {
  2299. if (!preserveQueryParameters) {
  2300. return combine(q1, q2);
  2301. }
  2302. var result = clone(q1, true);
  2303. for (var param in q2) {
  2304. if (q2.hasOwnProperty(param)) {
  2305. var value = result[param];
  2306. var q2Value = q2[param];
  2307. if (when.defined(value)) {
  2308. if (!Array.isArray(value)) {
  2309. value = result[param] = [value];
  2310. }
  2311. result[param] = value.concat(q2Value);
  2312. } else {
  2313. result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
  2314. }
  2315. }
  2316. }
  2317. return result;
  2318. }
  2319. /**
  2320. * A resource that includes the location and any other parameters we need to retrieve it or create derived resources. It also provides the ability to retry requests.
  2321. *
  2322. * @alias Resource
  2323. * @constructor
  2324. *
  2325. * @param {String|Object} options A url or an object with the following properties
  2326. * @param {String} options.url The url of the resource.
  2327. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  2328. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  2329. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2330. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2331. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  2332. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  2333. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2334. *
  2335. * @example
  2336. * function refreshTokenRetryCallback(resource, error) {
  2337. * if (error.statusCode === 403) {
  2338. * // 403 status code means a new token should be generated
  2339. * return getNewAccessToken()
  2340. * .then(function(token) {
  2341. * resource.queryParameters.access_token = token;
  2342. * return true;
  2343. * })
  2344. * .otherwise(function() {
  2345. * return false;
  2346. * });
  2347. * }
  2348. *
  2349. * return false;
  2350. * }
  2351. *
  2352. * var resource = new Resource({
  2353. * url: 'http://server.com/path/to/resource.json',
  2354. * proxy: new DefaultProxy('/proxy/'),
  2355. * headers: {
  2356. * 'X-My-Header': 'valueOfHeader'
  2357. * },
  2358. * queryParameters: {
  2359. * 'access_token': '123-435-456-000'
  2360. * },
  2361. * retryCallback: refreshTokenRetryCallback,
  2362. * retryAttempts: 1
  2363. * });
  2364. */
  2365. function Resource(options) {
  2366. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  2367. if (typeof options === 'string') {
  2368. options = {
  2369. url: options
  2370. };
  2371. }
  2372. //>>includeStart('debug', pragmas.debug);
  2373. Check.Check.typeOf.string('options.url', options.url);
  2374. //>>includeEnd('debug');
  2375. this._url = undefined;
  2376. this._templateValues = defaultClone(options.templateValues, {});
  2377. this._queryParameters = defaultClone(options.queryParameters, {});
  2378. /**
  2379. * Additional HTTP headers that will be sent with the request.
  2380. *
  2381. * @type {Object}
  2382. */
  2383. this.headers = defaultClone(options.headers, {});
  2384. /**
  2385. * A Request object that will be used. Intended for internal use only.
  2386. *
  2387. * @type {Request}
  2388. */
  2389. this.request = when.defaultValue(options.request, new Request());
  2390. /**
  2391. * A proxy to be used when loading the resource.
  2392. *
  2393. * @type {DefaultProxy}
  2394. */
  2395. this.proxy = options.proxy;
  2396. /**
  2397. * Function to call when a request for this resource fails. If it returns true or a Promise that resolves to true, the request will be retried.
  2398. *
  2399. * @type {Function}
  2400. */
  2401. this.retryCallback = options.retryCallback;
  2402. /**
  2403. * The number of times the retryCallback should be called before giving up.
  2404. *
  2405. * @type {Number}
  2406. */
  2407. this.retryAttempts = when.defaultValue(options.retryAttempts, 0);
  2408. this._retryCount = 0;
  2409. var uri = new URI(options.url);
  2410. parseQuery(uri, this, true, true);
  2411. // Remove the fragment as it's not sent with a request
  2412. uri.fragment = undefined;
  2413. this._url = uri.toString();
  2414. }
  2415. /**
  2416. * A helper function to create a resource depending on whether we have a String or a Resource
  2417. *
  2418. * @param {Resource|String} resource A Resource or a String to use when creating a new Resource.
  2419. *
  2420. * @returns {Resource} If resource is a String, a Resource constructed with the url and options. Otherwise the resource parameter is returned.
  2421. *
  2422. * @private
  2423. */
  2424. Resource.createIfNeeded = function(resource) {
  2425. if (resource instanceof Resource) {
  2426. // Keep existing request object. This function is used internally to duplicate a Resource, so that it can't
  2427. // be modified outside of a class that holds it (eg. an imagery or terrain provider). Since the Request objects
  2428. // are managed outside of the providers, by the tile loading code, we want to keep the request property the same so if it is changed
  2429. // in the underlying tiling code the requests for this resource will use it.
  2430. return resource.getDerivedResource({
  2431. request: resource.request
  2432. });
  2433. }
  2434. if (typeof resource !== 'string') {
  2435. return resource;
  2436. }
  2437. return new Resource({
  2438. url: resource
  2439. });
  2440. };
  2441. var supportsImageBitmapOptionsPromise;
  2442. /**
  2443. * A helper function to check whether createImageBitmap supports passing ImageBitmapOptions.
  2444. *
  2445. * @returns {Promise<Boolean>} A promise that resolves to true if this browser supports creating an ImageBitmap with options.
  2446. *
  2447. * @private
  2448. */
  2449. Resource.supportsImageBitmapOptions = function() {
  2450. // Until the HTML folks figure out what to do about this, we need to actually try loading an image to
  2451. // know if this browser supports passing options to the createImageBitmap function.
  2452. // https://github.com/whatwg/html/pull/4248
  2453. if (when.defined(supportsImageBitmapOptionsPromise)) {
  2454. return supportsImageBitmapOptionsPromise;
  2455. }
  2456. if (typeof createImageBitmap !== 'function') {
  2457. supportsImageBitmapOptionsPromise = when.when.resolve(false);
  2458. return supportsImageBitmapOptionsPromise;
  2459. }
  2460. var imageDataUri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWP4////fwAJ+wP9CNHoHgAAAABJRU5ErkJggg==';
  2461. supportsImageBitmapOptionsPromise = Resource.fetchBlob({
  2462. url : imageDataUri
  2463. })
  2464. .then(function(blob) {
  2465. return createImageBitmap(blob, {
  2466. imageOrientation: 'flipY',
  2467. premultiplyAlpha: 'none'
  2468. });
  2469. })
  2470. .then(function(imageBitmap) {
  2471. return true;
  2472. })
  2473. .otherwise(function() {
  2474. return false;
  2475. });
  2476. return supportsImageBitmapOptionsPromise;
  2477. };
  2478. Object.defineProperties(Resource, {
  2479. /**
  2480. * Returns true if blobs are supported.
  2481. *
  2482. * @memberof Resource
  2483. * @type {Boolean}
  2484. *
  2485. * @readonly
  2486. */
  2487. isBlobSupported : {
  2488. get : function() {
  2489. return xhrBlobSupported;
  2490. }
  2491. }
  2492. });
  2493. Object.defineProperties(Resource.prototype, {
  2494. /**
  2495. * Query parameters appended to the url.
  2496. *
  2497. * @memberof Resource.prototype
  2498. * @type {Object}
  2499. *
  2500. * @readonly
  2501. */
  2502. queryParameters: {
  2503. get: function() {
  2504. return this._queryParameters;
  2505. }
  2506. },
  2507. /**
  2508. * The key/value pairs used to replace template parameters in the url.
  2509. *
  2510. * @memberof Resource.prototype
  2511. * @type {Object}
  2512. *
  2513. * @readonly
  2514. */
  2515. templateValues: {
  2516. get: function() {
  2517. return this._templateValues;
  2518. }
  2519. },
  2520. /**
  2521. * The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
  2522. *
  2523. * @memberof Resource.prototype
  2524. * @type {String}
  2525. */
  2526. url: {
  2527. get: function() {
  2528. return this.getUrlComponent(true, true);
  2529. },
  2530. set: function(value) {
  2531. var uri = new URI(value);
  2532. parseQuery(uri, this, false);
  2533. // Remove the fragment as it's not sent with a request
  2534. uri.fragment = undefined;
  2535. this._url = uri.toString();
  2536. }
  2537. },
  2538. /**
  2539. * The file extension of the resource.
  2540. *
  2541. * @memberof Resource.prototype
  2542. * @type {String}
  2543. *
  2544. * @readonly
  2545. */
  2546. extension: {
  2547. get: function() {
  2548. return getExtensionFromUri(this._url);
  2549. }
  2550. },
  2551. /**
  2552. * True if the Resource refers to a data URI.
  2553. *
  2554. * @memberof Resource.prototype
  2555. * @type {Boolean}
  2556. */
  2557. isDataUri: {
  2558. get: function() {
  2559. return isDataUri(this._url);
  2560. }
  2561. },
  2562. /**
  2563. * True if the Resource refers to a blob URI.
  2564. *
  2565. * @memberof Resource.prototype
  2566. * @type {Boolean}
  2567. */
  2568. isBlobUri: {
  2569. get: function() {
  2570. return isBlobUri(this._url);
  2571. }
  2572. },
  2573. /**
  2574. * True if the Resource refers to a cross origin URL.
  2575. *
  2576. * @memberof Resource.prototype
  2577. * @type {Boolean}
  2578. */
  2579. isCrossOriginUrl: {
  2580. get: function() {
  2581. return isCrossOriginUrl(this._url);
  2582. }
  2583. },
  2584. /**
  2585. * True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
  2586. *
  2587. * @memberof Resource.prototype
  2588. * @type {Boolean}
  2589. */
  2590. hasHeaders: {
  2591. get: function() {
  2592. return (Object.keys(this.headers).length > 0);
  2593. }
  2594. }
  2595. });
  2596. /**
  2597. * Returns the url, optional with the query string and processed by a proxy.
  2598. *
  2599. * @param {Boolean} [query=false] If true, the query string is included.
  2600. * @param {Boolean} [proxy=false] If true, the url is processed the proxy object if defined.
  2601. *
  2602. * @returns {String} The url with all the requested components.
  2603. */
  2604. Resource.prototype.getUrlComponent = function(query, proxy) {
  2605. if(this.isDataUri) {
  2606. return this._url;
  2607. }
  2608. var uri = new URI(this._url);
  2609. if (query) {
  2610. stringifyQuery(uri, this);
  2611. }
  2612. // objectToQuery escapes the placeholders. Undo that.
  2613. var url = uri.toString().replace(/%7B/g, '{').replace(/%7D/g, '}');
  2614. var templateValues = this._templateValues;
  2615. url = url.replace(/{(.*?)}/g, function(match, key) {
  2616. var replacement = templateValues[key];
  2617. if (when.defined(replacement)) {
  2618. // use the replacement value from templateValues if there is one...
  2619. return encodeURIComponent(replacement);
  2620. }
  2621. // otherwise leave it unchanged
  2622. return match;
  2623. });
  2624. if (proxy && when.defined(this.proxy)) {
  2625. url = this.proxy.getURL(url);
  2626. }
  2627. return url;
  2628. };
  2629. /**
  2630. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  2631. * as opposed to adding them one at a time to the queryParameters property. If a value is already set, it will be replaced with the new value.
  2632. *
  2633. * @param {Object} params The query parameters
  2634. * @param {Boolean} [useAsDefault=false] If true the params will be used as the default values, so they will only be set if they are undefined.
  2635. */
  2636. Resource.prototype.setQueryParameters = function(params, useAsDefault) {
  2637. if (useAsDefault) {
  2638. this._queryParameters = combineQueryParameters(this._queryParameters, params, false);
  2639. } else {
  2640. this._queryParameters = combineQueryParameters(params, this._queryParameters, false);
  2641. }
  2642. };
  2643. /**
  2644. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  2645. * as opposed to adding them one at a time to the queryParameters property.
  2646. *
  2647. * @param {Object} params The query parameters
  2648. */
  2649. Resource.prototype.appendQueryParameters = function(params) {
  2650. this._queryParameters = combineQueryParameters(params, this._queryParameters, true);
  2651. };
  2652. /**
  2653. * Combines the specified object and the existing template values. This allows you to add many values at once,
  2654. * as opposed to adding them one at a time to the templateValues property. If a value is already set, it will become an array and the new value will be appended.
  2655. *
  2656. * @param {Object} template The template values
  2657. * @param {Boolean} [useAsDefault=false] If true the values will be used as the default values, so they will only be set if they are undefined.
  2658. */
  2659. Resource.prototype.setTemplateValues = function(template, useAsDefault) {
  2660. if (useAsDefault) {
  2661. this._templateValues = combine(this._templateValues, template);
  2662. } else {
  2663. this._templateValues = combine(template, this._templateValues);
  2664. }
  2665. };
  2666. /**
  2667. * Returns a resource relative to the current instance. All properties remain the same as the current instance unless overridden in options.
  2668. *
  2669. * @param {Object} options An object with the following properties
  2670. * @param {String} [options.url] The url that will be resolved relative to the url of the current instance.
  2671. * @param {Object} [options.queryParameters] An object containing query parameters that will be combined with those of the current instance.
  2672. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}). These will be combined with those of the current instance.
  2673. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2674. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2675. * @param {Resource~RetryCallback} [options.retryCallback] The function to call when loading the resource fails.
  2676. * @param {Number} [options.retryAttempts] The number of times the retryCallback should be called before giving up.
  2677. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2678. * @param {Boolean} [options.preserveQueryParameters=false] If true, this will keep all query parameters from the current resource and derived resource. If false, derived parameters will replace those of the current resource.
  2679. *
  2680. * @returns {Resource} The resource derived from the current one.
  2681. */
  2682. Resource.prototype.getDerivedResource = function(options) {
  2683. var resource = this.clone();
  2684. resource._retryCount = 0;
  2685. if (when.defined(options.url)) {
  2686. var uri = new URI(options.url);
  2687. var preserveQueryParameters = when.defaultValue(options.preserveQueryParameters, false);
  2688. parseQuery(uri, resource, true, preserveQueryParameters);
  2689. // Remove the fragment as it's not sent with a request
  2690. uri.fragment = undefined;
  2691. resource._url = uri.resolve(new URI(getAbsoluteUri(this._url))).toString();
  2692. }
  2693. if (when.defined(options.queryParameters)) {
  2694. resource._queryParameters = combine(options.queryParameters, resource._queryParameters);
  2695. }
  2696. if (when.defined(options.templateValues)) {
  2697. resource._templateValues = combine(options.templateValues, resource.templateValues);
  2698. }
  2699. if (when.defined(options.headers)) {
  2700. resource.headers = combine(options.headers, resource.headers);
  2701. }
  2702. if (when.defined(options.proxy)) {
  2703. resource.proxy = options.proxy;
  2704. }
  2705. if (when.defined(options.request)) {
  2706. resource.request = options.request;
  2707. }
  2708. if (when.defined(options.retryCallback)) {
  2709. resource.retryCallback = options.retryCallback;
  2710. }
  2711. if (when.defined(options.retryAttempts)) {
  2712. resource.retryAttempts = options.retryAttempts;
  2713. }
  2714. return resource;
  2715. };
  2716. /**
  2717. * Called when a resource fails to load. This will call the retryCallback function if defined until retryAttempts is reached.
  2718. *
  2719. * @param {Error} [error] The error that was encountered.
  2720. *
  2721. * @returns {Promise<Boolean>} A promise to a boolean, that if true will cause the resource request to be retried.
  2722. *
  2723. * @private
  2724. */
  2725. Resource.prototype.retryOnError = function(error) {
  2726. var retryCallback = this.retryCallback;
  2727. if ((typeof retryCallback !== 'function') || (this._retryCount >= this.retryAttempts)) {
  2728. return when.when(false);
  2729. }
  2730. var that = this;
  2731. return when.when(retryCallback(this, error))
  2732. .then(function(result) {
  2733. ++that._retryCount;
  2734. return result;
  2735. });
  2736. };
  2737. /**
  2738. * Duplicates a Resource instance.
  2739. *
  2740. * @param {Resource} [result] The object onto which to store the result.
  2741. *
  2742. * @returns {Resource} The modified result parameter or a new Resource instance if one was not provided.
  2743. */
  2744. Resource.prototype.clone = function(result) {
  2745. if (!when.defined(result)) {
  2746. result = new Resource({
  2747. url : this._url
  2748. });
  2749. }
  2750. result._url = this._url;
  2751. result._queryParameters = clone(this._queryParameters);
  2752. result._templateValues = clone(this._templateValues);
  2753. result.headers = clone(this.headers);
  2754. result.proxy = this.proxy;
  2755. result.retryCallback = this.retryCallback;
  2756. result.retryAttempts = this.retryAttempts;
  2757. result._retryCount = 0;
  2758. result.request = this.request.clone();
  2759. return result;
  2760. };
  2761. /**
  2762. * Returns the base path of the Resource.
  2763. *
  2764. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  2765. *
  2766. * @returns {String} The base URI of the resource
  2767. */
  2768. Resource.prototype.getBaseUri = function(includeQuery) {
  2769. return getBaseUri(this.getUrlComponent(includeQuery), includeQuery);
  2770. };
  2771. /**
  2772. * Appends a forward slash to the URL.
  2773. */
  2774. Resource.prototype.appendForwardSlash = function() {
  2775. this._url = appendForwardSlash(this._url);
  2776. };
  2777. /**
  2778. * Asynchronously loads the resource as raw binary data. Returns a promise that will resolve to
  2779. * an ArrayBuffer once loaded, or reject if the resource failed to load. The data is loaded
  2780. * using XMLHttpRequest, which means that in order to make requests to another origin,
  2781. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  2782. *
  2783. * @returns {Promise.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2784. *
  2785. * @example
  2786. * // load a single URL asynchronously
  2787. * resource.fetchArrayBuffer().then(function(arrayBuffer) {
  2788. * // use the data
  2789. * }).otherwise(function(error) {
  2790. * // an error occurred
  2791. * });
  2792. *
  2793. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  2794. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  2795. */
  2796. Resource.prototype.fetchArrayBuffer = function () {
  2797. return this.fetch({
  2798. responseType : 'arraybuffer'
  2799. });
  2800. };
  2801. /**
  2802. * Creates a Resource and calls fetchArrayBuffer() on it.
  2803. *
  2804. * @param {String|Object} options A url or an object with the following properties
  2805. * @param {String} options.url The url of the resource.
  2806. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  2807. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  2808. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2809. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2810. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  2811. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  2812. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2813. * @returns {Promise.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2814. */
  2815. Resource.fetchArrayBuffer = function (options) {
  2816. var resource = new Resource(options);
  2817. return resource.fetchArrayBuffer();
  2818. };
  2819. /**
  2820. * Asynchronously loads the given resource as a blob. Returns a promise that will resolve to
  2821. * a Blob once loaded, or reject if the resource failed to load. The data is loaded
  2822. * using XMLHttpRequest, which means that in order to make requests to another origin,
  2823. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  2824. *
  2825. * @returns {Promise.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2826. *
  2827. * @example
  2828. * // load a single URL asynchronously
  2829. * resource.fetchBlob().then(function(blob) {
  2830. * // use the data
  2831. * }).otherwise(function(error) {
  2832. * // an error occurred
  2833. * });
  2834. *
  2835. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  2836. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  2837. */
  2838. Resource.prototype.fetchBlob = function () {
  2839. return this.fetch({
  2840. responseType : 'blob'
  2841. });
  2842. };
  2843. /**
  2844. * Creates a Resource and calls fetchBlob() on it.
  2845. *
  2846. * @param {String|Object} options A url or an object with the following properties
  2847. * @param {String} options.url The url of the resource.
  2848. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  2849. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  2850. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2851. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2852. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  2853. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  2854. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2855. * @returns {Promise.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2856. */
  2857. Resource.fetchBlob = function (options) {
  2858. var resource = new Resource(options);
  2859. return resource.fetchBlob();
  2860. };
  2861. /**
  2862. * Asynchronously loads the given image resource. Returns a promise that will resolve to
  2863. * an {@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap|ImageBitmap} if <code>preferImageBitmap</code> is true and the browser supports <code>createImageBitmap</code> or otherwise an
  2864. * {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement|Image} once loaded, or reject if the image failed to load.
  2865. *
  2866. * @param {Object} [options] An object with the following properties.
  2867. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  2868. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  2869. * @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  2870. * @returns {Promise.<ImageBitmap>|Promise.<Image>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2871. *
  2872. *
  2873. * @example
  2874. * // load a single image asynchronously
  2875. * resource.fetchImage().then(function(image) {
  2876. * // use the loaded image
  2877. * }).otherwise(function(error) {
  2878. * // an error occurred
  2879. * });
  2880. *
  2881. * // load several images in parallel
  2882. * when.all([resource1.fetchImage(), resource2.fetchImage()]).then(function(images) {
  2883. * // images is an array containing all the loaded images
  2884. * });
  2885. *
  2886. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  2887. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  2888. */
  2889. Resource.prototype.fetchImage = function (options) {
  2890. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  2891. var preferImageBitmap = when.defaultValue(options.preferImageBitmap, false);
  2892. var preferBlob = when.defaultValue(options.preferBlob, false);
  2893. var flipY = when.defaultValue(options.flipY, false);
  2894. checkAndResetRequest(this.request);
  2895. // We try to load the image normally if
  2896. // 1. Blobs aren't supported
  2897. // 2. It's a data URI
  2898. // 3. It's a blob URI
  2899. // 4. It doesn't have request headers and we preferBlob is false
  2900. if (!xhrBlobSupported || this.isDataUri || this.isBlobUri || (!this.hasHeaders && !preferBlob)) {
  2901. return fetchImage({
  2902. resource: this,
  2903. flipY: flipY,
  2904. preferImageBitmap: preferImageBitmap
  2905. });
  2906. }
  2907. var blobPromise = this.fetchBlob();
  2908. if (!when.defined(blobPromise)) {
  2909. return;
  2910. }
  2911. var supportsImageBitmap;
  2912. var useImageBitmap;
  2913. var generatedBlobResource;
  2914. var generatedBlob;
  2915. return Resource.supportsImageBitmapOptions()
  2916. .then(function(result) {
  2917. supportsImageBitmap = result;
  2918. useImageBitmap = supportsImageBitmap && preferImageBitmap;
  2919. return blobPromise;
  2920. })
  2921. .then(function(blob) {
  2922. if (!when.defined(blob)) {
  2923. return;
  2924. }
  2925. generatedBlob = blob;
  2926. if (useImageBitmap) {
  2927. return Resource.createImageBitmapFromBlob(blob, {
  2928. flipY: flipY,
  2929. premultiplyAlpha: false
  2930. });
  2931. }
  2932. var blobUrl = window.URL.createObjectURL(blob);
  2933. generatedBlobResource = new Resource({
  2934. url: blobUrl
  2935. });
  2936. return fetchImage({
  2937. resource: generatedBlobResource,
  2938. flipY: flipY,
  2939. preferImageBitmap: false
  2940. });
  2941. })
  2942. .then(function(image) {
  2943. if (!when.defined(image)) {
  2944. return;
  2945. }
  2946. // The blob object may be needed for use by a TileDiscardPolicy,
  2947. // so attach it to the image.
  2948. image.blob = generatedBlob;
  2949. if (useImageBitmap) {
  2950. return image;
  2951. }
  2952. window.URL.revokeObjectURL(generatedBlobResource.url);
  2953. return image;
  2954. })
  2955. .otherwise(function(error) {
  2956. if (when.defined(generatedBlobResource)) {
  2957. window.URL.revokeObjectURL(generatedBlobResource.url);
  2958. }
  2959. // If the blob load succeeded but the image decode failed, attach the blob
  2960. // to the error object for use by a TileDiscardPolicy.
  2961. // In particular, BingMapsImageryProvider uses this to detect the
  2962. // zero-length response that is returned when a tile is not available.
  2963. error.blob = generatedBlob;
  2964. return when.when.reject(error);
  2965. });
  2966. };
  2967. /**
  2968. * Fetches an image and returns a promise to it.
  2969. *
  2970. * @param {Object} [options] An object with the following properties.
  2971. * @param {Resource} [options.resource] Resource object that points to an image to fetch.
  2972. * @param {Boolean} [options.preferImageBitmap] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  2973. * @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  2974. *
  2975. * @private
  2976. */
  2977. function fetchImage(options) {
  2978. var resource = options.resource;
  2979. var flipY = options.flipY;
  2980. var preferImageBitmap = options.preferImageBitmap;
  2981. var request = resource.request;
  2982. request.url = resource.url;
  2983. request.requestFunction = function() {
  2984. var crossOrigin = false;
  2985. // data URIs can't have crossorigin set.
  2986. if (!resource.isDataUri && !resource.isBlobUri) {
  2987. crossOrigin = resource.isCrossOriginUrl;
  2988. }
  2989. var deferred = when.when.defer();
  2990. Resource._Implementations.createImage(request, crossOrigin, deferred, flipY, preferImageBitmap);
  2991. return deferred.promise;
  2992. };
  2993. var promise = RequestScheduler.request(request);
  2994. if (!when.defined(promise)) {
  2995. return;
  2996. }
  2997. return promise
  2998. .otherwise(function(e) {
  2999. // Don't retry cancelled or otherwise aborted requests
  3000. if (request.state !== RequestState$1.FAILED) {
  3001. return when.when.reject(e);
  3002. }
  3003. return resource.retryOnError(e)
  3004. .then(function(retry) {
  3005. if (retry) {
  3006. // Reset request so it can try again
  3007. request.state = RequestState$1.UNISSUED;
  3008. request.deferred = undefined;
  3009. return fetchImage({
  3010. resource: resource,
  3011. flipY: flipY,
  3012. preferImageBitmap: preferImageBitmap
  3013. });
  3014. }
  3015. return when.when.reject(e);
  3016. });
  3017. });
  3018. }
  3019. /**
  3020. * Creates a Resource and calls fetchImage() on it.
  3021. *
  3022. * @param {String|Object} options A url or an object with the following properties
  3023. * @param {String} options.url The url of the resource.
  3024. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3025. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3026. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3027. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3028. * @param {Boolean} [options.flipY=false] Whether to vertically flip the image during fetch and decode. Only applies when requesting an image and the browser supports <code>createImageBitmap</code>.
  3029. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3030. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3031. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3032. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  3033. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  3034. * @returns {Promise.<ImageBitmap>|Promise.<Image>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3035. */
  3036. Resource.fetchImage = function (options) {
  3037. var resource = new Resource(options);
  3038. return resource.fetchImage({
  3039. flipY: options.flipY,
  3040. preferBlob: options.preferBlob,
  3041. preferImageBitmap: options.preferImageBitmap
  3042. });
  3043. };
  3044. /**
  3045. * Asynchronously loads the given resource as text. Returns a promise that will resolve to
  3046. * a String once loaded, or reject if the resource failed to load. The data is loaded
  3047. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3048. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3049. *
  3050. * @returns {Promise.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3051. *
  3052. * @example
  3053. * // load text from a URL, setting a custom header
  3054. * var resource = new Resource({
  3055. * url: 'http://someUrl.com/someJson.txt',
  3056. * headers: {
  3057. * 'X-Custom-Header' : 'some value'
  3058. * }
  3059. * });
  3060. * resource.fetchText().then(function(text) {
  3061. * // Do something with the text
  3062. * }).otherwise(function(error) {
  3063. * // an error occurred
  3064. * });
  3065. *
  3066. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  3067. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3068. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3069. */
  3070. Resource.prototype.fetchText = function() {
  3071. return this.fetch({
  3072. responseType : 'text'
  3073. });
  3074. };
  3075. /**
  3076. * Creates a Resource and calls fetchText() on it.
  3077. *
  3078. * @param {String|Object} options A url or an object with the following properties
  3079. * @param {String} options.url The url of the resource.
  3080. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3081. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3082. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3083. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3084. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3085. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3086. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3087. * @returns {Promise.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3088. */
  3089. Resource.fetchText = function (options) {
  3090. var resource = new Resource(options);
  3091. return resource.fetchText();
  3092. };
  3093. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  3094. /**
  3095. * Asynchronously loads the given resource as JSON. Returns a promise that will resolve to
  3096. * a JSON object once loaded, or reject if the resource failed to load. The data is loaded
  3097. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3098. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  3099. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  3100. * already specified.
  3101. *
  3102. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3103. *
  3104. *
  3105. * @example
  3106. * resource.fetchJson().then(function(jsonData) {
  3107. * // Do something with the JSON object
  3108. * }).otherwise(function(error) {
  3109. * // an error occurred
  3110. * });
  3111. *
  3112. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3113. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3114. */
  3115. Resource.prototype.fetchJson = function() {
  3116. var promise = this.fetch({
  3117. responseType : 'text',
  3118. headers: {
  3119. Accept : 'application/json,*/*;q=0.01'
  3120. }
  3121. });
  3122. if (!when.defined(promise)) {
  3123. return undefined;
  3124. }
  3125. return promise
  3126. .then(function(value) {
  3127. if (!when.defined(value)) {
  3128. return;
  3129. }
  3130. return JSON.parse(value);
  3131. });
  3132. };
  3133. /**
  3134. * Creates a Resource and calls fetchJson() on it.
  3135. *
  3136. * @param {String|Object} options A url or an object with the following properties
  3137. * @param {String} options.url The url of the resource.
  3138. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3139. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3140. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3141. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3142. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3143. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3144. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3145. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3146. */
  3147. Resource.fetchJson = function (options) {
  3148. var resource = new Resource(options);
  3149. return resource.fetchJson();
  3150. };
  3151. /**
  3152. * Asynchronously loads the given resource as XML. Returns a promise that will resolve to
  3153. * an XML Document once loaded, or reject if the resource failed to load. The data is loaded
  3154. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3155. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3156. *
  3157. * @returns {Promise.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3158. *
  3159. *
  3160. * @example
  3161. * // load XML from a URL, setting a custom header
  3162. * Cesium.loadXML('http://someUrl.com/someXML.xml', {
  3163. * 'X-Custom-Header' : 'some value'
  3164. * }).then(function(document) {
  3165. * // Do something with the document
  3166. * }).otherwise(function(error) {
  3167. * // an error occurred
  3168. * });
  3169. *
  3170. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  3171. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3172. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3173. */
  3174. Resource.prototype.fetchXML = function() {
  3175. return this.fetch({
  3176. responseType : 'document',
  3177. overrideMimeType : 'text/xml'
  3178. });
  3179. };
  3180. /**
  3181. * Creates a Resource and calls fetchXML() on it.
  3182. *
  3183. * @param {String|Object} options A url or an object with the following properties
  3184. * @param {String} options.url The url of the resource.
  3185. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3186. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3187. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3188. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3189. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3190. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3191. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3192. * @returns {Promise.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3193. */
  3194. Resource.fetchXML = function (options) {
  3195. var resource = new Resource(options);
  3196. return resource.fetchXML();
  3197. };
  3198. /**
  3199. * Requests a resource using JSONP.
  3200. *
  3201. * @param {String} [callbackParameterName='callback'] The callback parameter name that the server expects.
  3202. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3203. *
  3204. *
  3205. * @example
  3206. * // load a data asynchronously
  3207. * resource.fetchJsonp().then(function(data) {
  3208. * // use the loaded data
  3209. * }).otherwise(function(error) {
  3210. * // an error occurred
  3211. * });
  3212. *
  3213. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3214. */
  3215. Resource.prototype.fetchJsonp = function(callbackParameterName) {
  3216. callbackParameterName = when.defaultValue(callbackParameterName, 'callback');
  3217. checkAndResetRequest(this.request);
  3218. //generate a unique function name
  3219. var functionName;
  3220. do {
  3221. functionName = 'loadJsonp' + Math.random().toString().substring(2, 8);
  3222. } while (when.defined(window[functionName]));
  3223. return fetchJsonp(this, callbackParameterName, functionName);
  3224. };
  3225. function fetchJsonp(resource, callbackParameterName, functionName) {
  3226. var callbackQuery = {};
  3227. callbackQuery[callbackParameterName] = functionName;
  3228. resource.setQueryParameters(callbackQuery);
  3229. var request = resource.request;
  3230. request.url = resource.url;
  3231. request.requestFunction = function() {
  3232. var deferred = when.when.defer();
  3233. //assign a function with that name in the global scope
  3234. window[functionName] = function(data) {
  3235. deferred.resolve(data);
  3236. try {
  3237. delete window[functionName];
  3238. } catch (e) {
  3239. window[functionName] = undefined;
  3240. }
  3241. };
  3242. Resource._Implementations.loadAndExecuteScript(resource.url, functionName, deferred);
  3243. return deferred.promise;
  3244. };
  3245. var promise = RequestScheduler.request(request);
  3246. if (!when.defined(promise)) {
  3247. return;
  3248. }
  3249. return promise
  3250. .otherwise(function(e) {
  3251. if (request.state !== RequestState$1.FAILED) {
  3252. return when.when.reject(e);
  3253. }
  3254. return resource.retryOnError(e)
  3255. .then(function(retry) {
  3256. if (retry) {
  3257. // Reset request so it can try again
  3258. request.state = RequestState$1.UNISSUED;
  3259. request.deferred = undefined;
  3260. return fetchJsonp(resource, callbackParameterName, functionName);
  3261. }
  3262. return when.when.reject(e);
  3263. });
  3264. });
  3265. }
  3266. /**
  3267. * Creates a Resource from a URL and calls fetchJsonp() on it.
  3268. *
  3269. * @param {String|Object} options A url or an object with the following properties
  3270. * @param {String} options.url The url of the resource.
  3271. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3272. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3273. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3274. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3275. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3276. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3277. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3278. * @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects.
  3279. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3280. */
  3281. Resource.fetchJsonp = function (options) {
  3282. var resource = new Resource(options);
  3283. return resource.fetchJsonp(options.callbackParameterName);
  3284. };
  3285. /**
  3286. * @private
  3287. */
  3288. Resource.prototype._makeRequest = function(options) {
  3289. var resource = this;
  3290. checkAndResetRequest(resource.request);
  3291. var request = resource.request;
  3292. request.url = resource.url;
  3293. request.requestFunction = function(url) {
  3294. var responseType = options.responseType;
  3295. var headers = combine(options.headers, resource.headers);
  3296. var overrideMimeType = options.overrideMimeType;
  3297. var method = options.method;
  3298. var data = options.data;
  3299. var deferred = when.when.defer();
  3300. var newUrl = when.defined(url) ? url : resource.url;
  3301. var xhr = Resource._Implementations.loadWithXhr(newUrl, responseType, method, data, headers, deferred, overrideMimeType);
  3302. if (when.defined(xhr) && when.defined(xhr.abort)) {
  3303. request.cancelFunction = function() {
  3304. xhr.abort();
  3305. };
  3306. }
  3307. return deferred.promise;
  3308. };
  3309. var promise = RequestScheduler.request(request);
  3310. if (!when.defined(promise)) {
  3311. return;
  3312. }
  3313. return promise
  3314. .then(function(data) {
  3315. return data;
  3316. })
  3317. .otherwise(function(e) {
  3318. if (request.state !== RequestState$1.FAILED) {
  3319. return when.when.reject(e);
  3320. }
  3321. return resource.retryOnError(e)
  3322. .then(function(retry) {
  3323. if (retry) {
  3324. // Reset request so it can try again
  3325. request.state = RequestState$1.UNISSUED;
  3326. request.deferred = undefined;
  3327. return resource.fetch(options);
  3328. }
  3329. return when.when.reject(e);
  3330. });
  3331. });
  3332. };
  3333. var dataUriRegex$1 = /^data:(.*?)(;base64)?,(.*)$/;
  3334. function decodeDataUriText(isBase64, data) {
  3335. var result = decodeURIComponent(data);
  3336. if (isBase64) {
  3337. return atob(result);
  3338. }
  3339. return result;
  3340. }
  3341. function decodeDataUriArrayBuffer(isBase64, data) {
  3342. var byteString = decodeDataUriText(isBase64, data);
  3343. var buffer = new ArrayBuffer(byteString.length);
  3344. var view = new Uint8Array(buffer);
  3345. for (var i = 0; i < byteString.length; i++) {
  3346. view[i] = byteString.charCodeAt(i);
  3347. }
  3348. return buffer;
  3349. }
  3350. function decodeDataUri(dataUriRegexResult, responseType) {
  3351. responseType = when.defaultValue(responseType, '');
  3352. var mimeType = dataUriRegexResult[1];
  3353. var isBase64 = !!dataUriRegexResult[2];
  3354. var data = dataUriRegexResult[3];
  3355. switch (responseType) {
  3356. case '':
  3357. case 'text':
  3358. return decodeDataUriText(isBase64, data);
  3359. case 'arraybuffer':
  3360. return decodeDataUriArrayBuffer(isBase64, data);
  3361. case 'blob':
  3362. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  3363. return new Blob([buffer], {
  3364. type : mimeType
  3365. });
  3366. case 'document':
  3367. var parser = new DOMParser();
  3368. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  3369. case 'json':
  3370. return JSON.parse(decodeDataUriText(isBase64, data));
  3371. default:
  3372. //>>includeStart('debug', pragmas.debug);
  3373. throw new Check.DeveloperError('Unhandled responseType: ' + responseType);
  3374. //>>includeEnd('debug');
  3375. }
  3376. }
  3377. /**
  3378. * Asynchronously loads the given resource. Returns a promise that will resolve to
  3379. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3380. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3381. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. It's recommended that you use
  3382. * the more specific functions eg. fetchJson, fetchBlob, etc.
  3383. *
  3384. * @param {Object} [options] Object with the following properties:
  3385. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3386. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3387. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3388. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3389. *
  3390. *
  3391. * @example
  3392. * resource.fetch()
  3393. * .then(function(body) {
  3394. * // use the data
  3395. * }).otherwise(function(error) {
  3396. * // an error occurred
  3397. * });
  3398. *
  3399. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3400. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3401. */
  3402. Resource.prototype.fetch = function(options) {
  3403. options = defaultClone(options, {});
  3404. options.method = 'GET';
  3405. return this._makeRequest(options);
  3406. };
  3407. /**
  3408. * Creates a Resource from a URL and calls fetch() on it.
  3409. *
  3410. * @param {String|Object} options A url or an object with the following properties
  3411. * @param {String} options.url The url of the resource.
  3412. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3413. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3414. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3415. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3416. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3417. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3418. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3419. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3420. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3421. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3422. */
  3423. Resource.fetch = function (options) {
  3424. var resource = new Resource(options);
  3425. return resource.fetch({
  3426. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3427. responseType: options.responseType,
  3428. overrideMimeType: options.overrideMimeType
  3429. });
  3430. };
  3431. /**
  3432. * Asynchronously deletes the given resource. Returns a promise that will resolve to
  3433. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3434. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3435. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3436. *
  3437. * @param {Object} [options] Object with the following properties:
  3438. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3439. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3440. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3441. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3442. *
  3443. *
  3444. * @example
  3445. * resource.delete()
  3446. * .then(function(body) {
  3447. * // use the data
  3448. * }).otherwise(function(error) {
  3449. * // an error occurred
  3450. * });
  3451. *
  3452. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3453. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3454. */
  3455. Resource.prototype.delete = function(options) {
  3456. options = defaultClone(options, {});
  3457. options.method = 'DELETE';
  3458. return this._makeRequest(options);
  3459. };
  3460. /**
  3461. * Creates a Resource from a URL and calls delete() on it.
  3462. *
  3463. * @param {String|Object} options A url or an object with the following properties
  3464. * @param {String} options.url The url of the resource.
  3465. * @param {Object} [options.data] Data that is posted with the resource.
  3466. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3467. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3468. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3469. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3470. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3471. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3472. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3473. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3474. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3475. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3476. */
  3477. Resource.delete = function (options) {
  3478. var resource = new Resource(options);
  3479. return resource.delete({
  3480. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3481. responseType: options.responseType,
  3482. overrideMimeType: options.overrideMimeType,
  3483. data: options.data
  3484. });
  3485. };
  3486. /**
  3487. * Asynchronously gets headers the given resource. Returns a promise that will resolve to
  3488. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3489. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3490. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3491. *
  3492. * @param {Object} [options] Object with the following properties:
  3493. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3494. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3495. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3496. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3497. *
  3498. *
  3499. * @example
  3500. * resource.head()
  3501. * .then(function(headers) {
  3502. * // use the data
  3503. * }).otherwise(function(error) {
  3504. * // an error occurred
  3505. * });
  3506. *
  3507. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3508. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3509. */
  3510. Resource.prototype.head = function(options) {
  3511. options = defaultClone(options, {});
  3512. options.method = 'HEAD';
  3513. return this._makeRequest(options);
  3514. };
  3515. /**
  3516. * Creates a Resource from a URL and calls head() on it.
  3517. *
  3518. * @param {String|Object} options A url or an object with the following properties
  3519. * @param {String} options.url The url of the resource.
  3520. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3521. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3522. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3523. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3524. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3525. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3526. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3527. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3528. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3529. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3530. */
  3531. Resource.head = function (options) {
  3532. var resource = new Resource(options);
  3533. return resource.head({
  3534. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3535. responseType: options.responseType,
  3536. overrideMimeType: options.overrideMimeType
  3537. });
  3538. };
  3539. /**
  3540. * Asynchronously gets options the given resource. Returns a promise that will resolve to
  3541. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3542. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3543. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3544. *
  3545. * @param {Object} [options] Object with the following properties:
  3546. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3547. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3548. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3549. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3550. *
  3551. *
  3552. * @example
  3553. * resource.options()
  3554. * .then(function(headers) {
  3555. * // use the data
  3556. * }).otherwise(function(error) {
  3557. * // an error occurred
  3558. * });
  3559. *
  3560. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3561. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3562. */
  3563. Resource.prototype.options = function(options) {
  3564. options = defaultClone(options, {});
  3565. options.method = 'OPTIONS';
  3566. return this._makeRequest(options);
  3567. };
  3568. /**
  3569. * Creates a Resource from a URL and calls options() on it.
  3570. *
  3571. * @param {String|Object} options A url or an object with the following properties
  3572. * @param {String} options.url The url of the resource.
  3573. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3574. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3575. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3576. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3577. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3578. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3579. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3580. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3581. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3582. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3583. */
  3584. Resource.options = function (options) {
  3585. var resource = new Resource(options);
  3586. return resource.options({
  3587. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3588. responseType: options.responseType,
  3589. overrideMimeType: options.overrideMimeType
  3590. });
  3591. };
  3592. /**
  3593. * Asynchronously posts data to the given resource. Returns a promise that will resolve to
  3594. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3595. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3596. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3597. *
  3598. * @param {Object} data Data that is posted with the resource.
  3599. * @param {Object} [options] Object with the following properties:
  3600. * @param {Object} [options.data] Data that is posted with the resource.
  3601. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3602. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3603. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3604. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3605. *
  3606. *
  3607. * @example
  3608. * resource.post(data)
  3609. * .then(function(result) {
  3610. * // use the result
  3611. * }).otherwise(function(error) {
  3612. * // an error occurred
  3613. * });
  3614. *
  3615. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3616. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3617. */
  3618. Resource.prototype.post = function(data, options) {
  3619. Check.Check.defined('data', data);
  3620. options = defaultClone(options, {});
  3621. options.method = 'POST';
  3622. options.data = data;
  3623. return this._makeRequest(options);
  3624. };
  3625. /**
  3626. * Creates a Resource from a URL and calls post() on it.
  3627. *
  3628. * @param {Object} options A url or an object with the following properties
  3629. * @param {String} options.url The url of the resource.
  3630. * @param {Object} options.data Data that is posted with the resource.
  3631. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3632. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3633. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3634. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3635. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3636. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3637. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3638. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3639. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3640. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3641. */
  3642. Resource.post = function (options) {
  3643. var resource = new Resource(options);
  3644. return resource.post(options.data, {
  3645. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  3646. responseType: options.responseType,
  3647. overrideMimeType: options.overrideMimeType
  3648. });
  3649. };
  3650. /**
  3651. * Asynchronously puts data to the given resource. Returns a promise that will resolve to
  3652. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3653. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3654. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3655. *
  3656. * @param {Object} data Data that is posted with the resource.
  3657. * @param {Object} [options] Object with the following properties:
  3658. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3659. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3660. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3661. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3662. *
  3663. *
  3664. * @example
  3665. * resource.put(data)
  3666. * .then(function(result) {
  3667. * // use the result
  3668. * }).otherwise(function(error) {
  3669. * // an error occurred
  3670. * });
  3671. *
  3672. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3673. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3674. */
  3675. Resource.prototype.put = function(data, options) {
  3676. Check.Check.defined('data', data);
  3677. options = defaultClone(options, {});
  3678. options.method = 'PUT';
  3679. options.data = data;
  3680. return this._makeRequest(options);
  3681. };
  3682. /**
  3683. * Creates a Resource from a URL and calls put() on it.
  3684. *
  3685. * @param {Object} options A url or an object with the following properties
  3686. * @param {String} options.url The url of the resource.
  3687. * @param {Object} options.data Data that is posted with the resource.
  3688. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3689. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3690. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3691. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3692. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3693. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3694. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3695. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3696. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3697. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3698. */
  3699. Resource.put = function (options) {
  3700. var resource = new Resource(options);
  3701. return resource.put(options.data, {
  3702. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  3703. responseType: options.responseType,
  3704. overrideMimeType: options.overrideMimeType
  3705. });
  3706. };
  3707. /**
  3708. * Asynchronously patches data to the given resource. Returns a promise that will resolve to
  3709. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3710. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3711. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3712. *
  3713. * @param {Object} data Data that is posted with the resource.
  3714. * @param {Object} [options] Object with the following properties:
  3715. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3716. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3717. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3718. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3719. *
  3720. *
  3721. * @example
  3722. * resource.patch(data)
  3723. * .then(function(result) {
  3724. * // use the result
  3725. * }).otherwise(function(error) {
  3726. * // an error occurred
  3727. * });
  3728. *
  3729. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3730. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3731. */
  3732. Resource.prototype.patch = function(data, options) {
  3733. Check.Check.defined('data', data);
  3734. options = defaultClone(options, {});
  3735. options.method = 'PATCH';
  3736. options.data = data;
  3737. return this._makeRequest(options);
  3738. };
  3739. /**
  3740. * Creates a Resource from a URL and calls patch() on it.
  3741. *
  3742. * @param {Object} options A url or an object with the following properties
  3743. * @param {String} options.url The url of the resource.
  3744. * @param {Object} options.data Data that is posted with the resource.
  3745. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3746. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3747. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3748. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3749. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3750. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3751. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3752. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3753. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3754. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3755. */
  3756. Resource.patch = function (options) {
  3757. var resource = new Resource(options);
  3758. return resource.patch(options.data, {
  3759. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  3760. responseType: options.responseType,
  3761. overrideMimeType: options.overrideMimeType
  3762. });
  3763. };
  3764. /**
  3765. * Contains implementations of functions that can be replaced for testing
  3766. *
  3767. * @private
  3768. */
  3769. Resource._Implementations = {};
  3770. function loadImageElement(url, crossOrigin, deferred) {
  3771. var image = new Image();
  3772. image.onload = function() {
  3773. deferred.resolve(image);
  3774. };
  3775. image.onerror = function(e) {
  3776. deferred.reject(e);
  3777. };
  3778. if (crossOrigin) {
  3779. if (TrustedServers.contains(url)) {
  3780. image.crossOrigin = 'use-credentials';
  3781. } else {
  3782. image.crossOrigin = '';
  3783. }
  3784. }
  3785. image.src = url;
  3786. }
  3787. Resource._Implementations.createImage = function(request, crossOrigin, deferred, flipY, preferImageBitmap) {
  3788. var url = request.url;
  3789. // Passing an Image to createImageBitmap will force it to run on the main thread
  3790. // since DOM elements don't exist on workers. We convert it to a blob so it's non-blocking.
  3791. // See:
  3792. // https://bugzilla.mozilla.org/show_bug.cgi?id=1044102#c38
  3793. // https://bugs.chromium.org/p/chromium/issues/detail?id=580202#c10
  3794. Resource.supportsImageBitmapOptions()
  3795. .then(function(supportsImageBitmap) {
  3796. // We can only use ImageBitmap if we can flip on decode.
  3797. // See: https://github.com/CesiumGS/cesium/pull/7579#issuecomment-466146898
  3798. if (!(supportsImageBitmap && preferImageBitmap)) {
  3799. loadImageElement(url, crossOrigin, deferred);
  3800. return;
  3801. }
  3802. var responseType = 'blob';
  3803. var method = 'GET';
  3804. var xhrDeferred = when.when.defer();
  3805. var xhr = Resource._Implementations.loadWithXhr(
  3806. url,
  3807. responseType,
  3808. method,
  3809. undefined,
  3810. undefined,
  3811. xhrDeferred,
  3812. undefined,
  3813. undefined,
  3814. undefined
  3815. );
  3816. if (when.defined(xhr) && when.defined(xhr.abort)) {
  3817. request.cancelFunction = function() {
  3818. xhr.abort();
  3819. };
  3820. }
  3821. return xhrDeferred.promise.then(function(blob) {
  3822. if (!when.defined(blob)) {
  3823. deferred.reject(new RuntimeError.RuntimeError('Successfully retrieved ' + url + ' but it contained no content.'));
  3824. return;
  3825. }
  3826. return Resource.createImageBitmapFromBlob(blob, {
  3827. flipY: flipY,
  3828. premultiplyAlpha: false
  3829. });
  3830. }).then(deferred.resolve);
  3831. })
  3832. .otherwise(deferred.reject);
  3833. };
  3834. /**
  3835. * Wrapper for createImageBitmap
  3836. *
  3837. * @private
  3838. */
  3839. Resource.createImageBitmapFromBlob = function(blob, options) {
  3840. Check.Check.defined('options', options);
  3841. Check.Check.typeOf.bool('options.flipY', options.flipY);
  3842. Check.Check.typeOf.bool('options.premultiplyAlpha', options.premultiplyAlpha);
  3843. return createImageBitmap(blob, {
  3844. imageOrientation: options.flipY ? 'flipY' : 'none',
  3845. premultiplyAlpha: options.premultiplyAlpha ? 'premultiply' : 'none'
  3846. });
  3847. };
  3848. function decodeResponse(loadWithHttpResponse, responseType) {
  3849. switch (responseType) {
  3850. case 'text':
  3851. return loadWithHttpResponse.toString('utf8');
  3852. case 'json':
  3853. return JSON.parse(loadWithHttpResponse.toString('utf8'));
  3854. default:
  3855. return new Uint8Array(loadWithHttpResponse).buffer;
  3856. }
  3857. }
  3858. function loadWithHttpRequest(url, responseType, method, data, headers, deferred, overrideMimeType) {
  3859. // Note: only the 'json' and 'text' responseTypes transforms the loaded buffer
  3860. var URL = require('url').parse(url); // eslint-disable-line
  3861. var http = URL.protocol === 'https:' ? require('https') : require('http'); // eslint-disable-line
  3862. var zlib = require('zlib'); // eslint-disable-line
  3863. var options = {
  3864. protocol : URL.protocol,
  3865. hostname : URL.hostname,
  3866. port : URL.port,
  3867. path : URL.path,
  3868. query : URL.query,
  3869. method : method,
  3870. headers : headers
  3871. };
  3872. http.request(options)
  3873. .on('response', function(res) {
  3874. if (res.statusCode < 200 || res.statusCode >= 300) {
  3875. deferred.reject(new RequestErrorEvent(res.statusCode, res, res.headers));
  3876. return;
  3877. }
  3878. var chunkArray = [];
  3879. res.on('data', function(chunk) {
  3880. chunkArray.push(chunk);
  3881. });
  3882. res.on('end', function() {
  3883. var result = Buffer.concat(chunkArray); // eslint-disable-line
  3884. if (res.headers['content-encoding'] === 'gzip') {
  3885. zlib.gunzip(result, function(error, resultUnzipped) {
  3886. if (error) {
  3887. deferred.reject(new RuntimeError.RuntimeError('Error decompressing response.'));
  3888. } else {
  3889. deferred.resolve(decodeResponse(resultUnzipped, responseType));
  3890. }
  3891. });
  3892. } else {
  3893. deferred.resolve(decodeResponse(result, responseType));
  3894. }
  3895. });
  3896. }).on('error', function(e) {
  3897. deferred.reject(new RequestErrorEvent());
  3898. }).end();
  3899. }
  3900. var noXMLHttpRequest = typeof XMLHttpRequest === 'undefined';
  3901. Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  3902. var dataUriRegexResult = dataUriRegex$1.exec(url);
  3903. if (dataUriRegexResult !== null) {
  3904. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  3905. return;
  3906. }
  3907. if (noXMLHttpRequest) {
  3908. loadWithHttpRequest(url, responseType, method, data, headers, deferred);
  3909. return;
  3910. }
  3911. var xhr = new XMLHttpRequest();
  3912. if (TrustedServers.contains(url)) {
  3913. xhr.withCredentials = true;
  3914. }
  3915. url = url.replace(/{/g, '%7B').replace(/}/g, '%7D');
  3916. xhr.open(method, url, true);
  3917. if (when.defined(overrideMimeType) && when.defined(xhr.overrideMimeType)) {
  3918. xhr.overrideMimeType(overrideMimeType);
  3919. }
  3920. if (when.defined(headers)) {
  3921. for (var key in headers) {
  3922. if (headers.hasOwnProperty(key)) {
  3923. xhr.setRequestHeader(key, headers[key]);
  3924. }
  3925. }
  3926. }
  3927. if (when.defined(responseType)) {
  3928. xhr.responseType = responseType;
  3929. }
  3930. // While non-standard, file protocol always returns a status of 0 on success
  3931. var localFile = false;
  3932. if (typeof url === 'string') {
  3933. localFile = (url.indexOf('file://') === 0) || (typeof window !== 'undefined' && window.location.origin === 'file://');
  3934. }
  3935. xhr.onload = function() {
  3936. if ((xhr.status < 200 || xhr.status >= 300) && !(localFile && xhr.status === 0)) {
  3937. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  3938. return;
  3939. }
  3940. var response = xhr.response;
  3941. var browserResponseType = xhr.responseType;
  3942. if (method === 'HEAD' || method === 'OPTIONS') {
  3943. var responseHeaderString = xhr.getAllResponseHeaders();
  3944. var splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
  3945. var responseHeaders = {};
  3946. splitHeaders.forEach(function (line) {
  3947. var parts = line.split(': ');
  3948. var header = parts.shift();
  3949. responseHeaders[header] = parts.join(': ');
  3950. });
  3951. deferred.resolve(responseHeaders);
  3952. return;
  3953. }
  3954. //All modern browsers will go into either the first or second if block or last else block.
  3955. //Other code paths support older browsers that either do not support the supplied responseType
  3956. //or do not support the xhr.response property.
  3957. if (xhr.status === 204) {
  3958. // accept no content
  3959. deferred.resolve();
  3960. } else if (when.defined(response) && (!when.defined(responseType) || (browserResponseType === responseType))) {
  3961. deferred.resolve(response);
  3962. } else if ((responseType === 'json') && typeof response === 'string') {
  3963. try {
  3964. deferred.resolve(JSON.parse(response));
  3965. } catch (e) {
  3966. deferred.reject(e);
  3967. }
  3968. } else if ((browserResponseType === '' || browserResponseType === 'document') && when.defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  3969. deferred.resolve(xhr.responseXML);
  3970. } else if ((browserResponseType === '' || browserResponseType === 'text') && when.defined(xhr.responseText)) {
  3971. deferred.resolve(xhr.responseText);
  3972. } else {
  3973. deferred.reject(new RuntimeError.RuntimeError('Invalid XMLHttpRequest response type.'));
  3974. }
  3975. };
  3976. xhr.onerror = function(e) {
  3977. deferred.reject(new RequestErrorEvent());
  3978. };
  3979. xhr.send(data);
  3980. return xhr;
  3981. };
  3982. Resource._Implementations.loadAndExecuteScript = function(url, functionName, deferred) {
  3983. return loadAndExecuteScript(url).otherwise(deferred.reject);
  3984. };
  3985. /**
  3986. * The default implementations
  3987. *
  3988. * @private
  3989. */
  3990. Resource._DefaultImplementations = {};
  3991. Resource._DefaultImplementations.createImage = Resource._Implementations.createImage;
  3992. Resource._DefaultImplementations.loadWithXhr = Resource._Implementations.loadWithXhr;
  3993. Resource._DefaultImplementations.loadAndExecuteScript = Resource._Implementations.loadAndExecuteScript;
  3994. /**
  3995. * A resource instance initialized to the current browser location
  3996. *
  3997. * @type {Resource}
  3998. * @constant
  3999. */
  4000. Resource.DEFAULT = Object.freeze(new Resource({
  4001. url: (typeof document === 'undefined') ? '' : document.location.href.split('?')[0]
  4002. }));
  4003. /*global CESIUM_BASE_URL*/
  4004. var cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js$/;
  4005. function getBaseUrlFromCesiumScript() {
  4006. var scripts = document.getElementsByTagName('script');
  4007. for ( var i = 0, len = scripts.length; i < len; ++i) {
  4008. var src = scripts[i].getAttribute('src');
  4009. var result = cesiumScriptRegex.exec(src);
  4010. if (result !== null) {
  4011. return result[1];
  4012. }
  4013. }
  4014. return undefined;
  4015. }
  4016. var a$1;
  4017. function tryMakeAbsolute(url) {
  4018. if (typeof document === 'undefined') {
  4019. //Node.js and Web Workers. In both cases, the URL will already be absolute.
  4020. return url;
  4021. }
  4022. if (!when.defined(a$1)) {
  4023. a$1 = document.createElement('a');
  4024. }
  4025. a$1.href = url;
  4026. // IE only absolutizes href on get, not set
  4027. a$1.href = a$1.href; // eslint-disable-line no-self-assign
  4028. return a$1.href;
  4029. }
  4030. var baseResource;
  4031. function getCesiumBaseUrl() {
  4032. if (when.defined(baseResource)) {
  4033. return baseResource;
  4034. }
  4035. var baseUrlString;
  4036. if (typeof CESIUM_BASE_URL !== 'undefined') {
  4037. baseUrlString = CESIUM_BASE_URL;
  4038. } else if (typeof define === 'object' && when.defined(define.amd) && !define.amd.toUrlUndefined && when.defined(require.toUrl)) {
  4039. baseUrlString = getAbsoluteUri('..', buildModuleUrl('Core/buildModuleUrl.js'));
  4040. } else {
  4041. baseUrlString = getBaseUrlFromCesiumScript();
  4042. }
  4043. //>>includeStart('debug', pragmas.debug);
  4044. if (!when.defined(baseUrlString)) {
  4045. throw new Check.DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  4046. }
  4047. //>>includeEnd('debug');
  4048. baseResource = new Resource({
  4049. url: tryMakeAbsolute(baseUrlString)
  4050. });
  4051. baseResource.appendForwardSlash();
  4052. return baseResource;
  4053. }
  4054. function buildModuleUrlFromRequireToUrl(moduleID) {
  4055. //moduleID will be non-relative, so require it relative to this module, in Core.
  4056. return tryMakeAbsolute(require.toUrl('../' + moduleID));
  4057. }
  4058. function buildModuleUrlFromBaseUrl(moduleID) {
  4059. var resource = getCesiumBaseUrl().getDerivedResource({
  4060. url: moduleID
  4061. });
  4062. return resource.url;
  4063. }
  4064. var implementation;
  4065. /**
  4066. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  4067. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  4068. * the base URL of the Cesium.js script.
  4069. *
  4070. * @private
  4071. */
  4072. function buildModuleUrl(moduleID) {
  4073. if (!when.defined(implementation)) {
  4074. //select implementation
  4075. if (typeof define === 'object' && when.defined(define.amd) && !define.amd.toUrlUndefined && when.defined(require.toUrl)) {
  4076. implementation = buildModuleUrlFromRequireToUrl;
  4077. } else {
  4078. implementation = buildModuleUrlFromBaseUrl;
  4079. }
  4080. }
  4081. var url = implementation(moduleID);
  4082. return url;
  4083. }
  4084. // exposed for testing
  4085. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  4086. buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
  4087. buildModuleUrl._clearBaseResource = function() {
  4088. baseResource = undefined;
  4089. };
  4090. /**
  4091. * Sets the base URL for resolving modules.
  4092. * @param {String} value The new base URL.
  4093. */
  4094. buildModuleUrl.setBaseUrl = function(value) {
  4095. baseResource = Resource.DEFAULT.getDerivedResource({
  4096. url: value
  4097. });
  4098. };
  4099. /**
  4100. * Gets the base URL for resolving modules.
  4101. */
  4102. buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
  4103. exports.Resource = Resource;
  4104. exports.buildModuleUrl = buildModuleUrl;
  4105. exports.deprecationWarning = deprecationWarning;
  4106. exports.oneTimeWarning = oneTimeWarning;
  4107. });