cos-wx-sdk-v5.js 452 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083
  1. (function webpackUniversalModuleDefinition(root, factory) {
  2. if(typeof exports === 'object' && typeof module === 'object')
  3. module.exports = factory();
  4. else if(typeof define === 'function' && define.amd)
  5. define([], factory);
  6. else if(typeof exports === 'object')
  7. exports["COS"] = factory();
  8. else
  9. root["COS"] = factory();
  10. })(window, function() {
  11. return /******/ (function(modules) { // webpackBootstrap
  12. /******/ // The module cache
  13. /******/ var installedModules = {};
  14. /******/
  15. /******/ // The require function
  16. /******/ function __webpack_require__(moduleId) {
  17. /******/
  18. /******/ // Check if module is in cache
  19. /******/ if(installedModules[moduleId]) {
  20. /******/ return installedModules[moduleId].exports;
  21. /******/ }
  22. /******/ // Create a new module (and put it into the cache)
  23. /******/ var module = installedModules[moduleId] = {
  24. /******/ i: moduleId,
  25. /******/ l: false,
  26. /******/ exports: {}
  27. /******/ };
  28. /******/
  29. /******/ // Execute the module function
  30. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  31. /******/
  32. /******/ // Flag the module as loaded
  33. /******/ module.l = true;
  34. /******/
  35. /******/ // Return the exports of the module
  36. /******/ return module.exports;
  37. /******/ }
  38. /******/
  39. /******/
  40. /******/ // expose the modules object (__webpack_modules__)
  41. /******/ __webpack_require__.m = modules;
  42. /******/
  43. /******/ // expose the module cache
  44. /******/ __webpack_require__.c = installedModules;
  45. /******/
  46. /******/ // define getter function for harmony exports
  47. /******/ __webpack_require__.d = function(exports, name, getter) {
  48. /******/ if(!__webpack_require__.o(exports, name)) {
  49. /******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
  50. /******/ }
  51. /******/ };
  52. /******/
  53. /******/ // define __esModule on exports
  54. /******/ __webpack_require__.r = function(exports) {
  55. /******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
  56. /******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
  57. /******/ }
  58. /******/ Object.defineProperty(exports, '__esModule', { value: true });
  59. /******/ };
  60. /******/
  61. /******/ // create a fake namespace object
  62. /******/ // mode & 1: value is a module id, require it
  63. /******/ // mode & 2: merge all properties of value into the ns
  64. /******/ // mode & 4: return value when already ns object
  65. /******/ // mode & 8|1: behave like require
  66. /******/ __webpack_require__.t = function(value, mode) {
  67. /******/ if(mode & 1) value = __webpack_require__(value);
  68. /******/ if(mode & 8) return value;
  69. /******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
  70. /******/ var ns = Object.create(null);
  71. /******/ __webpack_require__.r(ns);
  72. /******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
  73. /******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
  74. /******/ return ns;
  75. /******/ };
  76. /******/
  77. /******/ // getDefaultExport function for compatibility with non-harmony modules
  78. /******/ __webpack_require__.n = function(module) {
  79. /******/ var getter = module && module.__esModule ?
  80. /******/ function getDefault() { return module['default']; } :
  81. /******/ function getModuleExports() { return module; };
  82. /******/ __webpack_require__.d(getter, 'a', getter);
  83. /******/ return getter;
  84. /******/ };
  85. /******/
  86. /******/ // Object.prototype.hasOwnProperty.call
  87. /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
  88. /******/
  89. /******/ // __webpack_public_path__
  90. /******/ __webpack_require__.p = "/Users/chrisftian/Documents/projects/cos-sdk/cos-wx-sdk-v5/demo/lib";
  91. /******/
  92. /******/
  93. /******/ // Load entry module and return exports
  94. /******/ return __webpack_require__(__webpack_require__.s = "./index.js");
  95. /******/ })
  96. /************************************************************************/
  97. /******/ ({
  98. /***/ "./index.js":
  99. /*!******************!*\
  100. !*** ./index.js ***!
  101. \******************/
  102. /*! no static exports found */
  103. /***/ (function(module, exports, __webpack_require__) {
  104. var COS = __webpack_require__(/*! ./src/cos */ "./src/cos.js");
  105. module.exports = COS;
  106. /***/ }),
  107. /***/ "./lib/base64.js":
  108. /*!***********************!*\
  109. !*** ./lib/base64.js ***!
  110. \***********************/
  111. /*! no static exports found */
  112. /***/ (function(module, exports) {
  113. /*
  114. * $Id: base64.js,v 2.15 2014/04/05 12:58:57 dankogai Exp dankogai $
  115. *
  116. * Licensed under the BSD 3-Clause License.
  117. * http://opensource.org/licenses/BSD-3-Clause
  118. *
  119. * References:
  120. * http://en.wikipedia.org/wiki/Base64
  121. */
  122. var Base64 = function (global) {
  123. global = global || {};
  124. 'use strict';
  125. // existing version for noConflict()
  126. var _Base64 = global.Base64;
  127. var version = "2.1.9";
  128. // if node.js, we use Buffer
  129. var buffer;
  130. // constants
  131. var b64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
  132. var b64tab = function (bin) {
  133. var t = {};
  134. for (var i = 0, l = bin.length; i < l; i++) t[bin.charAt(i)] = i;
  135. return t;
  136. }(b64chars);
  137. var fromCharCode = String.fromCharCode;
  138. // encoder stuff
  139. var cb_utob = function cb_utob(c) {
  140. if (c.length < 2) {
  141. var cc = c.charCodeAt(0);
  142. return cc < 0x80 ? c : cc < 0x800 ? fromCharCode(0xc0 | cc >>> 6) + fromCharCode(0x80 | cc & 0x3f) : fromCharCode(0xe0 | cc >>> 12 & 0x0f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);
  143. } else {
  144. var cc = 0x10000 + (c.charCodeAt(0) - 0xD800) * 0x400 + (c.charCodeAt(1) - 0xDC00);
  145. return fromCharCode(0xf0 | cc >>> 18 & 0x07) + fromCharCode(0x80 | cc >>> 12 & 0x3f) + fromCharCode(0x80 | cc >>> 6 & 0x3f) + fromCharCode(0x80 | cc & 0x3f);
  146. }
  147. };
  148. var re_utob = /[\uD800-\uDBFF][\uDC00-\uDFFFF]|[^\x00-\x7F]/g;
  149. var utob = function utob(u) {
  150. return u.replace(re_utob, cb_utob);
  151. };
  152. var cb_encode = function cb_encode(ccc) {
  153. var padlen = [0, 2, 1][ccc.length % 3],
  154. ord = ccc.charCodeAt(0) << 16 | (ccc.length > 1 ? ccc.charCodeAt(1) : 0) << 8 | (ccc.length > 2 ? ccc.charCodeAt(2) : 0),
  155. chars = [b64chars.charAt(ord >>> 18), b64chars.charAt(ord >>> 12 & 63), padlen >= 2 ? '=' : b64chars.charAt(ord >>> 6 & 63), padlen >= 1 ? '=' : b64chars.charAt(ord & 63)];
  156. return chars.join('');
  157. };
  158. var btoa = global.btoa ? function (b) {
  159. return global.btoa(b);
  160. } : function (b) {
  161. return b.replace(/[\s\S]{1,3}/g, cb_encode);
  162. };
  163. var _encode = buffer ? function (u) {
  164. return (u.constructor === buffer.constructor ? u : new buffer(u)).toString('base64');
  165. } : function (u) {
  166. return btoa(utob(u));
  167. };
  168. var encode = function encode(u, urisafe) {
  169. return !urisafe ? _encode(String(u)) : _encode(String(u)).replace(/[+\/]/g, function (m0) {
  170. return m0 == '+' ? '-' : '_';
  171. }).replace(/=/g, '');
  172. };
  173. var encodeURI = function encodeURI(u) {
  174. return encode(u, true);
  175. };
  176. // decoder stuff
  177. var re_btou = new RegExp(['[\xC0-\xDF][\x80-\xBF]', '[\xE0-\xEF][\x80-\xBF]{2}', '[\xF0-\xF7][\x80-\xBF]{3}'].join('|'), 'g');
  178. var cb_btou = function cb_btou(cccc) {
  179. switch (cccc.length) {
  180. case 4:
  181. var cp = (0x07 & cccc.charCodeAt(0)) << 18 | (0x3f & cccc.charCodeAt(1)) << 12 | (0x3f & cccc.charCodeAt(2)) << 6 | 0x3f & cccc.charCodeAt(3),
  182. offset = cp - 0x10000;
  183. return fromCharCode((offset >>> 10) + 0xD800) + fromCharCode((offset & 0x3FF) + 0xDC00);
  184. case 3:
  185. return fromCharCode((0x0f & cccc.charCodeAt(0)) << 12 | (0x3f & cccc.charCodeAt(1)) << 6 | 0x3f & cccc.charCodeAt(2));
  186. default:
  187. return fromCharCode((0x1f & cccc.charCodeAt(0)) << 6 | 0x3f & cccc.charCodeAt(1));
  188. }
  189. };
  190. var btou = function btou(b) {
  191. return b.replace(re_btou, cb_btou);
  192. };
  193. var cb_decode = function cb_decode(cccc) {
  194. var len = cccc.length,
  195. padlen = len % 4,
  196. n = (len > 0 ? b64tab[cccc.charAt(0)] << 18 : 0) | (len > 1 ? b64tab[cccc.charAt(1)] << 12 : 0) | (len > 2 ? b64tab[cccc.charAt(2)] << 6 : 0) | (len > 3 ? b64tab[cccc.charAt(3)] : 0),
  197. chars = [fromCharCode(n >>> 16), fromCharCode(n >>> 8 & 0xff), fromCharCode(n & 0xff)];
  198. chars.length -= [0, 0, 2, 1][padlen];
  199. return chars.join('');
  200. };
  201. var atob = global.atob ? function (a) {
  202. return global.atob(a);
  203. } : function (a) {
  204. return a.replace(/[\s\S]{1,4}/g, cb_decode);
  205. };
  206. var _decode = buffer ? function (a) {
  207. return (a.constructor === buffer.constructor ? a : new buffer(a, 'base64')).toString();
  208. } : function (a) {
  209. return btou(atob(a));
  210. };
  211. var decode = function decode(a) {
  212. return _decode(String(a).replace(/[-_]/g, function (m0) {
  213. return m0 == '-' ? '+' : '/';
  214. }).replace(/[^A-Za-z0-9\+\/]/g, ''));
  215. };
  216. var noConflict = function noConflict() {
  217. var Base64 = global.Base64;
  218. global.Base64 = _Base64;
  219. return Base64;
  220. };
  221. // export Base64
  222. var Base64 = {
  223. VERSION: version,
  224. atob: atob,
  225. btoa: btoa,
  226. fromBase64: decode,
  227. toBase64: encode,
  228. utob: utob,
  229. encode: encode,
  230. encodeURI: encodeURI,
  231. btou: btou,
  232. decode: decode,
  233. noConflict: noConflict
  234. };
  235. return Base64;
  236. }();
  237. module.exports = Base64;
  238. /***/ }),
  239. /***/ "./lib/crypto.js":
  240. /*!***********************!*\
  241. !*** ./lib/crypto.js ***!
  242. \***********************/
  243. /*! no static exports found */
  244. /***/ (function(module, exports) {
  245. /*
  246. CryptoJS v3.1.2
  247. code.google.com/p/crypto-js
  248. (c) 2009-2013 by Jeff Mott. All rights reserved.
  249. code.google.com/p/crypto-js/wiki/License
  250. */
  251. var CryptoJS = CryptoJS || function (g, l) {
  252. var e = {},
  253. d = e.lib = {},
  254. m = function m() {},
  255. k = d.Base = {
  256. extend: function extend(a) {
  257. m.prototype = this;
  258. var c = new m();
  259. a && c.mixIn(a);
  260. c.hasOwnProperty("init") || (c.init = function () {
  261. c.$super.init.apply(this, arguments);
  262. });
  263. c.init.prototype = c;
  264. c.$super = this;
  265. return c;
  266. },
  267. create: function create() {
  268. var a = this.extend();
  269. a.init.apply(a, arguments);
  270. return a;
  271. },
  272. init: function init() {},
  273. mixIn: function mixIn(a) {
  274. for (var c in a) a.hasOwnProperty(c) && (this[c] = a[c]);
  275. a.hasOwnProperty("toString") && (this.toString = a.toString);
  276. },
  277. clone: function clone() {
  278. return this.init.prototype.extend(this);
  279. }
  280. },
  281. p = d.WordArray = k.extend({
  282. init: function init(a, c) {
  283. a = this.words = a || [];
  284. this.sigBytes = c != l ? c : 4 * a.length;
  285. },
  286. toString: function toString(a) {
  287. return (a || n).stringify(this);
  288. },
  289. concat: function concat(a) {
  290. var c = this.words,
  291. q = a.words,
  292. f = this.sigBytes;
  293. a = a.sigBytes;
  294. this.clamp();
  295. if (f % 4) for (var b = 0; b < a; b++) c[f + b >>> 2] |= (q[b >>> 2] >>> 24 - 8 * (b % 4) & 255) << 24 - 8 * ((f + b) % 4);else if (65535 < q.length) for (b = 0; b < a; b += 4) c[f + b >>> 2] = q[b >>> 2];else c.push.apply(c, q);
  296. this.sigBytes += a;
  297. return this;
  298. },
  299. clamp: function clamp() {
  300. var a = this.words,
  301. c = this.sigBytes;
  302. a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4);
  303. a.length = g.ceil(c / 4);
  304. },
  305. clone: function clone() {
  306. var a = k.clone.call(this);
  307. a.words = this.words.slice(0);
  308. return a;
  309. },
  310. random: function random(a) {
  311. for (var c = [], b = 0; b < a; b += 4) c.push(4294967296 * g.random() | 0);
  312. return new p.init(c, a);
  313. }
  314. }),
  315. b = e.enc = {},
  316. n = b.Hex = {
  317. stringify: function stringify(a) {
  318. var c = a.words;
  319. a = a.sigBytes;
  320. for (var b = [], f = 0; f < a; f++) {
  321. var d = c[f >>> 2] >>> 24 - 8 * (f % 4) & 255;
  322. b.push((d >>> 4).toString(16));
  323. b.push((d & 15).toString(16));
  324. }
  325. return b.join("");
  326. },
  327. parse: function parse(a) {
  328. for (var c = a.length, b = [], f = 0; f < c; f += 2) b[f >>> 3] |= parseInt(a.substr(f, 2), 16) << 24 - 4 * (f % 8);
  329. return new p.init(b, c / 2);
  330. }
  331. },
  332. j = b.Latin1 = {
  333. stringify: function stringify(a) {
  334. var c = a.words;
  335. a = a.sigBytes;
  336. for (var b = [], f = 0; f < a; f++) b.push(String.fromCharCode(c[f >>> 2] >>> 24 - 8 * (f % 4) & 255));
  337. return b.join("");
  338. },
  339. parse: function parse(a) {
  340. for (var c = a.length, b = [], f = 0; f < c; f++) b[f >>> 2] |= (a.charCodeAt(f) & 255) << 24 - 8 * (f % 4);
  341. return new p.init(b, c);
  342. }
  343. },
  344. h = b.Utf8 = {
  345. stringify: function stringify(a) {
  346. try {
  347. return decodeURIComponent(escape(j.stringify(a)));
  348. } catch (c) {
  349. throw Error("Malformed UTF-8 data");
  350. }
  351. },
  352. parse: function parse(a) {
  353. return j.parse(unescape(encodeURIComponent(a)));
  354. }
  355. },
  356. r = d.BufferedBlockAlgorithm = k.extend({
  357. reset: function reset() {
  358. this._data = new p.init();
  359. this._nDataBytes = 0;
  360. },
  361. _append: function _append(a) {
  362. "string" == typeof a && (a = h.parse(a));
  363. this._data.concat(a);
  364. this._nDataBytes += a.sigBytes;
  365. },
  366. _process: function _process(a) {
  367. var c = this._data,
  368. b = c.words,
  369. f = c.sigBytes,
  370. d = this.blockSize,
  371. e = f / (4 * d),
  372. e = a ? g.ceil(e) : g.max((e | 0) - this._minBufferSize, 0);
  373. a = e * d;
  374. f = g.min(4 * a, f);
  375. if (a) {
  376. for (var k = 0; k < a; k += d) this._doProcessBlock(b, k);
  377. k = b.splice(0, a);
  378. c.sigBytes -= f;
  379. }
  380. return new p.init(k, f);
  381. },
  382. clone: function clone() {
  383. var a = k.clone.call(this);
  384. a._data = this._data.clone();
  385. return a;
  386. },
  387. _minBufferSize: 0
  388. });
  389. d.Hasher = r.extend({
  390. cfg: k.extend(),
  391. init: function init(a) {
  392. this.cfg = this.cfg.extend(a);
  393. this.reset();
  394. },
  395. reset: function reset() {
  396. r.reset.call(this);
  397. this._doReset();
  398. },
  399. update: function update(a) {
  400. this._append(a);
  401. this._process();
  402. return this;
  403. },
  404. finalize: function finalize(a) {
  405. a && this._append(a);
  406. return this._doFinalize();
  407. },
  408. blockSize: 16,
  409. _createHelper: function _createHelper(a) {
  410. return function (b, d) {
  411. return new a.init(d).finalize(b);
  412. };
  413. },
  414. _createHmacHelper: function _createHmacHelper(a) {
  415. return function (b, d) {
  416. return new s.HMAC.init(a, d).finalize(b);
  417. };
  418. }
  419. });
  420. var s = e.algo = {};
  421. return e;
  422. }(Math);
  423. (function () {
  424. var g = CryptoJS,
  425. l = g.lib,
  426. e = l.WordArray,
  427. d = l.Hasher,
  428. m = [],
  429. l = g.algo.SHA1 = d.extend({
  430. _doReset: function _doReset() {
  431. this._hash = new e.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]);
  432. },
  433. _doProcessBlock: function _doProcessBlock(d, e) {
  434. for (var b = this._hash.words, n = b[0], j = b[1], h = b[2], g = b[3], l = b[4], a = 0; 80 > a; a++) {
  435. if (16 > a) m[a] = d[e + a] | 0;else {
  436. var c = m[a - 3] ^ m[a - 8] ^ m[a - 14] ^ m[a - 16];
  437. m[a] = c << 1 | c >>> 31;
  438. }
  439. c = (n << 5 | n >>> 27) + l + m[a];
  440. c = 20 > a ? c + ((j & h | ~j & g) + 1518500249) : 40 > a ? c + ((j ^ h ^ g) + 1859775393) : 60 > a ? c + ((j & h | j & g | h & g) - 1894007588) : c + ((j ^ h ^ g) - 899497514);
  441. l = g;
  442. g = h;
  443. h = j << 30 | j >>> 2;
  444. j = n;
  445. n = c;
  446. }
  447. b[0] = b[0] + n | 0;
  448. b[1] = b[1] + j | 0;
  449. b[2] = b[2] + h | 0;
  450. b[3] = b[3] + g | 0;
  451. b[4] = b[4] + l | 0;
  452. },
  453. _doFinalize: function _doFinalize() {
  454. var d = this._data,
  455. e = d.words,
  456. b = 8 * this._nDataBytes,
  457. g = 8 * d.sigBytes;
  458. e[g >>> 5] |= 128 << 24 - g % 32;
  459. e[(g + 64 >>> 9 << 4) + 14] = Math.floor(b / 4294967296);
  460. e[(g + 64 >>> 9 << 4) + 15] = b;
  461. d.sigBytes = 4 * e.length;
  462. this._process();
  463. return this._hash;
  464. },
  465. clone: function clone() {
  466. var e = d.clone.call(this);
  467. e._hash = this._hash.clone();
  468. return e;
  469. }
  470. });
  471. g.SHA1 = d._createHelper(l);
  472. g.HmacSHA1 = d._createHmacHelper(l);
  473. })();
  474. (function () {
  475. var g = CryptoJS,
  476. l = g.enc.Utf8;
  477. g.algo.HMAC = g.lib.Base.extend({
  478. init: function init(e, d) {
  479. e = this._hasher = new e.init();
  480. "string" == typeof d && (d = l.parse(d));
  481. var g = e.blockSize,
  482. k = 4 * g;
  483. d.sigBytes > k && (d = e.finalize(d));
  484. d.clamp();
  485. for (var p = this._oKey = d.clone(), b = this._iKey = d.clone(), n = p.words, j = b.words, h = 0; h < g; h++) n[h] ^= 1549556828, j[h] ^= 909522486;
  486. p.sigBytes = b.sigBytes = k;
  487. this.reset();
  488. },
  489. reset: function reset() {
  490. var e = this._hasher;
  491. e.reset();
  492. e.update(this._iKey);
  493. },
  494. update: function update(e) {
  495. this._hasher.update(e);
  496. return this;
  497. },
  498. finalize: function finalize(e) {
  499. var d = this._hasher;
  500. e = d.finalize(e);
  501. d.reset();
  502. return d.finalize(this._oKey.clone().concat(e));
  503. }
  504. });
  505. })();
  506. (function () {
  507. // Shortcuts
  508. var C = CryptoJS;
  509. var C_lib = C.lib;
  510. var WordArray = C_lib.WordArray;
  511. var C_enc = C.enc;
  512. /**
  513. * Base64 encoding strategy.
  514. */
  515. var Base64 = C_enc.Base64 = {
  516. /**
  517. * Converts a word array to a Base64 string.
  518. *
  519. * @param {WordArray} wordArray The word array.
  520. *
  521. * @return {string} The Base64 string.
  522. *
  523. * @static
  524. *
  525. * @example
  526. *
  527. * var base64String = CryptoJS.enc.Base64.stringify(wordArray);
  528. */
  529. stringify: function stringify(wordArray) {
  530. // Shortcuts
  531. var words = wordArray.words;
  532. var sigBytes = wordArray.sigBytes;
  533. var map = this._map;
  534. // Clamp excess bits
  535. wordArray.clamp();
  536. // Convert
  537. var base64Chars = [];
  538. for (var i = 0; i < sigBytes; i += 3) {
  539. var byte1 = words[i >>> 2] >>> 24 - i % 4 * 8 & 0xff;
  540. var byte2 = words[i + 1 >>> 2] >>> 24 - (i + 1) % 4 * 8 & 0xff;
  541. var byte3 = words[i + 2 >>> 2] >>> 24 - (i + 2) % 4 * 8 & 0xff;
  542. var triplet = byte1 << 16 | byte2 << 8 | byte3;
  543. for (var j = 0; j < 4 && i + j * 0.75 < sigBytes; j++) {
  544. base64Chars.push(map.charAt(triplet >>> 6 * (3 - j) & 0x3f));
  545. }
  546. }
  547. // Add padding
  548. var paddingChar = map.charAt(64);
  549. if (paddingChar) {
  550. while (base64Chars.length % 4) {
  551. base64Chars.push(paddingChar);
  552. }
  553. }
  554. return base64Chars.join('');
  555. },
  556. /**
  557. * Converts a Base64 string to a word array.
  558. *
  559. * @param {string} base64Str The Base64 string.
  560. *
  561. * @return {WordArray} The word array.
  562. *
  563. * @static
  564. *
  565. * @example
  566. *
  567. * var wordArray = CryptoJS.enc.Base64.parse(base64String);
  568. */
  569. parse: function parse(base64Str) {
  570. // Shortcuts
  571. var base64StrLength = base64Str.length;
  572. var map = this._map;
  573. // Ignore padding
  574. var paddingChar = map.charAt(64);
  575. if (paddingChar) {
  576. var paddingIndex = base64Str.indexOf(paddingChar);
  577. if (paddingIndex != -1) {
  578. base64StrLength = paddingIndex;
  579. }
  580. }
  581. // Convert
  582. var words = [];
  583. var nBytes = 0;
  584. for (var i = 0; i < base64StrLength; i++) {
  585. if (i % 4) {
  586. var bits1 = map.indexOf(base64Str.charAt(i - 1)) << i % 4 * 2;
  587. var bits2 = map.indexOf(base64Str.charAt(i)) >>> 6 - i % 4 * 2;
  588. words[nBytes >>> 2] |= (bits1 | bits2) << 24 - nBytes % 4 * 8;
  589. nBytes++;
  590. }
  591. }
  592. return WordArray.create(words, nBytes);
  593. },
  594. _map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  595. };
  596. })();
  597. module.exports = CryptoJS;
  598. /***/ }),
  599. /***/ "./lib/md5.js":
  600. /*!********************!*\
  601. !*** ./lib/md5.js ***!
  602. \********************/
  603. /*! no static exports found */
  604. /***/ (function(module, exports, __webpack_require__) {
  605. /* WEBPACK VAR INJECTION */(function(module) {var __WEBPACK_AMD_DEFINE_RESULT__;function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  606. /* https://github.com/emn178/js-md5 */
  607. (function () {
  608. 'use strict';
  609. var ERROR = 'input is invalid type';
  610. var WINDOW = (typeof window === "undefined" ? "undefined" : _typeof(window)) === 'object';
  611. var root = WINDOW ? window : {};
  612. if (root.JS_MD5_NO_WINDOW) {
  613. WINDOW = false;
  614. }
  615. var WEB_WORKER = !WINDOW && (typeof self === "undefined" ? "undefined" : _typeof(self)) === 'object';
  616. if (WEB_WORKER) {
  617. root = self;
  618. }
  619. var COMMON_JS = !root.JS_MD5_NO_COMMON_JS && ( false ? undefined : _typeof(module)) === 'object' && module.exports;
  620. var AMD = true && __webpack_require__(/*! !webpack amd options */ "./node_modules/webpack/buildin/amd-options.js");
  621. var ARRAY_BUFFER = !root.JS_MD5_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
  622. var HEX_CHARS = '0123456789abcdef'.split('');
  623. var EXTRA = [128, 32768, 8388608, -2147483648];
  624. var SHIFT = [0, 8, 16, 24];
  625. var OUTPUT_TYPES = ['hex', 'array', 'digest', 'buffer', 'arrayBuffer', 'base64'];
  626. var BASE64_ENCODE_CHAR = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split('');
  627. var blocks = [],
  628. buffer8;
  629. if (ARRAY_BUFFER) {
  630. var buffer = new ArrayBuffer(68);
  631. buffer8 = new Uint8Array(buffer);
  632. blocks = new Uint32Array(buffer);
  633. }
  634. if (root.JS_MD5_NO_NODE_JS || !Array.isArray) {
  635. Array.isArray = function (obj) {
  636. return Object.prototype.toString.call(obj) === '[object Array]';
  637. };
  638. }
  639. if (ARRAY_BUFFER && (root.JS_MD5_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
  640. ArrayBuffer.isView = function (obj) {
  641. return _typeof(obj) === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
  642. };
  643. }
  644. /**
  645. * @method hex
  646. * @memberof md5
  647. * @description Output hash as hex string
  648. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  649. * @returns {String} Hex string
  650. * @example
  651. * md5.hex('The quick brown fox jumps over the lazy dog');
  652. * // equal to
  653. * md5('The quick brown fox jumps over the lazy dog');
  654. */
  655. /**
  656. * @method digest
  657. * @memberof md5
  658. * @description Output hash as bytes array
  659. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  660. * @returns {Array} Bytes array
  661. * @example
  662. * md5.digest('The quick brown fox jumps over the lazy dog');
  663. */
  664. /**
  665. * @method array
  666. * @memberof md5
  667. * @description Output hash as bytes array
  668. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  669. * @returns {Array} Bytes array
  670. * @example
  671. * md5.array('The quick brown fox jumps over the lazy dog');
  672. */
  673. /**
  674. * @method arrayBuffer
  675. * @memberof md5
  676. * @description Output hash as ArrayBuffer
  677. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  678. * @returns {ArrayBuffer} ArrayBuffer
  679. * @example
  680. * md5.arrayBuffer('The quick brown fox jumps over the lazy dog');
  681. */
  682. /**
  683. * @method buffer
  684. * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.
  685. * @memberof md5
  686. * @description Output hash as ArrayBuffer
  687. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  688. * @returns {ArrayBuffer} ArrayBuffer
  689. * @example
  690. * md5.buffer('The quick brown fox jumps over the lazy dog');
  691. */
  692. /**
  693. * @method base64
  694. * @memberof md5
  695. * @description Output hash as base64 string
  696. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  697. * @returns {String} base64 string
  698. * @example
  699. * md5.base64('The quick brown fox jumps over the lazy dog');
  700. */
  701. var createOutputMethod = function createOutputMethod(outputType) {
  702. return function (message) {
  703. return new Md5(true).update(message)[outputType]();
  704. };
  705. };
  706. /**
  707. * @method create
  708. * @memberof md5
  709. * @description Create Md5 object
  710. * @returns {Md5} Md5 object.
  711. * @example
  712. * var hash = md5.create();
  713. */
  714. /**
  715. * @method update
  716. * @memberof md5
  717. * @description Create and update Md5 object
  718. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  719. * @returns {Md5} Md5 object.
  720. * @example
  721. * var hash = md5.update('The quick brown fox jumps over the lazy dog');
  722. * // equal to
  723. * var hash = md5.create();
  724. * hash.update('The quick brown fox jumps over the lazy dog');
  725. */
  726. var createMethod = function createMethod() {
  727. var method = createOutputMethod('hex');
  728. method.getCtx = method.create = function () {
  729. return new Md5();
  730. };
  731. method.update = function (message) {
  732. return method.create().update(message);
  733. };
  734. for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
  735. var type = OUTPUT_TYPES[i];
  736. method[type] = createOutputMethod(type);
  737. }
  738. return method;
  739. };
  740. /**
  741. * Md5 class
  742. * @class Md5
  743. * @description This is internal class.
  744. * @see {@link md5.create}
  745. */
  746. function Md5(sharedMemory) {
  747. if (sharedMemory) {
  748. blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
  749. this.blocks = blocks;
  750. this.buffer8 = buffer8;
  751. } else {
  752. if (ARRAY_BUFFER) {
  753. var buffer = new ArrayBuffer(68);
  754. this.buffer8 = new Uint8Array(buffer);
  755. this.blocks = new Uint32Array(buffer);
  756. } else {
  757. this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
  758. }
  759. }
  760. this.h0 = this.h1 = this.h2 = this.h3 = this.start = this.bytes = this.hBytes = 0;
  761. this.finalized = this.hashed = false;
  762. this.first = true;
  763. }
  764. /**
  765. * @method update
  766. * @memberof Md5
  767. * @instance
  768. * @description Update hash
  769. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  770. * @returns {Md5} Md5 object.
  771. * @see {@link md5.update}
  772. */
  773. Md5.prototype.update = function (message) {
  774. if (this.finalized) {
  775. return;
  776. }
  777. var notString,
  778. type = _typeof(message);
  779. if (type !== 'string') {
  780. if (type === 'object') {
  781. if (message === null) {
  782. throw ERROR;
  783. } else if (ARRAY_BUFFER && (message.constructor === ArrayBuffer || message.constructor.name === 'ArrayBuffer')) {
  784. message = new Uint8Array(message);
  785. } else if (!Array.isArray(message)) {
  786. if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
  787. throw ERROR;
  788. }
  789. }
  790. } else {
  791. throw ERROR;
  792. }
  793. notString = true;
  794. }
  795. var code,
  796. index = 0,
  797. i,
  798. length = message.length,
  799. blocks = this.blocks;
  800. var buffer8 = this.buffer8;
  801. while (index < length) {
  802. if (this.hashed) {
  803. this.hashed = false;
  804. blocks[0] = blocks[16];
  805. blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
  806. }
  807. if (notString) {
  808. if (ARRAY_BUFFER) {
  809. for (i = this.start; index < length && i < 64; ++index) {
  810. buffer8[i++] = message[index];
  811. }
  812. } else {
  813. for (i = this.start; index < length && i < 64; ++index) {
  814. blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
  815. }
  816. }
  817. } else {
  818. if (ARRAY_BUFFER) {
  819. for (i = this.start; index < length && i < 64; ++index) {
  820. code = message.charCodeAt(index);
  821. if (code < 0x80) {
  822. buffer8[i++] = code;
  823. } else if (code < 0x800) {
  824. buffer8[i++] = 0xc0 | code >> 6;
  825. buffer8[i++] = 0x80 | code & 0x3f;
  826. } else if (code < 0xd800 || code >= 0xe000) {
  827. buffer8[i++] = 0xe0 | code >> 12;
  828. buffer8[i++] = 0x80 | code >> 6 & 0x3f;
  829. buffer8[i++] = 0x80 | code & 0x3f;
  830. } else {
  831. code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
  832. buffer8[i++] = 0xf0 | code >> 18;
  833. buffer8[i++] = 0x80 | code >> 12 & 0x3f;
  834. buffer8[i++] = 0x80 | code >> 6 & 0x3f;
  835. buffer8[i++] = 0x80 | code & 0x3f;
  836. }
  837. }
  838. } else {
  839. for (i = this.start; index < length && i < 64; ++index) {
  840. code = message.charCodeAt(index);
  841. if (code < 0x80) {
  842. blocks[i >> 2] |= code << SHIFT[i++ & 3];
  843. } else if (code < 0x800) {
  844. blocks[i >> 2] |= (0xc0 | code >> 6) << SHIFT[i++ & 3];
  845. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  846. } else if (code < 0xd800 || code >= 0xe000) {
  847. blocks[i >> 2] |= (0xe0 | code >> 12) << SHIFT[i++ & 3];
  848. blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
  849. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  850. } else {
  851. code = 0x10000 + ((code & 0x3ff) << 10 | message.charCodeAt(++index) & 0x3ff);
  852. blocks[i >> 2] |= (0xf0 | code >> 18) << SHIFT[i++ & 3];
  853. blocks[i >> 2] |= (0x80 | code >> 12 & 0x3f) << SHIFT[i++ & 3];
  854. blocks[i >> 2] |= (0x80 | code >> 6 & 0x3f) << SHIFT[i++ & 3];
  855. blocks[i >> 2] |= (0x80 | code & 0x3f) << SHIFT[i++ & 3];
  856. }
  857. }
  858. }
  859. }
  860. this.lastByteIndex = i;
  861. this.bytes += i - this.start;
  862. if (i >= 64) {
  863. this.start = i - 64;
  864. this.hash();
  865. this.hashed = true;
  866. } else {
  867. this.start = i;
  868. }
  869. }
  870. if (this.bytes > 4294967295) {
  871. this.hBytes += this.bytes / 4294967296 << 0;
  872. this.bytes = this.bytes % 4294967296;
  873. }
  874. return this;
  875. };
  876. Md5.prototype.finalize = function () {
  877. if (this.finalized) {
  878. return;
  879. }
  880. this.finalized = true;
  881. var blocks = this.blocks,
  882. i = this.lastByteIndex;
  883. blocks[i >> 2] |= EXTRA[i & 3];
  884. if (i >= 56) {
  885. if (!this.hashed) {
  886. this.hash();
  887. }
  888. blocks[0] = blocks[16];
  889. blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
  890. }
  891. blocks[14] = this.bytes << 3;
  892. blocks[15] = this.hBytes << 3 | this.bytes >>> 29;
  893. this.hash();
  894. };
  895. Md5.prototype.hash = function () {
  896. var a,
  897. b,
  898. c,
  899. d,
  900. bc,
  901. da,
  902. blocks = this.blocks;
  903. if (this.first) {
  904. a = blocks[0] - 680876937;
  905. a = (a << 7 | a >>> 25) - 271733879 << 0;
  906. d = (-1732584194 ^ a & 2004318071) + blocks[1] - 117830708;
  907. d = (d << 12 | d >>> 20) + a << 0;
  908. c = (-271733879 ^ d & (a ^ -271733879)) + blocks[2] - 1126478375;
  909. c = (c << 17 | c >>> 15) + d << 0;
  910. b = (a ^ c & (d ^ a)) + blocks[3] - 1316259209;
  911. b = (b << 22 | b >>> 10) + c << 0;
  912. } else {
  913. a = this.h0;
  914. b = this.h1;
  915. c = this.h2;
  916. d = this.h3;
  917. a += (d ^ b & (c ^ d)) + blocks[0] - 680876936;
  918. a = (a << 7 | a >>> 25) + b << 0;
  919. d += (c ^ a & (b ^ c)) + blocks[1] - 389564586;
  920. d = (d << 12 | d >>> 20) + a << 0;
  921. c += (b ^ d & (a ^ b)) + blocks[2] + 606105819;
  922. c = (c << 17 | c >>> 15) + d << 0;
  923. b += (a ^ c & (d ^ a)) + blocks[3] - 1044525330;
  924. b = (b << 22 | b >>> 10) + c << 0;
  925. }
  926. a += (d ^ b & (c ^ d)) + blocks[4] - 176418897;
  927. a = (a << 7 | a >>> 25) + b << 0;
  928. d += (c ^ a & (b ^ c)) + blocks[5] + 1200080426;
  929. d = (d << 12 | d >>> 20) + a << 0;
  930. c += (b ^ d & (a ^ b)) + blocks[6] - 1473231341;
  931. c = (c << 17 | c >>> 15) + d << 0;
  932. b += (a ^ c & (d ^ a)) + blocks[7] - 45705983;
  933. b = (b << 22 | b >>> 10) + c << 0;
  934. a += (d ^ b & (c ^ d)) + blocks[8] + 1770035416;
  935. a = (a << 7 | a >>> 25) + b << 0;
  936. d += (c ^ a & (b ^ c)) + blocks[9] - 1958414417;
  937. d = (d << 12 | d >>> 20) + a << 0;
  938. c += (b ^ d & (a ^ b)) + blocks[10] - 42063;
  939. c = (c << 17 | c >>> 15) + d << 0;
  940. b += (a ^ c & (d ^ a)) + blocks[11] - 1990404162;
  941. b = (b << 22 | b >>> 10) + c << 0;
  942. a += (d ^ b & (c ^ d)) + blocks[12] + 1804603682;
  943. a = (a << 7 | a >>> 25) + b << 0;
  944. d += (c ^ a & (b ^ c)) + blocks[13] - 40341101;
  945. d = (d << 12 | d >>> 20) + a << 0;
  946. c += (b ^ d & (a ^ b)) + blocks[14] - 1502002290;
  947. c = (c << 17 | c >>> 15) + d << 0;
  948. b += (a ^ c & (d ^ a)) + blocks[15] + 1236535329;
  949. b = (b << 22 | b >>> 10) + c << 0;
  950. a += (c ^ d & (b ^ c)) + blocks[1] - 165796510;
  951. a = (a << 5 | a >>> 27) + b << 0;
  952. d += (b ^ c & (a ^ b)) + blocks[6] - 1069501632;
  953. d = (d << 9 | d >>> 23) + a << 0;
  954. c += (a ^ b & (d ^ a)) + blocks[11] + 643717713;
  955. c = (c << 14 | c >>> 18) + d << 0;
  956. b += (d ^ a & (c ^ d)) + blocks[0] - 373897302;
  957. b = (b << 20 | b >>> 12) + c << 0;
  958. a += (c ^ d & (b ^ c)) + blocks[5] - 701558691;
  959. a = (a << 5 | a >>> 27) + b << 0;
  960. d += (b ^ c & (a ^ b)) + blocks[10] + 38016083;
  961. d = (d << 9 | d >>> 23) + a << 0;
  962. c += (a ^ b & (d ^ a)) + blocks[15] - 660478335;
  963. c = (c << 14 | c >>> 18) + d << 0;
  964. b += (d ^ a & (c ^ d)) + blocks[4] - 405537848;
  965. b = (b << 20 | b >>> 12) + c << 0;
  966. a += (c ^ d & (b ^ c)) + blocks[9] + 568446438;
  967. a = (a << 5 | a >>> 27) + b << 0;
  968. d += (b ^ c & (a ^ b)) + blocks[14] - 1019803690;
  969. d = (d << 9 | d >>> 23) + a << 0;
  970. c += (a ^ b & (d ^ a)) + blocks[3] - 187363961;
  971. c = (c << 14 | c >>> 18) + d << 0;
  972. b += (d ^ a & (c ^ d)) + blocks[8] + 1163531501;
  973. b = (b << 20 | b >>> 12) + c << 0;
  974. a += (c ^ d & (b ^ c)) + blocks[13] - 1444681467;
  975. a = (a << 5 | a >>> 27) + b << 0;
  976. d += (b ^ c & (a ^ b)) + blocks[2] - 51403784;
  977. d = (d << 9 | d >>> 23) + a << 0;
  978. c += (a ^ b & (d ^ a)) + blocks[7] + 1735328473;
  979. c = (c << 14 | c >>> 18) + d << 0;
  980. b += (d ^ a & (c ^ d)) + blocks[12] - 1926607734;
  981. b = (b << 20 | b >>> 12) + c << 0;
  982. bc = b ^ c;
  983. a += (bc ^ d) + blocks[5] - 378558;
  984. a = (a << 4 | a >>> 28) + b << 0;
  985. d += (bc ^ a) + blocks[8] - 2022574463;
  986. d = (d << 11 | d >>> 21) + a << 0;
  987. da = d ^ a;
  988. c += (da ^ b) + blocks[11] + 1839030562;
  989. c = (c << 16 | c >>> 16) + d << 0;
  990. b += (da ^ c) + blocks[14] - 35309556;
  991. b = (b << 23 | b >>> 9) + c << 0;
  992. bc = b ^ c;
  993. a += (bc ^ d) + blocks[1] - 1530992060;
  994. a = (a << 4 | a >>> 28) + b << 0;
  995. d += (bc ^ a) + blocks[4] + 1272893353;
  996. d = (d << 11 | d >>> 21) + a << 0;
  997. da = d ^ a;
  998. c += (da ^ b) + blocks[7] - 155497632;
  999. c = (c << 16 | c >>> 16) + d << 0;
  1000. b += (da ^ c) + blocks[10] - 1094730640;
  1001. b = (b << 23 | b >>> 9) + c << 0;
  1002. bc = b ^ c;
  1003. a += (bc ^ d) + blocks[13] + 681279174;
  1004. a = (a << 4 | a >>> 28) + b << 0;
  1005. d += (bc ^ a) + blocks[0] - 358537222;
  1006. d = (d << 11 | d >>> 21) + a << 0;
  1007. da = d ^ a;
  1008. c += (da ^ b) + blocks[3] - 722521979;
  1009. c = (c << 16 | c >>> 16) + d << 0;
  1010. b += (da ^ c) + blocks[6] + 76029189;
  1011. b = (b << 23 | b >>> 9) + c << 0;
  1012. bc = b ^ c;
  1013. a += (bc ^ d) + blocks[9] - 640364487;
  1014. a = (a << 4 | a >>> 28) + b << 0;
  1015. d += (bc ^ a) + blocks[12] - 421815835;
  1016. d = (d << 11 | d >>> 21) + a << 0;
  1017. da = d ^ a;
  1018. c += (da ^ b) + blocks[15] + 530742520;
  1019. c = (c << 16 | c >>> 16) + d << 0;
  1020. b += (da ^ c) + blocks[2] - 995338651;
  1021. b = (b << 23 | b >>> 9) + c << 0;
  1022. a += (c ^ (b | ~d)) + blocks[0] - 198630844;
  1023. a = (a << 6 | a >>> 26) + b << 0;
  1024. d += (b ^ (a | ~c)) + blocks[7] + 1126891415;
  1025. d = (d << 10 | d >>> 22) + a << 0;
  1026. c += (a ^ (d | ~b)) + blocks[14] - 1416354905;
  1027. c = (c << 15 | c >>> 17) + d << 0;
  1028. b += (d ^ (c | ~a)) + blocks[5] - 57434055;
  1029. b = (b << 21 | b >>> 11) + c << 0;
  1030. a += (c ^ (b | ~d)) + blocks[12] + 1700485571;
  1031. a = (a << 6 | a >>> 26) + b << 0;
  1032. d += (b ^ (a | ~c)) + blocks[3] - 1894986606;
  1033. d = (d << 10 | d >>> 22) + a << 0;
  1034. c += (a ^ (d | ~b)) + blocks[10] - 1051523;
  1035. c = (c << 15 | c >>> 17) + d << 0;
  1036. b += (d ^ (c | ~a)) + blocks[1] - 2054922799;
  1037. b = (b << 21 | b >>> 11) + c << 0;
  1038. a += (c ^ (b | ~d)) + blocks[8] + 1873313359;
  1039. a = (a << 6 | a >>> 26) + b << 0;
  1040. d += (b ^ (a | ~c)) + blocks[15] - 30611744;
  1041. d = (d << 10 | d >>> 22) + a << 0;
  1042. c += (a ^ (d | ~b)) + blocks[6] - 1560198380;
  1043. c = (c << 15 | c >>> 17) + d << 0;
  1044. b += (d ^ (c | ~a)) + blocks[13] + 1309151649;
  1045. b = (b << 21 | b >>> 11) + c << 0;
  1046. a += (c ^ (b | ~d)) + blocks[4] - 145523070;
  1047. a = (a << 6 | a >>> 26) + b << 0;
  1048. d += (b ^ (a | ~c)) + blocks[11] - 1120210379;
  1049. d = (d << 10 | d >>> 22) + a << 0;
  1050. c += (a ^ (d | ~b)) + blocks[2] + 718787259;
  1051. c = (c << 15 | c >>> 17) + d << 0;
  1052. b += (d ^ (c | ~a)) + blocks[9] - 343485551;
  1053. b = (b << 21 | b >>> 11) + c << 0;
  1054. if (this.first) {
  1055. this.h0 = a + 1732584193 << 0;
  1056. this.h1 = b - 271733879 << 0;
  1057. this.h2 = c - 1732584194 << 0;
  1058. this.h3 = d + 271733878 << 0;
  1059. this.first = false;
  1060. } else {
  1061. this.h0 = this.h0 + a << 0;
  1062. this.h1 = this.h1 + b << 0;
  1063. this.h2 = this.h2 + c << 0;
  1064. this.h3 = this.h3 + d << 0;
  1065. }
  1066. };
  1067. /**
  1068. * @method hex
  1069. * @memberof Md5
  1070. * @instance
  1071. * @description Output hash as hex string
  1072. * @returns {String} Hex string
  1073. * @see {@link md5.hex}
  1074. * @example
  1075. * hash.hex();
  1076. */
  1077. Md5.prototype.hex = function () {
  1078. this.finalize();
  1079. var h0 = this.h0,
  1080. h1 = this.h1,
  1081. h2 = this.h2,
  1082. h3 = this.h3;
  1083. return HEX_CHARS[h0 >> 4 & 0x0F] + HEX_CHARS[h0 & 0x0F] + HEX_CHARS[h0 >> 12 & 0x0F] + HEX_CHARS[h0 >> 8 & 0x0F] + HEX_CHARS[h0 >> 20 & 0x0F] + HEX_CHARS[h0 >> 16 & 0x0F] + HEX_CHARS[h0 >> 28 & 0x0F] + HEX_CHARS[h0 >> 24 & 0x0F] + HEX_CHARS[h1 >> 4 & 0x0F] + HEX_CHARS[h1 & 0x0F] + HEX_CHARS[h1 >> 12 & 0x0F] + HEX_CHARS[h1 >> 8 & 0x0F] + HEX_CHARS[h1 >> 20 & 0x0F] + HEX_CHARS[h1 >> 16 & 0x0F] + HEX_CHARS[h1 >> 28 & 0x0F] + HEX_CHARS[h1 >> 24 & 0x0F] + HEX_CHARS[h2 >> 4 & 0x0F] + HEX_CHARS[h2 & 0x0F] + HEX_CHARS[h2 >> 12 & 0x0F] + HEX_CHARS[h2 >> 8 & 0x0F] + HEX_CHARS[h2 >> 20 & 0x0F] + HEX_CHARS[h2 >> 16 & 0x0F] + HEX_CHARS[h2 >> 28 & 0x0F] + HEX_CHARS[h2 >> 24 & 0x0F] + HEX_CHARS[h3 >> 4 & 0x0F] + HEX_CHARS[h3 & 0x0F] + HEX_CHARS[h3 >> 12 & 0x0F] + HEX_CHARS[h3 >> 8 & 0x0F] + HEX_CHARS[h3 >> 20 & 0x0F] + HEX_CHARS[h3 >> 16 & 0x0F] + HEX_CHARS[h3 >> 28 & 0x0F] + HEX_CHARS[h3 >> 24 & 0x0F];
  1084. };
  1085. /**
  1086. * @method toString
  1087. * @memberof Md5
  1088. * @instance
  1089. * @description Output hash as hex string
  1090. * @returns {String} Hex string
  1091. * @see {@link md5.hex}
  1092. * @example
  1093. * hash.toString();
  1094. */
  1095. Md5.prototype.toString = Md5.prototype.hex;
  1096. /**
  1097. * @method digest
  1098. * @memberof Md5
  1099. * @instance
  1100. * @description Output hash as bytes array
  1101. * @returns {Array} Bytes array
  1102. * @see {@link md5.digest}
  1103. * @example
  1104. * hash.digest();
  1105. */
  1106. Md5.prototype.digest = function () {
  1107. this.finalize();
  1108. var h0 = this.h0,
  1109. h1 = this.h1,
  1110. h2 = this.h2,
  1111. h3 = this.h3;
  1112. return [h0 & 0xFF, h0 >> 8 & 0xFF, h0 >> 16 & 0xFF, h0 >> 24 & 0xFF, h1 & 0xFF, h1 >> 8 & 0xFF, h1 >> 16 & 0xFF, h1 >> 24 & 0xFF, h2 & 0xFF, h2 >> 8 & 0xFF, h2 >> 16 & 0xFF, h2 >> 24 & 0xFF, h3 & 0xFF, h3 >> 8 & 0xFF, h3 >> 16 & 0xFF, h3 >> 24 & 0xFF];
  1113. };
  1114. /**
  1115. * @method array
  1116. * @memberof Md5
  1117. * @instance
  1118. * @description Output hash as bytes array
  1119. * @returns {Array} Bytes array
  1120. * @see {@link md5.array}
  1121. * @example
  1122. * hash.array();
  1123. */
  1124. Md5.prototype.array = Md5.prototype.digest;
  1125. /**
  1126. * @method arrayBuffer
  1127. * @memberof Md5
  1128. * @instance
  1129. * @description Output hash as ArrayBuffer
  1130. * @returns {ArrayBuffer} ArrayBuffer
  1131. * @see {@link md5.arrayBuffer}
  1132. * @example
  1133. * hash.arrayBuffer();
  1134. */
  1135. Md5.prototype.arrayBuffer = function () {
  1136. this.finalize();
  1137. var buffer = new ArrayBuffer(16);
  1138. var blocks = new Uint32Array(buffer);
  1139. blocks[0] = this.h0;
  1140. blocks[1] = this.h1;
  1141. blocks[2] = this.h2;
  1142. blocks[3] = this.h3;
  1143. return buffer;
  1144. };
  1145. /**
  1146. * @method buffer
  1147. * @deprecated This maybe confuse with Buffer in node.js. Please use arrayBuffer instead.
  1148. * @memberof Md5
  1149. * @instance
  1150. * @description Output hash as ArrayBuffer
  1151. * @returns {ArrayBuffer} ArrayBuffer
  1152. * @see {@link md5.buffer}
  1153. * @example
  1154. * hash.buffer();
  1155. */
  1156. Md5.prototype.buffer = Md5.prototype.arrayBuffer;
  1157. /**
  1158. * @method base64
  1159. * @memberof Md5
  1160. * @instance
  1161. * @description Output hash as base64 string
  1162. * @returns {String} base64 string
  1163. * @see {@link md5.base64}
  1164. * @example
  1165. * hash.base64();
  1166. */
  1167. Md5.prototype.base64 = function () {
  1168. var v1,
  1169. v2,
  1170. v3,
  1171. base64Str = '',
  1172. bytes = this.array();
  1173. for (var i = 0; i < 15;) {
  1174. v1 = bytes[i++];
  1175. v2 = bytes[i++];
  1176. v3 = bytes[i++];
  1177. base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + BASE64_ENCODE_CHAR[(v1 << 4 | v2 >>> 4) & 63] + BASE64_ENCODE_CHAR[(v2 << 2 | v3 >>> 6) & 63] + BASE64_ENCODE_CHAR[v3 & 63];
  1178. }
  1179. v1 = bytes[i];
  1180. base64Str += BASE64_ENCODE_CHAR[v1 >>> 2] + BASE64_ENCODE_CHAR[v1 << 4 & 63] + '==';
  1181. return base64Str;
  1182. };
  1183. var exports = createMethod();
  1184. if (COMMON_JS) {
  1185. module.exports = exports;
  1186. } else {
  1187. /**
  1188. * @method md5
  1189. * @description Md5 hash function, export to global in browsers.
  1190. * @param {String|Array|Uint8Array|ArrayBuffer} message message to hash
  1191. * @returns {String} md5 hashes
  1192. * @example
  1193. * md5(''); // d41d8cd98f00b204e9800998ecf8427e
  1194. * md5('The quick brown fox jumps over the lazy dog'); // 9e107d9d372bb6826bd81d3542a419d6
  1195. * md5('The quick brown fox jumps over the lazy dog.'); // e4d909c290d0fb1ca068ffaddf22cbd0
  1196. *
  1197. * // It also supports UTF-8 encoding
  1198. * md5('中文'); // a7bac2239fcdcb3a067903d8077c4a07
  1199. *
  1200. * // It also supports byte `Array`, `Uint8Array`, `ArrayBuffer`
  1201. * md5([]); // d41d8cd98f00b204e9800998ecf8427e
  1202. * md5(new Uint8Array([])); // d41d8cd98f00b204e9800998ecf8427e
  1203. */
  1204. root.md5 = exports;
  1205. if (AMD) {
  1206. !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
  1207. return exports;
  1208. }).call(exports, __webpack_require__, exports, module),
  1209. __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
  1210. }
  1211. }
  1212. })();
  1213. /* WEBPACK VAR INJECTION */}.call(this, __webpack_require__(/*! ./../node_modules/webpack/buildin/module.js */ "./node_modules/webpack/buildin/module.js")(module)))
  1214. /***/ }),
  1215. /***/ "./lib/request.js":
  1216. /*!************************!*\
  1217. !*** ./lib/request.js ***!
  1218. \************************/
  1219. /*! no static exports found */
  1220. /***/ (function(module, exports) {
  1221. function camSafeUrlEncode(str) {
  1222. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
  1223. }
  1224. function getObjectKeys(obj, forKey) {
  1225. var list = [];
  1226. for (var key in obj) {
  1227. if (obj.hasOwnProperty(key)) {
  1228. list.push(forKey ? camSafeUrlEncode(key).toLowerCase() : key);
  1229. }
  1230. }
  1231. return list.sort(function (a, b) {
  1232. a = a.toLowerCase();
  1233. b = b.toLowerCase();
  1234. return a === b ? 0 : a > b ? 1 : -1;
  1235. });
  1236. }
  1237. ;
  1238. var obj2str = function obj2str(obj, lowerCaseKey) {
  1239. var i, key, val;
  1240. var list = [];
  1241. var keyList = getObjectKeys(obj);
  1242. for (i = 0; i < keyList.length; i++) {
  1243. key = keyList[i];
  1244. val = obj[key] === undefined || obj[key] === null ? '' : '' + obj[key];
  1245. key = lowerCaseKey ? camSafeUrlEncode(key).toLowerCase() : camSafeUrlEncode(key);
  1246. val = camSafeUrlEncode(val) || '';
  1247. list.push(key + '=' + val);
  1248. }
  1249. return list.join('&');
  1250. };
  1251. var request = function request(params, callback) {
  1252. var filePath = params.filePath;
  1253. var headers = params.headers || {};
  1254. var url = params.url || params.Url;
  1255. var method = params.method;
  1256. var onProgress = params.onProgress;
  1257. var httpDNSServiceId = params.httpDNSServiceId;
  1258. var requestTask;
  1259. var cb = function cb(err, response) {
  1260. var H = response.header;
  1261. var headers = {};
  1262. if (H) for (var key in H) {
  1263. if (H.hasOwnProperty(key)) headers[key.toLowerCase()] = H[key];
  1264. }
  1265. callback(err, {
  1266. statusCode: response.statusCode,
  1267. headers: headers
  1268. }, response.data);
  1269. };
  1270. if (filePath) {
  1271. var fileKey;
  1272. var m = url.match(/^(https?:\/\/[^/]+\/)([^/]*\/?)(.*)$/);
  1273. if (params.pathStyle) {
  1274. fileKey = decodeURIComponent(m[3] || '');
  1275. url = m[1] + m[2];
  1276. } else {
  1277. fileKey = decodeURIComponent(m[2] + m[3] || '');
  1278. url = m[1];
  1279. }
  1280. // 整理 postObject 参数
  1281. var formData = {
  1282. 'key': fileKey,
  1283. 'success_action_status': 200,
  1284. 'Signature': headers.Authorization
  1285. };
  1286. var headerKeys = ['Cache-Control', 'Content-Type', 'Content-Disposition', 'Content-Encoding', 'Expires', 'x-cos-storage-class', 'x-cos-security-token', 'x-ci-security-token'];
  1287. for (var i in params.headers) {
  1288. if (params.headers.hasOwnProperty(i) && (i.indexOf('x-cos-meta-') > -1 || headerKeys.indexOf(i) > -1)) {
  1289. formData[i] = params.headers[i];
  1290. }
  1291. }
  1292. headers['x-cos-acl'] && (formData.acl = headers['x-cos-acl']);
  1293. !formData['Content-Type'] && (formData['Content-Type'] = '');
  1294. requestTask = wx.uploadFile({
  1295. url: url,
  1296. method: method,
  1297. name: 'file',
  1298. header: headers,
  1299. filePath: filePath,
  1300. formData: formData,
  1301. timeout: params.timeout,
  1302. success: function success(response) {
  1303. cb(null, response);
  1304. },
  1305. fail: function fail(response) {
  1306. cb(response.errMsg, response);
  1307. }
  1308. });
  1309. requestTask.onProgressUpdate(function (res) {
  1310. onProgress && onProgress({
  1311. loaded: res.totalBytesSent,
  1312. total: res.totalBytesExpectedToSend,
  1313. progress: res.progress / 100
  1314. });
  1315. });
  1316. } else {
  1317. var qsStr = params.qs && obj2str(params.qs) || '';
  1318. if (qsStr) {
  1319. url += (url.indexOf('?') > -1 ? '&' : '?') + qsStr;
  1320. }
  1321. headers['Content-Length'] && delete headers['Content-Length'];
  1322. var requestParams = {
  1323. url: url,
  1324. method: method,
  1325. header: headers,
  1326. dataType: 'text',
  1327. data: params.body,
  1328. responseType: params.dataType || 'text',
  1329. timeout: params.timeout,
  1330. redirect: 'manual',
  1331. success: function success(response) {
  1332. cb(null, response);
  1333. },
  1334. fail: function fail(response) {
  1335. cb(response.errMsg, response);
  1336. }
  1337. };
  1338. if (httpDNSServiceId) {
  1339. Object.assign(requestParams, {
  1340. enableHttpDNS: true,
  1341. httpDNSServiceId: httpDNSServiceId
  1342. });
  1343. }
  1344. requestTask = wx.request(requestParams);
  1345. }
  1346. return requestTask;
  1347. };
  1348. module.exports = request;
  1349. /***/ }),
  1350. /***/ "./node_modules/fast-xml-parser/src/fxp.js":
  1351. /*!*************************************************!*\
  1352. !*** ./node_modules/fast-xml-parser/src/fxp.js ***!
  1353. \*************************************************/
  1354. /*! no static exports found */
  1355. /***/ (function(module, exports, __webpack_require__) {
  1356. "use strict";
  1357. const validator = __webpack_require__(/*! ./validator */ "./node_modules/fast-xml-parser/src/validator.js");
  1358. const XMLParser = __webpack_require__(/*! ./xmlparser/XMLParser */ "./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js");
  1359. const XMLBuilder = __webpack_require__(/*! ./xmlbuilder/json2xml */ "./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js");
  1360. module.exports = {
  1361. XMLParser: XMLParser,
  1362. XMLValidator: validator,
  1363. XMLBuilder: XMLBuilder
  1364. }
  1365. /***/ }),
  1366. /***/ "./node_modules/fast-xml-parser/src/util.js":
  1367. /*!**************************************************!*\
  1368. !*** ./node_modules/fast-xml-parser/src/util.js ***!
  1369. \**************************************************/
  1370. /*! no static exports found */
  1371. /***/ (function(module, exports, __webpack_require__) {
  1372. "use strict";
  1373. const nameStartChar = ':A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD';
  1374. const nameChar = nameStartChar + '\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040';
  1375. const nameRegexp = '[' + nameStartChar + '][' + nameChar + ']*'
  1376. const regexName = new RegExp('^' + nameRegexp + '$');
  1377. const getAllMatches = function(string, regex) {
  1378. const matches = [];
  1379. let match = regex.exec(string);
  1380. while (match) {
  1381. const allmatches = [];
  1382. allmatches.startIndex = regex.lastIndex - match[0].length;
  1383. const len = match.length;
  1384. for (let index = 0; index < len; index++) {
  1385. allmatches.push(match[index]);
  1386. }
  1387. matches.push(allmatches);
  1388. match = regex.exec(string);
  1389. }
  1390. return matches;
  1391. };
  1392. const isName = function(string) {
  1393. const match = regexName.exec(string);
  1394. return !(match === null || typeof match === 'undefined');
  1395. };
  1396. exports.isExist = function(v) {
  1397. return typeof v !== 'undefined';
  1398. };
  1399. exports.isEmptyObject = function(obj) {
  1400. return Object.keys(obj).length === 0;
  1401. };
  1402. /**
  1403. * Copy all the properties of a into b.
  1404. * @param {*} target
  1405. * @param {*} a
  1406. */
  1407. exports.merge = function(target, a, arrayMode) {
  1408. if (a) {
  1409. const keys = Object.keys(a); // will return an array of own properties
  1410. const len = keys.length; //don't make it inline
  1411. for (let i = 0; i < len; i++) {
  1412. if (arrayMode === 'strict') {
  1413. target[keys[i]] = [ a[keys[i]] ];
  1414. } else {
  1415. target[keys[i]] = a[keys[i]];
  1416. }
  1417. }
  1418. }
  1419. };
  1420. /* exports.merge =function (b,a){
  1421. return Object.assign(b,a);
  1422. } */
  1423. exports.getValue = function(v) {
  1424. if (exports.isExist(v)) {
  1425. return v;
  1426. } else {
  1427. return '';
  1428. }
  1429. };
  1430. // const fakeCall = function(a) {return a;};
  1431. // const fakeCallNoReturn = function() {};
  1432. exports.isName = isName;
  1433. exports.getAllMatches = getAllMatches;
  1434. exports.nameRegexp = nameRegexp;
  1435. /***/ }),
  1436. /***/ "./node_modules/fast-xml-parser/src/validator.js":
  1437. /*!*******************************************************!*\
  1438. !*** ./node_modules/fast-xml-parser/src/validator.js ***!
  1439. \*******************************************************/
  1440. /*! no static exports found */
  1441. /***/ (function(module, exports, __webpack_require__) {
  1442. "use strict";
  1443. const util = __webpack_require__(/*! ./util */ "./node_modules/fast-xml-parser/src/util.js");
  1444. const defaultOptions = {
  1445. allowBooleanAttributes: false, //A tag can have attributes without any value
  1446. unpairedTags: []
  1447. };
  1448. //const tagsPattern = new RegExp("<\\/?([\\w:\\-_\.]+)\\s*\/?>","g");
  1449. exports.validate = function (xmlData, options) {
  1450. options = Object.assign({}, defaultOptions, options);
  1451. //xmlData = xmlData.replace(/(\r\n|\n|\r)/gm,"");//make it single line
  1452. //xmlData = xmlData.replace(/(^\s*<\?xml.*?\?>)/g,"");//Remove XML starting tag
  1453. //xmlData = xmlData.replace(/(<!DOCTYPE[\s\w\"\.\/\-\:]+(\[.*\])*\s*>)/g,"");//Remove DOCTYPE
  1454. const tags = [];
  1455. let tagFound = false;
  1456. //indicates that the root tag has been closed (aka. depth 0 has been reached)
  1457. let reachedRoot = false;
  1458. if (xmlData[0] === '\ufeff') {
  1459. // check for byte order mark (BOM)
  1460. xmlData = xmlData.substr(1);
  1461. }
  1462. for (let i = 0; i < xmlData.length; i++) {
  1463. if (xmlData[i] === '<' && xmlData[i+1] === '?') {
  1464. i+=2;
  1465. i = readPI(xmlData,i);
  1466. if (i.err) return i;
  1467. }else if (xmlData[i] === '<') {
  1468. //starting of tag
  1469. //read until you reach to '>' avoiding any '>' in attribute value
  1470. let tagStartPos = i;
  1471. i++;
  1472. if (xmlData[i] === '!') {
  1473. i = readCommentAndCDATA(xmlData, i);
  1474. continue;
  1475. } else {
  1476. let closingTag = false;
  1477. if (xmlData[i] === '/') {
  1478. //closing tag
  1479. closingTag = true;
  1480. i++;
  1481. }
  1482. //read tagname
  1483. let tagName = '';
  1484. for (; i < xmlData.length &&
  1485. xmlData[i] !== '>' &&
  1486. xmlData[i] !== ' ' &&
  1487. xmlData[i] !== '\t' &&
  1488. xmlData[i] !== '\n' &&
  1489. xmlData[i] !== '\r'; i++
  1490. ) {
  1491. tagName += xmlData[i];
  1492. }
  1493. tagName = tagName.trim();
  1494. //console.log(tagName);
  1495. if (tagName[tagName.length - 1] === '/') {
  1496. //self closing tag without attributes
  1497. tagName = tagName.substring(0, tagName.length - 1);
  1498. //continue;
  1499. i--;
  1500. }
  1501. if (!validateTagName(tagName)) {
  1502. let msg;
  1503. if (tagName.trim().length === 0) {
  1504. msg = "Invalid space after '<'.";
  1505. } else {
  1506. msg = "Tag '"+tagName+"' is an invalid name.";
  1507. }
  1508. return getErrorObject('InvalidTag', msg, getLineNumberForPosition(xmlData, i));
  1509. }
  1510. const result = readAttributeStr(xmlData, i);
  1511. if (result === false) {
  1512. return getErrorObject('InvalidAttr', "Attributes for '"+tagName+"' have open quote.", getLineNumberForPosition(xmlData, i));
  1513. }
  1514. let attrStr = result.value;
  1515. i = result.index;
  1516. if (attrStr[attrStr.length - 1] === '/') {
  1517. //self closing tag
  1518. const attrStrStart = i - attrStr.length;
  1519. attrStr = attrStr.substring(0, attrStr.length - 1);
  1520. const isValid = validateAttributeString(attrStr, options);
  1521. if (isValid === true) {
  1522. tagFound = true;
  1523. //continue; //text may presents after self closing tag
  1524. } else {
  1525. //the result from the nested function returns the position of the error within the attribute
  1526. //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
  1527. //this gives us the absolute index in the entire xml, which we can use to find the line at last
  1528. return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, attrStrStart + isValid.err.line));
  1529. }
  1530. } else if (closingTag) {
  1531. if (!result.tagClosed) {
  1532. return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' doesn't have proper closing.", getLineNumberForPosition(xmlData, i));
  1533. } else if (attrStr.trim().length > 0) {
  1534. return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' can't have attributes or invalid starting.", getLineNumberForPosition(xmlData, tagStartPos));
  1535. } else if (tags.length === 0) {
  1536. return getErrorObject('InvalidTag', "Closing tag '"+tagName+"' has not been opened.", getLineNumberForPosition(xmlData, tagStartPos));
  1537. } else {
  1538. const otg = tags.pop();
  1539. if (tagName !== otg.tagName) {
  1540. let openPos = getLineNumberForPosition(xmlData, otg.tagStartPos);
  1541. return getErrorObject('InvalidTag',
  1542. "Expected closing tag '"+otg.tagName+"' (opened in line "+openPos.line+", col "+openPos.col+") instead of closing tag '"+tagName+"'.",
  1543. getLineNumberForPosition(xmlData, tagStartPos));
  1544. }
  1545. //when there are no more tags, we reached the root level.
  1546. if (tags.length == 0) {
  1547. reachedRoot = true;
  1548. }
  1549. }
  1550. } else {
  1551. const isValid = validateAttributeString(attrStr, options);
  1552. if (isValid !== true) {
  1553. //the result from the nested function returns the position of the error within the attribute
  1554. //in order to get the 'true' error line, we need to calculate the position where the attribute begins (i - attrStr.length) and then add the position within the attribute
  1555. //this gives us the absolute index in the entire xml, which we can use to find the line at last
  1556. return getErrorObject(isValid.err.code, isValid.err.msg, getLineNumberForPosition(xmlData, i - attrStr.length + isValid.err.line));
  1557. }
  1558. //if the root level has been reached before ...
  1559. if (reachedRoot === true) {
  1560. return getErrorObject('InvalidXml', 'Multiple possible root nodes found.', getLineNumberForPosition(xmlData, i));
  1561. } else if(options.unpairedTags.indexOf(tagName) !== -1){
  1562. //don't push into stack
  1563. } else {
  1564. tags.push({tagName, tagStartPos});
  1565. }
  1566. tagFound = true;
  1567. }
  1568. //skip tag text value
  1569. //It may include comments and CDATA value
  1570. for (i++; i < xmlData.length; i++) {
  1571. if (xmlData[i] === '<') {
  1572. if (xmlData[i + 1] === '!') {
  1573. //comment or CADATA
  1574. i++;
  1575. i = readCommentAndCDATA(xmlData, i);
  1576. continue;
  1577. } else if (xmlData[i+1] === '?') {
  1578. i = readPI(xmlData, ++i);
  1579. if (i.err) return i;
  1580. } else{
  1581. break;
  1582. }
  1583. } else if (xmlData[i] === '&') {
  1584. const afterAmp = validateAmpersand(xmlData, i);
  1585. if (afterAmp == -1)
  1586. return getErrorObject('InvalidChar', "char '&' is not expected.", getLineNumberForPosition(xmlData, i));
  1587. i = afterAmp;
  1588. }else{
  1589. if (reachedRoot === true && !isWhiteSpace(xmlData[i])) {
  1590. return getErrorObject('InvalidXml', "Extra text at the end", getLineNumberForPosition(xmlData, i));
  1591. }
  1592. }
  1593. } //end of reading tag text value
  1594. if (xmlData[i] === '<') {
  1595. i--;
  1596. }
  1597. }
  1598. } else {
  1599. if ( isWhiteSpace(xmlData[i])) {
  1600. continue;
  1601. }
  1602. return getErrorObject('InvalidChar', "char '"+xmlData[i]+"' is not expected.", getLineNumberForPosition(xmlData, i));
  1603. }
  1604. }
  1605. if (!tagFound) {
  1606. return getErrorObject('InvalidXml', 'Start tag expected.', 1);
  1607. }else if (tags.length == 1) {
  1608. return getErrorObject('InvalidTag', "Unclosed tag '"+tags[0].tagName+"'.", getLineNumberForPosition(xmlData, tags[0].tagStartPos));
  1609. }else if (tags.length > 0) {
  1610. return getErrorObject('InvalidXml', "Invalid '"+
  1611. JSON.stringify(tags.map(t => t.tagName), null, 4).replace(/\r?\n/g, '')+
  1612. "' found.", {line: 1, col: 1});
  1613. }
  1614. return true;
  1615. };
  1616. function isWhiteSpace(char){
  1617. return char === ' ' || char === '\t' || char === '\n' || char === '\r';
  1618. }
  1619. /**
  1620. * Read Processing insstructions and skip
  1621. * @param {*} xmlData
  1622. * @param {*} i
  1623. */
  1624. function readPI(xmlData, i) {
  1625. const start = i;
  1626. for (; i < xmlData.length; i++) {
  1627. if (xmlData[i] == '?' || xmlData[i] == ' ') {
  1628. //tagname
  1629. const tagname = xmlData.substr(start, i - start);
  1630. if (i > 5 && tagname === 'xml') {
  1631. return getErrorObject('InvalidXml', 'XML declaration allowed only at the start of the document.', getLineNumberForPosition(xmlData, i));
  1632. } else if (xmlData[i] == '?' && xmlData[i + 1] == '>') {
  1633. //check if valid attribut string
  1634. i++;
  1635. break;
  1636. } else {
  1637. continue;
  1638. }
  1639. }
  1640. }
  1641. return i;
  1642. }
  1643. function readCommentAndCDATA(xmlData, i) {
  1644. if (xmlData.length > i + 5 && xmlData[i + 1] === '-' && xmlData[i + 2] === '-') {
  1645. //comment
  1646. for (i += 3; i < xmlData.length; i++) {
  1647. if (xmlData[i] === '-' && xmlData[i + 1] === '-' && xmlData[i + 2] === '>') {
  1648. i += 2;
  1649. break;
  1650. }
  1651. }
  1652. } else if (
  1653. xmlData.length > i + 8 &&
  1654. xmlData[i + 1] === 'D' &&
  1655. xmlData[i + 2] === 'O' &&
  1656. xmlData[i + 3] === 'C' &&
  1657. xmlData[i + 4] === 'T' &&
  1658. xmlData[i + 5] === 'Y' &&
  1659. xmlData[i + 6] === 'P' &&
  1660. xmlData[i + 7] === 'E'
  1661. ) {
  1662. let angleBracketsCount = 1;
  1663. for (i += 8; i < xmlData.length; i++) {
  1664. if (xmlData[i] === '<') {
  1665. angleBracketsCount++;
  1666. } else if (xmlData[i] === '>') {
  1667. angleBracketsCount--;
  1668. if (angleBracketsCount === 0) {
  1669. break;
  1670. }
  1671. }
  1672. }
  1673. } else if (
  1674. xmlData.length > i + 9 &&
  1675. xmlData[i + 1] === '[' &&
  1676. xmlData[i + 2] === 'C' &&
  1677. xmlData[i + 3] === 'D' &&
  1678. xmlData[i + 4] === 'A' &&
  1679. xmlData[i + 5] === 'T' &&
  1680. xmlData[i + 6] === 'A' &&
  1681. xmlData[i + 7] === '['
  1682. ) {
  1683. for (i += 8; i < xmlData.length; i++) {
  1684. if (xmlData[i] === ']' && xmlData[i + 1] === ']' && xmlData[i + 2] === '>') {
  1685. i += 2;
  1686. break;
  1687. }
  1688. }
  1689. }
  1690. return i;
  1691. }
  1692. const doubleQuote = '"';
  1693. const singleQuote = "'";
  1694. /**
  1695. * Keep reading xmlData until '<' is found outside the attribute value.
  1696. * @param {string} xmlData
  1697. * @param {number} i
  1698. */
  1699. function readAttributeStr(xmlData, i) {
  1700. let attrStr = '';
  1701. let startChar = '';
  1702. let tagClosed = false;
  1703. for (; i < xmlData.length; i++) {
  1704. if (xmlData[i] === doubleQuote || xmlData[i] === singleQuote) {
  1705. if (startChar === '') {
  1706. startChar = xmlData[i];
  1707. } else if (startChar !== xmlData[i]) {
  1708. //if vaue is enclosed with double quote then single quotes are allowed inside the value and vice versa
  1709. } else {
  1710. startChar = '';
  1711. }
  1712. } else if (xmlData[i] === '>') {
  1713. if (startChar === '') {
  1714. tagClosed = true;
  1715. break;
  1716. }
  1717. }
  1718. attrStr += xmlData[i];
  1719. }
  1720. if (startChar !== '') {
  1721. return false;
  1722. }
  1723. return {
  1724. value: attrStr,
  1725. index: i,
  1726. tagClosed: tagClosed
  1727. };
  1728. }
  1729. /**
  1730. * Select all the attributes whether valid or invalid.
  1731. */
  1732. const validAttrStrRegxp = new RegExp('(\\s*)([^\\s=]+)(\\s*=)?(\\s*([\'"])(([\\s\\S])*?)\\5)?', 'g');
  1733. //attr, ="sd", a="amit's", a="sd"b="saf", ab cd=""
  1734. function validateAttributeString(attrStr, options) {
  1735. //console.log("start:"+attrStr+":end");
  1736. //if(attrStr.trim().length === 0) return true; //empty string
  1737. const matches = util.getAllMatches(attrStr, validAttrStrRegxp);
  1738. const attrNames = {};
  1739. for (let i = 0; i < matches.length; i++) {
  1740. if (matches[i][1].length === 0) {
  1741. //nospace before attribute name: a="sd"b="saf"
  1742. return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' has no space in starting.", getPositionFromMatch(matches[i]))
  1743. } else if (matches[i][3] !== undefined && matches[i][4] === undefined) {
  1744. return getErrorObject('InvalidAttr', "Attribute '"+matches[i][2]+"' is without value.", getPositionFromMatch(matches[i]));
  1745. } else if (matches[i][3] === undefined && !options.allowBooleanAttributes) {
  1746. //independent attribute: ab
  1747. return getErrorObject('InvalidAttr', "boolean attribute '"+matches[i][2]+"' is not allowed.", getPositionFromMatch(matches[i]));
  1748. }
  1749. /* else if(matches[i][6] === undefined){//attribute without value: ab=
  1750. return { err: { code:"InvalidAttr",msg:"attribute " + matches[i][2] + " has no value assigned."}};
  1751. } */
  1752. const attrName = matches[i][2];
  1753. if (!validateAttrName(attrName)) {
  1754. return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is an invalid name.", getPositionFromMatch(matches[i]));
  1755. }
  1756. if (!attrNames.hasOwnProperty(attrName)) {
  1757. //check for duplicate attribute.
  1758. attrNames[attrName] = 1;
  1759. } else {
  1760. return getErrorObject('InvalidAttr', "Attribute '"+attrName+"' is repeated.", getPositionFromMatch(matches[i]));
  1761. }
  1762. }
  1763. return true;
  1764. }
  1765. function validateNumberAmpersand(xmlData, i) {
  1766. let re = /\d/;
  1767. if (xmlData[i] === 'x') {
  1768. i++;
  1769. re = /[\da-fA-F]/;
  1770. }
  1771. for (; i < xmlData.length; i++) {
  1772. if (xmlData[i] === ';')
  1773. return i;
  1774. if (!xmlData[i].match(re))
  1775. break;
  1776. }
  1777. return -1;
  1778. }
  1779. function validateAmpersand(xmlData, i) {
  1780. // https://www.w3.org/TR/xml/#dt-charref
  1781. i++;
  1782. if (xmlData[i] === ';')
  1783. return -1;
  1784. if (xmlData[i] === '#') {
  1785. i++;
  1786. return validateNumberAmpersand(xmlData, i);
  1787. }
  1788. let count = 0;
  1789. for (; i < xmlData.length; i++, count++) {
  1790. if (xmlData[i].match(/\w/) && count < 20)
  1791. continue;
  1792. if (xmlData[i] === ';')
  1793. break;
  1794. return -1;
  1795. }
  1796. return i;
  1797. }
  1798. function getErrorObject(code, message, lineNumber) {
  1799. return {
  1800. err: {
  1801. code: code,
  1802. msg: message,
  1803. line: lineNumber.line || lineNumber,
  1804. col: lineNumber.col,
  1805. },
  1806. };
  1807. }
  1808. function validateAttrName(attrName) {
  1809. return util.isName(attrName);
  1810. }
  1811. // const startsWithXML = /^xml/i;
  1812. function validateTagName(tagname) {
  1813. return util.isName(tagname) /* && !tagname.match(startsWithXML) */;
  1814. }
  1815. //this function returns the line number for the character at the given index
  1816. function getLineNumberForPosition(xmlData, index) {
  1817. const lines = xmlData.substring(0, index).split(/\r?\n/);
  1818. return {
  1819. line: lines.length,
  1820. // column number is last line's length + 1, because column numbering starts at 1:
  1821. col: lines[lines.length - 1].length + 1
  1822. };
  1823. }
  1824. //this function returns the position of the first character of match within attrStr
  1825. function getPositionFromMatch(match) {
  1826. return match.startIndex + match[1].length;
  1827. }
  1828. /***/ }),
  1829. /***/ "./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js":
  1830. /*!*****************************************************************!*\
  1831. !*** ./node_modules/fast-xml-parser/src/xmlbuilder/json2xml.js ***!
  1832. \*****************************************************************/
  1833. /*! no static exports found */
  1834. /***/ (function(module, exports, __webpack_require__) {
  1835. "use strict";
  1836. //parse Empty Node as self closing node
  1837. const buildFromOrderedJs = __webpack_require__(/*! ./orderedJs2Xml */ "./node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js");
  1838. const defaultOptions = {
  1839. attributeNamePrefix: '@_',
  1840. attributesGroupName: false,
  1841. textNodeName: '#text',
  1842. ignoreAttributes: true,
  1843. cdataPropName: false,
  1844. format: false,
  1845. indentBy: ' ',
  1846. suppressEmptyNode: false,
  1847. suppressUnpairedNode: true,
  1848. suppressBooleanAttributes: true,
  1849. tagValueProcessor: function(key, a) {
  1850. return a;
  1851. },
  1852. attributeValueProcessor: function(attrName, a) {
  1853. return a;
  1854. },
  1855. preserveOrder: false,
  1856. commentPropName: false,
  1857. unpairedTags: [],
  1858. entities: [
  1859. { regex: new RegExp("&", "g"), val: "&amp;" },//it must be on top
  1860. { regex: new RegExp(">", "g"), val: "&gt;" },
  1861. { regex: new RegExp("<", "g"), val: "&lt;" },
  1862. { regex: new RegExp("\'", "g"), val: "&apos;" },
  1863. { regex: new RegExp("\"", "g"), val: "&quot;" }
  1864. ],
  1865. processEntities: true,
  1866. stopNodes: [],
  1867. // transformTagName: false,
  1868. // transformAttributeName: false,
  1869. oneListGroup: false
  1870. };
  1871. function Builder(options) {
  1872. this.options = Object.assign({}, defaultOptions, options);
  1873. if (this.options.ignoreAttributes || this.options.attributesGroupName) {
  1874. this.isAttribute = function(/*a*/) {
  1875. return false;
  1876. };
  1877. } else {
  1878. this.attrPrefixLen = this.options.attributeNamePrefix.length;
  1879. this.isAttribute = isAttribute;
  1880. }
  1881. this.processTextOrObjNode = processTextOrObjNode
  1882. if (this.options.format) {
  1883. this.indentate = indentate;
  1884. this.tagEndChar = '>\n';
  1885. this.newLine = '\n';
  1886. } else {
  1887. this.indentate = function() {
  1888. return '';
  1889. };
  1890. this.tagEndChar = '>';
  1891. this.newLine = '';
  1892. }
  1893. }
  1894. Builder.prototype.build = function(jObj) {
  1895. if(this.options.preserveOrder){
  1896. return buildFromOrderedJs(jObj, this.options);
  1897. }else {
  1898. if(Array.isArray(jObj) && this.options.arrayNodeName && this.options.arrayNodeName.length > 1){
  1899. jObj = {
  1900. [this.options.arrayNodeName] : jObj
  1901. }
  1902. }
  1903. return this.j2x(jObj, 0).val;
  1904. }
  1905. };
  1906. Builder.prototype.j2x = function(jObj, level) {
  1907. let attrStr = '';
  1908. let val = '';
  1909. for (let key in jObj) {
  1910. if(!Object.prototype.hasOwnProperty.call(jObj, key)) continue;
  1911. if (typeof jObj[key] === 'undefined') {
  1912. // supress undefined node only if it is not an attribute
  1913. if (this.isAttribute(key)) {
  1914. val += '';
  1915. }
  1916. } else if (jObj[key] === null) {
  1917. // null attribute should be ignored by the attribute list, but should not cause the tag closing
  1918. if (this.isAttribute(key)) {
  1919. val += '';
  1920. } else if (key[0] === '?') {
  1921. val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
  1922. } else {
  1923. val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
  1924. }
  1925. // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
  1926. } else if (jObj[key] instanceof Date) {
  1927. val += this.buildTextValNode(jObj[key], key, '', level);
  1928. } else if (typeof jObj[key] !== 'object') {
  1929. //premitive type
  1930. const attr = this.isAttribute(key);
  1931. if (attr) {
  1932. attrStr += this.buildAttrPairStr(attr, '' + jObj[key]);
  1933. }else {
  1934. //tag value
  1935. if (key === this.options.textNodeName) {
  1936. let newval = this.options.tagValueProcessor(key, '' + jObj[key]);
  1937. val += this.replaceEntitiesValue(newval);
  1938. } else {
  1939. val += this.buildTextValNode(jObj[key], key, '', level);
  1940. }
  1941. }
  1942. } else if (Array.isArray(jObj[key])) {
  1943. //repeated nodes
  1944. const arrLen = jObj[key].length;
  1945. let listTagVal = "";
  1946. for (let j = 0; j < arrLen; j++) {
  1947. const item = jObj[key][j];
  1948. if (typeof item === 'undefined') {
  1949. // supress undefined node
  1950. } else if (item === null) {
  1951. if(key[0] === "?") val += this.indentate(level) + '<' + key + '?' + this.tagEndChar;
  1952. else val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
  1953. // val += this.indentate(level) + '<' + key + '/' + this.tagEndChar;
  1954. } else if (typeof item === 'object') {
  1955. if(this.options.oneListGroup ){
  1956. listTagVal += this.j2x(item, level + 1).val;
  1957. }else{
  1958. listTagVal += this.processTextOrObjNode(item, key, level)
  1959. }
  1960. } else {
  1961. listTagVal += this.buildTextValNode(item, key, '', level);
  1962. }
  1963. }
  1964. if(this.options.oneListGroup){
  1965. listTagVal = this.buildObjectNode(listTagVal, key, '', level);
  1966. }
  1967. val += listTagVal;
  1968. } else {
  1969. //nested node
  1970. if (this.options.attributesGroupName && key === this.options.attributesGroupName) {
  1971. const Ks = Object.keys(jObj[key]);
  1972. const L = Ks.length;
  1973. for (let j = 0; j < L; j++) {
  1974. attrStr += this.buildAttrPairStr(Ks[j], '' + jObj[key][Ks[j]]);
  1975. }
  1976. } else {
  1977. val += this.processTextOrObjNode(jObj[key], key, level)
  1978. }
  1979. }
  1980. }
  1981. return {attrStr: attrStr, val: val};
  1982. };
  1983. Builder.prototype.buildAttrPairStr = function(attrName, val){
  1984. val = this.options.attributeValueProcessor(attrName, '' + val);
  1985. val = this.replaceEntitiesValue(val);
  1986. if (this.options.suppressBooleanAttributes && val === "true") {
  1987. return ' ' + attrName;
  1988. } else return ' ' + attrName + '="' + val + '"';
  1989. }
  1990. function processTextOrObjNode (object, key, level) {
  1991. const result = this.j2x(object, level + 1);
  1992. if (object[this.options.textNodeName] !== undefined && Object.keys(object).length === 1) {
  1993. return this.buildTextValNode(object[this.options.textNodeName], key, result.attrStr, level);
  1994. } else {
  1995. return this.buildObjectNode(result.val, key, result.attrStr, level);
  1996. }
  1997. }
  1998. Builder.prototype.buildObjectNode = function(val, key, attrStr, level) {
  1999. if(val === ""){
  2000. if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
  2001. else {
  2002. return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
  2003. }
  2004. }else{
  2005. let tagEndExp = '</' + key + this.tagEndChar;
  2006. let piClosingChar = "";
  2007. if(key[0] === "?") {
  2008. piClosingChar = "?";
  2009. tagEndExp = "";
  2010. }
  2011. // attrStr is an empty string in case the attribute came as undefined or null
  2012. if ((attrStr || attrStr === '') && val.indexOf('<') === -1) {
  2013. return ( this.indentate(level) + '<' + key + attrStr + piClosingChar + '>' + val + tagEndExp );
  2014. } else if (this.options.commentPropName !== false && key === this.options.commentPropName && piClosingChar.length === 0) {
  2015. return this.indentate(level) + `<!--${val}-->` + this.newLine;
  2016. }else {
  2017. return (
  2018. this.indentate(level) + '<' + key + attrStr + piClosingChar + this.tagEndChar +
  2019. val +
  2020. this.indentate(level) + tagEndExp );
  2021. }
  2022. }
  2023. }
  2024. Builder.prototype.closeTag = function(key){
  2025. let closeTag = "";
  2026. if(this.options.unpairedTags.indexOf(key) !== -1){ //unpaired
  2027. if(!this.options.suppressUnpairedNode) closeTag = "/"
  2028. }else if(this.options.suppressEmptyNode){ //empty
  2029. closeTag = "/";
  2030. }else{
  2031. closeTag = `></${key}`
  2032. }
  2033. return closeTag;
  2034. }
  2035. function buildEmptyObjNode(val, key, attrStr, level) {
  2036. if (val !== '') {
  2037. return this.buildObjectNode(val, key, attrStr, level);
  2038. } else {
  2039. if(key[0] === "?") return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
  2040. else {
  2041. return this.indentate(level) + '<' + key + attrStr + '/' + this.tagEndChar;
  2042. // return this.buildTagStr(level,key, attrStr);
  2043. }
  2044. }
  2045. }
  2046. Builder.prototype.buildTextValNode = function(val, key, attrStr, level) {
  2047. if (this.options.cdataPropName !== false && key === this.options.cdataPropName) {
  2048. return this.indentate(level) + `<![CDATA[${val}]]>` + this.newLine;
  2049. }else if (this.options.commentPropName !== false && key === this.options.commentPropName) {
  2050. return this.indentate(level) + `<!--${val}-->` + this.newLine;
  2051. }else if(key[0] === "?") {//PI tag
  2052. return this.indentate(level) + '<' + key + attrStr+ '?' + this.tagEndChar;
  2053. }else{
  2054. let textValue = this.options.tagValueProcessor(key, val);
  2055. textValue = this.replaceEntitiesValue(textValue);
  2056. if( textValue === ''){
  2057. return this.indentate(level) + '<' + key + attrStr + this.closeTag(key) + this.tagEndChar;
  2058. }else{
  2059. return this.indentate(level) + '<' + key + attrStr + '>' +
  2060. textValue +
  2061. '</' + key + this.tagEndChar;
  2062. }
  2063. }
  2064. }
  2065. Builder.prototype.replaceEntitiesValue = function(textValue){
  2066. if(textValue && textValue.length > 0 && this.options.processEntities){
  2067. for (let i=0; i<this.options.entities.length; i++) {
  2068. const entity = this.options.entities[i];
  2069. textValue = textValue.replace(entity.regex, entity.val);
  2070. }
  2071. }
  2072. return textValue;
  2073. }
  2074. function indentate(level) {
  2075. return this.options.indentBy.repeat(level);
  2076. }
  2077. function isAttribute(name /*, options*/) {
  2078. if (name.startsWith(this.options.attributeNamePrefix) && name !== this.options.textNodeName) {
  2079. return name.substr(this.attrPrefixLen);
  2080. } else {
  2081. return false;
  2082. }
  2083. }
  2084. module.exports = Builder;
  2085. /***/ }),
  2086. /***/ "./node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js":
  2087. /*!**********************************************************************!*\
  2088. !*** ./node_modules/fast-xml-parser/src/xmlbuilder/orderedJs2Xml.js ***!
  2089. \**********************************************************************/
  2090. /*! no static exports found */
  2091. /***/ (function(module, exports) {
  2092. const EOL = "\n";
  2093. /**
  2094. *
  2095. * @param {array} jArray
  2096. * @param {any} options
  2097. * @returns
  2098. */
  2099. function toXml(jArray, options) {
  2100. let indentation = "";
  2101. if (options.format && options.indentBy.length > 0) {
  2102. indentation = EOL;
  2103. }
  2104. return arrToStr(jArray, options, "", indentation);
  2105. }
  2106. function arrToStr(arr, options, jPath, indentation) {
  2107. let xmlStr = "";
  2108. let isPreviousElementTag = false;
  2109. for (let i = 0; i < arr.length; i++) {
  2110. const tagObj = arr[i];
  2111. const tagName = propName(tagObj);
  2112. if(tagName === undefined) continue;
  2113. let newJPath = "";
  2114. if (jPath.length === 0) newJPath = tagName
  2115. else newJPath = `${jPath}.${tagName}`;
  2116. if (tagName === options.textNodeName) {
  2117. let tagText = tagObj[tagName];
  2118. if (!isStopNode(newJPath, options)) {
  2119. tagText = options.tagValueProcessor(tagName, tagText);
  2120. tagText = replaceEntitiesValue(tagText, options);
  2121. }
  2122. if (isPreviousElementTag) {
  2123. xmlStr += indentation;
  2124. }
  2125. xmlStr += tagText;
  2126. isPreviousElementTag = false;
  2127. continue;
  2128. } else if (tagName === options.cdataPropName) {
  2129. if (isPreviousElementTag) {
  2130. xmlStr += indentation;
  2131. }
  2132. xmlStr += `<![CDATA[${tagObj[tagName][0][options.textNodeName]}]]>`;
  2133. isPreviousElementTag = false;
  2134. continue;
  2135. } else if (tagName === options.commentPropName) {
  2136. xmlStr += indentation + `<!--${tagObj[tagName][0][options.textNodeName]}-->`;
  2137. isPreviousElementTag = true;
  2138. continue;
  2139. } else if (tagName[0] === "?") {
  2140. const attStr = attr_to_str(tagObj[":@"], options);
  2141. const tempInd = tagName === "?xml" ? "" : indentation;
  2142. let piTextNodeName = tagObj[tagName][0][options.textNodeName];
  2143. piTextNodeName = piTextNodeName.length !== 0 ? " " + piTextNodeName : ""; //remove extra spacing
  2144. xmlStr += tempInd + `<${tagName}${piTextNodeName}${attStr}?>`;
  2145. isPreviousElementTag = true;
  2146. continue;
  2147. }
  2148. let newIdentation = indentation;
  2149. if (newIdentation !== "") {
  2150. newIdentation += options.indentBy;
  2151. }
  2152. const attStr = attr_to_str(tagObj[":@"], options);
  2153. const tagStart = indentation + `<${tagName}${attStr}`;
  2154. const tagValue = arrToStr(tagObj[tagName], options, newJPath, newIdentation);
  2155. if (options.unpairedTags.indexOf(tagName) !== -1) {
  2156. if (options.suppressUnpairedNode) xmlStr += tagStart + ">";
  2157. else xmlStr += tagStart + "/>";
  2158. } else if ((!tagValue || tagValue.length === 0) && options.suppressEmptyNode) {
  2159. xmlStr += tagStart + "/>";
  2160. } else if (tagValue && tagValue.endsWith(">")) {
  2161. xmlStr += tagStart + `>${tagValue}${indentation}</${tagName}>`;
  2162. } else {
  2163. xmlStr += tagStart + ">";
  2164. if (tagValue && indentation !== "" && (tagValue.includes("/>") || tagValue.includes("</"))) {
  2165. xmlStr += indentation + options.indentBy + tagValue + indentation;
  2166. } else {
  2167. xmlStr += tagValue;
  2168. }
  2169. xmlStr += `</${tagName}>`;
  2170. }
  2171. isPreviousElementTag = true;
  2172. }
  2173. return xmlStr;
  2174. }
  2175. function propName(obj) {
  2176. const keys = Object.keys(obj);
  2177. for (let i = 0; i < keys.length; i++) {
  2178. const key = keys[i];
  2179. if(!obj.hasOwnProperty(key)) continue;
  2180. if (key !== ":@") return key;
  2181. }
  2182. }
  2183. function attr_to_str(attrMap, options) {
  2184. let attrStr = "";
  2185. if (attrMap && !options.ignoreAttributes) {
  2186. for (let attr in attrMap) {
  2187. if(!attrMap.hasOwnProperty(attr)) continue;
  2188. let attrVal = options.attributeValueProcessor(attr, attrMap[attr]);
  2189. attrVal = replaceEntitiesValue(attrVal, options);
  2190. if (attrVal === true && options.suppressBooleanAttributes) {
  2191. attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}`;
  2192. } else {
  2193. attrStr += ` ${attr.substr(options.attributeNamePrefix.length)}="${attrVal}"`;
  2194. }
  2195. }
  2196. }
  2197. return attrStr;
  2198. }
  2199. function isStopNode(jPath, options) {
  2200. jPath = jPath.substr(0, jPath.length - options.textNodeName.length - 1);
  2201. let tagName = jPath.substr(jPath.lastIndexOf(".") + 1);
  2202. for (let index in options.stopNodes) {
  2203. if (options.stopNodes[index] === jPath || options.stopNodes[index] === "*." + tagName) return true;
  2204. }
  2205. return false;
  2206. }
  2207. function replaceEntitiesValue(textValue, options) {
  2208. if (textValue && textValue.length > 0 && options.processEntities) {
  2209. for (let i = 0; i < options.entities.length; i++) {
  2210. const entity = options.entities[i];
  2211. textValue = textValue.replace(entity.regex, entity.val);
  2212. }
  2213. }
  2214. return textValue;
  2215. }
  2216. module.exports = toXml;
  2217. /***/ }),
  2218. /***/ "./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js":
  2219. /*!*********************************************************************!*\
  2220. !*** ./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js ***!
  2221. \*********************************************************************/
  2222. /*! no static exports found */
  2223. /***/ (function(module, exports, __webpack_require__) {
  2224. const util = __webpack_require__(/*! ../util */ "./node_modules/fast-xml-parser/src/util.js");
  2225. //TODO: handle comments
  2226. function readDocType(xmlData, i){
  2227. const entities = {};
  2228. if( xmlData[i + 3] === 'O' &&
  2229. xmlData[i + 4] === 'C' &&
  2230. xmlData[i + 5] === 'T' &&
  2231. xmlData[i + 6] === 'Y' &&
  2232. xmlData[i + 7] === 'P' &&
  2233. xmlData[i + 8] === 'E')
  2234. {
  2235. i = i+9;
  2236. let angleBracketsCount = 1;
  2237. let hasBody = false, comment = false;
  2238. let exp = "";
  2239. for(;i<xmlData.length;i++){
  2240. if (xmlData[i] === '<' && !comment) { //Determine the tag type
  2241. if( hasBody && isEntity(xmlData, i)){
  2242. i += 7;
  2243. [entityName, val,i] = readEntityExp(xmlData,i+1);
  2244. if(val.indexOf("&") === -1) //Parameter entities are not supported
  2245. entities[ validateEntityName(entityName) ] = {
  2246. regx : RegExp( `&${entityName};`,"g"),
  2247. val: val
  2248. };
  2249. }
  2250. else if( hasBody && isElement(xmlData, i)) i += 8;//Not supported
  2251. else if( hasBody && isAttlist(xmlData, i)) i += 8;//Not supported
  2252. else if( hasBody && isNotation(xmlData, i)) i += 9;//Not supported
  2253. else if( isComment) comment = true;
  2254. else throw new Error("Invalid DOCTYPE");
  2255. angleBracketsCount++;
  2256. exp = "";
  2257. } else if (xmlData[i] === '>') { //Read tag content
  2258. if(comment){
  2259. if( xmlData[i - 1] === "-" && xmlData[i - 2] === "-"){
  2260. comment = false;
  2261. angleBracketsCount--;
  2262. }
  2263. }else{
  2264. angleBracketsCount--;
  2265. }
  2266. if (angleBracketsCount === 0) {
  2267. break;
  2268. }
  2269. }else if( xmlData[i] === '['){
  2270. hasBody = true;
  2271. }else{
  2272. exp += xmlData[i];
  2273. }
  2274. }
  2275. if(angleBracketsCount !== 0){
  2276. throw new Error(`Unclosed DOCTYPE`);
  2277. }
  2278. }else{
  2279. throw new Error(`Invalid Tag instead of DOCTYPE`);
  2280. }
  2281. return {entities, i};
  2282. }
  2283. function readEntityExp(xmlData,i){
  2284. //External entities are not supported
  2285. // <!ENTITY ext SYSTEM "http://normal-website.com" >
  2286. //Parameter entities are not supported
  2287. // <!ENTITY entityname "&anotherElement;">
  2288. //Internal entities are supported
  2289. // <!ENTITY entityname "replacement text">
  2290. //read EntityName
  2291. let entityName = "";
  2292. for (; i < xmlData.length && (xmlData[i] !== "'" && xmlData[i] !== '"' ); i++) {
  2293. // if(xmlData[i] === " ") continue;
  2294. // else
  2295. entityName += xmlData[i];
  2296. }
  2297. entityName = entityName.trim();
  2298. if(entityName.indexOf(" ") !== -1) throw new Error("External entites are not supported");
  2299. //read Entity Value
  2300. const startChar = xmlData[i++];
  2301. let val = ""
  2302. for (; i < xmlData.length && xmlData[i] !== startChar ; i++) {
  2303. val += xmlData[i];
  2304. }
  2305. return [entityName, val, i];
  2306. }
  2307. function isComment(xmlData, i){
  2308. if(xmlData[i+1] === '!' &&
  2309. xmlData[i+2] === '-' &&
  2310. xmlData[i+3] === '-') return true
  2311. return false
  2312. }
  2313. function isEntity(xmlData, i){
  2314. if(xmlData[i+1] === '!' &&
  2315. xmlData[i+2] === 'E' &&
  2316. xmlData[i+3] === 'N' &&
  2317. xmlData[i+4] === 'T' &&
  2318. xmlData[i+5] === 'I' &&
  2319. xmlData[i+6] === 'T' &&
  2320. xmlData[i+7] === 'Y') return true
  2321. return false
  2322. }
  2323. function isElement(xmlData, i){
  2324. if(xmlData[i+1] === '!' &&
  2325. xmlData[i+2] === 'E' &&
  2326. xmlData[i+3] === 'L' &&
  2327. xmlData[i+4] === 'E' &&
  2328. xmlData[i+5] === 'M' &&
  2329. xmlData[i+6] === 'E' &&
  2330. xmlData[i+7] === 'N' &&
  2331. xmlData[i+8] === 'T') return true
  2332. return false
  2333. }
  2334. function isAttlist(xmlData, i){
  2335. if(xmlData[i+1] === '!' &&
  2336. xmlData[i+2] === 'A' &&
  2337. xmlData[i+3] === 'T' &&
  2338. xmlData[i+4] === 'T' &&
  2339. xmlData[i+5] === 'L' &&
  2340. xmlData[i+6] === 'I' &&
  2341. xmlData[i+7] === 'S' &&
  2342. xmlData[i+8] === 'T') return true
  2343. return false
  2344. }
  2345. function isNotation(xmlData, i){
  2346. if(xmlData[i+1] === '!' &&
  2347. xmlData[i+2] === 'N' &&
  2348. xmlData[i+3] === 'O' &&
  2349. xmlData[i+4] === 'T' &&
  2350. xmlData[i+5] === 'A' &&
  2351. xmlData[i+6] === 'T' &&
  2352. xmlData[i+7] === 'I' &&
  2353. xmlData[i+8] === 'O' &&
  2354. xmlData[i+9] === 'N') return true
  2355. return false
  2356. }
  2357. function validateEntityName(name){
  2358. if (util.isName(name))
  2359. return name;
  2360. else
  2361. throw new Error(`Invalid entity name ${name}`);
  2362. }
  2363. module.exports = readDocType;
  2364. /***/ }),
  2365. /***/ "./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js":
  2366. /*!**********************************************************************!*\
  2367. !*** ./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js ***!
  2368. \**********************************************************************/
  2369. /*! no static exports found */
  2370. /***/ (function(module, exports) {
  2371. const defaultOptions = {
  2372. preserveOrder: false,
  2373. attributeNamePrefix: '@_',
  2374. attributesGroupName: false,
  2375. textNodeName: '#text',
  2376. ignoreAttributes: true,
  2377. removeNSPrefix: false, // remove NS from tag name or attribute name if true
  2378. allowBooleanAttributes: false, //a tag can have attributes without any value
  2379. //ignoreRootElement : false,
  2380. parseTagValue: true,
  2381. parseAttributeValue: false,
  2382. trimValues: true, //Trim string values of tag and attributes
  2383. cdataPropName: false,
  2384. numberParseOptions: {
  2385. hex: true,
  2386. leadingZeros: true,
  2387. eNotation: true
  2388. },
  2389. tagValueProcessor: function(tagName, val) {
  2390. return val;
  2391. },
  2392. attributeValueProcessor: function(attrName, val) {
  2393. return val;
  2394. },
  2395. stopNodes: [], //nested tags will not be parsed even for errors
  2396. alwaysCreateTextNode: false,
  2397. isArray: () => false,
  2398. commentPropName: false,
  2399. unpairedTags: [],
  2400. processEntities: true,
  2401. htmlEntities: false,
  2402. ignoreDeclaration: false,
  2403. ignorePiTags: false,
  2404. transformTagName: false,
  2405. transformAttributeName: false,
  2406. updateTag: function(tagName, jPath, attrs){
  2407. return tagName
  2408. },
  2409. // skipEmptyListItem: false
  2410. };
  2411. const buildOptions = function(options) {
  2412. return Object.assign({}, defaultOptions, options);
  2413. };
  2414. exports.buildOptions = buildOptions;
  2415. exports.defaultOptions = defaultOptions;
  2416. /***/ }),
  2417. /***/ "./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js":
  2418. /*!************************************************************************!*\
  2419. !*** ./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js ***!
  2420. \************************************************************************/
  2421. /*! no static exports found */
  2422. /***/ (function(module, exports, __webpack_require__) {
  2423. "use strict";
  2424. ///@ts-check
  2425. const util = __webpack_require__(/*! ../util */ "./node_modules/fast-xml-parser/src/util.js");
  2426. const xmlNode = __webpack_require__(/*! ./xmlNode */ "./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js");
  2427. const readDocType = __webpack_require__(/*! ./DocTypeReader */ "./node_modules/fast-xml-parser/src/xmlparser/DocTypeReader.js");
  2428. const toNumber = __webpack_require__(/*! strnum */ "./node_modules/strnum/strnum.js");
  2429. // const regx =
  2430. // '<((!\\[CDATA\\[([\\s\\S]*?)(]]>))|((NAME:)?(NAME))([^>]*)>|((\\/)(NAME)\\s*>))([^<]*)'
  2431. // .replace(/NAME/g, util.nameRegexp);
  2432. //const tagsRegx = new RegExp("<(\\/?[\\w:\\-\._]+)([^>]*)>(\\s*"+cdataRegx+")*([^<]+)?","g");
  2433. //const tagsRegx = new RegExp("<(\\/?)((\\w*:)?([\\w:\\-\._]+))([^>]*)>([^<]*)("+cdataRegx+"([^<]*))*([^<]+)?","g");
  2434. class OrderedObjParser{
  2435. constructor(options){
  2436. this.options = options;
  2437. this.currentNode = null;
  2438. this.tagsNodeStack = [];
  2439. this.docTypeEntities = {};
  2440. this.lastEntities = {
  2441. "apos" : { regex: /&(apos|#39|#x27);/g, val : "'"},
  2442. "gt" : { regex: /&(gt|#62|#x3E);/g, val : ">"},
  2443. "lt" : { regex: /&(lt|#60|#x3C);/g, val : "<"},
  2444. "quot" : { regex: /&(quot|#34|#x22);/g, val : "\""},
  2445. };
  2446. this.ampEntity = { regex: /&(amp|#38|#x26);/g, val : "&"};
  2447. this.htmlEntities = {
  2448. "space": { regex: /&(nbsp|#160);/g, val: " " },
  2449. // "lt" : { regex: /&(lt|#60);/g, val: "<" },
  2450. // "gt" : { regex: /&(gt|#62);/g, val: ">" },
  2451. // "amp" : { regex: /&(amp|#38);/g, val: "&" },
  2452. // "quot" : { regex: /&(quot|#34);/g, val: "\"" },
  2453. // "apos" : { regex: /&(apos|#39);/g, val: "'" },
  2454. "cent" : { regex: /&(cent|#162);/g, val: "¢" },
  2455. "pound" : { regex: /&(pound|#163);/g, val: "£" },
  2456. "yen" : { regex: /&(yen|#165);/g, val: "¥" },
  2457. "euro" : { regex: /&(euro|#8364);/g, val: "€" },
  2458. "copyright" : { regex: /&(copy|#169);/g, val: "©" },
  2459. "reg" : { regex: /&(reg|#174);/g, val: "®" },
  2460. "inr" : { regex: /&(inr|#8377);/g, val: "₹" },
  2461. "num_dec": { regex: /&#([0-9]{1,7});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 10)) },
  2462. "num_hex": { regex: /&#x([0-9a-fA-F]{1,6});/g, val : (_, str) => String.fromCharCode(Number.parseInt(str, 16)) },
  2463. };
  2464. this.addExternalEntities = addExternalEntities;
  2465. this.parseXml = parseXml;
  2466. this.parseTextData = parseTextData;
  2467. this.resolveNameSpace = resolveNameSpace;
  2468. this.buildAttributesMap = buildAttributesMap;
  2469. this.isItStopNode = isItStopNode;
  2470. this.replaceEntitiesValue = replaceEntitiesValue;
  2471. this.readStopNodeData = readStopNodeData;
  2472. this.saveTextToParentTag = saveTextToParentTag;
  2473. this.addChild = addChild;
  2474. }
  2475. }
  2476. function addExternalEntities(externalEntities){
  2477. const entKeys = Object.keys(externalEntities);
  2478. for (let i = 0; i < entKeys.length; i++) {
  2479. const ent = entKeys[i];
  2480. this.lastEntities[ent] = {
  2481. regex: new RegExp("&"+ent+";","g"),
  2482. val : externalEntities[ent]
  2483. }
  2484. }
  2485. }
  2486. /**
  2487. * @param {string} val
  2488. * @param {string} tagName
  2489. * @param {string} jPath
  2490. * @param {boolean} dontTrim
  2491. * @param {boolean} hasAttributes
  2492. * @param {boolean} isLeafNode
  2493. * @param {boolean} escapeEntities
  2494. */
  2495. function parseTextData(val, tagName, jPath, dontTrim, hasAttributes, isLeafNode, escapeEntities) {
  2496. if (val !== undefined) {
  2497. if (this.options.trimValues && !dontTrim) {
  2498. val = val.trim();
  2499. }
  2500. if(val.length > 0){
  2501. if(!escapeEntities) val = this.replaceEntitiesValue(val);
  2502. const newval = this.options.tagValueProcessor(tagName, val, jPath, hasAttributes, isLeafNode);
  2503. if(newval === null || newval === undefined){
  2504. //don't parse
  2505. return val;
  2506. }else if(typeof newval !== typeof val || newval !== val){
  2507. //overwrite
  2508. return newval;
  2509. }else if(this.options.trimValues){
  2510. return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
  2511. }else{
  2512. const trimmedVal = val.trim();
  2513. if(trimmedVal === val){
  2514. return parseValue(val, this.options.parseTagValue, this.options.numberParseOptions);
  2515. }else{
  2516. return val;
  2517. }
  2518. }
  2519. }
  2520. }
  2521. }
  2522. function resolveNameSpace(tagname) {
  2523. if (this.options.removeNSPrefix) {
  2524. const tags = tagname.split(':');
  2525. const prefix = tagname.charAt(0) === '/' ? '/' : '';
  2526. if (tags[0] === 'xmlns') {
  2527. return '';
  2528. }
  2529. if (tags.length === 2) {
  2530. tagname = prefix + tags[1];
  2531. }
  2532. }
  2533. return tagname;
  2534. }
  2535. //TODO: change regex to capture NS
  2536. //const attrsRegx = new RegExp("([\\w\\-\\.\\:]+)\\s*=\\s*(['\"])((.|\n)*?)\\2","gm");
  2537. const attrsRegx = new RegExp('([^\\s=]+)\\s*(=\\s*([\'"])([\\s\\S]*?)\\3)?', 'gm');
  2538. function buildAttributesMap(attrStr, jPath, tagName) {
  2539. if (!this.options.ignoreAttributes && typeof attrStr === 'string') {
  2540. // attrStr = attrStr.replace(/\r?\n/g, ' ');
  2541. //attrStr = attrStr || attrStr.trim();
  2542. const matches = util.getAllMatches(attrStr, attrsRegx);
  2543. const len = matches.length; //don't make it inline
  2544. const attrs = {};
  2545. for (let i = 0; i < len; i++) {
  2546. const attrName = this.resolveNameSpace(matches[i][1]);
  2547. let oldVal = matches[i][4];
  2548. let aName = this.options.attributeNamePrefix + attrName;
  2549. if (attrName.length) {
  2550. if (this.options.transformAttributeName) {
  2551. aName = this.options.transformAttributeName(aName);
  2552. }
  2553. if(aName === "__proto__") aName = "#__proto__";
  2554. if (oldVal !== undefined) {
  2555. if (this.options.trimValues) {
  2556. oldVal = oldVal.trim();
  2557. }
  2558. oldVal = this.replaceEntitiesValue(oldVal);
  2559. const newVal = this.options.attributeValueProcessor(attrName, oldVal, jPath);
  2560. if(newVal === null || newVal === undefined){
  2561. //don't parse
  2562. attrs[aName] = oldVal;
  2563. }else if(typeof newVal !== typeof oldVal || newVal !== oldVal){
  2564. //overwrite
  2565. attrs[aName] = newVal;
  2566. }else{
  2567. //parse
  2568. attrs[aName] = parseValue(
  2569. oldVal,
  2570. this.options.parseAttributeValue,
  2571. this.options.numberParseOptions
  2572. );
  2573. }
  2574. } else if (this.options.allowBooleanAttributes) {
  2575. attrs[aName] = true;
  2576. }
  2577. }
  2578. }
  2579. if (!Object.keys(attrs).length) {
  2580. return;
  2581. }
  2582. if (this.options.attributesGroupName) {
  2583. const attrCollection = {};
  2584. attrCollection[this.options.attributesGroupName] = attrs;
  2585. return attrCollection;
  2586. }
  2587. return attrs
  2588. }
  2589. }
  2590. const parseXml = function(xmlData) {
  2591. xmlData = xmlData.replace(/\r\n?/g, "\n"); //TODO: remove this line
  2592. const xmlObj = new xmlNode('!xml');
  2593. let currentNode = xmlObj;
  2594. let textData = "";
  2595. let jPath = "";
  2596. for(let i=0; i< xmlData.length; i++){//for each char in XML data
  2597. const ch = xmlData[i];
  2598. if(ch === '<'){
  2599. // const nextIndex = i+1;
  2600. // const _2ndChar = xmlData[nextIndex];
  2601. if( xmlData[i+1] === '/') {//Closing Tag
  2602. const closeIndex = findClosingIndex(xmlData, ">", i, "Closing Tag is not closed.")
  2603. let tagName = xmlData.substring(i+2,closeIndex).trim();
  2604. if(this.options.removeNSPrefix){
  2605. const colonIndex = tagName.indexOf(":");
  2606. if(colonIndex !== -1){
  2607. tagName = tagName.substr(colonIndex+1);
  2608. }
  2609. }
  2610. if(this.options.transformTagName) {
  2611. tagName = this.options.transformTagName(tagName);
  2612. }
  2613. if(currentNode){
  2614. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  2615. }
  2616. //check if last tag of nested tag was unpaired tag
  2617. const lastTagName = jPath.substring(jPath.lastIndexOf(".")+1);
  2618. if(tagName && this.options.unpairedTags.indexOf(tagName) !== -1 ){
  2619. throw new Error(`Unpaired tag can not be used as closing tag: </${tagName}>`);
  2620. }
  2621. let propIndex = 0
  2622. if(lastTagName && this.options.unpairedTags.indexOf(lastTagName) !== -1 ){
  2623. propIndex = jPath.lastIndexOf('.', jPath.lastIndexOf('.')-1)
  2624. this.tagsNodeStack.pop();
  2625. }else{
  2626. propIndex = jPath.lastIndexOf(".");
  2627. }
  2628. jPath = jPath.substring(0, propIndex);
  2629. currentNode = this.tagsNodeStack.pop();//avoid recursion, set the parent tag scope
  2630. textData = "";
  2631. i = closeIndex;
  2632. } else if( xmlData[i+1] === '?') {
  2633. let tagData = readTagExp(xmlData,i, false, "?>");
  2634. if(!tagData) throw new Error("Pi Tag is not closed.");
  2635. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  2636. if( (this.options.ignoreDeclaration && tagData.tagName === "?xml") || this.options.ignorePiTags){
  2637. }else{
  2638. const childNode = new xmlNode(tagData.tagName);
  2639. childNode.add(this.options.textNodeName, "");
  2640. if(tagData.tagName !== tagData.tagExp && tagData.attrExpPresent){
  2641. childNode[":@"] = this.buildAttributesMap(tagData.tagExp, jPath, tagData.tagName);
  2642. }
  2643. this.addChild(currentNode, childNode, jPath)
  2644. }
  2645. i = tagData.closeIndex + 1;
  2646. } else if(xmlData.substr(i + 1, 3) === '!--') {
  2647. const endIndex = findClosingIndex(xmlData, "-->", i+4, "Comment is not closed.")
  2648. if(this.options.commentPropName){
  2649. const comment = xmlData.substring(i + 4, endIndex - 2);
  2650. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  2651. currentNode.add(this.options.commentPropName, [ { [this.options.textNodeName] : comment } ]);
  2652. }
  2653. i = endIndex;
  2654. } else if( xmlData.substr(i + 1, 2) === '!D') {
  2655. const result = readDocType(xmlData, i);
  2656. this.docTypeEntities = result.entities;
  2657. i = result.i;
  2658. }else if(xmlData.substr(i + 1, 2) === '![') {
  2659. const closeIndex = findClosingIndex(xmlData, "]]>", i, "CDATA is not closed.") - 2;
  2660. const tagExp = xmlData.substring(i + 9,closeIndex);
  2661. textData = this.saveTextToParentTag(textData, currentNode, jPath);
  2662. let val = this.parseTextData(tagExp, currentNode.tagname, jPath, true, false, true, true);
  2663. if(val == undefined) val = "";
  2664. //cdata should be set even if it is 0 length string
  2665. if(this.options.cdataPropName){
  2666. currentNode.add(this.options.cdataPropName, [ { [this.options.textNodeName] : tagExp } ]);
  2667. }else{
  2668. currentNode.add(this.options.textNodeName, val);
  2669. }
  2670. i = closeIndex + 2;
  2671. }else {//Opening tag
  2672. let result = readTagExp(xmlData,i, this.options.removeNSPrefix);
  2673. let tagName= result.tagName;
  2674. const rawTagName = result.rawTagName;
  2675. let tagExp = result.tagExp;
  2676. let attrExpPresent = result.attrExpPresent;
  2677. let closeIndex = result.closeIndex;
  2678. if (this.options.transformTagName) {
  2679. tagName = this.options.transformTagName(tagName);
  2680. }
  2681. //save text as child node
  2682. if (currentNode && textData) {
  2683. if(currentNode.tagname !== '!xml'){
  2684. //when nested tag is found
  2685. textData = this.saveTextToParentTag(textData, currentNode, jPath, false);
  2686. }
  2687. }
  2688. //check if last tag was unpaired tag
  2689. const lastTag = currentNode;
  2690. if(lastTag && this.options.unpairedTags.indexOf(lastTag.tagname) !== -1 ){
  2691. currentNode = this.tagsNodeStack.pop();
  2692. jPath = jPath.substring(0, jPath.lastIndexOf("."));
  2693. }
  2694. if(tagName !== xmlObj.tagname){
  2695. jPath += jPath ? "." + tagName : tagName;
  2696. }
  2697. if (this.isItStopNode(this.options.stopNodes, jPath, tagName)) {
  2698. let tagContent = "";
  2699. //self-closing tag
  2700. if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
  2701. if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
  2702. tagName = tagName.substr(0, tagName.length - 1);
  2703. jPath = jPath.substr(0, jPath.length - 1);
  2704. tagExp = tagName;
  2705. }else{
  2706. tagExp = tagExp.substr(0, tagExp.length - 1);
  2707. }
  2708. i = result.closeIndex;
  2709. }
  2710. //unpaired tag
  2711. else if(this.options.unpairedTags.indexOf(tagName) !== -1){
  2712. i = result.closeIndex;
  2713. }
  2714. //normal tag
  2715. else{
  2716. //read until closing tag is found
  2717. const result = this.readStopNodeData(xmlData, rawTagName, closeIndex + 1);
  2718. if(!result) throw new Error(`Unexpected end of ${rawTagName}`);
  2719. i = result.i;
  2720. tagContent = result.tagContent;
  2721. }
  2722. const childNode = new xmlNode(tagName);
  2723. if(tagName !== tagExp && attrExpPresent){
  2724. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  2725. }
  2726. if(tagContent) {
  2727. tagContent = this.parseTextData(tagContent, tagName, jPath, true, attrExpPresent, true, true);
  2728. }
  2729. jPath = jPath.substr(0, jPath.lastIndexOf("."));
  2730. childNode.add(this.options.textNodeName, tagContent);
  2731. this.addChild(currentNode, childNode, jPath)
  2732. }else{
  2733. //selfClosing tag
  2734. if(tagExp.length > 0 && tagExp.lastIndexOf("/") === tagExp.length - 1){
  2735. if(tagName[tagName.length - 1] === "/"){ //remove trailing '/'
  2736. tagName = tagName.substr(0, tagName.length - 1);
  2737. jPath = jPath.substr(0, jPath.length - 1);
  2738. tagExp = tagName;
  2739. }else{
  2740. tagExp = tagExp.substr(0, tagExp.length - 1);
  2741. }
  2742. if(this.options.transformTagName) {
  2743. tagName = this.options.transformTagName(tagName);
  2744. }
  2745. const childNode = new xmlNode(tagName);
  2746. if(tagName !== tagExp && attrExpPresent){
  2747. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  2748. }
  2749. this.addChild(currentNode, childNode, jPath)
  2750. jPath = jPath.substr(0, jPath.lastIndexOf("."));
  2751. }
  2752. //opening tag
  2753. else{
  2754. const childNode = new xmlNode( tagName);
  2755. this.tagsNodeStack.push(currentNode);
  2756. if(tagName !== tagExp && attrExpPresent){
  2757. childNode[":@"] = this.buildAttributesMap(tagExp, jPath, tagName);
  2758. }
  2759. this.addChild(currentNode, childNode, jPath)
  2760. currentNode = childNode;
  2761. }
  2762. textData = "";
  2763. i = closeIndex;
  2764. }
  2765. }
  2766. }else{
  2767. textData += xmlData[i];
  2768. }
  2769. }
  2770. return xmlObj.child;
  2771. }
  2772. function addChild(currentNode, childNode, jPath){
  2773. const result = this.options.updateTag(childNode.tagname, jPath, childNode[":@"])
  2774. if(result === false){
  2775. }else if(typeof result === "string"){
  2776. childNode.tagname = result
  2777. currentNode.addChild(childNode);
  2778. }else{
  2779. currentNode.addChild(childNode);
  2780. }
  2781. }
  2782. const replaceEntitiesValue = function(val){
  2783. if(this.options.processEntities){
  2784. for(let entityName in this.docTypeEntities){
  2785. const entity = this.docTypeEntities[entityName];
  2786. val = val.replace( entity.regx, entity.val);
  2787. }
  2788. for(let entityName in this.lastEntities){
  2789. const entity = this.lastEntities[entityName];
  2790. val = val.replace( entity.regex, entity.val);
  2791. }
  2792. if(this.options.htmlEntities){
  2793. for(let entityName in this.htmlEntities){
  2794. const entity = this.htmlEntities[entityName];
  2795. val = val.replace( entity.regex, entity.val);
  2796. }
  2797. }
  2798. val = val.replace( this.ampEntity.regex, this.ampEntity.val);
  2799. }
  2800. return val;
  2801. }
  2802. function saveTextToParentTag(textData, currentNode, jPath, isLeafNode) {
  2803. if (textData) { //store previously collected data as textNode
  2804. if(isLeafNode === undefined) isLeafNode = Object.keys(currentNode.child).length === 0
  2805. textData = this.parseTextData(textData,
  2806. currentNode.tagname,
  2807. jPath,
  2808. false,
  2809. currentNode[":@"] ? Object.keys(currentNode[":@"]).length !== 0 : false,
  2810. isLeafNode);
  2811. if (textData !== undefined && textData !== "")
  2812. currentNode.add(this.options.textNodeName, textData);
  2813. textData = "";
  2814. }
  2815. return textData;
  2816. }
  2817. //TODO: use jPath to simplify the logic
  2818. /**
  2819. *
  2820. * @param {string[]} stopNodes
  2821. * @param {string} jPath
  2822. * @param {string} currentTagName
  2823. */
  2824. function isItStopNode(stopNodes, jPath, currentTagName){
  2825. const allNodesExp = "*." + currentTagName;
  2826. for (const stopNodePath in stopNodes) {
  2827. const stopNodeExp = stopNodes[stopNodePath];
  2828. if( allNodesExp === stopNodeExp || jPath === stopNodeExp ) return true;
  2829. }
  2830. return false;
  2831. }
  2832. /**
  2833. * Returns the tag Expression and where it is ending handling single-double quotes situation
  2834. * @param {string} xmlData
  2835. * @param {number} i starting index
  2836. * @returns
  2837. */
  2838. function tagExpWithClosingIndex(xmlData, i, closingChar = ">"){
  2839. let attrBoundary;
  2840. let tagExp = "";
  2841. for (let index = i; index < xmlData.length; index++) {
  2842. let ch = xmlData[index];
  2843. if (attrBoundary) {
  2844. if (ch === attrBoundary) attrBoundary = "";//reset
  2845. } else if (ch === '"' || ch === "'") {
  2846. attrBoundary = ch;
  2847. } else if (ch === closingChar[0]) {
  2848. if(closingChar[1]){
  2849. if(xmlData[index + 1] === closingChar[1]){
  2850. return {
  2851. data: tagExp,
  2852. index: index
  2853. }
  2854. }
  2855. }else{
  2856. return {
  2857. data: tagExp,
  2858. index: index
  2859. }
  2860. }
  2861. } else if (ch === '\t') {
  2862. ch = " "
  2863. }
  2864. tagExp += ch;
  2865. }
  2866. }
  2867. function findClosingIndex(xmlData, str, i, errMsg){
  2868. const closingIndex = xmlData.indexOf(str, i);
  2869. if(closingIndex === -1){
  2870. throw new Error(errMsg)
  2871. }else{
  2872. return closingIndex + str.length - 1;
  2873. }
  2874. }
  2875. function readTagExp(xmlData,i, removeNSPrefix, closingChar = ">"){
  2876. const result = tagExpWithClosingIndex(xmlData, i+1, closingChar);
  2877. if(!result) return;
  2878. let tagExp = result.data;
  2879. const closeIndex = result.index;
  2880. const separatorIndex = tagExp.search(/\s/);
  2881. let tagName = tagExp;
  2882. let attrExpPresent = true;
  2883. if(separatorIndex !== -1){//separate tag name and attributes expression
  2884. tagName = tagExp.substring(0, separatorIndex);
  2885. tagExp = tagExp.substring(separatorIndex + 1).trimStart();
  2886. }
  2887. const rawTagName = tagName;
  2888. if(removeNSPrefix){
  2889. const colonIndex = tagName.indexOf(":");
  2890. if(colonIndex !== -1){
  2891. tagName = tagName.substr(colonIndex+1);
  2892. attrExpPresent = tagName !== result.data.substr(colonIndex + 1);
  2893. }
  2894. }
  2895. return {
  2896. tagName: tagName,
  2897. tagExp: tagExp,
  2898. closeIndex: closeIndex,
  2899. attrExpPresent: attrExpPresent,
  2900. rawTagName: rawTagName,
  2901. }
  2902. }
  2903. /**
  2904. * find paired tag for a stop node
  2905. * @param {string} xmlData
  2906. * @param {string} tagName
  2907. * @param {number} i
  2908. */
  2909. function readStopNodeData(xmlData, tagName, i){
  2910. const startIndex = i;
  2911. // Starting at 1 since we already have an open tag
  2912. let openTagCount = 1;
  2913. for (; i < xmlData.length; i++) {
  2914. if( xmlData[i] === "<"){
  2915. if (xmlData[i+1] === "/") {//close tag
  2916. const closeIndex = findClosingIndex(xmlData, ">", i, `${tagName} is not closed`);
  2917. let closeTagName = xmlData.substring(i+2,closeIndex).trim();
  2918. if(closeTagName === tagName){
  2919. openTagCount--;
  2920. if (openTagCount === 0) {
  2921. return {
  2922. tagContent: xmlData.substring(startIndex, i),
  2923. i : closeIndex
  2924. }
  2925. }
  2926. }
  2927. i=closeIndex;
  2928. } else if(xmlData[i+1] === '?') {
  2929. const closeIndex = findClosingIndex(xmlData, "?>", i+1, "StopNode is not closed.")
  2930. i=closeIndex;
  2931. } else if(xmlData.substr(i + 1, 3) === '!--') {
  2932. const closeIndex = findClosingIndex(xmlData, "-->", i+3, "StopNode is not closed.")
  2933. i=closeIndex;
  2934. } else if(xmlData.substr(i + 1, 2) === '![') {
  2935. const closeIndex = findClosingIndex(xmlData, "]]>", i, "StopNode is not closed.") - 2;
  2936. i=closeIndex;
  2937. } else {
  2938. const tagData = readTagExp(xmlData, i, '>')
  2939. if (tagData) {
  2940. const openTagName = tagData && tagData.tagName;
  2941. if (openTagName === tagName && tagData.tagExp[tagData.tagExp.length-1] !== "/") {
  2942. openTagCount++;
  2943. }
  2944. i=tagData.closeIndex;
  2945. }
  2946. }
  2947. }
  2948. }//end for loop
  2949. }
  2950. function parseValue(val, shouldParse, options) {
  2951. if (shouldParse && typeof val === 'string') {
  2952. //console.log(options)
  2953. const newval = val.trim();
  2954. if(newval === 'true' ) return true;
  2955. else if(newval === 'false' ) return false;
  2956. else return toNumber(val, options);
  2957. } else {
  2958. if (util.isExist(val)) {
  2959. return val;
  2960. } else {
  2961. return '';
  2962. }
  2963. }
  2964. }
  2965. module.exports = OrderedObjParser;
  2966. /***/ }),
  2967. /***/ "./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js":
  2968. /*!*****************************************************************!*\
  2969. !*** ./node_modules/fast-xml-parser/src/xmlparser/XMLParser.js ***!
  2970. \*****************************************************************/
  2971. /*! no static exports found */
  2972. /***/ (function(module, exports, __webpack_require__) {
  2973. const { buildOptions} = __webpack_require__(/*! ./OptionsBuilder */ "./node_modules/fast-xml-parser/src/xmlparser/OptionsBuilder.js");
  2974. const OrderedObjParser = __webpack_require__(/*! ./OrderedObjParser */ "./node_modules/fast-xml-parser/src/xmlparser/OrderedObjParser.js");
  2975. const { prettify} = __webpack_require__(/*! ./node2json */ "./node_modules/fast-xml-parser/src/xmlparser/node2json.js");
  2976. const validator = __webpack_require__(/*! ../validator */ "./node_modules/fast-xml-parser/src/validator.js");
  2977. class XMLParser{
  2978. constructor(options){
  2979. this.externalEntities = {};
  2980. this.options = buildOptions(options);
  2981. }
  2982. /**
  2983. * Parse XML dats to JS object
  2984. * @param {string|Buffer} xmlData
  2985. * @param {boolean|Object} validationOption
  2986. */
  2987. parse(xmlData,validationOption){
  2988. if(typeof xmlData === "string"){
  2989. }else if( xmlData.toString){
  2990. xmlData = xmlData.toString();
  2991. }else{
  2992. throw new Error("XML data is accepted in String or Bytes[] form.")
  2993. }
  2994. if( validationOption){
  2995. if(validationOption === true) validationOption = {}; //validate with default options
  2996. const result = validator.validate(xmlData, validationOption);
  2997. if (result !== true) {
  2998. throw Error( `${result.err.msg}:${result.err.line}:${result.err.col}` )
  2999. }
  3000. }
  3001. const orderedObjParser = new OrderedObjParser(this.options);
  3002. orderedObjParser.addExternalEntities(this.externalEntities);
  3003. const orderedResult = orderedObjParser.parseXml(xmlData);
  3004. if(this.options.preserveOrder || orderedResult === undefined) return orderedResult;
  3005. else return prettify(orderedResult, this.options);
  3006. }
  3007. /**
  3008. * Add Entity which is not by default supported by this library
  3009. * @param {string} key
  3010. * @param {string} value
  3011. */
  3012. addEntity(key, value){
  3013. if(value.indexOf("&") !== -1){
  3014. throw new Error("Entity value can't have '&'")
  3015. }else if(key.indexOf("&") !== -1 || key.indexOf(";") !== -1){
  3016. throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'")
  3017. }else if(value === "&"){
  3018. throw new Error("An entity with value '&' is not permitted");
  3019. }else{
  3020. this.externalEntities[key] = value;
  3021. }
  3022. }
  3023. }
  3024. module.exports = XMLParser;
  3025. /***/ }),
  3026. /***/ "./node_modules/fast-xml-parser/src/xmlparser/node2json.js":
  3027. /*!*****************************************************************!*\
  3028. !*** ./node_modules/fast-xml-parser/src/xmlparser/node2json.js ***!
  3029. \*****************************************************************/
  3030. /*! no static exports found */
  3031. /***/ (function(module, exports, __webpack_require__) {
  3032. "use strict";
  3033. /**
  3034. *
  3035. * @param {array} node
  3036. * @param {any} options
  3037. * @returns
  3038. */
  3039. function prettify(node, options){
  3040. return compress( node, options);
  3041. }
  3042. /**
  3043. *
  3044. * @param {array} arr
  3045. * @param {object} options
  3046. * @param {string} jPath
  3047. * @returns object
  3048. */
  3049. function compress(arr, options, jPath){
  3050. let text;
  3051. const compressedObj = {};
  3052. for (let i = 0; i < arr.length; i++) {
  3053. const tagObj = arr[i];
  3054. const property = propName(tagObj);
  3055. let newJpath = "";
  3056. if(jPath === undefined) newJpath = property;
  3057. else newJpath = jPath + "." + property;
  3058. if(property === options.textNodeName){
  3059. if(text === undefined) text = tagObj[property];
  3060. else text += "" + tagObj[property];
  3061. }else if(property === undefined){
  3062. continue;
  3063. }else if(tagObj[property]){
  3064. let val = compress(tagObj[property], options, newJpath);
  3065. const isLeaf = isLeafTag(val, options);
  3066. if(tagObj[":@"]){
  3067. assignAttributes( val, tagObj[":@"], newJpath, options);
  3068. }else if(Object.keys(val).length === 1 && val[options.textNodeName] !== undefined && !options.alwaysCreateTextNode){
  3069. val = val[options.textNodeName];
  3070. }else if(Object.keys(val).length === 0){
  3071. if(options.alwaysCreateTextNode) val[options.textNodeName] = "";
  3072. else val = "";
  3073. }
  3074. if(compressedObj[property] !== undefined && compressedObj.hasOwnProperty(property)) {
  3075. if(!Array.isArray(compressedObj[property])) {
  3076. compressedObj[property] = [ compressedObj[property] ];
  3077. }
  3078. compressedObj[property].push(val);
  3079. }else{
  3080. //TODO: if a node is not an array, then check if it should be an array
  3081. //also determine if it is a leaf node
  3082. if (options.isArray(property, newJpath, isLeaf )) {
  3083. compressedObj[property] = [val];
  3084. }else{
  3085. compressedObj[property] = val;
  3086. }
  3087. }
  3088. }
  3089. }
  3090. // if(text && text.length > 0) compressedObj[options.textNodeName] = text;
  3091. if(typeof text === "string"){
  3092. if(text.length > 0) compressedObj[options.textNodeName] = text;
  3093. }else if(text !== undefined) compressedObj[options.textNodeName] = text;
  3094. return compressedObj;
  3095. }
  3096. function propName(obj){
  3097. const keys = Object.keys(obj);
  3098. for (let i = 0; i < keys.length; i++) {
  3099. const key = keys[i];
  3100. if(key !== ":@") return key;
  3101. }
  3102. }
  3103. function assignAttributes(obj, attrMap, jpath, options){
  3104. if (attrMap) {
  3105. const keys = Object.keys(attrMap);
  3106. const len = keys.length; //don't make it inline
  3107. for (let i = 0; i < len; i++) {
  3108. const atrrName = keys[i];
  3109. if (options.isArray(atrrName, jpath + "." + atrrName, true, true)) {
  3110. obj[atrrName] = [ attrMap[atrrName] ];
  3111. } else {
  3112. obj[atrrName] = attrMap[atrrName];
  3113. }
  3114. }
  3115. }
  3116. }
  3117. function isLeafTag(obj, options){
  3118. const { textNodeName } = options;
  3119. const propCount = Object.keys(obj).length;
  3120. if (propCount === 0) {
  3121. return true;
  3122. }
  3123. if (
  3124. propCount === 1 &&
  3125. (obj[textNodeName] || typeof obj[textNodeName] === "boolean" || obj[textNodeName] === 0)
  3126. ) {
  3127. return true;
  3128. }
  3129. return false;
  3130. }
  3131. exports.prettify = prettify;
  3132. /***/ }),
  3133. /***/ "./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js":
  3134. /*!***************************************************************!*\
  3135. !*** ./node_modules/fast-xml-parser/src/xmlparser/xmlNode.js ***!
  3136. \***************************************************************/
  3137. /*! no static exports found */
  3138. /***/ (function(module, exports, __webpack_require__) {
  3139. "use strict";
  3140. class XmlNode{
  3141. constructor(tagname) {
  3142. this.tagname = tagname;
  3143. this.child = []; //nested tags, text, cdata, comments in order
  3144. this[":@"] = {}; //attributes map
  3145. }
  3146. add(key,val){
  3147. // this.child.push( {name : key, val: val, isCdata: isCdata });
  3148. if(key === "__proto__") key = "#__proto__";
  3149. this.child.push( {[key]: val });
  3150. }
  3151. addChild(node) {
  3152. if(node.tagname === "__proto__") node.tagname = "#__proto__";
  3153. if(node[":@"] && Object.keys(node[":@"]).length > 0){
  3154. this.child.push( { [node.tagname]: node.child, [":@"]: node[":@"] });
  3155. }else{
  3156. this.child.push( { [node.tagname]: node.child });
  3157. }
  3158. };
  3159. };
  3160. module.exports = XmlNode;
  3161. /***/ }),
  3162. /***/ "./node_modules/mime/Mime.js":
  3163. /*!***********************************!*\
  3164. !*** ./node_modules/mime/Mime.js ***!
  3165. \***********************************/
  3166. /*! no static exports found */
  3167. /***/ (function(module, exports, __webpack_require__) {
  3168. "use strict";
  3169. /**
  3170. * @param typeMap [Object] Map of MIME type -> Array[extensions]
  3171. * @param ...
  3172. */
  3173. function Mime() {
  3174. this._types = Object.create(null);
  3175. this._extensions = Object.create(null);
  3176. for (let i = 0; i < arguments.length; i++) {
  3177. this.define(arguments[i]);
  3178. }
  3179. this.define = this.define.bind(this);
  3180. this.getType = this.getType.bind(this);
  3181. this.getExtension = this.getExtension.bind(this);
  3182. }
  3183. /**
  3184. * Define mimetype -> extension mappings. Each key is a mime-type that maps
  3185. * to an array of extensions associated with the type. The first extension is
  3186. * used as the default extension for the type.
  3187. *
  3188. * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
  3189. *
  3190. * If a type declares an extension that has already been defined, an error will
  3191. * be thrown. To suppress this error and force the extension to be associated
  3192. * with the new type, pass `force`=true. Alternatively, you may prefix the
  3193. * extension with "*" to map the type to extension, without mapping the
  3194. * extension to the type.
  3195. *
  3196. * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']});
  3197. *
  3198. *
  3199. * @param map (Object) type definitions
  3200. * @param force (Boolean) if true, force overriding of existing definitions
  3201. */
  3202. Mime.prototype.define = function(typeMap, force) {
  3203. for (let type in typeMap) {
  3204. let extensions = typeMap[type].map(function(t) {
  3205. return t.toLowerCase();
  3206. });
  3207. type = type.toLowerCase();
  3208. for (let i = 0; i < extensions.length; i++) {
  3209. const ext = extensions[i];
  3210. // '*' prefix = not the preferred type for this extension. So fixup the
  3211. // extension, and skip it.
  3212. if (ext[0] === '*') {
  3213. continue;
  3214. }
  3215. if (!force && (ext in this._types)) {
  3216. throw new Error(
  3217. 'Attempt to change mapping for "' + ext +
  3218. '" extension from "' + this._types[ext] + '" to "' + type +
  3219. '". Pass `force=true` to allow this, otherwise remove "' + ext +
  3220. '" from the list of extensions for "' + type + '".'
  3221. );
  3222. }
  3223. this._types[ext] = type;
  3224. }
  3225. // Use first extension as default
  3226. if (force || !this._extensions[type]) {
  3227. const ext = extensions[0];
  3228. this._extensions[type] = (ext[0] !== '*') ? ext : ext.substr(1);
  3229. }
  3230. }
  3231. };
  3232. /**
  3233. * Lookup a mime type based on extension
  3234. */
  3235. Mime.prototype.getType = function(path) {
  3236. path = String(path);
  3237. let last = path.replace(/^.*[/\\]/, '').toLowerCase();
  3238. let ext = last.replace(/^.*\./, '').toLowerCase();
  3239. let hasPath = last.length < path.length;
  3240. let hasDot = ext.length < last.length - 1;
  3241. return (hasDot || !hasPath) && this._types[ext] || null;
  3242. };
  3243. /**
  3244. * Return file extension associated with a mime type
  3245. */
  3246. Mime.prototype.getExtension = function(type) {
  3247. type = /^\s*([^;\s]*)/.test(type) && RegExp.$1;
  3248. return type && this._extensions[type.toLowerCase()] || null;
  3249. };
  3250. module.exports = Mime;
  3251. /***/ }),
  3252. /***/ "./node_modules/mime/index.js":
  3253. /*!************************************!*\
  3254. !*** ./node_modules/mime/index.js ***!
  3255. \************************************/
  3256. /*! no static exports found */
  3257. /***/ (function(module, exports, __webpack_require__) {
  3258. "use strict";
  3259. let Mime = __webpack_require__(/*! ./Mime */ "./node_modules/mime/Mime.js");
  3260. module.exports = new Mime(__webpack_require__(/*! ./types/standard */ "./node_modules/mime/types/standard.js"), __webpack_require__(/*! ./types/other */ "./node_modules/mime/types/other.js"));
  3261. /***/ }),
  3262. /***/ "./node_modules/mime/types/other.js":
  3263. /*!******************************************!*\
  3264. !*** ./node_modules/mime/types/other.js ***!
  3265. \******************************************/
  3266. /*! no static exports found */
  3267. /***/ (function(module, exports) {
  3268. module.exports = {"application/prs.cww":["cww"],"application/vnd.1000minds.decision-model+xml":["1km"],"application/vnd.3gpp.pic-bw-large":["plb"],"application/vnd.3gpp.pic-bw-small":["psb"],"application/vnd.3gpp.pic-bw-var":["pvb"],"application/vnd.3gpp2.tcap":["tcap"],"application/vnd.3m.post-it-notes":["pwn"],"application/vnd.accpac.simply.aso":["aso"],"application/vnd.accpac.simply.imp":["imp"],"application/vnd.acucobol":["acu"],"application/vnd.acucorp":["atc","acutc"],"application/vnd.adobe.air-application-installer-package+zip":["air"],"application/vnd.adobe.formscentral.fcdt":["fcdt"],"application/vnd.adobe.fxp":["fxp","fxpl"],"application/vnd.adobe.xdp+xml":["xdp"],"application/vnd.adobe.xfdf":["xfdf"],"application/vnd.ahead.space":["ahead"],"application/vnd.airzip.filesecure.azf":["azf"],"application/vnd.airzip.filesecure.azs":["azs"],"application/vnd.amazon.ebook":["azw"],"application/vnd.americandynamics.acc":["acc"],"application/vnd.amiga.ami":["ami"],"application/vnd.android.package-archive":["apk"],"application/vnd.anser-web-certificate-issue-initiation":["cii"],"application/vnd.anser-web-funds-transfer-initiation":["fti"],"application/vnd.antix.game-component":["atx"],"application/vnd.apple.installer+xml":["mpkg"],"application/vnd.apple.keynote":["key"],"application/vnd.apple.mpegurl":["m3u8"],"application/vnd.apple.numbers":["numbers"],"application/vnd.apple.pages":["pages"],"application/vnd.apple.pkpass":["pkpass"],"application/vnd.aristanetworks.swi":["swi"],"application/vnd.astraea-software.iota":["iota"],"application/vnd.audiograph":["aep"],"application/vnd.balsamiq.bmml+xml":["bmml"],"application/vnd.blueice.multipass":["mpm"],"application/vnd.bmi":["bmi"],"application/vnd.businessobjects":["rep"],"application/vnd.chemdraw+xml":["cdxml"],"application/vnd.chipnuts.karaoke-mmd":["mmd"],"application/vnd.cinderella":["cdy"],"application/vnd.citationstyles.style+xml":["csl"],"application/vnd.claymore":["cla"],"application/vnd.cloanto.rp9":["rp9"],"application/vnd.clonk.c4group":["c4g","c4d","c4f","c4p","c4u"],"application/vnd.cluetrust.cartomobile-config":["c11amc"],"application/vnd.cluetrust.cartomobile-config-pkg":["c11amz"],"application/vnd.commonspace":["csp"],"application/vnd.contact.cmsg":["cdbcmsg"],"application/vnd.cosmocaller":["cmc"],"application/vnd.crick.clicker":["clkx"],"application/vnd.crick.clicker.keyboard":["clkk"],"application/vnd.crick.clicker.palette":["clkp"],"application/vnd.crick.clicker.template":["clkt"],"application/vnd.crick.clicker.wordbank":["clkw"],"application/vnd.criticaltools.wbs+xml":["wbs"],"application/vnd.ctc-posml":["pml"],"application/vnd.cups-ppd":["ppd"],"application/vnd.curl.car":["car"],"application/vnd.curl.pcurl":["pcurl"],"application/vnd.dart":["dart"],"application/vnd.data-vision.rdz":["rdz"],"application/vnd.dbf":["dbf"],"application/vnd.dece.data":["uvf","uvvf","uvd","uvvd"],"application/vnd.dece.ttml+xml":["uvt","uvvt"],"application/vnd.dece.unspecified":["uvx","uvvx"],"application/vnd.dece.zip":["uvz","uvvz"],"application/vnd.denovo.fcselayout-link":["fe_launch"],"application/vnd.dna":["dna"],"application/vnd.dolby.mlp":["mlp"],"application/vnd.dpgraph":["dpg"],"application/vnd.dreamfactory":["dfac"],"application/vnd.ds-keypoint":["kpxx"],"application/vnd.dvb.ait":["ait"],"application/vnd.dvb.service":["svc"],"application/vnd.dynageo":["geo"],"application/vnd.ecowin.chart":["mag"],"application/vnd.enliven":["nml"],"application/vnd.epson.esf":["esf"],"application/vnd.epson.msf":["msf"],"application/vnd.epson.quickanime":["qam"],"application/vnd.epson.salt":["slt"],"application/vnd.epson.ssf":["ssf"],"application/vnd.eszigno3+xml":["es3","et3"],"application/vnd.ezpix-album":["ez2"],"application/vnd.ezpix-package":["ez3"],"application/vnd.fdf":["fdf"],"application/vnd.fdsn.mseed":["mseed"],"application/vnd.fdsn.seed":["seed","dataless"],"application/vnd.flographit":["gph"],"application/vnd.fluxtime.clip":["ftc"],"application/vnd.framemaker":["fm","frame","maker","book"],"application/vnd.frogans.fnc":["fnc"],"application/vnd.frogans.ltf":["ltf"],"application/vnd.fsc.weblaunch":["fsc"],"application/vnd.fujitsu.oasys":["oas"],"application/vnd.fujitsu.oasys2":["oa2"],"application/vnd.fujitsu.oasys3":["oa3"],"application/vnd.fujitsu.oasysgp":["fg5"],"application/vnd.fujitsu.oasysprs":["bh2"],"application/vnd.fujixerox.ddd":["ddd"],"application/vnd.fujixerox.docuworks":["xdw"],"application/vnd.fujixerox.docuworks.binder":["xbd"],"application/vnd.fuzzysheet":["fzs"],"application/vnd.genomatix.tuxedo":["txd"],"application/vnd.geogebra.file":["ggb"],"application/vnd.geogebra.tool":["ggt"],"application/vnd.geometry-explorer":["gex","gre"],"application/vnd.geonext":["gxt"],"application/vnd.geoplan":["g2w"],"application/vnd.geospace":["g3w"],"application/vnd.gmx":["gmx"],"application/vnd.google-apps.document":["gdoc"],"application/vnd.google-apps.presentation":["gslides"],"application/vnd.google-apps.spreadsheet":["gsheet"],"application/vnd.google-earth.kml+xml":["kml"],"application/vnd.google-earth.kmz":["kmz"],"application/vnd.grafeq":["gqf","gqs"],"application/vnd.groove-account":["gac"],"application/vnd.groove-help":["ghf"],"application/vnd.groove-identity-message":["gim"],"application/vnd.groove-injector":["grv"],"application/vnd.groove-tool-message":["gtm"],"application/vnd.groove-tool-template":["tpl"],"application/vnd.groove-vcard":["vcg"],"application/vnd.hal+xml":["hal"],"application/vnd.handheld-entertainment+xml":["zmm"],"application/vnd.hbci":["hbci"],"application/vnd.hhe.lesson-player":["les"],"application/vnd.hp-hpgl":["hpgl"],"application/vnd.hp-hpid":["hpid"],"application/vnd.hp-hps":["hps"],"application/vnd.hp-jlyt":["jlt"],"application/vnd.hp-pcl":["pcl"],"application/vnd.hp-pclxl":["pclxl"],"application/vnd.hydrostatix.sof-data":["sfd-hdstx"],"application/vnd.ibm.minipay":["mpy"],"application/vnd.ibm.modcap":["afp","listafp","list3820"],"application/vnd.ibm.rights-management":["irm"],"application/vnd.ibm.secure-container":["sc"],"application/vnd.iccprofile":["icc","icm"],"application/vnd.igloader":["igl"],"application/vnd.immervision-ivp":["ivp"],"application/vnd.immervision-ivu":["ivu"],"application/vnd.insors.igm":["igm"],"application/vnd.intercon.formnet":["xpw","xpx"],"application/vnd.intergeo":["i2g"],"application/vnd.intu.qbo":["qbo"],"application/vnd.intu.qfx":["qfx"],"application/vnd.ipunplugged.rcprofile":["rcprofile"],"application/vnd.irepository.package+xml":["irp"],"application/vnd.is-xpr":["xpr"],"application/vnd.isac.fcs":["fcs"],"application/vnd.jam":["jam"],"application/vnd.jcp.javame.midlet-rms":["rms"],"application/vnd.jisp":["jisp"],"application/vnd.joost.joda-archive":["joda"],"application/vnd.kahootz":["ktz","ktr"],"application/vnd.kde.karbon":["karbon"],"application/vnd.kde.kchart":["chrt"],"application/vnd.kde.kformula":["kfo"],"application/vnd.kde.kivio":["flw"],"application/vnd.kde.kontour":["kon"],"application/vnd.kde.kpresenter":["kpr","kpt"],"application/vnd.kde.kspread":["ksp"],"application/vnd.kde.kword":["kwd","kwt"],"application/vnd.kenameaapp":["htke"],"application/vnd.kidspiration":["kia"],"application/vnd.kinar":["kne","knp"],"application/vnd.koan":["skp","skd","skt","skm"],"application/vnd.kodak-descriptor":["sse"],"application/vnd.las.las+xml":["lasxml"],"application/vnd.llamagraphics.life-balance.desktop":["lbd"],"application/vnd.llamagraphics.life-balance.exchange+xml":["lbe"],"application/vnd.lotus-1-2-3":["123"],"application/vnd.lotus-approach":["apr"],"application/vnd.lotus-freelance":["pre"],"application/vnd.lotus-notes":["nsf"],"application/vnd.lotus-organizer":["org"],"application/vnd.lotus-screencam":["scm"],"application/vnd.lotus-wordpro":["lwp"],"application/vnd.macports.portpkg":["portpkg"],"application/vnd.mapbox-vector-tile":["mvt"],"application/vnd.mcd":["mcd"],"application/vnd.medcalcdata":["mc1"],"application/vnd.mediastation.cdkey":["cdkey"],"application/vnd.mfer":["mwf"],"application/vnd.mfmp":["mfm"],"application/vnd.micrografx.flo":["flo"],"application/vnd.micrografx.igx":["igx"],"application/vnd.mif":["mif"],"application/vnd.mobius.daf":["daf"],"application/vnd.mobius.dis":["dis"],"application/vnd.mobius.mbk":["mbk"],"application/vnd.mobius.mqy":["mqy"],"application/vnd.mobius.msl":["msl"],"application/vnd.mobius.plc":["plc"],"application/vnd.mobius.txf":["txf"],"application/vnd.mophun.application":["mpn"],"application/vnd.mophun.certificate":["mpc"],"application/vnd.mozilla.xul+xml":["xul"],"application/vnd.ms-artgalry":["cil"],"application/vnd.ms-cab-compressed":["cab"],"application/vnd.ms-excel":["xls","xlm","xla","xlc","xlt","xlw"],"application/vnd.ms-excel.addin.macroenabled.12":["xlam"],"application/vnd.ms-excel.sheet.binary.macroenabled.12":["xlsb"],"application/vnd.ms-excel.sheet.macroenabled.12":["xlsm"],"application/vnd.ms-excel.template.macroenabled.12":["xltm"],"application/vnd.ms-fontobject":["eot"],"application/vnd.ms-htmlhelp":["chm"],"application/vnd.ms-ims":["ims"],"application/vnd.ms-lrm":["lrm"],"application/vnd.ms-officetheme":["thmx"],"application/vnd.ms-outlook":["msg"],"application/vnd.ms-pki.seccat":["cat"],"application/vnd.ms-pki.stl":["*stl"],"application/vnd.ms-powerpoint":["ppt","pps","pot"],"application/vnd.ms-powerpoint.addin.macroenabled.12":["ppam"],"application/vnd.ms-powerpoint.presentation.macroenabled.12":["pptm"],"application/vnd.ms-powerpoint.slide.macroenabled.12":["sldm"],"application/vnd.ms-powerpoint.slideshow.macroenabled.12":["ppsm"],"application/vnd.ms-powerpoint.template.macroenabled.12":["potm"],"application/vnd.ms-project":["mpp","mpt"],"application/vnd.ms-word.document.macroenabled.12":["docm"],"application/vnd.ms-word.template.macroenabled.12":["dotm"],"application/vnd.ms-works":["wps","wks","wcm","wdb"],"application/vnd.ms-wpl":["wpl"],"application/vnd.ms-xpsdocument":["xps"],"application/vnd.mseq":["mseq"],"application/vnd.musician":["mus"],"application/vnd.muvee.style":["msty"],"application/vnd.mynfc":["taglet"],"application/vnd.neurolanguage.nlu":["nlu"],"application/vnd.nitf":["ntf","nitf"],"application/vnd.noblenet-directory":["nnd"],"application/vnd.noblenet-sealer":["nns"],"application/vnd.noblenet-web":["nnw"],"application/vnd.nokia.n-gage.ac+xml":["*ac"],"application/vnd.nokia.n-gage.data":["ngdat"],"application/vnd.nokia.n-gage.symbian.install":["n-gage"],"application/vnd.nokia.radio-preset":["rpst"],"application/vnd.nokia.radio-presets":["rpss"],"application/vnd.novadigm.edm":["edm"],"application/vnd.novadigm.edx":["edx"],"application/vnd.novadigm.ext":["ext"],"application/vnd.oasis.opendocument.chart":["odc"],"application/vnd.oasis.opendocument.chart-template":["otc"],"application/vnd.oasis.opendocument.database":["odb"],"application/vnd.oasis.opendocument.formula":["odf"],"application/vnd.oasis.opendocument.formula-template":["odft"],"application/vnd.oasis.opendocument.graphics":["odg"],"application/vnd.oasis.opendocument.graphics-template":["otg"],"application/vnd.oasis.opendocument.image":["odi"],"application/vnd.oasis.opendocument.image-template":["oti"],"application/vnd.oasis.opendocument.presentation":["odp"],"application/vnd.oasis.opendocument.presentation-template":["otp"],"application/vnd.oasis.opendocument.spreadsheet":["ods"],"application/vnd.oasis.opendocument.spreadsheet-template":["ots"],"application/vnd.oasis.opendocument.text":["odt"],"application/vnd.oasis.opendocument.text-master":["odm"],"application/vnd.oasis.opendocument.text-template":["ott"],"application/vnd.oasis.opendocument.text-web":["oth"],"application/vnd.olpc-sugar":["xo"],"application/vnd.oma.dd2+xml":["dd2"],"application/vnd.openblox.game+xml":["obgx"],"application/vnd.openofficeorg.extension":["oxt"],"application/vnd.openstreetmap.data+xml":["osm"],"application/vnd.openxmlformats-officedocument.presentationml.presentation":["pptx"],"application/vnd.openxmlformats-officedocument.presentationml.slide":["sldx"],"application/vnd.openxmlformats-officedocument.presentationml.slideshow":["ppsx"],"application/vnd.openxmlformats-officedocument.presentationml.template":["potx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":["xlsx"],"application/vnd.openxmlformats-officedocument.spreadsheetml.template":["xltx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.document":["docx"],"application/vnd.openxmlformats-officedocument.wordprocessingml.template":["dotx"],"application/vnd.osgeo.mapguide.package":["mgp"],"application/vnd.osgi.dp":["dp"],"application/vnd.osgi.subsystem":["esa"],"application/vnd.palm":["pdb","pqa","oprc"],"application/vnd.pawaafile":["paw"],"application/vnd.pg.format":["str"],"application/vnd.pg.osasli":["ei6"],"application/vnd.picsel":["efif"],"application/vnd.pmi.widget":["wg"],"application/vnd.pocketlearn":["plf"],"application/vnd.powerbuilder6":["pbd"],"application/vnd.previewsystems.box":["box"],"application/vnd.proteus.magazine":["mgz"],"application/vnd.publishare-delta-tree":["qps"],"application/vnd.pvi.ptid1":["ptid"],"application/vnd.quark.quarkxpress":["qxd","qxt","qwd","qwt","qxl","qxb"],"application/vnd.rar":["rar"],"application/vnd.realvnc.bed":["bed"],"application/vnd.recordare.musicxml":["mxl"],"application/vnd.recordare.musicxml+xml":["musicxml"],"application/vnd.rig.cryptonote":["cryptonote"],"application/vnd.rim.cod":["cod"],"application/vnd.rn-realmedia":["rm"],"application/vnd.rn-realmedia-vbr":["rmvb"],"application/vnd.route66.link66+xml":["link66"],"application/vnd.sailingtracker.track":["st"],"application/vnd.seemail":["see"],"application/vnd.sema":["sema"],"application/vnd.semd":["semd"],"application/vnd.semf":["semf"],"application/vnd.shana.informed.formdata":["ifm"],"application/vnd.shana.informed.formtemplate":["itp"],"application/vnd.shana.informed.interchange":["iif"],"application/vnd.shana.informed.package":["ipk"],"application/vnd.simtech-mindmapper":["twd","twds"],"application/vnd.smaf":["mmf"],"application/vnd.smart.teacher":["teacher"],"application/vnd.software602.filler.form+xml":["fo"],"application/vnd.solent.sdkm+xml":["sdkm","sdkd"],"application/vnd.spotfire.dxp":["dxp"],"application/vnd.spotfire.sfs":["sfs"],"application/vnd.stardivision.calc":["sdc"],"application/vnd.stardivision.draw":["sda"],"application/vnd.stardivision.impress":["sdd"],"application/vnd.stardivision.math":["smf"],"application/vnd.stardivision.writer":["sdw","vor"],"application/vnd.stardivision.writer-global":["sgl"],"application/vnd.stepmania.package":["smzip"],"application/vnd.stepmania.stepchart":["sm"],"application/vnd.sun.wadl+xml":["wadl"],"application/vnd.sun.xml.calc":["sxc"],"application/vnd.sun.xml.calc.template":["stc"],"application/vnd.sun.xml.draw":["sxd"],"application/vnd.sun.xml.draw.template":["std"],"application/vnd.sun.xml.impress":["sxi"],"application/vnd.sun.xml.impress.template":["sti"],"application/vnd.sun.xml.math":["sxm"],"application/vnd.sun.xml.writer":["sxw"],"application/vnd.sun.xml.writer.global":["sxg"],"application/vnd.sun.xml.writer.template":["stw"],"application/vnd.sus-calendar":["sus","susp"],"application/vnd.svd":["svd"],"application/vnd.symbian.install":["sis","sisx"],"application/vnd.syncml+xml":["xsm"],"application/vnd.syncml.dm+wbxml":["bdm"],"application/vnd.syncml.dm+xml":["xdm"],"application/vnd.syncml.dmddf+xml":["ddf"],"application/vnd.tao.intent-module-archive":["tao"],"application/vnd.tcpdump.pcap":["pcap","cap","dmp"],"application/vnd.tmobile-livetv":["tmo"],"application/vnd.trid.tpt":["tpt"],"application/vnd.triscape.mxs":["mxs"],"application/vnd.trueapp":["tra"],"application/vnd.ufdl":["ufd","ufdl"],"application/vnd.uiq.theme":["utz"],"application/vnd.umajin":["umj"],"application/vnd.unity":["unityweb"],"application/vnd.uoml+xml":["uoml"],"application/vnd.vcx":["vcx"],"application/vnd.visio":["vsd","vst","vss","vsw"],"application/vnd.visionary":["vis"],"application/vnd.vsf":["vsf"],"application/vnd.wap.wbxml":["wbxml"],"application/vnd.wap.wmlc":["wmlc"],"application/vnd.wap.wmlscriptc":["wmlsc"],"application/vnd.webturbo":["wtb"],"application/vnd.wolfram.player":["nbp"],"application/vnd.wordperfect":["wpd"],"application/vnd.wqd":["wqd"],"application/vnd.wt.stf":["stf"],"application/vnd.xara":["xar"],"application/vnd.xfdl":["xfdl"],"application/vnd.yamaha.hv-dic":["hvd"],"application/vnd.yamaha.hv-script":["hvs"],"application/vnd.yamaha.hv-voice":["hvp"],"application/vnd.yamaha.openscoreformat":["osf"],"application/vnd.yamaha.openscoreformat.osfpvg+xml":["osfpvg"],"application/vnd.yamaha.smaf-audio":["saf"],"application/vnd.yamaha.smaf-phrase":["spf"],"application/vnd.yellowriver-custom-menu":["cmp"],"application/vnd.zul":["zir","zirz"],"application/vnd.zzazz.deck+xml":["zaz"],"application/x-7z-compressed":["7z"],"application/x-abiword":["abw"],"application/x-ace-compressed":["ace"],"application/x-apple-diskimage":["*dmg"],"application/x-arj":["arj"],"application/x-authorware-bin":["aab","x32","u32","vox"],"application/x-authorware-map":["aam"],"application/x-authorware-seg":["aas"],"application/x-bcpio":["bcpio"],"application/x-bdoc":["*bdoc"],"application/x-bittorrent":["torrent"],"application/x-blorb":["blb","blorb"],"application/x-bzip":["bz"],"application/x-bzip2":["bz2","boz"],"application/x-cbr":["cbr","cba","cbt","cbz","cb7"],"application/x-cdlink":["vcd"],"application/x-cfs-compressed":["cfs"],"application/x-chat":["chat"],"application/x-chess-pgn":["pgn"],"application/x-chrome-extension":["crx"],"application/x-cocoa":["cco"],"application/x-conference":["nsc"],"application/x-cpio":["cpio"],"application/x-csh":["csh"],"application/x-debian-package":["*deb","udeb"],"application/x-dgc-compressed":["dgc"],"application/x-director":["dir","dcr","dxr","cst","cct","cxt","w3d","fgd","swa"],"application/x-doom":["wad"],"application/x-dtbncx+xml":["ncx"],"application/x-dtbook+xml":["dtb"],"application/x-dtbresource+xml":["res"],"application/x-dvi":["dvi"],"application/x-envoy":["evy"],"application/x-eva":["eva"],"application/x-font-bdf":["bdf"],"application/x-font-ghostscript":["gsf"],"application/x-font-linux-psf":["psf"],"application/x-font-pcf":["pcf"],"application/x-font-snf":["snf"],"application/x-font-type1":["pfa","pfb","pfm","afm"],"application/x-freearc":["arc"],"application/x-futuresplash":["spl"],"application/x-gca-compressed":["gca"],"application/x-glulx":["ulx"],"application/x-gnumeric":["gnumeric"],"application/x-gramps-xml":["gramps"],"application/x-gtar":["gtar"],"application/x-hdf":["hdf"],"application/x-httpd-php":["php"],"application/x-install-instructions":["install"],"application/x-iso9660-image":["*iso"],"application/x-iwork-keynote-sffkey":["*key"],"application/x-iwork-numbers-sffnumbers":["*numbers"],"application/x-iwork-pages-sffpages":["*pages"],"application/x-java-archive-diff":["jardiff"],"application/x-java-jnlp-file":["jnlp"],"application/x-keepass2":["kdbx"],"application/x-latex":["latex"],"application/x-lua-bytecode":["luac"],"application/x-lzh-compressed":["lzh","lha"],"application/x-makeself":["run"],"application/x-mie":["mie"],"application/x-mobipocket-ebook":["prc","mobi"],"application/x-ms-application":["application"],"application/x-ms-shortcut":["lnk"],"application/x-ms-wmd":["wmd"],"application/x-ms-wmz":["wmz"],"application/x-ms-xbap":["xbap"],"application/x-msaccess":["mdb"],"application/x-msbinder":["obd"],"application/x-mscardfile":["crd"],"application/x-msclip":["clp"],"application/x-msdos-program":["*exe"],"application/x-msdownload":["*exe","*dll","com","bat","*msi"],"application/x-msmediaview":["mvb","m13","m14"],"application/x-msmetafile":["*wmf","*wmz","*emf","emz"],"application/x-msmoney":["mny"],"application/x-mspublisher":["pub"],"application/x-msschedule":["scd"],"application/x-msterminal":["trm"],"application/x-mswrite":["wri"],"application/x-netcdf":["nc","cdf"],"application/x-ns-proxy-autoconfig":["pac"],"application/x-nzb":["nzb"],"application/x-perl":["pl","pm"],"application/x-pilot":["*prc","*pdb"],"application/x-pkcs12":["p12","pfx"],"application/x-pkcs7-certificates":["p7b","spc"],"application/x-pkcs7-certreqresp":["p7r"],"application/x-rar-compressed":["*rar"],"application/x-redhat-package-manager":["rpm"],"application/x-research-info-systems":["ris"],"application/x-sea":["sea"],"application/x-sh":["sh"],"application/x-shar":["shar"],"application/x-shockwave-flash":["swf"],"application/x-silverlight-app":["xap"],"application/x-sql":["sql"],"application/x-stuffit":["sit"],"application/x-stuffitx":["sitx"],"application/x-subrip":["srt"],"application/x-sv4cpio":["sv4cpio"],"application/x-sv4crc":["sv4crc"],"application/x-t3vm-image":["t3"],"application/x-tads":["gam"],"application/x-tar":["tar"],"application/x-tcl":["tcl","tk"],"application/x-tex":["tex"],"application/x-tex-tfm":["tfm"],"application/x-texinfo":["texinfo","texi"],"application/x-tgif":["*obj"],"application/x-ustar":["ustar"],"application/x-virtualbox-hdd":["hdd"],"application/x-virtualbox-ova":["ova"],"application/x-virtualbox-ovf":["ovf"],"application/x-virtualbox-vbox":["vbox"],"application/x-virtualbox-vbox-extpack":["vbox-extpack"],"application/x-virtualbox-vdi":["vdi"],"application/x-virtualbox-vhd":["vhd"],"application/x-virtualbox-vmdk":["vmdk"],"application/x-wais-source":["src"],"application/x-web-app-manifest+json":["webapp"],"application/x-x509-ca-cert":["der","crt","pem"],"application/x-xfig":["fig"],"application/x-xliff+xml":["*xlf"],"application/x-xpinstall":["xpi"],"application/x-xz":["xz"],"application/x-zmachine":["z1","z2","z3","z4","z5","z6","z7","z8"],"audio/vnd.dece.audio":["uva","uvva"],"audio/vnd.digital-winds":["eol"],"audio/vnd.dra":["dra"],"audio/vnd.dts":["dts"],"audio/vnd.dts.hd":["dtshd"],"audio/vnd.lucent.voice":["lvp"],"audio/vnd.ms-playready.media.pya":["pya"],"audio/vnd.nuera.ecelp4800":["ecelp4800"],"audio/vnd.nuera.ecelp7470":["ecelp7470"],"audio/vnd.nuera.ecelp9600":["ecelp9600"],"audio/vnd.rip":["rip"],"audio/x-aac":["aac"],"audio/x-aiff":["aif","aiff","aifc"],"audio/x-caf":["caf"],"audio/x-flac":["flac"],"audio/x-m4a":["*m4a"],"audio/x-matroska":["mka"],"audio/x-mpegurl":["m3u"],"audio/x-ms-wax":["wax"],"audio/x-ms-wma":["wma"],"audio/x-pn-realaudio":["ram","ra"],"audio/x-pn-realaudio-plugin":["rmp"],"audio/x-realaudio":["*ra"],"audio/x-wav":["*wav"],"chemical/x-cdx":["cdx"],"chemical/x-cif":["cif"],"chemical/x-cmdf":["cmdf"],"chemical/x-cml":["cml"],"chemical/x-csml":["csml"],"chemical/x-xyz":["xyz"],"image/prs.btif":["btif"],"image/prs.pti":["pti"],"image/vnd.adobe.photoshop":["psd"],"image/vnd.airzip.accelerator.azv":["azv"],"image/vnd.dece.graphic":["uvi","uvvi","uvg","uvvg"],"image/vnd.djvu":["djvu","djv"],"image/vnd.dvb.subtitle":["*sub"],"image/vnd.dwg":["dwg"],"image/vnd.dxf":["dxf"],"image/vnd.fastbidsheet":["fbs"],"image/vnd.fpx":["fpx"],"image/vnd.fst":["fst"],"image/vnd.fujixerox.edmics-mmr":["mmr"],"image/vnd.fujixerox.edmics-rlc":["rlc"],"image/vnd.microsoft.icon":["ico"],"image/vnd.ms-dds":["dds"],"image/vnd.ms-modi":["mdi"],"image/vnd.ms-photo":["wdp"],"image/vnd.net-fpx":["npx"],"image/vnd.pco.b16":["b16"],"image/vnd.tencent.tap":["tap"],"image/vnd.valve.source.texture":["vtf"],"image/vnd.wap.wbmp":["wbmp"],"image/vnd.xiff":["xif"],"image/vnd.zbrush.pcx":["pcx"],"image/x-3ds":["3ds"],"image/x-cmu-raster":["ras"],"image/x-cmx":["cmx"],"image/x-freehand":["fh","fhc","fh4","fh5","fh7"],"image/x-icon":["*ico"],"image/x-jng":["jng"],"image/x-mrsid-image":["sid"],"image/x-ms-bmp":["*bmp"],"image/x-pcx":["*pcx"],"image/x-pict":["pic","pct"],"image/x-portable-anymap":["pnm"],"image/x-portable-bitmap":["pbm"],"image/x-portable-graymap":["pgm"],"image/x-portable-pixmap":["ppm"],"image/x-rgb":["rgb"],"image/x-tga":["tga"],"image/x-xbitmap":["xbm"],"image/x-xpixmap":["xpm"],"image/x-xwindowdump":["xwd"],"message/vnd.wfa.wsc":["wsc"],"model/vnd.collada+xml":["dae"],"model/vnd.dwf":["dwf"],"model/vnd.gdl":["gdl"],"model/vnd.gtw":["gtw"],"model/vnd.mts":["mts"],"model/vnd.opengex":["ogex"],"model/vnd.parasolid.transmit.binary":["x_b"],"model/vnd.parasolid.transmit.text":["x_t"],"model/vnd.sap.vds":["vds"],"model/vnd.usdz+zip":["usdz"],"model/vnd.valve.source.compiled-map":["bsp"],"model/vnd.vtu":["vtu"],"text/prs.lines.tag":["dsc"],"text/vnd.curl":["curl"],"text/vnd.curl.dcurl":["dcurl"],"text/vnd.curl.mcurl":["mcurl"],"text/vnd.curl.scurl":["scurl"],"text/vnd.dvb.subtitle":["sub"],"text/vnd.fly":["fly"],"text/vnd.fmi.flexstor":["flx"],"text/vnd.graphviz":["gv"],"text/vnd.in3d.3dml":["3dml"],"text/vnd.in3d.spot":["spot"],"text/vnd.sun.j2me.app-descriptor":["jad"],"text/vnd.wap.wml":["wml"],"text/vnd.wap.wmlscript":["wmls"],"text/x-asm":["s","asm"],"text/x-c":["c","cc","cxx","cpp","h","hh","dic"],"text/x-component":["htc"],"text/x-fortran":["f","for","f77","f90"],"text/x-handlebars-template":["hbs"],"text/x-java-source":["java"],"text/x-lua":["lua"],"text/x-markdown":["mkd"],"text/x-nfo":["nfo"],"text/x-opml":["opml"],"text/x-org":["*org"],"text/x-pascal":["p","pas"],"text/x-processing":["pde"],"text/x-sass":["sass"],"text/x-scss":["scss"],"text/x-setext":["etx"],"text/x-sfv":["sfv"],"text/x-suse-ymp":["ymp"],"text/x-uuencode":["uu"],"text/x-vcalendar":["vcs"],"text/x-vcard":["vcf"],"video/vnd.dece.hd":["uvh","uvvh"],"video/vnd.dece.mobile":["uvm","uvvm"],"video/vnd.dece.pd":["uvp","uvvp"],"video/vnd.dece.sd":["uvs","uvvs"],"video/vnd.dece.video":["uvv","uvvv"],"video/vnd.dvb.file":["dvb"],"video/vnd.fvt":["fvt"],"video/vnd.mpegurl":["mxu","m4u"],"video/vnd.ms-playready.media.pyv":["pyv"],"video/vnd.uvvu.mp4":["uvu","uvvu"],"video/vnd.vivo":["viv"],"video/x-f4v":["f4v"],"video/x-fli":["fli"],"video/x-flv":["flv"],"video/x-m4v":["m4v"],"video/x-matroska":["mkv","mk3d","mks"],"video/x-mng":["mng"],"video/x-ms-asf":["asf","asx"],"video/x-ms-vob":["vob"],"video/x-ms-wm":["wm"],"video/x-ms-wmv":["wmv"],"video/x-ms-wmx":["wmx"],"video/x-ms-wvx":["wvx"],"video/x-msvideo":["avi"],"video/x-sgi-movie":["movie"],"video/x-smv":["smv"],"x-conference/x-cooltalk":["ice"]};
  3269. /***/ }),
  3270. /***/ "./node_modules/mime/types/standard.js":
  3271. /*!*********************************************!*\
  3272. !*** ./node_modules/mime/types/standard.js ***!
  3273. \*********************************************/
  3274. /*! no static exports found */
  3275. /***/ (function(module, exports) {
  3276. module.exports = {"application/andrew-inset":["ez"],"application/applixware":["aw"],"application/atom+xml":["atom"],"application/atomcat+xml":["atomcat"],"application/atomdeleted+xml":["atomdeleted"],"application/atomsvc+xml":["atomsvc"],"application/atsc-dwd+xml":["dwd"],"application/atsc-held+xml":["held"],"application/atsc-rsat+xml":["rsat"],"application/bdoc":["bdoc"],"application/calendar+xml":["xcs"],"application/ccxml+xml":["ccxml"],"application/cdfx+xml":["cdfx"],"application/cdmi-capability":["cdmia"],"application/cdmi-container":["cdmic"],"application/cdmi-domain":["cdmid"],"application/cdmi-object":["cdmio"],"application/cdmi-queue":["cdmiq"],"application/cu-seeme":["cu"],"application/dash+xml":["mpd"],"application/davmount+xml":["davmount"],"application/docbook+xml":["dbk"],"application/dssc+der":["dssc"],"application/dssc+xml":["xdssc"],"application/ecmascript":["es","ecma"],"application/emma+xml":["emma"],"application/emotionml+xml":["emotionml"],"application/epub+zip":["epub"],"application/exi":["exi"],"application/express":["exp"],"application/fdt+xml":["fdt"],"application/font-tdpfr":["pfr"],"application/geo+json":["geojson"],"application/gml+xml":["gml"],"application/gpx+xml":["gpx"],"application/gxf":["gxf"],"application/gzip":["gz"],"application/hjson":["hjson"],"application/hyperstudio":["stk"],"application/inkml+xml":["ink","inkml"],"application/ipfix":["ipfix"],"application/its+xml":["its"],"application/java-archive":["jar","war","ear"],"application/java-serialized-object":["ser"],"application/java-vm":["class"],"application/javascript":["js","mjs"],"application/json":["json","map"],"application/json5":["json5"],"application/jsonml+json":["jsonml"],"application/ld+json":["jsonld"],"application/lgr+xml":["lgr"],"application/lost+xml":["lostxml"],"application/mac-binhex40":["hqx"],"application/mac-compactpro":["cpt"],"application/mads+xml":["mads"],"application/manifest+json":["webmanifest"],"application/marc":["mrc"],"application/marcxml+xml":["mrcx"],"application/mathematica":["ma","nb","mb"],"application/mathml+xml":["mathml"],"application/mbox":["mbox"],"application/mediaservercontrol+xml":["mscml"],"application/metalink+xml":["metalink"],"application/metalink4+xml":["meta4"],"application/mets+xml":["mets"],"application/mmt-aei+xml":["maei"],"application/mmt-usd+xml":["musd"],"application/mods+xml":["mods"],"application/mp21":["m21","mp21"],"application/mp4":["mp4s","m4p"],"application/msword":["doc","dot"],"application/mxf":["mxf"],"application/n-quads":["nq"],"application/n-triples":["nt"],"application/node":["cjs"],"application/octet-stream":["bin","dms","lrf","mar","so","dist","distz","pkg","bpk","dump","elc","deploy","exe","dll","deb","dmg","iso","img","msi","msp","msm","buffer"],"application/oda":["oda"],"application/oebps-package+xml":["opf"],"application/ogg":["ogx"],"application/omdoc+xml":["omdoc"],"application/onenote":["onetoc","onetoc2","onetmp","onepkg"],"application/oxps":["oxps"],"application/p2p-overlay+xml":["relo"],"application/patch-ops-error+xml":["xer"],"application/pdf":["pdf"],"application/pgp-encrypted":["pgp"],"application/pgp-signature":["asc","sig"],"application/pics-rules":["prf"],"application/pkcs10":["p10"],"application/pkcs7-mime":["p7m","p7c"],"application/pkcs7-signature":["p7s"],"application/pkcs8":["p8"],"application/pkix-attr-cert":["ac"],"application/pkix-cert":["cer"],"application/pkix-crl":["crl"],"application/pkix-pkipath":["pkipath"],"application/pkixcmp":["pki"],"application/pls+xml":["pls"],"application/postscript":["ai","eps","ps"],"application/provenance+xml":["provx"],"application/pskc+xml":["pskcxml"],"application/raml+yaml":["raml"],"application/rdf+xml":["rdf","owl"],"application/reginfo+xml":["rif"],"application/relax-ng-compact-syntax":["rnc"],"application/resource-lists+xml":["rl"],"application/resource-lists-diff+xml":["rld"],"application/rls-services+xml":["rs"],"application/route-apd+xml":["rapd"],"application/route-s-tsid+xml":["sls"],"application/route-usd+xml":["rusd"],"application/rpki-ghostbusters":["gbr"],"application/rpki-manifest":["mft"],"application/rpki-roa":["roa"],"application/rsd+xml":["rsd"],"application/rss+xml":["rss"],"application/rtf":["rtf"],"application/sbml+xml":["sbml"],"application/scvp-cv-request":["scq"],"application/scvp-cv-response":["scs"],"application/scvp-vp-request":["spq"],"application/scvp-vp-response":["spp"],"application/sdp":["sdp"],"application/senml+xml":["senmlx"],"application/sensml+xml":["sensmlx"],"application/set-payment-initiation":["setpay"],"application/set-registration-initiation":["setreg"],"application/shf+xml":["shf"],"application/sieve":["siv","sieve"],"application/smil+xml":["smi","smil"],"application/sparql-query":["rq"],"application/sparql-results+xml":["srx"],"application/srgs":["gram"],"application/srgs+xml":["grxml"],"application/sru+xml":["sru"],"application/ssdl+xml":["ssdl"],"application/ssml+xml":["ssml"],"application/swid+xml":["swidtag"],"application/tei+xml":["tei","teicorpus"],"application/thraud+xml":["tfi"],"application/timestamped-data":["tsd"],"application/toml":["toml"],"application/trig":["trig"],"application/ttml+xml":["ttml"],"application/ubjson":["ubj"],"application/urc-ressheet+xml":["rsheet"],"application/urc-targetdesc+xml":["td"],"application/voicexml+xml":["vxml"],"application/wasm":["wasm"],"application/widget":["wgt"],"application/winhlp":["hlp"],"application/wsdl+xml":["wsdl"],"application/wspolicy+xml":["wspolicy"],"application/xaml+xml":["xaml"],"application/xcap-att+xml":["xav"],"application/xcap-caps+xml":["xca"],"application/xcap-diff+xml":["xdf"],"application/xcap-el+xml":["xel"],"application/xcap-ns+xml":["xns"],"application/xenc+xml":["xenc"],"application/xhtml+xml":["xhtml","xht"],"application/xliff+xml":["xlf"],"application/xml":["xml","xsl","xsd","rng"],"application/xml-dtd":["dtd"],"application/xop+xml":["xop"],"application/xproc+xml":["xpl"],"application/xslt+xml":["*xsl","xslt"],"application/xspf+xml":["xspf"],"application/xv+xml":["mxml","xhvml","xvml","xvm"],"application/yang":["yang"],"application/yin+xml":["yin"],"application/zip":["zip"],"audio/3gpp":["*3gpp"],"audio/adpcm":["adp"],"audio/amr":["amr"],"audio/basic":["au","snd"],"audio/midi":["mid","midi","kar","rmi"],"audio/mobile-xmf":["mxmf"],"audio/mp3":["*mp3"],"audio/mp4":["m4a","mp4a"],"audio/mpeg":["mpga","mp2","mp2a","mp3","m2a","m3a"],"audio/ogg":["oga","ogg","spx","opus"],"audio/s3m":["s3m"],"audio/silk":["sil"],"audio/wav":["wav"],"audio/wave":["*wav"],"audio/webm":["weba"],"audio/xm":["xm"],"font/collection":["ttc"],"font/otf":["otf"],"font/ttf":["ttf"],"font/woff":["woff"],"font/woff2":["woff2"],"image/aces":["exr"],"image/apng":["apng"],"image/avif":["avif"],"image/bmp":["bmp"],"image/cgm":["cgm"],"image/dicom-rle":["drle"],"image/emf":["emf"],"image/fits":["fits"],"image/g3fax":["g3"],"image/gif":["gif"],"image/heic":["heic"],"image/heic-sequence":["heics"],"image/heif":["heif"],"image/heif-sequence":["heifs"],"image/hej2k":["hej2"],"image/hsj2":["hsj2"],"image/ief":["ief"],"image/jls":["jls"],"image/jp2":["jp2","jpg2"],"image/jpeg":["jpeg","jpg","jpe"],"image/jph":["jph"],"image/jphc":["jhc"],"image/jpm":["jpm"],"image/jpx":["jpx","jpf"],"image/jxr":["jxr"],"image/jxra":["jxra"],"image/jxrs":["jxrs"],"image/jxs":["jxs"],"image/jxsc":["jxsc"],"image/jxsi":["jxsi"],"image/jxss":["jxss"],"image/ktx":["ktx"],"image/ktx2":["ktx2"],"image/png":["png"],"image/sgi":["sgi"],"image/svg+xml":["svg","svgz"],"image/t38":["t38"],"image/tiff":["tif","tiff"],"image/tiff-fx":["tfx"],"image/webp":["webp"],"image/wmf":["wmf"],"message/disposition-notification":["disposition-notification"],"message/global":["u8msg"],"message/global-delivery-status":["u8dsn"],"message/global-disposition-notification":["u8mdn"],"message/global-headers":["u8hdr"],"message/rfc822":["eml","mime"],"model/3mf":["3mf"],"model/gltf+json":["gltf"],"model/gltf-binary":["glb"],"model/iges":["igs","iges"],"model/mesh":["msh","mesh","silo"],"model/mtl":["mtl"],"model/obj":["obj"],"model/step+xml":["stpx"],"model/step+zip":["stpz"],"model/step-xml+zip":["stpxz"],"model/stl":["stl"],"model/vrml":["wrl","vrml"],"model/x3d+binary":["*x3db","x3dbz"],"model/x3d+fastinfoset":["x3db"],"model/x3d+vrml":["*x3dv","x3dvz"],"model/x3d+xml":["x3d","x3dz"],"model/x3d-vrml":["x3dv"],"text/cache-manifest":["appcache","manifest"],"text/calendar":["ics","ifb"],"text/coffeescript":["coffee","litcoffee"],"text/css":["css"],"text/csv":["csv"],"text/html":["html","htm","shtml"],"text/jade":["jade"],"text/jsx":["jsx"],"text/less":["less"],"text/markdown":["markdown","md"],"text/mathml":["mml"],"text/mdx":["mdx"],"text/n3":["n3"],"text/plain":["txt","text","conf","def","list","log","in","ini"],"text/richtext":["rtx"],"text/rtf":["*rtf"],"text/sgml":["sgml","sgm"],"text/shex":["shex"],"text/slim":["slim","slm"],"text/spdx":["spdx"],"text/stylus":["stylus","styl"],"text/tab-separated-values":["tsv"],"text/troff":["t","tr","roff","man","me","ms"],"text/turtle":["ttl"],"text/uri-list":["uri","uris","urls"],"text/vcard":["vcard"],"text/vtt":["vtt"],"text/xml":["*xml"],"text/yaml":["yaml","yml"],"video/3gpp":["3gp","3gpp"],"video/3gpp2":["3g2"],"video/h261":["h261"],"video/h263":["h263"],"video/h264":["h264"],"video/iso.segment":["m4s"],"video/jpeg":["jpgv"],"video/jpm":["*jpm","jpgm"],"video/mj2":["mj2","mjp2"],"video/mp2t":["ts"],"video/mp4":["mp4","mp4v","mpg4"],"video/mpeg":["mpeg","mpg","mpe","m1v","m2v"],"video/ogg":["ogv"],"video/quicktime":["qt","mov"],"video/webm":["webm"]};
  3277. /***/ }),
  3278. /***/ "./node_modules/strnum/strnum.js":
  3279. /*!***************************************!*\
  3280. !*** ./node_modules/strnum/strnum.js ***!
  3281. \***************************************/
  3282. /*! no static exports found */
  3283. /***/ (function(module, exports) {
  3284. const hexRegex = /^[-+]?0x[a-fA-F0-9]+$/;
  3285. const numRegex = /^([\-\+])?(0*)(\.[0-9]+([eE]\-?[0-9]+)?|[0-9]+(\.[0-9]+([eE]\-?[0-9]+)?)?)$/;
  3286. // const octRegex = /0x[a-z0-9]+/;
  3287. // const binRegex = /0x[a-z0-9]+/;
  3288. //polyfill
  3289. if (!Number.parseInt && window.parseInt) {
  3290. Number.parseInt = window.parseInt;
  3291. }
  3292. if (!Number.parseFloat && window.parseFloat) {
  3293. Number.parseFloat = window.parseFloat;
  3294. }
  3295. const consider = {
  3296. hex : true,
  3297. leadingZeros: true,
  3298. decimalPoint: "\.",
  3299. eNotation: true
  3300. //skipLike: /regex/
  3301. };
  3302. function toNumber(str, options = {}){
  3303. // const options = Object.assign({}, consider);
  3304. // if(opt.leadingZeros === false){
  3305. // options.leadingZeros = false;
  3306. // }else if(opt.hex === false){
  3307. // options.hex = false;
  3308. // }
  3309. options = Object.assign({}, consider, options );
  3310. if(!str || typeof str !== "string" ) return str;
  3311. let trimmedStr = str.trim();
  3312. // if(trimmedStr === "0.0") return 0;
  3313. // else if(trimmedStr === "+0.0") return 0;
  3314. // else if(trimmedStr === "-0.0") return -0;
  3315. if(options.skipLike !== undefined && options.skipLike.test(trimmedStr)) return str;
  3316. else if (options.hex && hexRegex.test(trimmedStr)) {
  3317. return Number.parseInt(trimmedStr, 16);
  3318. // } else if (options.parseOct && octRegex.test(str)) {
  3319. // return Number.parseInt(val, 8);
  3320. // }else if (options.parseBin && binRegex.test(str)) {
  3321. // return Number.parseInt(val, 2);
  3322. }else{
  3323. //separate negative sign, leading zeros, and rest number
  3324. const match = numRegex.exec(trimmedStr);
  3325. if(match){
  3326. const sign = match[1];
  3327. const leadingZeros = match[2];
  3328. let numTrimmedByZeros = trimZeros(match[3]); //complete num without leading zeros
  3329. //trim ending zeros for floating number
  3330. const eNotation = match[4] || match[6];
  3331. if(!options.leadingZeros && leadingZeros.length > 0 && sign && trimmedStr[2] !== ".") return str; //-0123
  3332. else if(!options.leadingZeros && leadingZeros.length > 0 && !sign && trimmedStr[1] !== ".") return str; //0123
  3333. else{//no leading zeros or leading zeros are allowed
  3334. const num = Number(trimmedStr);
  3335. const numStr = "" + num;
  3336. if(numStr.search(/[eE]/) !== -1){ //given number is long and parsed to eNotation
  3337. if(options.eNotation) return num;
  3338. else return str;
  3339. }else if(eNotation){ //given number has enotation
  3340. if(options.eNotation) return num;
  3341. else return str;
  3342. }else if(trimmedStr.indexOf(".") !== -1){ //floating number
  3343. // const decimalPart = match[5].substr(1);
  3344. // const intPart = trimmedStr.substr(0,trimmedStr.indexOf("."));
  3345. // const p = numStr.indexOf(".");
  3346. // const givenIntPart = numStr.substr(0,p);
  3347. // const givenDecPart = numStr.substr(p+1);
  3348. if(numStr === "0" && (numTrimmedByZeros === "") ) return num; //0.0
  3349. else if(numStr === numTrimmedByZeros) return num; //0.456. 0.79000
  3350. else if( sign && numStr === "-"+numTrimmedByZeros) return num;
  3351. else return str;
  3352. }
  3353. if(leadingZeros){
  3354. // if(numTrimmedByZeros === numStr){
  3355. // if(options.leadingZeros) return num;
  3356. // else return str;
  3357. // }else return str;
  3358. if(numTrimmedByZeros === numStr) return num;
  3359. else if(sign+numTrimmedByZeros === numStr) return num;
  3360. else return str;
  3361. }
  3362. if(trimmedStr === numStr) return num;
  3363. else if(trimmedStr === sign+numStr) return num;
  3364. // else{
  3365. // //number with +/- sign
  3366. // trimmedStr.test(/[-+][0-9]);
  3367. // }
  3368. return str;
  3369. }
  3370. // else if(!eNotation && trimmedStr && trimmedStr !== Number(trimmedStr) ) return str;
  3371. }else{ //non-numeric string
  3372. return str;
  3373. }
  3374. }
  3375. }
  3376. /**
  3377. *
  3378. * @param {string} numStr without leading zeros
  3379. * @returns
  3380. */
  3381. function trimZeros(numStr){
  3382. if(numStr && numStr.indexOf(".") !== -1){//float
  3383. numStr = numStr.replace(/0+$/, ""); //remove ending zeros
  3384. if(numStr === ".") numStr = "0";
  3385. else if(numStr[0] === ".") numStr = "0"+numStr;
  3386. else if(numStr[numStr.length-1] === ".") numStr = numStr.substr(0,numStr.length-1);
  3387. return numStr;
  3388. }
  3389. return numStr;
  3390. }
  3391. module.exports = toNumber
  3392. /***/ }),
  3393. /***/ "./node_modules/webpack/buildin/amd-options.js":
  3394. /*!****************************************!*\
  3395. !*** (webpack)/buildin/amd-options.js ***!
  3396. \****************************************/
  3397. /*! no static exports found */
  3398. /***/ (function(module, exports) {
  3399. /* WEBPACK VAR INJECTION */(function(__webpack_amd_options__) {/* globals __webpack_amd_options__ */
  3400. module.exports = __webpack_amd_options__;
  3401. /* WEBPACK VAR INJECTION */}.call(this, {}))
  3402. /***/ }),
  3403. /***/ "./node_modules/webpack/buildin/module.js":
  3404. /*!***********************************!*\
  3405. !*** (webpack)/buildin/module.js ***!
  3406. \***********************************/
  3407. /*! no static exports found */
  3408. /***/ (function(module, exports) {
  3409. module.exports = function(module) {
  3410. if (!module.webpackPolyfill) {
  3411. module.deprecate = function() {};
  3412. module.paths = [];
  3413. // module.parent = undefined by default
  3414. if (!module.children) module.children = [];
  3415. Object.defineProperty(module, "loaded", {
  3416. enumerable: true,
  3417. get: function() {
  3418. return module.l;
  3419. }
  3420. });
  3421. Object.defineProperty(module, "id", {
  3422. enumerable: true,
  3423. get: function() {
  3424. return module.i;
  3425. }
  3426. });
  3427. module.webpackPolyfill = 1;
  3428. }
  3429. return module;
  3430. };
  3431. /***/ }),
  3432. /***/ "./package.json":
  3433. /*!**********************!*\
  3434. !*** ./package.json ***!
  3435. \**********************/
  3436. /*! exports provided: name, version, description, main, scripts, repository, author, license, dependencies, devDependencies, default */
  3437. /***/ (function(module) {
  3438. module.exports = JSON.parse("{\"name\":\"cos-wx-sdk-v5\",\"version\":\"1.7.2\",\"description\":\"小程序 SDK for [腾讯云对象存储服务](https://cloud.tencent.com/product/cos)\",\"main\":\"demo/lib/cos-wx-sdk-v5.min.js\",\"scripts\":{\"prettier\":\"prettier --write src demo/demo-sdk.js demo/test.js demo/ciDemo\",\"dev\":\"cross-env NODE_ENV=development node build.js --mode=development\",\"build\":\"cross-env NODE_ENV=production node build.js --mode=production\",\"sts.js\":\"node server/sts.js\"},\"repository\":{\"type\":\"git\",\"url\":\"http://github.com/tencentyun/cos-wx-sdk-v5.git\"},\"author\":\"carsonxu\",\"license\":\"ISC\",\"dependencies\":{\"fast-xml-parser\":\"^4.4.0\",\"mime\":\"^2.4.6\"},\"devDependencies\":{\"@babel/core\":\"7.17.9\",\"@babel/preset-env\":\"7.16.11\",\"babel-loader\":\"8.2.5\",\"body-parser\":\"^1.18.3\",\"cross-env\":\"^7.0.3\",\"express\":\"^4.17.1\",\"prettier\":\"^3.0.1\",\"qcloud-cos-sts\":\"^3.0.2\",\"terser-webpack-plugin\":\"4.2.3\",\"webpack\":\"4.46.0\",\"webpack-cli\":\"4.10.0\"}}");
  3439. /***/ }),
  3440. /***/ "./src/advance.js":
  3441. /*!************************!*\
  3442. !*** ./src/advance.js ***!
  3443. \************************/
  3444. /*! no static exports found */
  3445. /***/ (function(module, exports, __webpack_require__) {
  3446. function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
  3447. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  3448. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  3449. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  3450. var session = __webpack_require__(/*! ./session */ "./src/session.js");
  3451. var Async = __webpack_require__(/*! ./async */ "./src/async.js");
  3452. var EventProxy = __webpack_require__(/*! ./event */ "./src/event.js").EventProxy;
  3453. var util = __webpack_require__(/*! ./util */ "./src/util.js");
  3454. var Tracker = __webpack_require__(/*! ./tracker */ "./src/tracker.js");
  3455. // 文件分块上传全过程,暴露的分块上传接口
  3456. function sliceUploadFile(params, callback) {
  3457. var self = this;
  3458. // 如果小程序版本不支持获取文件分片内容,统一转到 简单上传 接口上传
  3459. if (!util.canFileSlice()) {
  3460. params.SkipTask = true;
  3461. if (self.options.SimpleUploadMethod === 'postObject') {
  3462. self.postObject(params, callback);
  3463. } else {
  3464. self.putObject(params, callback);
  3465. }
  3466. return;
  3467. }
  3468. var ep = new EventProxy();
  3469. var TaskId = params.TaskId;
  3470. var Bucket = params.Bucket;
  3471. var Region = params.Region;
  3472. var Key = params.Key;
  3473. var FilePath = params.FilePath;
  3474. var ChunkSize = params.ChunkSize || params.SliceSize || self.options.ChunkSize;
  3475. var AsyncLimit = params.AsyncLimit;
  3476. var StorageClass = params.StorageClass;
  3477. var ServerSideEncryption = params.ServerSideEncryption;
  3478. var FileSize;
  3479. var onProgress;
  3480. var onHashProgress = params.onHashProgress;
  3481. var tracker = params.tracker;
  3482. tracker && tracker.setParams({
  3483. chunkSize: ChunkSize
  3484. });
  3485. // 上传过程中出现错误,返回错误
  3486. ep.on('error', function (err) {
  3487. if (!self._isRunningTask(TaskId)) return;
  3488. var _err = {
  3489. UploadId: params.UploadData.UploadId || '',
  3490. err: err,
  3491. error: err
  3492. };
  3493. return callback(_err);
  3494. });
  3495. // 上传分块完成,开始 uploadSliceComplete 操作
  3496. ep.on('upload_complete', function (UploadCompleteData) {
  3497. var _UploadCompleteData = util.extend({
  3498. UploadId: params.UploadData.UploadId || ''
  3499. }, UploadCompleteData);
  3500. callback(null, _UploadCompleteData);
  3501. });
  3502. // 上传分块完成,开始 uploadSliceComplete 操作
  3503. ep.on('upload_slice_complete', function (UploadData) {
  3504. var metaHeaders = {};
  3505. util.each(params.Headers, function (val, k) {
  3506. var shortKey = k.toLowerCase();
  3507. if (shortKey.indexOf('x-cos-meta-') === 0 || shortKey === 'pic-operations') {
  3508. metaHeaders[k] = val;
  3509. }
  3510. });
  3511. uploadSliceComplete.call(self, {
  3512. Bucket: Bucket,
  3513. Region: Region,
  3514. Key: Key,
  3515. UploadId: UploadData.UploadId,
  3516. SliceList: UploadData.SliceList,
  3517. Headers: metaHeaders,
  3518. tracker: tracker
  3519. }, function (err, data) {
  3520. if (!self._isRunningTask(TaskId)) return;
  3521. session.removeUsing(UploadData.UploadId);
  3522. if (err) {
  3523. onProgress(null, true);
  3524. return ep.emit('error', err);
  3525. }
  3526. session.removeUploadId(UploadData.UploadId);
  3527. onProgress({
  3528. loaded: FileSize,
  3529. total: FileSize
  3530. }, true);
  3531. ep.emit('upload_complete', data);
  3532. });
  3533. });
  3534. // 获取 UploadId 完成,开始上传每个分片
  3535. ep.on('get_upload_data_finish', function (UploadData) {
  3536. // 处理 UploadId 缓存
  3537. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key);
  3538. uuid && session.saveUploadId(uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // 缓存 UploadId
  3539. session.setUsing(UploadData.UploadId); // 标记 UploadId 为正在使用
  3540. // 获取 UploadId
  3541. onProgress(null, true); // 任务状态开始 uploading
  3542. uploadSliceList.call(self, {
  3543. TaskId: TaskId,
  3544. Bucket: Bucket,
  3545. Region: Region,
  3546. Key: Key,
  3547. FilePath: FilePath,
  3548. FileSize: FileSize,
  3549. SliceSize: ChunkSize,
  3550. AsyncLimit: AsyncLimit,
  3551. ServerSideEncryption: ServerSideEncryption,
  3552. UploadData: UploadData,
  3553. onProgress: onProgress,
  3554. tracker: tracker
  3555. }, function (err, data) {
  3556. if (!self._isRunningTask(TaskId)) return;
  3557. if (err) {
  3558. onProgress(null, true);
  3559. return ep.emit('error', err);
  3560. }
  3561. ep.emit('upload_slice_complete', data);
  3562. });
  3563. });
  3564. // 开始获取文件 UploadId,里面会视情况计算 ETag,并比对,保证文件一致性,也优化上传
  3565. ep.on('get_file_size_finish', function () {
  3566. onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  3567. if (params.UploadData.UploadId) {
  3568. ep.emit('get_upload_data_finish', params.UploadData);
  3569. } else {
  3570. var _params = util.extend({
  3571. TaskId: TaskId,
  3572. Bucket: Bucket,
  3573. Region: Region,
  3574. Key: Key,
  3575. Headers: params.Headers,
  3576. StorageClass: StorageClass,
  3577. FilePath: FilePath,
  3578. FileSize: FileSize,
  3579. SliceSize: ChunkSize,
  3580. onHashProgress: onHashProgress,
  3581. tracker: tracker
  3582. }, params);
  3583. // 这里用户传入的params.FileSize可能单位不统一,必须使用sdk内获取的大小
  3584. _params.FileSize = FileSize;
  3585. getUploadIdAndPartList.call(self, _params, function (err, UploadData) {
  3586. if (!self._isRunningTask(TaskId)) return;
  3587. if (err) return ep.emit('error', err);
  3588. params.UploadData.UploadId = UploadData.UploadId;
  3589. params.UploadData.PartList = UploadData.PartList;
  3590. ep.emit('get_upload_data_finish', params.UploadData);
  3591. });
  3592. }
  3593. });
  3594. // 获取上传文件大小
  3595. FileSize = params.ContentLength;
  3596. delete params.ContentLength;
  3597. !params.Headers && (params.Headers = {});
  3598. util.each(params.Headers, function (item, key) {
  3599. if (key.toLowerCase() === 'content-length') {
  3600. delete params.Headers[key];
  3601. }
  3602. });
  3603. // 控制分片大小
  3604. (function () {
  3605. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  3606. var AutoChunkSize = 1024 * 1024;
  3607. for (var i = 0; i < SIZE.length; i++) {
  3608. AutoChunkSize = SIZE[i] * 1024 * 1024;
  3609. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  3610. }
  3611. params.ChunkSize = params.SliceSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  3612. })();
  3613. // 开始上传
  3614. if (FileSize === 0) {
  3615. params.Body = '';
  3616. params.ContentLength = 0;
  3617. params.SkipTask = true;
  3618. self.putObject(params, function (err, data) {
  3619. if (err) {
  3620. return callback(err);
  3621. }
  3622. callback(null, data);
  3623. });
  3624. } else {
  3625. ep.emit('get_file_size_finish');
  3626. }
  3627. }
  3628. // 获取上传任务的 UploadId
  3629. function getUploadIdAndPartList(params, callback) {
  3630. var TaskId = params.TaskId;
  3631. var Bucket = params.Bucket;
  3632. var Region = params.Region;
  3633. var Key = params.Key;
  3634. var StorageClass = params.StorageClass;
  3635. var self = this;
  3636. // 计算 ETag
  3637. var ETagMap = {};
  3638. var FileSize = params.FileSize;
  3639. var SliceSize = params.SliceSize;
  3640. var SliceCount = Math.ceil(FileSize / SliceSize);
  3641. var FinishSliceCount = 0;
  3642. var FinishSize = 0;
  3643. var onHashProgress = util.throttleOnProgress.call(self, FileSize, params.onHashProgress);
  3644. var getChunkETag = function getChunkETag(PartNumber, callback) {
  3645. var start = SliceSize * (PartNumber - 1);
  3646. var end = Math.min(start + SliceSize, FileSize);
  3647. var ChunkSize = end - start;
  3648. if (ETagMap[PartNumber]) {
  3649. callback(null, {
  3650. PartNumber: PartNumber,
  3651. ETag: ETagMap[PartNumber],
  3652. Size: ChunkSize
  3653. });
  3654. } else {
  3655. util.fileSlice(params.FilePath, start, end, function (chunkItem) {
  3656. try {
  3657. var md5 = util.getFileMd5(chunkItem);
  3658. } catch (err) {
  3659. return callback(err);
  3660. }
  3661. var ETag = '"' + md5 + '"';
  3662. ETagMap[PartNumber] = ETag;
  3663. FinishSliceCount += 1;
  3664. FinishSize += ChunkSize;
  3665. callback(null, {
  3666. PartNumber: PartNumber,
  3667. ETag: ETag,
  3668. Size: ChunkSize
  3669. });
  3670. onHashProgress({
  3671. loaded: FinishSize,
  3672. total: FileSize
  3673. });
  3674. });
  3675. }
  3676. };
  3677. // 通过和文件的 md5 对比,判断 UploadId 是否可用
  3678. var isAvailableUploadList = function isAvailableUploadList(PartList, callback) {
  3679. var PartCount = PartList.length;
  3680. // 如果没有分片,通过
  3681. if (PartCount === 0) {
  3682. return callback(null, true);
  3683. }
  3684. // 检查分片数量
  3685. if (PartCount > SliceCount) {
  3686. return callback(null, false);
  3687. }
  3688. // 检查分片大小
  3689. if (PartCount > 1) {
  3690. var PartSliceSize = Math.max(PartList[0].Size, PartList[1].Size);
  3691. if (PartSliceSize !== SliceSize) {
  3692. return callback(null, false);
  3693. }
  3694. }
  3695. // 逐个分片计算并检查 ETag 是否一致
  3696. var next = function next(index) {
  3697. if (index < PartCount) {
  3698. var Part = PartList[index];
  3699. getChunkETag(Part.PartNumber, function (err, chunk) {
  3700. if (chunk && chunk.ETag === Part.ETag && chunk.Size === Part.Size) {
  3701. next(index + 1);
  3702. } else {
  3703. callback(null, false);
  3704. }
  3705. });
  3706. } else {
  3707. callback(null, true);
  3708. }
  3709. };
  3710. next(0);
  3711. };
  3712. var ep = new EventProxy();
  3713. ep.on('error', function (errData) {
  3714. if (!self._isRunningTask(TaskId)) return;
  3715. return callback(errData);
  3716. });
  3717. // 存在 UploadId
  3718. ep.on('upload_id_available', function (UploadData) {
  3719. // 转换成 map
  3720. var map = {};
  3721. var list = [];
  3722. util.each(UploadData.PartList, function (item) {
  3723. map[item.PartNumber] = item;
  3724. });
  3725. for (var PartNumber = 1; PartNumber <= SliceCount; PartNumber++) {
  3726. var item = map[PartNumber];
  3727. if (item) {
  3728. item.PartNumber = PartNumber;
  3729. item.Uploaded = true;
  3730. } else {
  3731. item = {
  3732. PartNumber: PartNumber,
  3733. ETag: null,
  3734. Uploaded: false
  3735. };
  3736. }
  3737. list.push(item);
  3738. }
  3739. UploadData.PartList = list;
  3740. callback(null, UploadData);
  3741. });
  3742. // 不存在 UploadId, 初始化生成 UploadId
  3743. ep.on('no_available_upload_id', function () {
  3744. if (!self._isRunningTask(TaskId)) return;
  3745. var _params = util.extend({
  3746. Bucket: Bucket,
  3747. Region: Region,
  3748. Key: Key,
  3749. Headers: util.clone(params.Headers),
  3750. Query: util.clone(params.Query),
  3751. StorageClass: StorageClass,
  3752. calledBySdk: 'sliceUploadFile',
  3753. tracker: params.tracker
  3754. }, params);
  3755. self.multipartInit(_params, function (err, data) {
  3756. if (!self._isRunningTask(TaskId)) return;
  3757. if (err) return ep.emit('error', err);
  3758. var UploadId = data.UploadId;
  3759. if (!UploadId) {
  3760. return callback({
  3761. Message: 'no upload id'
  3762. });
  3763. }
  3764. ep.emit('upload_id_available', {
  3765. UploadId: UploadId,
  3766. PartList: []
  3767. });
  3768. });
  3769. });
  3770. // 如果已存在 UploadId,找一个可以用的 UploadId
  3771. ep.on('has_and_check_upload_id', function (UploadIdList) {
  3772. // 串行地,找一个内容一致的 UploadId
  3773. UploadIdList = UploadIdList.reverse();
  3774. Async.eachLimit(UploadIdList, 1, function (UploadId, asyncCallback) {
  3775. if (!self._isRunningTask(TaskId)) return;
  3776. // 如果正在上传,跳过
  3777. if (session.using[UploadId]) {
  3778. asyncCallback(); // 检查下一个 UploadId
  3779. return;
  3780. }
  3781. // 判断 UploadId 是否可用
  3782. wholeMultipartListPart.call(self, {
  3783. Bucket: Bucket,
  3784. Region: Region,
  3785. Key: Key,
  3786. UploadId: UploadId,
  3787. tracker: params.tracker
  3788. }, function (err, PartListData) {
  3789. if (!self._isRunningTask(TaskId)) return;
  3790. if (err) {
  3791. session.removeUsing(UploadId);
  3792. return ep.emit('error', err);
  3793. }
  3794. var PartList = PartListData.PartList;
  3795. PartList.forEach(function (item) {
  3796. item.PartNumber *= 1;
  3797. item.Size *= 1;
  3798. item.ETag = item.ETag || '';
  3799. });
  3800. isAvailableUploadList(PartList, function (err, isAvailable) {
  3801. if (!self._isRunningTask(TaskId)) return;
  3802. if (err) return ep.emit('error', err);
  3803. if (isAvailable) {
  3804. asyncCallback({
  3805. UploadId: UploadId,
  3806. PartList: PartList
  3807. }); // 马上结束
  3808. } else {
  3809. asyncCallback(); // 检查下一个 UploadId
  3810. }
  3811. });
  3812. });
  3813. }, function (AvailableUploadData) {
  3814. if (!self._isRunningTask(TaskId)) return;
  3815. onHashProgress(null, true);
  3816. if (AvailableUploadData && AvailableUploadData.UploadId) {
  3817. ep.emit('upload_id_available', AvailableUploadData);
  3818. } else {
  3819. ep.emit('no_available_upload_id');
  3820. }
  3821. });
  3822. });
  3823. // 在本地缓存找可用的 UploadId
  3824. ep.on('seek_local_avail_upload_id', function (RemoteUploadIdList) {
  3825. // 在本地找可用的 UploadId
  3826. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key);
  3827. var LocalUploadIdList = session.getUploadIdList(uuid);
  3828. if (!uuid || !LocalUploadIdList) {
  3829. ep.emit('has_and_check_upload_id', RemoteUploadIdList);
  3830. return;
  3831. }
  3832. var next = function next(index) {
  3833. // 如果本地找不到可用 UploadId,再一个个遍历校验远端
  3834. if (index >= LocalUploadIdList.length) {
  3835. ep.emit('has_and_check_upload_id', RemoteUploadIdList);
  3836. return;
  3837. }
  3838. var UploadId = LocalUploadIdList[index];
  3839. // 如果不在远端 UploadId 列表里,跳过并删除
  3840. if (!util.isInArray(RemoteUploadIdList, UploadId)) {
  3841. session.removeUploadId(UploadId);
  3842. next(index + 1);
  3843. return;
  3844. }
  3845. // 如果正在上传,跳过
  3846. if (session.using[UploadId]) {
  3847. next(index + 1);
  3848. return;
  3849. }
  3850. // 判断 UploadId 是否存在线上
  3851. wholeMultipartListPart.call(self, {
  3852. Bucket: Bucket,
  3853. Region: Region,
  3854. Key: Key,
  3855. UploadId: UploadId,
  3856. tracker: params.tracker
  3857. }, function (err, PartListData) {
  3858. if (!self._isRunningTask(TaskId)) return;
  3859. if (err) {
  3860. // 如果 UploadId 获取会出错,跳过并删除
  3861. session.removeUploadId(UploadId);
  3862. next(index + 1);
  3863. } else {
  3864. // 找到可用 UploadId
  3865. ep.emit('upload_id_available', {
  3866. UploadId: UploadId,
  3867. PartList: PartListData.PartList
  3868. });
  3869. }
  3870. });
  3871. };
  3872. next(0);
  3873. });
  3874. // 获取线上 UploadId 列表
  3875. ep.on('get_remote_upload_id_list', function () {
  3876. // 获取符合条件的 UploadId 列表,因为同一个文件可以有多个上传任务。
  3877. wholeMultipartList.call(self, {
  3878. Bucket: Bucket,
  3879. Region: Region,
  3880. Key: Key,
  3881. tracker: params.tracker
  3882. }, function (err, data) {
  3883. if (!self._isRunningTask(TaskId)) return;
  3884. if (err) {
  3885. return ep.emit('error', err);
  3886. }
  3887. // 整理远端 UploadId 列表
  3888. var RemoteUploadIdList = util.filter(data.UploadList, function (item) {
  3889. return item.Key === Key && (!StorageClass || item.StorageClass.toUpperCase() === StorageClass.toUpperCase());
  3890. }).reverse().map(function (item) {
  3891. return item.UploadId || item.UploadID;
  3892. });
  3893. if (RemoteUploadIdList.length) {
  3894. ep.emit('seek_local_avail_upload_id', RemoteUploadIdList);
  3895. } else {
  3896. // 远端没有 UploadId,清理缓存的 UploadId
  3897. var uuid = session.getFileId(params.FileStat, params.ChunkSize, Bucket, Key),
  3898. LocalUploadIdList;
  3899. if (uuid && (LocalUploadIdList = session.getUploadIdList(uuid))) {
  3900. util.each(LocalUploadIdList, function (UploadId) {
  3901. session.removeUploadId(UploadId);
  3902. });
  3903. }
  3904. ep.emit('no_available_upload_id');
  3905. }
  3906. });
  3907. });
  3908. // 开始找可用 UploadId
  3909. ep.emit('get_remote_upload_id_list');
  3910. }
  3911. // 获取符合条件的全部上传任务 (条件包括 Bucket, Region, Prefix)
  3912. function wholeMultipartList(params, callback) {
  3913. var self = this;
  3914. var UploadList = [];
  3915. var sendParams = {
  3916. Bucket: params.Bucket,
  3917. Region: params.Region,
  3918. Prefix: params.Key,
  3919. calledBySdk: params.calledBySdk || 'sliceUploadFile',
  3920. tracker: params.tracker
  3921. };
  3922. var next = function next() {
  3923. self.multipartList(sendParams, function (err, data) {
  3924. if (err) return callback(err);
  3925. UploadList.push.apply(UploadList, data.Upload || []);
  3926. if (data.IsTruncated === 'true') {
  3927. // 列表不完整
  3928. sendParams.KeyMarker = data.NextKeyMarker;
  3929. sendParams.UploadIdMarker = data.NextUploadIdMarker;
  3930. next();
  3931. } else {
  3932. callback(null, {
  3933. UploadList: UploadList
  3934. });
  3935. }
  3936. });
  3937. };
  3938. next();
  3939. }
  3940. // 获取指定上传任务的分块列表
  3941. function wholeMultipartListPart(params, callback) {
  3942. var self = this;
  3943. var PartList = [];
  3944. var sendParams = {
  3945. Bucket: params.Bucket,
  3946. Region: params.Region,
  3947. Key: params.Key,
  3948. UploadId: params.UploadId,
  3949. calledBySdk: 'sliceUploadFile',
  3950. tracker: params.tracker
  3951. };
  3952. var next = function next() {
  3953. self.multipartListPart(sendParams, function (err, data) {
  3954. if (err) return callback(err);
  3955. PartList.push.apply(PartList, data.Part || []);
  3956. if (data.IsTruncated === 'true') {
  3957. // 列表不完整
  3958. sendParams.PartNumberMarker = data.NextPartNumberMarker;
  3959. next();
  3960. } else {
  3961. callback(null, {
  3962. PartList: PartList
  3963. });
  3964. }
  3965. });
  3966. };
  3967. next();
  3968. }
  3969. // 上传文件分块,包括
  3970. /*
  3971. UploadId (上传任务编号)
  3972. AsyncLimit (并发量),
  3973. SliceList (上传的分块数组),
  3974. FilePath (本地文件的位置),
  3975. SliceSize (文件分块大小)
  3976. FileSize (文件大小)
  3977. onProgress (上传成功之后的回调函数)
  3978. */
  3979. function uploadSliceList(params, cb) {
  3980. var self = this;
  3981. var TaskId = params.TaskId;
  3982. var Bucket = params.Bucket;
  3983. var Region = params.Region;
  3984. var Key = params.Key;
  3985. var UploadData = params.UploadData;
  3986. var FileSize = params.FileSize;
  3987. var SliceSize = params.SliceSize;
  3988. var ChunkParallel = Math.min(params.AsyncLimit || self.options.ChunkParallelLimit || 1, 256);
  3989. var FilePath = params.FilePath;
  3990. var SliceCount = Math.ceil(FileSize / SliceSize);
  3991. var FinishSize = 0;
  3992. var ServerSideEncryption = params.ServerSideEncryption;
  3993. var needUploadSlices = util.filter(UploadData.PartList, function (SliceItem) {
  3994. if (SliceItem['Uploaded']) {
  3995. FinishSize += SliceItem['PartNumber'] >= SliceCount ? FileSize % SliceSize || SliceSize : SliceSize;
  3996. }
  3997. return !SliceItem['Uploaded'];
  3998. });
  3999. var _onProgress2 = params.onProgress;
  4000. Async.eachLimit(needUploadSlices, ChunkParallel, function (SliceItem, asyncCallback) {
  4001. if (!self._isRunningTask(TaskId)) return;
  4002. var PartNumber = SliceItem['PartNumber'];
  4003. var currentSize = Math.min(FileSize, SliceItem['PartNumber'] * SliceSize) - (SliceItem['PartNumber'] - 1) * SliceSize;
  4004. var preAddSize = 0;
  4005. uploadSliceItem.call(self, {
  4006. TaskId: TaskId,
  4007. Bucket: Bucket,
  4008. Region: Region,
  4009. Key: Key,
  4010. SliceSize: SliceSize,
  4011. FileSize: FileSize,
  4012. PartNumber: PartNumber,
  4013. ServerSideEncryption: ServerSideEncryption,
  4014. FilePath: FilePath,
  4015. UploadData: UploadData,
  4016. onProgress: function onProgress(data) {
  4017. FinishSize += data.loaded - preAddSize;
  4018. preAddSize = data.loaded;
  4019. _onProgress2({
  4020. loaded: FinishSize,
  4021. total: FileSize
  4022. });
  4023. },
  4024. tracker: params.tracker
  4025. }, function (err, data) {
  4026. if (!self._isRunningTask(TaskId)) return;
  4027. if (err) {
  4028. FinishSize -= preAddSize;
  4029. } else {
  4030. FinishSize += currentSize - preAddSize;
  4031. SliceItem.ETag = data.ETag;
  4032. }
  4033. _onProgress2({
  4034. loaded: FinishSize,
  4035. total: FileSize
  4036. });
  4037. asyncCallback(err || null, data);
  4038. });
  4039. }, function (err) {
  4040. if (!self._isRunningTask(TaskId)) return;
  4041. if (err) return cb(err);
  4042. cb(null, {
  4043. UploadId: UploadData.UploadId,
  4044. SliceList: UploadData.PartList
  4045. });
  4046. });
  4047. }
  4048. // 上传指定分片
  4049. function uploadSliceItem(params, callback) {
  4050. var self = this;
  4051. var TaskId = params.TaskId;
  4052. var Bucket = params.Bucket;
  4053. var Region = params.Region;
  4054. var Key = params.Key;
  4055. var FileSize = params.FileSize;
  4056. var FilePath = params.FilePath;
  4057. var PartNumber = params.PartNumber * 1;
  4058. var SliceSize = params.SliceSize;
  4059. var ServerSideEncryption = params.ServerSideEncryption;
  4060. var UploadData = params.UploadData;
  4061. var ChunkRetryTimes = self.options.ChunkRetryTimes + 1;
  4062. var Headers = params.Headers || {};
  4063. var start = SliceSize * (PartNumber - 1);
  4064. var ContentLength = SliceSize;
  4065. var end = start + SliceSize;
  4066. if (end > FileSize) {
  4067. end = FileSize;
  4068. ContentLength = end - start;
  4069. }
  4070. var headersWhiteList = ['x-cos-traffic-limit', 'x-cos-mime-limit'];
  4071. var headers = {};
  4072. util.each(Headers, function (v, k) {
  4073. if (headersWhiteList.indexOf(k) > -1) {
  4074. headers[k] = v;
  4075. }
  4076. });
  4077. util.fileSlice(FilePath, start, end, function (Body) {
  4078. var md5 = util.getFileMd5(Body);
  4079. var contentMd5 = md5 ? util.binaryBase64(md5) : null;
  4080. var PartItem = UploadData.PartList[PartNumber - 1];
  4081. Async.retry(ChunkRetryTimes, function (tryCallback) {
  4082. if (!self._isRunningTask(TaskId)) return;
  4083. self.multipartUpload({
  4084. TaskId: TaskId,
  4085. Bucket: Bucket,
  4086. Region: Region,
  4087. Key: Key,
  4088. ContentLength: ContentLength,
  4089. PartNumber: PartNumber,
  4090. UploadId: UploadData.UploadId,
  4091. ServerSideEncryption: ServerSideEncryption,
  4092. Body: Body,
  4093. Headers: headers,
  4094. onProgress: params.onProgress,
  4095. ContentMD5: contentMd5,
  4096. calledBySdk: 'sliceUploadFile',
  4097. tracker: params.tracker
  4098. }, function (err, data) {
  4099. if (!self._isRunningTask(TaskId)) return;
  4100. if (err) {
  4101. return tryCallback(err);
  4102. } else {
  4103. PartItem.Uploaded = true;
  4104. return tryCallback(null, data);
  4105. }
  4106. });
  4107. }, function (err, data) {
  4108. if (!self._isRunningTask(TaskId)) return;
  4109. return callback(err, data);
  4110. });
  4111. });
  4112. }
  4113. // 完成分块上传
  4114. function uploadSliceComplete(params, callback) {
  4115. var Bucket = params.Bucket;
  4116. var Region = params.Region;
  4117. var Key = params.Key;
  4118. var UploadId = params.UploadId;
  4119. var SliceList = params.SliceList;
  4120. var self = this;
  4121. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  4122. var Parts = SliceList.map(function (item) {
  4123. return {
  4124. PartNumber: item.PartNumber,
  4125. ETag: item.ETag
  4126. };
  4127. });
  4128. // 完成上传的请求也做重试
  4129. Async.retry(ChunkRetryTimes, function (tryCallback) {
  4130. self.multipartComplete({
  4131. Bucket: Bucket,
  4132. Region: Region,
  4133. Key: Key,
  4134. UploadId: UploadId,
  4135. Parts: Parts,
  4136. calledBySdk: 'sliceUploadFile',
  4137. Headers: params.Headers || {},
  4138. tracker: params.tracker
  4139. }, tryCallback);
  4140. }, function (err, data) {
  4141. callback(err, data);
  4142. });
  4143. }
  4144. // 抛弃分块上传任务
  4145. /*
  4146. AsyncLimit (抛弃上传任务的并发量),
  4147. UploadId (上传任务的编号,当 Level 为 task 时候需要)
  4148. Level (抛弃分块上传任务的级别,task : 抛弃指定的上传任务,file : 抛弃指定的文件对应的上传任务,其他值 :抛弃指定Bucket 的全部上传任务)
  4149. */
  4150. function abortUploadTask(params, callback) {
  4151. var Bucket = params.Bucket;
  4152. var Region = params.Region;
  4153. var Key = params.Key;
  4154. var UploadId = params.UploadId;
  4155. var Level = params.Level || 'task';
  4156. var AsyncLimit = params.AsyncLimit;
  4157. var self = this;
  4158. var ep = new EventProxy();
  4159. ep.on('error', function (errData) {
  4160. return callback(errData);
  4161. });
  4162. // 已经获取到需要抛弃的任务列表
  4163. ep.on('get_abort_array', function (AbortArray) {
  4164. abortUploadTaskArray.call(self, {
  4165. Bucket: Bucket,
  4166. Region: Region,
  4167. Key: Key,
  4168. Headers: params.Headers,
  4169. AsyncLimit: AsyncLimit,
  4170. AbortArray: AbortArray
  4171. }, function (err, data) {
  4172. if (err) {
  4173. return callback(err);
  4174. }
  4175. callback(null, data);
  4176. });
  4177. });
  4178. if (Level === 'bucket') {
  4179. // Bucket 级别的任务抛弃,抛弃该 Bucket 下的全部上传任务
  4180. wholeMultipartList.call(self, {
  4181. Bucket: Bucket,
  4182. Region: Region,
  4183. calledBySdk: 'abortUploadTask'
  4184. }, function (err, data) {
  4185. if (err) {
  4186. return callback(err);
  4187. }
  4188. ep.emit('get_abort_array', data.UploadList || []);
  4189. });
  4190. } else if (Level === 'file') {
  4191. // 文件级别的任务抛弃,抛弃该文件的全部上传任务
  4192. if (!Key) return callback({
  4193. error: 'abort_upload_task_no_key'
  4194. });
  4195. wholeMultipartList.call(self, {
  4196. Bucket: Bucket,
  4197. Region: Region,
  4198. Key: Key,
  4199. calledBySdk: 'abortUploadTask'
  4200. }, function (err, data) {
  4201. if (err) {
  4202. return callback(err);
  4203. }
  4204. ep.emit('get_abort_array', data.UploadList || []);
  4205. });
  4206. } else if (Level === 'task') {
  4207. // 单个任务级别的任务抛弃,抛弃指定 UploadId 的上传任务
  4208. if (!UploadId) return callback({
  4209. error: 'abort_upload_task_no_id'
  4210. });
  4211. if (!Key) return callback({
  4212. error: 'abort_upload_task_no_key'
  4213. });
  4214. ep.emit('get_abort_array', [{
  4215. Key: Key,
  4216. UploadId: UploadId
  4217. }]);
  4218. } else {
  4219. return callback({
  4220. error: 'abort_unknown_level'
  4221. });
  4222. }
  4223. }
  4224. // 批量抛弃分块上传任务
  4225. function abortUploadTaskArray(params, callback) {
  4226. var Bucket = params.Bucket;
  4227. var Region = params.Region;
  4228. var Key = params.Key;
  4229. var AbortArray = params.AbortArray;
  4230. var AsyncLimit = params.AsyncLimit || 1;
  4231. var self = this;
  4232. var index = 0;
  4233. var resultList = new Array(AbortArray.length);
  4234. Async.eachLimit(AbortArray, AsyncLimit, function (AbortItem, callback) {
  4235. var eachIndex = index;
  4236. if (Key && Key !== AbortItem.Key) {
  4237. resultList[eachIndex] = {
  4238. error: {
  4239. KeyNotMatch: true
  4240. }
  4241. };
  4242. callback(null);
  4243. return;
  4244. }
  4245. var UploadId = AbortItem.UploadId || AbortItem.UploadID;
  4246. self.multipartAbort({
  4247. Bucket: Bucket,
  4248. Region: Region,
  4249. Key: AbortItem.Key,
  4250. Headers: params.Headers,
  4251. UploadId: UploadId
  4252. }, function (err) {
  4253. var task = {
  4254. Bucket: Bucket,
  4255. Region: Region,
  4256. Key: AbortItem.Key,
  4257. UploadId: UploadId
  4258. };
  4259. resultList[eachIndex] = {
  4260. error: err,
  4261. task: task
  4262. };
  4263. callback(null);
  4264. });
  4265. index++;
  4266. }, function (err) {
  4267. if (err) {
  4268. return callback(err);
  4269. }
  4270. var successList = [];
  4271. var errorList = [];
  4272. for (var i = 0, len = resultList.length; i < len; i++) {
  4273. var item = resultList[i];
  4274. if (item['task']) {
  4275. if (item['error']) {
  4276. errorList.push(item['task']);
  4277. } else {
  4278. successList.push(item['task']);
  4279. }
  4280. }
  4281. }
  4282. return callback(null, {
  4283. successList: successList,
  4284. errorList: errorList
  4285. });
  4286. });
  4287. }
  4288. // 高级上传
  4289. function uploadFile(_x, _x2) {
  4290. return _uploadFile.apply(this, arguments);
  4291. } // 批量上传文件
  4292. function _uploadFile() {
  4293. _uploadFile = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(params, callback) {
  4294. var self, SliceSize, taskList, FileSize, fileInfo, accelerate, realApi, _onTaskReady, _onFileFinish, onFileFinish, simpleUploadMethod, api;
  4295. return _regeneratorRuntime().wrap(function _callee$(_context) {
  4296. while (1) switch (_context.prev = _context.next) {
  4297. case 0:
  4298. self = this; // 判断多大的文件使用分片上传
  4299. SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize;
  4300. taskList = []; // var FileSize = params.FileSize;
  4301. _context.prev = 3;
  4302. _context.next = 6;
  4303. return util.getFileSizeByPath(params.FilePath);
  4304. case 6:
  4305. FileSize = _context.sent;
  4306. _context.next = 13;
  4307. break;
  4308. case 9:
  4309. _context.prev = 9;
  4310. _context.t0 = _context["catch"](3);
  4311. callback({
  4312. error: _context.t0
  4313. });
  4314. return _context.abrupt("return");
  4315. case 13:
  4316. fileInfo = {
  4317. TaskId: ''
  4318. }; // 上传链路
  4319. if (self.options.EnableReporter) {
  4320. accelerate = self.options.UseAccelerate || typeof self.options.Domain === 'string' && self.options.Domain.includes('accelerate.');
  4321. realApi = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject';
  4322. params.tracker = new Tracker({
  4323. Beacon: self.options.BeaconReporter,
  4324. clsReporter: self.options.ClsReporter,
  4325. bucket: params.Bucket,
  4326. region: params.Region,
  4327. apiName: 'uploadFile',
  4328. realApi: realApi,
  4329. fileKey: params.Key,
  4330. fileSize: FileSize,
  4331. accelerate: accelerate,
  4332. deepTracker: self.options.DeepTracker,
  4333. customId: self.options.CustomId,
  4334. delay: self.options.TrackerDelay
  4335. });
  4336. }
  4337. // 整理 option,用于返回给回调
  4338. util.each(params, function (v, k) {
  4339. if (_typeof(v) !== 'object' && typeof v !== 'function') {
  4340. fileInfo[k] = v;
  4341. }
  4342. });
  4343. // 处理文件 TaskReady
  4344. _onTaskReady = params.onTaskReady;
  4345. params.onTaskReady = function (tid) {
  4346. fileInfo.TaskId = tid;
  4347. _onTaskReady && _onTaskReady(tid);
  4348. };
  4349. // 处理文件完成
  4350. _onFileFinish = params.onFileFinish;
  4351. onFileFinish = function onFileFinish(err, data) {
  4352. // 格式化上报参数并上报
  4353. params.tracker && params.tracker.report(err, data);
  4354. _onFileFinish && _onFileFinish(err, data, fileInfo);
  4355. callback && callback(err, data);
  4356. }; // 添加上传任务
  4357. simpleUploadMethod = self.options.SimpleUploadMethod === 'postObject' ? 'postObject' : 'putObject';
  4358. api = FileSize > SliceSize ? 'sliceUploadFile' : simpleUploadMethod;
  4359. taskList.push({
  4360. api: api,
  4361. params: params,
  4362. callback: onFileFinish
  4363. });
  4364. self._addTasks(taskList);
  4365. case 24:
  4366. case "end":
  4367. return _context.stop();
  4368. }
  4369. }, _callee, this, [[3, 9]]);
  4370. }));
  4371. return _uploadFile.apply(this, arguments);
  4372. }
  4373. function uploadFiles(_x3, _x4) {
  4374. return _uploadFiles.apply(this, arguments);
  4375. } // 分片复制文件
  4376. function _uploadFiles() {
  4377. _uploadFiles = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3(params, callback) {
  4378. var self, SliceSize, TotalSize, TotalFinish, onTotalProgress, unFinishCount, _onTotalFileFinish, resultList, onTotalFileFinish, taskList, getTaskList;
  4379. return _regeneratorRuntime().wrap(function _callee3$(_context3) {
  4380. while (1) switch (_context3.prev = _context3.next) {
  4381. case 0:
  4382. self = this; // 判断多大的文件使用分片上传
  4383. SliceSize = params.SliceSize === undefined ? self.options.SliceSize : params.SliceSize; // 汇总返回进度
  4384. TotalSize = 0;
  4385. TotalFinish = 0;
  4386. onTotalProgress = util.throttleOnProgress.call(self, TotalFinish, params.onProgress); // 汇总返回回调
  4387. unFinishCount = params.files.length;
  4388. _onTotalFileFinish = params.onFileFinish;
  4389. resultList = Array(unFinishCount);
  4390. onTotalFileFinish = function onTotalFileFinish(err, data, options) {
  4391. onTotalProgress(null, true);
  4392. _onTotalFileFinish && _onTotalFileFinish(err, data, options);
  4393. resultList[options.Index] = {
  4394. options: options,
  4395. error: err,
  4396. data: data
  4397. };
  4398. if (--unFinishCount <= 0 && callback) {
  4399. callback(null, {
  4400. files: resultList
  4401. });
  4402. }
  4403. }; // 开始处理每个文件
  4404. taskList = [];
  4405. getTaskList = function getTaskList() {
  4406. return params.files.map(function (fileParams, index) {
  4407. return new Promise( /*#__PURE__*/function () {
  4408. var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(resolve) {
  4409. var FileSize, fileInfo, accelerate, realApi, _onTaskReady, PreAddSize, _onProgress, _onFileFinish, onFileFinish, simpleUploadMethod, api;
  4410. return _regeneratorRuntime().wrap(function _callee2$(_context2) {
  4411. while (1) switch (_context2.prev = _context2.next) {
  4412. case 0:
  4413. FileSize = 0;
  4414. _context2.prev = 1;
  4415. _context2.next = 4;
  4416. return util.getFileSizeByPath(fileParams.FilePath);
  4417. case 4:
  4418. FileSize = _context2.sent;
  4419. _context2.next = 9;
  4420. break;
  4421. case 7:
  4422. _context2.prev = 7;
  4423. _context2.t0 = _context2["catch"](1);
  4424. case 9:
  4425. fileInfo = {
  4426. Index: index,
  4427. TaskId: ''
  4428. }; // 更新文件总大小
  4429. TotalSize += FileSize;
  4430. // 单个文件上传链路
  4431. if (self.options.EnableReporter) {
  4432. accelerate = self.options.UseAccelerate || typeof self.options.Domain === 'string' && self.options.Domain.includes('accelerate.');
  4433. realApi = FileSize > SliceSize ? 'sliceUploadFile' : 'putObject';
  4434. fileParams.tracker = new Tracker({
  4435. Beacon: self.options.BeaconReporter,
  4436. clsReporter: self.options.ClsReporter,
  4437. bucket: fileParams.Bucket,
  4438. region: fileParams.Region,
  4439. apiName: 'uploadFiles',
  4440. realApi: realApi,
  4441. fileKey: fileParams.Key,
  4442. fileSize: FileSize,
  4443. accelerate: accelerate,
  4444. deepTracker: self.options.DeepTracker,
  4445. customId: self.options.CustomId,
  4446. delay: self.options.TrackerDelay
  4447. });
  4448. }
  4449. // 整理 option,用于返回给回调
  4450. util.each(fileParams, function (v, k) {
  4451. if (_typeof(v) !== 'object' && typeof v !== 'function') {
  4452. fileInfo[k] = v;
  4453. }
  4454. });
  4455. // 处理单个文件 TaskReady
  4456. _onTaskReady = fileParams.onTaskReady;
  4457. fileParams.onTaskReady = function (tid) {
  4458. fileInfo.TaskId = tid;
  4459. _onTaskReady && _onTaskReady(tid);
  4460. };
  4461. // 处理单个文件进度
  4462. PreAddSize = 0;
  4463. _onProgress = fileParams.onProgress;
  4464. fileParams.onProgress = function (info) {
  4465. TotalFinish = TotalFinish - PreAddSize + info.loaded;
  4466. PreAddSize = info.loaded;
  4467. _onProgress && _onProgress(info);
  4468. onTotalProgress({
  4469. loaded: TotalFinish,
  4470. total: TotalSize
  4471. });
  4472. };
  4473. // 处理单个文件完成
  4474. _onFileFinish = fileParams.onFileFinish;
  4475. onFileFinish = function onFileFinish(err, data) {
  4476. // 格式化上报参数并上报
  4477. fileParams.tracker && fileParams.tracker.report(err, data);
  4478. _onFileFinish && _onFileFinish(err, data);
  4479. onTotalFileFinish && onTotalFileFinish(err, data, fileInfo);
  4480. }; // 添加上传任务
  4481. simpleUploadMethod = self.options.SimpleUploadMethod === 'postObject' ? 'postObject' : 'putObject';
  4482. api = FileSize > SliceSize ? 'sliceUploadFile' : simpleUploadMethod;
  4483. taskList.push({
  4484. api: api,
  4485. params: fileParams,
  4486. callback: onFileFinish
  4487. });
  4488. resolve(true);
  4489. case 24:
  4490. case "end":
  4491. return _context2.stop();
  4492. }
  4493. }, _callee2, null, [[1, 7]]);
  4494. }));
  4495. return function (_x5) {
  4496. return _ref.apply(this, arguments);
  4497. };
  4498. }());
  4499. });
  4500. };
  4501. _context3.next = 13;
  4502. return Promise.all(getTaskList());
  4503. case 13:
  4504. self._addTasks(taskList);
  4505. case 14:
  4506. case "end":
  4507. return _context3.stop();
  4508. }
  4509. }, _callee3, this);
  4510. }));
  4511. return _uploadFiles.apply(this, arguments);
  4512. }
  4513. function sliceCopyFile(params, callback) {
  4514. var ep = new EventProxy();
  4515. var self = this;
  4516. var Bucket = params.Bucket;
  4517. var Region = params.Region;
  4518. var Key = params.Key;
  4519. var CopySource = params.CopySource;
  4520. var m = util.getSourceParams.call(this, CopySource);
  4521. if (!m) {
  4522. callback({
  4523. error: 'CopySource format error'
  4524. });
  4525. return;
  4526. }
  4527. var SourceBucket = m.Bucket;
  4528. var SourceRegion = m.Region;
  4529. var SourceKey = decodeURIComponent(m.Key);
  4530. var CopySliceSize = params.CopySliceSize === undefined ? self.options.CopySliceSize : params.CopySliceSize;
  4531. CopySliceSize = Math.max(0, CopySliceSize);
  4532. var ChunkSize = params.CopyChunkSize || this.options.CopyChunkSize;
  4533. var ChunkParallel = this.options.CopyChunkParallelLimit;
  4534. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  4535. var ChunkCount = 0;
  4536. var FinishSize = 0;
  4537. var FileSize;
  4538. var _onProgress3;
  4539. var SourceResHeaders = {};
  4540. var SourceHeaders = {};
  4541. var TargetHeader = {};
  4542. // 分片复制完成,开始 multipartComplete 操作
  4543. ep.on('copy_slice_complete', function (UploadData) {
  4544. var metaHeaders = {};
  4545. util.each(params.Headers, function (val, k) {
  4546. if (k.toLowerCase().indexOf('x-cos-meta-') === 0) metaHeaders[k] = val;
  4547. });
  4548. var Parts = util.map(UploadData.PartList, function (item) {
  4549. return {
  4550. PartNumber: item.PartNumber,
  4551. ETag: item.ETag
  4552. };
  4553. });
  4554. // 完成上传的请求也做重试
  4555. Async.retry(ChunkRetryTimes, function (tryCallback) {
  4556. self.multipartComplete({
  4557. Bucket: Bucket,
  4558. Region: Region,
  4559. Key: Key,
  4560. UploadId: UploadData.UploadId,
  4561. Parts: Parts,
  4562. tracker: params.tracker,
  4563. calledBySdk: 'sliceCopyFile'
  4564. }, tryCallback);
  4565. }, function (err, data) {
  4566. session.removeUsing(UploadData.UploadId); // 标记 UploadId 没被使用了,因为复制没提供重试,所以只要出错,就是 UploadId 停用了。
  4567. if (err) {
  4568. _onProgress3(null, true);
  4569. return callback(err);
  4570. }
  4571. session.removeUploadId(UploadData.UploadId);
  4572. _onProgress3({
  4573. loaded: FileSize,
  4574. total: FileSize
  4575. }, true);
  4576. callback(null, data);
  4577. });
  4578. });
  4579. ep.on('get_copy_data_finish', function (UploadData) {
  4580. // 处理 UploadId 缓存
  4581. var uuid = session.getCopyFileId(CopySource, SourceResHeaders, ChunkSize, Bucket, Key);
  4582. uuid && session.saveUploadId(uuid, UploadData.UploadId, self.options.UploadIdCacheLimit); // 缓存 UploadId
  4583. session.setUsing(UploadData.UploadId); // 标记 UploadId 为正在使用
  4584. var needCopySlices = util.filter(UploadData.PartList, function (SliceItem) {
  4585. if (SliceItem['Uploaded']) {
  4586. FinishSize += SliceItem['PartNumber'] >= ChunkCount ? FileSize % ChunkSize || ChunkSize : ChunkSize;
  4587. }
  4588. return !SliceItem['Uploaded'];
  4589. });
  4590. Async.eachLimit(needCopySlices, ChunkParallel, function (SliceItem, asyncCallback) {
  4591. var PartNumber = SliceItem.PartNumber;
  4592. var CopySourceRange = SliceItem.CopySourceRange;
  4593. var currentSize = SliceItem.end - SliceItem.start;
  4594. var preAddSize = 0;
  4595. Async.retry(ChunkRetryTimes, function (tryCallback) {
  4596. copySliceItem.call(self, {
  4597. Bucket: Bucket,
  4598. Region: Region,
  4599. Key: Key,
  4600. CopySource: CopySource,
  4601. UploadId: UploadData.UploadId,
  4602. PartNumber: PartNumber,
  4603. CopySourceRange: CopySourceRange,
  4604. tracker: params.tracker,
  4605. calledBySdk: 'sliceCopyFile',
  4606. onProgress: function onProgress(data) {
  4607. FinishSize += data.loaded - preAddSize;
  4608. preAddSize = data.loaded;
  4609. _onProgress3({
  4610. loaded: FinishSize,
  4611. total: FileSize
  4612. });
  4613. }
  4614. }, tryCallback);
  4615. }, function (err, data) {
  4616. if (err) {
  4617. return asyncCallback(err);
  4618. }
  4619. _onProgress3({
  4620. loaded: FinishSize,
  4621. total: FileSize
  4622. });
  4623. FinishSize += currentSize - preAddSize;
  4624. SliceItem.ETag = data.ETag;
  4625. asyncCallback(err || null, data);
  4626. });
  4627. }, function (err) {
  4628. if (err) {
  4629. session.removeUsing(UploadData.UploadId); // 标记 UploadId 没被使用了,因为复制没提供重试,所以只要出错,就是 UploadId 停用了。
  4630. _onProgress3(null, true);
  4631. return callback(err);
  4632. }
  4633. ep.emit('copy_slice_complete', UploadData);
  4634. });
  4635. });
  4636. ep.on('get_chunk_size_finish', function () {
  4637. var createNewUploadId = function createNewUploadId() {
  4638. self.multipartInit({
  4639. Bucket: Bucket,
  4640. Region: Region,
  4641. Key: Key,
  4642. Headers: TargetHeader,
  4643. tracker: params.tracker,
  4644. calledBySdk: 'sliceCopyFile'
  4645. }, function (err, data) {
  4646. if (err) return callback(err);
  4647. params.UploadId = data.UploadId;
  4648. ep.emit('get_copy_data_finish', {
  4649. UploadId: params.UploadId,
  4650. PartList: params.PartList
  4651. });
  4652. });
  4653. };
  4654. // 在本地找可用的 UploadId
  4655. var uuid = session.getCopyFileId(CopySource, SourceResHeaders, ChunkSize, Bucket, Key);
  4656. var LocalUploadIdList = session.getUploadIdList(uuid);
  4657. if (!uuid || !LocalUploadIdList) return createNewUploadId();
  4658. var next = function next(index) {
  4659. // 如果本地找不到可用 UploadId,再一个个遍历校验远端
  4660. if (index >= LocalUploadIdList.length) return createNewUploadId();
  4661. var UploadId = LocalUploadIdList[index];
  4662. // 如果正在被使用,跳过
  4663. if (session.using[UploadId]) return next(index + 1);
  4664. // 判断 UploadId 是否存在线上
  4665. wholeMultipartListPart.call(self, {
  4666. Bucket: Bucket,
  4667. Region: Region,
  4668. Key: Key,
  4669. UploadId: UploadId,
  4670. tracker: params.tracker,
  4671. calledBySdk: 'sliceCopyFile'
  4672. }, function (err, PartListData) {
  4673. if (err) {
  4674. // 如果 UploadId 获取会出错,跳过并删除
  4675. session.removeUploadId(UploadId);
  4676. next(index + 1);
  4677. } else {
  4678. // 如果异步回来 UploadId 已经被用了,也跳过
  4679. if (session.using[UploadId]) return next(index + 1);
  4680. // 找到可用 UploadId
  4681. var finishETagMap = {};
  4682. var offset = 0;
  4683. util.each(PartListData.PartList, function (PartItem) {
  4684. var size = parseInt(PartItem.Size);
  4685. var end = offset + size - 1;
  4686. finishETagMap[PartItem.PartNumber + '|' + offset + '|' + end] = PartItem.ETag;
  4687. offset += size;
  4688. });
  4689. util.each(params.PartList, function (PartItem) {
  4690. var ETag = finishETagMap[PartItem.PartNumber + '|' + PartItem.start + '|' + PartItem.end];
  4691. if (ETag) {
  4692. PartItem.ETag = ETag;
  4693. PartItem.Uploaded = true;
  4694. }
  4695. });
  4696. ep.emit('get_copy_data_finish', {
  4697. UploadId: UploadId,
  4698. PartList: params.PartList
  4699. });
  4700. }
  4701. });
  4702. };
  4703. next(0);
  4704. });
  4705. ep.on('get_file_size_finish', function () {
  4706. // 控制分片大小
  4707. (function () {
  4708. var SIZE = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 1024 * 2, 1024 * 4, 1024 * 5];
  4709. var AutoChunkSize = 1024 * 1024;
  4710. for (var i = 0; i < SIZE.length; i++) {
  4711. AutoChunkSize = SIZE[i] * 1024 * 1024;
  4712. if (FileSize / AutoChunkSize <= self.options.MaxPartNumber) break;
  4713. }
  4714. params.ChunkSize = ChunkSize = Math.max(ChunkSize, AutoChunkSize);
  4715. ChunkCount = Math.ceil(FileSize / ChunkSize);
  4716. var list = [];
  4717. for (var partNumber = 1; partNumber <= ChunkCount; partNumber++) {
  4718. var start = (partNumber - 1) * ChunkSize;
  4719. var end = partNumber * ChunkSize < FileSize ? partNumber * ChunkSize - 1 : FileSize - 1;
  4720. var item = {
  4721. PartNumber: partNumber,
  4722. start: start,
  4723. end: end,
  4724. CopySourceRange: 'bytes=' + start + '-' + end
  4725. };
  4726. list.push(item);
  4727. }
  4728. params.PartList = list;
  4729. })();
  4730. var TargetHeader;
  4731. if (params.Headers['x-cos-metadata-directive'] === 'Replaced') {
  4732. TargetHeader = params.Headers;
  4733. } else {
  4734. TargetHeader = SourceHeaders;
  4735. }
  4736. TargetHeader['x-cos-storage-class'] = params.Headers['x-cos-storage-class'] || SourceHeaders['x-cos-storage-class'];
  4737. TargetHeader = util.clearKey(TargetHeader);
  4738. /**
  4739. * 对于归档存储的对象,如果未恢复副本,则不允许 Copy
  4740. */
  4741. if (SourceHeaders['x-cos-storage-class'] === 'ARCHIVE' || SourceHeaders['x-cos-storage-class'] === 'DEEP_ARCHIVE') {
  4742. var restoreHeader = SourceHeaders['x-cos-restore'];
  4743. if (!restoreHeader || restoreHeader === 'ongoing-request="true"') {
  4744. callback({
  4745. error: 'Unrestored archive object is not allowed to be copied'
  4746. });
  4747. return;
  4748. }
  4749. }
  4750. /**
  4751. * 去除一些无用的头部,规避 multipartInit 出错
  4752. * 这些头部通常是在 putObjectCopy 时才使用
  4753. */
  4754. delete TargetHeader['x-cos-copy-source'];
  4755. delete TargetHeader['x-cos-metadata-directive'];
  4756. delete TargetHeader['x-cos-copy-source-If-Modified-Since'];
  4757. delete TargetHeader['x-cos-copy-source-If-Unmodified-Since'];
  4758. delete TargetHeader['x-cos-copy-source-If-Match'];
  4759. delete TargetHeader['x-cos-copy-source-If-None-Match'];
  4760. ep.emit('get_chunk_size_finish');
  4761. });
  4762. // 获取远端复制源文件的大小
  4763. self.headObject({
  4764. Bucket: SourceBucket,
  4765. Region: SourceRegion,
  4766. Key: SourceKey,
  4767. tracker: params.tracker,
  4768. calledBySdk: 'sliceCopyFile'
  4769. }, function (err, data) {
  4770. if (err) {
  4771. if (err.statusCode && err.statusCode === 404) {
  4772. callback({
  4773. ErrorStatus: SourceKey + ' Not Exist'
  4774. });
  4775. } else {
  4776. callback(err);
  4777. }
  4778. return;
  4779. }
  4780. FileSize = params.FileSize = data.headers['content-length'];
  4781. if (FileSize === undefined || !FileSize) {
  4782. callback({
  4783. error: 'get Content-Length error, please add "Content-Length" to CORS ExposeHeader setting.'
  4784. });
  4785. return;
  4786. }
  4787. params.tracker && params.tracker.setParams({
  4788. httpSize: FileSize
  4789. });
  4790. _onProgress3 = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  4791. // 开始上传
  4792. if (FileSize <= CopySliceSize) {
  4793. if (!params.Headers['x-cos-metadata-directive']) {
  4794. params.Headers['x-cos-metadata-directive'] = 'Copy';
  4795. }
  4796. self.putObjectCopy(Object.assign(params, {
  4797. calledBySdk: 'sliceCopyFile'
  4798. }), function (err, data) {
  4799. if (err) {
  4800. _onProgress3(null, true);
  4801. return callback(err);
  4802. }
  4803. _onProgress3({
  4804. loaded: FileSize,
  4805. total: FileSize
  4806. }, true);
  4807. callback(err, data);
  4808. });
  4809. } else {
  4810. var resHeaders = data.headers;
  4811. SourceResHeaders = resHeaders;
  4812. SourceHeaders = {
  4813. 'Cache-Control': resHeaders['cache-control'],
  4814. 'Content-Disposition': resHeaders['content-disposition'],
  4815. 'Content-Encoding': resHeaders['content-encoding'],
  4816. 'Content-Type': resHeaders['content-type'],
  4817. Expires: resHeaders['expires'],
  4818. 'x-cos-storage-class': resHeaders['x-cos-storage-class']
  4819. };
  4820. util.each(resHeaders, function (v, k) {
  4821. var metaPrefix = 'x-cos-meta-';
  4822. if (k.indexOf(metaPrefix) === 0 && k.length > metaPrefix.length) {
  4823. SourceHeaders[k] = v;
  4824. }
  4825. });
  4826. ep.emit('get_file_size_finish');
  4827. }
  4828. });
  4829. }
  4830. // 复制指定分片
  4831. function copySliceItem(params, callback) {
  4832. var TaskId = params.TaskId;
  4833. var Bucket = params.Bucket;
  4834. var Region = params.Region;
  4835. var Key = params.Key;
  4836. var CopySource = params.CopySource;
  4837. var UploadId = params.UploadId;
  4838. var PartNumber = params.PartNumber * 1;
  4839. var CopySourceRange = params.CopySourceRange;
  4840. var ChunkRetryTimes = this.options.ChunkRetryTimes + 1;
  4841. var self = this;
  4842. Async.retry(ChunkRetryTimes, function (tryCallback) {
  4843. self.uploadPartCopy({
  4844. TaskId: TaskId,
  4845. Bucket: Bucket,
  4846. Region: Region,
  4847. Key: Key,
  4848. CopySource: CopySource,
  4849. UploadId: UploadId,
  4850. PartNumber: PartNumber,
  4851. CopySourceRange: CopySourceRange,
  4852. onProgress: params.onProgress,
  4853. tracker: params.tracker,
  4854. calledBySdk: params.calledBySdk
  4855. }, function (err, data) {
  4856. tryCallback(err || null, data);
  4857. });
  4858. }, function (err, data) {
  4859. return callback(err, data);
  4860. });
  4861. }
  4862. var API_MAP = {
  4863. sliceUploadFile: sliceUploadFile,
  4864. abortUploadTask: abortUploadTask,
  4865. uploadFile: uploadFile,
  4866. uploadFiles: uploadFiles,
  4867. sliceCopyFile: sliceCopyFile
  4868. };
  4869. module.exports.init = function (COS, task) {
  4870. task.transferToTaskMethod(API_MAP, 'sliceUploadFile');
  4871. util.each(API_MAP, function (fn, apiName) {
  4872. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  4873. });
  4874. };
  4875. /***/ }),
  4876. /***/ "./src/async.js":
  4877. /*!**********************!*\
  4878. !*** ./src/async.js ***!
  4879. \**********************/
  4880. /*! no static exports found */
  4881. /***/ (function(module, exports) {
  4882. var eachLimit = function eachLimit(arr, limit, iterator, callback) {
  4883. callback = callback || function () {};
  4884. if (!arr.length || limit <= 0) {
  4885. return callback();
  4886. }
  4887. var completed = 0;
  4888. var started = 0;
  4889. var running = 0;
  4890. (function replenish() {
  4891. if (completed >= arr.length) {
  4892. return callback();
  4893. }
  4894. while (running < limit && started < arr.length) {
  4895. started += 1;
  4896. running += 1;
  4897. iterator(arr[started - 1], function (err) {
  4898. if (err) {
  4899. callback(err);
  4900. callback = function callback() {};
  4901. } else {
  4902. completed += 1;
  4903. running -= 1;
  4904. if (completed >= arr.length) {
  4905. callback();
  4906. } else {
  4907. replenish();
  4908. }
  4909. }
  4910. });
  4911. }
  4912. })();
  4913. };
  4914. var retry = function retry(times, iterator, callback) {
  4915. var next = function next(index) {
  4916. iterator(function (err, data) {
  4917. if (err && index < times) {
  4918. next(index + 1);
  4919. } else {
  4920. callback(err, data);
  4921. }
  4922. });
  4923. };
  4924. if (times < 1) {
  4925. callback();
  4926. } else {
  4927. next(1);
  4928. }
  4929. };
  4930. var async = {
  4931. eachLimit: eachLimit,
  4932. retry: retry
  4933. };
  4934. module.exports = async;
  4935. /***/ }),
  4936. /***/ "./src/base.js":
  4937. /*!*********************!*\
  4938. !*** ./src/base.js ***!
  4939. \*********************/
  4940. /*! no static exports found */
  4941. /***/ (function(module, exports, __webpack_require__) {
  4942. "use strict";
  4943. var REQUEST = __webpack_require__(/*! ../lib/request */ "./lib/request.js");
  4944. var util = __webpack_require__(/*! ./util */ "./src/util.js");
  4945. var mime = __webpack_require__(/*! mime */ "./node_modules/mime/index.js");
  4946. // Bucket 相关
  4947. /**
  4948. * 获取用户的 bucket 列表
  4949. * @param {Object} params 回调函数,必须,下面为参数列表
  4950. * 无特殊参数
  4951. * @param {Function} callback 回调函数,必须
  4952. */
  4953. function getService(params, callback) {
  4954. if (typeof params === 'function') {
  4955. callback = params;
  4956. params = {};
  4957. }
  4958. var protocol = 'https:';
  4959. var domain = this.options.ServiceDomain;
  4960. var region = params.Region;
  4961. if (domain) {
  4962. domain = domain.replace(/\{\{Region\}\}/gi, region || '').replace(/\{\{.*?\}\}/gi, '');
  4963. if (!/^[a-zA-Z]+:\/\//.test(domain)) {
  4964. domain = protocol + '//' + domain;
  4965. }
  4966. if (domain.slice(-1) === '/') {
  4967. domain = domain.slice(0, -1);
  4968. }
  4969. } else if (region) {
  4970. domain = protocol + '//cos.' + region + '.myqcloud.com';
  4971. } else {
  4972. domain = protocol + '//service.cos.myqcloud.com';
  4973. }
  4974. var SignHost = '';
  4975. var standardHost = region ? 'cos.' + region + '.myqcloud.com' : 'service.cos.myqcloud.com';
  4976. var urlHost = domain.replace(/^https?:\/\/([^/]+)(\/.*)?$/, '$1');
  4977. if (standardHost === urlHost) SignHost = standardHost;
  4978. submitRequest.call(this, {
  4979. Action: 'name/cos:GetService',
  4980. url: domain,
  4981. method: 'GET',
  4982. headers: params.Headers,
  4983. tracker: params.tracker
  4984. }, function (err, data) {
  4985. if (err) return callback(err);
  4986. var buckets = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Buckets && data.ListAllMyBucketsResult.Buckets.Bucket || [];
  4987. buckets = util.isArray(buckets) ? buckets : [buckets];
  4988. var owner = data && data.ListAllMyBucketsResult && data.ListAllMyBucketsResult.Owner || {};
  4989. callback(null, {
  4990. Buckets: buckets,
  4991. Owner: owner,
  4992. statusCode: data.statusCode,
  4993. headers: data.headers
  4994. });
  4995. });
  4996. }
  4997. /**
  4998. * 创建 Bucket,并初始化访问权限
  4999. * @param {Object} params 参数对象,必须
  5000. * @param {String} params.Bucket Bucket名称,必须
  5001. * @param {String} params.Region 地域名称,必须
  5002. * @param {String} params.ACL 用户自定义文件权限,可以设置:private,public-read;默认值:private,非必须
  5003. * @param {String} params.GrantRead 赋予被授权者读的权限,格式x-cos-grant-read: uin=" ",uin=" ",非必须
  5004. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式x-cos-grant-write: uin=" ",uin=" ",非必须
  5005. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式x-cos-grant-full-control: uin=" ",uin=" ",非必须
  5006. * @param {Function} callback 回调函数,必须
  5007. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5008. * @return {Object} data 返回的数据
  5009. * @return {String} data.Location 操作地址
  5010. */
  5011. function putBucket(params, callback) {
  5012. var self = this;
  5013. var xml = '';
  5014. if (params['BucketAZConfig']) {
  5015. var CreateBucketConfiguration = {
  5016. BucketAZConfig: params.BucketAZConfig
  5017. };
  5018. xml = util.json2xml({
  5019. CreateBucketConfiguration: CreateBucketConfiguration
  5020. });
  5021. }
  5022. submitRequest.call(this, {
  5023. Action: 'name/cos:PutBucket',
  5024. method: 'PUT',
  5025. Bucket: params.Bucket,
  5026. Region: params.Region,
  5027. headers: params.Headers,
  5028. body: xml,
  5029. tracker: params.tracker
  5030. }, function (err, data) {
  5031. if (err) return callback(err);
  5032. var url = getUrl({
  5033. protocol: self.options.Protocol,
  5034. domain: self.options.Domain,
  5035. bucket: params.Bucket,
  5036. region: params.Region,
  5037. isLocation: true
  5038. });
  5039. callback(null, {
  5040. Location: url,
  5041. statusCode: data.statusCode,
  5042. headers: data.headers
  5043. });
  5044. });
  5045. }
  5046. /**
  5047. * 查看是否存在该Bucket,是否有权限访问
  5048. * @param {Object} params 参数对象,必须
  5049. * @param {String} params.Bucket Bucket名称,必须
  5050. * @param {String} params.Region 地域名称,必须
  5051. * @param {Function} callback 回调函数,必须
  5052. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5053. * @return {Object} data 返回的数据
  5054. * @return {Boolean} data.BucketExist Bucket是否存在
  5055. * @return {Boolean} data.BucketAuth 是否有 Bucket 的访问权限
  5056. */
  5057. function headBucket(params, callback) {
  5058. submitRequest.call(this, {
  5059. Action: 'name/cos:HeadBucket',
  5060. Bucket: params.Bucket,
  5061. Region: params.Region,
  5062. headers: params.Headers,
  5063. method: 'HEAD',
  5064. tracker: params.tracker
  5065. }, function (err, data) {
  5066. callback(err, data);
  5067. });
  5068. }
  5069. /**
  5070. * 获取 Bucket 下的 object 列表
  5071. * @param {Object} params 参数对象,必须
  5072. * @param {String} params.Bucket Bucket名称,必须
  5073. * @param {String} params.Region 地域名称,必须
  5074. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  5075. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,非必须
  5076. * @param {String} params.Marker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  5077. * @param {String} params.MaxKeys 单次返回最大的条目数量,默认1000,非必须
  5078. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  5079. * @param {Function} callback 回调函数,必须
  5080. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5081. * @return {Object} data 返回的数据
  5082. * @return {Object} data.ListBucketResult 返回的 object 列表信息
  5083. */
  5084. function getBucket(params, callback) {
  5085. var reqParams = {};
  5086. reqParams['prefix'] = params['Prefix'] || '';
  5087. reqParams['delimiter'] = params['Delimiter'];
  5088. reqParams['marker'] = params['Marker'];
  5089. reqParams['max-keys'] = params['MaxKeys'];
  5090. reqParams['encoding-type'] = params['EncodingType'];
  5091. submitRequest.call(this, {
  5092. Action: 'name/cos:GetBucket',
  5093. ResourceKey: reqParams['prefix'],
  5094. method: 'GET',
  5095. Bucket: params.Bucket,
  5096. Region: params.Region,
  5097. headers: params.Headers,
  5098. qs: reqParams,
  5099. tracker: params.tracker
  5100. }, function (err, data) {
  5101. if (err) return callback(err);
  5102. var ListBucketResult = data.ListBucketResult || {};
  5103. var Contents = ListBucketResult.Contents || [];
  5104. var CommonPrefixes = ListBucketResult.CommonPrefixes || [];
  5105. Contents = util.isArray(Contents) ? Contents : [Contents];
  5106. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  5107. var result = util.clone(ListBucketResult);
  5108. util.extend(result, {
  5109. Contents: Contents,
  5110. CommonPrefixes: CommonPrefixes,
  5111. statusCode: data.statusCode,
  5112. headers: data.headers
  5113. });
  5114. callback(null, result);
  5115. });
  5116. }
  5117. /**
  5118. * 删除 Bucket
  5119. * @param {Object} params 参数对象,必须
  5120. * @param {String} params.Bucket Bucket名称,必须
  5121. * @param {String} params.Region 地域名称,必须
  5122. * @param {Function} callback 回调函数,必须
  5123. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5124. * @return {Object} data 返回的数据
  5125. * @return {String} data.Location 操作地址
  5126. */
  5127. function deleteBucket(params, callback) {
  5128. submitRequest.call(this, {
  5129. Action: 'name/cos:DeleteBucket',
  5130. Bucket: params.Bucket,
  5131. Region: params.Region,
  5132. headers: params.Headers,
  5133. method: 'DELETE',
  5134. tracker: params.tracker
  5135. }, function (err, data) {
  5136. if (err && err.statusCode === 204) {
  5137. return callback(null, {
  5138. statusCode: err.statusCode
  5139. });
  5140. } else if (err) {
  5141. return callback(err);
  5142. }
  5143. callback(null, {
  5144. statusCode: data.statusCode,
  5145. headers: data.headers
  5146. });
  5147. });
  5148. }
  5149. /**
  5150. * 设置 Bucket 的 权限列表
  5151. * @param {Object} params 参数对象,必须
  5152. * @param {String} params.Bucket Bucket名称,必须
  5153. * @param {String} params.Region 地域名称,必须
  5154. * @param {String} params.ACL 用户自定义文件权限,可以设置:private,public-read;默认值:private,非必须
  5155. * @param {String} params.GrantRead 赋予被授权者读的权限,格式x-cos-grant-read: uin=" ",uin=" ",非必须
  5156. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式x-cos-grant-write: uin=" ",uin=" ",非必须
  5157. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式x-cos-grant-full-control: uin=" ",uin=" ",非必须
  5158. * @param {Function} callback 回调函数,必须
  5159. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5160. * @return {Object} data 返回的数据
  5161. */
  5162. function putBucketAcl(params, callback) {
  5163. var headers = params.Headers;
  5164. var xml = '';
  5165. if (params['AccessControlPolicy']) {
  5166. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  5167. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  5168. Grants = util.isArray(Grants) ? Grants : [Grants];
  5169. delete AccessControlPolicy.Grant;
  5170. delete AccessControlPolicy.Grants;
  5171. AccessControlPolicy.AccessControlList = {
  5172. Grant: Grants
  5173. };
  5174. xml = util.json2xml({
  5175. AccessControlPolicy: AccessControlPolicy
  5176. });
  5177. headers['Content-Type'] = 'application/xml';
  5178. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5179. }
  5180. // Grant Header 去重
  5181. util.each(headers, function (val, key) {
  5182. if (key.indexOf('x-cos-grant-') === 0) {
  5183. headers[key] = uniqGrant(headers[key]);
  5184. }
  5185. });
  5186. submitRequest.call(this, {
  5187. Action: 'name/cos:PutBucketACL',
  5188. method: 'PUT',
  5189. Bucket: params.Bucket,
  5190. Region: params.Region,
  5191. headers: headers,
  5192. action: 'acl',
  5193. body: xml,
  5194. tracker: params.tracker
  5195. }, function (err, data) {
  5196. if (err) return callback(err);
  5197. callback(null, {
  5198. statusCode: data.statusCode,
  5199. headers: data.headers
  5200. });
  5201. });
  5202. }
  5203. /**
  5204. * 获取 Bucket 的 权限列表
  5205. * @param {Object} params 参数对象,必须
  5206. * @param {String} params.Bucket Bucket名称,必须
  5207. * @param {String} params.Region 地域名称,必须
  5208. * @param {Function} callback 回调函数,必须
  5209. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5210. * @return {Object} data 返回的数据
  5211. * @return {Object} data.AccessControlPolicy 访问权限信息
  5212. */
  5213. function getBucketAcl(params, callback) {
  5214. submitRequest.call(this, {
  5215. Action: 'name/cos:GetBucketACL',
  5216. method: 'GET',
  5217. Bucket: params.Bucket,
  5218. Region: params.Region,
  5219. headers: params.Headers,
  5220. action: 'acl',
  5221. tracker: params.tracker
  5222. }, function (err, data) {
  5223. if (err) return callback(err);
  5224. var AccessControlPolicy = data.AccessControlPolicy || {};
  5225. var Owner = AccessControlPolicy.Owner || {};
  5226. var Grant = AccessControlPolicy.AccessControlList.Grant || [];
  5227. Grant = util.isArray(Grant) ? Grant : [Grant];
  5228. var result = decodeAcl(AccessControlPolicy);
  5229. if (data.headers && data.headers['x-cos-acl']) {
  5230. result.ACL = data.headers['x-cos-acl'];
  5231. }
  5232. result = util.extend(result, {
  5233. Owner: Owner,
  5234. Grants: Grant,
  5235. statusCode: data.statusCode,
  5236. headers: data.headers
  5237. });
  5238. callback(null, result);
  5239. });
  5240. }
  5241. /**
  5242. * 设置 Bucket 的 跨域设置
  5243. * @param {Object} params 参数对象,必须
  5244. * @param {String} params.Bucket Bucket名称,必须
  5245. * @param {String} params.Region 地域名称,必须
  5246. * @param {Object} params.CORSConfiguration 相关的跨域设置,必须
  5247. * @param {Array} params.CORSConfiguration.CORSRules 对应的跨域规则
  5248. * @param {Function} callback 回调函数,必须
  5249. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5250. * @return {Object} data 返回的数据
  5251. */
  5252. function putBucketCors(params, callback) {
  5253. var CORSConfiguration = params['CORSConfiguration'] || {};
  5254. var CORSRules = CORSConfiguration['CORSRules'] || params['CORSRules'] || [];
  5255. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  5256. util.each(CORSRules, function (rule) {
  5257. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {
  5258. var sKey = key + 's';
  5259. var val = rule[sKey] || rule[key] || [];
  5260. delete rule[sKey];
  5261. rule[key] = util.isArray(val) ? val : [val];
  5262. });
  5263. });
  5264. var Conf = {
  5265. CORSRule: CORSRules
  5266. };
  5267. if (params.ResponseVary) Conf.ResponseVary = params.ResponseVary;
  5268. var xml = util.json2xml({
  5269. CORSConfiguration: Conf
  5270. });
  5271. var headers = params.Headers;
  5272. headers['Content-Type'] = 'application/xml';
  5273. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5274. submitRequest.call(this, {
  5275. Action: 'name/cos:PutBucketCORS',
  5276. method: 'PUT',
  5277. Bucket: params.Bucket,
  5278. Region: params.Region,
  5279. body: xml,
  5280. action: 'cors',
  5281. headers: headers,
  5282. tracker: params.tracker
  5283. }, function (err, data) {
  5284. if (err) return callback(err);
  5285. callback(null, {
  5286. statusCode: data.statusCode,
  5287. headers: data.headers
  5288. });
  5289. });
  5290. }
  5291. /**
  5292. * 获取 Bucket 的 跨域设置
  5293. * @param {Object} params 参数对象,必须
  5294. * @param {String} params.Bucket Bucket名称,必须
  5295. * @param {String} params.Region 地域名称,必须
  5296. * @param {Function} callback 回调函数,必须
  5297. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5298. * @return {Object} data 返回的数据
  5299. * @return {Object} data.CORSRules Bucket的跨域设置
  5300. */
  5301. function getBucketCors(params, callback) {
  5302. submitRequest.call(this, {
  5303. Action: 'name/cos:GetBucketCORS',
  5304. method: 'GET',
  5305. Bucket: params.Bucket,
  5306. Region: params.Region,
  5307. headers: params.Headers,
  5308. action: 'cors',
  5309. tracker: params.tracker
  5310. }, function (err, data) {
  5311. if (err) {
  5312. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchCORSConfiguration') {
  5313. var result = {
  5314. CORSRules: [],
  5315. statusCode: err.statusCode
  5316. };
  5317. err.headers && (result.headers = err.headers);
  5318. callback(null, result);
  5319. } else {
  5320. callback(err);
  5321. }
  5322. return;
  5323. }
  5324. var CORSConfiguration = data.CORSConfiguration || {};
  5325. var CORSRules = CORSConfiguration.CORSRules || CORSConfiguration.CORSRule || [];
  5326. CORSRules = util.clone(util.isArray(CORSRules) ? CORSRules : [CORSRules]);
  5327. var ResponseVary = CORSConfiguration.ResponseVary;
  5328. util.each(CORSRules, function (rule) {
  5329. util.each(['AllowedOrigin', 'AllowedHeader', 'AllowedMethod', 'ExposeHeader'], function (key) {
  5330. var sKey = key + 's';
  5331. var val = rule[sKey] || rule[key] || [];
  5332. delete rule[key];
  5333. rule[sKey] = util.isArray(val) ? val : [val];
  5334. });
  5335. });
  5336. callback(null, {
  5337. CORSRules: CORSRules,
  5338. ResponseVary: ResponseVary,
  5339. statusCode: data.statusCode,
  5340. headers: data.headers
  5341. });
  5342. });
  5343. }
  5344. /**
  5345. * 删除 Bucket 的 跨域设置
  5346. * @param {Object} params 参数对象,必须
  5347. * @param {String} params.Bucket Bucket名称,必须
  5348. * @param {String} params.Region 地域名称,必须
  5349. * @param {Function} callback 回调函数,必须
  5350. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5351. * @return {Object} data 返回的数据
  5352. */
  5353. function deleteBucketCors(params, callback) {
  5354. submitRequest.call(this, {
  5355. Action: 'name/cos:DeleteBucketCORS',
  5356. method: 'DELETE',
  5357. Bucket: params.Bucket,
  5358. Region: params.Region,
  5359. headers: params.Headers,
  5360. action: 'cors',
  5361. tracker: params.tracker
  5362. }, function (err, data) {
  5363. if (err && err.statusCode === 204) {
  5364. return callback(null, {
  5365. statusCode: err.statusCode
  5366. });
  5367. } else if (err) {
  5368. return callback(err);
  5369. }
  5370. callback(null, {
  5371. statusCode: data.statusCode || err.statusCode,
  5372. headers: data.headers
  5373. });
  5374. });
  5375. }
  5376. /**
  5377. * 获取 Bucket 的 地域信息
  5378. * @param {Object} params 参数对象,必须
  5379. * @param {String} params.Bucket Bucket名称,必须
  5380. * @param {String} params.Region 地域名称,必须
  5381. * @param {Function} callback 回调函数,必须
  5382. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5383. * @return {Object} data 返回数据,包含地域信息 LocationConstraint
  5384. */
  5385. function getBucketLocation(params, callback) {
  5386. submitRequest.call(this, {
  5387. Action: 'name/cos:GetBucketLocation',
  5388. method: 'GET',
  5389. Bucket: params.Bucket,
  5390. Region: params.Region,
  5391. headers: params.Headers,
  5392. action: 'location',
  5393. tracker: params.tracker
  5394. }, function (err, data) {
  5395. if (err) return callback(err);
  5396. callback(null, data);
  5397. });
  5398. }
  5399. function putBucketPolicy(params, callback) {
  5400. var Policy = params['Policy'];
  5401. var PolicyStr = Policy;
  5402. try {
  5403. if (typeof Policy === 'string') {
  5404. Policy = JSON.parse(PolicyStr);
  5405. } else {
  5406. PolicyStr = JSON.stringify(Policy);
  5407. }
  5408. } catch (e) {
  5409. callback({
  5410. error: 'Policy format error'
  5411. });
  5412. }
  5413. var headers = params.Headers;
  5414. headers['Content-Type'] = 'application/json';
  5415. headers['Content-MD5'] = util.binaryBase64(util.md5(PolicyStr));
  5416. submitRequest.call(this, {
  5417. Action: 'name/cos:PutBucketPolicy',
  5418. method: 'PUT',
  5419. Bucket: params.Bucket,
  5420. Region: params.Region,
  5421. action: 'policy',
  5422. body: PolicyStr,
  5423. headers: headers,
  5424. json: true,
  5425. tracker: params.tracker
  5426. }, function (err, data) {
  5427. if (err && err.statusCode === 204) {
  5428. return callback(null, {
  5429. statusCode: err.statusCode
  5430. });
  5431. } else if (err) {
  5432. return callback(err);
  5433. }
  5434. callback(null, {
  5435. statusCode: data.statusCode,
  5436. headers: data.headers
  5437. });
  5438. });
  5439. }
  5440. /**
  5441. * 获取 Bucket 的读取权限策略
  5442. * @param {Object} params 参数对象,必须
  5443. * @param {String} params.Bucket Bucket名称,必须
  5444. * @param {String} params.Region 地域名称,必须
  5445. * @param {Function} callback 回调函数,必须
  5446. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5447. * @return {Object} data 返回数据
  5448. */
  5449. function getBucketPolicy(params, callback) {
  5450. submitRequest.call(this, {
  5451. Action: 'name/cos:GetBucketPolicy',
  5452. method: 'GET',
  5453. Bucket: params.Bucket,
  5454. Region: params.Region,
  5455. headers: params.Headers,
  5456. action: 'policy',
  5457. rawBody: true,
  5458. tracker: params.tracker
  5459. }, function (err, data) {
  5460. if (err) {
  5461. if (err.statusCode && err.statusCode === 403) {
  5462. return callback({
  5463. ErrorStatus: 'Access Denied'
  5464. });
  5465. }
  5466. if (err.statusCode && err.statusCode === 405) {
  5467. return callback({
  5468. ErrorStatus: 'Method Not Allowed'
  5469. });
  5470. }
  5471. if (err.statusCode && err.statusCode === 404) {
  5472. return callback({
  5473. ErrorStatus: 'Policy Not Found'
  5474. });
  5475. }
  5476. return callback(err);
  5477. }
  5478. var Policy = {};
  5479. try {
  5480. Policy = JSON.parse(data.body);
  5481. } catch (e) {}
  5482. callback(null, {
  5483. Policy: Policy,
  5484. statusCode: data.statusCode,
  5485. headers: data.headers
  5486. });
  5487. });
  5488. }
  5489. /**
  5490. * 删除 Bucket 的 跨域设置
  5491. * @param {Object} params 参数对象,必须
  5492. * @param {String} params.Bucket Bucket名称,必须
  5493. * @param {String} params.Region 地域名称,必须
  5494. * @param {Function} callback 回调函数,必须
  5495. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5496. * @return {Object} data 返回的数据
  5497. */
  5498. function deleteBucketPolicy(params, callback) {
  5499. submitRequest.call(this, {
  5500. Action: 'name/cos:DeleteBucketPolicy',
  5501. method: 'DELETE',
  5502. Bucket: params.Bucket,
  5503. Region: params.Region,
  5504. headers: params.Headers,
  5505. action: 'policy',
  5506. tracker: params.tracker
  5507. }, function (err, data) {
  5508. if (err && err.statusCode === 204) {
  5509. return callback(null, {
  5510. statusCode: err.statusCode
  5511. });
  5512. } else if (err) {
  5513. return callback(err);
  5514. }
  5515. callback(null, {
  5516. statusCode: data.statusCode || err.statusCode,
  5517. headers: data.headers
  5518. });
  5519. });
  5520. }
  5521. /**
  5522. * 设置 Bucket 的标签
  5523. * @param {Object} params 参数对象,必须
  5524. * @param {String} params.Bucket Bucket名称,必须
  5525. * @param {String} params.Region 地域名称,必须
  5526. * @param {Array} params.TagSet 标签设置,必须
  5527. * @param {Function} callback 回调函数,必须
  5528. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5529. * @return {Object} data 返回数据
  5530. */
  5531. function putBucketTagging(params, callback) {
  5532. var Tagging = params['Tagging'] || {};
  5533. var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];
  5534. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  5535. var xml = util.json2xml({
  5536. Tagging: {
  5537. TagSet: {
  5538. Tag: Tags
  5539. }
  5540. }
  5541. });
  5542. var headers = params.Headers;
  5543. headers['Content-Type'] = 'application/xml';
  5544. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5545. submitRequest.call(this, {
  5546. Action: 'name/cos:PutBucketTagging',
  5547. method: 'PUT',
  5548. Bucket: params.Bucket,
  5549. Region: params.Region,
  5550. body: xml,
  5551. action: 'tagging',
  5552. headers: headers,
  5553. tracker: params.tracker
  5554. }, function (err, data) {
  5555. if (err && err.statusCode === 204) {
  5556. return callback(null, {
  5557. statusCode: err.statusCode
  5558. });
  5559. } else if (err) {
  5560. return callback(err);
  5561. }
  5562. callback(null, {
  5563. statusCode: data.statusCode,
  5564. headers: data.headers
  5565. });
  5566. });
  5567. }
  5568. /**
  5569. * 获取 Bucket 的标签设置
  5570. * @param {Object} params 参数对象,必须
  5571. * @param {String} params.Bucket Bucket名称,必须
  5572. * @param {String} params.Region 地域名称,必须
  5573. * @param {Function} callback 回调函数,必须
  5574. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5575. * @return {Object} data 返回数据
  5576. */
  5577. function getBucketTagging(params, callback) {
  5578. submitRequest.call(this, {
  5579. Action: 'name/cos:GetBucketTagging',
  5580. method: 'GET',
  5581. Bucket: params.Bucket,
  5582. Region: params.Region,
  5583. headers: params.Headers,
  5584. action: 'tagging',
  5585. tracker: params.tracker
  5586. }, function (err, data) {
  5587. if (err) {
  5588. if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'NoSuchTagSet')) {
  5589. var result = {
  5590. Tags: [],
  5591. statusCode: err.statusCode
  5592. };
  5593. err.headers && (result.headers = err.headers);
  5594. callback(null, result);
  5595. } else {
  5596. callback(err);
  5597. }
  5598. return;
  5599. }
  5600. var Tags = [];
  5601. try {
  5602. Tags = data.Tagging.TagSet.Tag || [];
  5603. } catch (e) {}
  5604. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  5605. callback(null, {
  5606. Tags: Tags,
  5607. statusCode: data.statusCode,
  5608. headers: data.headers
  5609. });
  5610. });
  5611. }
  5612. /**
  5613. * 删除 Bucket 的 标签设置
  5614. * @param {Object} params 参数对象,必须
  5615. * @param {String} params.Bucket Bucket名称,必须
  5616. * @param {String} params.Region 地域名称,必须
  5617. * @param {Function} callback 回调函数,必须
  5618. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5619. * @return {Object} data 返回的数据
  5620. */
  5621. function deleteBucketTagging(params, callback) {
  5622. submitRequest.call(this, {
  5623. Action: 'name/cos:DeleteBucketTagging',
  5624. method: 'DELETE',
  5625. Bucket: params.Bucket,
  5626. Region: params.Region,
  5627. headers: params.Headers,
  5628. action: 'tagging',
  5629. tracker: params.tracker
  5630. }, function (err, data) {
  5631. if (err && err.statusCode === 204) {
  5632. return callback(null, {
  5633. statusCode: err.statusCode
  5634. });
  5635. } else if (err) {
  5636. return callback(err);
  5637. }
  5638. callback(null, {
  5639. statusCode: data.statusCode,
  5640. headers: data.headers
  5641. });
  5642. });
  5643. }
  5644. function putBucketLifecycle(params, callback) {
  5645. var LifecycleConfiguration = params['LifecycleConfiguration'] || {};
  5646. var Rules = LifecycleConfiguration.Rules || params.Rules || [];
  5647. Rules = util.clone(Rules);
  5648. var xml = util.json2xml({
  5649. LifecycleConfiguration: {
  5650. Rule: Rules
  5651. }
  5652. });
  5653. var headers = params.Headers;
  5654. headers['Content-Type'] = 'application/xml';
  5655. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5656. submitRequest.call(this, {
  5657. Action: 'name/cos:PutBucketLifecycle',
  5658. method: 'PUT',
  5659. Bucket: params.Bucket,
  5660. Region: params.Region,
  5661. body: xml,
  5662. action: 'lifecycle',
  5663. headers: headers,
  5664. tracker: params.tracker
  5665. }, function (err, data) {
  5666. if (err && err.statusCode === 204) {
  5667. return callback(null, {
  5668. statusCode: err.statusCode
  5669. });
  5670. } else if (err) {
  5671. return callback(err);
  5672. }
  5673. callback(null, {
  5674. statusCode: data.statusCode,
  5675. headers: data.headers
  5676. });
  5677. });
  5678. }
  5679. function getBucketLifecycle(params, callback) {
  5680. submitRequest.call(this, {
  5681. Action: 'name/cos:GetBucketLifecycle',
  5682. method: 'GET',
  5683. Bucket: params.Bucket,
  5684. Region: params.Region,
  5685. headers: params.Headers,
  5686. action: 'lifecycle',
  5687. tracker: params.tracker
  5688. }, function (err, data) {
  5689. if (err) {
  5690. if (err.statusCode === 404 && err.error && err.error.Code === 'NoSuchLifecycleConfiguration') {
  5691. var result = {
  5692. Rules: [],
  5693. statusCode: err.statusCode
  5694. };
  5695. err.headers && (result.headers = err.headers);
  5696. callback(null, result);
  5697. } else {
  5698. callback(err);
  5699. }
  5700. return;
  5701. }
  5702. var Rules = [];
  5703. try {
  5704. Rules = data.LifecycleConfiguration.Rule || [];
  5705. } catch (e) {}
  5706. Rules = util.clone(util.isArray(Rules) ? Rules : [Rules]);
  5707. callback(null, {
  5708. Rules: Rules,
  5709. statusCode: data.statusCode,
  5710. headers: data.headers
  5711. });
  5712. });
  5713. }
  5714. function deleteBucketLifecycle(params, callback) {
  5715. submitRequest.call(this, {
  5716. Action: 'name/cos:DeleteBucketLifecycle',
  5717. method: 'DELETE',
  5718. Bucket: params.Bucket,
  5719. Region: params.Region,
  5720. headers: params.Headers,
  5721. action: 'lifecycle',
  5722. tracker: params.tracker
  5723. }, function (err, data) {
  5724. if (err && err.statusCode === 204) {
  5725. return callback(null, {
  5726. statusCode: err.statusCode
  5727. });
  5728. } else if (err) {
  5729. return callback(err);
  5730. }
  5731. callback(null, {
  5732. statusCode: data.statusCode,
  5733. headers: data.headers
  5734. });
  5735. });
  5736. }
  5737. function putBucketVersioning(params, callback) {
  5738. if (!params['VersioningConfiguration']) {
  5739. callback({
  5740. error: 'missing param VersioningConfiguration'
  5741. });
  5742. return;
  5743. }
  5744. var VersioningConfiguration = params['VersioningConfiguration'] || {};
  5745. var xml = util.json2xml({
  5746. VersioningConfiguration: VersioningConfiguration
  5747. });
  5748. var headers = params.Headers;
  5749. headers['Content-Type'] = 'application/xml';
  5750. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5751. submitRequest.call(this, {
  5752. Action: 'name/cos:PutBucketVersioning',
  5753. method: 'PUT',
  5754. Bucket: params.Bucket,
  5755. Region: params.Region,
  5756. body: xml,
  5757. action: 'versioning',
  5758. headers: headers,
  5759. tracker: params.tracker
  5760. }, function (err, data) {
  5761. if (err && err.statusCode === 204) {
  5762. return callback(null, {
  5763. statusCode: err.statusCode
  5764. });
  5765. } else if (err) {
  5766. return callback(err);
  5767. }
  5768. callback(null, {
  5769. statusCode: data.statusCode,
  5770. headers: data.headers
  5771. });
  5772. });
  5773. }
  5774. function getBucketVersioning(params, callback) {
  5775. submitRequest.call(this, {
  5776. Action: 'name/cos:GetBucketVersioning',
  5777. method: 'GET',
  5778. Bucket: params.Bucket,
  5779. Region: params.Region,
  5780. headers: params.Headers,
  5781. action: 'versioning',
  5782. tracker: params.tracker
  5783. }, function (err, data) {
  5784. if (!err) {
  5785. !data.VersioningConfiguration && (data.VersioningConfiguration = {});
  5786. }
  5787. callback(err, data);
  5788. });
  5789. }
  5790. function putBucketReplication(params, callback) {
  5791. var ReplicationConfiguration = util.clone(params.ReplicationConfiguration);
  5792. var xml = util.json2xml({
  5793. ReplicationConfiguration: ReplicationConfiguration
  5794. });
  5795. xml = xml.replace(/<(\/?)Rules>/gi, '<$1Rule>');
  5796. xml = xml.replace(/<(\/?)Tags>/gi, '<$1Tag>');
  5797. var headers = params.Headers;
  5798. headers['Content-Type'] = 'application/xml';
  5799. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5800. submitRequest.call(this, {
  5801. Action: 'name/cos:PutBucketReplication',
  5802. method: 'PUT',
  5803. Bucket: params.Bucket,
  5804. Region: params.Region,
  5805. body: xml,
  5806. action: 'replication',
  5807. headers: headers,
  5808. tracker: params.tracker
  5809. }, function (err, data) {
  5810. if (err && err.statusCode === 204) {
  5811. return callback(null, {
  5812. statusCode: err.statusCode
  5813. });
  5814. } else if (err) {
  5815. return callback(err);
  5816. }
  5817. callback(null, {
  5818. statusCode: data.statusCode,
  5819. headers: data.headers
  5820. });
  5821. });
  5822. }
  5823. function getBucketReplication(params, callback) {
  5824. submitRequest.call(this, {
  5825. Action: 'name/cos:GetBucketReplication',
  5826. method: 'GET',
  5827. Bucket: params.Bucket,
  5828. Region: params.Region,
  5829. headers: params.Headers,
  5830. action: 'replication',
  5831. tracker: params.tracker
  5832. }, function (err, data) {
  5833. if (err) {
  5834. if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'ReplicationConfigurationnotFoundError')) {
  5835. var result = {
  5836. ReplicationConfiguration: {
  5837. Rules: []
  5838. },
  5839. statusCode: err.statusCode
  5840. };
  5841. err.headers && (result.headers = err.headers);
  5842. callback(null, result);
  5843. } else {
  5844. callback(err);
  5845. }
  5846. return;
  5847. }
  5848. if (!err) {
  5849. !data.ReplicationConfiguration && (data.ReplicationConfiguration = {});
  5850. }
  5851. if (data.ReplicationConfiguration.Rule) {
  5852. data.ReplicationConfiguration.Rules = data.ReplicationConfiguration.Rule;
  5853. delete data.ReplicationConfiguration.Rule;
  5854. }
  5855. callback(err, data);
  5856. });
  5857. }
  5858. function deleteBucketReplication(params, callback) {
  5859. submitRequest.call(this, {
  5860. Action: 'name/cos:DeleteBucketReplication',
  5861. method: 'DELETE',
  5862. Bucket: params.Bucket,
  5863. Region: params.Region,
  5864. headers: params.Headers,
  5865. action: 'replication',
  5866. tracker: params.tracker
  5867. }, function (err, data) {
  5868. if (err && err.statusCode === 204) {
  5869. return callback(null, {
  5870. statusCode: err.statusCode
  5871. });
  5872. } else if (err) {
  5873. return callback(err);
  5874. }
  5875. callback(null, {
  5876. statusCode: data.statusCode,
  5877. headers: data.headers
  5878. });
  5879. });
  5880. }
  5881. /**
  5882. * 设置 Bucket 静态网站配置信息
  5883. * @param {Object} params 参数对象,必须
  5884. * @param {String} params.Bucket Bucket名称,必须
  5885. * @param {String} params.Region 地域名称,必须
  5886. * @param {Object} params.WebsiteConfiguration 地域名称,必须
  5887. * @param {Object} WebsiteConfiguration.IndexDocument 索引文档,必须
  5888. * @param {Object} WebsiteConfiguration.ErrorDocument 错误文档,非必须
  5889. * @param {Object} WebsiteConfiguration.RedirectAllRequestsTo 重定向所有请求,非必须
  5890. * @param {Array} params.RoutingRules 重定向规则,非必须
  5891. * @param {Function} callback 回调函数,必须
  5892. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5893. * @return {Object} data 返回数据
  5894. */
  5895. function putBucketWebsite(params, callback) {
  5896. if (!params['WebsiteConfiguration']) {
  5897. callback({
  5898. error: 'missing param WebsiteConfiguration'
  5899. });
  5900. return;
  5901. }
  5902. var WebsiteConfiguration = util.clone(params['WebsiteConfiguration'] || {});
  5903. var RoutingRules = WebsiteConfiguration['RoutingRules'] || WebsiteConfiguration['RoutingRule'] || [];
  5904. RoutingRules = util.isArray(RoutingRules) ? RoutingRules : [RoutingRules];
  5905. delete WebsiteConfiguration.RoutingRule;
  5906. delete WebsiteConfiguration.RoutingRules;
  5907. if (RoutingRules.length) WebsiteConfiguration.RoutingRules = {
  5908. RoutingRule: RoutingRules
  5909. };
  5910. var xml = util.json2xml({
  5911. WebsiteConfiguration: WebsiteConfiguration
  5912. });
  5913. var headers = params.Headers;
  5914. headers['Content-Type'] = 'application/xml';
  5915. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  5916. submitRequest.call(this, {
  5917. Action: 'name/cos:PutBucketWebsite',
  5918. method: 'PUT',
  5919. Bucket: params.Bucket,
  5920. Region: params.Region,
  5921. body: xml,
  5922. action: 'website',
  5923. headers: headers,
  5924. tracker: params.tracker
  5925. }, function (err, data) {
  5926. if (err && err.statusCode === 204) {
  5927. return callback(null, {
  5928. statusCode: err.statusCode
  5929. });
  5930. } else if (err) {
  5931. return callback(err);
  5932. }
  5933. callback(null, {
  5934. statusCode: data.statusCode,
  5935. headers: data.headers
  5936. });
  5937. });
  5938. }
  5939. /**
  5940. * 获取 Bucket 的静态网站配置信息
  5941. * @param {Object} params 参数对象,必须
  5942. * @param {String} params.Bucket Bucket名称,必须
  5943. * @param {String} params.Region 地域名称,必须
  5944. * @param {Function} callback 回调函数,必须
  5945. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5946. * @return {Object} data 返回数据
  5947. */
  5948. function getBucketWebsite(params, callback) {
  5949. submitRequest.call(this, {
  5950. Action: 'name/cos:GetBucketWebsite',
  5951. method: 'GET',
  5952. Bucket: params.Bucket,
  5953. Region: params.Region,
  5954. Key: params.Key,
  5955. headers: params.Headers,
  5956. action: 'website',
  5957. tracker: params.tracker
  5958. }, function (err, data) {
  5959. if (err) {
  5960. if (err.statusCode === 404 && err.error.Code === 'NoSuchWebsiteConfiguration') {
  5961. var result = {
  5962. WebsiteConfiguration: {},
  5963. statusCode: err.statusCode
  5964. };
  5965. err.headers && (result.headers = err.headers);
  5966. callback(null, result);
  5967. } else {
  5968. callback(err);
  5969. }
  5970. return;
  5971. }
  5972. var WebsiteConfiguration = data.WebsiteConfiguration || {};
  5973. if (WebsiteConfiguration['RoutingRules']) {
  5974. var RoutingRules = util.clone(WebsiteConfiguration['RoutingRules'].RoutingRule || []);
  5975. RoutingRules = util.makeArray(RoutingRules);
  5976. WebsiteConfiguration.RoutingRules = RoutingRules;
  5977. }
  5978. callback(null, {
  5979. WebsiteConfiguration: WebsiteConfiguration,
  5980. statusCode: data.statusCode,
  5981. headers: data.headers
  5982. });
  5983. });
  5984. }
  5985. /**
  5986. * 删除 Bucket 的静态网站配置
  5987. * @param {Object} params 参数对象,必须
  5988. * @param {String} params.Bucket Bucket名称,必须
  5989. * @param {String} params.Region 地域名称,必须
  5990. * @param {Function} callback 回调函数,必须
  5991. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  5992. * @return {Object} data 返回数据
  5993. */
  5994. function deleteBucketWebsite(params, callback) {
  5995. submitRequest.call(this, {
  5996. Action: 'name/cos:DeleteBucketWebsite',
  5997. method: 'DELETE',
  5998. Bucket: params.Bucket,
  5999. Region: params.Region,
  6000. headers: params.Headers,
  6001. action: 'website',
  6002. tracker: params.tracker
  6003. }, function (err, data) {
  6004. if (err && err.statusCode === 204) {
  6005. return callback(null, {
  6006. statusCode: err.statusCode
  6007. });
  6008. } else if (err) {
  6009. return callback(err);
  6010. }
  6011. callback(null, {
  6012. statusCode: data.statusCode,
  6013. headers: data.headers
  6014. });
  6015. });
  6016. }
  6017. /**
  6018. * 设置 Bucket 的防盗链白名单或者黑名单
  6019. * @param {Object} params 参数对象,必须
  6020. * @param {String} params.Bucket Bucket名称,必须
  6021. * @param {String} params.Region 地域名称,必须
  6022. * @param {Object} params.RefererConfiguration 地域名称,必须
  6023. * @param {String} RefererConfiguration.Status 是否开启防盗链,枚举值:Enabled、Disabled
  6024. * @param {String} RefererConfiguration.RefererType 防盗链类型,枚举值:Black-List、White-List,必须
  6025. * @param {Array} RefererConfiguration.DomianList.Domain 生效域名,必须
  6026. * @param {String} RefererConfiguration.EmptyReferConfiguration ,非必须
  6027. * @param {Function} callback 回调函数,必须
  6028. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6029. * @return {Object} data 返回数据
  6030. */
  6031. function putBucketReferer(params, callback) {
  6032. if (!params['RefererConfiguration']) {
  6033. callback({
  6034. error: 'missing param RefererConfiguration'
  6035. });
  6036. return;
  6037. }
  6038. var RefererConfiguration = util.clone(params['RefererConfiguration'] || {});
  6039. var DomainList = RefererConfiguration['DomainList'] || {};
  6040. var Domains = DomainList['Domains'] || DomainList['Domain'] || [];
  6041. Domains = util.isArray(Domains) ? Domains : [Domains];
  6042. if (Domains.length) RefererConfiguration.DomainList = {
  6043. Domain: Domains
  6044. };
  6045. var xml = util.json2xml({
  6046. RefererConfiguration: RefererConfiguration
  6047. });
  6048. var headers = params.Headers;
  6049. headers['Content-Type'] = 'application/xml';
  6050. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6051. submitRequest.call(this, {
  6052. Action: 'name/cos:PutBucketReferer',
  6053. method: 'PUT',
  6054. Bucket: params.Bucket,
  6055. Region: params.Region,
  6056. body: xml,
  6057. action: 'referer',
  6058. headers: headers,
  6059. tracker: params.tracker
  6060. }, function (err, data) {
  6061. if (err && err.statusCode === 204) {
  6062. return callback(null, {
  6063. statusCode: err.statusCode
  6064. });
  6065. } else if (err) {
  6066. return callback(err);
  6067. }
  6068. callback(null, {
  6069. statusCode: data.statusCode,
  6070. headers: data.headers
  6071. });
  6072. });
  6073. }
  6074. /**
  6075. * 获取 Bucket 的防盗链白名单或者黑名单
  6076. * @param {Object} params 参数对象,必须
  6077. * @param {String} params.Bucket Bucket名称,必须
  6078. * @param {String} params.Region 地域名称,必须
  6079. * @param {Function} callback 回调函数,必须
  6080. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6081. * @return {Object} data 返回数据
  6082. */
  6083. function getBucketReferer(params, callback) {
  6084. submitRequest.call(this, {
  6085. Action: 'name/cos:GetBucketReferer',
  6086. method: 'GET',
  6087. Bucket: params.Bucket,
  6088. Region: params.Region,
  6089. Key: params.Key,
  6090. headers: params.Headers,
  6091. action: 'referer',
  6092. tracker: params.tracker
  6093. }, function (err, data) {
  6094. if (err) {
  6095. if (err.statusCode === 404 && err.error.Code === 'NoSuchRefererConfiguration') {
  6096. var result = {
  6097. WebsiteConfiguration: {},
  6098. statusCode: err.statusCode
  6099. };
  6100. err.headers && (result.headers = err.headers);
  6101. callback(null, result);
  6102. } else {
  6103. callback(err);
  6104. }
  6105. return;
  6106. }
  6107. var RefererConfiguration = data.RefererConfiguration || {};
  6108. if (RefererConfiguration['DomainList']) {
  6109. var Domains = util.makeArray(RefererConfiguration['DomainList'].Domain || []);
  6110. RefererConfiguration.DomainList = {
  6111. Domains: Domains
  6112. };
  6113. }
  6114. callback(null, {
  6115. RefererConfiguration: RefererConfiguration,
  6116. statusCode: data.statusCode,
  6117. headers: data.headers
  6118. });
  6119. });
  6120. }
  6121. /**
  6122. * 设置 Bucket 自定义域名
  6123. * @param {Object} params 参数对象,必须
  6124. * @param {String} params.Bucket Bucket名称,必须
  6125. * @param {String} params.Region 地域名称,必须
  6126. * @param {Function} callback 回调函数,必须
  6127. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6128. * @return {Object} data 返回数据
  6129. */
  6130. function putBucketDomain(params, callback) {
  6131. var DomainConfiguration = params['DomainConfiguration'] || {};
  6132. var DomainRule = DomainConfiguration.DomainRule || params.DomainRule || [];
  6133. DomainRule = util.clone(DomainRule);
  6134. var xml = util.json2xml({
  6135. DomainConfiguration: {
  6136. DomainRule: DomainRule
  6137. }
  6138. });
  6139. var headers = params.Headers;
  6140. headers['Content-Type'] = 'application/xml';
  6141. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6142. submitRequest.call(this, {
  6143. Action: 'name/cos:PutBucketDomain',
  6144. method: 'PUT',
  6145. Bucket: params.Bucket,
  6146. Region: params.Region,
  6147. body: xml,
  6148. action: 'domain',
  6149. headers: headers,
  6150. tracker: params.tracker
  6151. }, function (err, data) {
  6152. if (err && err.statusCode === 204) {
  6153. return callback(null, {
  6154. statusCode: err.statusCode
  6155. });
  6156. } else if (err) {
  6157. return callback(err);
  6158. }
  6159. callback(null, {
  6160. statusCode: data.statusCode,
  6161. headers: data.headers
  6162. });
  6163. });
  6164. }
  6165. /**
  6166. * 获取 Bucket 的自定义域名
  6167. * @param {Object} params 参数对象,必须
  6168. * @param {String} params.Bucket Bucket名称,必须
  6169. * @param {String} params.Region 地域名称,必须
  6170. * @param {Function} callback 回调函数,必须
  6171. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6172. * @return {Object} data 返回数据
  6173. */
  6174. function getBucketDomain(params, callback) {
  6175. submitRequest.call(this, {
  6176. Action: 'name/cos:GetBucketDomain',
  6177. method: 'GET',
  6178. Bucket: params.Bucket,
  6179. Region: params.Region,
  6180. headers: params.Headers,
  6181. action: 'domain',
  6182. tracker: params.tracker
  6183. }, function (err, data) {
  6184. if (err) return callback(err);
  6185. var DomainRule = [];
  6186. try {
  6187. DomainRule = data.DomainConfiguration.DomainRule || [];
  6188. } catch (e) {}
  6189. DomainRule = util.clone(util.isArray(DomainRule) ? DomainRule : [DomainRule]);
  6190. callback(null, {
  6191. DomainRule: DomainRule,
  6192. statusCode: data.statusCode,
  6193. headers: data.headers
  6194. });
  6195. });
  6196. }
  6197. /**
  6198. * 删除 Bucket 自定义域名
  6199. * @param {Object} params 参数对象,必须
  6200. * @param {String} params.Bucket Bucket名称,必须
  6201. * @param {String} params.Region 地域名称,必须
  6202. * @param {Function} callback 回调函数,必须
  6203. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6204. * @return {Object} data 返回数据
  6205. */
  6206. function deleteBucketDomain(params, callback) {
  6207. submitRequest.call(this, {
  6208. Action: 'name/cos:DeleteBucketDomain',
  6209. method: 'DELETE',
  6210. Bucket: params.Bucket,
  6211. Region: params.Region,
  6212. headers: params.Headers,
  6213. action: 'domain',
  6214. tracker: params.tracker
  6215. }, function (err, data) {
  6216. if (err && err.statusCode === 204) {
  6217. return callback(null, {
  6218. statusCode: err.statusCode
  6219. });
  6220. } else if (err) {
  6221. return callback(err);
  6222. }
  6223. callback(null, {
  6224. statusCode: data.statusCode,
  6225. headers: data.headers
  6226. });
  6227. });
  6228. }
  6229. /**
  6230. * 设置 Bucket 的回源
  6231. * @param {Object} params 参数对象,必须
  6232. * @param {String} params.Bucket Bucket名称,必须
  6233. * @param {String} params.Region 地域名称,必须
  6234. * @param {Function} callback 回调函数,必须
  6235. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6236. * @return {Object} data 返回数据
  6237. */
  6238. function putBucketOrigin(params, callback) {
  6239. var OriginConfiguration = params['OriginConfiguration'] || {};
  6240. var OriginRule = OriginConfiguration.OriginRule || params.OriginRule || [];
  6241. OriginRule = util.clone(OriginRule);
  6242. var xml = util.json2xml({
  6243. OriginConfiguration: {
  6244. OriginRule: OriginRule
  6245. }
  6246. });
  6247. var headers = params.Headers;
  6248. headers['Content-Type'] = 'application/xml';
  6249. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6250. submitRequest.call(this, {
  6251. Action: 'name/cos:PutBucketOrigin',
  6252. method: 'PUT',
  6253. Bucket: params.Bucket,
  6254. Region: params.Region,
  6255. body: xml,
  6256. action: 'origin',
  6257. headers: headers,
  6258. tracker: params.tracker
  6259. }, function (err, data) {
  6260. if (err && err.statusCode === 204) {
  6261. return callback(null, {
  6262. statusCode: err.statusCode
  6263. });
  6264. } else if (err) {
  6265. return callback(err);
  6266. }
  6267. callback(null, {
  6268. statusCode: data.statusCode,
  6269. headers: data.headers
  6270. });
  6271. });
  6272. }
  6273. /**
  6274. * 获取 Bucket 的回源
  6275. * @param {Object} params 参数对象,必须
  6276. * @param {String} params.Bucket Bucket名称,必须
  6277. * @param {String} params.Region 地域名称,必须
  6278. * @param {Function} callback 回调函数,必须
  6279. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6280. * @return {Object} data 返回数据
  6281. */
  6282. function getBucketOrigin(params, callback) {
  6283. submitRequest.call(this, {
  6284. Action: 'name/cos:GetBucketOrigin',
  6285. method: 'GET',
  6286. Bucket: params.Bucket,
  6287. Region: params.Region,
  6288. headers: params.Headers,
  6289. action: 'origin',
  6290. tracker: params.tracker
  6291. }, function (err, data) {
  6292. if (err) return callback(err);
  6293. var OriginRule = [];
  6294. try {
  6295. OriginRule = data.OriginConfiguration.OriginRule || [];
  6296. } catch (e) {}
  6297. OriginRule = util.clone(util.isArray(OriginRule) ? OriginRule : [OriginRule]);
  6298. callback(null, {
  6299. OriginRule: OriginRule,
  6300. statusCode: data.statusCode,
  6301. headers: data.headers
  6302. });
  6303. });
  6304. }
  6305. /**
  6306. * 删除 Bucket 的回源
  6307. * @param {Object} params 参数对象,必须
  6308. * @param {String} params.Bucket Bucket名称,必须
  6309. * @param {String} params.Region 地域名称,必须
  6310. * @param {Function} callback 回调函数,必须
  6311. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6312. * @return {Object} data 返回数据
  6313. */
  6314. function deleteBucketOrigin(params, callback) {
  6315. submitRequest.call(this, {
  6316. Action: 'name/cos:DeleteBucketOrigin',
  6317. method: 'DELETE',
  6318. Bucket: params.Bucket,
  6319. Region: params.Region,
  6320. headers: params.Headers,
  6321. action: 'origin',
  6322. tracker: params.tracker
  6323. }, function (err, data) {
  6324. if (err && err.statusCode === 204) {
  6325. return callback(null, {
  6326. statusCode: err.statusCode
  6327. });
  6328. } else if (err) {
  6329. return callback(err);
  6330. }
  6331. callback(null, {
  6332. statusCode: data.statusCode,
  6333. headers: data.headers
  6334. });
  6335. });
  6336. }
  6337. /**
  6338. * 设置 Bucket 的日志记录
  6339. * @param {Object} params 参数对象,必须
  6340. * @param {String} params.Bucket Bucket名称,必须
  6341. * @param {String} params.Region 地域名称,必须
  6342. * @param {(Object|String)} params.BucketLoggingStatus 说明日志记录配置的状态,如果无子节点信息则意为关闭日志记录,必须
  6343. * @param {Function} callback 回调函数,必须
  6344. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6345. * @return {Object} data 返回数据
  6346. */
  6347. function putBucketLogging(params, callback) {
  6348. var xml = util.json2xml({
  6349. BucketLoggingStatus: params['BucketLoggingStatus'] || ''
  6350. });
  6351. var headers = params.Headers;
  6352. headers['Content-Type'] = 'application/xml';
  6353. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6354. submitRequest.call(this, {
  6355. Action: 'name/cos:PutBucketLogging',
  6356. method: 'PUT',
  6357. Bucket: params.Bucket,
  6358. Region: params.Region,
  6359. body: xml,
  6360. action: 'logging',
  6361. headers: headers,
  6362. tracker: params.tracker
  6363. }, function (err, data) {
  6364. if (err && err.statusCode === 204) {
  6365. return callback(null, {
  6366. statusCode: err.statusCode
  6367. });
  6368. } else if (err) {
  6369. return callback(err);
  6370. }
  6371. callback(null, {
  6372. statusCode: data.statusCode,
  6373. headers: data.headers
  6374. });
  6375. });
  6376. }
  6377. /**
  6378. * 获取 Bucket 的日志记录
  6379. * @param {Object} params 参数对象,必须
  6380. * @param {String} params.Bucket Bucket名称,必须
  6381. * @param {String} params.Region 地域名称,必须
  6382. * @param {Function} callback 回调函数,必须
  6383. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6384. * @return {Object} data 返回数据
  6385. */
  6386. function getBucketLogging(params, callback) {
  6387. submitRequest.call(this, {
  6388. Action: 'name/cos:GetBucketLogging',
  6389. method: 'GET',
  6390. Bucket: params.Bucket,
  6391. Region: params.Region,
  6392. headers: params.Headers,
  6393. action: 'logging',
  6394. tracker: params.tracker
  6395. }, function (err, data) {
  6396. if (err) return callback(err);
  6397. delete data.BucketLoggingStatus._xmlns;
  6398. callback(null, {
  6399. BucketLoggingStatus: data.BucketLoggingStatus,
  6400. statusCode: data.statusCode,
  6401. headers: data.headers
  6402. });
  6403. });
  6404. }
  6405. /**
  6406. * 创建/编辑 Bucket 的清单任务
  6407. * @param {Object} params 参数对象,必须
  6408. * @param {String} params.Bucket Bucket名称,必须
  6409. * @param {String} params.Region 地域名称,必须
  6410. * @param {String} params.Id 清单任务的名称,必须
  6411. * @param {Object} params.InventoryConfiguration 包含清单的配置参数,必须
  6412. * @param {Function} callback 回调函数,必须
  6413. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6414. * @return {Object} data 返回数据
  6415. */
  6416. function putBucketInventory(params, callback) {
  6417. var InventoryConfiguration = util.clone(params['InventoryConfiguration']);
  6418. if (InventoryConfiguration.OptionalFields) {
  6419. var Field = InventoryConfiguration.OptionalFields || [];
  6420. InventoryConfiguration.OptionalFields = {
  6421. Field: Field
  6422. };
  6423. }
  6424. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  6425. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  6426. if (Object.keys(Encryption).indexOf('SSECOS') > -1) {
  6427. Encryption['SSE-COS'] = Encryption['SSECOS'];
  6428. delete Encryption['SSECOS'];
  6429. }
  6430. }
  6431. var xml = util.json2xml({
  6432. InventoryConfiguration: InventoryConfiguration
  6433. });
  6434. var headers = params.Headers;
  6435. headers['Content-Type'] = 'application/xml';
  6436. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6437. submitRequest.call(this, {
  6438. Action: 'name/cos:PutBucketInventory',
  6439. method: 'PUT',
  6440. Bucket: params.Bucket,
  6441. Region: params.Region,
  6442. body: xml,
  6443. action: 'inventory',
  6444. qs: {
  6445. id: params['Id']
  6446. },
  6447. headers: headers,
  6448. tracker: params.tracker
  6449. }, function (err, data) {
  6450. if (err && err.statusCode === 204) {
  6451. return callback(null, {
  6452. statusCode: err.statusCode
  6453. });
  6454. } else if (err) {
  6455. return callback(err);
  6456. }
  6457. callback(null, {
  6458. statusCode: data.statusCode,
  6459. headers: data.headers
  6460. });
  6461. });
  6462. }
  6463. /**
  6464. * 获取 Bucket 的清单任务信息
  6465. * @param {Object} params 参数对象,必须
  6466. * @param {String} params.Bucket Bucket名称,必须
  6467. * @param {String} params.Region 地域名称,必须
  6468. * @param {String} params.Id 清单任务的名称,必须
  6469. * @param {Function} callback 回调函数,必须
  6470. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6471. * @return {Object} data 返回数据
  6472. */
  6473. function getBucketInventory(params, callback) {
  6474. submitRequest.call(this, {
  6475. Action: 'name/cos:GetBucketInventory',
  6476. method: 'GET',
  6477. Bucket: params.Bucket,
  6478. Region: params.Region,
  6479. headers: params.Headers,
  6480. action: 'inventory',
  6481. qs: {
  6482. id: params['Id']
  6483. },
  6484. tracker: params.tracker
  6485. }, function (err, data) {
  6486. if (err) return callback(err);
  6487. var InventoryConfiguration = data['InventoryConfiguration'];
  6488. if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {
  6489. var Field = InventoryConfiguration.OptionalFields.Field;
  6490. if (!util.isArray(Field)) {
  6491. Field = [Field];
  6492. }
  6493. InventoryConfiguration.OptionalFields = Field;
  6494. }
  6495. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  6496. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  6497. if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {
  6498. Encryption['SSECOS'] = Encryption['SSE-COS'];
  6499. delete Encryption['SSE-COS'];
  6500. }
  6501. }
  6502. callback(null, {
  6503. InventoryConfiguration: InventoryConfiguration,
  6504. statusCode: data.statusCode,
  6505. headers: data.headers
  6506. });
  6507. });
  6508. }
  6509. /**
  6510. * 获取 Bucket 的清单任务信息
  6511. * @param {Object} params 参数对象,必须
  6512. * @param {String} params.Bucket Bucket名称,必须
  6513. * @param {String} params.Region 地域名称,必须
  6514. * @param {String} params.ContinuationToken 当 COS 响应体中 IsTruncated 为 true,且 NextContinuationToken 节点中存在参数值时,您可以将这个参数作为 continuation-token 参数值,以获取下一页的清单任务信息,非必须
  6515. * @param {Function} callback 回调函数,必须
  6516. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6517. * @return {Object} data 返回数据
  6518. */
  6519. function listBucketInventory(params, callback) {
  6520. submitRequest.call(this, {
  6521. Action: 'name/cos:ListBucketInventory',
  6522. method: 'GET',
  6523. Bucket: params.Bucket,
  6524. Region: params.Region,
  6525. headers: params.Headers,
  6526. action: 'inventory',
  6527. qs: {
  6528. 'continuation-token': params['ContinuationToken']
  6529. },
  6530. tracker: params.tracker
  6531. }, function (err, data) {
  6532. if (err) return callback(err);
  6533. var ListInventoryConfigurationResult = data['ListInventoryConfigurationResult'];
  6534. var InventoryConfigurations = ListInventoryConfigurationResult.InventoryConfiguration || [];
  6535. InventoryConfigurations = util.isArray(InventoryConfigurations) ? InventoryConfigurations : [InventoryConfigurations];
  6536. delete ListInventoryConfigurationResult['InventoryConfiguration'];
  6537. util.each(InventoryConfigurations, function (InventoryConfiguration) {
  6538. if (InventoryConfiguration && InventoryConfiguration.OptionalFields && InventoryConfiguration.OptionalFields.Field) {
  6539. var Field = InventoryConfiguration.OptionalFields.Field;
  6540. if (!util.isArray(Field)) {
  6541. Field = [Field];
  6542. }
  6543. InventoryConfiguration.OptionalFields = Field;
  6544. }
  6545. if (InventoryConfiguration.Destination && InventoryConfiguration.Destination.COSBucketDestination && InventoryConfiguration.Destination.COSBucketDestination.Encryption) {
  6546. var Encryption = InventoryConfiguration.Destination.COSBucketDestination.Encryption;
  6547. if (Object.keys(Encryption).indexOf('SSE-COS') > -1) {
  6548. Encryption['SSECOS'] = Encryption['SSE-COS'];
  6549. delete Encryption['SSE-COS'];
  6550. }
  6551. }
  6552. });
  6553. ListInventoryConfigurationResult.InventoryConfigurations = InventoryConfigurations;
  6554. util.extend(ListInventoryConfigurationResult, {
  6555. statusCode: data.statusCode,
  6556. headers: data.headers
  6557. });
  6558. callback(null, ListInventoryConfigurationResult);
  6559. });
  6560. }
  6561. /**
  6562. * 删除 Bucket 的清单任务
  6563. * @param {Object} params 参数对象,必须
  6564. * @param {String} params.Bucket Bucket名称,必须
  6565. * @param {String} params.Region 地域名称,必须
  6566. * @param {String} params.Id 清单任务的名称,必须
  6567. * @param {Function} callback 回调函数,必须
  6568. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6569. * @return {Object} data 返回数据
  6570. */
  6571. function deleteBucketInventory(params, callback) {
  6572. submitRequest.call(this, {
  6573. Action: 'name/cos:DeleteBucketInventory',
  6574. method: 'DELETE',
  6575. Bucket: params.Bucket,
  6576. Region: params.Region,
  6577. headers: params.Headers,
  6578. action: 'inventory',
  6579. qs: {
  6580. id: params['Id']
  6581. },
  6582. tracker: params.tracker
  6583. }, function (err, data) {
  6584. if (err && err.statusCode === 204) {
  6585. return callback(null, {
  6586. statusCode: err.statusCode
  6587. });
  6588. } else if (err) {
  6589. return callback(err);
  6590. }
  6591. callback(null, {
  6592. statusCode: data.statusCode,
  6593. headers: data.headers
  6594. });
  6595. });
  6596. }
  6597. /* 全球加速 */
  6598. function putBucketAccelerate(params, callback) {
  6599. if (!params['AccelerateConfiguration']) {
  6600. callback({
  6601. error: 'missing param AccelerateConfiguration'
  6602. });
  6603. return;
  6604. }
  6605. var configuration = {
  6606. AccelerateConfiguration: params.AccelerateConfiguration || {}
  6607. };
  6608. var xml = util.json2xml(configuration);
  6609. var headers = {};
  6610. headers['Content-Type'] = 'application/xml';
  6611. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  6612. submitRequest.call(this, {
  6613. Interface: 'putBucketAccelerate',
  6614. Action: 'name/cos:PutBucketAccelerate',
  6615. method: 'PUT',
  6616. Bucket: params.Bucket,
  6617. Region: params.Region,
  6618. body: xml,
  6619. action: 'accelerate',
  6620. headers: headers,
  6621. tracker: params.tracker
  6622. }, function (err, data) {
  6623. if (err) return callback(err);
  6624. callback(null, {
  6625. statusCode: data.statusCode,
  6626. headers: data.headers
  6627. });
  6628. });
  6629. }
  6630. function getBucketAccelerate(params, callback) {
  6631. submitRequest.call(this, {
  6632. Interface: 'getBucketAccelerate',
  6633. Action: 'name/cos:GetBucketAccelerate',
  6634. method: 'GET',
  6635. Bucket: params.Bucket,
  6636. Region: params.Region,
  6637. action: 'accelerate',
  6638. tracker: params.tracker
  6639. }, function (err, data) {
  6640. if (!err) {
  6641. !data.AccelerateConfiguration && (data.AccelerateConfiguration = {});
  6642. }
  6643. callback(err, data);
  6644. });
  6645. }
  6646. // Object 相关
  6647. /**
  6648. * 取回对应Object的元数据,Head的权限与Get的权限一致
  6649. * @param {Object} params 参数对象,必须
  6650. * @param {String} params.Bucket Bucket名称,必须
  6651. * @param {String} params.Region 地域名称,必须
  6652. * @param {String} params.Key 文件名称,必须
  6653. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  6654. * @param {Function} callback 回调函数,必须
  6655. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6656. * @return {Object} data 为指定 object 的元数据,如果设置了 IfModifiedSince ,且文件未修改,则返回一个对象,NotModified 属性为 true
  6657. * @return {Boolean} data.NotModified 是否在 IfModifiedSince 时间点之后未修改该 object,则为 true
  6658. */
  6659. function headObject(params, callback) {
  6660. submitRequest.call(this, {
  6661. Action: 'name/cos:HeadObject',
  6662. method: 'HEAD',
  6663. Bucket: params.Bucket,
  6664. Region: params.Region,
  6665. Key: params.Key,
  6666. VersionId: params.VersionId,
  6667. headers: params.Headers,
  6668. tracker: params.tracker
  6669. }, function (err, data) {
  6670. if (err) {
  6671. var statusCode = err.statusCode;
  6672. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  6673. return callback(null, {
  6674. NotModified: true,
  6675. statusCode: statusCode
  6676. });
  6677. }
  6678. return callback(err);
  6679. }
  6680. data.ETag = util.attr(data.headers, 'etag', '');
  6681. callback(null, data);
  6682. });
  6683. }
  6684. function listObjectVersions(params, callback) {
  6685. var reqParams = {};
  6686. reqParams['prefix'] = params['Prefix'] || '';
  6687. reqParams['delimiter'] = params['Delimiter'];
  6688. reqParams['key-marker'] = params['KeyMarker'];
  6689. reqParams['version-id-marker'] = params['VersionIdMarker'];
  6690. reqParams['max-keys'] = params['MaxKeys'];
  6691. reqParams['encoding-type'] = params['EncodingType'];
  6692. submitRequest.call(this, {
  6693. Action: 'name/cos:GetBucketObjectVersions',
  6694. ResourceKey: reqParams['prefix'],
  6695. method: 'GET',
  6696. Bucket: params.Bucket,
  6697. Region: params.Region,
  6698. headers: params.Headers,
  6699. qs: reqParams,
  6700. action: 'versions',
  6701. tracker: params.tracker
  6702. }, function (err, data) {
  6703. if (err) return callback(err);
  6704. var ListVersionsResult = data.ListVersionsResult || {};
  6705. var DeleteMarkers = ListVersionsResult.DeleteMarker || [];
  6706. DeleteMarkers = util.isArray(DeleteMarkers) ? DeleteMarkers : [DeleteMarkers];
  6707. var Versions = ListVersionsResult.Version || [];
  6708. Versions = util.isArray(Versions) ? Versions : [Versions];
  6709. var result = util.clone(ListVersionsResult);
  6710. delete result.DeleteMarker;
  6711. delete result.Version;
  6712. util.extend(result, {
  6713. DeleteMarkers: DeleteMarkers,
  6714. Versions: Versions,
  6715. statusCode: data.statusCode,
  6716. headers: data.headers
  6717. });
  6718. callback(null, result);
  6719. });
  6720. }
  6721. /**
  6722. * 下载 object
  6723. * @param {Object} params 参数对象,必须
  6724. * @param {String} params.Bucket Bucket名称,必须
  6725. * @param {String} params.Region 地域名称,必须
  6726. * @param {String} params.Key 文件名称,必须
  6727. * @param {WriteStream} params.Output 文件写入流,非必须
  6728. * @param {String} params.IfModifiedSince 当Object在指定时间后被修改,则返回对应Object元信息,否则返回304,非必须
  6729. * @param {String} params.IfUnmodifiedSince 如果文件修改时间早于或等于指定时间,才返回文件内容。否则返回 412 (precondition failed),非必须
  6730. * @param {String} params.IfMatch 当 ETag 与指定的内容一致,才返回文件。否则返回 412 (precondition failed),非必须
  6731. * @param {String} params.IfNoneMatch 当 ETag 与指定的内容不一致,才返回文件。否则返回304 (not modified),非必须
  6732. * @param {String} params.ResponseContentType 设置返回头部中的 Content-Type 参数,非必须
  6733. * @param {String} params.ResponseContentLanguage 设置返回头部中的 Content-Language 参数,非必须
  6734. * @param {String} params.ResponseExpires 设置返回头部中的 Content-Expires 参数,非必须
  6735. * @param {String} params.ResponseCacheControl 设置返回头部中的 Cache-Control 参数,非必须
  6736. * @param {String} params.ResponseContentDisposition 设置返回头部中的 Content-Disposition 参数,非必须
  6737. * @param {String} params.ResponseContentEncoding 设置返回头部中的 Content-Encoding 参数,非必须
  6738. * @param {Function} callback 回调函数,必须
  6739. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6740. * @param {Object} data 为对应的 object 数据,包括 body 和 headers
  6741. */
  6742. function getObject(params, callback) {
  6743. if (this.options.ObjectKeySimplifyCheck) {
  6744. // getObject 的 Key 需要校验,避免调用成 getBucket
  6745. var formatKey = util.simplifyPath(params.Key);
  6746. if (formatKey === '/') {
  6747. callback(util.error(new Error('The Getobject Key is illegal')));
  6748. return;
  6749. }
  6750. }
  6751. var reqParams = params.Query || {};
  6752. var reqParamsStr = params.QueryString || '';
  6753. var tracker = params.tracker;
  6754. tracker && tracker.setParams({
  6755. signStartTime: new Date().getTime()
  6756. });
  6757. reqParams['response-content-type'] = params['ResponseContentType'];
  6758. reqParams['response-content-language'] = params['ResponseContentLanguage'];
  6759. reqParams['response-expires'] = params['ResponseExpires'];
  6760. reqParams['response-cache-control'] = params['ResponseCacheControl'];
  6761. reqParams['response-content-disposition'] = params['ResponseContentDisposition'];
  6762. reqParams['response-content-encoding'] = params['ResponseContentEncoding'];
  6763. // 如果用户自己传入了 output
  6764. submitRequest.call(this, {
  6765. Action: 'name/cos:GetObject',
  6766. method: 'GET',
  6767. Bucket: params.Bucket,
  6768. Region: params.Region,
  6769. Key: params.Key,
  6770. VersionId: params.VersionId,
  6771. headers: params.Headers,
  6772. qs: reqParams,
  6773. qsStr: reqParamsStr,
  6774. rawBody: true,
  6775. dataType: params.DataType,
  6776. tracker: tracker
  6777. }, function (err, data) {
  6778. if (err) {
  6779. var statusCode = err.statusCode;
  6780. if (params.Headers['If-Modified-Since'] && statusCode && statusCode === 304) {
  6781. return callback(null, {
  6782. NotModified: true
  6783. });
  6784. }
  6785. return callback(err);
  6786. }
  6787. callback(null, {
  6788. Body: data.body,
  6789. ETag: util.attr(data.headers, 'etag', ''),
  6790. statusCode: data.statusCode,
  6791. headers: data.headers
  6792. });
  6793. });
  6794. }
  6795. /**
  6796. * 上传 object
  6797. * @param {Object} params 参数对象,必须
  6798. * @param {String} params.Bucket Bucket名称,必须
  6799. * @param {String} params.Region 地域名称,必须
  6800. * @param {String} params.Key 文件名称,必须
  6801. * @param {String} params.Body 上传文件的内容,只支持字符串
  6802. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  6803. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存,非必须
  6804. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  6805. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),必须
  6806. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  6807. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  6808. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  6809. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须
  6810. * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须
  6811. * @param {String} params.GrantRead 赋予被授权者读的权限,格式 x-cos-grant-read: uin=" ",uin=" ",非必须
  6812. * @param {String} params.GrantWrite 赋予被授权者写的权限,格式 x-cos-grant-write: uin=" ",uin=" ",非必须
  6813. * @param {String} params.GrantFullControl 赋予被授权者读写权限,格式 x-cos-grant-full-control: uin=" ",uin=" ",非必须
  6814. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  6815. * @param {Function} params.onProgress 上传进度回调函数
  6816. * @param {Function} callback 回调函数,必须
  6817. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6818. * @return {Object} data 为对应的 object 数据
  6819. * @return {String} data.ETag 为对应上传文件的 ETag 值
  6820. */
  6821. function putObject(params, callback) {
  6822. var self = this;
  6823. var FileSize = params.ContentLength;
  6824. var onProgress = util.throttleOnProgress.call(self, FileSize, params.onProgress);
  6825. // 特殊处理 Cache-Control、Content-Type,避免代理更改这两个字段导致写入到 Object 属性里
  6826. var headers = params.Headers;
  6827. if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';
  6828. if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = mime.getType(params.Key) || 'application/octet-stream';
  6829. var needCalcMd5 = params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5 || self.options.UploadCheckContentMd5;
  6830. var tracker = params.tracker;
  6831. needCalcMd5 && tracker && tracker.setParams({
  6832. md5StartTime: new Date().getTime()
  6833. });
  6834. util.getBodyMd5(needCalcMd5, params.Body, function (md5) {
  6835. if (md5) {
  6836. tracker && tracker.setParams({
  6837. md5EndTime: new Date().getTime()
  6838. });
  6839. if (self.options.UploadCheckContentMd5) headers['Content-MD5'] = util.binaryBase64(md5);
  6840. if (params.UploadAddMetaMd5 || self.options.UploadAddMetaMd5) headers['x-cos-meta-md5'] = md5;
  6841. }
  6842. if (params.ContentLength !== undefined) headers['Content-Length'] = params.ContentLength;
  6843. onProgress(null, true); // 任务状态开始 uploading
  6844. submitRequest.call(self, {
  6845. Action: 'name/cos:PutObject',
  6846. TaskId: params.TaskId,
  6847. method: 'PUT',
  6848. Bucket: params.Bucket,
  6849. Region: params.Region,
  6850. Key: params.Key,
  6851. headers: params.Headers,
  6852. qs: params.Query,
  6853. body: params.Body,
  6854. onProgress: onProgress,
  6855. tracker: tracker
  6856. }, function (err, data) {
  6857. if (err) {
  6858. onProgress(null, true);
  6859. return callback(err);
  6860. }
  6861. onProgress({
  6862. loaded: FileSize,
  6863. total: FileSize
  6864. }, true);
  6865. var url = getUrl({
  6866. ForcePathStyle: self.options.ForcePathStyle,
  6867. protocol: self.options.Protocol,
  6868. domain: self.options.Domain,
  6869. bucket: params.Bucket,
  6870. region: !self.options.UseAccelerate ? params.Region : 'accelerate',
  6871. object: params.Key
  6872. });
  6873. url = url.substr(url.indexOf('://') + 3);
  6874. data.Location = url;
  6875. data.ETag = util.attr(data.headers, 'etag', '');
  6876. callback(null, data);
  6877. });
  6878. });
  6879. }
  6880. /**
  6881. * 上传 object
  6882. * @param {Object} params 参数对象,必须
  6883. * @param {String} params.Bucket Bucket名称,必须
  6884. * @param {String} params.Region 地域名称,必须
  6885. * @param {String} params.Key 文件名称,必须
  6886. * @param {FilePath} params.FilePath 要上传的文件路径
  6887. * @param {Function} params.onProgress 上传进度回调函数
  6888. * @param {Function} callback 回调函数,必须
  6889. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6890. * @return {Object} data 为对应的 object 数据
  6891. * @return {String} data.ETag 为对应上传文件的 ETag 值
  6892. */
  6893. function postObject(params, callback) {
  6894. var self = this;
  6895. var headers = {};
  6896. var filePath = params.FilePath;
  6897. if (!filePath) {
  6898. callback({
  6899. error: 'missing param FilePath'
  6900. });
  6901. return;
  6902. }
  6903. headers['Cache-Control'] = params['CacheControl'];
  6904. headers['Content-Disposition'] = params['ContentDisposition'];
  6905. headers['Content-Encoding'] = params['ContentEncoding'];
  6906. headers['Content-MD5'] = params['ContentMD5'];
  6907. headers['Content-Length'] = params['ContentLength'];
  6908. headers['Content-Type'] = params['ContentType'];
  6909. headers['Expect'] = params['Expect'];
  6910. headers['Expires'] = params['Expires'];
  6911. headers['x-cos-acl'] = params['ACL'];
  6912. headers['x-cos-grant-read'] = params['GrantRead'];
  6913. headers['x-cos-grant-write'] = params['GrantWrite'];
  6914. headers['x-cos-grant-full-control'] = params['GrantFullControl'];
  6915. headers['x-cos-storage-class'] = params['StorageClass'];
  6916. headers['x-cos-mime-limit'] = params['MimeLimit'];
  6917. headers['x-cos-traffic-limit'] = params['TrafficLimit'];
  6918. headers['x-cos-forbid-overwrite'] = params['ForbidOverwrite'];
  6919. // SSE-C
  6920. headers['x-cos-server-side-encryption-customer-algorithm'] = params['SSECustomerAlgorithm'];
  6921. headers['x-cos-server-side-encryption-customer-key'] = params['SSECustomerKey'];
  6922. headers['x-cos-server-side-encryption-customer-key-MD5'] = params['SSECustomerKeyMD5'];
  6923. // SSE-COS、SSE-KMS
  6924. headers['x-cos-server-side-encryption'] = params['ServerSideEncryption'];
  6925. headers['x-cos-server-side-encryption-cos-kms-key-id'] = params['SSEKMSKeyId'];
  6926. headers['x-cos-server-side-encryption-context'] = params['SSEContext'];
  6927. // 删除 Content-Length 避免签名错误
  6928. delete headers['Content-Length'];
  6929. delete headers['content-length'];
  6930. for (var key in params) {
  6931. if (key.indexOf('x-cos-meta-') > -1) {
  6932. headers[key] = params[key];
  6933. }
  6934. }
  6935. var onProgress = util.throttleOnProgress.call(self, headers['Content-Length'], params.onProgress);
  6936. submitRequest.call(this, {
  6937. Action: 'name/cos:PostObject',
  6938. method: 'POST',
  6939. Bucket: params.Bucket,
  6940. Region: params.Region,
  6941. Key: params.Key,
  6942. headers: headers,
  6943. qs: params.Query,
  6944. filePath: filePath,
  6945. TaskId: params.TaskId,
  6946. onProgress: onProgress,
  6947. tracker: params.tracker
  6948. }, function (err, data) {
  6949. onProgress(null, true);
  6950. if (err) return callback(err);
  6951. if (data && data.headers) {
  6952. var headers = data.headers;
  6953. var ETag = headers.etag || headers.Etag || headers.ETag || '';
  6954. var filename = filePath.substr(filePath.lastIndexOf('/') + 1);
  6955. var url = getUrl({
  6956. ForcePathStyle: self.options.ForcePathStyle,
  6957. protocol: self.options.Protocol,
  6958. domain: self.options.Domain,
  6959. bucket: params.Bucket,
  6960. region: params.Region,
  6961. object: params.Key.replace(/\$\{filename\}/g, filename),
  6962. isLocation: true
  6963. });
  6964. return callback(null, {
  6965. Location: url,
  6966. statusCode: data.statusCode,
  6967. headers: headers,
  6968. ETag: ETag
  6969. });
  6970. }
  6971. callback(null, data);
  6972. });
  6973. }
  6974. /**
  6975. * 删除 object
  6976. * @param {Object} params 参数对象,必须
  6977. * @param {String} params.Bucket Bucket名称,必须
  6978. * @param {String} params.Region 地域名称,必须
  6979. * @param {String} params.Key object名称,必须
  6980. * @param {Function} callback 回调函数,必须
  6981. * @param {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  6982. * @param {Object} data 删除操作成功之后返回的数据
  6983. */
  6984. function deleteObject(params, callback) {
  6985. submitRequest.call(this, {
  6986. Action: 'name/cos:DeleteObject',
  6987. method: 'DELETE',
  6988. Bucket: params.Bucket,
  6989. Region: params.Region,
  6990. Key: params.Key,
  6991. headers: params.Headers,
  6992. VersionId: params.VersionId,
  6993. tracker: params.tracker
  6994. }, function (err, data) {
  6995. if (err) {
  6996. var statusCode = err.statusCode;
  6997. if (statusCode && statusCode === 204) {
  6998. return callback(null, {
  6999. statusCode: statusCode
  7000. });
  7001. } else if (statusCode && statusCode === 404) {
  7002. return callback(null, {
  7003. BucketNotFound: true,
  7004. statusCode: statusCode
  7005. });
  7006. } else {
  7007. return callback(err);
  7008. }
  7009. }
  7010. callback(null, {
  7011. statusCode: data.statusCode,
  7012. headers: data.headers
  7013. });
  7014. });
  7015. }
  7016. /**
  7017. * 获取 object 的 权限列表
  7018. * @param {Object} params 参数对象,必须
  7019. * @param {String} params.Bucket Bucket名称,必须
  7020. * @param {String} params.Region 地域名称,必须
  7021. * @param {String} params.Key object名称,必须
  7022. * @param {Function} callback 回调函数,必须
  7023. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7024. * @return {Object} data 返回的数据
  7025. * @return {Object} data.AccessControlPolicy 权限列表
  7026. */
  7027. function getObjectAcl(params, callback) {
  7028. var reqParams = {};
  7029. if (params.VersionId) {
  7030. reqParams.versionId = params.VersionId;
  7031. }
  7032. submitRequest.call(this, {
  7033. Action: 'name/cos:GetObjectACL',
  7034. method: 'GET',
  7035. Bucket: params.Bucket,
  7036. Region: params.Region,
  7037. Key: params.Key,
  7038. headers: params.Headers,
  7039. qs: reqParams,
  7040. action: 'acl',
  7041. tracker: params.tracker
  7042. }, function (err, data) {
  7043. if (err) return callback(err);
  7044. var AccessControlPolicy = data.AccessControlPolicy || {};
  7045. var Owner = AccessControlPolicy.Owner || {};
  7046. var Grant = AccessControlPolicy.AccessControlList && AccessControlPolicy.AccessControlList.Grant || [];
  7047. Grant = util.isArray(Grant) ? Grant : [Grant];
  7048. var result = decodeAcl(AccessControlPolicy);
  7049. if (data.headers && data.headers['x-cos-acl']) {
  7050. result.ACL = data.headers['x-cos-acl'];
  7051. }
  7052. result = util.extend(result, {
  7053. Owner: Owner,
  7054. Grants: Grant,
  7055. statusCode: data.statusCode,
  7056. headers: data.headers
  7057. });
  7058. callback(null, result);
  7059. });
  7060. }
  7061. /**
  7062. * 设置 object 的 权限列表
  7063. * @param {Object} params 参数对象,必须
  7064. * @param {String} params.Bucket Bucket名称,必须
  7065. * @param {String} params.Region 地域名称,必须
  7066. * @param {String} params.Key object名称,必须
  7067. * @param {Function} callback 回调函数,必须
  7068. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7069. * @return {Object} data 返回的数据
  7070. */
  7071. function putObjectAcl(params, callback) {
  7072. var headers = params.Headers;
  7073. var xml = '';
  7074. if (params['AccessControlPolicy']) {
  7075. var AccessControlPolicy = util.clone(params['AccessControlPolicy'] || {});
  7076. var Grants = AccessControlPolicy.Grants || AccessControlPolicy.Grant;
  7077. Grants = util.isArray(Grants) ? Grants : [Grants];
  7078. delete AccessControlPolicy.Grant;
  7079. delete AccessControlPolicy.Grants;
  7080. AccessControlPolicy.AccessControlList = {
  7081. Grant: Grants
  7082. };
  7083. xml = util.json2xml({
  7084. AccessControlPolicy: AccessControlPolicy
  7085. });
  7086. headers['Content-Type'] = 'application/xml';
  7087. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7088. }
  7089. // Grant Header 去重
  7090. util.each(headers, function (val, key) {
  7091. if (key.indexOf('x-cos-grant-') === 0) {
  7092. headers[key] = uniqGrant(headers[key]);
  7093. }
  7094. });
  7095. submitRequest.call(this, {
  7096. Action: 'name/cos:PutObjectACL',
  7097. method: 'PUT',
  7098. Bucket: params.Bucket,
  7099. Region: params.Region,
  7100. Key: params.Key,
  7101. action: 'acl',
  7102. headers: headers,
  7103. body: xml,
  7104. tracker: params.tracker
  7105. }, function (err, data) {
  7106. if (err) return callback(err);
  7107. callback(null, {
  7108. statusCode: data.statusCode,
  7109. headers: data.headers
  7110. });
  7111. });
  7112. }
  7113. /**
  7114. * Options Object请求实现跨域访问的预请求。即发出一个 OPTIONS 请求给服务器以确认是否可以进行跨域操作。
  7115. * @param {Object} params 参数对象,必须
  7116. * @param {String} params.Bucket Bucket名称,必须
  7117. * @param {String} params.Region 地域名称,必须
  7118. * @param {String} params.Key object名称,必须
  7119. * @param {Function} callback 回调函数,必须
  7120. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7121. * @return {Object} data 返回的数据
  7122. */
  7123. function optionsObject(params, callback) {
  7124. var headers = params.Headers;
  7125. headers['Origin'] = params['Origin'];
  7126. headers['Access-Control-Request-Method'] = params['AccessControlRequestMethod'];
  7127. headers['Access-Control-Request-Headers'] = params['AccessControlRequestHeaders'];
  7128. submitRequest.call(this, {
  7129. Action: 'name/cos:OptionsObject',
  7130. method: 'OPTIONS',
  7131. Bucket: params.Bucket,
  7132. Region: params.Region,
  7133. Key: params.Key,
  7134. headers: headers,
  7135. tracker: params.tracker
  7136. }, function (err, data) {
  7137. if (err) {
  7138. if (err.statusCode && err.statusCode === 403) {
  7139. return callback(null, {
  7140. OptionsForbidden: true,
  7141. statusCode: err.statusCode
  7142. });
  7143. }
  7144. return callback(err);
  7145. }
  7146. var headers = data.headers || {};
  7147. callback(null, {
  7148. AccessControlAllowOrigin: headers['access-control-allow-origin'],
  7149. AccessControlAllowMethods: headers['access-control-allow-methods'],
  7150. AccessControlAllowHeaders: headers['access-control-allow-headers'],
  7151. AccessControlExposeHeaders: headers['access-control-expose-headers'],
  7152. AccessControlMaxAge: headers['access-control-max-age'],
  7153. statusCode: data.statusCode,
  7154. headers: data.headers
  7155. });
  7156. });
  7157. }
  7158. /**
  7159. * @param {Object} 参数列表
  7160. * @param {String} Bucket Bucket 名称
  7161. * @param {String} Region 地域名称
  7162. * @param {String} Key 文件名称
  7163. * @param {String} CopySource 源文件URL绝对路径,可以通过versionid子资源指定历史版本
  7164. * @param {String} ACL 允许用户自定义文件权限。有效值:private,public-read默认值:private。
  7165. * @param {String} GrantRead 赋予被授权者读的权限,格式 x-cos-grant-read: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  7166. * @param {String} GrantWrite 赋予被授权者写的权限,格式 x-cos-grant-write: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  7167. * @param {String} GrantFullControl 赋予被授权者读写权限,格式 x-cos-grant-full-control: uin=" ",uin=" ",当需要给子账户授权时,uin="RootAcountID/SubAccountID",当需要给根账户授权时,uin="RootAcountID"。
  7168. * @param {String} MetadataDirective 是否拷贝元数据,枚举值:Copy, Replaced,默认值Copy。假如标记为Copy,忽略Header中的用户元数据信息直接复制;假如标记为Replaced,按Header信息修改元数据。当目标路径和原路径一致,即用户试图修改元数据时,必须为Replaced
  7169. * @param {String} CopySourceIfModifiedSince 当Object在指定时间后被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-None-Match一起使用,与其他条件联合使用返回冲突。
  7170. * @param {String} CopySourceIfUnmodifiedSince 当Object在指定时间后未被修改,则执行操作,否则返回412。可与x-cos-copy-source-If-Match一起使用,与其他条件联合使用返回冲突。
  7171. * @param {String} CopySourceIfMatch 当Object的ETag和给定一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Unmodified-Since一起使用,与其他条件联合使用返回冲突。
  7172. * @param {String} CopySourceIfNoneMatch 当Object的ETag和给定不一致时,则执行操作,否则返回412。可与x-cos-copy-source-If-Modified-Since一起使用,与其他条件联合使用返回冲突。
  7173. * @param {String} StorageClass 存储级别,枚举值:存储级别,枚举值:Standard, Standard_IA,Archive;默认值:Standard
  7174. * @param {String} CacheControl 指定所有缓存机制在整个请求/响应链中必须服从的指令。
  7175. * @param {String} ContentDisposition MIME 协议的扩展,MIME 协议指示 MIME 用户代理如何显示附加的文件
  7176. * @param {String} ContentEncoding HTTP 中用来对「采用何种编码格式传输正文」进行协定的一对头部字段
  7177. * @param {String} ContentLength 设置响应消息的实体内容的大小,单位为字节
  7178. * @param {String} ContentType RFC 2616 中定义的 HTTP 请求内容类型(MIME),例如text/plain
  7179. * @param {String} Expect 请求的特定的服务器行为
  7180. * @param {String} Expires 响应过期的日期和时间
  7181. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7182. * @param {String} ContentLanguage 指定内容语言
  7183. * @param {String} x-cos-meta-* 允许用户自定义的头部信息,将作为 Object 元数据返回。大小限制2K。
  7184. */
  7185. function putObjectCopy(params, callback) {
  7186. // 特殊处理 Cache-Control
  7187. var headers = params.Headers;
  7188. if (!headers['Cache-Control'] && !!headers['cache-control']) headers['Cache-Control'] = '';
  7189. var CopySource = params.CopySource || '';
  7190. var m = util.getSourceParams.call(this, CopySource);
  7191. if (!m) {
  7192. callback({
  7193. error: 'CopySource format error'
  7194. });
  7195. return;
  7196. }
  7197. var SourceBucket = m.Bucket;
  7198. var SourceRegion = m.Region;
  7199. var SourceKey = decodeURIComponent(m.Key);
  7200. submitRequest.call(this, {
  7201. Scope: [{
  7202. action: 'name/cos:GetObject',
  7203. bucket: SourceBucket,
  7204. region: SourceRegion,
  7205. prefix: SourceKey
  7206. }, {
  7207. action: 'name/cos:PutObject',
  7208. bucket: params.Bucket,
  7209. region: params.Region,
  7210. prefix: params.Key
  7211. }],
  7212. method: 'PUT',
  7213. Bucket: params.Bucket,
  7214. Region: params.Region,
  7215. Key: params.Key,
  7216. VersionId: params.VersionId,
  7217. headers: params.Headers,
  7218. tracker: params.tracker
  7219. }, function (err, data) {
  7220. if (err) return callback(err);
  7221. var result = util.clone(data.CopyObjectResult || {});
  7222. util.extend(result, {
  7223. statusCode: data.statusCode,
  7224. headers: data.headers
  7225. });
  7226. callback(null, result);
  7227. });
  7228. }
  7229. function uploadPartCopy(params, callback) {
  7230. var CopySource = params.CopySource || '';
  7231. var m = util.getSourceParams.call(this, CopySource);
  7232. if (!m) {
  7233. callback({
  7234. error: 'CopySource format error'
  7235. });
  7236. return;
  7237. }
  7238. var SourceBucket = m.Bucket;
  7239. var SourceRegion = m.Region;
  7240. var SourceKey = decodeURIComponent(m.Key);
  7241. submitRequest.call(this, {
  7242. Scope: [{
  7243. action: 'name/cos:GetObject',
  7244. bucket: SourceBucket,
  7245. region: SourceRegion,
  7246. prefix: SourceKey
  7247. }, {
  7248. action: 'name/cos:PutObject',
  7249. bucket: params.Bucket,
  7250. region: params.Region,
  7251. prefix: params.Key
  7252. }],
  7253. method: 'PUT',
  7254. Bucket: params.Bucket,
  7255. Region: params.Region,
  7256. Key: params.Key,
  7257. VersionId: params.VersionId,
  7258. qs: {
  7259. partNumber: params['PartNumber'],
  7260. uploadId: params['UploadId']
  7261. },
  7262. headers: params.Headers,
  7263. tracker: params.tracker
  7264. }, function (err, data) {
  7265. if (err) return callback(err);
  7266. var result = util.clone(data.CopyPartResult || {});
  7267. util.extend(result, {
  7268. statusCode: data.statusCode,
  7269. headers: data.headers
  7270. });
  7271. callback(null, result);
  7272. });
  7273. }
  7274. function deleteMultipleObject(params, callback) {
  7275. var Objects = params.Objects || [];
  7276. var Quiet = params.Quiet;
  7277. Objects = util.isArray(Objects) ? Objects : [Objects];
  7278. var xml = util.json2xml({
  7279. Delete: {
  7280. Object: Objects,
  7281. Quiet: Quiet || false
  7282. }
  7283. });
  7284. var headers = params.Headers;
  7285. headers['Content-Type'] = 'application/xml';
  7286. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7287. var Scope = util.map(Objects, function (v) {
  7288. return {
  7289. action: 'name/cos:DeleteObject',
  7290. bucket: params.Bucket,
  7291. region: params.Region,
  7292. prefix: v.Key
  7293. };
  7294. });
  7295. submitRequest.call(this, {
  7296. Scope: Scope,
  7297. method: 'POST',
  7298. Bucket: params.Bucket,
  7299. Region: params.Region,
  7300. body: xml,
  7301. action: 'delete',
  7302. headers: headers,
  7303. tracker: params.tracker
  7304. }, function (err, data) {
  7305. if (err) return callback(err);
  7306. var DeleteResult = data.DeleteResult || {};
  7307. var Deleted = DeleteResult.Deleted || [];
  7308. var Errors = DeleteResult.Error || [];
  7309. Deleted = util.isArray(Deleted) ? Deleted : [Deleted];
  7310. Errors = util.isArray(Errors) ? Errors : [Errors];
  7311. var result = util.clone(DeleteResult);
  7312. util.extend(result, {
  7313. Error: Errors,
  7314. Deleted: Deleted,
  7315. statusCode: data.statusCode,
  7316. headers: data.headers
  7317. });
  7318. callback(null, result);
  7319. });
  7320. }
  7321. function restoreObject(params, callback) {
  7322. var headers = params.Headers;
  7323. if (!params['RestoreRequest']) {
  7324. callback({
  7325. error: 'missing param RestoreRequest'
  7326. });
  7327. return;
  7328. }
  7329. var RestoreRequest = params.RestoreRequest || {};
  7330. var xml = util.json2xml({
  7331. RestoreRequest: RestoreRequest
  7332. });
  7333. headers['Content-Type'] = 'application/xml';
  7334. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7335. submitRequest.call(this, {
  7336. Action: 'name/cos:RestoreObject',
  7337. method: 'POST',
  7338. Bucket: params.Bucket,
  7339. Region: params.Region,
  7340. Key: params.Key,
  7341. VersionId: params.VersionId,
  7342. body: xml,
  7343. action: 'restore',
  7344. headers: headers,
  7345. tracker: params.tracker
  7346. }, function (err, data) {
  7347. callback(err, data);
  7348. });
  7349. }
  7350. /**
  7351. * 设置 Object 的标签
  7352. * @param {Object} params 参数对象,必须
  7353. * @param {String} params.Bucket Object名称,必须
  7354. * @param {String} params.Region 地域名称,必须
  7355. * @param {Array} params.TagSet 标签设置,必须
  7356. * @param {Function} callback 回调函数,必须
  7357. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7358. * @return {Object} data 返回数据
  7359. */
  7360. function putObjectTagging(params, callback) {
  7361. var Tagging = params['Tagging'] || {};
  7362. var Tags = Tagging.TagSet || Tagging.Tags || params['Tags'] || [];
  7363. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  7364. var xml = util.json2xml({
  7365. Tagging: {
  7366. TagSet: {
  7367. Tag: Tags
  7368. }
  7369. }
  7370. });
  7371. var headers = params.Headers;
  7372. headers['Content-Type'] = 'application/xml';
  7373. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7374. submitRequest.call(this, {
  7375. Interface: 'putObjectTagging',
  7376. Action: 'name/cos:PutObjectTagging',
  7377. method: 'PUT',
  7378. Bucket: params.Bucket,
  7379. Key: params.Key,
  7380. Region: params.Region,
  7381. body: xml,
  7382. action: 'tagging',
  7383. headers: headers,
  7384. VersionId: params.VersionId,
  7385. tracker: params.tracker
  7386. }, function (err, data) {
  7387. if (err && err.statusCode === 204) {
  7388. return callback(null, {
  7389. statusCode: err.statusCode
  7390. });
  7391. } else if (err) {
  7392. return callback(err);
  7393. }
  7394. callback(null, {
  7395. statusCode: data.statusCode,
  7396. headers: data.headers
  7397. });
  7398. });
  7399. }
  7400. /**
  7401. * 获取 Object 的标签设置
  7402. * @param {Object} params 参数对象,必须
  7403. * @param {String} params.Bucket Bucket名称,必须
  7404. * @param {String} params.Region 地域名称,必须
  7405. * @param {Function} callback 回调函数,必须
  7406. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7407. * @return {Object} data 返回数据
  7408. */
  7409. function getObjectTagging(params, callback) {
  7410. submitRequest.call(this, {
  7411. Interface: 'getObjectTagging',
  7412. Action: 'name/cos:GetObjectTagging',
  7413. method: 'GET',
  7414. Key: params.Key,
  7415. Bucket: params.Bucket,
  7416. Region: params.Region,
  7417. headers: params.Headers,
  7418. action: 'tagging',
  7419. VersionId: params.VersionId,
  7420. tracker: params.tracker
  7421. }, function (err, data) {
  7422. if (err) {
  7423. if (err.statusCode === 404 && err.error && (err.error === 'Not Found' || err.error.Code === 'NoSuchTagSet')) {
  7424. var result = {
  7425. Tags: [],
  7426. statusCode: err.statusCode
  7427. };
  7428. err.headers && (result.headers = err.headers);
  7429. callback(null, result);
  7430. } else {
  7431. callback(err);
  7432. }
  7433. return;
  7434. }
  7435. var Tags = [];
  7436. try {
  7437. Tags = data.Tagging.TagSet.Tag || [];
  7438. } catch (e) {}
  7439. Tags = util.clone(util.isArray(Tags) ? Tags : [Tags]);
  7440. callback(null, {
  7441. Tags: Tags,
  7442. statusCode: data.statusCode,
  7443. headers: data.headers
  7444. });
  7445. });
  7446. }
  7447. /**
  7448. * 删除 Object 的 标签设置
  7449. * @param {Object} params 参数对象,必须
  7450. * @param {String} params.Bucket Object名称,必须
  7451. * @param {String} params.Region 地域名称,必须
  7452. * @param {Function} callback 回调函数,必须
  7453. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/42998
  7454. * @return {Object} data 返回的数据
  7455. */
  7456. function deleteObjectTagging(params, callback) {
  7457. submitRequest.call(this, {
  7458. Interface: 'deleteObjectTagging',
  7459. Action: 'name/cos:DeleteObjectTagging',
  7460. method: 'DELETE',
  7461. Bucket: params.Bucket,
  7462. Region: params.Region,
  7463. Key: params.Key,
  7464. headers: params.Headers,
  7465. action: 'tagging',
  7466. VersionId: params.VersionId,
  7467. tracker: params.tracker
  7468. }, function (err, data) {
  7469. if (err && err.statusCode === 204) {
  7470. return callback(null, {
  7471. statusCode: err.statusCode
  7472. });
  7473. } else if (err) {
  7474. return callback(err);
  7475. }
  7476. callback(null, {
  7477. statusCode: data.statusCode,
  7478. headers: data.headers
  7479. });
  7480. });
  7481. }
  7482. // 分块上传
  7483. /**
  7484. * 初始化分块上传
  7485. * @param {Object} params 参数对象,必须
  7486. * @param {String} params.Bucket Bucket名称,必须
  7487. * @param {String} params.Region 地域名称,必须
  7488. * @param {String} params.Key object名称,必须
  7489. * @param {String} params.UploadId object名称,必须
  7490. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  7491. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存 ,非必须
  7492. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  7493. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  7494. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  7495. * @param {String} params.ACL 允许用户自定义文件权限,非必须
  7496. * @param {String} params.GrantRead 赋予被授权者读的权限 ,非必须
  7497. * @param {String} params.GrantWrite 赋予被授权者写的权限 ,非必须
  7498. * @param {String} params.GrantFullControl 赋予被授权者读写权限 ,非必须
  7499. * @param {String} params.StorageClass 设置Object的存储级别,枚举值:Standard,Standard_IA,Archive,非必须
  7500. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7501. * @param {Function} callback 回调函数,必须
  7502. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7503. * @return {Object} data 返回的数据
  7504. */
  7505. function multipartInit(params, callback) {
  7506. var self = this;
  7507. var headers = params.Headers;
  7508. var tracker = params.tracker;
  7509. // 特殊处理 Cache-Control、Content-Type
  7510. if (!headers['Cache-Control'] && !headers['cache-control']) headers['Cache-Control'] = '';
  7511. if (!headers['Content-Type'] && !headers['content-type']) headers['Content-Type'] = mime.getType(params.Key) || 'application/octet-stream';
  7512. submitRequest.call(self, {
  7513. Action: 'name/cos:InitiateMultipartUpload',
  7514. method: 'POST',
  7515. Bucket: params.Bucket,
  7516. Region: params.Region,
  7517. Key: params.Key,
  7518. action: 'uploads',
  7519. headers: params.Headers,
  7520. qs: params.Query,
  7521. tracker: tracker
  7522. }, function (err, data) {
  7523. if (err) {
  7524. tracker && tracker.parent && tracker.parent.setParams({
  7525. errorNode: 'multipartInit'
  7526. });
  7527. return callback(err);
  7528. }
  7529. data = util.clone(data || {});
  7530. if (data && data.InitiateMultipartUploadResult) {
  7531. return callback(null, util.extend(data.InitiateMultipartUploadResult, {
  7532. statusCode: data.statusCode,
  7533. headers: data.headers
  7534. }));
  7535. }
  7536. callback(null, data);
  7537. });
  7538. }
  7539. /**
  7540. * 分块上传
  7541. * @param {Object} params 参数对象,必须
  7542. * @param {String} params.Bucket Bucket名称,必须
  7543. * @param {String} params.Region 地域名称,必须
  7544. * @param {String} params.Key object名称,必须
  7545. * @param {String} params.Body 上传文件对象或字符串
  7546. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),非必须
  7547. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  7548. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7549. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验值,非必须
  7550. * @param {Function} callback 回调函数,必须
  7551. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7552. * @return {Object} data 返回的数据
  7553. * @return {Object} data.ETag 返回的文件分块 sha1 值
  7554. */
  7555. function multipartUpload(params, callback) {
  7556. var self = this;
  7557. util.getFileSize('multipartUpload', params, function () {
  7558. var tracker = params.tracker;
  7559. var needCalcMd5 = self.options.UploadCheckContentMd5;
  7560. needCalcMd5 && tracker && tracker.setParams({
  7561. md5StartTime: new Date().getTime()
  7562. });
  7563. util.getBodyMd5(needCalcMd5, params.Body, function (md5) {
  7564. if (md5) {
  7565. params.Headers['Content-MD5'] = util.binaryBase64(md5);
  7566. needCalcMd5 && tracker && tracker.setParams({
  7567. md5EndTime: new Date().getTime()
  7568. });
  7569. }
  7570. tracker && tracker.setParams({
  7571. partNumber: params.PartNumber
  7572. });
  7573. submitRequest.call(self, {
  7574. Action: 'name/cos:UploadPart',
  7575. TaskId: params.TaskId,
  7576. method: 'PUT',
  7577. Bucket: params.Bucket,
  7578. Region: params.Region,
  7579. Key: params.Key,
  7580. qs: {
  7581. partNumber: params['PartNumber'],
  7582. uploadId: params['UploadId']
  7583. },
  7584. headers: params.Headers,
  7585. onProgress: params.onProgress,
  7586. body: params.Body || null,
  7587. tracker: tracker
  7588. }, function (err, data) {
  7589. if (err) {
  7590. tracker && tracker.parent && tracker.parent.setParams({
  7591. errorNode: 'multipartUpload'
  7592. });
  7593. return callback(err);
  7594. }
  7595. callback(null, {
  7596. ETag: util.attr(data.headers, 'etag', {}),
  7597. statusCode: data.statusCode,
  7598. headers: data.headers
  7599. });
  7600. });
  7601. });
  7602. });
  7603. }
  7604. /**
  7605. * 完成分块上传
  7606. * @param {Object} params 参数对象,必须
  7607. * @param {String} params.Bucket Bucket名称,必须
  7608. * @param {String} params.Region 地域名称,必须
  7609. * @param {String} params.Key object名称,必须
  7610. * @param {Array} params.Parts 分块信息列表,必须
  7611. * @param {String} params.Parts[i].PartNumber 块编号,必须
  7612. * @param {String} params.Parts[i].ETag 分块的 sha1 校验值
  7613. * @param {Function} callback 回调函数,必须
  7614. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7615. * @return {Object} data 返回的数据
  7616. * @return {Object} data.CompleteMultipartUpload 完成分块上传后的文件信息,包括Location, Bucket, Key 和 ETag
  7617. */
  7618. function multipartComplete(params, callback) {
  7619. var self = this;
  7620. var UploadId = params.UploadId;
  7621. var Parts = params['Parts'];
  7622. var tracker = params.tracker;
  7623. for (var i = 0, len = Parts.length; i < len; i++) {
  7624. if (Parts[i]['ETag'].indexOf('"') === 0) {
  7625. continue;
  7626. }
  7627. Parts[i]['ETag'] = '"' + Parts[i]['ETag'] + '"';
  7628. }
  7629. var xml = util.json2xml({
  7630. CompleteMultipartUpload: {
  7631. Part: Parts
  7632. }
  7633. });
  7634. var headers = params.Headers;
  7635. headers['Content-Type'] = 'application/xml';
  7636. headers['Content-MD5'] = util.binaryBase64(util.md5(xml));
  7637. submitRequest.call(this, {
  7638. Action: 'name/cos:CompleteMultipartUpload',
  7639. method: 'POST',
  7640. Bucket: params.Bucket,
  7641. Region: params.Region,
  7642. Key: params.Key,
  7643. qs: {
  7644. uploadId: UploadId
  7645. },
  7646. body: xml,
  7647. headers: headers,
  7648. tracker: tracker
  7649. }, function (err, data) {
  7650. if (err) {
  7651. tracker && tracker.parent && tracker.parent.setParams({
  7652. errorNode: 'multipartComplete'
  7653. });
  7654. return callback(err);
  7655. }
  7656. var url = getUrl({
  7657. ForcePathStyle: self.options.ForcePathStyle,
  7658. protocol: self.options.Protocol,
  7659. domain: self.options.Domain,
  7660. bucket: params.Bucket,
  7661. region: params.Region,
  7662. object: params.Key,
  7663. isLocation: true
  7664. });
  7665. var CompleteMultipartUploadResult = data.CompleteMultipartUploadResult || {};
  7666. var result = util.extend(CompleteMultipartUploadResult, {
  7667. Location: url,
  7668. statusCode: data.statusCode,
  7669. headers: data.headers
  7670. });
  7671. callback(null, result);
  7672. });
  7673. }
  7674. /**
  7675. * 分块上传任务列表查询
  7676. * @param {Object} params 参数对象,必须
  7677. * @param {String} params.Bucket Bucket名称,必须
  7678. * @param {String} params.Region 地域名称,必须
  7679. * @param {String} params.Delimiter 定界符为一个符号,如果有Prefix,则将Prefix到delimiter之间的相同路径归为一类,定义为Common Prefix,然后列出所有Common Prefix。如果没有Prefix,则从路径起点开始,非必须
  7680. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  7681. * @param {String} params.Prefix 前缀匹配,用来规定返回的文件前缀地址,非必须
  7682. * @param {String} params.MaxUploads 单次返回最大的条目数量,默认1000,非必须
  7683. * @param {String} params.KeyMarker 与upload-id-marker一起使用 </Br>当upload-id-marker未被指定时,ObjectName字母顺序大于key-marker的条目将被列出 </Br>当upload-id-marker被指定时,ObjectName字母顺序大于key-marker的条目被列出,ObjectName字母顺序等于key-marker同时UploadId大于upload-id-marker的条目将被列出,非必须
  7684. * @param {String} params.UploadIdMarker 与key-marker一起使用 </Br>当key-marker未被指定时,upload-id-marker将被忽略 </Br>当key-marker被指定时,ObjectName字母顺序大于key-marker的条目被列出,ObjectName字母顺序等于key-marker同时UploadId大于upload-id-marker的条目将被列出,非必须
  7685. * @param {Function} callback 回调函数,必须
  7686. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7687. * @return {Object} data 返回的数据
  7688. * @return {Object} data.ListMultipartUploadsResult 分块上传任务信息
  7689. */
  7690. function multipartList(params, callback) {
  7691. var reqParams = {};
  7692. reqParams['delimiter'] = params['Delimiter'];
  7693. reqParams['encoding-type'] = params['EncodingType'];
  7694. reqParams['prefix'] = params['Prefix'] || '';
  7695. reqParams['max-uploads'] = params['MaxUploads'];
  7696. reqParams['key-marker'] = params['KeyMarker'];
  7697. reqParams['upload-id-marker'] = params['UploadIdMarker'];
  7698. reqParams = util.clearKey(reqParams);
  7699. var tracker = params.tracker;
  7700. tracker && tracker.setParams({
  7701. signStartTime: new Date().getTime()
  7702. });
  7703. submitRequest.call(this, {
  7704. Action: 'name/cos:ListMultipartUploads',
  7705. ResourceKey: reqParams['prefix'],
  7706. method: 'GET',
  7707. Bucket: params.Bucket,
  7708. Region: params.Region,
  7709. headers: params.Headers,
  7710. qs: reqParams,
  7711. action: 'uploads',
  7712. tracker: tracker
  7713. }, function (err, data) {
  7714. if (err) {
  7715. tracker && tracker.parent && tracker.parent.setParams({
  7716. errorNode: 'multipartList'
  7717. });
  7718. return callback(err);
  7719. }
  7720. if (data && data.ListMultipartUploadsResult) {
  7721. var Upload = data.ListMultipartUploadsResult.Upload || [];
  7722. var CommonPrefixes = data.ListMultipartUploadsResult.CommonPrefixes || [];
  7723. CommonPrefixes = util.isArray(CommonPrefixes) ? CommonPrefixes : [CommonPrefixes];
  7724. Upload = util.isArray(Upload) ? Upload : [Upload];
  7725. data.ListMultipartUploadsResult.Upload = Upload;
  7726. data.ListMultipartUploadsResult.CommonPrefixes = CommonPrefixes;
  7727. }
  7728. var result = util.clone(data.ListMultipartUploadsResult || {});
  7729. util.extend(result, {
  7730. statusCode: data.statusCode,
  7731. headers: data.headers
  7732. });
  7733. callback(null, result);
  7734. });
  7735. }
  7736. /**
  7737. * 上传的分块列表查询
  7738. * @param {Object} params 参数对象,必须
  7739. * @param {String} params.Bucket Bucket名称,必须
  7740. * @param {String} params.Region 地域名称,必须
  7741. * @param {String} params.Key object名称,必须
  7742. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  7743. * @param {String} params.EncodingType 规定返回值的编码方式,非必须
  7744. * @param {String} params.MaxParts 单次返回最大的条目数量,默认1000,非必须
  7745. * @param {String} params.PartNumberMarker 默认以UTF-8二进制顺序列出条目,所有列出条目从marker开始,非必须
  7746. * @param {Function} callback 回调函数,必须
  7747. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7748. * @return {Object} data 返回的数据
  7749. * @return {Object} data.ListMultipartUploadsResult 分块信息
  7750. */
  7751. function multipartListPart(params, callback) {
  7752. var reqParams = {};
  7753. var tracker = params.tracker;
  7754. reqParams['uploadId'] = params['UploadId'];
  7755. reqParams['encoding-type'] = params['EncodingType'];
  7756. reqParams['max-parts'] = params['MaxParts'];
  7757. reqParams['part-number-marker'] = params['PartNumberMarker'];
  7758. submitRequest.call(this, {
  7759. Action: 'name/cos:ListParts',
  7760. method: 'GET',
  7761. Bucket: params.Bucket,
  7762. Region: params.Region,
  7763. Key: params.Key,
  7764. headers: params.Headers,
  7765. qs: reqParams,
  7766. tracker: tracker
  7767. }, function (err, data) {
  7768. if (err) {
  7769. tracker && tracker.parent && tracker.parent.setParams({
  7770. errorNode: 'multipartListPart'
  7771. });
  7772. return callback(err);
  7773. }
  7774. var ListPartsResult = data.ListPartsResult || {};
  7775. var Part = ListPartsResult.Part || [];
  7776. Part = util.isArray(Part) ? Part : [Part];
  7777. ListPartsResult.Part = Part;
  7778. var result = util.clone(ListPartsResult);
  7779. util.extend(result, {
  7780. statusCode: data.statusCode,
  7781. headers: data.headers
  7782. });
  7783. callback(null, result);
  7784. });
  7785. }
  7786. /**
  7787. * 抛弃分块上传
  7788. * @param {Object} params 参数对象,必须
  7789. * @param {String} params.Bucket Bucket名称,必须
  7790. * @param {String} params.Region 地域名称,必须
  7791. * @param {String} params.Key object名称,必须
  7792. * @param {String} params.UploadId 标示本次分块上传的ID,必须
  7793. * @param {Function} callback 回调函数,必须
  7794. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7795. * @return {Object} data 返回的数据
  7796. */
  7797. function multipartAbort(params, callback) {
  7798. var reqParams = {};
  7799. reqParams['uploadId'] = params['UploadId'];
  7800. submitRequest.call(this, {
  7801. Action: 'name/cos:AbortMultipartUpload',
  7802. method: 'DELETE',
  7803. Bucket: params.Bucket,
  7804. Region: params.Region,
  7805. Key: params.Key,
  7806. headers: params.Headers,
  7807. qs: reqParams,
  7808. tracker: params.tracker
  7809. }, function (err, data) {
  7810. if (err) return callback(err);
  7811. callback(null, {
  7812. statusCode: data.statusCode,
  7813. headers: data.headers
  7814. });
  7815. });
  7816. }
  7817. /**
  7818. * 追加上传
  7819. * @param {Object} params 参数对象,必须
  7820. * @param {String} params.Bucket Bucket名称,必须
  7821. * @param {String} params.Region 地域名称,必须
  7822. * @param {String} params.Key object名称,必须
  7823. * @param {String} params.Body 上传文件的内容,只支持字符串
  7824. * @param {Number} params.Position 追加操作的起始点,单位为字节,必须
  7825. * @param {String} params.CacheControl RFC 2616 中定义的缓存策略,将作为 Object 元数据保存,非必须
  7826. * @param {String} params.ContentDisposition RFC 2616 中定义的文件名称,将作为 Object 元数据保存,非必须
  7827. * @param {String} params.ContentEncoding RFC 2616 中定义的编码格式,将作为 Object 元数据保存,非必须
  7828. * @param {String} params.ContentLength RFC 2616 中定义的 HTTP 请求内容长度(字节),必须
  7829. * @param {String} params.ContentType RFC 2616 中定义的内容类型(MIME),将作为 Object 元数据保存,非必须
  7830. * @param {String} params.Expect 当使用 Expect: 100-continue 时,在收到服务端确认后,才会发送请求内容,非必须
  7831. * @param {String} params.Expires RFC 2616 中定义的过期时间,将作为 Object 元数据保存,非必须
  7832. * @param {String} params.ACL 允许用户自定义文件权限,有效值:private | public-read,非必须
  7833. * @param {String} params.GrantRead 赋予被授权者读取对象的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7834. * @param {String} params.GrantReadAcp 赋予被授权者读取对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7835. * @param {String} params.GrantWriteAcp 赋予被授权者写入对象的访问控制列表(ACL)的权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7836. * @param {String} params.GrantFullControl 赋予被授权者操作对象的所有权限,格式:id="[OwnerUin]",可使用半角逗号(,)分隔多组被授权者,非必须
  7837. * @param {String} params.StorageClass 设置对象的存储级别,枚举值:STANDARD、STANDARD_IA、ARCHIVE,默认值:STANDARD,非必须
  7838. * @param {String} params.x-cos-meta-* 允许用户自定义的头部信息,将作为对象的元数据保存。大小限制2KB,非必须
  7839. * @param {String} params.ContentSha1 RFC 3174 中定义的 160-bit 内容 SHA-1 算法校验,非必须
  7840. * @param {String} params.ServerSideEncryption 支持按照指定的加密算法进行服务端数据加密,格式 x-cos-server-side-encryption: "AES256",非必须
  7841. * @param {Function} callback 回调函数,必须
  7842. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7843. * @return {Object} data 返回的数据
  7844. */
  7845. function appendObject(params, callback) {
  7846. submitRequest.call(this, {
  7847. Action: 'name/cos:AppendObject',
  7848. method: 'POST',
  7849. Bucket: params.Bucket,
  7850. Region: params.Region,
  7851. action: 'append',
  7852. Key: params.Key,
  7853. body: params.Body,
  7854. qs: {
  7855. position: params.Position
  7856. },
  7857. headers: params.Headers,
  7858. tracker: params.tracker
  7859. }, function (err, data) {
  7860. if (err) return callback(err);
  7861. callback(null, data);
  7862. });
  7863. }
  7864. /**
  7865. * cos 内置请求
  7866. * @param {Object} params 参数对象,必须
  7867. * @param {String} params.Bucket Bucket名称,必须
  7868. * @param {String} params.Region 地域名称,必须
  7869. * @param {String} params.Key object名称,必须
  7870. * @param {Function} callback 回调函数,必须
  7871. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7872. * @return {Object} data 返回的数据
  7873. */
  7874. function request(params, callback) {
  7875. submitRequest.call(this, {
  7876. method: params.Method,
  7877. Bucket: params.Bucket,
  7878. Region: params.Region,
  7879. Key: params.Key,
  7880. action: params.Action,
  7881. headers: params.Headers,
  7882. qs: params.Query,
  7883. body: params.Body,
  7884. Url: params.Url,
  7885. rawBody: params.RawBody,
  7886. dataType: params.DataType,
  7887. tracker: params.tracker
  7888. }, function (err, data) {
  7889. if (err) return callback(err);
  7890. if (data && data.body) {
  7891. data.Body = data.body;
  7892. delete data.body;
  7893. }
  7894. callback(err, data);
  7895. });
  7896. }
  7897. /**
  7898. * 获取签名
  7899. * @param {Object} params 参数对象,必须
  7900. * @param {String} params.Method 请求方法,必须
  7901. * @param {String} params.Key object名称,必须
  7902. * @param {String} params.Expires 名超时时间,单位秒,可选
  7903. * @return {String} data 返回签名字符串
  7904. */
  7905. function getAuth(params) {
  7906. var self = this;
  7907. return util.getAuth({
  7908. SecretId: params.SecretId || this.options.SecretId || '',
  7909. SecretKey: params.SecretKey || this.options.SecretKey || '',
  7910. Bucket: params.Bucket,
  7911. Region: params.Region,
  7912. Method: params.Method,
  7913. Key: params.Key,
  7914. Query: params.Query,
  7915. Headers: params.Headers,
  7916. Expires: params.Expires,
  7917. SystemClockOffset: self.options.SystemClockOffset
  7918. });
  7919. }
  7920. /**
  7921. * 获取文件下载链接
  7922. * @param {Object} params 参数对象,必须
  7923. * @param {String} params.Bucket Bucket名称,必须
  7924. * @param {String} params.Region 地域名称,必须
  7925. * @param {String} params.Key object名称,必须
  7926. * @param {String} params.Method 请求的方法,可选
  7927. * @param {String} params.Expires 签名超时时间,单位秒,可选
  7928. * @param {Function} callback 回调函数,必须
  7929. * @return {Object} err 请求失败的错误,如果请求成功,则为空。https://cloud.tencent.com/document/product/436/7730
  7930. * @return {Object} data 返回的数据
  7931. */
  7932. function getObjectUrl(params, callback) {
  7933. var self = this;
  7934. var useAccelerate = params.UseAccelerate === undefined ? self.options.UseAccelerate : params.UseAccelerate;
  7935. var url = getUrl({
  7936. ForcePathStyle: self.options.ForcePathStyle,
  7937. protocol: params.Protocol || self.options.Protocol,
  7938. domain: params.Domain || self.options.Domain,
  7939. bucket: params.Bucket,
  7940. region: useAccelerate ? 'accelerate' : params.Region,
  7941. object: params.Key
  7942. });
  7943. var queryParamsStr = '';
  7944. if (params.Query) {
  7945. queryParamsStr += util.obj2str(params.Query);
  7946. }
  7947. if (params.QueryString) {
  7948. queryParamsStr += (queryParamsStr ? '&' : '') + params.QueryString;
  7949. }
  7950. var syncUrl = url;
  7951. if (params.Sign !== undefined && !params.Sign) {
  7952. queryParamsStr && (syncUrl += '?' + queryParamsStr);
  7953. callback(null, {
  7954. Url: syncUrl
  7955. });
  7956. return syncUrl;
  7957. }
  7958. // 签名加上 Host,避免跨桶访问
  7959. var SignHost = getSignHost.call(this, {
  7960. Bucket: params.Bucket,
  7961. Region: params.Region,
  7962. UseAccelerate: params.UseAccelerate,
  7963. Url: url
  7964. });
  7965. var AuthData = getAuthorizationAsync.call(this, {
  7966. Action: (params.Method || '').toUpperCase() === 'PUT' ? 'name/cos:PutObject' : 'name/cos:GetObject',
  7967. Bucket: params.Bucket || '',
  7968. Region: params.Region || '',
  7969. Method: params.Method || 'get',
  7970. Key: params.Key,
  7971. Expires: params.Expires,
  7972. Headers: params.Headers,
  7973. Query: params.Query,
  7974. SignHost: SignHost,
  7975. ForceSignHost: params.ForceSignHost === false ? false : self.options.ForceSignHost // getObjectUrl支持传参ForceSignHost
  7976. }, function (err, AuthData) {
  7977. if (!callback) return;
  7978. if (err) {
  7979. callback(err);
  7980. return;
  7981. }
  7982. // 兼容万象url qUrlParamList需要再encode一次
  7983. var replaceUrlParamList = function replaceUrlParamList(url) {
  7984. var urlParams = url.match(/q-url-param-list.*?(?=&)/g)[0];
  7985. var encodedParams = 'q-url-param-list=' + encodeURIComponent(urlParams.replace(/q-url-param-list=/, '')).toLowerCase();
  7986. var reg = new RegExp(urlParams, 'g');
  7987. var replacedUrl = url.replace(reg, encodedParams);
  7988. return replacedUrl;
  7989. };
  7990. var signUrl = url;
  7991. signUrl += '?' + (AuthData.Authorization.indexOf('q-signature') > -1 ? replaceUrlParamList(AuthData.Authorization) : 'sign=' + encodeURIComponent(AuthData.Authorization));
  7992. AuthData.SecurityToken && (signUrl += '&x-cos-security-token=' + AuthData.SecurityToken);
  7993. AuthData.ClientIP && (signUrl += '&clientIP=' + AuthData.ClientIP);
  7994. AuthData.ClientUA && (signUrl += '&clientUA=' + AuthData.ClientUA);
  7995. AuthData.Token && (signUrl += '&token=' + AuthData.Token);
  7996. queryParamsStr && (signUrl += '&' + queryParamsStr);
  7997. setTimeout(function () {
  7998. callback(null, {
  7999. Url: signUrl
  8000. });
  8001. });
  8002. });
  8003. if (AuthData) {
  8004. syncUrl += '?' + AuthData.Authorization + (AuthData.SecurityToken ? '&x-cos-security-token=' + AuthData.SecurityToken : '');
  8005. queryParamsStr && (syncUrl += '&' + queryParamsStr);
  8006. } else {
  8007. queryParamsStr && (syncUrl += '?' + queryParamsStr);
  8008. }
  8009. return syncUrl;
  8010. }
  8011. /**
  8012. * 私有方法
  8013. */
  8014. function decodeAcl(AccessControlPolicy) {
  8015. var result = {
  8016. GrantFullControl: [],
  8017. GrantWrite: [],
  8018. GrantRead: [],
  8019. GrantReadAcp: [],
  8020. GrantWriteAcp: [],
  8021. ACL: ''
  8022. };
  8023. var GrantMap = {
  8024. FULL_CONTROL: 'GrantFullControl',
  8025. WRITE: 'GrantWrite',
  8026. READ: 'GrantRead',
  8027. READ_ACP: 'GrantReadAcp',
  8028. WRITE_ACP: 'GrantWriteAcp'
  8029. };
  8030. var AccessControlList = AccessControlPolicy && AccessControlPolicy.AccessControlList || {};
  8031. var Grant = AccessControlList.Grant;
  8032. if (Grant) {
  8033. Grant = util.isArray(Grant) ? Grant : [Grant];
  8034. }
  8035. var PublicAcl = {
  8036. READ: 0,
  8037. WRITE: 0,
  8038. FULL_CONTROL: 0
  8039. };
  8040. Grant && Grant.length && util.each(Grant, function (item) {
  8041. if (item.Grantee.ID === 'qcs::cam::anyone:anyone' || item.Grantee.URI === 'http://cam.qcloud.com/groups/global/AllUsers') {
  8042. PublicAcl[item.Permission] = 1;
  8043. } else if (item.Grantee.ID !== AccessControlPolicy.Owner.ID) {
  8044. result[GrantMap[item.Permission]].push('id="' + item.Grantee.ID + '"');
  8045. }
  8046. });
  8047. if (PublicAcl.FULL_CONTROL || PublicAcl.WRITE && PublicAcl.READ) {
  8048. result.ACL = 'public-read-write';
  8049. } else if (PublicAcl.READ) {
  8050. result.ACL = 'public-read';
  8051. } else {
  8052. result.ACL = 'private';
  8053. }
  8054. util.each(GrantMap, function (item) {
  8055. result[item] = uniqGrant(result[item].join(','));
  8056. });
  8057. return result;
  8058. }
  8059. // Grant 去重
  8060. function uniqGrant(str) {
  8061. var arr = str.split(',');
  8062. var exist = {};
  8063. var i, item;
  8064. for (i = 0; i < arr.length;) {
  8065. item = arr[i].trim();
  8066. if (exist[item]) {
  8067. arr.splice(i, 1);
  8068. } else {
  8069. exist[item] = true;
  8070. arr[i] = item;
  8071. i++;
  8072. }
  8073. }
  8074. return arr.join(',');
  8075. }
  8076. // 生成操作 url
  8077. function getUrl(params) {
  8078. var longBucket = params.bucket;
  8079. var shortBucket = longBucket.substr(0, longBucket.lastIndexOf('-'));
  8080. var appId = longBucket.substr(longBucket.lastIndexOf('-') + 1);
  8081. var domain = params.domain;
  8082. var region = params.region;
  8083. var object = params.object;
  8084. var protocol = 'https:';
  8085. if (!domain) {
  8086. if (['cn-south', 'cn-south-2', 'cn-north', 'cn-east', 'cn-southwest', 'sg'].indexOf(region) > -1) {
  8087. domain = '{Region}.myqcloud.com';
  8088. } else {
  8089. domain = 'cos.{Region}.myqcloud.com';
  8090. }
  8091. if (!params.ForcePathStyle) {
  8092. domain = '{Bucket}.' + domain;
  8093. }
  8094. }
  8095. domain = domain.replace(/\{\{AppId\}\}/gi, appId).replace(/\{\{Bucket\}\}/gi, shortBucket).replace(/\{\{Region\}\}/gi, region).replace(/\{\{.*?\}\}/gi, '');
  8096. domain = domain.replace(/\{AppId\}/gi, appId).replace(/\{BucketName\}/gi, shortBucket).replace(/\{Bucket\}/gi, longBucket).replace(/\{Region\}/gi, region).replace(/\{.*?\}/gi, '');
  8097. if (!/^[a-zA-Z]+:\/\//.test(domain)) {
  8098. domain = protocol + '//' + domain;
  8099. }
  8100. // 去掉域名最后的斜杆
  8101. if (domain.slice(-1) === '/') {
  8102. domain = domain.slice(0, -1);
  8103. }
  8104. var url = domain;
  8105. if (params.ForcePathStyle) {
  8106. url += '/' + longBucket;
  8107. }
  8108. url += '/';
  8109. if (object) {
  8110. url += util.camSafeUrlEncode(object).replace(/%2F/g, '/');
  8111. }
  8112. if (params.isLocation) {
  8113. url = url.replace(/^https?:\/\//, '');
  8114. }
  8115. return url;
  8116. }
  8117. var getSignHost = function getSignHost(opt) {
  8118. if (!opt.Bucket || !opt.Region) return '';
  8119. var useAccelerate = opt.UseAccelerate === undefined ? this.options.UseAccelerate : opt.UseAccelerate;
  8120. var url = opt.Url || getUrl({
  8121. ForcePathStyle: this.options.ForcePathStyle,
  8122. protocol: this.options.Protocol,
  8123. domain: this.options.Domain,
  8124. bucket: opt.Bucket,
  8125. region: useAccelerate ? 'accelerate' : opt.Region
  8126. });
  8127. var urlHost = url.replace(/^https?:\/\/([^/]+)(\/.*)?$/, '$1');
  8128. return urlHost;
  8129. };
  8130. // 异步获取签名
  8131. function getAuthorizationAsync(params, callback) {
  8132. var headers = util.clone(params.Headers);
  8133. var headerHost = '';
  8134. util.each(headers, function (v, k) {
  8135. (v === '' || ['content-type', 'cache-control'].indexOf(k.toLowerCase()) > -1) && delete headers[k];
  8136. if (k.toLowerCase() === 'host') headerHost = v;
  8137. });
  8138. // ForceSignHost明确传入false才不加入host签名
  8139. var forceSignHost = params.ForceSignHost === false ? false : true;
  8140. // Host 加入签名计算
  8141. if (!headerHost && params.SignHost && forceSignHost) headers.Host = params.SignHost;
  8142. // 获取凭证的回调,避免用户 callback 多次
  8143. var cbDone = false;
  8144. var cb = function cb(err, AuthData) {
  8145. if (cbDone) return;
  8146. cbDone = true;
  8147. if (AuthData && AuthData.XCosSecurityToken && !AuthData.SecurityToken) {
  8148. AuthData = util.clone(AuthData);
  8149. AuthData.SecurityToken = AuthData.XCosSecurityToken;
  8150. delete AuthData.XCosSecurityToken;
  8151. }
  8152. callback && callback(err, AuthData);
  8153. };
  8154. var self = this;
  8155. var Bucket = params.Bucket || '';
  8156. var Region = params.Region || '';
  8157. // PathName
  8158. var KeyName = params.Action === 'name/cos:PostObject' || !params.Key ? '' : params.Key;
  8159. if (self.options.ForcePathStyle && Bucket) {
  8160. KeyName = Bucket + '/' + KeyName;
  8161. }
  8162. var Pathname = '/' + KeyName;
  8163. // Action、ResourceKey
  8164. var StsData = {};
  8165. var Scope = params.Scope;
  8166. if (!Scope) {
  8167. var Action = params.Action || '';
  8168. var ResourceKey = params.ResourceKey || params.Key || '';
  8169. Scope = params.Scope || [{
  8170. action: Action,
  8171. bucket: Bucket,
  8172. region: Region,
  8173. prefix: ResourceKey
  8174. }];
  8175. }
  8176. var ScopeKey = util.md5(JSON.stringify(Scope));
  8177. // STS
  8178. self._StsCache = self._StsCache || [];
  8179. (function () {
  8180. var i, AuthData;
  8181. for (i = self._StsCache.length - 1; i >= 0; i--) {
  8182. AuthData = self._StsCache[i];
  8183. var compareTime = Math.round(util.getSkewTime(self.options.SystemClockOffset) / 1000) + 30;
  8184. if (AuthData.StartTime && compareTime < AuthData.StartTime || compareTime >= AuthData.ExpiredTime) {
  8185. self._StsCache.splice(i, 1);
  8186. continue;
  8187. }
  8188. if (!AuthData.ScopeLimit || AuthData.ScopeLimit && AuthData.ScopeKey === ScopeKey) {
  8189. StsData = AuthData;
  8190. break;
  8191. }
  8192. }
  8193. })();
  8194. var calcAuthByTmpKey = function calcAuthByTmpKey() {
  8195. var KeyTime = '';
  8196. if (StsData.StartTime && params.Expires) {
  8197. KeyTime = StsData.StartTime + ';' + (StsData.StartTime + params.Expires * 1);
  8198. } else if (StsData.StartTime && StsData.ExpiredTime) {
  8199. KeyTime = StsData.StartTime + ';' + StsData.ExpiredTime;
  8200. }
  8201. var Authorization = util.getAuth({
  8202. SecretId: StsData.TmpSecretId,
  8203. SecretKey: StsData.TmpSecretKey,
  8204. Method: params.Method,
  8205. Pathname: Pathname,
  8206. Query: params.Query,
  8207. Headers: headers,
  8208. Expires: params.Expires,
  8209. SystemClockOffset: self.options.SystemClockOffset,
  8210. KeyTime: KeyTime,
  8211. ForceSignHost: forceSignHost
  8212. });
  8213. var AuthData = {
  8214. Authorization: Authorization,
  8215. SecurityToken: StsData.SecurityToken || StsData.XCosSecurityToken || '',
  8216. Token: StsData.Token || '',
  8217. ClientIP: StsData.ClientIP || '',
  8218. ClientUA: StsData.ClientUA || '',
  8219. SignFrom: 'client'
  8220. };
  8221. cb(null, AuthData);
  8222. };
  8223. var checkAuthError = function checkAuthError(AuthData) {
  8224. if (AuthData.Authorization) {
  8225. // 检查签名格式
  8226. var formatAllow = false;
  8227. var auth = AuthData.Authorization;
  8228. if (auth) {
  8229. if (auth.indexOf(' ') > -1) {
  8230. formatAllow = false;
  8231. } else if (auth.indexOf('q-sign-algorithm=') > -1 && auth.indexOf('q-ak=') > -1 && auth.indexOf('q-sign-time=') > -1 && auth.indexOf('q-key-time=') > -1 && auth.indexOf('q-url-param-list=') > -1) {
  8232. formatAllow = true;
  8233. } else {
  8234. try {
  8235. auth = atob(auth);
  8236. if (auth.indexOf('a=') > -1 && auth.indexOf('k=') > -1 && auth.indexOf('t=') > -1 && auth.indexOf('r=') > -1 && auth.indexOf('b=') > -1) {
  8237. formatAllow = true;
  8238. }
  8239. } catch (e) {}
  8240. }
  8241. }
  8242. if (!formatAllow) return util.error(new Error('getAuthorization callback params format error'));
  8243. } else {
  8244. if (!AuthData.TmpSecretId) return util.error(new Error('getAuthorization callback params missing "TmpSecretId"'));
  8245. if (!AuthData.TmpSecretKey) return util.error(new Error('getAuthorization callback params missing "TmpSecretKey"'));
  8246. if (!AuthData.SecurityToken && !AuthData.XCosSecurityToken) return util.error(new Error('getAuthorization callback params missing "SecurityToken"'));
  8247. if (!AuthData.ExpiredTime) return util.error(new Error('getAuthorization callback params missing "ExpiredTime"'));
  8248. if (AuthData.ExpiredTime && AuthData.ExpiredTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "ExpiredTime" should be 10 digits'));
  8249. if (AuthData.StartTime && AuthData.StartTime.toString().length !== 10) return util.error(new Error('getAuthorization callback params "StartTime" should be 10 StartTime'));
  8250. }
  8251. return false;
  8252. };
  8253. // 先判断是否有临时密钥
  8254. if (StsData.ExpiredTime && StsData.ExpiredTime - util.getSkewTime(self.options.SystemClockOffset) / 1000 > 60) {
  8255. // 如果缓存的临时密钥有效,并还有超过60秒有效期就直接使用
  8256. calcAuthByTmpKey();
  8257. } else if (self.options.getAuthorization) {
  8258. // 外部计算签名或获取临时密钥
  8259. self.options.getAuthorization.call(self, {
  8260. Bucket: Bucket,
  8261. Region: Region,
  8262. Method: params.Method,
  8263. Key: KeyName,
  8264. Pathname: Pathname,
  8265. Query: params.Query,
  8266. Headers: headers,
  8267. Scope: Scope,
  8268. SystemClockOffset: self.options.SystemClockOffset,
  8269. ForceSignHost: forceSignHost
  8270. }, function (AuthData) {
  8271. if (typeof AuthData === 'string') {
  8272. AuthData = {
  8273. Authorization: AuthData
  8274. };
  8275. }
  8276. var AuthError = checkAuthError(AuthData);
  8277. if (AuthError) return cb(AuthError);
  8278. if (AuthData.Authorization) {
  8279. cb(null, AuthData);
  8280. } else {
  8281. StsData = AuthData || {};
  8282. StsData.Scope = Scope;
  8283. StsData.ScopeKey = ScopeKey;
  8284. self._StsCache.push(StsData);
  8285. calcAuthByTmpKey();
  8286. }
  8287. });
  8288. } else if (self.options.getSTS) {
  8289. // 外部获取临时密钥
  8290. self.options.getSTS.call(self, {
  8291. Bucket: Bucket,
  8292. Region: Region
  8293. }, function (data) {
  8294. StsData = data || {};
  8295. StsData.Scope = Scope;
  8296. StsData.ScopeKey = ScopeKey;
  8297. if (!StsData.TmpSecretId) StsData.TmpSecretId = StsData.SecretId;
  8298. if (!StsData.TmpSecretKey) StsData.TmpSecretKey = StsData.SecretKey;
  8299. var AuthError = checkAuthError(StsData);
  8300. if (AuthError) return cb(AuthError);
  8301. self._StsCache.push(StsData);
  8302. calcAuthByTmpKey();
  8303. });
  8304. } else {
  8305. // 内部计算获取签名
  8306. return function () {
  8307. var KeyTime = '';
  8308. if (self.options.StartTime && params.Expires) {
  8309. if (self.options.StartTime.toString().length !== 10) {
  8310. return cb(util.error(new Error('params "StartTime" should be 10 digits')));
  8311. }
  8312. KeyTime = self.options.StartTime + ';' + (self.options.StartTime + params.Expires * 1);
  8313. } else if (self.options.StartTime && self.options.ExpiredTime) {
  8314. if (self.options.StartTime.toString().length !== 10) {
  8315. return cb(util.error(new Error('params "StartTime" should be 10 digits')));
  8316. }
  8317. if (self.options.ExpiredTime.toString().length !== 10) {
  8318. return cb(util.error(new Error('params "ExpiredTime" should be 10 digits')));
  8319. }
  8320. KeyTime = self.options.StartTime + ';' + self.options.ExpiredTime * 1;
  8321. }
  8322. var Authorization = util.getAuth({
  8323. SecretId: params.SecretId || self.options.SecretId,
  8324. SecretKey: params.SecretKey || self.options.SecretKey,
  8325. Method: params.Method,
  8326. Pathname: Pathname,
  8327. Query: params.Query,
  8328. Headers: headers,
  8329. Expires: params.Expires,
  8330. KeyTime: KeyTime,
  8331. SystemClockOffset: self.options.SystemClockOffset,
  8332. ForceSignHost: forceSignHost
  8333. });
  8334. var AuthData = {
  8335. Authorization: Authorization,
  8336. SecurityToken: self.options.SecurityToken || self.options.XCosSecurityToken,
  8337. SignFrom: 'client'
  8338. };
  8339. cb(null, AuthData);
  8340. return AuthData;
  8341. }();
  8342. }
  8343. return '';
  8344. }
  8345. // 判断当前请求出错时能否重试
  8346. function allowRetry(err) {
  8347. var self = this;
  8348. var canRetry = false;
  8349. var networkError = false;
  8350. var isTimeError = false;
  8351. var serverDate = err.headers && (err.headers.date || err.headers.Date) || err.error && err.error.ServerTime;
  8352. try {
  8353. var errorCode = err.error.Code;
  8354. var errorMessage = err.error.Message;
  8355. if (errorCode === 'RequestTimeTooSkewed' || errorCode === 'AccessDenied' && errorMessage === 'Request has expired') {
  8356. isTimeError = true;
  8357. }
  8358. } catch (e) {}
  8359. if (err) {
  8360. if (isTimeError && serverDate) {
  8361. var serverTime = Date.parse(serverDate);
  8362. if (this.options.CorrectClockSkew && Math.abs(util.getSkewTime(this.options.SystemClockOffset) - serverTime) >= 30000) {
  8363. console.error('error: Local time is too skewed.');
  8364. this.options.SystemClockOffset = serverTime - Date.now();
  8365. canRetry = true;
  8366. }
  8367. } else if (Math.floor(err.statusCode / 100) === 5) {
  8368. canRetry = true;
  8369. }
  8370. /**
  8371. * 归为网络错误
  8372. * 1、no statusCode
  8373. * 2、statusCode === 3xx || 4xx || 5xx && no requestId
  8374. */
  8375. if (!err.statusCode) {
  8376. canRetry = self.options.AutoSwitchHost;
  8377. networkError = true;
  8378. } else {
  8379. var statusCode = Math.floor(err.statusCode / 100);
  8380. var requestId = (err === null || err === void 0 ? void 0 : err.headers) && (err === null || err === void 0 ? void 0 : err.headers['x-cos-request-id']);
  8381. if ([3, 4, 5].includes(statusCode) && !requestId) {
  8382. canRetry = self.options.AutoSwitchHost;
  8383. networkError = true;
  8384. }
  8385. }
  8386. }
  8387. return {
  8388. canRetry: canRetry,
  8389. networkError: networkError
  8390. };
  8391. }
  8392. /**
  8393. * requestUrl:请求的url,用于判断是否cos主域名,true才切
  8394. * clientCalcSign:是否客户端计算签名,服务端返回的签名不能切,true才切
  8395. * networkError:是否未知网络错误,true才切
  8396. * */
  8397. function canSwitchHost(_ref) {
  8398. var requestUrl = _ref.requestUrl,
  8399. clientCalcSign = _ref.clientCalcSign,
  8400. networkError = _ref.networkError;
  8401. if (!this.options.AutoSwitchHost) return false;
  8402. if (!requestUrl) return false;
  8403. if (!clientCalcSign) return false;
  8404. if (!networkError) return false;
  8405. var commonReg = /^https?:\/\/[^\/]*\.cos\.[^\/]*\.myqcloud\.com(\/.*)?$/;
  8406. var accelerateReg = /^https?:\/\/[^\/]*\.cos\.accelerate\.myqcloud\.com(\/.*)?$/;
  8407. // 当前域名是cos主域名才切换
  8408. var isCommonCosHost = commonReg.test(requestUrl) && !accelerateReg.test(requestUrl);
  8409. return isCommonCosHost;
  8410. }
  8411. // 获取签名并发起请求
  8412. function submitRequest(params, callback) {
  8413. var self = this;
  8414. // 处理 headers
  8415. !params.headers && (params.headers = {});
  8416. // 处理 query
  8417. !params.qs && (params.qs = {});
  8418. params.VersionId && (params.qs.versionId = params.VersionId);
  8419. params.qs = util.clearKey(params.qs);
  8420. // 清理 undefined 和 null 字段
  8421. params.headers && (params.headers = util.clearKey(params.headers));
  8422. params.qs && (params.qs = util.clearKey(params.qs));
  8423. var Query = util.clone(params.qs);
  8424. params.action && (Query[params.action] = '');
  8425. var paramsUrl = params.url || params.Url;
  8426. var SignHost = params.SignHost || getSignHost.call(this, {
  8427. Bucket: params.Bucket,
  8428. Region: params.Region,
  8429. Url: paramsUrl
  8430. });
  8431. var tracker = params.tracker;
  8432. var next = function next(tryTimes) {
  8433. var oldClockOffset = self.options.SystemClockOffset;
  8434. if (params.SwitchHost) {
  8435. // 更换要签的host
  8436. SignHost = SignHost.replace(/myqcloud.com/, 'tencentcos.cn');
  8437. }
  8438. tracker && tracker.setParams({
  8439. signStartTime: new Date().getTime(),
  8440. httpRetryTimes: tryTimes - 1
  8441. });
  8442. getAuthorizationAsync.call(self, {
  8443. Bucket: params.Bucket || '',
  8444. Region: params.Region || '',
  8445. Method: params.method,
  8446. Key: params.Key,
  8447. Query: Query,
  8448. Headers: params.headers,
  8449. SignHost: SignHost,
  8450. Action: params.Action,
  8451. ResourceKey: params.ResourceKey,
  8452. Scope: params.Scope,
  8453. ForceSignHost: self.options.ForceSignHost
  8454. }, function (err, AuthData) {
  8455. if (err) {
  8456. callback(err);
  8457. return;
  8458. }
  8459. tracker && tracker.setParams({
  8460. signEndTime: new Date().getTime(),
  8461. httpStartTime: new Date().getTime()
  8462. });
  8463. params.AuthData = AuthData;
  8464. _submitRequest.call(self, params, function (err, data) {
  8465. var canRetry = false;
  8466. var networkError = false;
  8467. if (err) {
  8468. var info = allowRetry.call(self, err);
  8469. canRetry = info.canRetry || oldClockOffset !== self.options.SystemClockOffset;
  8470. networkError = info.networkError;
  8471. }
  8472. tracker && tracker.setParams({
  8473. httpEndTime: new Date().getTime()
  8474. });
  8475. if (err && tryTimes < 2 && canRetry) {
  8476. if (params.headers) {
  8477. delete params.headers.Authorization;
  8478. delete params.headers['token'];
  8479. delete params.headers['clientIP'];
  8480. delete params.headers['clientUA'];
  8481. params.headers['x-cos-security-token'] && delete params.headers['x-cos-security-token'];
  8482. params.headers['x-ci-security-token'] && delete params.headers['x-ci-security-token'];
  8483. }
  8484. // 进入重试逻辑时 需判断是否需要切换cos备用域名
  8485. var switchHost = canSwitchHost.call(self, {
  8486. requestUrl: (err === null || err === void 0 ? void 0 : err.url) || '',
  8487. clientCalcSign: (AuthData === null || AuthData === void 0 ? void 0 : AuthData.SignFrom) === 'client',
  8488. networkError: networkError
  8489. });
  8490. params.SwitchHost = switchHost;
  8491. params.retry = true;
  8492. next(tryTimes + 1);
  8493. } else {
  8494. callback(err, data);
  8495. }
  8496. });
  8497. });
  8498. };
  8499. next(1);
  8500. }
  8501. // 发起请求
  8502. function _submitRequest(params, callback) {
  8503. var self = this;
  8504. var TaskId = params.TaskId;
  8505. if (TaskId && !self._isRunningTask(TaskId)) return;
  8506. var bucket = params.Bucket;
  8507. var region = params.Region;
  8508. var object = params.Key;
  8509. var method = params.method || 'GET';
  8510. var url = params.url || params.Url;
  8511. var body = params.body;
  8512. var json = params.json;
  8513. var rawBody = params.rawBody;
  8514. var dataType = params.dataType;
  8515. var httpDNSServiceId = self.options.HttpDNSServiceId;
  8516. // url
  8517. if (self.options.UseAccelerate) {
  8518. region = 'accelerate';
  8519. }
  8520. url = url || getUrl({
  8521. ForcePathStyle: self.options.ForcePathStyle,
  8522. protocol: self.options.Protocol,
  8523. domain: self.options.Domain,
  8524. bucket: bucket,
  8525. region: region,
  8526. object: object
  8527. });
  8528. if (params.SwitchHost) {
  8529. // 更换请求的url
  8530. url = url.replace(/myqcloud.com/, 'tencentcos.cn');
  8531. }
  8532. var repoterUrl = object ? url : '';
  8533. if (params.action) {
  8534. url = url + '?' + params.action;
  8535. }
  8536. if (params.qsStr) {
  8537. if (url.indexOf('?') > -1) {
  8538. url = url + '&' + params.qsStr;
  8539. } else {
  8540. url = url + '?' + params.qsStr;
  8541. }
  8542. }
  8543. var opt = {
  8544. method: method,
  8545. url: url,
  8546. headers: params.headers,
  8547. qs: params.qs,
  8548. filePath: params.filePath,
  8549. body: body,
  8550. json: json,
  8551. httpDNSServiceId: httpDNSServiceId,
  8552. dataType: dataType
  8553. };
  8554. // 兼容ci接口
  8555. var token = 'x-cos-security-token';
  8556. if (util.isCIHost(url)) {
  8557. token = 'x-ci-security-token';
  8558. }
  8559. // 获取签名
  8560. opt.headers.Authorization = params.AuthData.Authorization;
  8561. params.AuthData.Token && (opt.headers['token'] = params.AuthData.Token);
  8562. params.AuthData.ClientIP && (opt.headers['clientIP'] = params.AuthData.ClientIP);
  8563. params.AuthData.ClientUA && (opt.headers['clientUA'] = params.AuthData.ClientUA);
  8564. params.AuthData.SecurityToken && (opt.headers[token] = params.AuthData.SecurityToken);
  8565. // 清理 undefined 和 null 字段
  8566. opt.headers && (opt.headers = util.clearKey(opt.headers));
  8567. if (params.retry) {
  8568. opt.headers['x-cos-sdk-retry'] = true;
  8569. }
  8570. opt = util.clearKey(opt);
  8571. // progress
  8572. if (params.onProgress && typeof params.onProgress === 'function') {
  8573. opt.onProgress = function (e) {
  8574. if (TaskId && !self._isRunningTask(TaskId)) return;
  8575. var loaded = e ? e.loaded : 0;
  8576. params.onProgress({
  8577. loaded: loaded,
  8578. total: e.total
  8579. });
  8580. };
  8581. }
  8582. if (this.options.Timeout) {
  8583. opt.timeout = this.options.Timeout;
  8584. }
  8585. self.options.ForcePathStyle && (opt.pathStyle = self.options.ForcePathStyle);
  8586. self.emit('before-send', opt);
  8587. var useAccelerate = opt.url.includes('accelerate.');
  8588. var queryString = opt.qs ? Object.keys(opt.qs).map(function (key) {
  8589. return "".concat(key, "=").concat(opt.qs[key]);
  8590. }).join('&') : '';
  8591. var fullUrl = queryString ? opt.url + '?' + queryString : opt.url;
  8592. if (params.tracker) {
  8593. var _opt$body;
  8594. params.tracker.setParams({
  8595. url: fullUrl,
  8596. httpMethod: opt.method,
  8597. accelerate: useAccelerate,
  8598. httpSize: ((_opt$body = opt.body) === null || _opt$body === void 0 ? void 0 : _opt$body.size) || 0
  8599. });
  8600. // 分块上传时给父级tracker设置url信息
  8601. if (params.tracker.parent && !params.tracker.parent.params.url) {
  8602. params.tracker.parent.setParams({
  8603. url: repoterUrl,
  8604. accelerate: useAccelerate
  8605. });
  8606. }
  8607. }
  8608. var sender = REQUEST(opt, function (err, response, body) {
  8609. if (err === 'abort') return;
  8610. // 返回内容添加 状态码 和 headers
  8611. var hasReturned;
  8612. var cb = function cb(err, data) {
  8613. TaskId && self.off('inner-kill-task', killTask);
  8614. if (hasReturned) return;
  8615. hasReturned = true;
  8616. var attrs = {};
  8617. response && response.statusCode && (attrs.statusCode = response.statusCode);
  8618. response && response.headers && (attrs.headers = response.headers);
  8619. if (err) {
  8620. opt.url && (attrs.url = opt.url);
  8621. opt.method && (attrs.method = opt.method);
  8622. err = util.extend(err || {}, attrs);
  8623. callback(err, null);
  8624. } else {
  8625. data = util.extend(data || {}, attrs);
  8626. callback(null, data);
  8627. }
  8628. sender = null;
  8629. };
  8630. // 请求错误,发生网络错误
  8631. if (err) {
  8632. cb({
  8633. error: err
  8634. });
  8635. return;
  8636. }
  8637. // 请求返回码不为 200
  8638. var statusCode = response.statusCode;
  8639. var statusSuccess = Math.floor(statusCode / 100) === 2; // 200 202 204 206
  8640. // 不对 body 进行转换,body 直接挂载返回
  8641. if (rawBody) {
  8642. if (statusSuccess) {
  8643. return cb(null, {
  8644. body: body
  8645. });
  8646. } else {
  8647. // 报错但是返回了 ArrayBuffer,需要解析成 string
  8648. if (body instanceof ArrayBuffer) {
  8649. var errorStr = util.arrayBufferToString(body);
  8650. var json = util.parseResBody(errorStr);
  8651. var errorBody = json.Error || json;
  8652. return cb({
  8653. error: errorBody
  8654. });
  8655. }
  8656. }
  8657. }
  8658. // 解析body,兼容 xml、json,解析失败时完整返回
  8659. var jsonRes = util.parseResBody(body);
  8660. if (!statusSuccess) {
  8661. cb({
  8662. error: jsonRes.Error || jsonRes
  8663. });
  8664. return;
  8665. }
  8666. if (jsonRes.Error) {
  8667. cb({
  8668. error: jsonRes.Error
  8669. });
  8670. return;
  8671. }
  8672. cb(null, jsonRes);
  8673. });
  8674. // kill task
  8675. var killTask = function killTask(data) {
  8676. if (data.TaskId === TaskId) {
  8677. sender && sender.abort && sender.abort();
  8678. self.off('inner-kill-task', killTask);
  8679. }
  8680. };
  8681. TaskId && self.on('inner-kill-task', killTask);
  8682. }
  8683. var API_MAP = {
  8684. // Bucket 相关方法
  8685. getService: getService,
  8686. // Bucket
  8687. putBucket: putBucket,
  8688. headBucket: headBucket,
  8689. // Bucket
  8690. getBucket: getBucket,
  8691. deleteBucket: deleteBucket,
  8692. putBucketAcl: putBucketAcl,
  8693. // BucketACL
  8694. getBucketAcl: getBucketAcl,
  8695. putBucketCors: putBucketCors,
  8696. // BucketCors
  8697. getBucketCors: getBucketCors,
  8698. deleteBucketCors: deleteBucketCors,
  8699. getBucketLocation: getBucketLocation,
  8700. // BucketLocation
  8701. getBucketPolicy: getBucketPolicy,
  8702. // BucketPolicy
  8703. putBucketPolicy: putBucketPolicy,
  8704. deleteBucketPolicy: deleteBucketPolicy,
  8705. putBucketTagging: putBucketTagging,
  8706. // BucketTagging
  8707. getBucketTagging: getBucketTagging,
  8708. deleteBucketTagging: deleteBucketTagging,
  8709. putBucketLifecycle: putBucketLifecycle,
  8710. // BucketLifecycle
  8711. getBucketLifecycle: getBucketLifecycle,
  8712. deleteBucketLifecycle: deleteBucketLifecycle,
  8713. putBucketVersioning: putBucketVersioning,
  8714. // BucketVersioning
  8715. getBucketVersioning: getBucketVersioning,
  8716. putBucketReplication: putBucketReplication,
  8717. // BucketReplication
  8718. getBucketReplication: getBucketReplication,
  8719. deleteBucketReplication: deleteBucketReplication,
  8720. putBucketWebsite: putBucketWebsite,
  8721. // BucketWebsite
  8722. getBucketWebsite: getBucketWebsite,
  8723. deleteBucketWebsite: deleteBucketWebsite,
  8724. putBucketReferer: putBucketReferer,
  8725. // BucketReferer
  8726. getBucketReferer: getBucketReferer,
  8727. putBucketDomain: putBucketDomain,
  8728. // BucketDomain
  8729. getBucketDomain: getBucketDomain,
  8730. deleteBucketDomain: deleteBucketDomain,
  8731. putBucketOrigin: putBucketOrigin,
  8732. // BucketOrigin
  8733. getBucketOrigin: getBucketOrigin,
  8734. deleteBucketOrigin: deleteBucketOrigin,
  8735. putBucketLogging: putBucketLogging,
  8736. // BucketLogging
  8737. getBucketLogging: getBucketLogging,
  8738. putBucketInventory: putBucketInventory,
  8739. // BucketInventory
  8740. getBucketInventory: getBucketInventory,
  8741. listBucketInventory: listBucketInventory,
  8742. deleteBucketInventory: deleteBucketInventory,
  8743. putBucketAccelerate: putBucketAccelerate,
  8744. getBucketAccelerate: getBucketAccelerate,
  8745. // Object 相关方法
  8746. getObject: getObject,
  8747. headObject: headObject,
  8748. listObjectVersions: listObjectVersions,
  8749. putObject: putObject,
  8750. postObject: postObject,
  8751. deleteObject: deleteObject,
  8752. getObjectAcl: getObjectAcl,
  8753. putObjectAcl: putObjectAcl,
  8754. optionsObject: optionsObject,
  8755. putObjectCopy: putObjectCopy,
  8756. deleteMultipleObject: deleteMultipleObject,
  8757. restoreObject: restoreObject,
  8758. putObjectTagging: putObjectTagging,
  8759. getObjectTagging: getObjectTagging,
  8760. deleteObjectTagging: deleteObjectTagging,
  8761. appendObject: appendObject,
  8762. // 分块上传相关方法
  8763. uploadPartCopy: uploadPartCopy,
  8764. multipartInit: multipartInit,
  8765. multipartUpload: multipartUpload,
  8766. multipartComplete: multipartComplete,
  8767. multipartList: multipartList,
  8768. multipartListPart: multipartListPart,
  8769. multipartAbort: multipartAbort,
  8770. // 工具方法
  8771. request: request,
  8772. getObjectUrl: getObjectUrl,
  8773. getAuth: getAuth
  8774. };
  8775. module.exports.init = function (COS, task) {
  8776. task.transferToTaskMethod(API_MAP, 'postObject');
  8777. task.transferToTaskMethod(API_MAP, 'putObject');
  8778. util.each(API_MAP, function (fn, apiName) {
  8779. COS.prototype[apiName] = util.apiWrapper(apiName, fn);
  8780. });
  8781. };
  8782. /***/ }),
  8783. /***/ "./src/cos.js":
  8784. /*!********************!*\
  8785. !*** ./src/cos.js ***!
  8786. \********************/
  8787. /*! no static exports found */
  8788. /***/ (function(module, exports, __webpack_require__) {
  8789. "use strict";
  8790. var util = __webpack_require__(/*! ./util */ "./src/util.js");
  8791. var event = __webpack_require__(/*! ./event */ "./src/event.js");
  8792. var task = __webpack_require__(/*! ./task */ "./src/task.js");
  8793. var base = __webpack_require__(/*! ./base */ "./src/base.js");
  8794. var advance = __webpack_require__(/*! ./advance */ "./src/advance.js");
  8795. var pkg = __webpack_require__(/*! ../package.json */ "./package.json");
  8796. var defaultOptions = {
  8797. SecretId: '',
  8798. SecretKey: '',
  8799. SecurityToken: '',
  8800. // 使用临时密钥需要注意自行刷新 Token
  8801. StartTime: 0,
  8802. // 临时密钥返回起始时间
  8803. ExpiredTime: 0,
  8804. // 临时密钥过期时间
  8805. ChunkRetryTimes: 2,
  8806. FileParallelLimit: 3,
  8807. ChunkParallelLimit: 3,
  8808. ChunkSize: 1024 * 1024,
  8809. SliceSize: 1024 * 1024,
  8810. CopyChunkParallelLimit: 20,
  8811. CopyChunkSize: 1024 * 1024 * 10,
  8812. CopySliceSize: 1024 * 1024 * 10,
  8813. MaxPartNumber: 10000,
  8814. ProgressInterval: 1000,
  8815. UploadQueueSize: 10000,
  8816. Domain: '',
  8817. ServiceDomain: '',
  8818. Protocol: '',
  8819. CompatibilityMode: false,
  8820. ForcePathStyle: false,
  8821. Timeout: 0,
  8822. // 单位毫秒,0 代表不设置超时时间
  8823. CorrectClockSkew: true,
  8824. SystemClockOffset: 0,
  8825. // 单位毫秒,ms
  8826. UploadCheckContentMd5: false,
  8827. UploadAddMetaMd5: false,
  8828. UploadIdCacheLimit: 50,
  8829. UseAccelerate: false,
  8830. ForceSignHost: true,
  8831. // 默认将host加入签名计算,关闭后可能导致越权风险,建议保持为true
  8832. HttpDNSServiceId: '',
  8833. // HttpDNS 服务商 Id,填写后代表开启 HttpDNS 服务。HttpDNS 用法详见https://developers.weixin.qq.com/miniprogram/dev/framework/ability/HTTPDNS.html
  8834. SimpleUploadMethod: 'postObject',
  8835. // 高级上传内部判断需要走简单上传时,指定的上传方法,可选postObject或putObject
  8836. AutoSwitchHost: false,
  8837. CopySourceParser: null,
  8838. // 自定义拷贝源解析器
  8839. ObjectKeySimplifyCheck: true,
  8840. // 开启合并校验 getObject Key
  8841. /** 上报相关配置 **/
  8842. DeepTracker: false,
  8843. // 上报时是否对每个分块上传做单独上报
  8844. TrackerDelay: 5000,
  8845. // 周期性上报,单位毫秒。0代表实时上报
  8846. CustomId: '',
  8847. // 自定义上报id
  8848. BeaconReporter: null,
  8849. // 灯塔上报组件,如有需要请自行传入,传入即代表开启上报
  8850. ClsReporter: null // cls 上报组件,如有需要请自行传入,传入即代表开启上报
  8851. };
  8852. // 对外暴露的类
  8853. var COS = function COS(options) {
  8854. this.options = util.extend(util.clone(defaultOptions), options || {});
  8855. this.options.FileParallelLimit = Math.max(1, this.options.FileParallelLimit);
  8856. this.options.ChunkParallelLimit = Math.max(1, this.options.ChunkParallelLimit);
  8857. this.options.ChunkRetryTimes = Math.max(0, this.options.ChunkRetryTimes);
  8858. this.options.ChunkSize = Math.max(1024 * 1024, this.options.ChunkSize);
  8859. this.options.CopyChunkParallelLimit = Math.max(1, this.options.CopyChunkParallelLimit);
  8860. this.options.CopyChunkSize = Math.max(1024 * 1024, this.options.CopyChunkSize);
  8861. this.options.CopySliceSize = Math.max(0, this.options.CopySliceSize);
  8862. this.options.MaxPartNumber = Math.max(1024, Math.min(10000, this.options.MaxPartNumber));
  8863. this.options.Timeout = Math.max(0, this.options.Timeout);
  8864. this.options.EnableReporter = this.options.BeaconReporter || this.options.ClsReporter;
  8865. if (this.options.AppId) {
  8866. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g: "test-1250000000").');
  8867. }
  8868. if (this.options.SecretId && this.options.SecretId.indexOf(' ') > -1) {
  8869. console.error('error: SecretId格式错误,请检查');
  8870. console.error('error: SecretId format is incorrect. Please check');
  8871. }
  8872. if (this.options.SecretKey && this.options.SecretKey.indexOf(' ') > -1) {
  8873. console.error('error: SecretKey格式错误,请检查');
  8874. console.error('error: SecretKey format is incorrect. Please check');
  8875. }
  8876. if (this.options.ForcePathStyle) {
  8877. console.warn('cos-wx-sdk-v5不再支持使用path-style,仅支持使用virtual-hosted-style,参考文档:https://cloud.tencent.com/document/product/436/96243');
  8878. throw new Error('ForcePathStyle is not supported');
  8879. }
  8880. event.init(this);
  8881. task.init(this);
  8882. };
  8883. base.init(COS, task);
  8884. advance.init(COS, task);
  8885. COS.util = {
  8886. md5: util.md5,
  8887. xml2json: util.xml2json,
  8888. json2xml: util.json2xml,
  8889. encodeBase64: util.encodeBase64
  8890. };
  8891. COS.getAuthorization = util.getAuth;
  8892. COS.version = pkg.version;
  8893. module.exports = COS;
  8894. /***/ }),
  8895. /***/ "./src/event.js":
  8896. /*!**********************!*\
  8897. !*** ./src/event.js ***!
  8898. \**********************/
  8899. /*! no static exports found */
  8900. /***/ (function(module, exports) {
  8901. var initEvent = function initEvent(cos) {
  8902. var listeners = {};
  8903. var getList = function getList(action) {
  8904. !listeners[action] && (listeners[action] = []);
  8905. return listeners[action];
  8906. };
  8907. cos.on = function (action, callback) {
  8908. getList(action).push(callback);
  8909. };
  8910. cos.off = function (action, callback) {
  8911. var list = getList(action);
  8912. for (var i = list.length - 1; i >= 0; i--) {
  8913. callback === list[i] && list.splice(i, 1);
  8914. }
  8915. };
  8916. cos.emit = function (action, data) {
  8917. var list = getList(action).map(function (cb) {
  8918. return cb;
  8919. });
  8920. for (var i = 0; i < list.length; i++) {
  8921. list[i](data);
  8922. }
  8923. };
  8924. };
  8925. var EventProxy = function EventProxy() {
  8926. initEvent(this);
  8927. };
  8928. module.exports.init = initEvent;
  8929. module.exports.EventProxy = EventProxy;
  8930. /***/ }),
  8931. /***/ "./src/session.js":
  8932. /*!************************!*\
  8933. !*** ./src/session.js ***!
  8934. \************************/
  8935. /*! no static exports found */
  8936. /***/ (function(module, exports, __webpack_require__) {
  8937. var util = __webpack_require__(/*! ./util */ "./src/util.js");
  8938. // 按照文件特征值,缓存 UploadId
  8939. var cacheKey = 'cos_sdk_upload_cache';
  8940. var expires = 30 * 24 * 3600;
  8941. var cache;
  8942. var timer;
  8943. var getCache = function getCache() {
  8944. try {
  8945. var val = JSON.parse(wx.getStorageSync(cacheKey));
  8946. } catch (e) {}
  8947. if (!val) val = [];
  8948. return val;
  8949. };
  8950. var setCache = function setCache() {
  8951. try {
  8952. if (cache.length) wx.setStorageSync(cacheKey, JSON.stringify(cache));else wx.removeStorageSync(cacheKey);
  8953. } catch (e) {}
  8954. };
  8955. var init = function init() {
  8956. if (cache) return;
  8957. cache = getCache();
  8958. // 清理太老旧的数据
  8959. var changed = false;
  8960. var now = Math.round(Date.now() / 1000);
  8961. for (var i = cache.length - 1; i >= 0; i--) {
  8962. var mtime = cache[i][2];
  8963. if (!mtime || mtime + expires < now) {
  8964. cache.splice(i, 1);
  8965. changed = true;
  8966. }
  8967. }
  8968. changed && setCache();
  8969. };
  8970. // 把缓存存到本地
  8971. var save = function save() {
  8972. if (timer) return;
  8973. timer = setTimeout(function () {
  8974. setCache();
  8975. timer = null;
  8976. }, 400);
  8977. };
  8978. var mod = {
  8979. using: {},
  8980. // 标记 UploadId 正在使用
  8981. setUsing: function setUsing(uuid) {
  8982. mod.using[uuid] = true;
  8983. },
  8984. // 标记 UploadId 已经没在使用
  8985. removeUsing: function removeUsing(uuid) {
  8986. delete mod.using[uuid];
  8987. },
  8988. // 用上传参数生成哈希值
  8989. getFileId: function getFileId(FileStat, ChunkSize, Bucket, Key) {
  8990. if (FileStat.FilePath && FileStat.size && FileStat.lastModifiedTime && ChunkSize) {
  8991. return util.md5([FileStat.FilePath].join('::')) + '-' + util.md5([FileStat.size, FileStat.mode, FileStat.lastAccessedTime, FileStat.lastModifiedTime, ChunkSize, Bucket, Key].join('::'));
  8992. } else {
  8993. return null;
  8994. }
  8995. },
  8996. // 用上传参数生成哈希值
  8997. getCopyFileId: function getCopyFileId(copySource, sourceHeaders, ChunkSize, Bucket, Key) {
  8998. var size = sourceHeaders['content-length'];
  8999. var etag = sourceHeaders.etag || '';
  9000. var lastModified = sourceHeaders['last-modified'];
  9001. if (copySource && ChunkSize) {
  9002. return util.md5([copySource, size, etag, lastModified, ChunkSize, Bucket, Key].join('::'));
  9003. } else {
  9004. return null;
  9005. }
  9006. },
  9007. // 获取文件对应的 UploadId 列表
  9008. getUploadIdList: function getUploadIdList(uuid) {
  9009. if (!uuid) return null;
  9010. init();
  9011. var list = [];
  9012. for (var i = 0; i < cache.length; i++) {
  9013. if (cache[i][0] === uuid) list.push(cache[i][1]);
  9014. }
  9015. return list.length ? list : null;
  9016. },
  9017. // 缓存 UploadId
  9018. saveUploadId: function saveUploadId(uuid, UploadId, limit) {
  9019. init();
  9020. if (!uuid) return;
  9021. // 清理没用的 UploadId
  9022. var part1 = uuid.substr(0, uuid.indexOf('-') + 1);
  9023. for (var i = cache.length - 1; i >= 0; i--) {
  9024. var item = cache[i];
  9025. if (item[0] === uuid && item[1] === UploadId) {
  9026. cache.splice(i, 1);
  9027. } else if (uuid !== item[0] && item[0].indexOf(part1) === 0) {
  9028. // 文件路径相同,但其他信息不同,说明文件改变了或上传参数(存储桶、路径、分片大小)变了,直接清理掉
  9029. cache.splice(i, 1);
  9030. }
  9031. }
  9032. cache.unshift([uuid, UploadId, Math.round(Date.now() / 1000)]);
  9033. if (cache.length > limit) cache.splice(limit);
  9034. save();
  9035. },
  9036. // UploadId 已用完,移除掉
  9037. removeUploadId: function removeUploadId(UploadId) {
  9038. init();
  9039. delete mod.using[UploadId];
  9040. for (var i = cache.length - 1; i >= 0; i--) {
  9041. if (cache[i][1] === UploadId) cache.splice(i, 1);
  9042. }
  9043. save();
  9044. }
  9045. };
  9046. module.exports = mod;
  9047. /***/ }),
  9048. /***/ "./src/task.js":
  9049. /*!*********************!*\
  9050. !*** ./src/task.js ***!
  9051. \*********************/
  9052. /*! no static exports found */
  9053. /***/ (function(module, exports, __webpack_require__) {
  9054. var session = __webpack_require__(/*! ./session */ "./src/session.js");
  9055. var util = __webpack_require__(/*! ./util */ "./src/util.js");
  9056. var originApiMap = {};
  9057. var transferToTaskMethod = function transferToTaskMethod(apiMap, apiName) {
  9058. originApiMap[apiName] = apiMap[apiName];
  9059. apiMap[apiName] = function (params, callback) {
  9060. if (params.SkipTask) {
  9061. originApiMap[apiName].call(this, params, callback);
  9062. } else {
  9063. this._addTask(apiName, params, callback);
  9064. }
  9065. };
  9066. };
  9067. var initTask = function initTask(cos) {
  9068. var queue = [];
  9069. var tasks = {};
  9070. var uploadingFileCount = 0;
  9071. var nextUploadIndex = 0;
  9072. // 接口返回简略的任务信息
  9073. var formatTask = function formatTask(task) {
  9074. var t = {
  9075. id: task.id,
  9076. Bucket: task.Bucket,
  9077. Region: task.Region,
  9078. Key: task.Key,
  9079. FilePath: task.FilePath,
  9080. state: task.state,
  9081. loaded: task.loaded,
  9082. size: task.size,
  9083. speed: task.speed,
  9084. percent: task.percent,
  9085. hashPercent: task.hashPercent,
  9086. error: task.error
  9087. };
  9088. if (task.FilePath) t.FilePath = task.FilePath;
  9089. return t;
  9090. };
  9091. var emitListUpdate = function () {
  9092. var timer;
  9093. var emit = function emit() {
  9094. timer = 0;
  9095. cos.emit('task-list-update', {
  9096. list: util.map(queue, formatTask)
  9097. });
  9098. cos.emit('list-update', {
  9099. list: util.map(queue, formatTask)
  9100. });
  9101. };
  9102. return function () {
  9103. if (!timer) timer = setTimeout(emit);
  9104. };
  9105. }();
  9106. var clearQueue = function clearQueue() {
  9107. if (queue.length <= cos.options.UploadQueueSize) return;
  9108. for
  9109. // 如果还太多,才继续清理
  9110. (var i = 0; i < nextUploadIndex &&
  9111. // 小于当前操作的 index 才清理
  9112. i < queue.length &&
  9113. // 大于队列才清理
  9114. queue.length > cos.options.UploadQueueSize;) {
  9115. var isActive = queue[i].state === 'waiting' || queue[i].state === 'checking' || queue[i].state === 'uploading';
  9116. if (!queue[i] || !isActive) {
  9117. tasks[queue[i].id] && delete tasks[queue[i].id];
  9118. queue.splice(i, 1);
  9119. nextUploadIndex--;
  9120. } else {
  9121. i++;
  9122. }
  9123. }
  9124. emitListUpdate();
  9125. };
  9126. var startNextTask = function startNextTask() {
  9127. // 检查是否允许增加执行进程
  9128. if (uploadingFileCount >= cos.options.FileParallelLimit) return;
  9129. // 跳过不可执行的任务
  9130. while (queue[nextUploadIndex] && queue[nextUploadIndex].state !== 'waiting') nextUploadIndex++;
  9131. // 检查是否已遍历结束
  9132. if (nextUploadIndex >= queue.length) return;
  9133. // 上传该遍历到的任务
  9134. var task = queue[nextUploadIndex];
  9135. nextUploadIndex++;
  9136. uploadingFileCount++;
  9137. task.state = 'checking';
  9138. task.params.onTaskStart && task.params.onTaskStart(formatTask(task));
  9139. !task.params.UploadData && (task.params.UploadData = {});
  9140. var apiParams = util.formatParams(task.api, task.params);
  9141. originApiMap[task.api].call(cos, apiParams, function (err, data) {
  9142. if (!cos._isRunningTask(task.id)) return;
  9143. if (task.state === 'checking' || task.state === 'uploading') {
  9144. task.state = err ? 'error' : 'success';
  9145. err && (task.error = err);
  9146. uploadingFileCount--;
  9147. emitListUpdate();
  9148. startNextTask();
  9149. task.callback && task.callback(err, data);
  9150. if (task.state === 'success') {
  9151. if (task.params) {
  9152. delete task.params.UploadData;
  9153. delete task.params.Body;
  9154. delete task.params;
  9155. }
  9156. delete task.callback;
  9157. }
  9158. }
  9159. clearQueue();
  9160. });
  9161. emitListUpdate();
  9162. // 异步执行下一个任务
  9163. setTimeout(startNextTask);
  9164. };
  9165. var killTask = function killTask(id, switchToState) {
  9166. var task = tasks[id];
  9167. if (!task) return;
  9168. var waiting = task && task.state === 'waiting';
  9169. var running = task && (task.state === 'checking' || task.state === 'uploading');
  9170. if (switchToState === 'canceled' && task.state !== 'canceled' || switchToState === 'paused' && waiting || switchToState === 'paused' && running) {
  9171. if (switchToState === 'paused' && task.params.Body && typeof task.params.Body.pipe === 'function') {
  9172. console.error('stream not support pause');
  9173. return;
  9174. }
  9175. task.state = switchToState;
  9176. cos.emit('inner-kill-task', {
  9177. TaskId: id,
  9178. toState: switchToState
  9179. });
  9180. try {
  9181. var UploadId = task && task.params && task.params.UploadData.UploadId;
  9182. } catch (e) {}
  9183. if (switchToState === 'canceled' && UploadId) session.removeUsing(UploadId);
  9184. emitListUpdate();
  9185. if (running) {
  9186. uploadingFileCount--;
  9187. startNextTask();
  9188. }
  9189. if (switchToState === 'canceled') {
  9190. if (task.params) {
  9191. delete task.params.UploadData;
  9192. delete task.params.Body;
  9193. delete task.params;
  9194. }
  9195. delete task.callback;
  9196. }
  9197. }
  9198. clearQueue();
  9199. };
  9200. cos._addTasks = function (taskList) {
  9201. util.each(taskList, function (task) {
  9202. cos._addTask(task.api, task.params, task.callback, true);
  9203. });
  9204. emitListUpdate();
  9205. };
  9206. cos._addTask = function (api, params, callback, ignoreAddEvent) {
  9207. // 如果小程序版本不支持获取文件分片内容,统一转到 简单上传 接口上传
  9208. var simpleUploadMethod = cos.options.SimpleUploadMethod === 'postObject' ? 'postObject' : 'putObject';
  9209. if (api === 'sliceUploadFile' && !util.canFileSlice()) api = simpleUploadMethod;
  9210. // 复制参数对象
  9211. params = util.formatParams(api, params);
  9212. // 生成 id
  9213. var id = util.uuid();
  9214. params.TaskId = id;
  9215. params.onTaskReady && params.onTaskReady(id);
  9216. var task = {
  9217. // env
  9218. params: params,
  9219. callback: callback,
  9220. api: api,
  9221. index: queue.length,
  9222. // task
  9223. id: id,
  9224. Bucket: params.Bucket,
  9225. Region: params.Region,
  9226. Key: params.Key,
  9227. FilePath: params.FilePath || '',
  9228. state: 'waiting',
  9229. loaded: 0,
  9230. size: 0,
  9231. speed: 0,
  9232. percent: 0,
  9233. hashPercent: 0,
  9234. error: null
  9235. };
  9236. var onHashProgress = params.onHashProgress;
  9237. params.onHashProgress = function (info) {
  9238. if (!cos._isRunningTask(task.id)) return;
  9239. task.hashPercent = info.percent;
  9240. onHashProgress && onHashProgress(info);
  9241. emitListUpdate();
  9242. };
  9243. var onProgress = params.onProgress;
  9244. params.onProgress = function (info) {
  9245. if (!cos._isRunningTask(task.id)) return;
  9246. task.state === 'checking' && (task.state = 'uploading');
  9247. task.loaded = info.loaded;
  9248. task.size = info.total;
  9249. task.speed = info.speed;
  9250. task.percent = info.percent;
  9251. onProgress && onProgress(info);
  9252. emitListUpdate();
  9253. };
  9254. // 异步获取 filesize
  9255. util.getFileSize(api, params, function (err, size) {
  9256. // 开始处理上传
  9257. if (err) {
  9258. // 如果获取大小出错,不加入队列
  9259. callback(err);
  9260. return;
  9261. }
  9262. // 获取完文件大小再把任务加入队列
  9263. tasks[id] = task;
  9264. queue.push(task);
  9265. task.size = size;
  9266. !ignoreAddEvent && emitListUpdate();
  9267. startNextTask();
  9268. clearQueue();
  9269. });
  9270. return id;
  9271. };
  9272. cos._isRunningTask = function (id) {
  9273. var task = tasks[id];
  9274. return !!(task && (task.state === 'checking' || task.state === 'uploading'));
  9275. };
  9276. cos.getTaskList = function () {
  9277. return util.map(queue, formatTask);
  9278. };
  9279. cos.cancelTask = function (id) {
  9280. killTask(id, 'canceled');
  9281. };
  9282. cos.pauseTask = function (id) {
  9283. killTask(id, 'paused');
  9284. };
  9285. cos.restartTask = function (id) {
  9286. var task = tasks[id];
  9287. if (task && (task.state === 'paused' || task.state === 'error')) {
  9288. task.state = 'waiting';
  9289. emitListUpdate();
  9290. nextUploadIndex = Math.min(nextUploadIndex, task.index);
  9291. startNextTask();
  9292. }
  9293. };
  9294. cos.isUploadRunning = function () {
  9295. return uploadingFileCount || nextUploadIndex < queue.length;
  9296. };
  9297. };
  9298. module.exports.transferToTaskMethod = transferToTaskMethod;
  9299. module.exports.init = initTask;
  9300. /***/ }),
  9301. /***/ "./src/tracker.js":
  9302. /*!************************!*\
  9303. !*** ./src/tracker.js ***!
  9304. \************************/
  9305. /*! no static exports found */
  9306. /***/ (function(module, exports, __webpack_require__) {
  9307. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  9308. function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
  9309. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  9310. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  9311. function _defineProperty(obj, key, value) { key = _toPropertyKey(key); if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
  9312. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  9313. function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
  9314. function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
  9315. function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == _typeof(i) ? i : i + ""; }
  9316. function _toPrimitive(t, r) { if ("object" != _typeof(t) || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != _typeof(i)) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
  9317. var pkg = __webpack_require__(/*! ../package.json */ "./package.json");
  9318. var beacon = null;
  9319. var getBeacon = function getBeacon(Beacon, delay) {
  9320. if (!beacon) {
  9321. // 生成 beacon
  9322. if (typeof Beacon !== 'function') {
  9323. throw new Error('Beacon not found');
  9324. }
  9325. beacon = new Beacon({
  9326. appkey: '0WEB05PY6MHRGK0U',
  9327. versionCode: pkg.version,
  9328. channelID: 'mp_sdk',
  9329. //渠道,选填
  9330. openid: 'openid',
  9331. // 用户id, 选填
  9332. unionid: 'unid',
  9333. //用户unionid , 类似idfv,选填
  9334. strictMode: false,
  9335. //严苛模式开关, 打开严苛模式会主动抛出异常, 上线请务必关闭!!!
  9336. delay: delay,
  9337. // 普通事件延迟上报时间(单位毫秒), 默认1000(1秒),选填
  9338. sessionDuration: 60 * 1000 // session变更的时间间隔, 一个用户持续30分钟(默认值)没有任何上报则算另一次 session,每变更一次session上报一次启动事件(rqd_applaunched),使用毫秒(ms),最小值30秒,选填
  9339. });
  9340. }
  9341. return beacon;
  9342. };
  9343. // 毫秒转秒
  9344. var ms2s = function ms2s(ms) {
  9345. if (!ms || ms < 0) return 0;
  9346. return (ms / 1000).toFixed(3);
  9347. };
  9348. var utils = {
  9349. // 生成uid 每个链路对应唯一一条uid
  9350. getUid: function getUid() {
  9351. var S4 = function S4() {
  9352. return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
  9353. };
  9354. return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
  9355. },
  9356. // 获取网络类型 4g | wifi
  9357. getNetType: function getNetType() {
  9358. return new Promise(function (resolve) {
  9359. if (wx.canIUse('getNetworkType')) {
  9360. try {
  9361. wx.getNetworkType({
  9362. success: function success(res) {
  9363. resolve(res.networkType);
  9364. }
  9365. });
  9366. } catch (e) {
  9367. resolve('can_not_get_network_type');
  9368. }
  9369. } else {
  9370. resolve('can_not_get_network_type');
  9371. }
  9372. });
  9373. },
  9374. // 获取系统信息
  9375. getSystemInfo: function getSystemInfo() {
  9376. var defaultInfo = {
  9377. devicePlatform: '',
  9378. wxVersion: '',
  9379. wxSystem: '',
  9380. wxSdkVersion: ''
  9381. };
  9382. return new Promise(function (resolve) {
  9383. if (wx.canIUse('getSystemInfo')) {
  9384. try {
  9385. wx.getSystemInfo({
  9386. success: function success(res) {
  9387. var platform = res.platform,
  9388. version = res.version,
  9389. system = res.system,
  9390. SDKVersion = res.SDKVersion;
  9391. Object.assign(defaultInfo, {
  9392. devicePlatform: platform,
  9393. wxVersion: version,
  9394. wxSystem: system,
  9395. wxSdkVersion: SDKVersion
  9396. });
  9397. resolve(defaultInfo);
  9398. }
  9399. });
  9400. } catch (e) {
  9401. resolve({
  9402. devicePlatform: 'can_not_get_system_info',
  9403. wxVersion: 'can_not_get_system_info',
  9404. wxSystem: 'can_not_get_system_info',
  9405. wxSdkVersion: 'can_not_get_system_info'
  9406. });
  9407. }
  9408. } else {
  9409. resolve({
  9410. devicePlatform: 'can_not_get_system_info',
  9411. wxVersion: 'can_not_get_system_info',
  9412. wxSystem: 'can_not_get_system_info',
  9413. wxSdkVersion: 'can_not_get_system_info'
  9414. });
  9415. }
  9416. });
  9417. }
  9418. };
  9419. // 设备信息,只取一次值
  9420. var deviceInfo = {
  9421. // ↓上报项
  9422. devicePlatform: '',
  9423. // ios/anroid/windows/mac/devtools
  9424. wxVersion: '',
  9425. wxSystem: '',
  9426. wxSdkVersion: ''
  9427. };
  9428. utils.getSystemInfo().then(function (res) {
  9429. Object.assign(deviceInfo, res);
  9430. });
  9431. var transApiName = function transApiName(api) {
  9432. if (['putObject', 'sliceUploadFile', 'uploadFile', 'uploadFiles'].includes(api)) {
  9433. return 'UploadTask';
  9434. } else if (api === 'getObject') {
  9435. return 'DownloadTask';
  9436. } else if (['putObjectCopy', 'sliceCopyFile'].includes(api)) {
  9437. return 'CopyTask';
  9438. }
  9439. return api;
  9440. };
  9441. // 上报参数驼峰改下划线
  9442. function camel2underline(key) {
  9443. return key.replace(/([A-Z])/g, '_$1').toLowerCase();
  9444. }
  9445. function formatParams(params) {
  9446. var formattedParams = {};
  9447. var successKeys = ['sdkVersionName', 'sdkVersionCode', 'osName', 'networkType', 'requestName', 'requestResult', 'bucket', 'region', 'appid', 'accelerate', 'url', 'host', 'requestPath', 'userAgent', 'httpMethod', 'httpSize', 'httpSpeed', 'httpTookTime', 'httpMd5', 'httpSign', 'httpFullTime', 'httpDomain', 'partNumber', 'httpRetryTimes', 'customId', 'traceId', 'realApi'];
  9448. var failureKeys = [].concat(successKeys, ['errorNode', 'errorCode', 'errorName', 'errorMessage', 'errorRequestId', 'errorHttpCode', 'errorServiceName', 'errorType', 'fullError']);
  9449. // 需要上报的参数字段
  9450. var reporterKeys = params.requestResult === 'Success' ? successKeys : failureKeys;
  9451. for (var key in params) {
  9452. if (!reporterKeys.includes(key)) continue;
  9453. var formattedKey = camel2underline(key);
  9454. formattedParams[formattedKey] = params[key];
  9455. }
  9456. formattedParams['request_name'] = params.realApi ? transApiName(params.realApi) : params.requestName;
  9457. return formattedParams;
  9458. }
  9459. // 链路追踪器
  9460. var Tracker = /*#__PURE__*/function () {
  9461. function Tracker(opt) {
  9462. var _this$params;
  9463. _classCallCheck(this, Tracker);
  9464. var parent = opt.parent,
  9465. traceId = opt.traceId,
  9466. bucket = opt.bucket,
  9467. region = opt.region,
  9468. apiName = opt.apiName,
  9469. realApi = opt.realApi,
  9470. httpMethod = opt.httpMethod,
  9471. fileKey = opt.fileKey,
  9472. fileSize = opt.fileSize,
  9473. accelerate = opt.accelerate,
  9474. customId = opt.customId,
  9475. delay = opt.delay,
  9476. deepTracker = opt.deepTracker,
  9477. Beacon = opt.Beacon,
  9478. clsReporter = opt.clsReporter;
  9479. var appid = bucket && bucket.substr(bucket.lastIndexOf('-') + 1) || '';
  9480. this.parent = parent;
  9481. this.deepTracker = deepTracker;
  9482. this.delay = delay;
  9483. if (clsReporter && !this.clsReporter) {
  9484. this.clsReporter = clsReporter;
  9485. }
  9486. // 上报用到的字段
  9487. this.params = (_this$params = {
  9488. // 通用字段
  9489. sdkVersionName: 'cos-wx-sdk-v5',
  9490. sdkVersionCode: pkg.version,
  9491. osName: deviceInfo.devicePlatform,
  9492. networkType: '',
  9493. requestName: apiName || '',
  9494. requestResult: '',
  9495. // sdk api调用结果Success、Failure
  9496. realApi: realApi,
  9497. bucket: bucket,
  9498. region: region,
  9499. accelerate: accelerate,
  9500. httpMethod: httpMethod,
  9501. url: '',
  9502. host: '',
  9503. httpDomain: '',
  9504. requestPath: fileKey || '',
  9505. errorType: '',
  9506. errorCode: '',
  9507. errorName: '',
  9508. errorMessage: '',
  9509. errorRequestId: '',
  9510. errorHttpCode: 0,
  9511. errorServiceName: '',
  9512. errorNode: '',
  9513. httpTookTime: 0,
  9514. // http整体耗时
  9515. httpSize: fileSize || 0,
  9516. // 主要是文件大小,大小 B
  9517. httpMd5: 0,
  9518. // MD5耗时
  9519. httpSign: 0,
  9520. // 计算签名耗时
  9521. httpFullTime: 0,
  9522. // 任务整体耗时(包括md5、签名等)
  9523. httpSpeed: 0,
  9524. // 主要关注上传速度,KB/s
  9525. size: fileSize || 0
  9526. }, _defineProperty(_this$params, "httpMd5", 0), _defineProperty(_this$params, "httpSign", 0), _defineProperty(_this$params, "httpFull", 0), _defineProperty(_this$params, "name", apiName || ''), _defineProperty(_this$params, "tookTime", 0), _defineProperty(_this$params, "md5StartTime", 0), _defineProperty(_this$params, "md5EndTime", 0), _defineProperty(_this$params, "signStartTime", 0), _defineProperty(_this$params, "signEndTime", 0), _defineProperty(_this$params, "httpStartTime", 0), _defineProperty(_this$params, "httpEndTime", 0), _defineProperty(_this$params, "startTime", new Date().getTime()), _defineProperty(_this$params, "endTime", 0), _defineProperty(_this$params, "traceId", traceId || utils.getUid()), _defineProperty(_this$params, "appid", appid), _defineProperty(_this$params, "partNumber", 0), _defineProperty(_this$params, "httpRetryTimes", 0), _defineProperty(_this$params, "customId", customId || ''), _defineProperty(_this$params, "partTime", 0), _this$params);
  9527. if (Beacon) {
  9528. this.beacon = getBeacon(Beacon, delay);
  9529. }
  9530. }
  9531. // 格式化sdk回调
  9532. _createClass(Tracker, [{
  9533. key: "formatResult",
  9534. value: function () {
  9535. var _formatResult = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(err, data) {
  9536. var _err$error, _err$error$error, _err$error2, _err$error2$error, _err$error3, _err$error4, _err$error5, _err$error5$error, _err$error6;
  9537. var now, networkType, errorCode, errorMessage, errorName, errorHttpCode, errorServiceName, requestId, errorType, isSliceUploadFile, isSliceCopyFile, speed, httpFullTime, httpTookTime, _speed, httpMd5, httpSign, exec;
  9538. return _regeneratorRuntime().wrap(function _callee$(_context) {
  9539. while (1) switch (_context.prev = _context.next) {
  9540. case 0:
  9541. /**
  9542. * 解析到err的格式为:
  9543. * 1.服务端有返回时
  9544. * {
  9545. * err: 同下方error,
  9546. * error: {
  9547. * error: {
  9548. * Code: '', Message: '', Resource: '', RequestId: '', TraceId: '',
  9549. * },
  9550. * statusCode: xxx,
  9551. * headers: {},
  9552. * RequestId: '',
  9553. * },
  9554. * }
  9555. * 2.本地抛出或小程序直接报错
  9556. * {error: 'message'}或{error: {error: 'message' }}
  9557. */
  9558. now = new Date().getTime();
  9559. _context.next = 3;
  9560. return utils.getNetType();
  9561. case 3:
  9562. networkType = _context.sent;
  9563. errorCode = err ? (err === null || err === void 0 ? void 0 : (_err$error = err.error) === null || _err$error === void 0 ? void 0 : (_err$error$error = _err$error.error) === null || _err$error$error === void 0 ? void 0 : _err$error$error.Code) || 'Error' : '';
  9564. errorMessage = err ? (err === null || err === void 0 ? void 0 : (_err$error2 = err.error) === null || _err$error2 === void 0 ? void 0 : (_err$error2$error = _err$error2.error) === null || _err$error2$error === void 0 ? void 0 : _err$error2$error.Message) || (err === null || err === void 0 ? void 0 : (_err$error3 = err.error) === null || _err$error3 === void 0 ? void 0 : _err$error3.error) || (err === null || err === void 0 ? void 0 : err.error) || '' : '';
  9565. errorName = errorMessage;
  9566. errorHttpCode = err ? err === null || err === void 0 ? void 0 : (_err$error4 = err.error) === null || _err$error4 === void 0 ? void 0 : _err$error4.statusCode : data.statusCode;
  9567. errorServiceName = err ? err === null || err === void 0 ? void 0 : (_err$error5 = err.error) === null || _err$error5 === void 0 ? void 0 : (_err$error5$error = _err$error5.error) === null || _err$error5$error === void 0 ? void 0 : _err$error5$error.Resource : '';
  9568. requestId = err ? (err === null || err === void 0 ? void 0 : (_err$error6 = err.error) === null || _err$error6 === void 0 ? void 0 : _err$error6.RequestId) || '' : (data === null || data === void 0 ? void 0 : data.RequestId) || '';
  9569. errorType = err ? requestId ? 'Server' : 'Client' : '';
  9570. if (this.params.requestName === 'getObject') {
  9571. this.params.httpSize = data ? data.headers && data.headers['content-length'] : 0;
  9572. }
  9573. // 上报 sliceUploadFile || uploadFile || uploadFiles 命中分块上传时
  9574. isSliceUploadFile = this.params.realApi === 'sliceUploadFile';
  9575. isSliceCopyFile = this.params.realApi === 'sliceCopyFile';
  9576. if (isSliceUploadFile || isSliceCopyFile) {
  9577. speed = this.params.httpSize / 1024 / this.params.partTime;
  9578. Object.assign(this.params, {
  9579. httpSpeed: speed < 0 ? 0 : speed.toFixed(3)
  9580. });
  9581. } else {
  9582. httpFullTime = now - this.params.startTime;
  9583. httpTookTime = this.params.httpEndTime - this.params.httpStartTime;
  9584. _speed = this.params.httpSize / 1024 / (httpTookTime / 1000);
  9585. httpMd5 = this.params.md5EndTime - this.params.md5StartTime;
  9586. httpSign = this.params.signEndTime - this.params.signStartTime;
  9587. if (this.parent) {
  9588. this.parent.addParamValue('httpTookTime', ms2s(httpTookTime));
  9589. this.parent.addParamValue('httpFullTime', ms2s(httpFullTime));
  9590. this.parent.addParamValue('httpMd5', ms2s(httpMd5));
  9591. this.parent.addParamValue('httpSign', ms2s(httpSign));
  9592. if (['multipartUpload', 'uploadPartCopy', 'putObjectCopy'].includes(this.params.requestName)) {
  9593. // 只有小分块上传|复制才累计纯请求耗时,计算速度时用到
  9594. this.parent.addParamValue('partTime', ms2s(httpTookTime));
  9595. }
  9596. }
  9597. Object.assign(this.params, {
  9598. httpFullTime: ms2s(httpFullTime),
  9599. httpMd5: ms2s(httpMd5),
  9600. httpSign: ms2s(httpSign),
  9601. httpTookTime: ms2s(httpTookTime),
  9602. httpSpeed: _speed < 0 ? 0 : _speed.toFixed(3)
  9603. });
  9604. }
  9605. Object.assign(this.params, {
  9606. networkType: networkType,
  9607. requestResult: err ? 'Failure' : 'Success',
  9608. errorType: errorType,
  9609. errorCode: errorCode,
  9610. errorHttpCode: errorHttpCode,
  9611. errorName: errorName,
  9612. errorMessage: errorMessage,
  9613. errorServiceName: errorServiceName,
  9614. errorRequestId: requestId
  9615. });
  9616. if (err && (!errorCode || !errorMessage)) {
  9617. // 暂存全量err一段时间 观察是否所有err格式都可被解析
  9618. this.params.fullError = err ? JSON.stringify(err) : '';
  9619. }
  9620. if (this.params.name === 'getObject') {
  9621. this.params.size = data ? data.headers && data.headers['content-length'] : -1;
  9622. }
  9623. if (this.params.url) {
  9624. try {
  9625. exec = /^http(s)?:\/\/(.*?)\//.exec(this.params.url);
  9626. this.params.host = exec[2];
  9627. } catch (e) {
  9628. this.params.host = this.params.url;
  9629. }
  9630. this.params.httpDomain = this.params.host;
  9631. }
  9632. case 19:
  9633. case "end":
  9634. return _context.stop();
  9635. }
  9636. }, _callee, this);
  9637. }));
  9638. function formatResult(_x, _x2) {
  9639. return _formatResult.apply(this, arguments);
  9640. }
  9641. return formatResult;
  9642. }() // 上报
  9643. }, {
  9644. key: "report",
  9645. value: function () {
  9646. var _report = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(err, data) {
  9647. var formattedParams;
  9648. return _regeneratorRuntime().wrap(function _callee2$(_context2) {
  9649. while (1) switch (_context2.prev = _context2.next) {
  9650. case 0:
  9651. if (!(!this.beacon && !this.clsReporter)) {
  9652. _context2.next = 2;
  9653. break;
  9654. }
  9655. return _context2.abrupt("return");
  9656. case 2:
  9657. _context2.next = 4;
  9658. return this.formatResult(err, data);
  9659. case 4:
  9660. formattedParams = formatParams(this.params);
  9661. if (this.beacon) {
  9662. this.sendEventsToBeacon(formattedParams);
  9663. }
  9664. if (this.clsReporter) {
  9665. this.sendEventsToCLS(formattedParams);
  9666. }
  9667. case 7:
  9668. case "end":
  9669. return _context2.stop();
  9670. }
  9671. }, _callee2, this);
  9672. }));
  9673. function report(_x3, _x4) {
  9674. return _report.apply(this, arguments);
  9675. }
  9676. return report;
  9677. }() // 设置当前链路的参数
  9678. }, {
  9679. key: "setParams",
  9680. value: function setParams(params) {
  9681. Object.assign(this.params, params);
  9682. }
  9683. }, {
  9684. key: "addParamValue",
  9685. value: function addParamValue(key, value) {
  9686. this.params[key] = (+this.params[key] + +value).toFixed(3);
  9687. }
  9688. // 上报灯塔
  9689. }, {
  9690. key: "sendEventsToBeacon",
  9691. value: function sendEventsToBeacon(formattedParams) {
  9692. // DeepTracker模式下才会上报分块上传内部细节
  9693. var isSliceUploadFile = this.params.requestName === 'sliceUploadFile' || this.params.realApi === 'sliceUploadFile';
  9694. if (isSliceUploadFile && !this.deepTracker) {
  9695. return;
  9696. }
  9697. var eventCode = 'qcloud_track_cos_sdk';
  9698. if (this.delay === 0) {
  9699. // 实时上报
  9700. this.beacon && this.beacon.onDirectUserAction(eventCode, formattedParams);
  9701. } else {
  9702. // 周期性上报
  9703. this.beacon && this.beacon.onUserAction(eventCode, formattedParams);
  9704. }
  9705. }
  9706. // 上报 cls
  9707. }, {
  9708. key: "sendEventsToCLS",
  9709. value: function sendEventsToCLS(formattedParams) {
  9710. // 是否实时上报
  9711. var immediate = !!(this.delay === 0);
  9712. this.clsReporter.log(formattedParams, immediate);
  9713. }
  9714. // 生成子实例,与父所属一个链路,可用于分块上传内部流程上报单个分块操作
  9715. }, {
  9716. key: "generateSubTracker",
  9717. value: function generateSubTracker(subParams) {
  9718. Object.assign(subParams, {
  9719. parent: this,
  9720. deepTracker: this.deepTracker,
  9721. traceId: this.params.traceId,
  9722. bucket: this.params.bucket,
  9723. region: this.params.region,
  9724. accelerate: this.params.accelerate,
  9725. fileKey: this.params.requestPath,
  9726. customId: this.params.customId,
  9727. delay: this.params.delay,
  9728. clsReporter: this.clsReporter
  9729. });
  9730. return new Tracker(subParams);
  9731. }
  9732. }]);
  9733. return Tracker;
  9734. }();
  9735. module.exports = Tracker;
  9736. /***/ }),
  9737. /***/ "./src/util.js":
  9738. /*!*********************!*\
  9739. !*** ./src/util.js ***!
  9740. \*********************/
  9741. /*! no static exports found */
  9742. /***/ (function(module, exports, __webpack_require__) {
  9743. "use strict";
  9744. function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = it.call(o); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it["return"] != null) it["return"](); } finally { if (didErr) throw err; } } }; }
  9745. function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
  9746. function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; }
  9747. function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator["return"] && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, "catch": function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
  9748. function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
  9749. function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
  9750. function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
  9751. var md5 = __webpack_require__(/*! ../lib/md5 */ "./lib/md5.js");
  9752. var CryptoJS = __webpack_require__(/*! ../lib/crypto */ "./lib/crypto.js");
  9753. var base64 = __webpack_require__(/*! ../lib/base64 */ "./lib/base64.js");
  9754. var btoa = base64.btoa;
  9755. var wxfs = wx.getFileSystemManager();
  9756. var Tracker = __webpack_require__(/*! ./tracker */ "./src/tracker.js");
  9757. var _require = __webpack_require__(/*! fast-xml-parser */ "./node_modules/fast-xml-parser/src/fxp.js"),
  9758. XMLParser = _require.XMLParser,
  9759. XMLBuilder = _require.XMLBuilder;
  9760. var xmlParser = new XMLParser({
  9761. ignoreDeclaration: true,
  9762. // 忽略 XML 声明
  9763. ignoreAttributes: true,
  9764. // 忽略属性
  9765. parseTagValue: false // 关闭自动解析
  9766. });
  9767. var xmlBuilder = new XMLBuilder();
  9768. // XML 对象转 JSON 对象
  9769. var xml2json = function xml2json(bodyStr) {
  9770. var d = xmlParser.parse(bodyStr);
  9771. return d;
  9772. };
  9773. // JSON 对象转 XML 对象
  9774. var json2xml = function json2xml(json) {
  9775. var xml = xmlBuilder.build(json);
  9776. return xml;
  9777. };
  9778. function camSafeUrlEncode(str) {
  9779. return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A');
  9780. }
  9781. function getObjectKeys(obj, forKey) {
  9782. var list = [];
  9783. for (var key in obj) {
  9784. if (obj.hasOwnProperty(key)) {
  9785. list.push(forKey ? camSafeUrlEncode(key).toLowerCase() : key);
  9786. }
  9787. }
  9788. return list.sort(function (a, b) {
  9789. a = a.toLowerCase();
  9790. b = b.toLowerCase();
  9791. return a === b ? 0 : a > b ? 1 : -1;
  9792. });
  9793. }
  9794. /**
  9795. * obj转为string
  9796. * @param {Object} obj 需要转的对象,必须
  9797. * @param {Boolean} lowerCaseKey key是否转为小写,默认false,非必须
  9798. * @return {String} data 返回字符串
  9799. */
  9800. var obj2str = function obj2str(obj, lowerCaseKey) {
  9801. var i, key, val;
  9802. var list = [];
  9803. var keyList = getObjectKeys(obj);
  9804. for (i = 0; i < keyList.length; i++) {
  9805. key = keyList[i];
  9806. val = obj[key] === undefined || obj[key] === null ? '' : '' + obj[key];
  9807. key = lowerCaseKey ? camSafeUrlEncode(key).toLowerCase() : camSafeUrlEncode(key);
  9808. val = camSafeUrlEncode(val) || '';
  9809. list.push(key + '=' + val);
  9810. }
  9811. return list.join('&');
  9812. };
  9813. // 可以签入签名的headers
  9814. var signHeaders = ['cache-control', 'content-disposition', 'content-encoding', 'content-length', 'content-md5', 'expect', 'expires', 'host', 'if-match', 'if-modified-since', 'if-none-match', 'if-unmodified-since', 'origin', 'range', 'transfer-encoding', 'pic-operations'];
  9815. var getSignHeaderObj = function getSignHeaderObj(headers) {
  9816. var signHeaderObj = {};
  9817. for (var i in headers) {
  9818. var key = i.toLowerCase();
  9819. if (key.indexOf('x-cos-') > -1 || signHeaders.indexOf(key) > -1) {
  9820. signHeaderObj[i] = headers[i];
  9821. }
  9822. }
  9823. return signHeaderObj;
  9824. };
  9825. //测试用的key后面可以去掉
  9826. var getAuth = function getAuth(opt) {
  9827. opt = opt || {};
  9828. var SecretId = opt.SecretId;
  9829. var SecretKey = opt.SecretKey;
  9830. var KeyTime = opt.KeyTime;
  9831. var method = (opt.method || opt.Method || 'get').toLowerCase();
  9832. var queryParams = clone(opt.Query || opt.params || {});
  9833. var headers = getSignHeaderObj(clone(opt.Headers || opt.headers || {}));
  9834. var Key = opt.Key || '';
  9835. var pathname;
  9836. if (opt.UseRawKey) {
  9837. pathname = opt.Pathname || opt.pathname || '/' + Key;
  9838. } else {
  9839. pathname = opt.Pathname || opt.pathname || Key;
  9840. pathname.indexOf('/') !== 0 && (pathname = '/' + pathname);
  9841. }
  9842. // ForceSignHost明确传入false才不加入host签名
  9843. var forceSignHost = opt.ForceSignHost === false ? false : true;
  9844. // 如果有传入存储桶,那么签名默认加 Host 参与计算,避免跨桶访问
  9845. if (!headers.Host && !headers.host && opt.Bucket && opt.Region && forceSignHost) headers.Host = opt.Bucket + '.cos.' + opt.Region + '.myqcloud.com';
  9846. if (!SecretId) return console.error('missing param SecretId');
  9847. if (!SecretKey) return console.error('missing param SecretKey');
  9848. // 签名有效起止时间
  9849. var now = Math.round(getSkewTime(opt.SystemClockOffset) / 1000) - 1;
  9850. var exp = now;
  9851. var Expires = opt.Expires || opt.expires;
  9852. if (Expires === undefined) {
  9853. exp += 900; // 签名过期时间为当前 + 900s
  9854. } else {
  9855. exp += Expires * 1 || 0;
  9856. }
  9857. // 要用到的 Authorization 参数列表
  9858. var qSignAlgorithm = 'sha1';
  9859. var qAk = SecretId;
  9860. var qSignTime = KeyTime || now + ';' + exp;
  9861. var qKeyTime = KeyTime || now + ';' + exp;
  9862. var qHeaderList = getObjectKeys(headers, true).join(';').toLowerCase();
  9863. var qUrlParamList = getObjectKeys(queryParams, true).join(';').toLowerCase();
  9864. // 签名算法说明文档:https://www.qcloud.com/document/product/436/7778
  9865. // 步骤一:计算 SignKey
  9866. var signKey = CryptoJS.HmacSHA1(qKeyTime, SecretKey).toString();
  9867. // 步骤二:构成 FormatString
  9868. var formatString = [method, pathname, util.obj2str(queryParams, true), util.obj2str(headers, true), ''].join('\n');
  9869. // 步骤三:计算 StringToSign
  9870. var stringToSign = ['sha1', qSignTime, CryptoJS.SHA1(formatString).toString(), ''].join('\n');
  9871. // 步骤四:计算 Signature
  9872. var qSignature = CryptoJS.HmacSHA1(stringToSign, signKey).toString();
  9873. // 步骤五:构造 Authorization
  9874. var authorization = ['q-sign-algorithm=' + qSignAlgorithm, 'q-ak=' + qAk, 'q-sign-time=' + qSignTime, 'q-key-time=' + qKeyTime, 'q-header-list=' + qHeaderList, 'q-url-param-list=' + qUrlParamList, 'q-signature=' + qSignature].join('&');
  9875. return authorization;
  9876. };
  9877. var getSourceParams = function getSourceParams(source) {
  9878. var parser = this.options.CopySourceParser;
  9879. if (parser) return parser(source);
  9880. var m = source.match(/^([^.]+-\d+)\.cos(v6|-cdc|-internal)?\.([^.]+)\.((myqcloud\.com)|(tencentcos\.cn))\/(.+)$/);
  9881. if (!m) return null;
  9882. return {
  9883. Bucket: m[1],
  9884. Region: m[3],
  9885. Key: m[7]
  9886. };
  9887. };
  9888. var noop = function noop() {};
  9889. // 清除对象里值为的 undefined 或 null 的属性
  9890. var clearKey = function clearKey(obj) {
  9891. var retObj = {};
  9892. for (var key in obj) {
  9893. if (obj.hasOwnProperty(key) && obj[key] !== undefined && obj[key] !== null) {
  9894. retObj[key] = obj[key];
  9895. }
  9896. }
  9897. return retObj;
  9898. };
  9899. // 获取文件分片
  9900. var fileSlice = function fileSlice(FilePath, start, end, callback) {
  9901. if (FilePath) {
  9902. wxfs.readFile({
  9903. filePath: FilePath,
  9904. position: start,
  9905. length: end - start,
  9906. success: function success(res) {
  9907. callback(res.data);
  9908. },
  9909. fail: function fail() {
  9910. callback(null);
  9911. }
  9912. });
  9913. } else {
  9914. callback(null);
  9915. }
  9916. };
  9917. // 获取文件内容的 MD5
  9918. var getBodyMd5 = function getBodyMd5(UploadCheckContentMd5, Body, callback) {
  9919. callback = callback || noop;
  9920. if (UploadCheckContentMd5) {
  9921. if (Body && Body instanceof ArrayBuffer) {
  9922. util.getFileMd5(Body, function (err, md5) {
  9923. callback(md5);
  9924. });
  9925. } else {
  9926. callback();
  9927. }
  9928. } else {
  9929. callback();
  9930. }
  9931. };
  9932. // 获取文件 md5 值
  9933. var getFileMd5 = function getFileMd5(body, callback) {
  9934. var hash = md5(body);
  9935. callback && callback(hash);
  9936. return hash;
  9937. };
  9938. function clone(obj) {
  9939. return map(obj, function (v) {
  9940. return _typeof(v) === 'object' && v !== null ? clone(v) : v;
  9941. });
  9942. }
  9943. function attr(obj, name, defaultValue) {
  9944. return obj && name in obj ? obj[name] : defaultValue;
  9945. }
  9946. function extend(target, source) {
  9947. each(source, function (val, key) {
  9948. target[key] = source[key];
  9949. });
  9950. return target;
  9951. }
  9952. function isArray(arr) {
  9953. return arr instanceof Array;
  9954. }
  9955. function isInArray(arr, item) {
  9956. var flag = false;
  9957. for (var i = 0; i < arr.length; i++) {
  9958. if (item === arr[i]) {
  9959. flag = true;
  9960. break;
  9961. }
  9962. }
  9963. return flag;
  9964. }
  9965. function makeArray(arr) {
  9966. return isArray(arr) ? arr : [arr];
  9967. }
  9968. function each(obj, fn) {
  9969. for (var i in obj) {
  9970. if (obj.hasOwnProperty(i)) {
  9971. fn(obj[i], i);
  9972. }
  9973. }
  9974. }
  9975. function map(obj, fn) {
  9976. var o = isArray(obj) ? [] : {};
  9977. for (var i in obj) {
  9978. if (obj.hasOwnProperty(i)) {
  9979. o[i] = fn(obj[i], i);
  9980. }
  9981. }
  9982. return o;
  9983. }
  9984. function filter(obj, fn) {
  9985. var iaArr = isArray(obj);
  9986. var o = iaArr ? [] : {};
  9987. for (var i in obj) {
  9988. if (obj.hasOwnProperty(i)) {
  9989. if (fn(obj[i], i)) {
  9990. if (iaArr) {
  9991. o.push(obj[i]);
  9992. } else {
  9993. o[i] = obj[i];
  9994. }
  9995. }
  9996. }
  9997. }
  9998. return o;
  9999. }
  10000. var binaryBase64 = function binaryBase64(str) {
  10001. var i,
  10002. len,
  10003. _char,
  10004. res = '';
  10005. for (i = 0, len = str.length / 2; i < len; i++) {
  10006. _char = parseInt(str[i * 2] + str[i * 2 + 1], 16);
  10007. res += String.fromCharCode(_char);
  10008. }
  10009. return btoa(res);
  10010. };
  10011. var uuid = function uuid() {
  10012. var S4 = function S4() {
  10013. return ((1 + Math.random()) * 0x10000 | 0).toString(16).substring(1);
  10014. };
  10015. return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
  10016. };
  10017. var hasMissingParams = function hasMissingParams(apiName, params) {
  10018. var Bucket = params.Bucket;
  10019. var Region = params.Region;
  10020. var Key = params.Key;
  10021. if (apiName.indexOf('Bucket') > -1 || apiName === 'deleteMultipleObject' || apiName === 'multipartList' || apiName === 'listObjectVersions') {
  10022. if (!Bucket) return 'Bucket';
  10023. if (!Region) return 'Region';
  10024. } else if (apiName.indexOf('Object') > -1 || apiName.indexOf('multipart') > -1 || apiName === 'sliceUploadFile' || apiName === 'abortUploadTask' || apiName === 'uploadFile') {
  10025. if (!Bucket) return 'Bucket';
  10026. if (!Region) return 'Region';
  10027. if (!Key) return 'Key';
  10028. }
  10029. return false;
  10030. };
  10031. var formatParams = function formatParams(apiName, params) {
  10032. // 复制参数对象
  10033. params = extend({}, params);
  10034. // 统一处理 Headers
  10035. if (apiName !== 'getAuth' && apiName !== 'getV4Auth' && apiName !== 'getObjectUrl') {
  10036. var Headers = params.Headers || {};
  10037. if (params && _typeof(params) === 'object') {
  10038. (function () {
  10039. for (var key in params) {
  10040. if (params.hasOwnProperty(key) && key.indexOf('x-cos-') > -1) {
  10041. Headers[key] = params[key];
  10042. }
  10043. }
  10044. })();
  10045. var headerMap = {
  10046. // params headers
  10047. 'x-cos-mfa': 'MFA',
  10048. 'Content-MD5': 'ContentMD5',
  10049. 'Content-Length': 'ContentLength',
  10050. 'Content-Type': 'ContentType',
  10051. Expect: 'Expect',
  10052. Expires: 'Expires',
  10053. 'Cache-Control': 'CacheControl',
  10054. 'Content-Disposition': 'ContentDisposition',
  10055. 'Content-Encoding': 'ContentEncoding',
  10056. Range: 'Range',
  10057. 'If-Modified-Since': 'IfModifiedSince',
  10058. 'If-Unmodified-Since': 'IfUnmodifiedSince',
  10059. 'If-Match': 'IfMatch',
  10060. 'If-None-Match': 'IfNoneMatch',
  10061. 'x-cos-copy-source': 'CopySource',
  10062. 'x-cos-copy-source-Range': 'CopySourceRange',
  10063. 'x-cos-metadata-directive': 'MetadataDirective',
  10064. 'x-cos-copy-source-If-Modified-Since': 'CopySourceIfModifiedSince',
  10065. 'x-cos-copy-source-If-Unmodified-Since': 'CopySourceIfUnmodifiedSince',
  10066. 'x-cos-copy-source-If-Match': 'CopySourceIfMatch',
  10067. 'x-cos-copy-source-If-None-Match': 'CopySourceIfNoneMatch',
  10068. 'x-cos-acl': 'ACL',
  10069. 'x-cos-grant-read': 'GrantRead',
  10070. 'x-cos-grant-write': 'GrantWrite',
  10071. 'x-cos-grant-full-control': 'GrantFullControl',
  10072. 'x-cos-grant-read-acp': 'GrantReadAcp',
  10073. 'x-cos-grant-write-acp': 'GrantWriteAcp',
  10074. 'x-cos-storage-class': 'StorageClass',
  10075. 'x-cos-traffic-limit': 'TrafficLimit',
  10076. 'x-cos-mime-limit': 'MimeLimit',
  10077. 'x-cos-forbid-overwrite': 'ForbidOverwrite',
  10078. // SSE-C
  10079. 'x-cos-server-side-encryption-customer-algorithm': 'SSECustomerAlgorithm',
  10080. 'x-cos-server-side-encryption-customer-key': 'SSECustomerKey',
  10081. 'x-cos-server-side-encryption-customer-key-MD5': 'SSECustomerKeyMD5',
  10082. // SSE-COS、SSE-KMS
  10083. 'x-cos-server-side-encryption': 'ServerSideEncryption',
  10084. 'x-cos-server-side-encryption-cos-kms-key-id': 'SSEKMSKeyId',
  10085. 'x-cos-server-side-encryption-context': 'SSEContext',
  10086. // 上传时图片处理
  10087. 'Pic-Operations': 'PicOperations'
  10088. };
  10089. util.each(headerMap, function (paramKey, headerKey) {
  10090. if (params[paramKey] !== undefined) {
  10091. Headers[headerKey] = params[paramKey];
  10092. }
  10093. });
  10094. params.Headers = clearKey(Headers);
  10095. }
  10096. }
  10097. return params;
  10098. };
  10099. var apiWrapper = function apiWrapper(apiName, apiFn) {
  10100. return function (params, callback) {
  10101. var self = this;
  10102. // 处理参数
  10103. if (typeof params === 'function') {
  10104. callback = params;
  10105. params = {};
  10106. }
  10107. // 整理参数格式
  10108. params = formatParams(apiName, params);
  10109. // tracker传递
  10110. var tracker;
  10111. if (self.options.EnableReporter) {
  10112. if (params.calledBySdk === 'sliceUploadFile' || params.calledBySdk === 'sliceCopyFile') {
  10113. // 分块上传内部方法使用sliceUploadFile的子链路
  10114. tracker = params.tracker && params.tracker.generateSubTracker({
  10115. apiName: apiName
  10116. });
  10117. } else if (['uploadFile', 'uploadFiles'].includes(apiName)) {
  10118. // uploadFile、uploadFiles方法在内部处理,此处不处理
  10119. tracker = null;
  10120. } else {
  10121. var fileSize = 0;
  10122. if (params.Body) {
  10123. fileSize = typeof params.Body === 'string' ? params.Body.length : params.Body.size || params.Body.byteLength || 0;
  10124. }
  10125. var accelerate = self.options.UseAccelerate || typeof self.options.Domain === 'string' && self.options.Domain.includes('accelerate.');
  10126. tracker = new Tracker({
  10127. Beacon: self.options.BeaconReporter,
  10128. clsReporter: self.options.ClsReporter,
  10129. bucket: params.Bucket,
  10130. region: params.Region,
  10131. apiName: apiName,
  10132. realApi: apiName,
  10133. accelerate: accelerate,
  10134. fileKey: params.Key,
  10135. fileSize: fileSize,
  10136. deepTracker: self.options.DeepTracker,
  10137. customId: self.options.CustomId,
  10138. delay: self.options.TrackerDelay
  10139. });
  10140. }
  10141. }
  10142. params.tracker = tracker;
  10143. // 代理回调函数
  10144. var formatResult = function formatResult(result) {
  10145. if (result && result.headers) {
  10146. result.headers['x-cos-request-id'] && (result.RequestId = result.headers['x-cos-request-id']);
  10147. result.headers['x-ci-request-id'] && (result.RequestId = result.headers['x-ci-request-id']);
  10148. result.headers['x-cos-version-id'] && (result.VersionId = result.headers['x-cos-version-id']);
  10149. result.headers['x-cos-delete-marker'] && (result.DeleteMarker = result.headers['x-cos-delete-marker']);
  10150. }
  10151. return result;
  10152. };
  10153. var _callback = function _callback(err, data) {
  10154. // 格式化上报参数并上报
  10155. tracker && tracker.report(err, data);
  10156. callback && callback(formatResult(err), formatResult(data));
  10157. };
  10158. var checkParams = function checkParams() {
  10159. if (apiName !== 'getService' && apiName !== 'abortUploadTask') {
  10160. // 判断参数是否完整
  10161. var missingResult = hasMissingParams(apiName, params);
  10162. if (missingResult) {
  10163. return 'missing param ' + missingResult;
  10164. }
  10165. // 判断 region 格式
  10166. if (params.Region) {
  10167. if (params.Region.indexOf('cos.') > -1) {
  10168. return 'param Region should not be start with "cos."';
  10169. } else if (!/^([a-z\d-]+)$/.test(params.Region)) {
  10170. return 'Region format error.';
  10171. }
  10172. // 判断 region 格式
  10173. if (!self.options.CompatibilityMode && params.Region.indexOf('-') === -1 && params.Region !== 'yfb' && params.Region !== 'default' && params.Region !== 'accelerate') {
  10174. console.warn('warning: param Region format error, find help here: https://cloud.tencent.com/document/product/436/6224');
  10175. }
  10176. }
  10177. // 兼容不带 AppId 的 Bucket
  10178. if (params.Bucket) {
  10179. if (!/^([a-z\d-]+)-(\d+)$/.test(params.Bucket)) {
  10180. if (params.AppId) {
  10181. params.Bucket = params.Bucket + '-' + params.AppId;
  10182. } else if (self.options.AppId) {
  10183. params.Bucket = params.Bucket + '-' + self.options.AppId;
  10184. } else {
  10185. return 'Bucket should format as "test-1250000000".';
  10186. }
  10187. }
  10188. if (params.AppId) {
  10189. console.warn('warning: AppId has been deprecated, Please put it at the end of parameter Bucket(E.g Bucket:"test-1250000000" ).');
  10190. delete params.AppId;
  10191. }
  10192. }
  10193. // 如果 Key 是 / 开头,强制去掉第一个 /
  10194. if (params.Key && params.Key.substr(0, 1) === '/') {
  10195. params.Key = params.Key.substr(1);
  10196. }
  10197. }
  10198. };
  10199. var errMsg = checkParams();
  10200. var isSync = ['getAuth', 'getObjectUrl'].includes(apiName);
  10201. if (!isSync && !callback) {
  10202. return new Promise(function (resolve, reject) {
  10203. callback = function callback(err, data) {
  10204. err ? reject(err) : resolve(data);
  10205. };
  10206. if (errMsg) return _callback({
  10207. error: errMsg
  10208. });
  10209. apiFn.call(self, params, _callback);
  10210. });
  10211. } else {
  10212. if (errMsg) return _callback({
  10213. error: errMsg
  10214. });
  10215. var res = apiFn.call(self, params, _callback);
  10216. if (isSync) return res;
  10217. }
  10218. };
  10219. };
  10220. var throttleOnProgress = function throttleOnProgress(total, onProgress) {
  10221. var self = this;
  10222. var size0 = 0;
  10223. var size1 = 0;
  10224. var time0 = Date.now();
  10225. var time1;
  10226. var timer;
  10227. function update() {
  10228. timer = 0;
  10229. if (onProgress && typeof onProgress === 'function') {
  10230. time1 = Date.now();
  10231. var speed = Math.max(0, Math.round((size1 - size0) / ((time1 - time0) / 1000) * 100) / 100) || 0;
  10232. var percent;
  10233. if (size1 === 0 && total === 0) {
  10234. percent = 1;
  10235. } else {
  10236. percent = Math.floor(size1 / total * 100) / 100 || 0;
  10237. }
  10238. time0 = time1;
  10239. size0 = size1;
  10240. try {
  10241. onProgress({
  10242. loaded: size1,
  10243. total: total,
  10244. speed: speed,
  10245. percent: percent
  10246. });
  10247. } catch (e) {}
  10248. }
  10249. }
  10250. return function (info, immediately) {
  10251. if (info) {
  10252. size1 = info.loaded;
  10253. total = info.total;
  10254. }
  10255. if (immediately) {
  10256. clearTimeout(timer);
  10257. update();
  10258. } else {
  10259. if (timer) return;
  10260. timer = setTimeout(update, self.options.ProgressInterval);
  10261. }
  10262. };
  10263. };
  10264. // 通过FilePath获取上传文件的内容
  10265. var getFileBody = function getFileBody(FilePath) {
  10266. return new Promise(function (resolve, reject) {
  10267. wxfs.readFile({
  10268. filePath: FilePath,
  10269. success: function success(res) {
  10270. resolve(res.data);
  10271. },
  10272. fail: function fail(res) {
  10273. reject((res === null || res === void 0 ? void 0 : res.errMsg) || '');
  10274. }
  10275. });
  10276. });
  10277. };
  10278. var getFileSize = /*#__PURE__*/function () {
  10279. var _ref = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(api, params, callback) {
  10280. return _regeneratorRuntime().wrap(function _callee$(_context) {
  10281. while (1) switch (_context.prev = _context.next) {
  10282. case 0:
  10283. if (!(api === 'postObject')) {
  10284. _context.next = 4;
  10285. break;
  10286. }
  10287. callback();
  10288. _context.next = 21;
  10289. break;
  10290. case 4:
  10291. if (!(api === 'putObject')) {
  10292. _context.next = 20;
  10293. break;
  10294. }
  10295. if (!(params.Body === undefined && params.FilePath)) {
  10296. _context.next = 17;
  10297. break;
  10298. }
  10299. _context.prev = 6;
  10300. _context.next = 9;
  10301. return getFileBody(params.FilePath);
  10302. case 9:
  10303. params.Body = _context.sent;
  10304. _context.next = 17;
  10305. break;
  10306. case 12:
  10307. _context.prev = 12;
  10308. _context.t0 = _context["catch"](6);
  10309. params.Body = undefined;
  10310. callback({
  10311. error: "readFile error, ".concat(_context.t0)
  10312. });
  10313. return _context.abrupt("return");
  10314. case 17:
  10315. if (params.Body !== undefined) {
  10316. params.ContentLength = params.Body.byteLength;
  10317. callback(null, params.ContentLength);
  10318. } else {
  10319. callback({
  10320. error: 'missing param Body'
  10321. });
  10322. }
  10323. _context.next = 21;
  10324. break;
  10325. case 20:
  10326. if (params.FilePath) {
  10327. wxfs.stat({
  10328. path: params.FilePath,
  10329. success: function success(res) {
  10330. var stats = res.stats;
  10331. params.FileStat = stats;
  10332. params.FileStat.FilePath = params.FilePath;
  10333. var size = stats.isDirectory() ? 0 : stats.size;
  10334. params.ContentLength = size = size || 0;
  10335. callback(null, size);
  10336. },
  10337. fail: function fail(err) {
  10338. callback(err);
  10339. }
  10340. });
  10341. } else {
  10342. callback({
  10343. error: 'missing param FilePath'
  10344. });
  10345. }
  10346. case 21:
  10347. case "end":
  10348. return _context.stop();
  10349. }
  10350. }, _callee, null, [[6, 12]]);
  10351. }));
  10352. return function getFileSize(_x, _x2, _x3) {
  10353. return _ref.apply(this, arguments);
  10354. };
  10355. }();
  10356. // 通过FilePath获取上传文件的大小
  10357. var getFileSizeByPath = function getFileSizeByPath(filePath) {
  10358. return new Promise(function (resolve, reject) {
  10359. wxfs.stat({
  10360. path: filePath,
  10361. success: function success(res) {
  10362. var stats = res.stats;
  10363. var size = stats.isDirectory() ? 0 : stats.size;
  10364. resolve(size);
  10365. },
  10366. fail: function fail(res) {
  10367. reject((res === null || res === void 0 ? void 0 : res.errMsg) || '');
  10368. }
  10369. });
  10370. });
  10371. };
  10372. var getSkewTime = function getSkewTime(offset) {
  10373. return Date.now() + (offset || 0);
  10374. };
  10375. var compareVersion = function compareVersion(v1, v2) {
  10376. v1 = v1.split('.');
  10377. v2 = v2.split('.');
  10378. var len = Math.max(v1.length, v2.length);
  10379. while (v1.length < len) {
  10380. v1.push('0');
  10381. }
  10382. while (v2.length < len) {
  10383. v2.push('0');
  10384. }
  10385. for (var i = 0; i < len; i++) {
  10386. var num1 = parseInt(v1[i]);
  10387. var num2 = parseInt(v2[i]);
  10388. if (num1 > num2) {
  10389. return 1;
  10390. } else if (num1 < num2) {
  10391. return -1;
  10392. }
  10393. }
  10394. return 0;
  10395. };
  10396. var canFileSlice = function () {
  10397. var systemInfo = wx.getSystemInfoSync();
  10398. var support = compareVersion(systemInfo.SDKVersion, '2.10.0') >= 0;
  10399. var needWarning = !support && systemInfo.platform === 'devtools';
  10400. return function () {
  10401. if (needWarning) console.warn('当前小程序版本小于 2.10.0,不支持分片上传,请更新软件。');
  10402. needWarning = false;
  10403. return support;
  10404. };
  10405. }();
  10406. var isCIHost = function isCIHost(url) {
  10407. return /^https?:\/\/([^/]+\.)?ci\.[^/]+/.test(url);
  10408. };
  10409. var error = function error(err, opt) {
  10410. var sourceErr = err;
  10411. err.message = err.message || null;
  10412. if (typeof opt === 'string') {
  10413. err.error = opt;
  10414. err.message = opt;
  10415. } else if (_typeof(opt) === 'object' && opt !== null) {
  10416. extend(err, opt);
  10417. if (opt.code || opt.name) err.code = opt.code || opt.name;
  10418. if (opt.message) err.message = opt.message;
  10419. if (opt.stack) err.stack = opt.stack;
  10420. }
  10421. if (typeof Object.defineProperty === 'function') {
  10422. Object.defineProperty(err, 'name', {
  10423. writable: true,
  10424. enumerable: false
  10425. });
  10426. Object.defineProperty(err, 'message', {
  10427. enumerable: true
  10428. });
  10429. }
  10430. err.name = opt && opt.name || err.name || err.code || 'Error';
  10431. if (!err.code) err.code = err.name;
  10432. if (!err.error) err.error = clone(sourceErr); // 兼容老的错误格式
  10433. return err;
  10434. };
  10435. var encodeBase64 = function encodeBase64(str, safe) {
  10436. var base64Str = base64.encode(str);
  10437. // 万象使用的安全base64格式需要特殊处理
  10438. if (safe) {
  10439. base64Str = base64Str.replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
  10440. }
  10441. return base64Str;
  10442. };
  10443. var simplifyPath = function simplifyPath(path) {
  10444. var names = path.split('/');
  10445. var stack = [];
  10446. var _iterator = _createForOfIteratorHelper(names),
  10447. _step;
  10448. try {
  10449. for (_iterator.s(); !(_step = _iterator.n()).done;) {
  10450. var name = _step.value;
  10451. if (name === '..') {
  10452. if (stack.length) {
  10453. stack.pop();
  10454. }
  10455. } else if (name.length && name !== '.') {
  10456. stack.push(name);
  10457. }
  10458. }
  10459. } catch (err) {
  10460. _iterator.e(err);
  10461. } finally {
  10462. _iterator.f();
  10463. }
  10464. return '/' + stack.join('/');
  10465. };
  10466. // 将ArrayBuffer转换为字符串
  10467. var arrayBufferToString = function arrayBufferToString(arrayBuffer) {
  10468. var decoder = new TextDecoder('utf-8');
  10469. return decoder.decode(arrayBuffer);
  10470. };
  10471. // 解析响应体,兼容 xml、json
  10472. var parseResBody = function parseResBody(responseBody) {
  10473. var json;
  10474. if (responseBody && typeof responseBody === 'string') {
  10475. var trimBody = responseBody.trim();
  10476. var isXml = trimBody.indexOf('<') === 0;
  10477. var isJson = trimBody.indexOf('{') === 0;
  10478. if (isXml) {
  10479. // xml 解析,解析失败返回{}
  10480. json = util.xml2json(responseBody) || {};
  10481. } else if (isJson) {
  10482. // json解析,解析失败返回原始 Body
  10483. try {
  10484. // 替换 json 中的换行符为空格,否则解析会出错
  10485. var formatBody = responseBody.replace(/\n/g, ' ');
  10486. var parsedBody = JSON.parse(formatBody);
  10487. // 确保解析出 json 对象
  10488. if (Object.prototype.toString.call(parsedBody) === '[object Object]') {
  10489. json = parsedBody;
  10490. } else {
  10491. json = responseBody;
  10492. }
  10493. } catch (e) {
  10494. json = responseBody;
  10495. }
  10496. } else {
  10497. json = responseBody;
  10498. }
  10499. } else {
  10500. json = responseBody || {};
  10501. }
  10502. return json;
  10503. };
  10504. var util = {
  10505. noop: noop,
  10506. formatParams: formatParams,
  10507. apiWrapper: apiWrapper,
  10508. xml2json: xml2json,
  10509. json2xml: json2xml,
  10510. md5: md5,
  10511. clearKey: clearKey,
  10512. fileSlice: fileSlice,
  10513. getBodyMd5: getBodyMd5,
  10514. getFileMd5: getFileMd5,
  10515. binaryBase64: binaryBase64,
  10516. extend: extend,
  10517. isArray: isArray,
  10518. isInArray: isInArray,
  10519. makeArray: makeArray,
  10520. each: each,
  10521. map: map,
  10522. filter: filter,
  10523. clone: clone,
  10524. attr: attr,
  10525. uuid: uuid,
  10526. camSafeUrlEncode: camSafeUrlEncode,
  10527. throttleOnProgress: throttleOnProgress,
  10528. getFileSize: getFileSize,
  10529. getFileSizeByPath: getFileSizeByPath,
  10530. getSkewTime: getSkewTime,
  10531. obj2str: obj2str,
  10532. getAuth: getAuth,
  10533. compareVersion: compareVersion,
  10534. canFileSlice: canFileSlice,
  10535. isCIHost: isCIHost,
  10536. error: error,
  10537. getSourceParams: getSourceParams,
  10538. encodeBase64: encodeBase64,
  10539. simplifyPath: simplifyPath,
  10540. arrayBufferToString: arrayBufferToString,
  10541. parseResBody: parseResBody
  10542. };
  10543. module.exports = util;
  10544. /***/ })
  10545. /******/ });
  10546. });